diff --git a/.gitignore b/.gitignore index 5dc7abec6a..7f1bab3751 100644 --- a/.gitignore +++ b/.gitignore @@ -107,4 +107,11 @@ spring-boot-modules/spring-boot-properties-3/*.log .sdkmanrc # Localstack -**/.localstack \ No newline at end of file +**/.localstack + +#libraries-2 +libraries-2/employee* +libraries-2/src/test/resources/crawler4j/** + +#web-modules/ninja +devDb*.db \ 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/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/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..ea127ea587 --- /dev/null +++ b/algorithms-modules/algorithms-miscellaneous-7/src/main/java/com/baeldung/algorithms/frequentelements/MostFrequentElementsFinder.java @@ -0,0 +1,103 @@ +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) { + // Create a Map to count occurrences of each element + Map countMap = Arrays.stream(arr) + .collect(Collectors.groupingBy(i -> i, Collectors.counting())); + + // Sort the elements by occurrence count + List sortedKeys = countMap.entrySet().stream() + .sorted(Collections.reverseOrder(Map.Entry.comparingByValue())) + .map(Map.Entry::getKey) + .collect(Collectors.toList()); + + // Extract the n most frequent elements from the sorted list + List result = new ArrayList<>(); + for (int i = 0; i < n && i < sortedKeys.size(); i++) { + result.add(sortedKeys.get(i)); + } + return result; + } + + 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/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/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/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/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/httpclient4/.gitignore b/apache-httpclient4/.gitignore similarity index 100% rename from httpclient4/.gitignore rename to apache-httpclient4/.gitignore diff --git a/httpclient4/README.md b/apache-httpclient4/README.md similarity index 70% rename from httpclient4/README.md rename to apache-httpclient4/README.md index 445db1108b..dff63a5cc1 100644 --- a/httpclient4/README.md +++ b/apache-httpclient4/README.md @@ -1,4 +1,4 @@ -## Apache HttpClient +## Apache HttpClient 4 This module contains articles about Apache HttpClient 4.5 @@ -7,6 +7,8 @@ This module contains articles about Apache HttpClient 4.5 - [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) ### 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 96% rename from httpclient4/pom.xml rename to apache-httpclient4/pom.xml index 8f896283b3..140dc0fbdb 100644 --- a/httpclient4/pom.xml +++ b/apache-httpclient4/pom.xml @@ -3,9 +3,9 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - 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,6 +289,7 @@ 2.5.1 4.4.16 4.5.14 + 5.11.2 1.6.1 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/httpclient4/src/main/resources/logback.xml b/apache-httpclient4/src/main/resources/logback.xml similarity index 100% rename from httpclient4/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/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/httpclient4/src/test/resources/.gitignore b/apache-httpclient4/src/test/resources/.gitignore similarity index 100% rename from httpclient4/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-libraries/pom.xml b/apache-libraries/pom.xml index 3d78869865..c1def03bee 100644 --- a/apache-libraries/pom.xml +++ b/apache-libraries/pom.xml @@ -118,11 +118,6 @@ curator-recipes ${curator.version} - - org.apache.zookeeper - zookeeper - ${zookeeper.version} - com.fasterxml.jackson.core jackson-core @@ -191,17 +186,15 @@ - 1.8 - 1.8 1.8.2 - 2.19.0 - 1.1.2 - 1.1.0.Final - 1.2.0 + 2.45.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/aws-modules/aws-lambda/shipping-tracker/ShippingFunction/pom.xml b/aws-modules/aws-lambda/shipping-tracker/ShippingFunction/pom.xml index c36c81375d..24f2a76912 100644 --- a/aws-modules/aws-lambda/shipping-tracker/ShippingFunction/pom.xml +++ b/aws-modules/aws-lambda/shipping-tracker/ShippingFunction/pom.xml @@ -69,8 +69,8 @@ - 1.8 - 1.8 + 11 + 11 5.4.21.Final 1.2.0 3.1.0 diff --git a/aws-modules/aws-lambda/todo-reminder/ToDoFunction/pom.xml b/aws-modules/aws-lambda/todo-reminder/ToDoFunction/pom.xml index cb6dd08d1e..0dd2e4d14a 100644 --- a/aws-modules/aws-lambda/todo-reminder/ToDoFunction/pom.xml +++ b/aws-modules/aws-lambda/todo-reminder/ToDoFunction/pom.xml @@ -1,6 +1,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 helloworld ToDoFunction @@ -101,16 +101,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/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..ca6a9a62c7 100644 --- a/core-groovy-modules/core-groovy-2/pom.xml +++ b/core-groovy-modules/core-groovy-2/pom.xml @@ -83,7 +83,7 @@ org.codehaus.groovy groovy-eclipse-batch - ${groovy.version}-01 + ${groovy-eclipse-batch.version} @@ -163,9 +163,10 @@ 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/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-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-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-8-2/README.md b/core-java-modules/core-java-8-2/README.md index c0bc63f21f..cad4a4f1fa 100644 --- a/core-java-modules/core-java-8-2/README.md +++ b/core-java-modules/core-java-8-2/README.md @@ -10,4 +10,5 @@ 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) - [[<-- Prev]](/core-java-modules/core-java-8) 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-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-5/README.md b/core-java-modules/core-java-collections-5/README.md new file mode 100644 index 0000000000..0d9b12b842 --- /dev/null +++ b/core-java-modules/core-java-collections-5/README.md @@ -0,0 +1,7 @@ +========= + +## Core Java Collections Cookbooks and Examples + +### Relevant Articles: +- [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 new file mode 100644 index 0000000000..67c9f7120c --- /dev/null +++ b/core-java-modules/core-java-collections-5/pom.xml @@ -0,0 +1,58 @@ + + + 4.0.0 + core-java-collections-5 + 0.0.1-SNAPSHOT + core-java-collections-5 + jar + + + com.baeldung.core-java-modules + core-java-modules + 0.0.1-SNAPSHOT + + + + + org.junit.platform + junit-platform-runner + ${junit-platform.version} + test + + + org.junit.jupiter + junit-jupiter + ${junit.version} + test + + + org.junit.vintage + junit-vintage-engine + ${junit.version} + test + + + org.roaringbitmap + RoaringBitmap + ${roaringbitmap.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh.version} + + + org.openjdk.jmh + jmh-core + ${jmh.version} + + + + + 5.9.2 + 0.9.38 + 1.36 + + diff --git a/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/roaringbitmap/BitSetsBenchmark.java b/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/roaringbitmap/BitSetsBenchmark.java new file mode 100644 index 0000000000..4968afb752 --- /dev/null +++ b/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/roaringbitmap/BitSetsBenchmark.java @@ -0,0 +1,82 @@ +package com.baeldung.roaringbitmap; + +import java.util.BitSet; + +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.Setup; +import org.openjdk.jmh.annotations.State; +import org.roaringbitmap.RoaringBitmap; + +@State(Scope.Thread) +public class BitSetsBenchmark { + private RoaringBitmap rb1; + private BitSet bs1; + private RoaringBitmap rb2; + private BitSet bs2; + private final static int SIZE = 10_000_000; + + @Setup + public void setup() { + rb1 = new RoaringBitmap(); + bs1 = new BitSet(SIZE); + rb2 = new RoaringBitmap(); + bs2 = new BitSet(SIZE); + for (int i = 0; i < SIZE / 2; i++) { + rb1.add(i); + bs1.set(i); + } + for (int i = SIZE / 2; i < SIZE; i++) { + rb2.add(i); + bs2.set(i); + } + } + + @Benchmark + public RoaringBitmap roaringBitmapUnion() { + return RoaringBitmap.or(rb1, rb2); + } + + @Benchmark + public BitSet bitSetUnion() { + BitSet result = (BitSet) bs1.clone(); + result.or(bs2); + return result; + } + + @Benchmark + public RoaringBitmap roaringBitmapIntersection() { + return RoaringBitmap.and(rb1, rb2); + } + + @Benchmark + public BitSet bitSetIntersection() { + BitSet result = (BitSet) bs1.clone(); + result.and(bs2); + return result; + } + + @Benchmark + public RoaringBitmap roaringBitmapDifference() { + return RoaringBitmap.andNot(rb1, rb2); + } + + @Benchmark + public BitSet bitSetDifference() { + BitSet result = (BitSet) bs1.clone(); + result.andNot(bs2); + return result; + } + + @Benchmark + public RoaringBitmap roaringBitmapXOR() { + return RoaringBitmap.xor(rb1, rb2); + } + + @Benchmark + public BitSet bitSetXOR() { + BitSet result = (BitSet) bs1.clone(); + result.xor(bs2); + return result; + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/roaringbitmap/BitSetsBenchmarkRunner.java b/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/roaringbitmap/BitSetsBenchmarkRunner.java new file mode 100644 index 0000000000..49d556df7e --- /dev/null +++ b/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/roaringbitmap/BitSetsBenchmarkRunner.java @@ -0,0 +1,9 @@ +package com.baeldung.roaringbitmap; + +import java.io.IOException; + +public class BitSetsBenchmarkRunner { + public static void main(String... args) throws IOException { + org.openjdk.jmh.Main.main(args); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-collections-5/src/test/java/com/baeldung/roaringbitmap/RoaringBitmapBenchmarkUnitTest.java b/core-java-modules/core-java-collections-5/src/test/java/com/baeldung/roaringbitmap/RoaringBitmapBenchmarkUnitTest.java new file mode 100644 index 0000000000..07170512d9 --- /dev/null +++ b/core-java-modules/core-java-collections-5/src/test/java/com/baeldung/roaringbitmap/RoaringBitmapBenchmarkUnitTest.java @@ -0,0 +1,45 @@ +package com.baeldung.roaringbitmap; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; +import org.roaringbitmap.RoaringBitmap; + +class RoaringBitmapBenchmarkUnitTest { + @Test + public void givenTwoRoaringBitmap_whenUsingOr_thenWillGetSetsUnion() { + RoaringBitmap expected = RoaringBitmap.bitmapOf(1, 2, 3, 4, 5, 6, 7, 8); + RoaringBitmap A = RoaringBitmap.bitmapOf(1, 2, 3, 4, 5); + RoaringBitmap B = RoaringBitmap.bitmapOf(4, 5, 6, 7, 8); + RoaringBitmap union = RoaringBitmap.or(A, B); + assertEquals(expected, union); + } + + @Test + public void givenTwoRoaringBitmap_whenUsingAnd_thenWillGetSetsIntersection() { + RoaringBitmap expected = RoaringBitmap.bitmapOf(4, 5); + RoaringBitmap A = RoaringBitmap.bitmapOfRange(1, 6); + RoaringBitmap B = RoaringBitmap.bitmapOf(4, 5, 6, 7, 8); + RoaringBitmap intersection = RoaringBitmap.and(A, B); + assertEquals(expected, intersection); + } + + @Test + public void givenTwoRoaringBitmap_whenUsingAndNot_thenWillGetSetsDifference() { + RoaringBitmap expected = RoaringBitmap.bitmapOf(1, 2, 3); + RoaringBitmap A = new RoaringBitmap(); + A.add(1L, 6L); + RoaringBitmap B = RoaringBitmap.bitmapOf(4, 5, 6, 7, 8); + RoaringBitmap difference = RoaringBitmap.andNot(A, B); + assertEquals(expected, difference); + } + + @Test + public void givenTwoRoaringBitmap_whenUsingXOR_thenWillGetSetsSymmetricDifference() { + RoaringBitmap expected = RoaringBitmap.bitmapOf(1, 2, 3, 6, 7, 8); + RoaringBitmap A = RoaringBitmap.bitmapOfRange(1, 6); + RoaringBitmap B = RoaringBitmap.bitmapOfRange(4, 9); + RoaringBitmap xor = RoaringBitmap.xor(A, B); + assertEquals(expected, xor); + } +} \ 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-list-5/README.md b/core-java-modules/core-java-collections-list-5/README.md index 78959e7d5d..d8cd989600 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,4 @@ 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) 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-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-concurrency-basic-3/README.md b/core-java-modules/core-java-concurrency-basic-3/README.md index 477f37e00a..46480c6b01 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,5 @@ 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) - [[<-- Prev]](../core-java-concurrency-basic-2) 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..fe21d0a72f --- /dev/null +++ b/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/path/DesktopPathUnitTest.java @@ -0,0 +1,29 @@ +package com.baeldung.path; + +import org.junit.jupiter.api.Test; + +import java.io.File; + +import static org.junit.Assert.assertEquals; + +import javax.swing.filechooser.FileSystemView; + +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-jndi/pom.xml b/core-java-modules/core-java-jndi/pom.xml index 23a2fe3bfb..752700c390 100644 --- a/core-java-modules/core-java-jndi/pom.xml +++ b/core-java-modules/core-java-jndi/pom.xml @@ -51,6 +51,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-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/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-lambdas/README.md b/core-java-modules/core-java-lambdas/README.md index cad2097673..56b2a79e7e 100644 --- a/core-java-modules/core-java-lambdas/README.md +++ b/core-java-modules/core-java-lambdas/README.md @@ -10,3 +10,4 @@ - [Serialize a Lambda in Java](https://www.baeldung.com/java-serialize-lambda) - [Convert Anonymous Class into Lambda in Java](https://www.baeldung.com/java-from-anonymous-class-to-lambda) - [When to Use Callable and Supplier in Java](https://www.baeldung.com/java-callable-vs-supplier) +- [Lambda Expression vs. Anonymous Inner Class](https://www.baeldung.com/java-lambdas-vs-anonymous-class) diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/anonymousclass/AnonymousClassExample.java b/core-java-modules/core-java-lambdas/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-lambdas/src/main/java/com/baeldung/anonymousclass/AnonymousClassExample.java diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/lambdaexpression/LambdaExpressionExample.java b/core-java-modules/core-java-lambdas/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-lambdas/src/main/java/com/baeldung/lambdaexpression/LambdaExpressionExample.java 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..e3130632fb 100644 --- a/core-java-modules/core-java-lang-5/pom.xml +++ b/core-java-modules/core-java-lang-5/pom.xml @@ -29,19 +29,4 @@ - - - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - - - - org.reflections - reflections - ${reflections.version} - - - \ No newline at end of file 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..4ac9224bb1 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) +- [Different Ways to Create an Object in Java](https://www.baeldung.com/java-different-ways-to-create-objects) diff --git a/core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/objectcreation/objects/ClonableRabbit.java b/core-java-modules/core-java-lang-oop-constructors/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/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/src/main/java/com/baeldung/objectcreation/objects/Rabbit.java b/core-java-modules/core-java-lang-oop-constructors/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/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/src/main/java/com/baeldung/objectcreation/objects/RabbitType.java b/core-java-modules/core-java-lang-oop-constructors/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/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/src/main/java/com/baeldung/objectcreation/objects/SerializableRabbit.java b/core-java-modules/core-java-lang-oop-constructors/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/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/src/main/java/com/baeldung/objectcreation/utils/CreateRabbits.java b/core-java-modules/core-java-lang-oop-constructors/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/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/src/test/java/com/baeldung/objectcreation/CreateRabbitsUnitTest.java b/core-java-modules/core-java-lang-oop-constructors/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/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-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-networking-4/README.md b/core-java-modules/core-java-networking-4/README.md index daec647ebe..e614801468 100644 --- a/core-java-modules/core-java-networking-4/README.md +++ b/core-java-modules/core-java-networking-4/README.md @@ -2,3 +2,4 @@ - [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) diff --git a/core-java-modules/core-java-networking-4/pom.xml b/core-java-modules/core-java-networking-4/pom.xml index 29531a5767..a3694cfea8 100644 --- a/core-java-modules/core-java-networking-4/pom.xml +++ b/core-java-modules/core-java-networking-4/pom.xml @@ -20,6 +20,12 @@ commons-validator ${apache.commons-validator.version} + + org.jsoup + jsoup + ${jsoup.version} + + @@ -28,6 +34,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-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..b53aa2c61b --- /dev/null +++ b/core-java-modules/core-java-reflection-private-constructor/pom.xml @@ -0,0 +1,60 @@ + + + 4.0.0 + core-java-reflection-private-constructor + 0.1.0-SNAPSHOT + 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} + + ${source.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..f6ee08dbda 100644 --- a/core-java-modules/core-java-reflection/pom.xml +++ b/core-java-modules/core-java-reflection/pom.xml @@ -14,6 +14,19 @@ 0.0.1-SNAPSHOT + + + org.reflections + reflections + ${reflections.version} + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + core-java-reflection @@ -39,6 +52,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-security-algorithms/src/test/java/com/baeldung/aes/AESUtilUnitTest.java b/core-java-modules/core-java-security-algorithms/src/test/java/com/baeldung/aes/AESUtilUnitTest.java index 531c20ca79..04499a4fed 100644 --- a/core-java-modules/core-java-security-algorithms/src/test/java/com/baeldung/aes/AESUtilUnitTest.java +++ b/core-java-modules/core-java-security-algorithms/src/test/java/com/baeldung/aes/AESUtilUnitTest.java @@ -48,7 +48,7 @@ class AESUtilUnitTest implements WithAssertions { IvParameterSpec ivParameterSpec = AESUtil.generateIv(); File inputFile = Paths.get("src/test/resources/baeldung.txt") .toFile(); - File encryptedFile = new File("classpath:baeldung.encrypted"); + File encryptedFile = new File("baeldung.encrypted"); File decryptedFile = new File("document.decrypted"); // when @@ -57,8 +57,8 @@ class AESUtilUnitTest implements WithAssertions { // then assertThat(inputFile).hasSameTextualContentAs(decryptedFile); - encryptedFile.delete(); - decryptedFile.delete(); + encryptedFile.deleteOnExit(); + decryptedFile.deleteOnExit(); } @Test 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-collect/README.md b/core-java-modules/core-java-streams-collect/README.md new file mode 100644 index 0000000000..97c76dc431 --- /dev/null +++ b/core-java-modules/core-java-streams-collect/README.md @@ -0,0 +1,2 @@ +## Relevant Articles: + 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..c60cf2ab93 --- /dev/null +++ b/core-java-modules/core-java-streams-collect/pom.xml @@ -0,0 +1,43 @@ + + + 4.0.0 + core-java-streams-4 + 0.1.0-SNAPSHOT + 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..729105e3fd --- /dev/null +++ b/core-java-modules/core-java-streams-maps/README.md @@ -0,0 +1 @@ +## Relevant Articles: 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..06cc9ceef6 --- /dev/null +++ b/core-java-modules/core-java-streams-maps/pom.xml @@ -0,0 +1,67 @@ + + + 4.0.0 + core-java-streams-maps + 0.1.0-SNAPSHOT + 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.source} + ${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/README.md b/core-java-modules/core-java/README.md index 6d9bbe03c2..087c5d356e 100644 --- a/core-java-modules/core-java/README.md +++ b/core-java-modules/core-java/README.md @@ -9,5 +9,3 @@ - [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/pom.xml b/core-java-modules/pom.xml index 1033213cd1..ac8b3115b5 100644 --- a/core-java-modules/pom.xml +++ b/core-java-modules/pom.xml @@ -31,6 +31,7 @@ core-java-collections-2 core-java-collections-3 core-java-collections-4 + core-java-collections-5 core-java-collections-conversions core-java-collections-conversions-2 core-java-collections-set-2 @@ -119,6 +120,8 @@ core-java-streams core-java-streams-2 core-java-streams-3 + core-java-streams-maps + core-java-streams-collect core-java-string-algorithms core-java-string-algorithms-2 core-java-string-apis diff --git a/couchbase/pom.xml b/couchbase/pom.xml index e87975a53c..095bda3610 100644 --- a/couchbase/pom.xml +++ b/couchbase/pom.xml @@ -64,11 +64,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 550f96de33..38a5e30404 100644 --- a/custom-pmd/pom.xml +++ b/custom-pmd/pom.xml @@ -44,10 +44,10 @@ - 3.7.0 - 6.0.1 - 1.8 - 1.8 + 3.10.0 + 6.53.0 + 11 + 11 \ No newline at end of file diff --git a/custom-pmd/src/main/java/com/baeldung/pmd/UnitTestNamingConventionRule.java b/custom-pmd/src/main/java/com/baeldung/pmd/UnitTestNamingConventionRule.java index e30164ac4f..a652bd1bfa 100644 --- a/custom-pmd/src/main/java/com/baeldung/pmd/UnitTestNamingConventionRule.java +++ b/custom-pmd/src/main/java/com/baeldung/pmd/UnitTestNamingConventionRule.java @@ -18,8 +18,9 @@ public class UnitTestNamingConventionRule extends AbstractJavaRule { "UnitTest", "jmhTest"); + @Override public Object visit(ASTClassOrInterfaceDeclaration node, Object data) { - String className = node.getImage(); + String className = node.getSimpleName(); Objects.requireNonNull(className); if (className.endsWith("SpringContextTest")) { diff --git a/dependency-exclusion/README.md b/dependency-exclusion/README.md new file mode 100644 index 0000000000..e9eee1be4d --- /dev/null +++ b/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/dependency-exclusion/core-java-exclusions/pom.xml b/dependency-exclusion/core-java-exclusions/pom.xml new file mode 100644 index 0000000000..cf1b36656d --- /dev/null +++ b/dependency-exclusion/core-java-exclusions/pom.xml @@ -0,0 +1,53 @@ + + + 4.0.0 + core-java-exclusions + 0.0.0-SNAPSHOT + core-java-exclusions + jar + + + com.baeldung.dependency-exclusion + dependency-exclusion + 0.0.1-SNAPSHOT + + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${surefire-version} + + alphabetical + 1 + + + junit + false + + + + + + + org.apache.maven.surefire + surefire-junit47 + dummy + + + + + + + + + junit + junit + test + + + + diff --git a/dependency-exclusion/core-java-exclusions/src/test/java/com/sample/project/tests/ExcludeDirectDependencyUnitTest.java b/dependency-exclusion/core-java-exclusions/src/test/java/com/sample/project/tests/ExcludeDirectDependencyUnitTest.java new file mode 100644 index 0000000000..ed2400f9ac --- /dev/null +++ b/dependency-exclusion/core-java-exclusions/src/test/java/com/sample/project/tests/ExcludeDirectDependencyUnitTest.java @@ -0,0 +1,12 @@ +package com.sample.project.tests; + +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class ExcludeDirectDependencyUnitTest { + @Test + public void basicUnitTest() { + assertTrue(true); + } +} diff --git a/dependency-exclusion/dummy-surefire-junit47/pom.xml b/dependency-exclusion/dummy-surefire-junit47/pom.xml new file mode 100644 index 0000000000..5859ddbe72 --- /dev/null +++ b/dependency-exclusion/dummy-surefire-junit47/pom.xml @@ -0,0 +1,9 @@ + + + 4.0.0 + org.apache.maven.surefire + surefire-junit47 + dummy + diff --git a/dependency-exclusion/pom.xml b/dependency-exclusion/pom.xml new file mode 100644 index 0000000000..ac83cc161a --- /dev/null +++ b/dependency-exclusion/pom.xml @@ -0,0 +1,71 @@ + + + 4.0.0 + com.baeldung.dependency-exclusion + dependency-exclusion + dependency-exclusion + pom + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + + 2.22.2 + + + + dummy-surefire-junit47 + core-java-exclusions + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.7.0 + + 1.8 + 1.8 + + -parameters + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${surefire-version} + + 1 + + + + org.apache.maven.surefire + surefire-junit-platform + ${surefire-version} + + + + + + + + + + + junit + junit + 4.13 + + + + + diff --git a/dependeny-exclusion/core-java-exclusions/pom.xml b/dependeny-exclusion/core-java-exclusions/pom.xml new file mode 100644 index 0000000000..cf1f6d1e1b --- /dev/null +++ b/dependeny-exclusion/core-java-exclusions/pom.xml @@ -0,0 +1,53 @@ + + + 4.0.0 + core-java-exclusions + 0.0.0-SNAPSHOT + core-java-exclusions + jar + + + com.baeldung.dependency-exclusion + dependency-exclusion + 0.0.1-SNAPSHOT + + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${surefire-version} + + alphabetical + 1 + + + junit + false + + + + + + + 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/dependeny-exclusion/core-java-exclusions/src/test/java/com/sample/project/tests/ExcludeDirectDependencyUnitTest.java new file mode 100644 index 0000000000..ed2400f9ac --- /dev/null +++ b/dependeny-exclusion/core-java-exclusions/src/test/java/com/sample/project/tests/ExcludeDirectDependencyUnitTest.java @@ -0,0 +1,12 @@ +package com.sample.project.tests; + +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class ExcludeDirectDependencyUnitTest { + @Test + public void basicUnitTest() { + assertTrue(true); + } +} diff --git a/dependeny-exclusion/dummy-surefire-junit47/pom.xml b/dependeny-exclusion/dummy-surefire-junit47/pom.xml new file mode 100644 index 0000000000..5859ddbe72 --- /dev/null +++ b/dependeny-exclusion/dummy-surefire-junit47/pom.xml @@ -0,0 +1,9 @@ + + + 4.0.0 + org.apache.maven.surefire + surefire-junit47 + dummy + diff --git a/dependeny-exclusion/pom.xml b/dependeny-exclusion/pom.xml new file mode 100644 index 0000000000..ac83cc161a --- /dev/null +++ b/dependeny-exclusion/pom.xml @@ -0,0 +1,71 @@ + + + 4.0.0 + com.baeldung.dependency-exclusion + dependency-exclusion + dependency-exclusion + pom + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + + 2.22.2 + + + + dummy-surefire-junit47 + core-java-exclusions + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.7.0 + + 1.8 + 1.8 + + -parameters + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${surefire-version} + + 1 + + + + org.apache.maven.surefire + surefire-junit-platform + ${surefire-version} + + + + + + + + + + + junit + junit + 4.13 + + + + + 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/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..bbc1f3170a 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.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,14 +43,10 @@ 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(); @@ -59,7 +54,6 @@ public class DroolsBeanFactory { kieFileSystem.write(ResourceFactory.newClassPathResource("com/baeldung/drools/rules/SuggestApplicant.drl")); kieFileSystem.write(ResourceFactory.newClassPathResource("com/baeldung/drools/rules/Product_rules.xls")); - KieBuilder kb = kieServices.newKieBuilder(kieFileSystem); kb.buildAll(); KieModule kieModule = kb.getKieModule(); @@ -67,7 +61,6 @@ public class DroolsBeanFactory { KieContainer kContainer = kieServices.newKieContainer(kieModule.getReleaseId()); return kContainer.newKieSession(); - } public KieSession getKieSession(Resource dt) { 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/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/feign/README.md b/feign/README.md index 2dea14ca52..3e733448fb 100644 --- a/feign/README.md +++ b/feign/README.md @@ -7,3 +7,9 @@ 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) +- [Post form-url-encoded Data with Spring Cloud Feign](https://www.baeldung.com/spring-cloud-post-form-url-encoded-data) diff --git a/feign/pom.xml b/feign/pom.xml index 3ac816fc1d..7338cf7508 100644 --- a/feign/pom.xml +++ b/feign/pom.xml @@ -64,6 +64,22 @@ spring-boot-starter-test test + + io.github.openfeign.form + feign-form-spring + ${feign.form.spring.version} + + + org.springframework.cloud + spring-cloud-starter-openfeign + ${spring.cloud.openfeign.version} + + + com.github.tomakehurst + wiremock-jre8 + ${wire.mock.version} + test + @@ -118,6 +134,9 @@ 11.8 1.6.3 + 3.8.0 + 3.1.2 + 2.33.2 \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/ExampleApplication.java b/feign/src/main/java/com/baeldung/core/ExampleApplication.java similarity index 90% rename from spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/ExampleApplication.java rename to feign/src/main/java/com/baeldung/core/ExampleApplication.java index c7f07f6667..391e808ede 100644 --- a/spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/ExampleApplication.java +++ b/feign/src/main/java/com/baeldung/core/ExampleApplication.java @@ -1,4 +1,4 @@ -package com.baeldung.cloud.openfeign; +package com.baeldung.core; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/client/EmployeeClient.java b/feign/src/main/java/com/baeldung/core/client/EmployeeClient.java similarity index 73% rename from spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/client/EmployeeClient.java rename to feign/src/main/java/com/baeldung/core/client/EmployeeClient.java index 569401bdcf..0ff8637a94 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/client/EmployeeClient.java +++ b/feign/src/main/java/com/baeldung/core/client/EmployeeClient.java @@ -1,6 +1,7 @@ -package com.baeldung.cloud.openfeign.client; +package com.baeldung.core.client; + +import com.baeldung.core.model.Employee; -import com.baeldung.cloud.openfeign.model.Employee; import feign.Headers; import feign.Param; import feign.RequestLine; diff --git a/feign/src/main/java/com/baeldung/core/client/FormClient.java b/feign/src/main/java/com/baeldung/core/client/FormClient.java new file mode 100644 index 0000000000..074402aef3 --- /dev/null +++ b/feign/src/main/java/com/baeldung/core/client/FormClient.java @@ -0,0 +1,37 @@ +package com.baeldung.core.client; + +import java.util.Map; + +import org.springframework.beans.factory.ObjectFactory; +import org.springframework.boot.autoconfigure.http.HttpMessageConverters; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.cloud.openfeign.support.SpringEncoder; +import org.springframework.context.annotation.Bean; +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; + +import com.baeldung.core.defaulterrorhandling.model.FormData; + +import feign.codec.Encoder; +import feign.form.spring.SpringFormEncoder; + +@FeignClient(name = "form-client", url = "http://localhost:8085/api", configuration = FormFeignEncoderConfig.class) +public interface FormClient { + + @PostMapping(value = "/form", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE) + void postFormData(@RequestBody FormData data); + + @PostMapping(value = "/form/map", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE) + void postFormMapData(Map data); + +} + +class FormFeignEncoderConfig { + + @Bean + public Encoder encoder(ObjectFactory converters) { + return new SpringFormEncoder(new SpringEncoder(converters)); + } + +} \ No newline at end of file diff --git a/feign/src/main/java/com/baeldung/core/client/UserClient.java b/feign/src/main/java/com/baeldung/core/client/UserClient.java new file mode 100644 index 0000000000..a16f924ad5 --- /dev/null +++ b/feign/src/main/java/com/baeldung/core/client/UserClient.java @@ -0,0 +1,13 @@ +package com.baeldung.core.client; + +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.web.bind.annotation.GetMapping; + +import com.baeldung.core.config.FeignConfig; + +@FeignClient(name = "user-client", url="https://jsonplaceholder.typicode.com", configuration = FeignConfig.class) +public interface UserClient { + + @GetMapping(value = "/users") + String getUsers(); +} \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/config/FeignConfig.java b/feign/src/main/java/com/baeldung/core/config/FeignConfig.java similarity index 79% rename from spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/config/FeignConfig.java rename to feign/src/main/java/com/baeldung/core/config/FeignConfig.java index d51e97b9e4..43da2fce0e 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/config/FeignConfig.java +++ b/feign/src/main/java/com/baeldung/core/config/FeignConfig.java @@ -1,7 +1,8 @@ -package com.baeldung.cloud.openfeign.config; +package com.baeldung.core.config; + +import org.springframework.context.annotation.Bean; import feign.Logger; -import org.springframework.context.annotation.Bean; public class FeignConfig { diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/controller/EmployeeController.java b/feign/src/main/java/com/baeldung/core/controller/EmployeeController.java similarity index 81% rename from spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/controller/EmployeeController.java rename to feign/src/main/java/com/baeldung/core/controller/EmployeeController.java index 65897ad48e..7f7d39240e 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/controller/EmployeeController.java +++ b/feign/src/main/java/com/baeldung/core/controller/EmployeeController.java @@ -1,13 +1,15 @@ -package com.baeldung.cloud.openfeign.controller; +package com.baeldung.core.controller; -import com.baeldung.cloud.openfeign.client.EmployeeClient; -import com.baeldung.cloud.openfeign.model.Employee; -import feign.Feign; -import feign.form.spring.SpringFormEncoder; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; +import com.baeldung.core.client.EmployeeClient; +import com.baeldung.core.model.Employee; + +import feign.Feign; +import feign.form.spring.SpringFormEncoder; + @RestController public class EmployeeController { diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/customizederrorhandling/client/ProductClient.java b/feign/src/main/java/com/baeldung/core/customizederrorhandling/client/ProductClient.java similarity index 70% rename from spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/customizederrorhandling/client/ProductClient.java rename to feign/src/main/java/com/baeldung/core/customizederrorhandling/client/ProductClient.java index 8a6c5d5846..113051722b 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/customizederrorhandling/client/ProductClient.java +++ b/feign/src/main/java/com/baeldung/core/customizederrorhandling/client/ProductClient.java @@ -1,13 +1,13 @@ -package com.baeldung.cloud.openfeign.customizederrorhandling.client; - -import com.baeldung.cloud.openfeign.customizederrorhandling.config.FeignConfig; -import com.baeldung.cloud.openfeign.defaulterrorhandling.model.Product; +package com.baeldung.core.customizederrorhandling.client; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; +import com.baeldung.core.customizederrorhandling.config.FeignConfig; +import com.baeldung.core.defaulterrorhandling.model.Product; + @FeignClient(name = "product-client-2", url = "http://localhost:8081/product/", configuration = FeignConfig.class) public interface ProductClient { diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/customizederrorhandling/config/CustomErrorDecoder.java b/feign/src/main/java/com/baeldung/core/customizederrorhandling/config/CustomErrorDecoder.java similarity index 65% rename from spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/customizederrorhandling/config/CustomErrorDecoder.java rename to feign/src/main/java/com/baeldung/core/customizederrorhandling/config/CustomErrorDecoder.java index 3750e6288d..5466b61b3a 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/customizederrorhandling/config/CustomErrorDecoder.java +++ b/feign/src/main/java/com/baeldung/core/customizederrorhandling/config/CustomErrorDecoder.java @@ -1,8 +1,9 @@ -package com.baeldung.cloud.openfeign.customizederrorhandling.config; +package com.baeldung.core.customizederrorhandling.config; + +import com.baeldung.core.customizederrorhandling.exception.ProductNotFoundException; +import com.baeldung.core.customizederrorhandling.exception.ProductServiceNotAvailableException; +import com.baeldung.core.exception.BadRequestException; -import com.baeldung.cloud.openfeign.exception.BadRequestException; -import com.baeldung.cloud.openfeign.customizederrorhandling.exception.ProductNotFoundException; -import com.baeldung.cloud.openfeign.customizederrorhandling.exception.ProductServiceNotAvailableException; import feign.Response; import feign.codec.ErrorDecoder; diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/customizederrorhandling/config/FeignConfig.java b/feign/src/main/java/com/baeldung/core/customizederrorhandling/config/FeignConfig.java similarity index 81% rename from spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/customizederrorhandling/config/FeignConfig.java rename to feign/src/main/java/com/baeldung/core/customizederrorhandling/config/FeignConfig.java index 5cddd521f1..980b8b5b38 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/customizederrorhandling/config/FeignConfig.java +++ b/feign/src/main/java/com/baeldung/core/customizederrorhandling/config/FeignConfig.java @@ -1,8 +1,9 @@ -package com.baeldung.cloud.openfeign.customizederrorhandling.config; +package com.baeldung.core.customizederrorhandling.config; + +import org.springframework.context.annotation.Bean; import feign.Logger; import feign.codec.ErrorDecoder; -import org.springframework.context.annotation.Bean; public class FeignConfig { diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/customizederrorhandling/controller/ProductController.java b/feign/src/main/java/com/baeldung/core/customizederrorhandling/controller/ProductController.java similarity index 52% rename from spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/customizederrorhandling/controller/ProductController.java rename to feign/src/main/java/com/baeldung/core/customizederrorhandling/controller/ProductController.java index 9b7a5aea1d..6d6f784e66 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/customizederrorhandling/controller/ProductController.java +++ b/feign/src/main/java/com/baeldung/core/customizederrorhandling/controller/ProductController.java @@ -1,12 +1,13 @@ -package com.baeldung.cloud.openfeign.customizederrorhandling.controller; +package com.baeldung.core.customizederrorhandling.controller; -import com.baeldung.cloud.openfeign.customizederrorhandling.client.ProductClient; - - -import com.baeldung.cloud.openfeign.defaulterrorhandling.model.Product; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.*; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import com.baeldung.core.customizederrorhandling.client.ProductClient; +import com.baeldung.core.defaulterrorhandling.model.Product; @RestController("product_controller2") @RequestMapping(value = "myapp2") diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/customizederrorhandling/exception/ErrorResponse.java b/feign/src/main/java/com/baeldung/core/customizederrorhandling/exception/ErrorResponse.java similarity index 94% rename from spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/customizederrorhandling/exception/ErrorResponse.java rename to feign/src/main/java/com/baeldung/core/customizederrorhandling/exception/ErrorResponse.java index c72e3db68b..6e739e5e40 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/customizederrorhandling/exception/ErrorResponse.java +++ b/feign/src/main/java/com/baeldung/core/customizederrorhandling/exception/ErrorResponse.java @@ -1,10 +1,11 @@ -package com.baeldung.cloud.openfeign.customizederrorhandling.exception; +package com.baeldung.core.customizederrorhandling.exception; + +import java.util.Date; + +import org.springframework.http.HttpStatus; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonProperty; -import org.springframework.http.HttpStatus; - -import java.util.Date; public class ErrorResponse { diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/customizederrorhandling/exception/ProductExceptionHandler.java b/feign/src/main/java/com/baeldung/core/customizederrorhandling/exception/ProductExceptionHandler.java similarity index 92% rename from spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/customizederrorhandling/exception/ProductExceptionHandler.java rename to feign/src/main/java/com/baeldung/core/customizederrorhandling/exception/ProductExceptionHandler.java index 2ed709bc34..c83d917570 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/customizederrorhandling/exception/ProductExceptionHandler.java +++ b/feign/src/main/java/com/baeldung/core/customizederrorhandling/exception/ProductExceptionHandler.java @@ -1,6 +1,5 @@ -package com.baeldung.cloud.openfeign.customizederrorhandling.exception; +package com.baeldung.core.customizederrorhandling.exception; -import com.baeldung.cloud.openfeign.exception.BadRequestException; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ExceptionHandler; diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/customizederrorhandling/exception/ProductNotFoundException.java b/feign/src/main/java/com/baeldung/core/customizederrorhandling/exception/ProductNotFoundException.java similarity index 68% rename from spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/customizederrorhandling/exception/ProductNotFoundException.java rename to feign/src/main/java/com/baeldung/core/customizederrorhandling/exception/ProductNotFoundException.java index 337cb89f7b..fa993ce700 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/customizederrorhandling/exception/ProductNotFoundException.java +++ b/feign/src/main/java/com/baeldung/core/customizederrorhandling/exception/ProductNotFoundException.java @@ -1,4 +1,4 @@ -package com.baeldung.cloud.openfeign.customizederrorhandling.exception; +package com.baeldung.core.customizederrorhandling.exception; public class ProductNotFoundException extends RuntimeException { diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/customizederrorhandling/exception/ProductServiceNotAvailableException.java b/feign/src/main/java/com/baeldung/core/customizederrorhandling/exception/ProductServiceNotAvailableException.java similarity index 70% rename from spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/customizederrorhandling/exception/ProductServiceNotAvailableException.java rename to feign/src/main/java/com/baeldung/core/customizederrorhandling/exception/ProductServiceNotAvailableException.java index ce30f8c310..887d2cd91d 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/customizederrorhandling/exception/ProductServiceNotAvailableException.java +++ b/feign/src/main/java/com/baeldung/core/customizederrorhandling/exception/ProductServiceNotAvailableException.java @@ -1,4 +1,4 @@ -package com.baeldung.cloud.openfeign.customizederrorhandling.exception; +package com.baeldung.core.customizederrorhandling.exception; public class ProductServiceNotAvailableException extends RuntimeException { diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/defaulterrorhandling/client/ProductClient.java b/feign/src/main/java/com/baeldung/core/defaulterrorhandling/client/ProductClient.java similarity index 70% rename from spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/defaulterrorhandling/client/ProductClient.java rename to feign/src/main/java/com/baeldung/core/defaulterrorhandling/client/ProductClient.java index 2cef3d4238..4eb435331d 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/defaulterrorhandling/client/ProductClient.java +++ b/feign/src/main/java/com/baeldung/core/defaulterrorhandling/client/ProductClient.java @@ -1,13 +1,13 @@ -package com.baeldung.cloud.openfeign.defaulterrorhandling.client; - -import com.baeldung.cloud.openfeign.defaulterrorhandling.config.FeignConfig; -import com.baeldung.cloud.openfeign.defaulterrorhandling.model.Product; +package com.baeldung.core.defaulterrorhandling.client; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; +import com.baeldung.core.defaulterrorhandling.config.FeignConfig; +import com.baeldung.core.defaulterrorhandling.model.Product; + @FeignClient(name = "product-client", url = "http://localhost:8084/product/", configuration = FeignConfig.class) public interface ProductClient { diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/defaulterrorhandling/config/FeignConfig.java b/feign/src/main/java/com/baeldung/core/defaulterrorhandling/config/FeignConfig.java similarity index 74% rename from spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/defaulterrorhandling/config/FeignConfig.java rename to feign/src/main/java/com/baeldung/core/defaulterrorhandling/config/FeignConfig.java index f2329ebe0b..cef8cbb6d9 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/defaulterrorhandling/config/FeignConfig.java +++ b/feign/src/main/java/com/baeldung/core/defaulterrorhandling/config/FeignConfig.java @@ -1,7 +1,8 @@ -package com.baeldung.cloud.openfeign.defaulterrorhandling.config; +package com.baeldung.core.defaulterrorhandling.config; + +import org.springframework.context.annotation.Bean; import feign.Logger; -import org.springframework.context.annotation.Bean; public class FeignConfig { diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/defaulterrorhandling/controller/ProductController.java b/feign/src/main/java/com/baeldung/core/defaulterrorhandling/controller/ProductController.java similarity index 52% rename from spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/defaulterrorhandling/controller/ProductController.java rename to feign/src/main/java/com/baeldung/core/defaulterrorhandling/controller/ProductController.java index df352f8d52..80f571f29a 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/defaulterrorhandling/controller/ProductController.java +++ b/feign/src/main/java/com/baeldung/core/defaulterrorhandling/controller/ProductController.java @@ -1,10 +1,13 @@ -package com.baeldung.cloud.openfeign.defaulterrorhandling.controller; +package com.baeldung.core.defaulterrorhandling.controller; -import com.baeldung.cloud.openfeign.defaulterrorhandling.client.ProductClient; - -import com.baeldung.cloud.openfeign.defaulterrorhandling.model.Product; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.*; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.baeldung.core.defaulterrorhandling.client.ProductClient; +import com.baeldung.core.defaulterrorhandling.model.Product; @RestController("product_controller1") @RequestMapping(value ="myapp1") diff --git a/feign/src/main/java/com/baeldung/core/defaulterrorhandling/model/FormData.java b/feign/src/main/java/com/baeldung/core/defaulterrorhandling/model/FormData.java new file mode 100644 index 0000000000..6210451f2d --- /dev/null +++ b/feign/src/main/java/com/baeldung/core/defaulterrorhandling/model/FormData.java @@ -0,0 +1,12 @@ +package com.baeldung.core.defaulterrorhandling.model; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class FormData { + + int id; + String name; +} diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/defaulterrorhandling/model/Product.java b/feign/src/main/java/com/baeldung/core/defaulterrorhandling/model/Product.java similarity index 82% rename from spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/defaulterrorhandling/model/Product.java rename to feign/src/main/java/com/baeldung/core/defaulterrorhandling/model/Product.java index 25a1662c99..35d860332e 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/defaulterrorhandling/model/Product.java +++ b/feign/src/main/java/com/baeldung/core/defaulterrorhandling/model/Product.java @@ -1,4 +1,4 @@ -package com.baeldung.cloud.openfeign.defaulterrorhandling.model; +package com.baeldung.core.defaulterrorhandling.model; public class Product { diff --git a/spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/exception/BadRequestException.java b/feign/src/main/java/com/baeldung/core/exception/BadRequestException.java similarity index 75% rename from spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/exception/BadRequestException.java rename to feign/src/main/java/com/baeldung/core/exception/BadRequestException.java index 7c2daf43fe..4553bb5576 100644 --- a/spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/exception/BadRequestException.java +++ b/feign/src/main/java/com/baeldung/core/exception/BadRequestException.java @@ -1,4 +1,4 @@ -package com.baeldung.cloud.openfeign.exception; +package com.baeldung.core.exception; public class BadRequestException extends Exception { @@ -15,7 +15,7 @@ public class BadRequestException extends Exception { @Override public String toString() { - return "BadRequestException: " + getMessage(); + return "BadRequestException: "+getMessage(); } } diff --git a/spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/exception/NotFoundException.java b/feign/src/main/java/com/baeldung/core/exception/NotFoundException.java similarity index 86% rename from spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/exception/NotFoundException.java rename to feign/src/main/java/com/baeldung/core/exception/NotFoundException.java index 19f6204b86..07f4e0862f 100644 --- a/spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/exception/NotFoundException.java +++ b/feign/src/main/java/com/baeldung/core/exception/NotFoundException.java @@ -1,4 +1,4 @@ -package com.baeldung.cloud.openfeign.exception; +package com.baeldung.core.exception; public class NotFoundException extends Exception { diff --git a/spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/fileupload/config/ExceptionMessage.java b/feign/src/main/java/com/baeldung/core/fileupload/config/ExceptionMessage.java similarity index 95% rename from spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/fileupload/config/ExceptionMessage.java rename to feign/src/main/java/com/baeldung/core/fileupload/config/ExceptionMessage.java index 45a555b2ea..8301705ca6 100644 --- a/spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/fileupload/config/ExceptionMessage.java +++ b/feign/src/main/java/com/baeldung/core/fileupload/config/ExceptionMessage.java @@ -1,4 +1,4 @@ -package com.baeldung.cloud.openfeign.fileupload.config; +package com.baeldung.core.fileupload.config; public class ExceptionMessage { private String timestamp; diff --git a/spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/fileupload/config/FeignSupportConfig.java b/feign/src/main/java/com/baeldung/core/fileupload/config/FeignSupportConfig.java similarity index 57% rename from spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/fileupload/config/FeignSupportConfig.java rename to feign/src/main/java/com/baeldung/core/fileupload/config/FeignSupportConfig.java index 802077a3d7..c8c9eb1acc 100644 --- a/spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/fileupload/config/FeignSupportConfig.java +++ b/feign/src/main/java/com/baeldung/core/fileupload/config/FeignSupportConfig.java @@ -1,6 +1,5 @@ -package com.baeldung.cloud.openfeign.fileupload.config; +package com.baeldung.core.fileupload.config; -import org.springframework.beans.factory.ObjectFactory; import org.springframework.boot.autoconfigure.http.HttpMessageConverters; import org.springframework.cloud.openfeign.support.SpringEncoder; import org.springframework.context.annotation.Bean; @@ -13,12 +12,7 @@ import feign.form.spring.SpringFormEncoder; public class FeignSupportConfig { @Bean public Encoder multipartFormEncoder() { - return new SpringFormEncoder(new SpringEncoder(new ObjectFactory() { - @Override - public HttpMessageConverters getObject() { - return new HttpMessageConverters(new RestTemplate().getMessageConverters()); - } - })); + return new SpringFormEncoder(new SpringEncoder(() -> new HttpMessageConverters(new RestTemplate().getMessageConverters()))); } @Bean diff --git a/spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/fileupload/config/RetreiveMessageErrorDecoder.java b/feign/src/main/java/com/baeldung/core/fileupload/config/RetreiveMessageErrorDecoder.java similarity index 82% rename from spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/fileupload/config/RetreiveMessageErrorDecoder.java rename to feign/src/main/java/com/baeldung/core/fileupload/config/RetreiveMessageErrorDecoder.java index 5ebd7b6887..fc2c8da0ed 100644 --- a/spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/fileupload/config/RetreiveMessageErrorDecoder.java +++ b/feign/src/main/java/com/baeldung/core/fileupload/config/RetreiveMessageErrorDecoder.java @@ -1,10 +1,10 @@ -package com.baeldung.cloud.openfeign.fileupload.config; +package com.baeldung.core.fileupload.config; import java.io.IOException; import java.io.InputStream; -import com.baeldung.cloud.openfeign.exception.BadRequestException; -import com.baeldung.cloud.openfeign.exception.NotFoundException; +import com.baeldung.core.exception.BadRequestException; +import com.baeldung.core.exception.NotFoundException; import com.fasterxml.jackson.databind.ObjectMapper; import feign.Response; @@ -12,9 +12,10 @@ 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 = null; + ExceptionMessage message; try (InputStream bodyIs = response.body() .asInputStream()) { ObjectMapper mapper = new ObjectMapper(); diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/controller/FileController.java b/feign/src/main/java/com/baeldung/core/fileupload/controller/FileController.java similarity index 88% rename from spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/controller/FileController.java rename to feign/src/main/java/com/baeldung/core/fileupload/controller/FileController.java index 1ddbfcea81..7ba4746979 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/controller/FileController.java +++ b/feign/src/main/java/com/baeldung/core/fileupload/controller/FileController.java @@ -1,4 +1,4 @@ -package com.baeldung.cloud.openfeign.fileupload.controller; +package com.baeldung.core.fileupload.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; @@ -6,7 +6,7 @@ import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; -import com.baeldung.cloud.openfeign.fileupload.service.UploadService; +import com.baeldung.core.fileupload.service.UploadService; @RestController public class FileController { diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/UploadClient.java b/feign/src/main/java/com/baeldung/core/fileupload/service/UploadClient.java similarity index 85% rename from spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/UploadClient.java rename to feign/src/main/java/com/baeldung/core/fileupload/service/UploadClient.java index 8f3ef7e421..37b059d642 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/UploadClient.java +++ b/feign/src/main/java/com/baeldung/core/fileupload/service/UploadClient.java @@ -1,4 +1,4 @@ -package com.baeldung.cloud.openfeign.fileupload.service; +package com.baeldung.core.fileupload.service; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.http.MediaType; @@ -6,7 +6,7 @@ import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.multipart.MultipartFile; -import com.baeldung.cloud.openfeign.fileupload.config.FeignSupportConfig; +import com.baeldung.core.fileupload.config.FeignSupportConfig; @FeignClient(name = "file", url = "http://localhost:8081", configuration = FeignSupportConfig.class) public interface UploadClient { diff --git a/spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/UploadResource.java b/feign/src/main/java/com/baeldung/core/fileupload/service/UploadResource.java similarity index 75% rename from spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/UploadResource.java rename to feign/src/main/java/com/baeldung/core/fileupload/service/UploadResource.java index 2d5090897d..9d3d173cd4 100644 --- a/spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/UploadResource.java +++ b/feign/src/main/java/com/baeldung/core/fileupload/service/UploadResource.java @@ -1,4 +1,4 @@ -package com.baeldung.cloud.openfeign.fileupload.service; +package com.baeldung.core.fileupload.service; import org.springframework.web.multipart.MultipartFile; @@ -9,7 +9,7 @@ import feign.Response; public interface UploadResource { - @RequestLine("POST /upload-error") + @RequestLine("POST /upload-file") @Headers("Content-Type: multipart/form-data") Response uploadFile(@Param("file") MultipartFile file); diff --git a/spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/UploadService.java b/feign/src/main/java/com/baeldung/core/fileupload/service/UploadService.java similarity index 62% rename from spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/UploadService.java rename to feign/src/main/java/com/baeldung/core/fileupload/service/UploadService.java index 244a5a2168..5176ddf0fa 100644 --- a/spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/UploadService.java +++ b/feign/src/main/java/com/baeldung/core/fileupload/service/UploadService.java @@ -1,4 +1,4 @@ -package com.baeldung.cloud.openfeign.fileupload.service; +package com.baeldung.core.fileupload.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @@ -13,22 +13,20 @@ public class UploadService { private static final String HTTP_FILE_UPLOAD_URL = "http://localhost:8081"; @Autowired - private FileUploadClientWithFallbackFactory fileUploadClient; - @Autowired - private FileUploadClientWithFallBack fileUploadClientWithFallback; - + 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 uploadFileWithFallbackFactory(MultipartFile file) { - return fileUploadClient.fileUpload(file); + + public String uploadFile(MultipartFile file) { + return client.fileUpload(file); } - - public String uploadFileWithFallback(MultipartFile file) { - return fileUploadClientWithFallback.fileUpload(file); + + public String uploadFileError(MultipartFile file) { + return client.fileUpload(file); } } \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/model/Employee.java b/feign/src/main/java/com/baeldung/core/model/Employee.java similarity index 81% rename from spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/model/Employee.java rename to feign/src/main/java/com/baeldung/core/model/Employee.java index 7b8ed1232b..7b0c9e1933 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/model/Employee.java +++ b/feign/src/main/java/com/baeldung/core/model/Employee.java @@ -1,4 +1,4 @@ -package com.baeldung.cloud.openfeign.model; +package com.baeldung.core.model; public class Employee { diff --git a/feign/src/main/resources/application.properties b/feign/src/main/resources/application.properties index a57c6e36a3..e48d5fd65a 100644 --- a/feign/src/main/resources/application.properties +++ b/feign/src/main/resources/application.properties @@ -5,3 +5,5 @@ ws.port.type.name=UsersPort ws.target.namespace=http://www.baeldung.com/springbootsoap/feignclient ws.location.uri=http://localhost:${server.port}/ws/users/ debug=false + +logging.level.com.baeldung.core=DEBUG \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-openfeign-2/src/main/resources/fileupload.txt b/feign/src/main/resources/fileupload.txt similarity index 100% rename from spring-cloud-modules/spring-cloud-openfeign-2/src/main/resources/fileupload.txt rename to feign/src/main/resources/fileupload.txt diff --git a/feign/src/main/resources/logback.xml b/feign/src/main/resources/logback.xml deleted file mode 100644 index e5e962c8e0..0000000000 --- a/feign/src/main/resources/logback.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - - \ No newline at end of file diff --git a/feign/src/main/resources/logback_spring.xml b/feign/src/main/resources/logback_spring.xml new file mode 100644 index 0000000000..2a307a5b27 --- /dev/null +++ b/feign/src/main/resources/logback_spring.xml @@ -0,0 +1,45 @@ + + + + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + ${LOGS}/spring-boot-logger.log + + %d %p %C{1.} [%t] %m%n + + + + + ${LOGS}/archived/spring-boot-logger-%d{yyyy-MM-dd}.%i.log + + + 10MB + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-openfeign-2/src/test/java/com/baeldung/cloud/openfeign/OpenFeignFileUploadLiveTest.java b/feign/src/test/java/com/baeldung/core/OpenFeignFileUploadLiveTest.java similarity index 55% rename from spring-cloud-modules/spring-cloud-openfeign-2/src/test/java/com/baeldung/cloud/openfeign/OpenFeignFileUploadLiveTest.java rename to feign/src/test/java/com/baeldung/core/OpenFeignFileUploadLiveTest.java index 6396be2453..f9dc8b13ed 100644 --- a/spring-cloud-modules/spring-cloud-openfeign-2/src/test/java/com/baeldung/cloud/openfeign/OpenFeignFileUploadLiveTest.java +++ b/feign/src/test/java/com/baeldung/core/OpenFeignFileUploadLiveTest.java @@ -1,4 +1,4 @@ -package com.baeldung.cloud.openfeign; +package com.baeldung.core; import java.io.File; import java.io.FileInputStream; @@ -14,11 +14,10 @@ import org.springframework.mock.web.MockMultipartFile; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.multipart.MultipartFile; -import com.baeldung.cloud.openfeign.exception.NotFoundException; -import com.baeldung.cloud.openfeign.fileupload.service.UploadService; +import com.baeldung.core.fileupload.service.UploadService; @RunWith(SpringRunner.class) -@SpringBootTest +@SpringBootTest(classes = ExampleApplication.class) public class OpenFeignFileUploadLiveTest { @Autowired @@ -26,36 +25,26 @@ public class OpenFeignFileUploadLiveTest { private static String FILE_NAME = "fileupload.txt"; - @Test(expected = NotFoundException.class) - public void whenFileUploadClientFallbackFactory_thenFileUploadError() throws IOException { + @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)); - uploadService.uploadFileWithFallbackFactory(multipartFile); - } - - @Test(expected = NotFoundException.class) - public void whenFileUploadClientFallback_thenFileUploadError() 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)); - uploadService.uploadFileWithFallback(multipartFile); + Assert.assertTrue(uploadService.uploadFileWithManualClient(multipartFile)); } - @Test(expected = NotFoundException.class) - public void whenFileUploadWithMannualClient_thenFileUploadError() throws IOException { + @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)); - uploadService.uploadFileWithManualClient(multipartFile); + String uploadFile = uploadService.uploadFile(multipartFile); + Assert.assertNotNull(uploadFile); } } diff --git a/feign/src/test/java/com/baeldung/core/client/FormClientUnitTest.java b/feign/src/test/java/com/baeldung/core/client/FormClientUnitTest.java new file mode 100644 index 0000000000..b9c263b60b --- /dev/null +++ b/feign/src/test/java/com/baeldung/core/client/FormClientUnitTest.java @@ -0,0 +1,78 @@ +package com.baeldung.core.client; + +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.configureFor; +import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; +import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor; +import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; +import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; +import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +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.http.HttpStatus; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import com.baeldung.core.defaulterrorhandling.model.FormData; +import com.github.tomakehurst.wiremock.WireMockServer; +import com.github.tomakehurst.wiremock.client.WireMock; + +import lombok.extern.slf4j.Slf4j; + +@ExtendWith(SpringExtension.class) +@SpringBootTest +@Slf4j +class FormClientUnitTest { + + private static WireMockServer wireMockServer; + + @Autowired + FormClient formClient; + + @BeforeAll + public static void startWireMockServer() { + wireMockServer = new WireMockServer(8085); + configureFor("localhost", 8085); + wireMockServer.start(); + + } + + @AfterAll + public static void stopWireMockServer() { + wireMockServer.stop(); + } + + @Test + public void givenFormData_whenPostFormDataCalled_thenReturnSuccess() { + FormData formData = new FormData(1, "baeldung"); + stubFor(WireMock.post(urlEqualTo("/api/form")) + .willReturn(aResponse().withStatus(HttpStatus.OK.value()))); + + formClient.postFormData(formData); + wireMockServer.verify(postRequestedFor(urlPathEqualTo("/api/form")) + .withHeader("Content-Type", equalTo("application/x-www-form-urlencoded; charset=UTF-8")) + .withRequestBody(equalTo("name=baeldung&id=1"))); + } + + @Test + public void givenFormMap_whenPostFormMapDataCalled_thenReturnSuccess() { + Map mapData = new HashMap<>(); + mapData.put("name", "baeldung"); + mapData.put("id", "1"); + stubFor(WireMock.post(urlEqualTo("/api/form/map")) + .willReturn(aResponse().withStatus(HttpStatus.OK.value()))); + + formClient.postFormMapData(mapData); + wireMockServer.verify(postRequestedFor(urlPathEqualTo("/api/form/map")) + .withHeader("Content-Type", equalTo("application/x-www-form-urlencoded; charset=UTF-8")) + .withRequestBody(equalTo("name=baeldung&id=1"))); + } + +} \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/customizederrorhandling/client/ProductClientUnitTest.java b/feign/src/test/java/com/baeldung/core/customizederrorhandling/client/ProductClientUnitTest.java similarity index 69% rename from spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/customizederrorhandling/client/ProductClientUnitTest.java rename to feign/src/test/java/com/baeldung/core/customizederrorhandling/client/ProductClientUnitTest.java index 7cf2a12692..ed5f18eb3f 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/customizederrorhandling/client/ProductClientUnitTest.java +++ b/feign/src/test/java/com/baeldung/core/customizederrorhandling/client/ProductClientUnitTest.java @@ -1,8 +1,12 @@ -package com.baeldung.cloud.openfeign.customizederrorhandling.client; +package com.baeldung.core.customizederrorhandling.client; + +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.configureFor; +import static com.github.tomakehurst.wiremock.client.WireMock.get; +import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; +import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; +import static org.junit.Assert.assertThrows; -import com.baeldung.cloud.openfeign.customizederrorhandling.exception.ProductNotFoundException; -import com.baeldung.cloud.openfeign.customizederrorhandling.exception.ProductServiceNotAvailableException; -import com.github.tomakehurst.wiremock.WireMockServer; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -11,11 +15,13 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; -import static com.github.tomakehurst.wiremock.client.WireMock.*; -import static org.junit.Assert.assertThrows; +import com.baeldung.core.ExampleApplication; +import com.baeldung.core.customizederrorhandling.exception.ProductNotFoundException; +import com.baeldung.core.customizederrorhandling.exception.ProductServiceNotAvailableException; +import com.github.tomakehurst.wiremock.WireMockServer; @RunWith(SpringRunner.class) -@SpringBootTest +@SpringBootTest(classes = ExampleApplication.class) public class ProductClientUnitTest { @Autowired diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/customizederrorhandling/controller/ProductControllerUnitTest.java b/feign/src/test/java/com/baeldung/core/customizederrorhandling/controller/ProductControllerUnitTest.java similarity index 88% rename from spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/customizederrorhandling/controller/ProductControllerUnitTest.java rename to feign/src/test/java/com/baeldung/core/customizederrorhandling/controller/ProductControllerUnitTest.java index cc9d029e07..04fd68d3e4 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/customizederrorhandling/controller/ProductControllerUnitTest.java +++ b/feign/src/test/java/com/baeldung/core/customizederrorhandling/controller/ProductControllerUnitTest.java @@ -1,10 +1,13 @@ -package com.baeldung.cloud.openfeign.customizederrorhandling.controller; +package com.baeldung.core.customizederrorhandling.controller; + +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.configureFor; +import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; +import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; +import static org.junit.Assert.assertEquals; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import com.baeldung.cloud.openfeign.customizederrorhandling.client.ProductClient; -import com.baeldung.cloud.openfeign.customizederrorhandling.exception.ErrorResponse; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.github.tomakehurst.wiremock.WireMockServer; -import com.github.tomakehurst.wiremock.client.WireMock; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -18,10 +21,11 @@ import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; -import static com.github.tomakehurst.wiremock.client.WireMock.*; -import static org.junit.Assert.assertEquals; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import com.baeldung.core.customizederrorhandling.client.ProductClient; +import com.baeldung.core.customizederrorhandling.exception.ErrorResponse; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.tomakehurst.wiremock.WireMockServer; +import com.github.tomakehurst.wiremock.client.WireMock; @RunWith(SpringRunner.class) diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/defaulterrorhandling/client/ProductClientUnitTest.java b/feign/src/test/java/com/baeldung/core/defaulterrorhandling/client/ProductClientUnitTest.java similarity index 81% rename from spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/defaulterrorhandling/client/ProductClientUnitTest.java rename to feign/src/test/java/com/baeldung/core/defaulterrorhandling/client/ProductClientUnitTest.java index 4dda2bbe15..8a9fa94074 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/defaulterrorhandling/client/ProductClientUnitTest.java +++ b/feign/src/test/java/com/baeldung/core/defaulterrorhandling/client/ProductClientUnitTest.java @@ -1,8 +1,13 @@ -package com.baeldung.cloud.openfeign.defaulterrorhandling.client; +package com.baeldung.core.defaulterrorhandling.client; + +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.configureFor; +import static com.github.tomakehurst.wiremock.client.WireMock.get; +import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; +import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; -import com.baeldung.cloud.openfeign.defaulterrorhandling.model.Product; -import com.github.tomakehurst.wiremock.WireMockServer; -import feign.FeignException; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -12,12 +17,14 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.HttpStatus; import org.springframework.test.context.junit4.SpringRunner; -import static com.github.tomakehurst.wiremock.client.WireMock.*; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThrows; +import com.baeldung.core.ExampleApplication; +import com.baeldung.core.defaulterrorhandling.model.Product; +import com.github.tomakehurst.wiremock.WireMockServer; + +import feign.FeignException; @RunWith(SpringRunner.class) -@SpringBootTest +@SpringBootTest(classes = ExampleApplication.class) public class ProductClientUnitTest { @Autowired diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/defaulterrorhandling/controller/ProductControllerUnitTest.java b/feign/src/test/java/com/baeldung/core/defaulterrorhandling/controller/ProductControllerUnitTest.java similarity index 85% rename from spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/defaulterrorhandling/controller/ProductControllerUnitTest.java rename to feign/src/test/java/com/baeldung/core/defaulterrorhandling/controller/ProductControllerUnitTest.java index f6ec7c3310..798ee9035c 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/defaulterrorhandling/controller/ProductControllerUnitTest.java +++ b/feign/src/test/java/com/baeldung/core/defaulterrorhandling/controller/ProductControllerUnitTest.java @@ -1,8 +1,13 @@ -package com.baeldung.cloud.openfeign.defaulterrorhandling.controller; +package com.baeldung.core.defaulterrorhandling.controller; + +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.configureFor; +import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; +import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; +import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import com.baeldung.cloud.openfeign.defaulterrorhandling.client.ProductClient; -import com.github.tomakehurst.wiremock.WireMockServer; -import com.github.tomakehurst.wiremock.client.WireMock; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -16,10 +21,9 @@ import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import static com.github.tomakehurst.wiremock.client.WireMock.*; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options; +import com.baeldung.core.defaulterrorhandling.client.ProductClient; +import com.github.tomakehurst.wiremock.WireMockServer; +import com.github.tomakehurst.wiremock.client.WireMock; @RunWith(SpringRunner.class) @WebMvcTest(ProductController.class) diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/defaulterrorhandling/controller/TestControllerAdvice.java b/feign/src/test/java/com/baeldung/core/defaulterrorhandling/controller/TestControllerAdvice.java similarity index 88% rename from spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/defaulterrorhandling/controller/TestControllerAdvice.java rename to feign/src/test/java/com/baeldung/core/defaulterrorhandling/controller/TestControllerAdvice.java index 0c7ed86b7c..dfd82ed07d 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/defaulterrorhandling/controller/TestControllerAdvice.java +++ b/feign/src/test/java/com/baeldung/core/defaulterrorhandling/controller/TestControllerAdvice.java @@ -1,11 +1,12 @@ -package com.baeldung.cloud.openfeign.defaulterrorhandling.controller; +package com.baeldung.core.defaulterrorhandling.controller; -import feign.FeignException; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; +import feign.FeignException; + @RestControllerAdvice public class TestControllerAdvice { diff --git a/geotools/pom.xml b/geotools/pom.xml index 6edb344c8c..f17b4cc5da 100644 --- a/geotools/pom.xml +++ b/geotools/pom.xml @@ -39,13 +39,6 @@ gt-swing ${geotools-swing.version} - - org.locationtech.jts - jts-core - 1.19.0 - - - diff --git a/guava-modules/guava-collections/pom.xml b/guava-modules/guava-collections/pom.xml index 9283107023..8dc052db75 100644 --- a/guava-modules/guava-collections/pom.xml +++ b/guava-modules/guava-collections/pom.xml @@ -37,6 +37,7 @@ ${java-hamcrest.version} test + 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/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/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..8453a38abd --- /dev/null +++ b/java-panama/pom.xml @@ -0,0 +1,49 @@ + + ${project.model.version} + + com.baeldung.java.panama + java-panama + ${project.version} + jar + + java-panama + https://maven.apache.org + + + 4.0.0 + UTF-8 + 1.0 + 19 + 19 + 3.10.1 + 5.9.0 + + + + + org.junit.jupiter + junit-jupiter + ${junit.jupiter.version} + test + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven.compiler.version} + + ${maven.compiler.source} + ${maven.compiler.target} + + --add-opens=java.base/java.lang.foreign=ALL-UNNAMED + --enable-preview + + + + + + 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/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/jaxb/pom.xml b/jaxb/pom.xml index 183f7f13cb..a7f0324bc0 100644 --- a/jaxb/pom.xml +++ b/jaxb/pom.xml @@ -25,6 +25,11 @@ commons-lang3 ${commons-lang3.version} + + org.glassfish.jaxb + jaxb-runtime + ${jaxb-runtime.version} + @@ -97,8 +102,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..18960b1d9e 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; diff --git a/jenkins-modules/jenkins-jobs/README.md b/jenkins-modules/jenkins-jobs/README.md index d29a25244f..f58761997e 100644 --- a/jenkins-modules/jenkins-jobs/README.md +++ b/jenkins-modules/jenkins-jobs/README.md @@ -3,3 +3,4 @@ - [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) 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/jersey/pom.xml b/jersey/pom.xml index 7c7330d84f..cb09247773 100644 --- a/jersey/pom.xml +++ b/jersey/pom.xml @@ -101,6 +101,7 @@ 2.38 + 3.3.2 \ No newline at end of file diff --git a/jsf/pom.xml b/jsf/pom.xml index 88099ef9c4..4e17540557 100644 --- a/jsf/pom.xml +++ b/jsf/pom.xml @@ -15,6 +15,13 @@ + + + javax.annotation + javax.annotation-api + ${javax.annotation-api.version} + + com.sun.faces @@ -70,6 +77,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/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/libraries-2/pom.xml b/libraries-2/pom.xml index ea1b2ca8b6..1d5cde75a2 100644 --- a/libraries-2/pom.xml +++ b/libraries-2/pom.xml @@ -12,22 +12,6 @@ 1.0.0-SNAPSHOT - - - jboss-public-repository-group - JBoss Public Repository Group - http://repository.jboss.org/nexus/content/groups/public/ - - true - never - - - true - daily - - - - org.mapdb @@ -82,6 +66,12 @@ edu.uci.ics crawler4j ${crawler4j.version} + + + com.sleepycat + je + + com.github.jknack @@ -119,22 +109,40 @@ spring-jdbc ${spring.version} + + com.sleepycat + je + 18.3.12 + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + --add-exports=java.base/jdk.internal.ref=ALL-UNNAMED --add-exports=java.base/sun.nio.ch=ALL-UNNAMED --add-exports=jdk.unsupported/sun.misc=ALL-UNNAMED --add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED --add-opens=jdk.compiler/com.sun.tools.javac=ALL-UNNAMED --add-opens=java.base/java.lang=ALL-UNNAMED --add-opens=java.base/java.lang.reflect=ALL-UNNAMED --add-opens=java.base/java.io=ALL-UNNAMED --add-opens=java.base/java.util=ALL-UNNAMED + + + + + - 3.0.7 - 4.8.28 - 6.0.0.Final - 3.9.6 - 3.17.2 + 3.0.8 + 4.8.153 + 7.1.0.Final + 4.7.0 + 3.24ea1 4.4.0 - 2.1.4.RELEASE - 0.28.3 + 2.7.8 + 1.11.0 1.1.0 - 4.1.2 - 6.17.0 - 5.1.9.RELEASE - 2.5.0 + 4.3.1 + 6.20.0 + 5.3.25 + 2.7.1 \ No newline at end of file diff --git a/libraries-2/src/test/java/com/baeldung/parallel_collectors/ParallelCollectorsUnitTest.java b/libraries-2/src/test/java/com/baeldung/parallel_collectors/ParallelCollectorsUnitTest.java index adc753a8ad..e1ad2f7537 100644 --- a/libraries-2/src/test/java/com/baeldung/parallel_collectors/ParallelCollectorsUnitTest.java +++ b/libraries-2/src/test/java/com/baeldung/parallel_collectors/ParallelCollectorsUnitTest.java @@ -40,7 +40,7 @@ public class ParallelCollectorsUnitTest { List ids = Arrays.asList(1, 2, 3); CompletableFuture> results = ids.stream() - .collect(parallelToList(i -> fetchById(i), executor, 4)); + .collect(parallelToList(ParallelCollectorsUnitTest::fetchById, executor, 4)); System.out.println(results.join()); } @@ -52,7 +52,7 @@ public class ParallelCollectorsUnitTest { List ids = Arrays.asList(1, 2, 3); List results = ids.stream() - .collect(parallelToList(i -> fetchById(i), executor, 4)) + .collect(parallelToList(ParallelCollectorsUnitTest::fetchById, executor, 4)) .join(); System.out.println(results); // [user-1, user-2, user-3] @@ -92,7 +92,7 @@ public class ParallelCollectorsUnitTest { List ids = Arrays.asList(1, 2, 3); ids.stream() - .collect(parallel(i -> fetchByIdWithRandomDelay(i), executor, 4)) + .collect(parallel(ParallelCollectorsUnitTest::fetchByIdWithRandomDelay, executor, 4)) .forEach(System.out::println); } @@ -103,7 +103,7 @@ public class ParallelCollectorsUnitTest { List ids = Arrays.asList(1, 2, 3); ids.stream() - .collect(parallelOrdered(i -> fetchByIdWithRandomDelay(i), executor, 4)) + .collect(parallelOrdered(ParallelCollectorsUnitTest::fetchByIdWithRandomDelay, executor, 4)) .forEach(System.out::println); } @@ -114,7 +114,7 @@ public class ParallelCollectorsUnitTest { List ids = Arrays.asList(1, 2, 3); Map results = ids.stream() - .collect(parallelToMap(i -> i, i -> fetchById(i), executor, 4)) + .collect(parallelToMap(i -> i, ParallelCollectorsUnitTest::fetchById, executor, 4)) .join(); System.out.println(results); // {1=user-1, 2=user-2, 3=user-3} @@ -127,7 +127,7 @@ public class ParallelCollectorsUnitTest { List ids = Arrays.asList(1, 2, 3); Map results = ids.stream() - .collect(parallelToMap(i -> i, i -> fetchById(i), TreeMap::new, executor, 4)) + .collect(parallelToMap(i -> i, ParallelCollectorsUnitTest::fetchById, TreeMap::new, executor, 4)) .join(); System.out.println(results); // {1=user-1, 2=user-2, 3=user-3} @@ -140,7 +140,7 @@ public class ParallelCollectorsUnitTest { List ids = Arrays.asList(1, 2, 3); Map results = ids.stream() - .collect(parallelToMap(i -> i, i -> fetchById(i), TreeMap::new, (s1, s2) -> s1, executor, 4)) + .collect(parallelToMap(i -> i, ParallelCollectorsUnitTest::fetchById, TreeMap::new, (s1, s2) -> s1, executor, 4)) .join(); System.out.println(results); // {1=user-1, 2=user-2, 3=user-3} diff --git a/libraries-apache-commons-io/pom.xml b/libraries-apache-commons-io/pom.xml index b45572ddad..7cac50a8e2 100644 --- a/libraries-apache-commons-io/pom.xml +++ b/libraries-apache-commons-io/pom.xml @@ -26,7 +26,7 @@ - 1.9.0 + 1.10.0 \ No newline at end of file diff --git a/libraries-apache-commons-io/src/test/java/com/baeldung/commons/io/csv/CSVReaderWriterUnitTest.java b/libraries-apache-commons-io/src/test/java/com/baeldung/commons/io/csv/CSVReaderWriterUnitTest.java index b99f4e8bc3..b37613e962 100644 --- a/libraries-apache-commons-io/src/test/java/com/baeldung/commons/io/csv/CSVReaderWriterUnitTest.java +++ b/libraries-apache-commons-io/src/test/java/com/baeldung/commons/io/csv/CSVReaderWriterUnitTest.java @@ -1,9 +1,11 @@ package com.baeldung.commons.io.csv; +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVPrinter; import org.apache.commons.csv.CSVRecord; -import org.junit.Test; import java.io.FileReader; import java.io.IOException; @@ -13,9 +15,7 @@ import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; -import static org.junit.Assert.assertEquals; - -public class CSVReaderWriterUnitTest { +class CSVReaderWriterUnitTest { public static final Map AUTHOR_BOOK_MAP = Collections.unmodifiableMap(new LinkedHashMap() { { @@ -24,12 +24,24 @@ public class CSVReaderWriterUnitTest { } }); public static final String[] HEADERS = { "author", "title" }; + + enum BookHeaders{ + author, title + } + public static final String EXPECTED_FILESTREAM = "author,title\r\n" + "Dan Simmons,Hyperion\r\n" + "Douglas Adams,The Hitchhiker's Guide to the Galaxy"; @Test - public void givenCSVFile_whenRead_thenContentsAsExpected() throws IOException { + void givenCSVFile_whenReadWithArrayHeader_thenContentsAsExpected() throws IOException { Reader in = new FileReader("src/test/resources/book.csv"); - Iterable records = CSVFormat.DEFAULT.withHeader(HEADERS).withFirstRecordAsHeader().parse(in); + + CSVFormat csvFormat = CSVFormat.DEFAULT.builder() + .setHeader(HEADERS) + .setSkipHeaderRecord(true) + .build(); + + Iterable records = csvFormat.parse(in); + for (CSVRecord record : records) { String author = record.get("author"); String title = record.get("title"); @@ -38,9 +50,32 @@ public class CSVReaderWriterUnitTest { } @Test - public void givenAuthorBookMap_whenWrittenToStream_thenOutputStreamAsExpected() throws IOException { + void givenCSVFile_whenReadWithEnumHeader_thenContentsAsExpected() throws IOException { + Reader in = new FileReader("src/test/resources/book.csv"); + + CSVFormat csvFormat = CSVFormat.DEFAULT.builder() + .setHeader(BookHeaders.class) + .setSkipHeaderRecord(true) + .build(); + + Iterable records = csvFormat.parse(in); + + for (CSVRecord record : records) { + String author = record.get(BookHeaders.author); + String title = record.get(BookHeaders.title); + assertEquals(AUTHOR_BOOK_MAP.get(author), title); + } + } + + @Test + void givenAuthorBookMap_whenWrittenToStream_thenOutputStreamAsExpected() throws IOException { StringWriter sw = new StringWriter(); - try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withHeader(HEADERS))) { + + CSVFormat csvFormat = CSVFormat.DEFAULT.builder() + .setHeader(BookHeaders.class) + .build(); + + try (final CSVPrinter printer = new CSVPrinter(sw, csvFormat)) { AUTHOR_BOOK_MAP.forEach((author, title) -> { try { printer.printRecord(author, title); @@ -49,7 +84,8 @@ public class CSVReaderWriterUnitTest { } }); } - assertEquals(EXPECTED_FILESTREAM, sw.toString().trim()); + assertEquals(EXPECTED_FILESTREAM, sw.toString() + .trim()); } } diff --git a/libraries-data-2/pom.xml b/libraries-data-2/pom.xml index d5322267d0..f673ebd470 100644 --- a/libraries-data-2/pom.xml +++ b/libraries-data-2/pom.xml @@ -15,12 +15,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} @@ -47,7 +47,7 @@ org.apache.flink - flink-test-utils_2.11 + flink-test-utils ${flink.version} test @@ -136,6 +136,21 @@ + + + + org.apache.maven.plugins + maven-surefire-plugin + + + --add-opens java.base/java.lang=ALL-UNNAMED + --add-opens java.base/java.util=ALL-UNNAMED + + + + + + nm-repo @@ -146,12 +161,12 @@ - 1.5.0 + 1.16.1 1.6.0 0.1.0 1.0.3 - 9.1.5.Final - 4.3.8.RELEASE + 14.0.6.Final + 5.3.25 4.0.0 1.1.0 3.0.0 diff --git a/libraries-data-io/pom.xml b/libraries-data-io/pom.xml index 640bf1ba07..2e126610d4 100644 --- a/libraries-data-io/pom.xml +++ b/libraries-data-io/pom.xml @@ -46,9 +46,9 @@ ${google-sheets.version} - javax.xml.bind - jaxb-api - ${jaxb-api.version} + org.glassfish.jaxb + jaxb-runtime + ${jaxb-runtime.version} org.docx4j @@ -104,8 +104,8 @@ 4.1 1.23.0 v4-rev493-1.21.0 - 3.3.5 - 2.1 + 6.1.2 + 2.3.1 2.8.7 1.15 0.14.2 diff --git a/libraries-data/pom.xml b/libraries-data/pom.xml index 85edf8b69a..6ba48a9d66 100644 --- a/libraries-data/pom.xml +++ b/libraries-data/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 libraries-data libraries-data @@ -34,7 +34,7 @@ org.apache.ignite ignite-spring-data - ${ignite.version} + ${ignite-spring-data.version} com.google.code.gson @@ -58,6 +58,11 @@ crunch-core ${org.apache.crunch.crunch-core.version} + + org.javassist + javassist + ${javassist.version} + org.apache.hadoop hadoop-client @@ -133,11 +138,42 @@ com.googlecode.jmapper-framework jmapper-core ${jmapper.version} + + + com.thoughtworks.xstream + xstream + + + + com.thoughtworks.xstream + xstream + 1.4.16 + + + + org.apache.maven.plugins + maven-surefire-plugin + + + --add-opens java.base/java.lang=ALL-UNNAMED + --add-opens jdk.management/com.sun.management.internal=ALL-UNNAMED + --add-opens java.base/jdk.internal.misc=ALL-UNNAMED + --add-opens java.base/sun.nio.ch=ALL-UNNAMED + --add-opens java.management/com.sun.jmx.mbeanserver=ALL-UNNAMED + --add-opens jdk.internal.jvmstat/sun.jvmstat.monitor=ALL-UNNAMED + --add-opens java.base/sun.reflect.generics.reflectiveObjects=ALL-UNNAMED + --add-opens java.base/java.io=ALL-UNNAMED + --add-opens java.base/java.nio=ALL-UNNAMED + --add-opens java.base/java.util=ALL-UNNAMED + --add-opens java.base/java.lang=ALL-UNNAMED + + + org.apache.maven.plugins maven-assembly-plugin @@ -166,11 +202,14 @@ + 11 + 11 2.3 3.1 1.2.2 3.3.1 - 2.4.0 + 2.14.0 + 2.9.1 2.9.1 1.1.1 1.5.0 @@ -178,6 +217,7 @@ 1.0.0 2.2.0 1.6.0.1 + 3.29.2-GA \ No newline at end of file diff --git a/libraries-data/src/test/java/com/baeldung/crunch/StopWordFilterUnitTest.java b/libraries-data/src/test/java/com/baeldung/crunch/StopWordFilterUnitTest.java index fffefc2bfb..0bb03016d8 100644 --- a/libraries-data/src/test/java/com/baeldung/crunch/StopWordFilterUnitTest.java +++ b/libraries-data/src/test/java/com/baeldung/crunch/StopWordFilterUnitTest.java @@ -7,6 +7,7 @@ import static org.junit.Assert.assertTrue; import org.apache.crunch.FilterFn; import org.apache.crunch.PCollection; import org.apache.crunch.impl.mem.MemPipeline; +import org.junit.Ignore; import org.junit.Test; import com.google.common.collect.ImmutableList; diff --git a/libraries-data/src/test/java/com/baeldung/crunch/ToUpperCaseWithCounterFnUnitTest.java b/libraries-data/src/test/java/com/baeldung/crunch/ToUpperCaseWithCounterFnUnitTest.java index 76294d273d..00c508e605 100644 --- a/libraries-data/src/test/java/com/baeldung/crunch/ToUpperCaseWithCounterFnUnitTest.java +++ b/libraries-data/src/test/java/com/baeldung/crunch/ToUpperCaseWithCounterFnUnitTest.java @@ -6,6 +6,7 @@ import org.apache.crunch.PCollection; import org.apache.crunch.impl.mem.MemPipeline; import org.apache.crunch.types.writable.Writables; import org.junit.Before; +import org.junit.Ignore; import org.junit.Test; import com.google.common.collect.ImmutableList; diff --git a/libraries-security/pom.xml b/libraries-security/pom.xml index 6d3bbcd26c..62c476a82c 100644 --- a/libraries-security/pom.xml +++ b/libraries-security/pom.xml @@ -96,8 +96,26 @@ + + org.glassfish.jaxb + jaxb-runtime + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + --add-opens java.base/java.lang=ALL-UNNAMED + + + + + + 5.6.0 1.3.1 diff --git a/libraries-server-2/pom.xml b/libraries-server-2/pom.xml index 7377fa3fa9..cf5d016d9f 100644 --- a/libraries-server-2/pom.xml +++ b/libraries-server-2/pom.xml @@ -73,6 +73,7 @@ 9.4.27.v20200227 8.1.11.v20170118 + 3.2.2 \ No newline at end of file diff --git a/libraries-testing/pom.xml b/libraries-testing/pom.xml index 2aaad59e09..9274c292ba 100644 --- a/libraries-testing/pom.xml +++ b/libraries-testing/pom.xml @@ -179,17 +179,16 @@ 1.9.9 1.9.0 1.9.0 - 1.9.27 + 3.6.12 1.5.0 3.0.0 0.8.1 4.3.8.RELEASE - 4.1.1 + 5.3.0 2.0.0.0 2.7.0 0.14.1 1.0.0 - 2.1.214 \ No newline at end of file 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..eaf7a73552 100644 --- a/maven-modules/pom.xml +++ b/maven-modules/pom.xml @@ -42,6 +42,7 @@ maven-simple maven-classifier maven-repositories + maven-reactor diff --git a/messaging-modules/pom.xml b/messaging-modules/pom.xml index f843b0fe11..8bda46f5cd 100644 --- a/messaging-modules/pom.xml +++ b/messaging-modules/pom.xml @@ -18,7 +18,6 @@ jgroups rabbitmq spring-amqp - spring-apache-camel spring-jms diff --git a/messaging-modules/spring-apache-camel/.gitignore b/messaging-modules/spring-apache-camel/.gitignore index eac473ac50..f137d908d6 100644 --- a/messaging-modules/spring-apache-camel/.gitignore +++ b/messaging-modules/spring-apache-camel/.gitignore @@ -1 +1,2 @@ -/src/test/destination-folder/* \ No newline at end of file +/src/test/destination-folder/* +/output/ \ No newline at end of file diff --git a/messaging-modules/spring-apache-camel/README.md b/messaging-modules/spring-apache-camel/README.md index 6a16e1da05..535c61cbef 100644 --- a/messaging-modules/spring-apache-camel/README.md +++ b/messaging-modules/spring-apache-camel/README.md @@ -4,17 +4,19 @@ This module contains articles about Spring with Apache Camel ### Relevant Articles -- [Apache Camel](http://camel.apache.org/) -- [Enterprise Integration Patterns](http://www.enterpriseintegrationpatterns.com/patterns/messaging/toc.html) - [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) +- [Apache Camel Exception Handling](https://www.baeldung.com/java-apache-camel-exception-handling) ### Framework Versions: -- Spring 4.2.4 -- Apache Camel 2.16.1 +- Spring 5.3.25 +- Apache Camel 3.14.7 ### Build and Run Application diff --git a/messaging-modules/spring-apache-camel/pom.xml b/messaging-modules/spring-apache-camel/pom.xml index 9f2e74dc36..ec7557666c 100644 --- a/messaging-modules/spring-apache-camel/pom.xml +++ b/messaging-modules/spring-apache-camel/pom.xml @@ -58,11 +58,67 @@ ${env.camel.version} test + + org.apache.camel.springboot + camel-servlet-starter + ${camel.version} + + + org.apache.camel.springboot + camel-jackson-starter + ${camel.version} + + + org.apache.camel.springboot + camel-swagger-java-starter + ${camel.version} + + + org.apache.camel.springboot + camel-spring-boot-starter + ${camel.version} + + + org.springframework.boot + spring-boot-starter-web + + + org.apache.camel + camel-test-spring-junit5 + ${camel.version} + test + - 2.18.1 - 4.3.4.RELEASE + 3.14.7 + 5.3.25 + 3.15.0 + + + spring-boot + + spring-boot:run + + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + com.baeldung.camel.boot.boot.testing.GreetingsFileSpringApplication + + + + + + + + + \ No newline at end of file diff --git a/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/file/ContentBasedFileRouter.java b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/file/ContentBasedFileRouter.java similarity index 94% rename from messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/file/ContentBasedFileRouter.java rename to messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/file/ContentBasedFileRouter.java index 9106e996c3..2a3f7e5c7b 100644 --- a/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/file/ContentBasedFileRouter.java +++ b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/file/ContentBasedFileRouter.java @@ -1,4 +1,4 @@ -package com.baeldung.camel.file; +package com.baeldung.camel.apache.file; import org.apache.camel.builder.RouteBuilder; diff --git a/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/file/DeadLetterChannelFileRouter.java b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/file/DeadLetterChannelFileRouter.java similarity index 94% rename from messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/file/DeadLetterChannelFileRouter.java rename to messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/file/DeadLetterChannelFileRouter.java index fdcad99f02..37a81af458 100644 --- a/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/file/DeadLetterChannelFileRouter.java +++ b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/file/DeadLetterChannelFileRouter.java @@ -1,4 +1,4 @@ -package com.baeldung.camel.file; +package com.baeldung.camel.apache.file; import org.apache.camel.LoggingLevel; import org.apache.camel.builder.RouteBuilder; diff --git a/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/file/FileProcessor.java b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/file/FileProcessor.java similarity index 93% rename from messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/file/FileProcessor.java rename to messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/file/FileProcessor.java index 1ea2cad188..ce4d92e8ab 100644 --- a/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/file/FileProcessor.java +++ b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/file/FileProcessor.java @@ -1,4 +1,4 @@ -package com.baeldung.camel.file; +package com.baeldung.camel.apache.file; import java.text.SimpleDateFormat; import java.util.Date; diff --git a/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/file/FileRouter.java b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/file/FileRouter.java similarity index 91% rename from messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/file/FileRouter.java rename to messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/file/FileRouter.java index 5216c9a595..760f37677b 100644 --- a/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/file/FileRouter.java +++ b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/file/FileRouter.java @@ -1,4 +1,4 @@ -package com.baeldung.camel.file; +package com.baeldung.camel.apache.file; import org.apache.camel.builder.RouteBuilder; diff --git a/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/file/MessageTranslatorFileRouter.java b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/file/MessageTranslatorFileRouter.java similarity index 92% rename from messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/file/MessageTranslatorFileRouter.java rename to messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/file/MessageTranslatorFileRouter.java index b99de99dac..5e65c24c40 100644 --- a/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/file/MessageTranslatorFileRouter.java +++ b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/file/MessageTranslatorFileRouter.java @@ -1,4 +1,4 @@ -package com.baeldung.camel.file; +package com.baeldung.camel.apache.file; import org.apache.camel.Exchange; import org.apache.camel.builder.RouteBuilder; diff --git a/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/file/MulticastFileRouter.java b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/file/MulticastFileRouter.java similarity index 95% rename from messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/file/MulticastFileRouter.java rename to messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/file/MulticastFileRouter.java index 75a6e81d45..6f6aad177d 100644 --- a/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/file/MulticastFileRouter.java +++ b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/file/MulticastFileRouter.java @@ -1,4 +1,4 @@ -package com.baeldung.camel.file; +package com.baeldung.camel.apache.file; import org.apache.camel.builder.RouteBuilder; diff --git a/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/file/SplitterFileRouter.java b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/file/SplitterFileRouter.java similarity index 93% rename from messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/file/SplitterFileRouter.java rename to messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/file/SplitterFileRouter.java index 551f9c9685..471dfa7a46 100644 --- a/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/file/SplitterFileRouter.java +++ b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/file/SplitterFileRouter.java @@ -1,4 +1,4 @@ -package com.baeldung.camel.file; +package com.baeldung.camel.apache.file; import org.apache.camel.Exchange; import org.apache.camel.builder.RouteBuilder; diff --git a/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/file/cfg/ContentBasedFileRouterConfig.java b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/file/cfg/ContentBasedFileRouterConfig.java similarity index 84% rename from messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/file/cfg/ContentBasedFileRouterConfig.java rename to messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/file/cfg/ContentBasedFileRouterConfig.java index ceb68dfa3b..2b24cf2a51 100644 --- a/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/file/cfg/ContentBasedFileRouterConfig.java +++ b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/file/cfg/ContentBasedFileRouterConfig.java @@ -1,4 +1,4 @@ -package com.baeldung.camel.file.cfg; +package com.baeldung.camel.apache.file.cfg; import java.util.Arrays; import java.util.List; @@ -8,7 +8,7 @@ import org.apache.camel.spring.javaconfig.CamelConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import com.baeldung.camel.file.ContentBasedFileRouter; +import com.baeldung.camel.apache.file.ContentBasedFileRouter; @Configuration public class ContentBasedFileRouterConfig extends CamelConfiguration { diff --git a/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/jackson/Fruit.java b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/jackson/Fruit.java similarity index 87% rename from messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/jackson/Fruit.java rename to messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/jackson/Fruit.java index 1932131ddd..d46eb0afd5 100644 --- a/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/jackson/Fruit.java +++ b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/jackson/Fruit.java @@ -1,4 +1,4 @@ -package com.baeldung.camel.jackson; +package com.baeldung.camel.apache.jackson; public class Fruit { diff --git a/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/jackson/FruitList.java b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/jackson/FruitList.java similarity index 84% rename from messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/jackson/FruitList.java rename to messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/jackson/FruitList.java index 02f2b6feb0..f8678c6a1e 100644 --- a/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/jackson/FruitList.java +++ b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/jackson/FruitList.java @@ -1,4 +1,4 @@ -package com.baeldung.camel.jackson; +package com.baeldung.camel.apache.jackson; import java.util.List; diff --git a/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/main/App.java b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/main/App.java similarity index 91% rename from messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/main/App.java rename to messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/main/App.java index ac0605a215..6071db0580 100644 --- a/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/main/App.java +++ b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/main/App.java @@ -1,4 +1,4 @@ -package com.baeldung.camel.main; +package com.baeldung.camel.apache.main; import org.springframework.context.support.ClassPathXmlApplicationContext; diff --git a/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/processor/FileProcessor.java b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/processor/FileProcessor.java similarity index 89% rename from messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/processor/FileProcessor.java rename to messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/processor/FileProcessor.java index 971dd206cd..5ca61a382a 100644 --- a/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/processor/FileProcessor.java +++ b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/processor/FileProcessor.java @@ -1,4 +1,4 @@ -package com.baeldung.camel.processor; +package com.baeldung.camel.apache.processor; import org.apache.camel.Exchange; import org.apache.camel.Processor; diff --git a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/Application.java b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/Application.java similarity index 97% rename from spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/Application.java rename to messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/Application.java index 48294e9c56..797ad57202 100644 --- a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/Application.java +++ b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/Application.java @@ -1,4 +1,4 @@ -package com.baeldung.camel; +package com.baeldung.camel.boot; import javax.ws.rs.core.MediaType; @@ -22,7 +22,7 @@ import org.springframework.context.annotation.ComponentScan; import org.springframework.stereotype.Component; @SpringBootApplication(exclude = { WebSocketServletAutoConfiguration.class, AopAutoConfiguration.class, OAuth2ResourceServerAutoConfiguration.class, EmbeddedWebServerFactoryCustomizerAutoConfiguration.class }) -@ComponentScan(basePackages = "com.baeldung.camel") +@ComponentScan(basePackages = "com.baeldung.camel.boot") public class Application { @Value("${server.port}") diff --git a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/ExampleServices.java b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/ExampleServices.java similarity index 90% rename from spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/ExampleServices.java rename to messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/ExampleServices.java index ec8f368e68..6fe5a1ed32 100644 --- a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/ExampleServices.java +++ b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/ExampleServices.java @@ -1,4 +1,4 @@ -package com.baeldung.camel; +package com.baeldung.camel.boot; /** * a Mock class to show how some other layer diff --git a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/MyBean.java b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/MyBean.java similarity index 90% rename from spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/MyBean.java rename to messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/MyBean.java index 5368e40c93..759fb06459 100644 --- a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/MyBean.java +++ b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/MyBean.java @@ -1,4 +1,4 @@ -package com.baeldung.camel; +package com.baeldung.camel.boot; public class MyBean { private Integer id; diff --git a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/boot/testing/GreetingsFileRouter.java b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/boot/testing/GreetingsFileRouter.java similarity index 89% rename from spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/boot/testing/GreetingsFileRouter.java rename to messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/boot/testing/GreetingsFileRouter.java index 670af5e08c..381a0a61a5 100644 --- a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/boot/testing/GreetingsFileRouter.java +++ b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/boot/testing/GreetingsFileRouter.java @@ -1,4 +1,4 @@ -package com.baeldung.camel.boot.testing; +package com.baeldung.camel.boot.boot.testing; import org.apache.camel.builder.RouteBuilder; import org.springframework.stereotype.Component; diff --git a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/boot/testing/GreetingsFileSpringApplication.java b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/boot/testing/GreetingsFileSpringApplication.java similarity index 87% rename from spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/boot/testing/GreetingsFileSpringApplication.java rename to messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/boot/testing/GreetingsFileSpringApplication.java index a4e862e65d..1d20d1977a 100644 --- a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/boot/testing/GreetingsFileSpringApplication.java +++ b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/boot/testing/GreetingsFileSpringApplication.java @@ -1,4 +1,4 @@ -package com.baeldung.camel.boot.testing; +package com.baeldung.camel.boot.boot.testing; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/conditional/ConditionalBeanRouter.java b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/conditional/ConditionalBeanRouter.java similarity index 93% rename from spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/conditional/ConditionalBeanRouter.java rename to messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/conditional/ConditionalBeanRouter.java index 8a03f6ef18..a747ba1f66 100644 --- a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/conditional/ConditionalBeanRouter.java +++ b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/conditional/ConditionalBeanRouter.java @@ -1,4 +1,4 @@ -package com.baeldung.camel.conditional; +package com.baeldung.camel.boot.conditional; import org.apache.camel.builder.RouteBuilder; import org.springframework.stereotype.Component; diff --git a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/conditional/ConditionalBodyRouter.java b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/conditional/ConditionalBodyRouter.java similarity index 93% rename from spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/conditional/ConditionalBodyRouter.java rename to messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/conditional/ConditionalBodyRouter.java index 99d23c747b..ea4f77cb9a 100644 --- a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/conditional/ConditionalBodyRouter.java +++ b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/conditional/ConditionalBodyRouter.java @@ -1,4 +1,4 @@ -package com.baeldung.camel.conditional; +package com.baeldung.camel.boot.conditional; import org.apache.camel.builder.RouteBuilder; import org.springframework.stereotype.Component; diff --git a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/conditional/ConditionalHeaderRouter.java b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/conditional/ConditionalHeaderRouter.java similarity index 93% rename from spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/conditional/ConditionalHeaderRouter.java rename to messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/conditional/ConditionalHeaderRouter.java index e723f97ef1..93371b06b6 100644 --- a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/conditional/ConditionalHeaderRouter.java +++ b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/conditional/ConditionalHeaderRouter.java @@ -1,4 +1,4 @@ -package com.baeldung.camel.conditional; +package com.baeldung.camel.boot.conditional; import org.apache.camel.builder.RouteBuilder; import org.springframework.stereotype.Component; diff --git a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/conditional/ConditionalRoutingSpringApplication.java b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/conditional/ConditionalRoutingSpringApplication.java similarity index 88% rename from spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/conditional/ConditionalRoutingSpringApplication.java rename to messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/conditional/ConditionalRoutingSpringApplication.java index f20d23068a..f11b4302c7 100644 --- a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/conditional/ConditionalRoutingSpringApplication.java +++ b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/conditional/ConditionalRoutingSpringApplication.java @@ -1,4 +1,4 @@ -package com.baeldung.camel.conditional; +package com.baeldung.camel.boot.conditional; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/conditional/FruitBean.java b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/conditional/FruitBean.java similarity index 84% rename from spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/conditional/FruitBean.java rename to messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/conditional/FruitBean.java index 080e3393b6..a3481361bd 100644 --- a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/conditional/FruitBean.java +++ b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/conditional/FruitBean.java @@ -1,4 +1,4 @@ -package com.baeldung.camel.conditional; +package com.baeldung.camel.boot.conditional; import org.apache.camel.Exchange; diff --git a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/exception/ExceptionHandlingSpringApplication.java b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/exception/ExceptionHandlingSpringApplication.java similarity index 88% rename from spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/exception/ExceptionHandlingSpringApplication.java rename to messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/exception/ExceptionHandlingSpringApplication.java index df4550d9d5..bfa08a5c7a 100644 --- a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/exception/ExceptionHandlingSpringApplication.java +++ b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/exception/ExceptionHandlingSpringApplication.java @@ -1,4 +1,4 @@ -package com.baeldung.camel.exception; +package com.baeldung.camel.boot.exception; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/exception/ExceptionHandlingWithDoTryRoute.java b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/exception/ExceptionHandlingWithDoTryRoute.java similarity index 94% rename from spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/exception/ExceptionHandlingWithDoTryRoute.java rename to messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/exception/ExceptionHandlingWithDoTryRoute.java index ce3cfc129b..d4c365d25c 100644 --- a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/exception/ExceptionHandlingWithDoTryRoute.java +++ b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/exception/ExceptionHandlingWithDoTryRoute.java @@ -1,4 +1,4 @@ -package com.baeldung.camel.exception; +package com.baeldung.camel.boot.exception; import java.io.IOException; diff --git a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/exception/ExceptionHandlingWithExceptionClauseRoute.java b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/exception/ExceptionHandlingWithExceptionClauseRoute.java similarity index 94% rename from spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/exception/ExceptionHandlingWithExceptionClauseRoute.java rename to messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/exception/ExceptionHandlingWithExceptionClauseRoute.java index 3a438e2402..e2ee3252de 100644 --- a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/exception/ExceptionHandlingWithExceptionClauseRoute.java +++ b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/exception/ExceptionHandlingWithExceptionClauseRoute.java @@ -1,4 +1,4 @@ -package com.baeldung.camel.exception; +package com.baeldung.camel.boot.exception; import org.apache.camel.builder.RouteBuilder; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/exception/ExceptionLoggingProcessor.java b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/exception/ExceptionLoggingProcessor.java similarity index 94% rename from spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/exception/ExceptionLoggingProcessor.java rename to messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/exception/ExceptionLoggingProcessor.java index 84e4072888..66add64441 100644 --- a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/exception/ExceptionLoggingProcessor.java +++ b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/exception/ExceptionLoggingProcessor.java @@ -1,4 +1,4 @@ -package com.baeldung.camel.exception; +package com.baeldung.camel.boot.exception; import java.util.Map; diff --git a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/exception/ExceptionThrowingRoute.java b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/exception/ExceptionThrowingRoute.java similarity index 95% rename from spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/exception/ExceptionThrowingRoute.java rename to messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/exception/ExceptionThrowingRoute.java index 752aabaf1a..bf4d464c23 100644 --- a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/exception/ExceptionThrowingRoute.java +++ b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/exception/ExceptionThrowingRoute.java @@ -1,4 +1,4 @@ -package com.baeldung.camel.exception; +package com.baeldung.camel.boot.exception; import org.apache.camel.Exchange; import org.apache.camel.Processor; diff --git a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/exception/IllegalArgumentExceptionThrowingProcessor.java b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/exception/IllegalArgumentExceptionThrowingProcessor.java similarity index 93% rename from spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/exception/IllegalArgumentExceptionThrowingProcessor.java rename to messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/exception/IllegalArgumentExceptionThrowingProcessor.java index 461a4e6553..db229418d2 100644 --- a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/exception/IllegalArgumentExceptionThrowingProcessor.java +++ b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/exception/IllegalArgumentExceptionThrowingProcessor.java @@ -1,4 +1,4 @@ -package com.baeldung.camel.exception; +package com.baeldung.camel.boot.exception; import org.apache.camel.Exchange; import org.apache.camel.Processor; diff --git a/spring-boot-modules/spring-boot-camel/src/main/resources/application.properties b/messaging-modules/spring-apache-camel/src/main/resources/application.properties similarity index 100% rename from spring-boot-modules/spring-boot-camel/src/main/resources/application.properties rename to messaging-modules/spring-apache-camel/src/main/resources/application.properties diff --git a/spring-boot-modules/spring-boot-camel/src/main/resources/application.yml b/messaging-modules/spring-apache-camel/src/main/resources/application.yml similarity index 100% rename from spring-boot-modules/spring-boot-camel/src/main/resources/application.yml rename to messaging-modules/spring-apache-camel/src/main/resources/application.yml diff --git a/messaging-modules/spring-apache-camel/src/main/resources/camel-context-ContentBasedFileRouterTest.xml b/messaging-modules/spring-apache-camel/src/main/resources/camel-context-ContentBasedFileRouterTest.xml index d6d3e62f1c..e93b9fb144 100644 --- a/messaging-modules/spring-apache-camel/src/main/resources/camel-context-ContentBasedFileRouterTest.xml +++ b/messaging-modules/spring-apache-camel/src/main/resources/camel-context-ContentBasedFileRouterTest.xml @@ -4,7 +4,7 @@ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd"> - + diff --git a/messaging-modules/spring-apache-camel/src/main/resources/camel-context-DeadLetterChannelFileRouter.xml b/messaging-modules/spring-apache-camel/src/main/resources/camel-context-DeadLetterChannelFileRouter.xml index ef61174b32..b9db0a189f 100644 --- a/messaging-modules/spring-apache-camel/src/main/resources/camel-context-DeadLetterChannelFileRouter.xml +++ b/messaging-modules/spring-apache-camel/src/main/resources/camel-context-DeadLetterChannelFileRouter.xml @@ -4,7 +4,7 @@ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd"> - + diff --git a/messaging-modules/spring-apache-camel/src/main/resources/camel-context-MessageTranslatorFileRouterTest.xml b/messaging-modules/spring-apache-camel/src/main/resources/camel-context-MessageTranslatorFileRouterTest.xml index 7ab988ca8a..fcb9e2b8be 100644 --- a/messaging-modules/spring-apache-camel/src/main/resources/camel-context-MessageTranslatorFileRouterTest.xml +++ b/messaging-modules/spring-apache-camel/src/main/resources/camel-context-MessageTranslatorFileRouterTest.xml @@ -4,7 +4,7 @@ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd"> - + diff --git a/messaging-modules/spring-apache-camel/src/main/resources/camel-context-MulticastFileRouterTest.xml b/messaging-modules/spring-apache-camel/src/main/resources/camel-context-MulticastFileRouterTest.xml index 6f7e7cbb60..73adecbc98 100644 --- a/messaging-modules/spring-apache-camel/src/main/resources/camel-context-MulticastFileRouterTest.xml +++ b/messaging-modules/spring-apache-camel/src/main/resources/camel-context-MulticastFileRouterTest.xml @@ -4,7 +4,7 @@ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd"> - + diff --git a/messaging-modules/spring-apache-camel/src/main/resources/camel-context-SplitterFileRouter.xml b/messaging-modules/spring-apache-camel/src/main/resources/camel-context-SplitterFileRouter.xml index 9d4a890cc6..a2ebe76e63 100644 --- a/messaging-modules/spring-apache-camel/src/main/resources/camel-context-SplitterFileRouter.xml +++ b/messaging-modules/spring-apache-camel/src/main/resources/camel-context-SplitterFileRouter.xml @@ -4,7 +4,7 @@ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd"> - + diff --git a/messaging-modules/spring-apache-camel/src/main/resources/camel-context-test.xml b/messaging-modules/spring-apache-camel/src/main/resources/camel-context-test.xml index e6435db9e5..f306574868 100644 --- a/messaging-modules/spring-apache-camel/src/main/resources/camel-context-test.xml +++ b/messaging-modules/spring-apache-camel/src/main/resources/camel-context-test.xml @@ -4,8 +4,8 @@ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd"> - - + + diff --git a/messaging-modules/spring-apache-camel/src/main/resources/camel-context.xml b/messaging-modules/spring-apache-camel/src/main/resources/camel-context.xml index 63ef406fdf..721ccab95c 100644 --- a/messaging-modules/spring-apache-camel/src/main/resources/camel-context.xml +++ b/messaging-modules/spring-apache-camel/src/main/resources/camel-context.xml @@ -35,5 +35,5 @@ - + \ No newline at end of file diff --git a/messaging-modules/spring-apache-camel/src/test/java/com/baeldung/SpringContextTest.java b/messaging-modules/spring-apache-camel/src/test/java/com/apache/baeldung/SpringContextTest.java similarity index 67% rename from messaging-modules/spring-apache-camel/src/test/java/com/baeldung/SpringContextTest.java rename to messaging-modules/spring-apache-camel/src/test/java/com/apache/baeldung/SpringContextTest.java index 14e7de2095..56969da1d7 100644 --- a/messaging-modules/spring-apache-camel/src/test/java/com/baeldung/SpringContextTest.java +++ b/messaging-modules/spring-apache-camel/src/test/java/com/apache/baeldung/SpringContextTest.java @@ -1,8 +1,8 @@ -package com.baeldung; +package com.apache.baeldung; import org.junit.Test; -import com.baeldung.camel.main.App; +import com.baeldung.camel.apache.main.App; public class SpringContextTest { diff --git a/messaging-modules/spring-apache-camel/src/test/java/com/baeldung/camel/jackson/FruitArrayJacksonUnmarshalUnitTest.java b/messaging-modules/spring-apache-camel/src/test/java/com/apache/baeldung/camel/jackson/FruitArrayJacksonUnmarshalUnitTest.java similarity index 95% rename from messaging-modules/spring-apache-camel/src/test/java/com/baeldung/camel/jackson/FruitArrayJacksonUnmarshalUnitTest.java rename to messaging-modules/spring-apache-camel/src/test/java/com/apache/baeldung/camel/jackson/FruitArrayJacksonUnmarshalUnitTest.java index 4810d7370e..bc0025b263 100644 --- a/messaging-modules/spring-apache-camel/src/test/java/com/baeldung/camel/jackson/FruitArrayJacksonUnmarshalUnitTest.java +++ b/messaging-modules/spring-apache-camel/src/test/java/com/apache/baeldung/camel/jackson/FruitArrayJacksonUnmarshalUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.camel.jackson; +package com.apache.baeldung.camel.jackson; import java.io.IOException; import java.net.URISyntaxException; @@ -13,6 +13,8 @@ import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.test.junit4.CamelTestSupport; import org.junit.Test; +import com.baeldung.camel.apache.jackson.Fruit; + public class FruitArrayJacksonUnmarshalUnitTest extends CamelTestSupport { @Test diff --git a/messaging-modules/spring-apache-camel/src/test/java/com/baeldung/camel/jackson/FruitListJacksonUnmarshalUnitTest.java b/messaging-modules/spring-apache-camel/src/test/java/com/apache/baeldung/camel/jackson/FruitListJacksonUnmarshalUnitTest.java similarity index 93% rename from messaging-modules/spring-apache-camel/src/test/java/com/baeldung/camel/jackson/FruitListJacksonUnmarshalUnitTest.java rename to messaging-modules/spring-apache-camel/src/test/java/com/apache/baeldung/camel/jackson/FruitListJacksonUnmarshalUnitTest.java index b5647f02f9..2d15ebf46b 100644 --- a/messaging-modules/spring-apache-camel/src/test/java/com/baeldung/camel/jackson/FruitListJacksonUnmarshalUnitTest.java +++ b/messaging-modules/spring-apache-camel/src/test/java/com/apache/baeldung/camel/jackson/FruitListJacksonUnmarshalUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.camel.jackson; +package com.apache.baeldung.camel.jackson; import java.io.IOException; import java.net.URISyntaxException; @@ -13,6 +13,9 @@ import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.test.junit4.CamelTestSupport; import org.junit.Test; +import com.baeldung.camel.apache.jackson.Fruit; +import com.baeldung.camel.apache.jackson.FruitList; + public class FruitListJacksonUnmarshalUnitTest extends CamelTestSupport { @Test diff --git a/messaging-modules/spring-apache-camel/src/test/java/com/apache/camel/file/processor/ContentBasedFileRouterIntegrationTest.java b/messaging-modules/spring-apache-camel/src/test/java/com/apache/camel/file/processor/ContentBasedFileRouterIntegrationTest.java index 23f5787e4e..1fc3ee7515 100644 --- a/messaging-modules/spring-apache-camel/src/test/java/com/apache/camel/file/processor/ContentBasedFileRouterIntegrationTest.java +++ b/messaging-modules/spring-apache-camel/src/test/java/com/apache/camel/file/processor/ContentBasedFileRouterIntegrationTest.java @@ -11,7 +11,7 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; -import com.baeldung.camel.file.cfg.ContentBasedFileRouterConfig; +import com.baeldung.camel.apache.file.cfg.ContentBasedFileRouterConfig; @RunWith(JUnit4.class) public class ContentBasedFileRouterIntegrationTest { diff --git a/messaging-modules/spring-apache-camel/src/test/java/com/apache/camel/file/processor/FileProcessorIntegrationTest.java b/messaging-modules/spring-apache-camel/src/test/java/com/apache/camel/file/processor/FileProcessorIntegrationTest.java index 1d88e8aeb4..bc5de17537 100644 --- a/messaging-modules/spring-apache-camel/src/test/java/com/apache/camel/file/processor/FileProcessorIntegrationTest.java +++ b/messaging-modules/spring-apache-camel/src/test/java/com/apache/camel/file/processor/FileProcessorIntegrationTest.java @@ -9,7 +9,7 @@ import org.junit.Before; import org.junit.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; -import com.baeldung.camel.file.FileProcessor; +import com.baeldung.camel.apache.file.FileProcessor; public class FileProcessorIntegrationTest { diff --git a/messaging-modules/spring-apache-camel/src/test/java/com/apache/camel/main/AppIntegrationTest.java b/messaging-modules/spring-apache-camel/src/test/java/com/apache/camel/main/AppIntegrationTest.java index b33e6a3b29..cef387dc14 100644 --- a/messaging-modules/spring-apache-camel/src/test/java/com/apache/camel/main/AppIntegrationTest.java +++ b/messaging-modules/spring-apache-camel/src/test/java/com/apache/camel/main/AppIntegrationTest.java @@ -1,6 +1,6 @@ package com.apache.camel.main; -import com.baeldung.camel.main.App; +import com.baeldung.camel.apache.main.App; import junit.framework.TestCase; import org.apache.camel.util.FileUtil; import org.junit.After; diff --git a/spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/SpringContextTest.java b/messaging-modules/spring-apache-camel/src/test/java/com/boot/SpringContextTest.java similarity index 85% rename from spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/SpringContextTest.java rename to messaging-modules/spring-apache-camel/src/test/java/com/boot/SpringContextTest.java index ce743e0f77..527877f47e 100644 --- a/spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/SpringContextTest.java +++ b/messaging-modules/spring-apache-camel/src/test/java/com/boot/SpringContextTest.java @@ -1,11 +1,11 @@ -package com.baeldung; +package com.boot; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; -import com.baeldung.camel.Application; +import com.baeldung.camel.boot.Application; @RunWith(SpringRunner.class) @SpringBootTest(classes = Application.class) diff --git a/spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/camel/boot/testing/GreetingsFileRouterUnitTest.java b/messaging-modules/spring-apache-camel/src/test/java/com/boot/camel/boot/testing/GreetingsFileRouterUnitTest.java similarity index 71% rename from spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/camel/boot/testing/GreetingsFileRouterUnitTest.java rename to messaging-modules/spring-apache-camel/src/test/java/com/boot/camel/boot/testing/GreetingsFileRouterUnitTest.java index baeb1fd39c..0f4d71f23b 100644 --- a/spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/camel/boot/testing/GreetingsFileRouterUnitTest.java +++ b/messaging-modules/spring-apache-camel/src/test/java/com/boot/camel/boot/testing/GreetingsFileRouterUnitTest.java @@ -1,4 +1,6 @@ -package com.baeldung.camel.boot.testing; +package com.boot.camel.boot.testing; + +import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD; import org.apache.camel.EndpointInject; import org.apache.camel.ProducerTemplate; @@ -8,10 +10,14 @@ import org.apache.camel.test.spring.junit5.MockEndpoints; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.annotation.DirtiesContext; -@SpringBootTest +import com.baeldung.camel.boot.Application; + +@SpringBootTest(classes = Application.class) @CamelSpringBootTest @MockEndpoints("file:output") +@DirtiesContext(classMode = AFTER_EACH_TEST_METHOD) class GreetingsFileRouterUnitTest { @Autowired @@ -21,6 +27,7 @@ class GreetingsFileRouterUnitTest { private MockEndpoint mock; @Test + @DirtiesContext void whenSendBody_thenGreetingReceivedSuccessfully() throws InterruptedException { mock.expectedBodiesReceived("Hello Baeldung Readers!"); diff --git a/spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/camel/conditional/ConditionalBeanRouterUnitTest.java b/messaging-modules/spring-apache-camel/src/test/java/com/boot/camel/conditional/ConditionalBeanRouterUnitTest.java similarity index 70% rename from spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/camel/conditional/ConditionalBeanRouterUnitTest.java rename to messaging-modules/spring-apache-camel/src/test/java/com/boot/camel/conditional/ConditionalBeanRouterUnitTest.java index bba1f21392..46a5bb5eb9 100644 --- a/spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/camel/conditional/ConditionalBeanRouterUnitTest.java +++ b/messaging-modules/spring-apache-camel/src/test/java/com/boot/camel/conditional/ConditionalBeanRouterUnitTest.java @@ -1,4 +1,6 @@ -package com.baeldung.camel.conditional; +package com.boot.camel.conditional; + +import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD; import org.apache.camel.EndpointInject; import org.apache.camel.ProducerTemplate; @@ -7,9 +9,13 @@ import org.apache.camel.test.spring.junit5.CamelSpringBootTest; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.annotation.DirtiesContext; -@SpringBootTest +import com.baeldung.camel.boot.Application; + +@SpringBootTest(classes = Application.class) @CamelSpringBootTest +@DirtiesContext(classMode = AFTER_EACH_TEST_METHOD) class ConditionalBeanRouterUnitTest { @Autowired @@ -19,6 +25,7 @@ class ConditionalBeanRouterUnitTest { private MockEndpoint mock; @Test + @DirtiesContext void whenSendBodyWithFruit_thenFavouriteHeaderReceivedSuccessfully() throws InterruptedException { mock.expectedHeaderReceived("favourite", "Apples"); diff --git a/spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/camel/conditional/ConditionalBodyRouterUnitTest.java b/messaging-modules/spring-apache-camel/src/test/java/com/boot/camel/conditional/ConditionalBodyRouterUnitTest.java similarity index 70% rename from spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/camel/conditional/ConditionalBodyRouterUnitTest.java rename to messaging-modules/spring-apache-camel/src/test/java/com/boot/camel/conditional/ConditionalBodyRouterUnitTest.java index 22c12a741f..745b9993ee 100644 --- a/spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/camel/conditional/ConditionalBodyRouterUnitTest.java +++ b/messaging-modules/spring-apache-camel/src/test/java/com/boot/camel/conditional/ConditionalBodyRouterUnitTest.java @@ -1,4 +1,6 @@ -package com.baeldung.camel.conditional; +package com.boot.camel.conditional; + +import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD; import org.apache.camel.EndpointInject; import org.apache.camel.ProducerTemplate; @@ -7,9 +9,13 @@ import org.apache.camel.test.spring.junit5.CamelSpringBootTest; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.annotation.DirtiesContext; -@SpringBootTest +import com.baeldung.camel.boot.Application; + +@SpringBootTest(classes = Application.class) @CamelSpringBootTest +@DirtiesContext(classMode = AFTER_EACH_TEST_METHOD) class ConditionalBodyRouterUnitTest { @Autowired @@ -19,6 +25,7 @@ class ConditionalBodyRouterUnitTest { private MockEndpoint mock; @Test + @DirtiesContext void whenSendBodyWithBaeldung_thenGoodbyeMessageReceivedSuccessfully() throws InterruptedException { mock.expectedBodiesReceived("Goodbye, Baeldung!"); diff --git a/spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/camel/conditional/ConditionalHeaderRouterUnitTest.java b/messaging-modules/spring-apache-camel/src/test/java/com/boot/camel/conditional/ConditionalHeaderRouterUnitTest.java similarity index 70% rename from spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/camel/conditional/ConditionalHeaderRouterUnitTest.java rename to messaging-modules/spring-apache-camel/src/test/java/com/boot/camel/conditional/ConditionalHeaderRouterUnitTest.java index 63fbf6682a..b2803f5682 100644 --- a/spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/camel/conditional/ConditionalHeaderRouterUnitTest.java +++ b/messaging-modules/spring-apache-camel/src/test/java/com/boot/camel/conditional/ConditionalHeaderRouterUnitTest.java @@ -1,4 +1,6 @@ -package com.baeldung.camel.conditional; +package com.boot.camel.conditional; + +import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD; import org.apache.camel.EndpointInject; import org.apache.camel.ProducerTemplate; @@ -7,9 +9,13 @@ import org.apache.camel.test.spring.junit5.CamelSpringBootTest; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.annotation.DirtiesContext; -@SpringBootTest +import com.baeldung.camel.boot.Application; + +@SpringBootTest(classes = Application.class) @CamelSpringBootTest +@DirtiesContext(classMode = AFTER_EACH_TEST_METHOD) class ConditionalHeaderRouterUnitTest { @Autowired @@ -19,6 +25,7 @@ class ConditionalHeaderRouterUnitTest { private MockEndpoint mock; @Test + @DirtiesContext void whenSendBodyWithFruit_thenFavouriteHeaderReceivedSuccessfully() throws InterruptedException { mock.expectedHeaderReceived("favourite", "Banana"); diff --git a/spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/camel/exception/ExceptionHandlingWithDoTryRouteUnitTest.java b/messaging-modules/spring-apache-camel/src/test/java/com/boot/camel/exception/ExceptionHandlingWithDoTryRouteUnitTest.java similarity index 70% rename from spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/camel/exception/ExceptionHandlingWithDoTryRouteUnitTest.java rename to messaging-modules/spring-apache-camel/src/test/java/com/boot/camel/exception/ExceptionHandlingWithDoTryRouteUnitTest.java index 23d3b1a392..68deb46883 100644 --- a/spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/camel/exception/ExceptionHandlingWithDoTryRouteUnitTest.java +++ b/messaging-modules/spring-apache-camel/src/test/java/com/boot/camel/exception/ExceptionHandlingWithDoTryRouteUnitTest.java @@ -1,4 +1,6 @@ -package com.baeldung.camel.exception; +package com.boot.camel.exception; + +import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD; import org.apache.camel.EndpointInject; import org.apache.camel.ProducerTemplate; @@ -7,9 +9,13 @@ import org.apache.camel.test.spring.junit5.CamelSpringBootTest; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.annotation.DirtiesContext; -@SpringBootTest +import com.baeldung.camel.boot.Application; + +@SpringBootTest(classes = Application.class) @CamelSpringBootTest +@DirtiesContext(classMode = AFTER_EACH_TEST_METHOD) class ExceptionHandlingWithDoTryRouteUnitTest { @Autowired @@ -19,6 +25,7 @@ class ExceptionHandlingWithDoTryRouteUnitTest { private MockEndpoint mock; @Test + @DirtiesContext void whenSendHeaders_thenExceptionRaisedAndHandledSuccessfully() throws Exception { mock.expectedMessageCount(1); diff --git a/spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/camel/exception/ExceptionHandlingWithExceptionClauseRouteUnitTest.java b/messaging-modules/spring-apache-camel/src/test/java/com/boot/camel/exception/ExceptionHandlingWithExceptionClauseRouteUnitTest.java similarity index 70% rename from spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/camel/exception/ExceptionHandlingWithExceptionClauseRouteUnitTest.java rename to messaging-modules/spring-apache-camel/src/test/java/com/boot/camel/exception/ExceptionHandlingWithExceptionClauseRouteUnitTest.java index 28d672bd64..25052f2c10 100644 --- a/spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/camel/exception/ExceptionHandlingWithExceptionClauseRouteUnitTest.java +++ b/messaging-modules/spring-apache-camel/src/test/java/com/boot/camel/exception/ExceptionHandlingWithExceptionClauseRouteUnitTest.java @@ -1,4 +1,6 @@ -package com.baeldung.camel.exception; +package com.boot.camel.exception; + +import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD; import org.apache.camel.EndpointInject; import org.apache.camel.ProducerTemplate; @@ -7,9 +9,13 @@ import org.apache.camel.test.spring.junit5.CamelSpringBootTest; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.annotation.DirtiesContext; -@SpringBootTest +import com.baeldung.camel.boot.Application; + +@SpringBootTest(classes = Application.class) @CamelSpringBootTest +@DirtiesContext(classMode = AFTER_EACH_TEST_METHOD) class ExceptionHandlingWithExceptionClauseRouteUnitTest { @Autowired @@ -19,6 +25,7 @@ class ExceptionHandlingWithExceptionClauseRouteUnitTest { private MockEndpoint mock; @Test + @DirtiesContext void whenSendHeaders_thenExceptionRaisedAndHandledSuccessfully() throws Exception { mock.expectedMessageCount(1); diff --git a/spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/camel/exception/ExceptionThrowingRouteUnitTest.java b/messaging-modules/spring-apache-camel/src/test/java/com/boot/camel/exception/ExceptionThrowingRouteUnitTest.java similarity index 78% rename from spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/camel/exception/ExceptionThrowingRouteUnitTest.java rename to messaging-modules/spring-apache-camel/src/test/java/com/boot/camel/exception/ExceptionThrowingRouteUnitTest.java index 6e6944fce8..a547e84a0b 100644 --- a/spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/camel/exception/ExceptionThrowingRouteUnitTest.java +++ b/messaging-modules/spring-apache-camel/src/test/java/com/boot/camel/exception/ExceptionThrowingRouteUnitTest.java @@ -1,7 +1,8 @@ -package com.baeldung.camel.exception; +package com.boot.camel.exception; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD; import org.apache.camel.CamelContext; import org.apache.camel.Exchange; @@ -11,15 +12,20 @@ import org.apache.camel.test.spring.junit5.CamelSpringBootTest; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.annotation.DirtiesContext; -@SpringBootTest +import com.baeldung.camel.boot.Application; + +@SpringBootTest(classes = Application.class) @CamelSpringBootTest +@DirtiesContext(classMode = AFTER_EACH_TEST_METHOD) class ExceptionThrowingRouteUnitTest { @Autowired private ProducerTemplate template; @Test + @DirtiesContext void whenSendBody_thenExceptionRaisedSuccessfully() { CamelContext context = template.getCamelContext(); Exchange exchange = context.getEndpoint("direct:start-exception") diff --git a/spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/camel/exception/IllegalArgumentExceptionThrowingProcessorUnitTest.java b/messaging-modules/spring-apache-camel/src/test/java/com/boot/camel/exception/IllegalArgumentExceptionThrowingProcessorUnitTest.java similarity index 76% rename from spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/camel/exception/IllegalArgumentExceptionThrowingProcessorUnitTest.java rename to messaging-modules/spring-apache-camel/src/test/java/com/boot/camel/exception/IllegalArgumentExceptionThrowingProcessorUnitTest.java index a95abdfd27..9d15f70547 100644 --- a/spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/camel/exception/IllegalArgumentExceptionThrowingProcessorUnitTest.java +++ b/messaging-modules/spring-apache-camel/src/test/java/com/boot/camel/exception/IllegalArgumentExceptionThrowingProcessorUnitTest.java @@ -1,9 +1,11 @@ -package com.baeldung.camel.exception; +package com.boot.camel.exception; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; +import com.baeldung.camel.boot.exception.IllegalArgumentExceptionThrowingProcessor; + class IllegalArgumentExceptionThrowingProcessorUnitTest { @Test 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/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/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/design-patterns-singleton/src/test/java/com/baeldung/serializable_singleton/EnumSingletonUnitTest.java b/patterns-modules/design-patterns-singleton/src/test/java/com/baeldung/serializable_singleton/EnumSingletonUnitTest.java index e0a098056a..7fdcb20850 100644 --- a/patterns-modules/design-patterns-singleton/src/test/java/com/baeldung/serializable_singleton/EnumSingletonUnitTest.java +++ b/patterns-modules/design-patterns-singleton/src/test/java/com/baeldung/serializable_singleton/EnumSingletonUnitTest.java @@ -1,8 +1,10 @@ package com.baeldung.serializable_singleton; +import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; +import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; @@ -10,8 +12,10 @@ import java.io.ObjectOutputStream; // Unit test for the EnumSingleton class. public class EnumSingletonUnitTest { - - // Checks that when an EnumSingleton instance is serialized + + private static final String ENUM_SINGLETON_TEST_TXT = "enum_singleton_test.txt"; + + // Checks that when an EnumSingleton instance is serialized // and then deserialized, its state is preserved. @Test public void givenEnumSingleton_whenSerializedAndDeserialized_thenStatePreserved() { @@ -19,11 +23,10 @@ public class EnumSingletonUnitTest { es1.setState("State One"); - try ( - FileOutputStream fos = new FileOutputStream("enum_singleton_test.txt"); - ObjectOutputStream oos = new ObjectOutputStream(fos); - FileInputStream fis = new FileInputStream("enum_singleton_test.txt"); - ObjectInputStream ois = new ObjectInputStream(fis)) { + try (FileOutputStream fos = new FileOutputStream(ENUM_SINGLETON_TEST_TXT); + ObjectOutputStream oos = new ObjectOutputStream(fos); + FileInputStream fis = new FileInputStream(ENUM_SINGLETON_TEST_TXT); + ObjectInputStream ois = new ObjectInputStream(fis)) { // Serializing. oos.writeObject(es1); @@ -46,11 +49,10 @@ public class EnumSingletonUnitTest { public void givenEnumSingleton_whenSerializedAndDeserialized_thenOneInstance() { EnumSingleton es1 = EnumSingleton.getInstance(); - try ( - FileOutputStream fos = new FileOutputStream("enum_singleton_test.txt"); - ObjectOutputStream oos = new ObjectOutputStream(fos); - FileInputStream fis = new FileInputStream("enum_singleton_test.txt"); - ObjectInputStream ois = new ObjectInputStream(fis)) { + try (FileOutputStream fos = new FileOutputStream(ENUM_SINGLETON_TEST_TXT); + ObjectOutputStream oos = new ObjectOutputStream(fos); + FileInputStream fis = new FileInputStream(ENUM_SINGLETON_TEST_TXT); + ObjectInputStream ois = new ObjectInputStream(fis)) { // Serializing. oos.writeObject(es1); @@ -66,4 +68,12 @@ public class EnumSingletonUnitTest { System.out.println(e); } } + + @AfterAll + public static void cleanUp() { + final File removeFile = new File(ENUM_SINGLETON_TEST_TXT); + if (removeFile.exists()) { + removeFile.deleteOnExit(); + } + } } diff --git a/patterns-modules/design-patterns-singleton/src/test/java/com/baeldung/serializable_singleton/SingletonUnitTest.java b/patterns-modules/design-patterns-singleton/src/test/java/com/baeldung/serializable_singleton/SingletonUnitTest.java index cc26eb6995..a46288cc8f 100644 --- a/patterns-modules/design-patterns-singleton/src/test/java/com/baeldung/serializable_singleton/SingletonUnitTest.java +++ b/patterns-modules/design-patterns-singleton/src/test/java/com/baeldung/serializable_singleton/SingletonUnitTest.java @@ -1,8 +1,10 @@ package com.baeldung.serializable_singleton; +import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; +import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; @@ -10,8 +12,10 @@ import java.io.ObjectOutputStream; // Unit test for the Singleton class. public class SingletonUnitTest { - - // Checks that when a Singleton instance is serialized + + private static final String SINGLETON_TEST_TXT = "singleton_test.txt"; + + // Checks that when a Singleton instance is serialized // and then deserialized, its state is preserved. @Test public void givenSingleton_whenSerializedAndDeserialized_thenStatePreserved() { @@ -19,11 +23,10 @@ public class SingletonUnitTest { s1.setState("State One"); - try ( - FileOutputStream fos = new FileOutputStream("singleton_test.txt"); - ObjectOutputStream oos = new ObjectOutputStream(fos); - FileInputStream fis = new FileInputStream("singleton_test.txt"); - ObjectInputStream ois = new ObjectInputStream(fis)) { + try (FileOutputStream fos = new FileOutputStream(SINGLETON_TEST_TXT); + ObjectOutputStream oos = new ObjectOutputStream(fos); + FileInputStream fis = new FileInputStream(SINGLETON_TEST_TXT); + ObjectInputStream ois = new ObjectInputStream(fis)) { // Serializing. oos.writeObject(s1); @@ -46,11 +49,10 @@ public class SingletonUnitTest { public void givenSingleton_whenSerializedAndDeserialized_thenTwoInstances() { Singleton s1 = Singleton.getInstance(); - try ( - FileOutputStream fos = new FileOutputStream("singleton_test.txt"); - ObjectOutputStream oos = new ObjectOutputStream(fos); - FileInputStream fis = new FileInputStream("singleton_test.txt"); - ObjectInputStream ois = new ObjectInputStream(fis)) { + try (FileOutputStream fos = new FileOutputStream(SINGLETON_TEST_TXT); + ObjectOutputStream oos = new ObjectOutputStream(fos); + FileInputStream fis = new FileInputStream(SINGLETON_TEST_TXT); + ObjectInputStream ois = new ObjectInputStream(fis)) { // Serializing. oos.writeObject(s1); @@ -65,4 +67,12 @@ public class SingletonUnitTest { System.out.println(e); } } + + @AfterAll + public static void cleanUp() { + final File removeFile = new File(SINGLETON_TEST_TXT); + if (removeFile.exists()) { + removeFile.deleteOnExit(); + } + } } 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/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/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..c30a7a666c 100644 --- a/patterns-modules/front-controller/pom.xml +++ b/patterns-modules/front-controller/pom.xml @@ -25,10 +25,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 +40,9 @@ + + 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..e320af31b4 --- /dev/null +++ b/patterns-modules/idd/README.md @@ -0,0 +1 @@ +### Relevant Articles: \ No newline at end of file diff --git a/patterns-modules/idd/pom.xml b/patterns-modules/idd/pom.xml new file mode 100644 index 0000000000..02795089e0 --- /dev/null +++ b/patterns-modules/idd/pom.xml @@ -0,0 +1,29 @@ + + + 4.0.0 + idd + 1.0 + idd + + + + org.apache.maven.plugins + maven-compiler-plugin + + 9 + 9 + + + + + 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..7bfacf8a48 --- /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.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..cbce56cd6c 100644 --- a/patterns-modules/intercepting-filter/pom.xml +++ b/patterns-modules/intercepting-filter/pom.xml @@ -30,6 +30,7 @@ org.apache.maven.plugins maven-war-plugin + ${maven-war-plugin.version} false @@ -46,4 +47,8 @@ + + 3.3.2 + + \ No newline at end of file diff --git a/patterns-modules/pom.xml b/patterns-modules/pom.xml index 26d9a76aee..5a99b539be 100644 --- a/patterns-modules/pom.xml +++ b/patterns-modules/pom.xml @@ -31,6 +31,7 @@ clean-architecture enterprise-patterns coupling + idd @@ -71,4 +72,4 @@ 9.4.0.v20161208 - \ No newline at end of file + 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 e530ea2555..68a46b82b1 100644 --- a/persistence-modules/hibernate-queries/pom.xml +++ b/persistence-modules/hibernate-queries/pom.xml @@ -79,6 +79,12 @@ jmh-generator-annprocess ${jmh-generator.version} + + org.testcontainers + mysql + ${testcontainers.mysql.version} + test + @@ -88,6 +94,7 @@ 6.0.6 2.2.3 2.1.214 + 1.17.6 \ No newline at end of file diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/keywords/BrokenPhoneOrder.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/keywords/BrokenPhoneOrder.java new file mode 100644 index 0000000000..e045005f28 --- /dev/null +++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/keywords/BrokenPhoneOrder.java @@ -0,0 +1,39 @@ +package com.baeldung.hibernate.keywords; + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "broken_phone_order") +public class BrokenPhoneOrder implements Serializable { + @Id + @Column(name = "order") + String order; + @Column(name = "where") + String where; + + public BrokenPhoneOrder(String order, String where) { + this.order = order; + this.where = where; + } + + public String getOrder() { + return order; + } + + public void setOrder(String order) { + this.order = order; + } + + public String getWhere() { + return where; + } + + public void setWhere(String where) { + this.where = where; + } +} diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/keywords/PhoneOrder.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/keywords/PhoneOrder.java new file mode 100644 index 0000000000..daee57d553 --- /dev/null +++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/keywords/PhoneOrder.java @@ -0,0 +1,39 @@ +package com.baeldung.hibernate.keywords; + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "phone_order") +public class PhoneOrder implements Serializable { + @Id + @Column(name = "`order`") + String order; + @Column(name = "`where`") + String where; + + public PhoneOrder(String order, String where) { + this.order = order; + this.where = where; + } + + public String getOrder() { + return order; + } + + public void setOrder(String order) { + this.order = order; + } + + public String getWhere() { + return where; + } + + public void setWhere(String where) { + this.where = where; + } +} 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/HibernateKeywordsApplicationIntegrationTest.java new file mode 100644 index 0000000000..4282da3de4 --- /dev/null +++ b/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/keywords/HibernateKeywordsApplicationIntegrationTest.java @@ -0,0 +1,58 @@ +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; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +public class HibernateKeywordsApplicationIntegrationTest { + + private static SessionFactory sessionFactory; + private Session session; + + @BeforeAll + static void createSession() { + sessionFactory = new Configuration().addAnnotatedClass(BrokenPhoneOrder.class) + .addAnnotatedClass(PhoneOrder.class) + .configure("keywords/hibernate.keywords.cfg.xml") + .buildSessionFactory(); + } + + @BeforeEach + void before() { + session = sessionFactory.openSession(); + session.beginTransaction(); + } + + @AfterEach + void after() { + session.close(); + } + + @Test + void givenBrokenPhoneOrderWithReservedKeywords_whenNewObjectIsPersisted_thenItFails() { + BrokenPhoneOrder order = new BrokenPhoneOrder(randomUUID().toString(), "My House"); + + assertThatExceptionOfType(PersistenceException.class).isThrownBy(() -> { + session.persist(order); + session.flush(); + }); + } + + @Test + void givenPhoneOrderWithEscapedKeywords_whenNewObjectIsPersisted_thenItSucceeds() { + PhoneOrder order = new PhoneOrder(randomUUID().toString(), "here"); + + session.persist(order); + session.flush(); + } + +} diff --git a/persistence-modules/hibernate-queries/src/test/resources/keywords/hibernate.keywords.cfg.xml b/persistence-modules/hibernate-queries/src/test/resources/keywords/hibernate.keywords.cfg.xml new file mode 100644 index 0000000000..9a1b6bb775 --- /dev/null +++ b/persistence-modules/hibernate-queries/src/test/resources/keywords/hibernate.keywords.cfg.xml @@ -0,0 +1,14 @@ + + + + + + org.hibernate.dialect.MySQLDialect + jdbc:tc:mysql:5.7.41:///restaurant?TC_INITSCRIPT=keywords/init.sql + org.testcontainers.jdbc.ContainerDatabaseDriver + validate + true + + + \ No newline at end of file diff --git a/persistence-modules/hibernate-queries/src/test/resources/keywords/init.sql b/persistence-modules/hibernate-queries/src/test/resources/keywords/init.sql new file mode 100644 index 0000000000..4d42a45f5b --- /dev/null +++ b/persistence-modules/hibernate-queries/src/test/resources/keywords/init.sql @@ -0,0 +1,9 @@ +CREATE TABLE IF NOT EXISTS phone_order ( + `order` varchar(255) PRIMARY KEY, + `where` varchar(255) +); + +CREATE TABLE IF NOT EXISTS broken_phone_order ( + `order` varchar(255) PRIMARY KEY, + `where` varchar(255) +); \ No newline at end of file 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..9606da4594 100644 --- a/persistence-modules/pom.xml +++ b/persistence-modules/pom.xml @@ -43,7 +43,8 @@ java-jpa java-jpa-2 java-jpa-3 - java-mongodb + + java-mongodb-2 java-mongodb-3 java-mongodb-queries 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-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-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/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-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 8751aedda6..fb26df5d18 100644 --- a/pom.xml +++ b/pom.xml @@ -330,59 +330,40 @@ parent-spring-5 parent-java - apache-cxf-modules - apache-libraries azure checker-plugin - core-groovy-modules core-java-modules - couchbase - custom-pmd - drools + couchbase + gradle-modules/gradle/maven-to-gradle - guava-modules apache-httpclient - httpclient4 + apache-httpclient4 - - jackson-modules - - javafx java-jdi java-websocket - jaxb - jersey jhipster-5 - jmeter - jmh - jsf - json-modules + jmh kubernetes-modules language-interop - libraries-2 libraries-3 - libraries-data - libraries-data-db - libraries-security - libraries-server-2 - libraries-testing + logging-modules lombok-modules @@ -397,22 +378,10 @@ 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 @@ -459,30 +428,21 @@ 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 @@ -599,58 +559,36 @@ parent-spring-5 parent-java - apache-cxf-modules - apache-libraries azure checker-plugin - core-groovy-modules core-java-modules couchbase - custom-pmd - drools gradle-modules/gradle/maven-to-gradle - - guava-modules apache-httpclient - httpclient4 + apache-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-data-db - libraries-security - libraries-server-2 - libraries-testing + logging-modules lombok-modules @@ -661,26 +599,14 @@ 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 @@ -719,29 +645,20 @@ 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 @@ -879,12 +796,47 @@ + spring-jersey + jersey + jaxb + javafx + spring-batch + spring-boot-rest + spring-drools + spring-exceptions + spring-jenkins-pipeline + spring-core + spring-core-4 + spring-integration + libraries-security + + 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 apache-velocity di-modules asciidoctor aws-modules + + couchbase + core-groovy-modules + core-java-modules/core-java-9 core-java-modules/core-java-9-improvements core-java-modules/core-java-9-jigsaw @@ -922,14 +874,19 @@ core-java-modules/core-java-networking-3 core-java-modules/core-java-strings core-java-modules/core-java-httpclient + custom-pmd spring-core-6 data-structures ddd-contexts + jackson-modules deeplearning4j docker-modules + drools + guava-modules apache-httpclient-2 kubernetes-modules/kubernetes-spring libraries-concurrency + libraries-testing maven-modules/compiler-plugin-java-9 maven-modules/maven-generate-war maven-modules/multimodulemavenproject @@ -939,8 +896,8 @@ persistence-modules/spring-data-jpa-repo-3 quarkus-modules/quarkus-vs-springboot quarkus-modules/quarkus-jandex + quarkus-modules spring-boot-modules/spring-boot-cassandre - spring-boot-modules/spring-boot-camel spring-boot-modules/spring-boot-3 spring-boot-modules/spring-boot-3-native spring-boot-modules/spring-boot-3-observation @@ -949,6 +906,12 @@ spring-swagger-codegen/custom-validations-opeanpi-codegen testing-modules/testing-assertions persistence-modules/fauna + + rule-engines-modules + + reactive-systems + rxjava-modules + lightrun tablesaw geotools @@ -972,7 +935,7 @@ asm atomikos atomix - axon + bazel code-generation @@ -1002,6 +965,8 @@ java-native jsoup ksqldb + jsf + libraries-2 libraries-7 libraries-apache-commons libraries-apache-commons-collections @@ -1036,7 +1001,7 @@ spring-5-webflux-2 spring-activiti spring-batch-2 - spring-caching-2 + spring-boot-modules/spring-caching-2 spring-core-2 spring-core-3 spring-core-5 @@ -1046,6 +1011,7 @@ spring-kafka spring-native + spring-security-modules/spring-security-oauth2-testing spring-protobuf spring-quartz @@ -1056,12 +1022,15 @@ tensorflow-java xstream webrtc + persistence-modules/java-mongodb + messaging-modules/spring-apache-camel UTF-8 11 - 11 + 11 + 11 @@ -1088,13 +1057,42 @@ + spring-jersey + jersey + jaxb + javafx + spring-batch + spring-boot-rest + spring-drools + spring-exceptions + spring-jenkins-pipeline + spring-core + spring-core-4 + spring-integration + libraries-security + + 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 apache-velocity di-modules asciidoctor aws-modules + couchbase + + core-groovy-modules core-java-modules/core-java-9 core-java-modules/core-java-9-improvements core-java-modules/core-java-9-jigsaw @@ -1132,14 +1130,22 @@ core-java-modules/core-java-networking-3 core-java-modules/core-java-strings core-java-modules/core-java-httpclient + spring-aop + spring-aop-2 + custom-pmd spring-core-6 data-structures ddd-contexts + jackson-modules deeplearning4j + jmeter docker-modules + drools + guava-modules apache-httpclient-2 kubernetes-modules/kubernetes-spring libraries-concurrency + libraries-testing maven-modules/compiler-plugin-java-9 maven-modules/maven-generate-war maven-modules/multimodulemavenproject @@ -1149,8 +1155,8 @@ persistence-modules/spring-data-jpa-repo-3 quarkus-modules/quarkus-vs-springboot quarkus-modules/quarkus-jandex + quarkus-modules spring-boot-modules/spring-boot-cassandre - spring-boot-modules/spring-boot-camel spring-boot-modules/spring-boot-3 spring-boot-modules/spring-boot-3-native spring-boot-modules/spring-boot-3-observation @@ -1159,6 +1165,12 @@ spring-swagger-codegen/custom-validations-opeanpi-codegen testing-modules/testing-assertions persistence-modules/fauna + + rule-engines-modules + + reactive-systems + rxjava-modules + lightrun tablesaw geotools @@ -1181,7 +1193,7 @@ asm atomikos atomix - axon + bazel code-generation @@ -1212,6 +1224,7 @@ java-native jsoup + jsf ksqldb libraries-7 @@ -1249,7 +1262,7 @@ spring-5-webflux-2 spring-activiti spring-batch-2 - spring-caching-2 + spring-boot-modules/spring-caching-2 spring-core-2 spring-core-3 spring-core-5 @@ -1269,12 +1282,16 @@ tensorflow-java xstream webrtc + persistence-modules/java-mongodb + libraries-2 + messaging-modules/spring-apache-camel UTF-8 11 - 11 + 11 + 11 @@ -1345,8 +1362,8 @@ 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/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/security-modules/pom.xml b/security-modules/pom.xml index 70f29cecd7..ed88ef842e 100644 --- a/security-modules/pom.xml +++ b/security-modules/pom.xml @@ -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/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-boot-modules/pom.xml b/spring-boot-modules/pom.xml index 3ed9eea431..7fdfac4b93 100644 --- a/spring-boot-modules/pom.xml +++ b/spring-boot-modules/pom.xml @@ -84,6 +84,7 @@ spring-boot-data-2 spring-boot-validation spring-boot-data-3 + spring-caching diff --git a/spring-boot-modules/spring-boot-3-test-pitfalls/README.md b/spring-boot-modules/spring-boot-3-test-pitfalls/README.md new file mode 100644 index 0000000000..1290cbfcc7 --- /dev/null +++ b/spring-boot-modules/spring-boot-3-test-pitfalls/README.md @@ -0,0 +1,2 @@ +## Relevant Articles +- [Pitfalls on Testing with Spring Boot](https://www.baeldung.com/spring-boot-testing-pitfalls) diff --git a/spring-boot-modules/spring-boot-3/README.md b/spring-boot-modules/spring-boot-3/README.md index 0d79f006e1..5fa884a053 100644 --- a/spring-boot-modules/spring-boot-3/README.md +++ b/spring-boot-modules/spring-boot-3/README.md @@ -3,3 +3,4 @@ - [Spring Boot 3 and Spring Framework 6.0 – What’s New](https://www.baeldung.com/spring-boot-3-spring-6-new) - [Singleton Design Pattern vs Singleton Beans in Spring Boot](https://www.baeldung.com/spring-boot-singleton-vs-beans) +- [Migrate Application From Spring Boot 2 to Spring Boot 3](https://www.baeldung.com/spring-boot-3-migration) diff --git a/spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/sample/boundary/ServerConfiguration.java b/spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/sample/boundary/ServerConfiguration.java new file mode 100644 index 0000000000..5533fe1b7d --- /dev/null +++ b/spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/sample/boundary/ServerConfiguration.java @@ -0,0 +1,21 @@ +package com.baeldung.sample.boundary; + +import org.apache.catalina.connector.Connector; +import org.springframework.boot.web.embedded.tomcat.TomcatConnectorCustomizer; +import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; +import org.springframework.boot.web.server.WebServerFactoryCustomizer; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class ServerConfiguration implements WebServerFactoryCustomizer { + + @Override + public void customize(TomcatServletWebServerFactory factory) { + factory.addConnectorCustomizers(new TomcatConnectorCustomizer() { + @Override + public void customize(Connector connector) { + connector.setProperty("maxHttpResponseHeaderSize", "100000"); + } + }); + } +} diff --git a/spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/sample/boundary/TodosController.java b/spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/sample/boundary/TodosController.java index 7efa7dfee3..cf21303659 100644 --- a/spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/sample/boundary/TodosController.java +++ b/spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/sample/boundary/TodosController.java @@ -18,6 +18,7 @@ import org.springframework.web.bind.annotation.RestController; import java.net.URI; import java.util.Collection; +import java.util.List; import java.util.stream.Collectors; import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo; @@ -35,6 +36,13 @@ public class TodosController { // Mapping zwischen den Schichten private final TodoDtoMapper mapper; + + @GetMapping(value = {"/name"},produces = DEFAULT_MEDIA_TYPE) + public List findAllName(){ + return List.of("Hello", "World"); + } + + @GetMapping(produces = DEFAULT_MEDIA_TYPE) public Collection findAll() { return service.findAll().stream() @@ -80,4 +88,4 @@ public class TodosController { service.delete(id); } -} +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/sample/boundary/WebConfiguration.java b/spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/sample/boundary/WebConfiguration.java new file mode 100644 index 0000000000..24bbc223ae --- /dev/null +++ b/spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/sample/boundary/WebConfiguration.java @@ -0,0 +1,13 @@ +package com.baeldung.sample.boundary; + +import org.springframework.web.servlet.config.annotation.PathMatchConfigurer; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +public class WebConfiguration implements WebMvcConfigurer { + + @Override + public void configurePathMatch(PathMatchConfigurer configurer) { + configurer.setUseTrailingSlashMatch(true); + } + +} diff --git a/spring-boot-modules/spring-boot-3/src/test/java/com/baeldung/sample/boundary/TodosControllerApiIntegrationTest.java b/spring-boot-modules/spring-boot-3/src/test/java/com/baeldung/sample/boundary/TodosControllerApiIntegrationTest.java index 680b6c85bb..3a80bc8a6c 100644 --- a/spring-boot-modules/spring-boot-3/src/test/java/com/baeldung/sample/boundary/TodosControllerApiIntegrationTest.java +++ b/spring-boot-modules/spring-boot-3/src/test/java/com/baeldung/sample/boundary/TodosControllerApiIntegrationTest.java @@ -215,4 +215,18 @@ class TodosControllerApiIntegrationTest { .andExpect(status().isNotFound()); } + @Test + void whenThereIsNoSlashMatching_ThenHttpStatusIs404() throws Exception { + mvc + .perform(get(BASEURL + "/name/").contentType(DEFAULT_MEDIA_TYPE)) + .andExpect(status().isNotFound()); + } + + @Test + void whenThereIsNoSlashMatching_ThenHttpStatusIs200() throws Exception { + mvc + .perform(get(BASEURL + "/name").contentType(DEFAULT_MEDIA_TYPE)) + .andExpect(status().isOk()); + } + } diff --git a/spring-boot-modules/spring-boot-camel/.gitignore b/spring-boot-modules/spring-boot-camel/.gitignore deleted file mode 100644 index 16be8f2193..0000000000 --- a/spring-boot-modules/spring-boot-camel/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/output/ diff --git a/spring-boot-modules/spring-boot-camel/README.md b/spring-boot-modules/spring-boot-camel/README.md deleted file mode 100644 index d797f1a0b5..0000000000 --- a/spring-boot-modules/spring-boot-camel/README.md +++ /dev/null @@ -1,30 +0,0 @@ -## Spring Boot Camel - -This module contains articles about Spring Boot with Apache Camel - -### Example for the Article on Camel API with SpringBoot - -To start, run: - -`mvn spring-boot:run` - -Then, make a POST http request to: - -`http://localhost:8080/camel/api/bean` - -Include the HEADER: Content-Type: application/json, - -and a BODY Payload like: - -`{"id": 1,"name": "World"}` - -We will get a return code of 201 and the response: `Hello, World` - if the transform() method from Application class is uncommented and the process() method is commented - -or return code of 201 and the response: `{"id": 10,"name": "Hello, World"}` - if the transform() method from Application class is commented and the process() method is uncommented - -## Relevant articles: - -- [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) -- [Apache Camel Exception Handling](https://www.baeldung.com/java-apache-camel-exception-handling) diff --git a/spring-boot-modules/spring-boot-camel/pom.xml b/spring-boot-modules/spring-boot-camel/pom.xml deleted file mode 100644 index ecf7143808..0000000000 --- a/spring-boot-modules/spring-boot-camel/pom.xml +++ /dev/null @@ -1,80 +0,0 @@ - - - 4.0.0 - com.example - spring-boot-camel - 0.0.1-SNAPSHOT - spring-boot-camel - - - com.baeldung.spring-boot-modules - spring-boot-modules - 1.0.0-SNAPSHOT - - - - - org.apache.camel.springboot - camel-servlet-starter - ${camel.version} - - - org.apache.camel.springboot - camel-jackson-starter - ${camel.version} - - - org.apache.camel.springboot - camel-swagger-java-starter - ${camel.version} - - - org.apache.camel.springboot - camel-spring-boot-starter - ${camel.version} - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-test - test - - - org.apache.camel - camel-test-spring-junit5 - ${camel.version} - test - - - - - spring-boot:run - - - org.springframework.boot - spring-boot-maven-plugin - - - - repackage - - - com.baeldung.camel.boot.testing.GreetingsFileSpringApplication - - - - - - - - - 11 - 3.15.0 - - - \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-camel/src/main/resources/logback.xml b/spring-boot-modules/spring-boot-camel/src/main/resources/logback.xml deleted file mode 100644 index d0b4334f5a..0000000000 --- a/spring-boot-modules/spring-boot-camel/src/main/resources/logback.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - diff --git a/spring-boot-modules/spring-boot-keycloak-2/pom.xml b/spring-boot-modules/spring-boot-keycloak-2/pom.xml index a119a09561..8b1eec2e4e 100644 --- a/spring-boot-modules/spring-boot-keycloak-2/pom.xml +++ b/spring-boot-modules/spring-boot-keycloak-2/pom.xml @@ -17,18 +17,6 @@ ../../parent-boot-2 - - - - org.keycloak.bom - keycloak-adapter-bom - ${keycloak-adapter-bom.version} - pom - import - - - - org.springframework.boot @@ -39,8 +27,12 @@ spring-boot-starter-security - org.keycloak - keycloak-spring-boot-starter + org.springframework.boot + spring-boot-starter-oauth2-resource-server + + + org.springframework.boot + spring-boot-starter-oauth2-client org.springframework.boot @@ -58,8 +50,4 @@ - - 15.0.2 - - \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-keycloak-2/src/main/java/com/baeldung/disablingkeycloak/KeycloakConfiguration.java b/spring-boot-modules/spring-boot-keycloak-2/src/main/java/com/baeldung/disablingkeycloak/KeycloakConfiguration.java deleted file mode 100644 index a9a2ea6a18..0000000000 --- a/spring-boot-modules/spring-boot-keycloak-2/src/main/java/com/baeldung/disablingkeycloak/KeycloakConfiguration.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.disablingkeycloak; - -import org.keycloak.adapters.springboot.KeycloakSpringBootConfigResolver; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -@Configuration -public class KeycloakConfiguration { - - @Bean - public KeycloakSpringBootConfigResolver keycloakConfigResolver() { - return new KeycloakSpringBootConfigResolver(); - } -} diff --git a/spring-boot-modules/spring-boot-keycloak-2/src/main/java/com/baeldung/disablingkeycloak/KeycloakSecurityConfig.java b/spring-boot-modules/spring-boot-keycloak-2/src/main/java/com/baeldung/disablingkeycloak/KeycloakSecurityConfig.java index d48c99d8fd..b41b64077c 100644 --- a/spring-boot-modules/spring-boot-keycloak-2/src/main/java/com/baeldung/disablingkeycloak/KeycloakSecurityConfig.java +++ b/spring-boot-modules/spring-boot-keycloak-2/src/main/java/com/baeldung/disablingkeycloak/KeycloakSecurityConfig.java @@ -1,38 +1,34 @@ package com.baeldung.disablingkeycloak; -import org.keycloak.adapters.springsecurity.KeycloakConfiguration; -import org.keycloak.adapters.springsecurity.config.KeycloakWebSecurityConfigurerAdapter; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.web.authentication.session.NullAuthenticatedSessionStrategy; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer; +import org.springframework.security.core.session.SessionRegistryImpl; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.authentication.session.RegisterSessionAuthenticationStrategy; import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy; -@KeycloakConfiguration +@Configuration +@EnableWebSecurity @ConditionalOnProperty(name = "keycloak.enabled", havingValue = "true", matchIfMissing = true) -public class KeycloakSecurityConfig extends KeycloakWebSecurityConfigurerAdapter { +public class KeycloakSecurityConfig { - @Autowired - public void configureGlobal(AuthenticationManagerBuilder auth) { - auth.authenticationProvider(keycloakAuthenticationProvider()); + @Bean + protected SessionAuthenticationStrategy sessionAuthenticationStrategy() { + return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl()); } @Bean - @Override - protected SessionAuthenticationStrategy sessionAuthenticationStrategy() { - return new NullAuthenticatedSessionStrategy(); - } - - @Override - protected void configure(HttpSecurity http) throws Exception { - super.configure(http); - + public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http.csrf() .disable() - .authorizeRequests() - .anyRequest() - .authenticated(); + .authorizeHttpRequests(auth -> auth.anyRequest() + .authenticated()); + http.oauth2Login(); + http.oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt); + return http.build(); } } diff --git a/spring-boot-modules/spring-boot-keycloak-2/src/main/resources/application-disabling-keycloak.properties b/spring-boot-modules/spring-boot-keycloak-2/src/main/resources/application-disabling-keycloak.properties index 21263cf725..1f08eac234 100644 --- a/spring-boot-modules/spring-boot-keycloak-2/src/main/resources/application-disabling-keycloak.properties +++ b/spring-boot-modules/spring-boot-keycloak-2/src/main/resources/application-disabling-keycloak.properties @@ -1,7 +1,10 @@ -# Keycloak authentication is enabled for production. +server.port=8081 keycloak.enabled=true -keycloak.realm=SpringBootKeycloak -keycloak.auth-server-url=http://localhost:8180/auth -keycloak.resource=login-app -keycloak.bearer-only=true -keycloak.ssl-required=external + +spring.security.oauth2.client.registration.keycloak.client-id=login-app +spring.security.oauth2.client.registration.keycloak.authorization-grant-type=authorization_code +spring.security.oauth2.client.registration.keycloak.scope=openid +spring.security.oauth2.client.provider.keycloak.issuer-uri=http://localhost:8080/realms/SpringBootKeycloak +spring.security.oauth2.client.provider.keycloak.user-name-attribute=preferred_username + +spring.security.oauth2.resourceserver.jwt.issuer-uri=http://localhost:8080/realms/SpringBootKeycloak \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-logging-log4j2/pom.xml b/spring-boot-modules/spring-boot-logging-log4j2/pom.xml index b2a6975964..b429339417 100644 --- a/spring-boot-modules/spring-boot-logging-log4j2/pom.xml +++ b/spring-boot-modules/spring-boot-logging-log4j2/pom.xml @@ -8,34 +8,13 @@ jar Demo project for Spring Boot Logging with Log4J2 - - org.springframework.boot - spring-boot-starter-parent - 2.2.2.RELEASE - + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 - - - - - - - junit - junit - ${junit.version} - - - org.junit - junit-bom - ${junit-jupiter.version} - pom - import - - - - org.springframework.boot @@ -62,7 +41,6 @@ org.projectlombok lombok - ${lombok.version} provided @@ -96,10 +74,6 @@ com.baeldung.springbootlogging.SpringBootLoggingApplication 1.3.8.RELEASE 1.1.16 - 1.18.24 - - 4.13.2 - 5.8.1 2.17.1 diff --git a/spring-boot-modules/spring-boot-swagger-2/README.md b/spring-boot-modules/spring-boot-swagger-2/README.md index 242f3d3385..e5ec236801 100644 --- a/spring-boot-modules/spring-boot-swagger-2/README.md +++ b/spring-boot-modules/spring-boot-swagger-2/README.md @@ -2,4 +2,5 @@ - [Swagger: Specify Two Responses with the Same Response Code](https://www.baeldung.com/swagger-two-responses-one-response-code) - [Specify an Array of Strings as Body Parameters in Swagger](https://www.baeldung.com/swagger-body-array-of-strings) -- [Swagger @ApiParam vs @ApiModelProperty](https://www.baeldung.com/swagger-apiparam-vs-apimodelproperty) \ No newline at end of file +- [Swagger @ApiParam vs @ApiModelProperty](https://www.baeldung.com/swagger-apiparam-vs-apimodelproperty) +- [Map Date Types With OpenAPI Generator](https://www.baeldung.com/openapi-map-date-types) diff --git a/spring-boot-modules/spring-boot-swagger-2/pom.xml b/spring-boot-modules/spring-boot-swagger-2/pom.xml index d2d1d10ad9..daca41426a 100644 --- a/spring-boot-modules/spring-boot-swagger-2/pom.xml +++ b/spring-boot-modules/spring-boot-swagger-2/pom.xml @@ -112,6 +112,7 @@ true ${project.basedir}/src/main/resources/static/event.yaml + ${project.basedir}/src/main/resources/static/account_api_description.yaml spring true diff --git a/spring-boot-modules/spring-boot-swagger-2/src/main/java/com/baeldung/apifirstdevelopment/controller/AccountController.java b/spring-boot-modules/spring-boot-swagger-2/src/main/java/com/baeldung/apifirstdevelopment/controller/AccountController.java new file mode 100644 index 0000000000..96242efb41 --- /dev/null +++ b/spring-boot-modules/spring-boot-swagger-2/src/main/java/com/baeldung/apifirstdevelopment/controller/AccountController.java @@ -0,0 +1,20 @@ +package com.baeldung.apifirstdevelopment.controller; + +import org.openapitools.api.AccountApi; +import org.openapitools.model.Account; +import org.openapitools.model.DepositRequest; +import org.springframework.http.ResponseEntity; + +public class AccountController implements AccountApi { + @Override + public ResponseEntity depositToAccount(DepositRequest depositRequest) { + //Execute the business logic through Service/Utils/Repository classes + return AccountApi.super.depositToAccount(depositRequest); + } + + @Override + public ResponseEntity getAccount() { + //Execute the business logic through Service/Utils/Repository classes + return AccountApi.super.getAccount(); + } +} diff --git a/spring-boot-modules/spring-boot-swagger-2/src/main/resources/static/account_api_description.yaml b/spring-boot-modules/spring-boot-swagger-2/src/main/resources/static/account_api_description.yaml new file mode 100644 index 0000000000..38349d6540 --- /dev/null +++ b/spring-boot-modules/spring-boot-swagger-2/src/main/resources/static/account_api_description.yaml @@ -0,0 +1,78 @@ +openapi: 3.0.3 +info: + title: Banking API Specification for account interoperations + description: |- + A simple banking API that allows two operations: + - get account balance given account number + - deposit amount to a account + version: 1.0-SNAPSHOT +servers: + - url: https://testenvironment.org/api/v1 + - url: https://prodenvironment.org/api/v1 +tags: + - name: accounts + description: Operations for bank accounts + +paths: + /account: + get: + tags: + - accounts + summary: Get account information + description: Get account information using account number + operationId: getAccount + responses: + 200: + description: Success + content: + application/json: + schema: + $ref: '#/components/schemas/Account' + 404: + description: Account not found + content: + application/json: + schema: + $ref: '#/components/schemas/AccountNotFoundError' + /account/deposit: + post: + tags: + - accounts + summary: Deposit amount to account + description: Initiates a deposit operation of a desired amount to the account specified + operationId: depositToAccount + requestBody: + description: Account number and desired amount to deposit + content: + application/json: + schema: + $ref: '#/components/schemas/DepositRequest' + required: true + responses: + 204: + description: Success + 404: + description: Account not found + content: + application/json: + schema: + $ref: '#/components/schemas/AccountNotFoundError' +components: + schemas: + Account: + type: object + properties: + balance: + type: number + AccountNotFoundError: + type: object + properties: + message: + type: string + DepositRequest: + type: object + properties: + accountNumber: + type: string + depositAmount: + type: number \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-testing-2/pom.xml b/spring-boot-modules/spring-boot-testing-2/pom.xml index 395fa27948..cf16407e76 100644 --- a/spring-boot-modules/spring-boot-testing-2/pom.xml +++ b/spring-boot-modules/spring-boot-testing-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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-boot-testing-2 spring-boot-testing-2 @@ -66,6 +66,18 @@ testcontainers ${testcontainers.version} + + org.testcontainers + junit-jupiter + ${testcontainers.version} + test + + + com.redis.testcontainers + testcontainers-redis-junit-jupiter + 1.4.6 + test + diff --git a/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/redistestcontainers/service/ProductServiceDynamicPropertyManualTest.java b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/redistestcontainers/service/ProductServiceDynamicPropertyManualTest.java new file mode 100644 index 0000000000..e7bcca2620 --- /dev/null +++ b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/redistestcontainers/service/ProductServiceDynamicPropertyManualTest.java @@ -0,0 +1,89 @@ +package com.baeldung.redistestcontainers.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import org.testcontainers.utility.DockerImageName; + +import com.baeldung.redistestcontainers.hash.Product; +import com.redis.testcontainers.RedisContainer; + +@SpringBootTest +@Testcontainers(disabledWithoutDocker = true) +public class ProductServiceDynamicPropertyManualTest { + + @Autowired + private ProductService productService; + + @Container + private static final RedisContainer REDIS_CONTAINER = new RedisContainer(DockerImageName.parse("redis:5.0.3-alpine")).withExposedPorts(6379); + + @DynamicPropertySource + private static void registerRedisProperties(DynamicPropertyRegistry registry) { + registry.add("spring.redis.host", REDIS_CONTAINER::getHost); + registry.add("spring.redis.port", () -> REDIS_CONTAINER.getMappedPort(6379) + .toString()); + } + + @Test + void givenRedisContainerConfiguredWithDynamicProperties_whenCheckingRunningStatus_thenStatusIsRunning() { + assertTrue(REDIS_CONTAINER.isRunning()); + } + + @Test + void givenProductCreated_whenGettingProductById_thenProductExistsAndHasSameProperties() { + Product product = new Product("1", "Test Product", 10.0); + productService.createProduct(product); + Product productFromDb = productService.getProduct("1"); + assertEquals("1", productFromDb.getId()); + assertEquals("Test Product", productFromDb.getName()); + assertEquals(10.0, productFromDb.getPrice()); + } + + @Test + void givenProductCreatedAndUpdated_whenGettingTheProduct_thenUpdatedProductReturned() { + Product product = new Product("1", "Test Product", 10.0); + productService.createProduct(product); + Product productFromDb = productService.getProduct("1"); + assertEquals("1", productFromDb.getId()); + assertEquals("Test Product", productFromDb.getName()); + assertEquals(10.0, productFromDb.getPrice()); + productFromDb.setName("Updated Product"); + productFromDb.setPrice(20.0); + productService.updateProduct(productFromDb); + Product updatedProductFromDb = productService.getProduct("1"); + assertEquals("Updated Product", updatedProductFromDb.getName()); + assertEquals(20.0, updatedProductFromDb.getPrice()); + } + + @Test + void givenProductCreatedAndDeleted_whenGettingTheProduct_thenNoProductReturned() { + Product product = new Product("1", "Test Product", 10.0); + productService.createProduct(product); + Product productFromDb = productService.getProduct("1"); + assertEquals("1", productFromDb.getId()); + assertEquals("Test Product", productFromDb.getName()); + assertEquals(10.0, productFromDb.getPrice()); + productService.deleteProduct("1"); + Product deletedProductFromDb = productService.getProduct("1"); + assertNull(deletedProductFromDb); + } + + @Test + void givenProductCreated_whenGettingProductById_thenSameProductReturned() { + Product product = new Product("1", "Test Product", 10.0); + productService.createProduct(product); + Product productFromDb = productService.getProduct("1"); + assertEquals("1", productFromDb.getId()); + assertEquals("Test Product", productFromDb.getName()); + assertEquals(10.0, productFromDb.getPrice()); + } +} diff --git a/spring-caching-2/README.md b/spring-boot-modules/spring-caching-2/README.md similarity index 100% rename from spring-caching-2/README.md rename to spring-boot-modules/spring-caching-2/README.md diff --git a/spring-caching-2/pom.xml b/spring-boot-modules/spring-caching-2/pom.xml similarity index 91% rename from spring-caching-2/pom.xml rename to spring-boot-modules/spring-caching-2/pom.xml index 0a07820fc4..6e33e42d2b 100644 --- a/spring-caching-2/pom.xml +++ b/spring-boot-modules/spring-caching-2/pom.xml @@ -9,10 +9,9 @@ jar - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../parent-boot-2/pom.xml + com.baeldung.spring-boot-modules + spring-boot-modules + 1.0.0-SNAPSHOT diff --git a/spring-caching-2/src/main/java/com/baeldung/caching/redis/CacheConfig.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/redis/CacheConfig.java similarity index 100% rename from spring-caching-2/src/main/java/com/baeldung/caching/redis/CacheConfig.java rename to spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/redis/CacheConfig.java diff --git a/spring-caching-2/src/main/java/com/baeldung/caching/redis/Item.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/redis/Item.java similarity index 100% rename from spring-caching-2/src/main/java/com/baeldung/caching/redis/Item.java rename to spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/redis/Item.java diff --git a/spring-caching-2/src/main/java/com/baeldung/caching/redis/ItemController.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/redis/ItemController.java similarity index 100% rename from spring-caching-2/src/main/java/com/baeldung/caching/redis/ItemController.java rename to spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/redis/ItemController.java diff --git a/spring-caching-2/src/main/java/com/baeldung/caching/redis/ItemRepository.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/redis/ItemRepository.java similarity index 100% rename from spring-caching-2/src/main/java/com/baeldung/caching/redis/ItemRepository.java rename to spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/redis/ItemRepository.java diff --git a/spring-caching-2/src/main/java/com/baeldung/caching/redis/ItemService.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/redis/ItemService.java similarity index 100% rename from spring-caching-2/src/main/java/com/baeldung/caching/redis/ItemService.java rename to spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/redis/ItemService.java diff --git a/spring-caching-2/src/main/java/com/baeldung/caching/redis/RedisCacheApplication.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/redis/RedisCacheApplication.java similarity index 100% rename from spring-caching-2/src/main/java/com/baeldung/caching/redis/RedisCacheApplication.java rename to spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/redis/RedisCacheApplication.java diff --git a/spring-caching-2/src/main/java/com/baeldung/caching/ttl/CachingTTLApplication.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/CachingTTLApplication.java old mode 100755 new mode 100644 similarity index 100% rename from spring-caching-2/src/main/java/com/baeldung/caching/ttl/CachingTTLApplication.java rename to spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/CachingTTLApplication.java diff --git a/spring-caching-2/src/main/java/com/baeldung/caching/ttl/config/SpringCachingConfig.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/config/SpringCachingConfig.java similarity index 100% rename from spring-caching-2/src/main/java/com/baeldung/caching/ttl/config/SpringCachingConfig.java rename to spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/config/SpringCachingConfig.java diff --git a/spring-caching-2/src/main/java/com/baeldung/caching/ttl/controller/HotelController.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/controller/HotelController.java old mode 100755 new mode 100644 similarity index 100% rename from spring-caching-2/src/main/java/com/baeldung/caching/ttl/controller/HotelController.java rename to spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/controller/HotelController.java diff --git a/spring-caching-2/src/main/java/com/baeldung/caching/ttl/exception/ControllerAdvisor.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/exception/ControllerAdvisor.java similarity index 100% rename from spring-caching-2/src/main/java/com/baeldung/caching/ttl/exception/ControllerAdvisor.java rename to spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/exception/ControllerAdvisor.java diff --git a/spring-caching-2/src/main/java/com/baeldung/caching/ttl/exception/ElementNotFoundException.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/exception/ElementNotFoundException.java similarity index 100% rename from spring-caching-2/src/main/java/com/baeldung/caching/ttl/exception/ElementNotFoundException.java rename to spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/exception/ElementNotFoundException.java diff --git a/spring-caching-2/src/main/java/com/baeldung/caching/ttl/model/City.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/model/City.java similarity index 100% rename from spring-caching-2/src/main/java/com/baeldung/caching/ttl/model/City.java rename to spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/model/City.java diff --git a/spring-caching-2/src/main/java/com/baeldung/caching/ttl/model/Hotel.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/model/Hotel.java old mode 100755 new mode 100644 similarity index 100% rename from spring-caching-2/src/main/java/com/baeldung/caching/ttl/model/Hotel.java rename to spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/model/Hotel.java diff --git a/spring-caching-2/src/main/java/com/baeldung/caching/ttl/repository/CityRepository.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/repository/CityRepository.java similarity index 100% rename from spring-caching-2/src/main/java/com/baeldung/caching/ttl/repository/CityRepository.java rename to spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/repository/CityRepository.java diff --git a/spring-caching-2/src/main/java/com/baeldung/caching/ttl/repository/HotelRepository.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/repository/HotelRepository.java old mode 100755 new mode 100644 similarity index 100% rename from spring-caching-2/src/main/java/com/baeldung/caching/ttl/repository/HotelRepository.java rename to spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/repository/HotelRepository.java diff --git a/spring-caching-2/src/main/java/com/baeldung/caching/ttl/service/HotelService.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/service/HotelService.java old mode 100755 new mode 100644 similarity index 100% rename from spring-caching-2/src/main/java/com/baeldung/caching/ttl/service/HotelService.java rename to spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/service/HotelService.java diff --git a/spring-caching-2/src/main/java/com/baeldung/caching/ttl/service/SpringCacheCustomizer.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/service/SpringCacheCustomizer.java similarity index 100% rename from spring-caching-2/src/main/java/com/baeldung/caching/ttl/service/SpringCacheCustomizer.java rename to spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/service/SpringCacheCustomizer.java diff --git a/spring-caching-2/src/main/resources/application.properties b/spring-boot-modules/spring-caching-2/src/main/resources/application.properties similarity index 100% rename from spring-caching-2/src/main/resources/application.properties rename to spring-boot-modules/spring-caching-2/src/main/resources/application.properties diff --git a/spring-caching-2/src/main/resources/data.sql b/spring-boot-modules/spring-caching-2/src/main/resources/data.sql similarity index 100% rename from spring-caching-2/src/main/resources/data.sql rename to spring-boot-modules/spring-caching-2/src/main/resources/data.sql diff --git a/spring-caching-2/src/test/java/com/baeldung/caching/redis/ItemServiceCachingIntegrationTest.java b/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/redis/ItemServiceCachingIntegrationTest.java similarity index 100% rename from spring-caching-2/src/test/java/com/baeldung/caching/redis/ItemServiceCachingIntegrationTest.java rename to spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/redis/ItemServiceCachingIntegrationTest.java diff --git a/spring-caching-2/src/test/java/com/baeldung/caching/ttl/HotelControllerIntegrationTest.java b/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/ttl/HotelControllerIntegrationTest.java similarity index 100% rename from spring-caching-2/src/test/java/com/baeldung/caching/ttl/HotelControllerIntegrationTest.java rename to spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/ttl/HotelControllerIntegrationTest.java diff --git a/spring-caching-2/src/test/java/com/baeldung/caching/ttl/SlowTest.java b/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/ttl/SlowTest.java similarity index 100% rename from spring-caching-2/src/test/java/com/baeldung/caching/ttl/SlowTest.java rename to spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/ttl/SlowTest.java diff --git a/spring-caching-2/src/test/resources/application.properties b/spring-boot-modules/spring-caching-2/src/test/resources/application.properties similarity index 100% rename from spring-caching-2/src/test/resources/application.properties rename to spring-boot-modules/spring-caching-2/src/test/resources/application.properties diff --git a/spring-caching/README.md b/spring-boot-modules/spring-caching/README.md similarity index 100% rename from spring-caching/README.md rename to spring-boot-modules/spring-caching/README.md diff --git a/spring-caching/pom.xml b/spring-boot-modules/spring-caching/pom.xml similarity index 93% rename from spring-caching/pom.xml rename to spring-boot-modules/spring-caching/pom.xml index 34c035a8ec..c0318729af 100644 --- a/spring-caching/pom.xml +++ b/spring-boot-modules/spring-caching/pom.xml @@ -8,11 +8,10 @@ spring-caching war - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../parent-boot-2 + + com.baeldung.spring-boot-modules + spring-boot-modules + 1.0.0-SNAPSHOT diff --git a/spring-caching/src/main/java/com/baeldung/cachetest/Application.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/cachetest/Application.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/cachetest/Application.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/cachetest/Application.java diff --git a/spring-caching/src/main/java/com/baeldung/cachetest/config/CacheConfig.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/cachetest/config/CacheConfig.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/cachetest/config/CacheConfig.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/cachetest/config/CacheConfig.java diff --git a/spring-caching/src/main/java/com/baeldung/cachetest/config/CacheEventLogger.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/cachetest/config/CacheEventLogger.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/cachetest/config/CacheEventLogger.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/cachetest/config/CacheEventLogger.java diff --git a/spring-caching/src/main/java/com/baeldung/cachetest/rest/NumberController.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/cachetest/rest/NumberController.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/cachetest/rest/NumberController.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/cachetest/rest/NumberController.java diff --git a/spring-caching/src/main/java/com/baeldung/cachetest/service/NumberService.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/cachetest/service/NumberService.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/cachetest/service/NumberService.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/cachetest/service/NumberService.java diff --git a/spring-caching/src/main/java/com/baeldung/caching/boot/CacheApplication.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/caching/boot/CacheApplication.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/caching/boot/CacheApplication.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/caching/boot/CacheApplication.java diff --git a/spring-caching/src/main/java/com/baeldung/caching/boot/SimpleCacheCustomizer.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/caching/boot/SimpleCacheCustomizer.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/caching/boot/SimpleCacheCustomizer.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/caching/boot/SimpleCacheCustomizer.java diff --git a/spring-caching/src/main/java/com/baeldung/caching/config/ApplicationCacheConfig.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/caching/config/ApplicationCacheConfig.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/caching/config/ApplicationCacheConfig.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/caching/config/ApplicationCacheConfig.java diff --git a/spring-caching/src/main/java/com/baeldung/caching/config/CachingConfig.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/caching/config/CachingConfig.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/caching/config/CachingConfig.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/caching/config/CachingConfig.java diff --git a/spring-caching/src/main/java/com/baeldung/caching/config/CustomKeyGenerator.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/caching/config/CustomKeyGenerator.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/caching/config/CustomKeyGenerator.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/caching/config/CustomKeyGenerator.java diff --git a/spring-caching/src/main/java/com/baeldung/caching/eviction/controllers/CachingController.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/caching/eviction/controllers/CachingController.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/caching/eviction/controllers/CachingController.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/caching/eviction/controllers/CachingController.java diff --git a/spring-caching/src/main/java/com/baeldung/caching/eviction/service/CachingService.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/caching/eviction/service/CachingService.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/caching/eviction/service/CachingService.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/caching/eviction/service/CachingService.java diff --git a/spring-caching/src/main/java/com/baeldung/caching/example/AbstractService.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/caching/example/AbstractService.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/caching/example/AbstractService.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/caching/example/AbstractService.java diff --git a/spring-caching/src/main/java/com/baeldung/caching/example/BookService.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/caching/example/BookService.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/caching/example/BookService.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/caching/example/BookService.java diff --git a/spring-caching/src/main/java/com/baeldung/caching/example/Customer.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/caching/example/Customer.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/caching/example/Customer.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/caching/example/Customer.java diff --git a/spring-caching/src/main/java/com/baeldung/caching/example/CustomerDataService.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/caching/example/CustomerDataService.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/caching/example/CustomerDataService.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/caching/example/CustomerDataService.java diff --git a/spring-caching/src/main/java/com/baeldung/caching/example/CustomerServiceWithParent.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/caching/example/CustomerServiceWithParent.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/caching/example/CustomerServiceWithParent.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/caching/example/CustomerServiceWithParent.java diff --git a/spring-caching/src/main/java/com/baeldung/caching/model/Book.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/caching/model/Book.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/caching/model/Book.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/caching/model/Book.java diff --git a/spring-caching/src/main/java/com/baeldung/ehcache/calculator/SquaredCalculator.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/ehcache/calculator/SquaredCalculator.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/ehcache/calculator/SquaredCalculator.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/ehcache/calculator/SquaredCalculator.java diff --git a/spring-caching/src/main/java/com/baeldung/ehcache/config/CacheHelper.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/ehcache/config/CacheHelper.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/ehcache/config/CacheHelper.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/ehcache/config/CacheHelper.java diff --git a/spring-caching/src/main/java/com/baeldung/multiplecachemanager/bo/CustomerDetailBO.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/multiplecachemanager/bo/CustomerDetailBO.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/multiplecachemanager/bo/CustomerDetailBO.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/multiplecachemanager/bo/CustomerDetailBO.java diff --git a/spring-caching/src/main/java/com/baeldung/multiplecachemanager/bo/OrderDetailBO.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/multiplecachemanager/bo/OrderDetailBO.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/multiplecachemanager/bo/OrderDetailBO.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/multiplecachemanager/bo/OrderDetailBO.java diff --git a/spring-caching/src/main/java/com/baeldung/multiplecachemanager/config/MultipleCacheManagerConfig.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/multiplecachemanager/config/MultipleCacheManagerConfig.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/multiplecachemanager/config/MultipleCacheManagerConfig.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/multiplecachemanager/config/MultipleCacheManagerConfig.java diff --git a/spring-caching/src/main/java/com/baeldung/multiplecachemanager/config/MultipleCacheResolver.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/multiplecachemanager/config/MultipleCacheResolver.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/multiplecachemanager/config/MultipleCacheResolver.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/multiplecachemanager/config/MultipleCacheResolver.java diff --git a/spring-caching/src/main/java/com/baeldung/multiplecachemanager/controller/MultipleCacheManagerController.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/multiplecachemanager/controller/MultipleCacheManagerController.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/multiplecachemanager/controller/MultipleCacheManagerController.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/multiplecachemanager/controller/MultipleCacheManagerController.java diff --git a/spring-caching/src/main/java/com/baeldung/multiplecachemanager/entity/Customer.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/multiplecachemanager/entity/Customer.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/multiplecachemanager/entity/Customer.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/multiplecachemanager/entity/Customer.java diff --git a/spring-caching/src/main/java/com/baeldung/multiplecachemanager/entity/Item.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/multiplecachemanager/entity/Item.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/multiplecachemanager/entity/Item.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/multiplecachemanager/entity/Item.java diff --git a/spring-caching/src/main/java/com/baeldung/multiplecachemanager/entity/Order.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/multiplecachemanager/entity/Order.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/multiplecachemanager/entity/Order.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/multiplecachemanager/entity/Order.java diff --git a/spring-caching/src/main/java/com/baeldung/multiplecachemanager/repository/CustomerDetailRepository.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/multiplecachemanager/repository/CustomerDetailRepository.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/multiplecachemanager/repository/CustomerDetailRepository.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/multiplecachemanager/repository/CustomerDetailRepository.java diff --git a/spring-caching/src/main/java/com/baeldung/multiplecachemanager/repository/OrderDetailRepository.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/multiplecachemanager/repository/OrderDetailRepository.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/multiplecachemanager/repository/OrderDetailRepository.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/multiplecachemanager/repository/OrderDetailRepository.java diff --git a/spring-caching/src/main/java/com/baeldung/springdatacaching/model/Book.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/springdatacaching/model/Book.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/springdatacaching/model/Book.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/springdatacaching/model/Book.java diff --git a/spring-caching/src/main/java/com/baeldung/springdatacaching/repositories/BookRepository.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/springdatacaching/repositories/BookRepository.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/springdatacaching/repositories/BookRepository.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/springdatacaching/repositories/BookRepository.java diff --git a/spring-caching/src/main/resources/application.properties b/spring-boot-modules/spring-caching/src/main/resources/application.properties similarity index 100% rename from spring-caching/src/main/resources/application.properties rename to spring-boot-modules/spring-caching/src/main/resources/application.properties diff --git a/spring-caching/src/main/resources/config.xml b/spring-boot-modules/spring-caching/src/main/resources/config.xml similarity index 100% rename from spring-caching/src/main/resources/config.xml rename to spring-boot-modules/spring-caching/src/main/resources/config.xml diff --git a/spring-caching/src/main/resources/data.sql b/spring-boot-modules/spring-caching/src/main/resources/data.sql similarity index 100% rename from spring-caching/src/main/resources/data.sql rename to spring-boot-modules/spring-caching/src/main/resources/data.sql diff --git a/spring-caching/src/main/resources/ehcache.xml b/spring-boot-modules/spring-caching/src/main/resources/ehcache.xml similarity index 100% rename from spring-caching/src/main/resources/ehcache.xml rename to spring-boot-modules/spring-caching/src/main/resources/ehcache.xml diff --git a/spring-caching/src/main/resources/logback.xml b/spring-boot-modules/spring-caching/src/main/resources/logback.xml similarity index 100% rename from spring-caching/src/main/resources/logback.xml rename to spring-boot-modules/spring-caching/src/main/resources/logback.xml diff --git a/spring-caching/src/main/resources/schema.sql b/spring-boot-modules/spring-caching/src/main/resources/schema.sql similarity index 100% rename from spring-caching/src/main/resources/schema.sql rename to spring-boot-modules/spring-caching/src/main/resources/schema.sql diff --git a/spring-caching/src/test/java/com/baeldung/caching/boot/SimpleCacheCustomizerIntegrationTest.java b/spring-boot-modules/spring-caching/src/test/java/com/baeldung/caching/boot/SimpleCacheCustomizerIntegrationTest.java similarity index 100% rename from spring-caching/src/test/java/com/baeldung/caching/boot/SimpleCacheCustomizerIntegrationTest.java rename to spring-boot-modules/spring-caching/src/test/java/com/baeldung/caching/boot/SimpleCacheCustomizerIntegrationTest.java diff --git a/spring-caching/src/test/java/com/baeldung/caching/test/CacheEvictAnnotationIntegrationTest.java b/spring-boot-modules/spring-caching/src/test/java/com/baeldung/caching/test/CacheEvictAnnotationIntegrationTest.java similarity index 100% rename from spring-caching/src/test/java/com/baeldung/caching/test/CacheEvictAnnotationIntegrationTest.java rename to spring-boot-modules/spring-caching/src/test/java/com/baeldung/caching/test/CacheEvictAnnotationIntegrationTest.java diff --git a/spring-caching/src/test/java/com/baeldung/caching/test/CacheManagerEvictIntegrationTest.java b/spring-boot-modules/spring-caching/src/test/java/com/baeldung/caching/test/CacheManagerEvictIntegrationTest.java similarity index 100% rename from spring-caching/src/test/java/com/baeldung/caching/test/CacheManagerEvictIntegrationTest.java rename to spring-boot-modules/spring-caching/src/test/java/com/baeldung/caching/test/CacheManagerEvictIntegrationTest.java diff --git a/spring-caching/src/test/java/com/baeldung/caching/test/SpringCachingIntegrationTest.java b/spring-boot-modules/spring-caching/src/test/java/com/baeldung/caching/test/SpringCachingIntegrationTest.java similarity index 100% rename from spring-caching/src/test/java/com/baeldung/caching/test/SpringCachingIntegrationTest.java rename to spring-boot-modules/spring-caching/src/test/java/com/baeldung/caching/test/SpringCachingIntegrationTest.java diff --git a/spring-caching/src/test/java/com/baeldung/ehcache/SquareCalculatorUnitTest.java b/spring-boot-modules/spring-caching/src/test/java/com/baeldung/ehcache/SquareCalculatorUnitTest.java similarity index 100% rename from spring-caching/src/test/java/com/baeldung/ehcache/SquareCalculatorUnitTest.java rename to spring-boot-modules/spring-caching/src/test/java/com/baeldung/ehcache/SquareCalculatorUnitTest.java diff --git a/spring-caching/src/test/java/com/baeldung/multiplecachemanager/MultipleCacheManagerIntegrationTest.java b/spring-boot-modules/spring-caching/src/test/java/com/baeldung/multiplecachemanager/MultipleCacheManagerIntegrationTest.java similarity index 100% rename from spring-caching/src/test/java/com/baeldung/multiplecachemanager/MultipleCacheManagerIntegrationTest.java rename to spring-boot-modules/spring-caching/src/test/java/com/baeldung/multiplecachemanager/MultipleCacheManagerIntegrationTest.java diff --git a/spring-caching/src/test/java/com/baeldung/springdatacaching/repositories/BookRepositoryCachingIntegrationTest.java b/spring-boot-modules/spring-caching/src/test/java/com/baeldung/springdatacaching/repositories/BookRepositoryCachingIntegrationTest.java similarity index 100% rename from spring-caching/src/test/java/com/baeldung/springdatacaching/repositories/BookRepositoryCachingIntegrationTest.java rename to spring-boot-modules/spring-caching/src/test/java/com/baeldung/springdatacaching/repositories/BookRepositoryCachingIntegrationTest.java diff --git a/spring-caching/src/test/java/com/baeldung/springdatacaching/repositories/BookRepositoryIntegrationTest.java b/spring-boot-modules/spring-caching/src/test/java/com/baeldung/springdatacaching/repositories/BookRepositoryIntegrationTest.java similarity index 100% rename from spring-caching/src/test/java/com/baeldung/springdatacaching/repositories/BookRepositoryIntegrationTest.java rename to spring-boot-modules/spring-caching/src/test/java/com/baeldung/springdatacaching/repositories/BookRepositoryIntegrationTest.java diff --git a/spring-boot-rest/pom.xml b/spring-boot-rest/pom.xml index f81286adb6..fb5df4e68a 100644 --- a/spring-boot-rest/pom.xml +++ b/spring-boot-rest/pom.xml @@ -88,6 +88,7 @@ com.baeldung.SpringBootRestApplication 1.4.11.1 3.1.0 + 3.3.2 \ No newline at end of file diff --git a/spring-cloud-modules/pom.xml b/spring-cloud-modules/pom.xml index 43e2687d74..68c7d45b7c 100644 --- a/spring-cloud-modules/pom.xml +++ b/spring-cloud-modules/pom.xml @@ -54,8 +54,7 @@ spring-cloud-bus spring-cloud-data-flow spring-cloud-sleuth - spring-cloud-openfeign-2 - spring-cloud-open-telemetry + spring-cloud-open-telemetry diff --git a/spring-cloud-modules/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/GatewayApplication.java b/spring-cloud-modules/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/GatewayApplication.java index 79785a3f20..8fc75e1ff6 100644 --- a/spring-cloud-modules/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/GatewayApplication.java +++ b/spring-cloud-modules/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/bootstrap/gateway/GatewayApplication.java @@ -1,7 +1,5 @@ package com.baeldung.spring.cloud.bootstrap.gateway; -import com.baeldung.spring.cloud.bootstrap.gateway.client.book.BooksClient; -import com.baeldung.spring.cloud.bootstrap.gateway.client.rating.RatingsClient; import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.EurekaClient; import org.springframework.beans.factory.annotation.Autowired; @@ -19,8 +17,6 @@ import org.springframework.cloud.sleuth.zipkin.HttpZipkinSpanReporter; import org.springframework.cloud.sleuth.zipkin.ZipkinProperties; import org.springframework.cloud.sleuth.zipkin.ZipkinSpanReporter; import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.FilterType; import org.springframework.web.client.RestTemplate; import zipkin.Span; @@ -69,11 +65,10 @@ public class GatewayApplication { @Override public void report(Span span) { InstanceInfo instance = eurekaClient.getNextServerFromEureka("zipkin", false); - if (!(baseUrl != null && instance.getHomePageUrl().equals(baseUrl))) { + if (baseUrl == null || !instance.getHomePageUrl().equals(baseUrl)) { baseUrl = instance.getHomePageUrl(); - delegate = new HttpZipkinSpanReporter(new RestTemplate(), baseUrl, zipkinProperties.getFlushInterval(), spanMetricReporter); - if (!span.name.matches(skipPattern)) delegate.report(span); } + delegate = new HttpZipkinSpanReporter(new RestTemplate(), baseUrl, zipkinProperties.getFlushInterval(), spanMetricReporter); if (!span.name.matches(skipPattern)) delegate.report(span); } }; diff --git a/spring-cloud-modules/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/BookServiceApplication.java b/spring-cloud-modules/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/BookServiceApplication.java index 91fd23e32d..d787b5e407 100644 --- a/spring-cloud-modules/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/BookServiceApplication.java +++ b/spring-cloud-modules/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/BookServiceApplication.java @@ -42,11 +42,11 @@ public class BookServiceApplication { @Override public void report(Span span) { InstanceInfo instance = eurekaClient.getNextServerFromEureka("zipkin", false); - if (!(baseUrl != null && instance.getHomePageUrl().equals(baseUrl))) { + if (baseUrl == null || !instance.getHomePageUrl().equals(baseUrl)) { baseUrl = instance.getHomePageUrl(); - delegate = new HttpZipkinSpanReporter(new RestTemplate(), baseUrl, zipkinProperties.getFlushInterval(), spanMetricReporter); - if (!span.name.matches(skipPattern)) delegate.report(span); } + delegate = new HttpZipkinSpanReporter(new RestTemplate(), baseUrl, zipkinProperties.getFlushInterval(), spanMetricReporter); + if (!span.name.matches(skipPattern)) delegate.report(span); } }; } diff --git a/spring-cloud-modules/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/RatingServiceApplication.java b/spring-cloud-modules/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/RatingServiceApplication.java index 8dacbaa79d..5a94f19472 100644 --- a/spring-cloud-modules/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/RatingServiceApplication.java +++ b/spring-cloud-modules/spring-cloud-bootstrap/svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/RatingServiceApplication.java @@ -51,11 +51,10 @@ public class RatingServiceApplication { @Override public void report(Span span) { InstanceInfo instance = eurekaClient.getNextServerFromEureka("zipkin", false); - if (!(baseUrl != null && instance.getHomePageUrl().equals(baseUrl))) { + if (baseUrl == null || !instance.getHomePageUrl().equals(baseUrl)) { baseUrl = instance.getHomePageUrl(); - delegate = new HttpZipkinSpanReporter(new RestTemplate(), baseUrl, zipkinProperties.getFlushInterval(), spanMetricReporter); - if (!span.name.matches(skipPattern)) delegate.report(span); } + delegate = new HttpZipkinSpanReporter(new RestTemplate(), baseUrl, zipkinProperties.getFlushInterval(), spanMetricReporter); if (!span.name.matches(skipPattern)) delegate.report(span); } }; diff --git a/spring-cloud-modules/spring-cloud-open-telemetry/docker-compose.yml b/spring-cloud-modules/spring-cloud-open-telemetry/docker-compose.yml index 8a6833095c..7ee2f67c0f 100644 --- a/spring-cloud-modules/spring-cloud-open-telemetry/docker-compose.yml +++ b/spring-cloud-modules/spring-cloud-open-telemetry/docker-compose.yml @@ -20,7 +20,7 @@ services: - "14250" collector: - image: otel/opentelemetry-collector:0.47.0 + image: otel/opentelemetry-collector:0.72.0 command: [ "--config=/etc/otel-collector-config.yml" ] volumes: - ./otel-config.yml:/etc/otel-collector-config.yml diff --git a/spring-cloud-modules/spring-cloud-open-telemetry/otel-config.yml b/spring-cloud-modules/spring-cloud-open-telemetry/otel-config.yml index 886c10a1c3..4402603a85 100644 --- a/spring-cloud-modules/spring-cloud-open-telemetry/otel-config.yml +++ b/spring-cloud-modules/spring-cloud-open-telemetry/otel-config.yml @@ -9,7 +9,7 @@ processors: exporters: logging: - logLevel: debug + loglevel: debug jaeger: endpoint: jaeger-service:14250 tls: diff --git a/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/Dockerfile b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/Dockerfile index 8bae52cec4..50cd35ed84 100644 --- a/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/Dockerfile +++ b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/Dockerfile @@ -2,6 +2,6 @@ FROM adoptopenjdk/openjdk11:alpine COPY target/spring-cloud-open-telemetry1-1.0.0-SNAPSHOT.jar spring-cloud-open-telemetry.jar -EXPOSE 8081 +EXPOSE 8080 ENTRYPOINT ["java","-jar","/spring-cloud-open-telemetry.jar"] \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/pom.xml b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/pom.xml index 5011590e73..3003113085 100644 --- a/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/pom.xml +++ b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/pom.xml @@ -62,12 +62,8 @@ io.opentelemetry - opentelemetry-exporter-otlp-trace - - - io.grpc - grpc-okhttp - ${grpc-okhttp.version} + opentelemetry-exporter-otlp + ${otel-exporter-otlp.version} org.junit.jupiter @@ -93,24 +89,11 @@ - - - spring-milestones - https://repo.spring.io/milestone - - - - - spring-milestones - https://repo.spring.io/milestone - - - - 2.5.7 - 2020.0.4 - 1.0.0-M12 - 1.42.1 + 2.7.9 + 2021.0.5 + 1.1.2 + 1.23.1 \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry2/pom.xml b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry2/pom.xml index 2d7ac8204e..4f56cc717e 100644 --- a/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry2/pom.xml +++ b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry2/pom.xml @@ -61,12 +61,8 @@ io.opentelemetry - opentelemetry-exporter-otlp-trace - - - io.grpc - grpc-okhttp - ${grpc-okhttp.version} + opentelemetry-exporter-otlp + ${otel-exporter-otlp.version} org.junit.jupiter @@ -92,24 +88,11 @@ - - - spring-milestones - https://repo.spring.io/milestone - - - - - spring-milestones - https://repo.spring.io/milestone - - - - 2.5.7 - 2020.0.4 - 1.0.0-M12 - 1.42.1 + 2.7.9 + 2021.0.5 + 1.1.2 + 1.23.1 \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-openfeign-2/README.md b/spring-cloud-modules/spring-cloud-openfeign-2/README.md deleted file mode 100644 index bc306e2302..0000000000 --- a/spring-cloud-modules/spring-cloud-openfeign-2/README.md +++ /dev/null @@ -1,4 +0,0 @@ - -### Relevant Articles: - -- [Feign Client Exception Handling](https://www.baeldung.com/java-feign-client-exception-handling) diff --git a/spring-cloud-modules/spring-cloud-openfeign-2/pom.xml b/spring-cloud-modules/spring-cloud-openfeign-2/pom.xml deleted file mode 100644 index 43cc7c6c50..0000000000 --- a/spring-cloud-modules/spring-cloud-openfeign-2/pom.xml +++ /dev/null @@ -1,64 +0,0 @@ - - - 4.0.0 - com.baeldung.cloud - spring-cloud-openfeign-2 - spring-cloud-openfeign-2 - OpenFeign project for Spring Boot - - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../../parent-boot-2 - - - - - - org.springframework.cloud - spring-cloud-dependencies - ${spring-cloud.version} - pom - import - - - - - - - org.springframework.cloud - spring-cloud-starter-openfeign - - - io.github.openfeign - feign-okhttp - - - org.springframework.boot - spring-boot-starter-web - - - io.github.openfeign.form - feign-form - ${feign-form.version} - - - io.github.openfeign.form - feign-form-spring - - - org.springframework.boot - spring-boot-starter-test - test - - - - - 2021.0.3 - 3.8.0 - - - \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-openfeign-2/src/main/resources/application.properties b/spring-cloud-modules/spring-cloud-openfeign-2/src/main/resources/application.properties deleted file mode 100644 index 7188b74c9b..0000000000 --- a/spring-cloud-modules/spring-cloud-openfeign-2/src/main/resources/application.properties +++ /dev/null @@ -1,10 +0,0 @@ -server.port=8085 -spring.main.allow-bean-definition-overriding=true -spring.application.name= openfeign -logging.level.com.baeldung.cloud.openfeign.client: DEBUG -feign.hystrix.enabled=true - -spring.security.oauth2.client.registration.keycloak.authorization-grant-type=client_credentials -spring.security.oauth2.client.registration.keycloak.client-id=payment-app -spring.security.oauth2.client.registration.keycloak.client-secret=863e9de4-33d4-4471-b35e-f8d2434385bb -spring.security.oauth2.client.provider.keycloak.token-uri=http://localhost:8083/auth/realms/master/protocol/openid-connect/token diff --git a/spring-cloud-modules/spring-cloud-openfeign-2/src/test/java/com/baeldung/cloud/openfeign/SpringContextTest.java b/spring-cloud-modules/spring-cloud-openfeign-2/src/test/java/com/baeldung/cloud/openfeign/SpringContextTest.java deleted file mode 100644 index 4bf35f74f4..0000000000 --- a/spring-cloud-modules/spring-cloud-openfeign-2/src/test/java/com/baeldung/cloud/openfeign/SpringContextTest.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung.cloud.openfeign; - - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = ExampleApplication.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-cloud-modules/spring-cloud-openfeign/README.md b/spring-cloud-modules/spring-cloud-openfeign/README.md index 421fa0284f..62434b35b8 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/README.md +++ b/spring-cloud-modules/spring-cloud-openfeign/README.md @@ -2,9 +2,6 @@ - [Introduction to Spring Cloud OpenFeign](https://www.baeldung.com/spring-cloud-openfeign) - [Differences Between Netflix Feign and OpenFeign](https://www.baeldung.com/netflix-feign-vs-openfeign) -- [File Upload With Open Feign](https://www.baeldung.com/java-feign-file-upload) -- [Feign Logging Configuration](https://www.baeldung.com/java-feign-logging) - [Provide an OAuth2 Token to a Feign Client](https://www.baeldung.com/spring-cloud-feign-oauth-token) -- [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) +- [Feign Client Exception Handling](https://www.baeldung.com/java-feign-client-exception-handling) diff --git a/spring-cloud-modules/spring-cloud-openfeign/pom.xml b/spring-cloud-modules/spring-cloud-openfeign/pom.xml index 570cb6a082..88ad38517b 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/pom.xml +++ b/spring-cloud-modules/spring-cloud-openfeign/pom.xml @@ -61,12 +61,6 @@ spring-boot-starter-test test - - com.github.tomakehurst - wiremock-jre8 - 2.33.2 - test - diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/client/UserClient.java b/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/client/UserClient.java deleted file mode 100644 index 9416bd30f0..0000000000 --- a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/client/UserClient.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.cloud.openfeign.client; - -import com.baeldung.cloud.openfeign.config.FeignConfig; -import org.springframework.cloud.openfeign.FeignClient; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; - -@FeignClient(name = "user-client", url="https://jsonplaceholder.typicode.com", configuration = FeignConfig.class) -public interface UserClient { - - @RequestMapping(value = "/users", method = RequestMethod.GET) - String getUsers(); -} \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/config/RetreiveMessageErrorDecoder.java b/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/config/RetreiveMessageErrorDecoder.java index 09bf8bf54b..5ebd7b6887 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/config/RetreiveMessageErrorDecoder.java +++ b/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/config/RetreiveMessageErrorDecoder.java @@ -12,7 +12,6 @@ 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 = null; diff --git a/spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/FileUploadClientFallbackFactory.java b/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/FileUploadClientFallbackFactory.java similarity index 100% rename from spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/FileUploadClientFallbackFactory.java rename to spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/FileUploadClientFallbackFactory.java diff --git a/spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/FileUploadClientWithFallBack.java b/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/FileUploadClientWithFallBack.java similarity index 100% rename from spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/FileUploadClientWithFallBack.java rename to spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/FileUploadClientWithFallBack.java diff --git a/spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/FileUploadClientWithFallbackFactory.java b/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/FileUploadClientWithFallbackFactory.java similarity index 100% rename from spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/FileUploadClientWithFallbackFactory.java rename to spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/FileUploadClientWithFallbackFactory.java diff --git a/spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/FileUploadClientWithFallbackImpl.java b/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/FileUploadClientWithFallbackImpl.java similarity index 100% rename from spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/FileUploadClientWithFallbackImpl.java rename to spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/FileUploadClientWithFallbackImpl.java diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/UploadResource.java b/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/UploadResource.java index 26e658a7f0..2d5090897d 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/UploadResource.java +++ b/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/UploadResource.java @@ -9,7 +9,7 @@ import feign.Response; public interface UploadResource { - @RequestLine("POST /upload-file") + @RequestLine("POST /upload-error") @Headers("Content-Type: multipart/form-data") Response uploadFile(@Param("file") MultipartFile file); diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/UploadService.java b/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/UploadService.java index c0d1962a71..244a5a2168 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/UploadService.java +++ b/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/UploadService.java @@ -13,20 +13,22 @@ public class UploadService { private static final String HTTP_FILE_UPLOAD_URL = "http://localhost:8081"; @Autowired - private UploadClient client; - + private FileUploadClientWithFallbackFactory fileUploadClient; + @Autowired + private FileUploadClientWithFallBack fileUploadClientWithFallback; + 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 uploadFileWithFallbackFactory(MultipartFile file) { + return fileUploadClient.fileUpload(file); } - - public String uploadFileError(MultipartFile file) { - return client.fileUpload(file); + + public String uploadFileWithFallback(MultipartFile file) { + return fileUploadClientWithFallback.fileUpload(file); } } \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/OpenFeignFileUploadLiveTest.java b/spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/OpenFeignFileUploadLiveTest.java index f558e07491..6396be2453 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/OpenFeignFileUploadLiveTest.java +++ b/spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/OpenFeignFileUploadLiveTest.java @@ -14,6 +14,7 @@ import org.springframework.mock.web.MockMultipartFile; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.multipart.MultipartFile; +import com.baeldung.cloud.openfeign.exception.NotFoundException; import com.baeldung.cloud.openfeign.fileupload.service.UploadService; @RunWith(SpringRunner.class) @@ -25,26 +26,36 @@ public class OpenFeignFileUploadLiveTest { private static String FILE_NAME = "fileupload.txt"; - @Test - public void whenFeignBuilder_thenFileUploadSuccess() throws IOException { + @Test(expected = NotFoundException.class) + public void whenFileUploadClientFallbackFactory_thenFileUploadError() 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)); + uploadService.uploadFileWithFallbackFactory(multipartFile); + } + + @Test(expected = NotFoundException.class) + public void whenFileUploadClientFallback_thenFileUploadError() 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)); + uploadService.uploadFileWithFallback(multipartFile); } - @Test - public void whenAnnotatedFeignClient_thenFileUploadSuccess() throws IOException { + @Test(expected = NotFoundException.class) + public void whenFileUploadWithMannualClient_thenFileUploadError() 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); + uploadService.uploadFileWithManualClient(multipartFile); } } diff --git a/spring-core-4/pom.xml b/spring-core-4/pom.xml index 2874931738..6ba8357a0e 100644 --- a/spring-core-4/pom.xml +++ b/spring-core-4/pom.xml @@ -66,6 +66,11 @@ javax.servlet-api ${servlet-api.version} + + javax.annotation + javax.annotation-api + ${annotation-api.version} + @@ -73,6 +78,8 @@ 2.2.2.RELEASE 4.0.2 4.0.0 + 1.3.2 + 3.3.2 \ No newline at end of file diff --git a/spring-core/pom.xml b/spring-core/pom.xml index d8eaf22220..d1c155b92a 100644 --- a/spring-core/pom.xml +++ b/spring-core/pom.xml @@ -62,6 +62,11 @@ commons-io ${commons-io.version} + + javax.annotation + javax.annotation-api + ${annotation-api.version} + @@ -82,6 +87,8 @@ 1 1.5.2.RELEASE 1.10.19 + 1.3.2 + 3.3.2 \ No newline at end of file diff --git a/spring-drools/pom.xml b/spring-drools/pom.xml index b8c025893c..e13feb6c80 100644 --- a/spring-drools/pom.xml +++ b/spring-drools/pom.xml @@ -39,7 +39,7 @@ org.kie kie-spring - ${drools-version} + ${kie-spring.version} org.springframework @@ -75,7 +75,8 @@ - 7.0.0.Final + 8.34.0.Final + 7.73.0.Final \ No newline at end of file diff --git a/spring-exceptions/pom.xml b/spring-exceptions/pom.xml index 0621009bdd..8912cad674 100644 --- a/spring-exceptions/pom.xml +++ b/spring-exceptions/pom.xml @@ -133,6 +133,11 @@ derbytools ${derby.version} + + javax.xml.bind + jaxb-api + ${jaxb-api.version} + @@ -157,7 +162,7 @@ - 4.3.4.RELEASE + 5.3.25 4.2.0.RELEASE 3.21.0-GA @@ -168,6 +173,7 @@ 5.3.3.Final 2.2 + 2.3.0 4.4.5 4.5.2 @@ -175,6 +181,7 @@ 2.7 1.6.1 + 3.3.2 \ No newline at end of file diff --git a/spring-exceptions/src/main/java/com/baeldung/ex/mappingexception/spring/Cause1PersistenceConfig.java b/spring-exceptions/src/main/java/com/baeldung/ex/mappingexception/spring/Cause1PersistenceConfig.java index d2929e3d91..6a24db6733 100644 --- a/spring-exceptions/src/main/java/com/baeldung/ex/mappingexception/spring/Cause1PersistenceConfig.java +++ b/spring-exceptions/src/main/java/com/baeldung/ex/mappingexception/spring/Cause1PersistenceConfig.java @@ -12,8 +12,8 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; -import org.springframework.orm.hibernate4.HibernateTransactionManager; -import org.springframework.orm.hibernate4.LocalSessionFactoryBean; +import org.springframework.orm.hibernate5.HibernateTransactionManager; +import org.springframework.orm.hibernate5.LocalSessionFactoryBean; import org.springframework.transaction.annotation.EnableTransactionManagement; import com.google.common.base.Preconditions; diff --git a/spring-exceptions/src/main/java/com/baeldung/ex/mappingexception/spring/Cause2PersistenceConfig.java b/spring-exceptions/src/main/java/com/baeldung/ex/mappingexception/spring/Cause2PersistenceConfig.java index 399238073c..a60fa5bc17 100644 --- a/spring-exceptions/src/main/java/com/baeldung/ex/mappingexception/spring/Cause2PersistenceConfig.java +++ b/spring-exceptions/src/main/java/com/baeldung/ex/mappingexception/spring/Cause2PersistenceConfig.java @@ -12,8 +12,8 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; -import org.springframework.orm.hibernate4.HibernateTransactionManager; -import org.springframework.orm.hibernate4.LocalSessionFactoryBean; +import org.springframework.orm.hibernate5.HibernateTransactionManager; +import org.springframework.orm.hibernate5.LocalSessionFactoryBean; import org.springframework.transaction.annotation.EnableTransactionManagement; import com.google.common.base.Preconditions; diff --git a/spring-exceptions/src/main/java/com/baeldung/ex/mappingexception/spring/Cause3PersistenceConfig.java b/spring-exceptions/src/main/java/com/baeldung/ex/mappingexception/spring/Cause3PersistenceConfig.java index f5191d52f2..ee76232323 100644 --- a/spring-exceptions/src/main/java/com/baeldung/ex/mappingexception/spring/Cause3PersistenceConfig.java +++ b/spring-exceptions/src/main/java/com/baeldung/ex/mappingexception/spring/Cause3PersistenceConfig.java @@ -13,8 +13,8 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; -import org.springframework.orm.hibernate4.HibernateTransactionManager; -import org.springframework.orm.hibernate4.LocalSessionFactoryBean; +import org.springframework.orm.hibernate5.HibernateTransactionManager; +import org.springframework.orm.hibernate5.LocalSessionFactoryBean; import org.springframework.transaction.annotation.EnableTransactionManagement; import com.google.common.base.Preconditions; diff --git a/spring-exceptions/src/main/java/com/baeldung/ex/nontransientexception/cause/Cause1NonTransientConfig.java b/spring-exceptions/src/main/java/com/baeldung/ex/nontransientexception/cause/Cause1NonTransientConfig.java index 118cb5da90..6cf905c330 100644 --- a/spring-exceptions/src/main/java/com/baeldung/ex/nontransientexception/cause/Cause1NonTransientConfig.java +++ b/spring-exceptions/src/main/java/com/baeldung/ex/nontransientexception/cause/Cause1NonTransientConfig.java @@ -12,8 +12,8 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; -import org.springframework.orm.hibernate4.HibernateTransactionManager; -import org.springframework.orm.hibernate4.LocalSessionFactoryBean; +import org.springframework.orm.hibernate5.HibernateTransactionManager; +import org.springframework.orm.hibernate5.LocalSessionFactoryBean; import org.springframework.transaction.annotation.EnableTransactionManagement; import com.google.common.base.Preconditions; diff --git a/spring-exceptions/src/main/java/com/baeldung/ex/nontransientexception/cause/Cause4NonTransientConfig.java b/spring-exceptions/src/main/java/com/baeldung/ex/nontransientexception/cause/Cause4NonTransientConfig.java index e79266e9ee..fdad253671 100644 --- a/spring-exceptions/src/main/java/com/baeldung/ex/nontransientexception/cause/Cause4NonTransientConfig.java +++ b/spring-exceptions/src/main/java/com/baeldung/ex/nontransientexception/cause/Cause4NonTransientConfig.java @@ -12,8 +12,8 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; -import org.springframework.orm.hibernate4.HibernateTransactionManager; -import org.springframework.orm.hibernate4.LocalSessionFactoryBean; +import org.springframework.orm.hibernate5.HibernateTransactionManager; +import org.springframework.orm.hibernate5.LocalSessionFactoryBean; import org.springframework.transaction.annotation.EnableTransactionManagement; import com.google.common.base.Preconditions; diff --git a/spring-exceptions/src/main/java/com/baeldung/ex/nontransientexception/cause/Cause5NonTransientConfig.java b/spring-exceptions/src/main/java/com/baeldung/ex/nontransientexception/cause/Cause5NonTransientConfig.java index 784b36afbf..3256b002da 100644 --- a/spring-exceptions/src/main/java/com/baeldung/ex/nontransientexception/cause/Cause5NonTransientConfig.java +++ b/spring-exceptions/src/main/java/com/baeldung/ex/nontransientexception/cause/Cause5NonTransientConfig.java @@ -12,8 +12,8 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; -import org.springframework.orm.hibernate4.HibernateTransactionManager; -import org.springframework.orm.hibernate4.LocalSessionFactoryBean; +import org.springframework.orm.hibernate5.HibernateTransactionManager; +import org.springframework.orm.hibernate5.LocalSessionFactoryBean; import org.springframework.transaction.annotation.EnableTransactionManagement; import com.google.common.base.Preconditions; diff --git a/spring-exceptions/src/main/java/com/baeldung/spring/config/PersistenceConfig.java b/spring-exceptions/src/main/java/com/baeldung/spring/config/PersistenceConfig.java index 0a31b158d9..b2630f5603 100644 --- a/spring-exceptions/src/main/java/com/baeldung/spring/config/PersistenceConfig.java +++ b/spring-exceptions/src/main/java/com/baeldung/spring/config/PersistenceConfig.java @@ -12,8 +12,8 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; -import org.springframework.orm.hibernate4.HibernateTransactionManager; -import org.springframework.orm.hibernate4.LocalSessionFactoryBean; +import org.springframework.orm.hibernate5.HibernateTransactionManager; +import org.springframework.orm.hibernate5.LocalSessionFactoryBean; import org.springframework.transaction.annotation.EnableTransactionManagement; import com.google.common.base.Preconditions; diff --git a/spring-exceptions/src/main/resources/hibernate-mysql.properties b/spring-exceptions/src/main/resources/hibernate-mysql.properties index 49ca7fb3d1..bba27db11b 100644 --- a/spring-exceptions/src/main/resources/hibernate-mysql.properties +++ b/spring-exceptions/src/main/resources/hibernate-mysql.properties @@ -2,6 +2,6 @@ hibernate.connection.username=tutorialuser hibernate.connection.password=tutorialmy5ql hibernate.connection.driver_class=com.mysql.jdbc.Driver hibernate.dialect=org.hibernate.dialect.MySQL5Dialect -hibernate.connection.url=jdbc:mysql://localhost:3306/spring_hibernate4_exceptions?createDatabaseIfNotExist=true +hibernate.connection.url=jdbc:mysql://localhost:3306/spring_hibernate5_exceptions?createDatabaseIfNotExist=true hibernate.show_sql=false hibernate.hbm2ddl.auto=create \ No newline at end of file diff --git a/spring-exceptions/src/main/resources/persistence-mysql-incorrect.properties b/spring-exceptions/src/main/resources/persistence-mysql-incorrect.properties index b5b8095104..142997a974 100644 --- a/spring-exceptions/src/main/resources/persistence-mysql-incorrect.properties +++ b/spring-exceptions/src/main/resources/persistence-mysql-incorrect.properties @@ -1,6 +1,6 @@ # jdbc.X jdbc.driverClassName=com.mysql.jdbc.Driver -jdbc.url=jdbc:mysql:3306://localhost/spring_hibernate4_exceptions?createDatabaseIfNotExist=true +jdbc.url=jdbc:mysql:3306://localhost/spring_hibernate5_exceptions?createDatabaseIfNotExist=true jdbc.user=tutorialuser jdbc.pass=tutorialmy5ql diff --git a/spring-exceptions/src/main/resources/persistence-mysql.properties b/spring-exceptions/src/main/resources/persistence-mysql.properties index af56ce1bf8..5ac477607c 100644 --- a/spring-exceptions/src/main/resources/persistence-mysql.properties +++ b/spring-exceptions/src/main/resources/persistence-mysql.properties @@ -1,6 +1,6 @@ # jdbc.X jdbc.driverClassName=com.mysql.jdbc.Driver -jdbc.url=jdbc:mysql://localhost:3306/spring_hibernate4_exceptions?createDatabaseIfNotExist=true +jdbc.url=jdbc:mysql://localhost:3306/spring_hibernate5_exceptions?createDatabaseIfNotExist=true jdbc.user=tutorialuser jdbc.pass=tutorialmy5ql diff --git a/spring-integration/pom.xml b/spring-integration/pom.xml index 2e0e242a56..9882e02c57 100644 --- a/spring-integration/pom.xml +++ b/spring-integration/pom.xml @@ -37,7 +37,7 @@ org.springframework.integration spring-integration-twitter - ${spring.version} + ${spring-integration-twitter.version} org.springframework.integration @@ -85,6 +85,11 @@ h2 ${h2.version} + + javax.xml.bind + jaxb-api + ${jaxb-api.version} + @@ -114,11 +119,13 @@ - 5.0.13.RELEASE + 5.1.13.RELEASE 1.1.4.RELEASE + 5.0.13.RELEASE 1.4.7 1.1.1 2.10 + 2.3.0 \ No newline at end of file diff --git a/spring-integration/src/main/java/com/baeldung/dsl/JavaDSLFileCopyConfig.java b/spring-integration/src/main/java/com/baeldung/dsl/JavaDSLFileCopyConfig.java index e79eec3e83..adaeac5386 100644 --- a/spring-integration/src/main/java/com/baeldung/dsl/JavaDSLFileCopyConfig.java +++ b/spring-integration/src/main/java/com/baeldung/dsl/JavaDSLFileCopyConfig.java @@ -16,7 +16,7 @@ import org.springframework.integration.core.MessageSource; import org.springframework.integration.dsl.IntegrationFlow; import org.springframework.integration.dsl.IntegrationFlows; import org.springframework.integration.dsl.Pollers; -import org.springframework.integration.dsl.channel.MessageChannels; +import org.springframework.integration.dsl.MessageChannels; import org.springframework.integration.file.FileReadingMessageSource; import org.springframework.integration.file.FileWritingMessageHandler; import org.springframework.messaging.MessageChannel; diff --git a/spring-jersey/pom.xml b/spring-jersey/pom.xml index 32f75aa676..17d527ca6a 100644 --- a/spring-jersey/pom.xml +++ b/spring-jersey/pom.xml @@ -221,6 +221,7 @@ 4.5.5 2.27.2 1.5.10.RELEASE + 3.3.2 \ No newline at end of file diff --git a/spring-kafka/pom.xml b/spring-kafka/pom.xml index d51c2e300f..7b0bb0a8b7 100644 --- a/spring-kafka/pom.xml +++ b/spring-kafka/pom.xml @@ -9,9 +9,9 @@ com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../parent-boot-2 + ../parent-boot-3 @@ -61,8 +61,24 @@ awaitility test + + org.apache.commons + commons-lang3 + + + + + org.springframework.boot + spring-boot-maven-plugin + + com.baeldung.spring.kafka.KafkaApplication + + + + + 1.16.2 diff --git a/spring-kafka/src/main/java/com/baeldung/countingmessages/KafkaCountingMessagesComponent.java b/spring-kafka/src/main/java/com/baeldung/countingmessages/KafkaCountingMessagesComponent.java index 89cd1c8dac..f76be95c1c 100644 --- a/spring-kafka/src/main/java/com/baeldung/countingmessages/KafkaCountingMessagesComponent.java +++ b/spring-kafka/src/main/java/com/baeldung/countingmessages/KafkaCountingMessagesComponent.java @@ -6,7 +6,7 @@ import org.apache.kafka.common.serialization.StringDeserializer; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; -import javax.annotation.PostConstruct; +import jakarta.annotation.PostConstruct; import java.util.Collections; import java.util.HashMap; import java.util.List; diff --git a/spring-kafka/src/main/java/com/baeldung/kafka/ssl/KafkaProducer.java b/spring-kafka/src/main/java/com/baeldung/kafka/ssl/KafkaProducer.java index 895d437c6b..38ce366355 100644 --- a/spring-kafka/src/main/java/com/baeldung/kafka/ssl/KafkaProducer.java +++ b/spring-kafka/src/main/java/com/baeldung/kafka/ssl/KafkaProducer.java @@ -15,9 +15,12 @@ public class KafkaProducer { public void sendMessage(String message, String topic) { log.info("Producing message: {}", message); kafkaTemplate.send(topic, "key", message) - .addCallback( - result -> log.info("Message sent to topic: {}", message), - ex -> log.error("Failed to send message", ex) - ); + .whenComplete((result, ex) -> { + if (ex == null) { + log.info("Message sent to topic: {}", message); + } else { + log.error("Failed to send message", ex); + } + }); } } diff --git a/spring-kafka/src/main/java/com/baeldung/kafka/streams/KafkaProducer.java b/spring-kafka/src/main/java/com/baeldung/kafka/streams/KafkaProducer.java index 2b8e9bbfbd..664758a052 100644 --- a/spring-kafka/src/main/java/com/baeldung/kafka/streams/KafkaProducer.java +++ b/spring-kafka/src/main/java/com/baeldung/kafka/streams/KafkaProducer.java @@ -15,9 +15,12 @@ public class KafkaProducer { public void sendMessage(String message) { kafkaTemplate.send("input-topic", message) - .addCallback( - result -> log.info("Message sent to topic: {}", message), - ex -> log.error("Failed to send message", ex) - ); + .whenComplete((result, ex) -> { + if (ex == null) { + log.info("Message sent to topic: {}", message); + } else { + log.error("Failed to send message", ex); + } + }); } } diff --git a/spring-kafka/src/main/java/com/baeldung/spring/kafka/KafkaApplication.java b/spring-kafka/src/main/java/com/baeldung/spring/kafka/KafkaApplication.java index 9b79f716e9..ff2d21668f 100644 --- a/spring-kafka/src/main/java/com/baeldung/spring/kafka/KafkaApplication.java +++ b/spring-kafka/src/main/java/com/baeldung/spring/kafka/KafkaApplication.java @@ -1,5 +1,6 @@ package com.baeldung.spring.kafka; +import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -16,8 +17,6 @@ import org.springframework.kafka.support.KafkaHeaders; import org.springframework.kafka.support.SendResult; import org.springframework.messaging.handler.annotation.Header; import org.springframework.messaging.handler.annotation.Payload; -import org.springframework.util.concurrent.ListenableFuture; -import org.springframework.util.concurrent.ListenableFutureCallback; @SpringBootApplication public class KafkaApplication { @@ -102,18 +101,13 @@ public class KafkaApplication { public void sendMessage(String message) { - ListenableFuture> future = kafkaTemplate.send(topicName, message); + CompletableFuture> future = kafkaTemplate.send(topicName, message); + future.whenComplete((result, ex) -> { - future.addCallback(new ListenableFutureCallback>() { - - @Override - public void onSuccess(SendResult result) { + if (ex == null) { System.out.println("Sent message=[" + message + "] with offset=[" + result.getRecordMetadata() .offset() + "]"); - } - - @Override - public void onFailure(Throwable ex) { + } else { System.out.println("Unable to send message=[" + message + "] due to : " + ex.getMessage()); } }); @@ -155,13 +149,13 @@ public class KafkaApplication { } @KafkaListener(topics = "${message.topic.name}", containerFactory = "headersKafkaListenerContainerFactory") - public void listenWithHeaders(@Payload String message, @Header(KafkaHeaders.RECEIVED_PARTITION_ID) int partition) { + public void listenWithHeaders(@Payload String message, @Header(KafkaHeaders.RECEIVED_PARTITION) int partition) { System.out.println("Received Message: " + message + " from partition: " + partition); latch.countDown(); } @KafkaListener(topicPartitions = @TopicPartition(topic = "${partitioned.topic.name}", partitions = { "0", "3" }), containerFactory = "partitionsKafkaListenerContainerFactory") - public void listenToPartition(@Payload String message, @Header(KafkaHeaders.RECEIVED_PARTITION_ID) int partition) { + public void listenToPartition(@Payload String message, @Header(KafkaHeaders.RECEIVED_PARTITION) int partition) { System.out.println("Received Message: " + message + " from partition: " + partition); this.partitionLatch.countDown(); } diff --git a/spring-kafka/src/test/java/com/baeldung/kafka/streams/KafkaStreamsApplicationLiveTest.java b/spring-kafka/src/test/java/com/baeldung/kafka/streams/KafkaStreamsApplicationLiveTest.java index 85df8485d2..aee3c2c0dc 100644 --- a/spring-kafka/src/test/java/com/baeldung/kafka/streams/KafkaStreamsApplicationLiveTest.java +++ b/spring-kafka/src/test/java/com/baeldung/kafka/streams/KafkaStreamsApplicationLiveTest.java @@ -20,7 +20,7 @@ import org.junit.jupiter.api.io.TempDir; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; diff --git a/spring-reactive-modules/spring-5-reactive-client/pom.xml b/spring-reactive-modules/spring-5-reactive-client/pom.xml index 16581d53af..a0e5f7794e 100644 --- a/spring-reactive-modules/spring-5-reactive-client/pom.xml +++ b/spring-reactive-modules/spring-5-reactive-client/pom.xml @@ -136,14 +136,6 @@ JAR - - org.apache.maven.plugins - maven-compiler-plugin - - 1.8 - 1.8 - - @@ -189,7 +181,7 @@ 1.0 1.1.6 4.0.1 - 3.2.10.RELEASE + 3.5.3 2.26.0 diff --git a/spring-reactive-modules/spring-5-reactive-client/src/test/java/com/baeldung/reactive/logging/WebClientLoggingIntegrationTest.java b/spring-reactive-modules/spring-5-reactive-client/src/test/java/com/baeldung/reactive/logging/WebClientLoggingIntegrationTest.java index dabfd22056..e1eefe4d61 100644 --- a/spring-reactive-modules/spring-5-reactive-client/src/test/java/com/baeldung/reactive/logging/WebClientLoggingIntegrationTest.java +++ b/spring-reactive-modules/spring-5-reactive-client/src/test/java/com/baeldung/reactive/logging/WebClientLoggingIntegrationTest.java @@ -49,7 +49,7 @@ public class WebClientLoggingIntegrationTest { private String sampleResponseBody; @BeforeEach - private void setup() throws Exception { + void setup() throws Exception { post = new Post("Learn WebClient logging with Baeldung!", "", 1); sampleResponseBody = new ObjectMapper().writeValueAsString(post); diff --git a/spring-reactive-modules/spring-reactive/src/main/java/com/baeldung/reactive/webflux/annotation/EmployeeController.java b/spring-reactive-modules/spring-reactive/src/main/java/com/baeldung/reactive/webflux/annotation/EmployeeController.java index 23aacfdd95..646a93ac48 100644 --- a/spring-reactive-modules/spring-reactive/src/main/java/com/baeldung/reactive/webflux/annotation/EmployeeController.java +++ b/spring-reactive-modules/spring-reactive/src/main/java/com/baeldung/reactive/webflux/annotation/EmployeeController.java @@ -22,17 +22,17 @@ public class EmployeeController { } @GetMapping("/{id}") - private Mono getEmployeeById(@PathVariable String id) { + public Mono getEmployeeById(@PathVariable String id) { return employeeRepository.findEmployeeById(id); } @GetMapping - private Flux getAllEmployees() { + public Flux getAllEmployees() { return employeeRepository.findAllEmployees(); } @PostMapping("/update") - private Mono updateEmployee(@RequestBody Employee employee) { + public Mono updateEmployee(@RequestBody Employee employee) { return employeeRepository.updateEmployee(employee); } diff --git a/spring-security-modules/pom.xml b/spring-security-modules/pom.xml index d6e30e8ab8..223f0894d5 100644 --- a/spring-security-modules/pom.xml +++ b/spring-security-modules/pom.xml @@ -49,6 +49,7 @@ spring-security-web-x509 spring-security-opa spring-security-pkce + spring-security-azuread \ No newline at end of file diff --git a/spring-security-modules/spring-security-azuread/README.md b/spring-security-modules/spring-security-azuread/README.md new file mode 100644 index 0000000000..8b4d6d9666 --- /dev/null +++ b/spring-security-modules/spring-security-azuread/README.md @@ -0,0 +1,2 @@ +## Relevant Articles +- [Authenticating Users with AzureAD in Spring Boot](https://www.baeldung.com/spring-boot-azuerad-authenticate-users) diff --git a/spring-security-modules/spring-security-azuread/pom.xml b/spring-security-modules/spring-security-azuread/pom.xml new file mode 100644 index 0000000000..c4dbbd14b9 --- /dev/null +++ b/spring-security-modules/spring-security-azuread/pom.xml @@ -0,0 +1,76 @@ + + + + 4.0.0 + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + spring-security-azuread + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-oauth2-client + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.boot + spring-boot-starter + + + org.springframework.boot + spring-boot-devtools + runtime + true + + + org.springframework.boot + spring-boot-configuration-processor + true + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + \ No newline at end of file diff --git a/spring-security-modules/spring-security-azuread/src/main/java/com/baeldung/security/azuread/Application.java b/spring-security-modules/spring-security-azuread/src/main/java/com/baeldung/security/azuread/Application.java new file mode 100644 index 0000000000..ac36bc1328 --- /dev/null +++ b/spring-security-modules/spring-security-azuread/src/main/java/com/baeldung/security/azuread/Application.java @@ -0,0 +1,14 @@ +package com.baeldung.security.azuread; + +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/spring-security-modules/spring-security-azuread/src/main/java/com/baeldung/security/azuread/config/JwtAuthorizationConfiguration.java b/spring-security-modules/spring-security-azuread/src/main/java/com/baeldung/security/azuread/config/JwtAuthorizationConfiguration.java new file mode 100644 index 0000000000..4d82e930ae --- /dev/null +++ b/spring-security-modules/spring-security-azuread/src/main/java/com/baeldung/security/azuread/config/JwtAuthorizationConfiguration.java @@ -0,0 +1,72 @@ +package com.baeldung.security.azuread.config; + +import java.util.HashSet; +import java.util.Set; + +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest; +import org.springframework.security.oauth2.client.oidc.userinfo.OidcUserService; +import org.springframework.security.oauth2.client.registration.ClientRegistration.ProviderDetails; +import org.springframework.security.oauth2.client.userinfo.OAuth2UserService; +import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser; +import org.springframework.security.oauth2.core.oidc.user.OidcUser; +import org.springframework.security.web.SecurityFilterChain; + +import com.baeldung.security.azuread.support.GroupsClaimMapper; +import com.baeldung.security.azuread.support.NamedOidcUser; + +@Configuration +@EnableConfigurationProperties(JwtAuthorizationProperties.class) +public class JwtAuthorizationConfiguration { + + + + @Bean + SecurityFilterChain customJwtSecurityChain(HttpSecurity http, JwtAuthorizationProperties props) throws Exception { + // @formatter:off + return http + .authorizeRequests( r -> r.anyRequest().authenticated()) + .oauth2Login(oauth2 -> { + oauth2.userInfoEndpoint(ep -> + ep.oidcUserService(customOidcUserService(props))); + }) + .build(); + // @formatter:on + } + + private OAuth2UserService customOidcUserService(JwtAuthorizationProperties props) { + final OidcUserService delegate = new OidcUserService(); + final GroupsClaimMapper mapper = new GroupsClaimMapper( + props.getAuthoritiesPrefix(), + props.getGroupsClaim(), + props.getGroupToAuthorities()); + + return (userRequest) -> { + OidcUser oidcUser = delegate.loadUser(userRequest); + // Enrich standard authorities with groups + Set mappedAuthorities = new HashSet<>(); + mappedAuthorities.addAll(oidcUser.getAuthorities()); + mappedAuthorities.addAll(mapper.mapAuthorities(oidcUser)); + + oidcUser = new NamedOidcUser(mappedAuthorities, oidcUser.getIdToken(), oidcUser.getUserInfo(),oidcUser.getName()); + + return oidcUser; + }; + } + + + +// @Bean +// GrantedAuthoritiesMapper jwtAuthoritiesMapper(JwtAuthorizationProperties props) { +// return new MappingJwtGrantedAuthoritiesMapper( +// props.getAuthoritiesPrefix(), +// props.getGroupsClaim(), +// props.getGroupToAuthorities()); +// } + + +} diff --git a/spring-security-modules/spring-security-azuread/src/main/java/com/baeldung/security/azuread/config/JwtAuthorizationProperties.java b/spring-security-modules/spring-security-azuread/src/main/java/com/baeldung/security/azuread/config/JwtAuthorizationProperties.java new file mode 100644 index 0000000000..981be317a3 --- /dev/null +++ b/spring-security-modules/spring-security-azuread/src/main/java/com/baeldung/security/azuread/config/JwtAuthorizationProperties.java @@ -0,0 +1,68 @@ +package com.baeldung.security.azuread.config; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +/** + * @author Baeldung + * + */ +@ConfigurationProperties(prefix="baeldung.jwt.authorization") +public class JwtAuthorizationProperties { + + // Claim that has the group list + private String groupsClaim = "groups"; + + private String authoritiesPrefix = "ROLE_"; + + // map groupIds to a list of authorities. + private Map> groupToAuthorities = new HashMap<>(); + + /** + * @return the groupsClaim + */ + public String getGroupsClaim() { + return groupsClaim; + } + + /** + * @param groupsClaim the groupsClaim to set + */ + public void setGroupsClaim(String groupsClaim) { + this.groupsClaim = groupsClaim; + } + + /** + * @return the groupToAuthorities + */ + public Map> getGroupToAuthorities() { + return groupToAuthorities; + } + + /** + * @param groupToAuthorities the groupToAuthorities to set + */ + public void setGroupToAuthorities(Map> groupToAuthorities) { + this.groupToAuthorities = groupToAuthorities; + } + + /** + * @return the authoritiesPrefix + */ + public String getAuthoritiesPrefix() { + return authoritiesPrefix; + } + + /** + * @param authoritiesPrefix the authoritiesPrefix to set + */ + public void setAuthoritiesPrefix(String authoritiesPrefix) { + this.authoritiesPrefix = authoritiesPrefix; + } + + + +} diff --git a/spring-security-modules/spring-security-azuread/src/main/java/com/baeldung/security/azuread/controllers/IndexController.java b/spring-security-modules/spring-security-azuread/src/main/java/com/baeldung/security/azuread/controllers/IndexController.java new file mode 100644 index 0000000000..d2cebd0231 --- /dev/null +++ b/spring-security-modules/spring-security-azuread/src/main/java/com/baeldung/security/azuread/controllers/IndexController.java @@ -0,0 +1,22 @@ +package com.baeldung.security.azuread.controllers; + +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; + +import lombok.extern.slf4j.Slf4j; + +@Controller +@RequestMapping("/") +@Slf4j +public class IndexController { + + @GetMapping + public String index(Model model, Authentication user) { + log.info("GET /: user={}", user); + model.addAttribute("user", user); + return "index"; + } +} diff --git a/spring-security-modules/spring-security-azuread/src/main/java/com/baeldung/security/azuread/support/GroupsClaimMapper.java b/spring-security-modules/spring-security-azuread/src/main/java/com/baeldung/security/azuread/support/GroupsClaimMapper.java new file mode 100644 index 0000000000..2487cd9db3 --- /dev/null +++ b/spring-security-modules/spring-security-azuread/src/main/java/com/baeldung/security/azuread/support/GroupsClaimMapper.java @@ -0,0 +1,61 @@ +/** + * + */ +package com.baeldung.security.azuread.support; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.springframework.core.convert.converter.Converter; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper; +import org.springframework.security.oauth2.core.ClaimAccessor; +import org.springframework.security.oauth2.jwt.Jwt; + +/** + * @author Baeldung + * + */ +public class GroupsClaimMapper { + + private final String authoritiesPrefix; + private final String groupsClaim; + private final Map> groupToAuthorities; + + public GroupsClaimMapper(String authoritiesPrefix, String groupsClaim, Map> groupToAuthorities) { + this.authoritiesPrefix = authoritiesPrefix; + this.groupsClaim = groupsClaim; + this.groupToAuthorities = Collections.unmodifiableMap(groupToAuthorities); + } + + public Collection mapAuthorities(ClaimAccessor source) { + + List groups = source.getClaimAsStringList(groupsClaim); + if ( groups == null || groups.isEmpty()) { + return Collections.emptyList(); + } + + List result = new ArrayList<>(); + for( String g : groups) { + List authNames = groupToAuthorities.get(g); + if ( authNames == null ) { + continue; + } + + List mapped = authNames.stream() + .map( s -> authoritiesPrefix + s) + .map( SimpleGrantedAuthority::new) + .collect(Collectors.toList()); + + result.addAll(mapped); + } + + return result; + } + +} diff --git a/spring-security-modules/spring-security-azuread/src/main/java/com/baeldung/security/azuread/support/NamedOidcUser.java b/spring-security-modules/spring-security-azuread/src/main/java/com/baeldung/security/azuread/support/NamedOidcUser.java new file mode 100644 index 0000000000..b29b04fe7b --- /dev/null +++ b/spring-security-modules/spring-security-azuread/src/main/java/com/baeldung/security/azuread/support/NamedOidcUser.java @@ -0,0 +1,24 @@ +package com.baeldung.security.azuread.support; + +import java.util.Collection; + +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.oauth2.core.oidc.OidcIdToken; +import org.springframework.security.oauth2.core.oidc.OidcUserInfo; +import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser; + +public class NamedOidcUser extends DefaultOidcUser { + private static final long serialVersionUID = 1L; + private final String userName; + + public NamedOidcUser(Collection authorities, OidcIdToken idToken, + OidcUserInfo userInfo, String userName) { + super(authorities,idToken,userInfo); + this.userName= userName; + } + + @Override + public String getName() { + return this.userName; + } +} diff --git a/spring-security-modules/spring-security-azuread/src/main/resources/application-azuread.yml b/spring-security-modules/spring-security-azuread/src/main/resources/application-azuread.yml new file mode 100644 index 0000000000..5e65c381c8 --- /dev/null +++ b/spring-security-modules/spring-security-azuread/src/main/resources/application-azuread.yml @@ -0,0 +1,27 @@ +spring: + security: + oauth2: + client: + provider: + azure: + issuer-uri: https://login.microsoftonline.com/2e9fde3a-38ec-44f9-8bcd-c184dc1e8033/v2.0 + user-name-attribute: name + registration: + azure-dev: + provider: azure + #client-id: "6035bfd4-22f0-437c-b76f-da729a916cbf" + #client-secret: "fo28Q~-aLbmQvonnZtzbgtSiqYstmBWEmGPAodmx" + client-id: your-client-id + client-secret: your-secret-id + scope: + - openid + - email + - profile + +# Group mapping +baeldung: + jwt: + authorization: + group-to-authorities: + "ceef656a-fca9-49b6-821b-f7543b7065cb": BAELDUNG_RW + "eaaecb69-ccbc-4143-b111-7dd1ce1d99f1": BAELDUNG_RO,BAELDUNG_ADMIN \ No newline at end of file diff --git a/spring-security-modules/spring-security-azuread/src/main/resources/application.properties b/spring-security-modules/spring-security-azuread/src/main/resources/application.properties new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/spring-security-modules/spring-security-azuread/src/main/resources/application.properties @@ -0,0 +1 @@ + diff --git a/spring-security-modules/spring-security-azuread/src/main/resources/templates/index.html b/spring-security-modules/spring-security-azuread/src/main/resources/templates/index.html new file mode 100644 index 0000000000..ca9a9bdbe8 --- /dev/null +++ b/spring-security-modules/spring-security-azuread/src/main/resources/templates/index.html @@ -0,0 +1,53 @@ + + + + +Insert title here + + + +

Hello, NOMO_NOMO

+ +

User info:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
AttributeValue
Nameuser.name
Classuser.class
Principal Classuser.principal.class
isAuthenticated?user.authenticated
clientRegistrationIduser.authorizedClientregistrationId
Claim: keyvalue
Granted Authority: authority
+ + \ No newline at end of file diff --git a/spring-security-modules/spring-security-azuread/src/test/java/com/baeldung/security/azuread/ApplicationLiveTest.java b/spring-security-modules/spring-security-azuread/src/test/java/com/baeldung/security/azuread/ApplicationLiveTest.java new file mode 100644 index 0000000000..8c941aa787 --- /dev/null +++ b/spring-security-modules/spring-security-azuread/src/test/java/com/baeldung/security/azuread/ApplicationLiveTest.java @@ -0,0 +1,62 @@ +package com.baeldung.security.azuread; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.*; + +import java.net.URI; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.boot.test.web.server.LocalServerPort; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.ActiveProfiles; + +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) +@ActiveProfiles("azuread") +class ApplicationLiveTest { + + @Autowired + TestRestTemplate rest; + + @LocalServerPort + int port; + + @Test + void testWhenAccessRootPath_thenRedirectToAzureAD() { + + ResponseEntity response = rest.getForEntity("http://localhost:" + port , String.class); + HttpStatus st = response.getStatusCode(); + assertThat(st) + .isEqualTo(HttpStatus.FOUND); + + URI location1 = response.getHeaders().getLocation(); + assertThat(location1) + .isNotNull(); + assertThat(location1.getPath()) + .isEqualTo("/oauth2/authorization/azure-dev"); + + assertThat(location1.getPort()) + .isEqualTo(port); + + assertThat(location1.getHost()) + .isEqualTo("localhost"); + + // Now let't follow this redirect + response = rest.getForEntity(location1, String.class); + assertThat(st) + .isEqualTo(HttpStatus.FOUND); + URI location2 = response.getHeaders().getLocation(); + assertThat(location2) + .isNotNull(); + + assertThat(location2.getHost()) + .describedAs("Should redirect to AzureAD") + .isEqualTo("login.microsoftonline.com"); + + } + +} diff --git a/spring-security-modules/spring-security-azuread/src/test/java/com/baeldung/security/azuread/support/GroupsClaimMapperUnitTest.java b/spring-security-modules/spring-security-azuread/src/test/java/com/baeldung/security/azuread/support/GroupsClaimMapperUnitTest.java new file mode 100644 index 0000000000..0a8f85d0d1 --- /dev/null +++ b/spring-security-modules/spring-security-azuread/src/test/java/com/baeldung/security/azuread/support/GroupsClaimMapperUnitTest.java @@ -0,0 +1,48 @@ +package com.baeldung.security.azuread.support; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.jupiter.api.Test; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.oauth2.core.ClaimAccessor; + +class GroupsClaimMapperUnitTest { + + private Map> g2a = new HashMap<>(); + + @Test + void testWhenNoGroupClaimsPresent_thenNoAuthoritiesAdded() { + + ClaimAccessor source = mock(ClaimAccessor.class); + GroupsClaimMapper mapper = new GroupsClaimMapper("ROLE", "group", g2a); + + Collection authorities = mapper.mapAuthorities(source); + assertThat(authorities) + .isNotNull() + .isEmpty(); + } + + @Test + void testWhenEmptyGroupClaimsPresent_thenNoAuthoritiesAdded() { + + ClaimAccessor source = mock(ClaimAccessor.class); + when(source.getClaimAsStringList("group")) + .thenReturn(Collections.emptyList()); + + GroupsClaimMapper mapper = new GroupsClaimMapper("ROLE", "group", g2a); + + Collection authorities = mapper.mapAuthorities(source); + assertThat(authorities) + .isNotNull() + .isEmpty(); + } + +} diff --git a/spring-security-modules/spring-security-oauth2-testing/pom.xml b/spring-security-modules/spring-security-oauth2-testing/pom.xml new file mode 100644 index 0000000000..93348cb48c --- /dev/null +++ b/spring-security-modules/spring-security-oauth2-testing/pom.xml @@ -0,0 +1,32 @@ + + + 4.0.0 + spring-security-oauth2-testing + spring-security-oauth2-testing + pom + spring-security 6 oauth testing sample project + + com.baeldung + parent-boot-3 + 0.0.1-SNAPSHOT + ../../parent-boot-3 + + + 6.1.0 + + + + + com.c4-soft.springaddons + spring-addons-oauth2-test + ${spring-addons.version} + + + + + reactive-resource-server + servlet-resource-server + + \ No newline at end of file diff --git a/spring-security-modules/spring-security-oauth2-testing/reactive-resource-server/pom.xml b/spring-security-modules/spring-security-oauth2-testing/reactive-resource-server/pom.xml new file mode 100644 index 0000000000..86f73cfdbf --- /dev/null +++ b/spring-security-modules/spring-security-oauth2-testing/reactive-resource-server/pom.xml @@ -0,0 +1,58 @@ + + + 4.0.0 + + com.baeldung + spring-security-oauth2-testing + 0.0.1-SNAPSHOT + + com.baeldung.spring-security-modules.testing + reactive-resource-server + reactive-resource-server + Demo project for Spring Boot reactive resource-server + + 17 + + + + org.springframework.boot + spring-boot-starter-oauth2-resource-server + + + org.springframework.boot + spring-boot-starter-webflux + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + com.c4-soft.springaddons + spring-addons-oauth2-test + test + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + \ No newline at end of file diff --git a/spring-security-modules/spring-security-oauth2-testing/reactive-resource-server/src/main/java/com/baeldung/ReactiveResourceServerApplication.java b/spring-security-modules/spring-security-oauth2-testing/reactive-resource-server/src/main/java/com/baeldung/ReactiveResourceServerApplication.java new file mode 100644 index 0000000000..500d876bc4 --- /dev/null +++ b/spring-security-modules/spring-security-oauth2-testing/reactive-resource-server/src/main/java/com/baeldung/ReactiveResourceServerApplication.java @@ -0,0 +1,144 @@ +package com.baeldung; + +import java.nio.charset.Charset; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.convert.converter.Converter; +import org.springframework.core.io.buffer.DataBufferUtils; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.security.authentication.AnonymousAuthenticationToken; +import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException; +import org.springframework.security.config.annotation.method.configuration.EnableReactiveMethodSecurity; +import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity; +import org.springframework.security.config.web.server.ServerHttpSecurity; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.context.ReactiveSecurityContextHolder; +import org.springframework.security.oauth2.core.oidc.StandardClaimNames; +import org.springframework.security.oauth2.jwt.Jwt; +import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken; +import org.springframework.security.web.server.SecurityWebFilterChain; +import org.springframework.security.web.server.context.NoOpServerSecurityContextRepository; +import org.springframework.stereotype.Service; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import lombok.RequiredArgsConstructor; +import reactor.core.publisher.Mono; + +@SpringBootApplication +public class ReactiveResourceServerApplication { + + public static void main(String[] args) { + SpringApplication.run(ReactiveResourceServerApplication.class, args); + } + + @Configuration + @EnableWebFluxSecurity + @EnableReactiveMethodSecurity + public class SecurityConfig { + @Bean + SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http, Converter>> authoritiesConverter) { + http.oauth2ResourceServer() + .jwt() + .jwtAuthenticationConverter(jwt -> authoritiesConverter.convert(jwt) + .map(authorities -> new JwtAuthenticationToken(jwt, authorities))); + http.securityContextRepository(NoOpServerSecurityContextRepository.getInstance()) + .csrf() + .disable(); + http.exceptionHandling() + .accessDeniedHandler((var exchange, var ex) -> exchange.getPrincipal() + .flatMap(principal -> { + final var response = exchange.getResponse(); + response.setStatusCode(principal instanceof AnonymousAuthenticationToken ? HttpStatus.UNAUTHORIZED : HttpStatus.FORBIDDEN); + response.getHeaders() + .setContentType(MediaType.TEXT_PLAIN); + final var dataBufferFactory = response.bufferFactory(); + final var buffer = dataBufferFactory.wrap(ex.getMessage() + .getBytes(Charset.defaultCharset())); + return response.writeWith(Mono.just(buffer)) + .doOnError(error -> DataBufferUtils.release(buffer)); + })); + + http.authorizeExchange() + .pathMatchers("/secured-route") + .hasRole("AUTHORIZED_PERSONNEL") + .anyExchange() + .authenticated(); + + return http.build(); + } + + static interface AuthoritiesConverter extends Converter>> { + } + + @Bean + AuthoritiesConverter realmRoles2AuthoritiesConverter() { + return (Jwt jwt) -> { + final var realmRoles = Optional.of(jwt.getClaimAsMap("realm_access")) + .orElse(Map.of()); + @SuppressWarnings("unchecked") + final var roles = (List) realmRoles.getOrDefault("roles", List.of()); + return Mono.just(roles.stream() + .map(SimpleGrantedAuthority::new) + .map(GrantedAuthority.class::cast) + .toList()); + }; + } + } + + @Service + public static class MessageService { + + public Mono greet() { + return ReactiveSecurityContextHolder.getContext() + .map(ctx -> { + final var who = (JwtAuthenticationToken) ctx.getAuthentication(); + final var claims = who.getTokenAttributes(); + return "Hello %s! You are granted with %s.".formatted(claims.getOrDefault(StandardClaimNames.PREFERRED_USERNAME, claims.get(StandardClaimNames.SUB)), who.getAuthorities()); + }) + .switchIfEmpty(Mono.error(new AuthenticationCredentialsNotFoundException("Security context is empty"))); + } + + @PreAuthorize("hasRole('AUTHORIZED_PERSONNEL')") + public Mono getSecret() { + return Mono.just("Only authorized personnel can read that"); + } + } + + @RestController + @RequiredArgsConstructor + public class GreetingController { + private final MessageService messageService; + + @GetMapping("/greet") + public Mono> greet() { + return messageService.greet() + .map(ResponseEntity::ok); + } + + @GetMapping("/secured-route") + public Mono> securedRoute() { + return messageService.getSecret() + .map(ResponseEntity::ok); + } + + @GetMapping("/secured-method") + @PreAuthorize("hasRole('AUTHORIZED_PERSONNEL')") + public Mono> securedMethod() { + return messageService.getSecret() + .map(ResponseEntity::ok); + } + } + +} diff --git a/spring-security-modules/spring-security-oauth2-testing/reactive-resource-server/src/main/resources/application.yaml b/spring-security-modules/spring-security-oauth2-testing/reactive-resource-server/src/main/resources/application.yaml new file mode 100644 index 0000000000..01e655e1b3 --- /dev/null +++ b/spring-security-modules/spring-security-oauth2-testing/reactive-resource-server/src/main/resources/application.yaml @@ -0,0 +1,6 @@ +spring: + security: + oauth2: + resourceserver: + jwt: + issuer-uri: https://localhost:8443/realms/master diff --git a/spring-security-modules/spring-security-oauth2-testing/reactive-resource-server/src/test/java/com/baeldung/MessageServiceUnitTest.java b/spring-security-modules/spring-security-oauth2-testing/reactive-resource-server/src/test/java/com/baeldung/MessageServiceUnitTest.java new file mode 100644 index 0000000000..97893bc1fb --- /dev/null +++ b/spring-security-modules/spring-security-oauth2-testing/reactive-resource-server/src/test/java/com/baeldung/MessageServiceUnitTest.java @@ -0,0 +1,86 @@ +package com.baeldung; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Import; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException; +import org.springframework.security.config.annotation.method.configuration.EnableReactiveMethodSecurity; +import org.springframework.security.test.context.support.WithAnonymousUser; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import com.baeldung.ReactiveResourceServerApplication.MessageService; +import com.c4_soft.springaddons.security.oauth2.test.annotations.OpenIdClaims; +import com.c4_soft.springaddons.security.oauth2.test.annotations.WithMockJwtAuth; + +@Import({ MessageService.class }) +@ExtendWith(SpringExtension.class) +@EnableReactiveMethodSecurity +class MessageServiceUnitTest { + @Autowired + MessageService messageService; + + /*----------------------------------------------------------------------------*/ + /* greet() */ + /* Expects a JwtAuthenticationToken to be retrieved from the security-context */ + /*----------------------------------------------------------------------------*/ + + @Test + void givenSecurityContextIsEmpty_whenGreet_thenThrowsAuthenticationCredentialsNotFoundException() { + assertThrows(AuthenticationCredentialsNotFoundException.class, () -> messageService.greet() + .block()); + } + + @Test + @WithAnonymousUser + void givenUserIsAnonymous_whenGreet_thenThrowsClassCastException() { + assertThrows(ClassCastException.class, () -> messageService.greet() + .block()); + } + + @Test + @WithMockJwtAuth(authorities = { "admin", "ROLE_AUTHORIZED_PERSONNEL" }, claims = @OpenIdClaims(preferredUsername = "ch4mpy")) + void givenSecurityContextIsPopulatedWithJwtAuthenticationToken_whenGreet_thenReturnGreetingWithPreferredUsernameAndAuthorities() { + assertEquals("Hello ch4mpy! You are granted with [admin, ROLE_AUTHORIZED_PERSONNEL].", messageService.greet() + .block()); + } + + @Test + @WithMockUser(authorities = { "admin", "ROLE_AUTHORIZED_PERSONNEL" }, username = "ch4mpy") + void givenSecurityContextIsPopulatedWithUsernamePasswordAuthenticationToken_whenGreet_thenThrowsClassCastException() { + assertThrows(ClassCastException.class, () -> messageService.greet() + .block()); + } + + /*--------------------------------------------------------------------*/ + /* getSecret() */ + /* is secured with "@PreAuthorize("hasRole('AUTHORIZED_PERSONNEL')")" */ + /*--------------------------------------------------------------------*/ + + @Test + @WithAnonymousUser + void givenUserIsAnonymous_whenGetSecret_thenThrowsAccessDeniedException() { + assertThrows(AccessDeniedException.class, () -> messageService.getSecret() + .block()); + } + + @Test + @WithMockJwtAuth(authorities = { "admin", "ROLE_AUTHORIZED_PERSONNEL" }, claims = @OpenIdClaims(preferredUsername = "ch4mpy")) + void givenUserIsGrantedWithRoleAuthorizedPersonnel_whenGetSecret_thenReturnSecret() { + assertEquals("Only authorized personnel can read that", messageService.getSecret() + .block()); + } + + @Test + @WithMockJwtAuth(authorities = { "admin" }, claims = @OpenIdClaims(preferredUsername = "ch4mpy")) + void givenUserIsNotGrantedWithRoleAuthorizedPersonnel_whenGetSecret_thenThrowsAccessDeniedException() { + assertThrows(AccessDeniedException.class, () -> messageService.getSecret() + .block()); + } + +} diff --git a/spring-security-modules/spring-security-oauth2-testing/reactive-resource-server/src/test/java/com/baeldung/ReactiveResourceServerApplicationIntegrationTest.java b/spring-security-modules/spring-security-oauth2-testing/reactive-resource-server/src/test/java/com/baeldung/ReactiveResourceServerApplicationIntegrationTest.java new file mode 100644 index 0000000000..1ee6fc7e87 --- /dev/null +++ b/spring-security-modules/spring-security-oauth2-testing/reactive-resource-server/src/test/java/com/baeldung/ReactiveResourceServerApplicationIntegrationTest.java @@ -0,0 +1,120 @@ +package com.baeldung; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.security.test.context.support.WithAnonymousUser; +import org.springframework.test.web.reactive.server.WebTestClient; + +import com.c4_soft.springaddons.security.oauth2.test.annotations.OpenIdClaims; +import com.c4_soft.springaddons.security.oauth2.test.annotations.WithMockJwtAuth; + +@SpringBootTest(webEnvironment = WebEnvironment.MOCK) +@AutoConfigureWebTestClient +class ReactiveResourceServerApplicationIntegrationTest { + @Autowired + WebTestClient api; + + /*-----------------------------------------------------------------------------*/ + /* /greet */ + /* This end-point secured with ".anyRequest().authenticated()" in SecurityConf */ + /*-----------------------------------------------------------------------------*/ + + @Test + @WithAnonymousUser + void givenRequestIsAnonymous_whenGetGreet_thenUnauthorized() throws Exception { + api.get() + .uri("/greet") + .exchange() + .expectStatus() + .isUnauthorized(); + } + + @Test + @WithMockJwtAuth(authorities = { "admin", "ROLE_AUTHORIZED_PERSONNEL" }, claims = @OpenIdClaims(preferredUsername = "ch4mpy")) + void givenUserIsAuthenticated_whenGetGreet_thenOk() throws Exception { + api.get() + .uri("/greet") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("Hello ch4mpy! You are granted with [admin, ROLE_AUTHORIZED_PERSONNEL]."); + } + + /*---------------------------------------------------------------------------------------------------------------------*/ + /* /secured-route */ + /* This end-point is secured with ".requestMatchers("/secured-route").hasRole("AUTHORIZED_PERSONNEL")" in SecurityConf */ + /*---------------------------------------------------------------------------------------------------------------------*/ + + @Test + @WithAnonymousUser + void givenRequestIsAnonymous_whenGetSecuredRoute_thenUnauthorized() throws Exception { + api.get() + .uri("/secured-route") + .exchange() + .expectStatus() + .isUnauthorized(); + } + + @Test + @WithMockJwtAuth("ROLE_AUTHORIZED_PERSONNEL") + void givenUserIsGrantedWithRoleAuthorizedPersonnel_whenGetSecuredRoute_thenOk() throws Exception { + api.get() + .uri("/secured-route") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("Only authorized personnel can read that"); + } + + @Test + @WithMockJwtAuth("admin") + void givenUserIsNotGrantedWithRoleAuthorizedPersonnel_whenGetSecuredRoute_thenForbidden() throws Exception { + api.get() + .uri("/secured-route") + .exchange() + .expectStatus() + .isForbidden(); + } + + /*---------------------------------------------------------------------------------------------------------*/ + /* /secured-method */ + /* This end-point is secured with "@PreAuthorize("hasRole('AUTHORIZED_PERSONNEL')")" on @Controller method */ + /*---------------------------------------------------------------------------------------------------------*/ + + @Test + @WithAnonymousUser + void givenRequestIsAnonymous_whenGetSecuredMethod_thenUnauthorized() throws Exception { + api.get() + .uri("/secured-method") + .exchange() + .expectStatus() + .isUnauthorized(); + } + + @Test + @WithMockJwtAuth("ROLE_AUTHORIZED_PERSONNEL") + void givenUserIsGrantedWithRoleAuthorizedPersonnel_whenGetSecuredMethod_thenOk() throws Exception { + api.get() + .uri("/secured-method") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo("Only authorized personnel can read that"); + } + + @Test + @WithMockJwtAuth("admin") + void givenUserIsNotGrantedWithRoleAuthorizedPersonnel_whenGetSecuredMethod_thenForbidden() throws Exception { + api.get() + .uri("/secured-method") + .exchange() + .expectStatus() + .isForbidden(); + } +} diff --git a/spring-security-modules/spring-security-oauth2-testing/reactive-resource-server/src/test/java/com/baeldung/SpringAddonsGreetingControllerUnitTest.java b/spring-security-modules/spring-security-oauth2-testing/reactive-resource-server/src/test/java/com/baeldung/SpringAddonsGreetingControllerUnitTest.java new file mode 100644 index 0000000000..6f55f287d8 --- /dev/null +++ b/spring-security-modules/spring-security-oauth2-testing/reactive-resource-server/src/test/java/com/baeldung/SpringAddonsGreetingControllerUnitTest.java @@ -0,0 +1,142 @@ +package com.baeldung; + +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.security.test.context.support.WithAnonymousUser; +import org.springframework.test.web.reactive.server.WebTestClient; + +import com.baeldung.ReactiveResourceServerApplication.GreetingController; +import com.baeldung.ReactiveResourceServerApplication.MessageService; +import com.c4_soft.springaddons.security.oauth2.test.annotations.OpenIdClaims; +import com.c4_soft.springaddons.security.oauth2.test.annotations.WithMockJwtAuth; + +import reactor.core.publisher.Mono; + +@WebFluxTest(controllers = GreetingController.class, properties = { "server.ssl.enabled=false" }) +class SpringAddonsGreetingControllerUnitTest { + + @MockBean + MessageService messageService; + + @Autowired + WebTestClient api; + + /*-----------------------------------------------------------------------------*/ + /* /greet */ + /* This end-point secured with ".anyRequest().authenticated()" in SecurityConf */ + /*-----------------------------------------------------------------------------*/ + + @Test + @WithAnonymousUser + void givenRequestIsAnonymous_whenGetGreet_thenUnauthorized() throws Exception { + api.get() + .uri("/greet") + .exchange() + .expectStatus() + .isUnauthorized(); + } + + @Test + @WithMockJwtAuth(authorities = { "admin", "ROLE_AUTHORIZED_PERSONNEL" }, claims = @OpenIdClaims(preferredUsername = "ch4mpy")) + void givenUserIsAuthenticated_whenGetGreet_thenOk() throws Exception { + final var greeting = "Whatever the service returns"; + when(messageService.greet()).thenReturn(Mono.just(greeting)); + + api.get() + .uri("/greet") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo(greeting); + + verify(messageService, times(1)).greet(); + } + + /*---------------------------------------------------------------------------------------------------------------------*/ + /* /secured-route */ + /* This end-point is secured with ".requestMatchers("/secured-route").hasRole("AUTHORIZED_PERSONNEL")" in SecurityConf */ + /*---------------------------------------------------------------------------------------------------------------------*/ + + @Test + @WithAnonymousUser + void givenRequestIsAnonymous_whenGetSecuredRoute_thenUnauthorized() throws Exception { + api.get() + .uri("/secured-route") + .exchange() + .expectStatus() + .isUnauthorized(); + } + + @Test + @WithMockJwtAuth("ROLE_AUTHORIZED_PERSONNEL") + void givenUserIsGrantedWithRoleAuthorizedPersonnel_whenGetSecuredRoute_thenOk() throws Exception { + final var secret = "Secret!"; + when(messageService.getSecret()).thenReturn(Mono.just(secret)); + + api.get() + .uri("/secured-route") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo(secret); + } + + @Test + @WithMockJwtAuth("admin") + void givenUserIsNotGrantedWithRoleAuthorizedPersonnel_whenGetSecuredRoute_thenForbidden() throws Exception { + api.get() + .uri("/secured-route") + .exchange() + .expectStatus() + .isForbidden(); + } + + /*---------------------------------------------------------------------------------------------------------*/ + /* /secured-method */ + /* This end-point is secured with "@PreAuthorize("hasRole('AUTHORIZED_PERSONNEL')")" on @Controller method */ + /*---------------------------------------------------------------------------------------------------------*/ + + @Test + @WithAnonymousUser + void givenRequestIsAnonymous_whenGetSecuredMethod_thenUnauthorized() throws Exception { + api.get() + .uri("/secured-method") + .exchange() + .expectStatus() + .isUnauthorized(); + } + + @Test + @WithMockJwtAuth("ROLE_AUTHORIZED_PERSONNEL") + void givenUserIsGrantedWithRoleAuthorizedPersonnel_whenGetSecuredMethod_thenOk() throws Exception { + final var secret = "Secret!"; + when(messageService.getSecret()).thenReturn(Mono.just(secret)); + + api.get() + .uri("/secured-method") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo(secret); + } + + @Test + @WithMockJwtAuth("admin") + void givenUserIsNotGrantedWithRoleAuthorizedPersonnel_whenGetSecuredMethod_thenForbidden() throws Exception { + api.get() + .uri("/secured-method") + .exchange() + .expectStatus() + .isForbidden(); + } + +} diff --git a/spring-security-modules/spring-security-oauth2-testing/reactive-resource-server/src/test/java/com/baeldung/SpringSecurityTestGreetingControllerUnitTest.java b/spring-security-modules/spring-security-oauth2-testing/reactive-resource-server/src/test/java/com/baeldung/SpringSecurityTestGreetingControllerUnitTest.java new file mode 100644 index 0000000000..e048481ce4 --- /dev/null +++ b/spring-security-modules/spring-security-oauth2-testing/reactive-resource-server/src/test/java/com/baeldung/SpringSecurityTestGreetingControllerUnitTest.java @@ -0,0 +1,149 @@ +package com.baeldung; + +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.mockAuthentication; +import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.mockJwt; + +import java.util.List; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.security.authentication.AnonymousAuthenticationToken; +import org.springframework.security.core.authority.AuthorityUtils; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.oauth2.core.oidc.StandardClaimNames; +import org.springframework.test.web.reactive.server.WebTestClient; + +import com.baeldung.ReactiveResourceServerApplication.GreetingController; +import com.baeldung.ReactiveResourceServerApplication.MessageService; + +import reactor.core.publisher.Mono; + +@WebFluxTest(controllers = GreetingController.class, properties = { "server.ssl.enabled=false" }) +class SpringSecurityTestGreetingControllerUnitTest { + private static final AnonymousAuthenticationToken ANONYMOUS_AUTHENTICATION = new AnonymousAuthenticationToken("anonymous", "anonymousUser", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")); + + @MockBean + MessageService messageService; + + @Autowired + WebTestClient api; + + /*-----------------------------------------------------------------------------*/ + /* /greet */ + /* This end-point secured with ".anyRequest().authenticated()" in SecurityConf */ + /*-----------------------------------------------------------------------------*/ + + @Test + void givenRequestIsAnonymous_whenGetGreet_thenUnauthorized() throws Exception { + api.mutateWith(mockAuthentication(ANONYMOUS_AUTHENTICATION)) + .get() + .uri("/greet") + .exchange() + .expectStatus() + .isUnauthorized(); + } + + @Test + void givenUserIsAuthenticated_whenGetGreet_thenOk() throws Exception { + final var greeting = "Whatever the service returns"; + when(messageService.greet()).thenReturn(Mono.just(greeting)); + + api.mutateWith(mockJwt().authorities(List.of(new SimpleGrantedAuthority("admin"), new SimpleGrantedAuthority("ROLE_AUTHORIZED_PERSONNEL"))) + .jwt(jwt -> jwt.claim(StandardClaimNames.PREFERRED_USERNAME, "ch4mpy"))) + .get() + .uri("/greet") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo(greeting); + + verify(messageService, times(1)).greet(); + } + + /*---------------------------------------------------------------------------------------------------------------------*/ + /* /secured-route */ + /* This end-point is secured with ".requestMatchers("/secured-route").hasRole("AUTHORIZED_PERSONNEL")" in SecurityConf */ + /*---------------------------------------------------------------------------------------------------------------------*/ + + @Test + void givenRequestIsAnonymous_whenGetSecuredRoute_thenUnauthorized() throws Exception { + api.mutateWith(mockAuthentication(ANONYMOUS_AUTHENTICATION)) + .get() + .uri("/secured-route") + .exchange() + .expectStatus() + .isUnauthorized(); + } + + @Test + void givenUserIsGrantedWithRoleAuthorizedPersonnel_whenGetSecuredRoute_thenOk() throws Exception { + final var secret = "Secret!"; + when(messageService.getSecret()).thenReturn(Mono.just(secret)); + + api.mutateWith(mockJwt().authorities(new SimpleGrantedAuthority("ROLE_AUTHORIZED_PERSONNEL"))) + .get() + .uri("/secured-route") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo(secret); + } + + @Test + void givenUserIsNotGrantedWithRoleAuthorizedPersonnel_whenGetSecuredRoute_thenForbidden() throws Exception { + api.mutateWith(mockJwt().authorities(new SimpleGrantedAuthority("admin"))) + .get() + .uri("/secured-route") + .exchange() + .expectStatus() + .isForbidden(); + } + + /*---------------------------------------------------------------------------------------------------------*/ + /* /secured-method */ + /* This end-point is secured with "@PreAuthorize("hasRole('AUTHORIZED_PERSONNEL')")" on @Controller method */ + /*---------------------------------------------------------------------------------------------------------*/ + + @Test + void givenRequestIsAnonymous_whenGetSecuredMethod_thenUnauthorized() throws Exception { + api.mutateWith(mockAuthentication(ANONYMOUS_AUTHENTICATION)) + .get() + .uri("/secured-method") + .exchange() + .expectStatus() + .isUnauthorized(); + } + + @Test + void givenUserIsGrantedWithRoleAuthorizedPersonnel_whenGetSecuredMethod_thenOk() throws Exception { + final var secret = "Secret!"; + when(messageService.getSecret()).thenReturn(Mono.just(secret)); + + api.mutateWith(mockJwt().authorities(new SimpleGrantedAuthority("ROLE_AUTHORIZED_PERSONNEL"))) + .get() + .uri("/secured-method") + .exchange() + .expectStatus() + .isOk() + .expectBody(String.class) + .isEqualTo(secret); + } + + @Test + void givenUserIsNotGrantedWithRoleAuthorizedPersonnel_whenGetSecuredMethod_thenForbidden() throws Exception { + api.mutateWith(mockJwt().authorities(new SimpleGrantedAuthority("admin"))) + .get() + .uri("/secured-method") + .exchange() + .expectStatus() + .isForbidden(); + } + +} diff --git a/spring-security-modules/spring-security-oauth2-testing/servlet-resource-server/pom.xml b/spring-security-modules/spring-security-oauth2-testing/servlet-resource-server/pom.xml new file mode 100644 index 0000000000..271cc7dc18 --- /dev/null +++ b/spring-security-modules/spring-security-oauth2-testing/servlet-resource-server/pom.xml @@ -0,0 +1,58 @@ + + + 4.0.0 + + com.baeldung + spring-security-oauth2-testing + 0.0.1-SNAPSHOT + + com.baeldung.spring-security-modules.testing + servlet-resource-server + servlet-resource-server + Demo project for Spring Boot servlet resource-server + + 17 + + + + org.springframework.boot + spring-boot-starter-oauth2-resource-server + + + org.springframework.boot + spring-boot-starter-web + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + com.c4-soft.springaddons + spring-addons-oauth2-test + test + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + diff --git a/spring-security-modules/spring-security-oauth2-testing/servlet-resource-server/src/main/java/com/baeldung/ServletResourceServerApplication.java b/spring-security-modules/spring-security-oauth2-testing/servlet-resource-server/src/main/java/com/baeldung/ServletResourceServerApplication.java new file mode 100644 index 0000000000..a30c60eab0 --- /dev/null +++ b/spring-security-modules/spring-security-oauth2-testing/servlet-resource-server/src/main/java/com/baeldung/ServletResourceServerApplication.java @@ -0,0 +1,126 @@ +package com.baeldung; + +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.convert.converter.Converter; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.oauth2.core.oidc.StandardClaimNames; +import org.springframework.security.oauth2.jwt.Jwt; +import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.stereotype.Service; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import lombok.RequiredArgsConstructor; + +@SpringBootApplication +public class ServletResourceServerApplication { + + public static void main(String[] args) { + SpringApplication.run(ServletResourceServerApplication.class, args); + } + + @Configuration + @EnableMethodSecurity + @EnableWebSecurity + static class SecurityConf { + @Bean + SecurityFilterChain filterChain(HttpSecurity http, Converter> authoritiesConverter) throws Exception { + http.oauth2ResourceServer() + .jwt() + .jwtAuthenticationConverter(jwt -> new JwtAuthenticationToken(jwt, authoritiesConverter.convert(jwt))); + http.sessionManagement() + .sessionCreationPolicy(SessionCreationPolicy.STATELESS) + .and() + .csrf() + .disable(); + http.exceptionHandling() + .authenticationEntryPoint((request, response, authException) -> { + response.addHeader(HttpHeaders.WWW_AUTHENTICATE, "Basic realm=\"Restricted Content\""); + response.sendError(HttpStatus.UNAUTHORIZED.value(), HttpStatus.UNAUTHORIZED.getReasonPhrase()); + }); + + http.authorizeHttpRequests() + .requestMatchers("/secured-route") + .hasRole("AUTHORIZED_PERSONNEL") + .anyRequest() + .authenticated(); + + return http.build(); + } + + static interface AuthoritiesConverter extends Converter> { + } + + @Bean + AuthoritiesConverter realmRoles2AuthoritiesConverter() { + return (Jwt jwt) -> { + final var realmRoles = Optional.of(jwt.getClaimAsMap("realm_access")) + .orElse(Map.of()); + @SuppressWarnings("unchecked") + final var roles = (List) realmRoles.getOrDefault("roles", List.of()); + return roles.stream() + .map(SimpleGrantedAuthority::new) + .map(GrantedAuthority.class::cast) + .toList(); + }; + } + } + + @Service + public static class MessageService { + + public String greet() { + final var who = (JwtAuthenticationToken) SecurityContextHolder.getContext() + .getAuthentication(); + final var claims = who.getTokenAttributes(); + return "Hello %s! You are granted with %s.".formatted(claims.getOrDefault(StandardClaimNames.PREFERRED_USERNAME, claims.get(StandardClaimNames.SUB)), who.getAuthorities()); + } + + @PreAuthorize("hasRole('AUTHORIZED_PERSONNEL')") + public String getSecret() { + return "Only authorized personnel can read that"; + } + } + + @RestController + @RequiredArgsConstructor + public static class GreetingController { + private final MessageService messageService; + + @GetMapping("/greet") + public ResponseEntity greet() { + return ResponseEntity.ok(messageService.greet()); + } + + @GetMapping("/secured-route") + public ResponseEntity securedRoute() { + return ResponseEntity.ok(messageService.getSecret()); + } + + @GetMapping("/secured-method") + @PreAuthorize("hasRole('AUTHORIZED_PERSONNEL')") + public ResponseEntity securedMethod() { + return ResponseEntity.ok(messageService.getSecret()); + } + } + +} diff --git a/spring-security-modules/spring-security-oauth2-testing/servlet-resource-server/src/main/resources/application.properties b/spring-security-modules/spring-security-oauth2-testing/servlet-resource-server/src/main/resources/application.properties new file mode 100644 index 0000000000..998f6303aa --- /dev/null +++ b/spring-security-modules/spring-security-oauth2-testing/servlet-resource-server/src/main/resources/application.properties @@ -0,0 +1 @@ +spring.security.oauth2.resourceserver.jwt.issuer-uri=https://localhost:8443/realms/master diff --git a/spring-security-modules/spring-security-oauth2-testing/servlet-resource-server/src/test/java/com/baeldung/MessageServiceUnitTest.java b/spring-security-modules/spring-security-oauth2-testing/servlet-resource-server/src/test/java/com/baeldung/MessageServiceUnitTest.java new file mode 100644 index 0000000000..3c608d226e --- /dev/null +++ b/spring-security-modules/spring-security-oauth2-testing/servlet-resource-server/src/test/java/com/baeldung/MessageServiceUnitTest.java @@ -0,0 +1,79 @@ +package com.baeldung; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Import; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException; +import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; +import org.springframework.security.test.context.support.WithAnonymousUser; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import com.baeldung.ServletResourceServerApplication.MessageService; +import com.c4_soft.springaddons.security.oauth2.test.annotations.OpenIdClaims; +import com.c4_soft.springaddons.security.oauth2.test.annotations.WithMockJwtAuth; + +@Import({ MessageService.class }) +@ExtendWith(SpringExtension.class) +@EnableMethodSecurity +class MessageServiceUnitTest { + @Autowired + MessageService messageService; + + /*----------------------------------------------------------------------------*/ + /* greet() */ + /* Expects a JwtAuthenticationToken to be retrieved from the security-context */ + /*----------------------------------------------------------------------------*/ + + @Test + void givenSecurityContextIsNotSet_whenGreet_thenThrowsAuthenticationCredentialsNotFoundException() { + assertThrows(AuthenticationCredentialsNotFoundException.class, () -> messageService.getSecret()); + } + + @Test + @WithAnonymousUser + void givenUserIsAnonymous_whenGreet_thenThrowsAccessDeniedException() { + assertThrows(AccessDeniedException.class, () -> messageService.getSecret()); + } + + @Test + @WithMockJwtAuth(authorities = { "admin", "ROLE_AUTHORIZED_PERSONNEL" }, claims = @OpenIdClaims(preferredUsername = "ch4mpy")) + void givenSecurityContextIsPopulatedWithJwtAuthenticationToken_whenGreet_thenReturnGreetingWithPreferredUsernameAndAuthorities() { + assertEquals("Hello ch4mpy! You are granted with [admin, ROLE_AUTHORIZED_PERSONNEL].", messageService.greet()); + } + + @Test + @WithMockUser(authorities = { "admin", "ROLE_AUTHORIZED_PERSONNEL" }, username = "ch4mpy") + void givenSecurityContextIsPopulatedWithUsernamePasswordAuthenticationToken_whenGreet_thenThrowsClassCastException() { + assertThrows(ClassCastException.class, () -> messageService.greet()); + } + + /*--------------------------------------------------------------------*/ + /* getSecret() */ + /* is secured with "@PreAuthorize("hasRole('AUTHORIZED_PERSONNEL')")" */ + /*--------------------------------------------------------------------*/ + + @Test + @WithAnonymousUser + void givenUserIsAnonymous_whenGetSecret_thenThrowsAccessDeniedException() { + assertThrows(AccessDeniedException.class, () -> messageService.getSecret()); + } + + @Test + @WithMockJwtAuth(authorities = { "admin", "ROLE_AUTHORIZED_PERSONNEL" }, claims = @OpenIdClaims(preferredUsername = "ch4mpy")) + void givenUserIsGrantedWithRoleAuthorizedPersonnel_whenGetSecret_thenReturnSecret() { + assertEquals("Only authorized personnel can read that", messageService.getSecret()); + } + + @Test + @WithMockJwtAuth(authorities = { "admin" }, claims = @OpenIdClaims(preferredUsername = "ch4mpy")) + void givenUserIsNotGrantedWithRoleAuthorizedPersonnel_whenGetSecret_thenThrowsAccessDeniedException() { + assertThrows(AccessDeniedException.class, () -> messageService.getSecret()); + } + +} diff --git a/spring-security-modules/spring-security-oauth2-testing/servlet-resource-server/src/test/java/com/baeldung/ServletResourceServerApplicationIntegrationTest.java b/spring-security-modules/spring-security-oauth2-testing/servlet-resource-server/src/test/java/com/baeldung/ServletResourceServerApplicationIntegrationTest.java new file mode 100644 index 0000000000..5bb539741f --- /dev/null +++ b/spring-security-modules/spring-security-oauth2-testing/servlet-resource-server/src/test/java/com/baeldung/ServletResourceServerApplicationIntegrationTest.java @@ -0,0 +1,98 @@ +package com.baeldung; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.security.test.context.support.WithAnonymousUser; +import org.springframework.test.web.servlet.MockMvc; + +import com.c4_soft.springaddons.security.oauth2.test.annotations.OpenIdClaims; +import com.c4_soft.springaddons.security.oauth2.test.annotations.WithMockJwtAuth; + +@SpringBootTest(webEnvironment = WebEnvironment.MOCK) +@AutoConfigureMockMvc +class ServletResourceServerApplicationIntegrationTest { + @Autowired + MockMvc api; + + /*-----------------------------------------------------------------------------*/ + /* /greet */ + /* This end-point secured with ".anyRequest().authenticated()" in SecurityConf */ + /*-----------------------------------------------------------------------------*/ + + @Test + @WithAnonymousUser + void givenRequestIsAnonymous_whenGetGreet_thenUnauthorized() throws Exception { + api.perform(get("/greet")) + .andExpect(status().isUnauthorized()); + } + + @Test + @WithMockJwtAuth(authorities = { "admin", "ROLE_AUTHORIZED_PERSONNEL" }, claims = @OpenIdClaims(preferredUsername = "ch4mpy")) + void givenUserIsAuthenticated_whenGetGreet_thenOk() throws Exception { + api.perform(get("/greet")) + .andExpect(status().isOk()) + .andExpect(content().string("Hello ch4mpy! You are granted with [admin, ROLE_AUTHORIZED_PERSONNEL].")); + } + + /*---------------------------------------------------------------------------------------------------------------------*/ + /* /secured-route */ + /* This end-point is secured with ".requestMatchers("/secured-route").hasRole("AUTHORIZED_PERSONNEL")" in SecurityConf */ + /*---------------------------------------------------------------------------------------------------------------------*/ + + @Test + @WithAnonymousUser + void givenRequestIsAnonymous_whenGetSecuredRoute_thenUnauthorized() throws Exception { + api.perform(get("/secured-route")) + .andExpect(status().isUnauthorized()); + } + + @Test + @WithMockJwtAuth("ROLE_AUTHORIZED_PERSONNEL") + void givenUserIsGrantedWithRoleAuthorizedPersonnel_whenGetSecuredRoute_thenOk() throws Exception { + api.perform(get("/secured-route")) + .andExpect(status().isOk()) + .andExpect(content().string("Only authorized personnel can read that")); + } + + @Test + @WithMockJwtAuth("admin") + void givenUserIsNotGrantedWithRoleAuthorizedPersonnel_whenGetSecuredRoute_thenForbidden() throws Exception { + api.perform(get("/secured-route")) + .andExpect(status().isForbidden()); + } + + /*---------------------------------------------------------------------------------------------------------*/ + /* /secured-method */ + /* This end-point is secured with "@PreAuthorize("hasRole('AUTHORIZED_PERSONNEL')")" on @Controller method */ + /*---------------------------------------------------------------------------------------------------------*/ + + @Test + @WithAnonymousUser + void givenRequestIsAnonymous_whenGetSecuredMethod_thenUnauthorized() throws Exception { + api.perform(get("/secured-method")) + .andExpect(status().isUnauthorized()); + } + + @Test + @WithMockJwtAuth("ROLE_AUTHORIZED_PERSONNEL") + void givenUserIsGrantedWithRoleAuthorizedPersonnel_whenGetSecuredMethod_thenOk() throws Exception { + api.perform(get("/secured-method")) + .andExpect(status().isOk()) + .andExpect(content().string("Only authorized personnel can read that")); + } + + @Test + @WithMockJwtAuth("admin") + void givenUserIsNotGrantedWithRoleAuthorizedPersonnel_whenGetSecuredMethod_thenForbidden() throws Exception { + api.perform(get("/secured-method")) + .andExpect(status().isForbidden()); + } + +} diff --git a/spring-security-modules/spring-security-oauth2-testing/servlet-resource-server/src/test/java/com/baeldung/SpringAddonsGreetingControllerUnitTest.java b/spring-security-modules/spring-security-oauth2-testing/servlet-resource-server/src/test/java/com/baeldung/SpringAddonsGreetingControllerUnitTest.java new file mode 100644 index 0000000000..9162768930 --- /dev/null +++ b/spring-security-modules/spring-security-oauth2-testing/servlet-resource-server/src/test/java/com/baeldung/SpringAddonsGreetingControllerUnitTest.java @@ -0,0 +1,116 @@ +package com.baeldung; + +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.security.test.context.support.WithAnonymousUser; +import org.springframework.test.web.servlet.MockMvc; + +import com.baeldung.ServletResourceServerApplication.GreetingController; +import com.baeldung.ServletResourceServerApplication.MessageService; +import com.c4_soft.springaddons.security.oauth2.test.annotations.OpenIdClaims; +import com.c4_soft.springaddons.security.oauth2.test.annotations.WithMockJwtAuth; + +@WebMvcTest(controllers = GreetingController.class, properties = { "server.ssl.enabled=false" }) +class SpringAddonsGreetingControllerUnitTest { + + @MockBean + MessageService messageService; + + @Autowired + MockMvc api; + + /*-----------------------------------------------------------------------------*/ + /* /greet */ + /* This end-point secured with ".anyRequest().authenticated()" in SecurityConf */ + /*-----------------------------------------------------------------------------*/ + + @Test + @WithAnonymousUser + void givenRequestIsAnonymous_whenGetGreet_thenUnauthorized() throws Exception { + api.perform(get("/greet")) + .andExpect(status().isUnauthorized()); + } + + @Test + @WithMockJwtAuth(authorities = { "admin", "ROLE_AUTHORIZED_PERSONNEL" }, claims = @OpenIdClaims(preferredUsername = "ch4mpy")) + void givenUserIsAuthenticated_whenGetGreet_thenOk() throws Exception { + final var greeting = "Whatever the service returns"; + when(messageService.greet()).thenReturn(greeting); + + api.perform(get("/greet")) + .andExpect(status().isOk()) + .andExpect(content().string(greeting)); + + verify(messageService, times(1)).greet(); + } + + /*---------------------------------------------------------------------------------------------------------------------*/ + /* /secured-route */ + /* This end-point is secured with ".requestMatchers("/secured-route").hasRole("AUTHORIZED_PERSONNEL")" in SecurityConf */ + /*---------------------------------------------------------------------------------------------------------------------*/ + + @Test + @WithAnonymousUser + void givenRequestIsAnonymous_whenGetSecuredRoute_thenUnauthorized() throws Exception { + api.perform(get("/secured-route")) + .andExpect(status().isUnauthorized()); + } + + @Test + @WithMockJwtAuth({ "admin", "ROLE_AUTHORIZED_PERSONNEL" }) + void givenUserIsGrantedWithRoleAuthorizedPersonnel_whenGetSecuredRoute_thenOk() throws Exception { + final var secret = "Secret!"; + when(messageService.getSecret()).thenReturn(secret); + + api.perform(get("/secured-route")) + .andExpect(status().isOk()) + .andExpect(content().string(secret)); + } + + @Test + @WithMockJwtAuth({ "admin" }) + void givenUserIsNotGrantedWithRoleAuthorizedPersonnel_whenGetSecuredRoute_thenForbidden() throws Exception { + api.perform(get("/secured-route")) + .andExpect(status().isForbidden()); + } + + /*---------------------------------------------------------------------------------------------------------*/ + /* /secured-method */ + /* This end-point is secured with "@PreAuthorize("hasRole('AUTHORIZED_PERSONNEL')")" on @Controller method */ + /*---------------------------------------------------------------------------------------------------------*/ + + @Test + @WithAnonymousUser + void givenRequestIsAnonymous_whenGetSecuredMethod_thenUnauthorized() throws Exception { + api.perform(get("/secured-method")) + .andExpect(status().isUnauthorized()); + } + + @Test + @WithMockJwtAuth({ "admin", "ROLE_AUTHORIZED_PERSONNEL" }) + void givenUserIsGrantedWithRoleAuthorizedPersonnel_whenGetSecuredMethod_thenOk() throws Exception { + final var secret = "Secret!"; + when(messageService.getSecret()).thenReturn(secret); + + api.perform(get("/secured-method")) + .andExpect(status().isOk()) + .andExpect(content().string(secret)); + } + + @Test + @WithMockJwtAuth(authorities = { "admin" }) + void givenUserIsNotGrantedWithRoleAuthorizedPersonnel_whenGetSecuredMethod_thenForbidden() throws Exception { + api.perform(get("/secured-method")) + .andExpect(status().isForbidden()); + } + +} diff --git a/spring-security-modules/spring-security-oauth2-testing/servlet-resource-server/src/test/java/com/baeldung/SpringSecurityTestGreetingControllerUnitTest.java b/spring-security-modules/spring-security-oauth2-testing/servlet-resource-server/src/test/java/com/baeldung/SpringSecurityTestGreetingControllerUnitTest.java new file mode 100644 index 0000000000..0e710bcc9f --- /dev/null +++ b/spring-security-modules/spring-security-oauth2-testing/servlet-resource-server/src/test/java/com/baeldung/SpringSecurityTestGreetingControllerUnitTest.java @@ -0,0 +1,112 @@ +package com.baeldung; + +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.anonymous; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.jwt; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.util.List; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.oauth2.core.oidc.StandardClaimNames; +import org.springframework.test.web.servlet.MockMvc; + +import com.baeldung.ServletResourceServerApplication.GreetingController; +import com.baeldung.ServletResourceServerApplication.MessageService; + +@WebMvcTest(controllers = GreetingController.class, properties = { "server.ssl.enabled=false" }) +class SpringSecurityTestGreetingControllerUnitTest { + + @MockBean + MessageService messageService; + + @Autowired + MockMvc api; + + /*-----------------------------------------------------------------------------*/ + /* /greet */ + /* This end-point secured with ".anyRequest().authenticated()" in SecurityConf */ + /*-----------------------------------------------------------------------------*/ + + @Test + void givenRequestIsAnonymous_whenGetGreet_thenUnauthorized() throws Exception { + api.perform(get("/greet").with(anonymous())) + .andExpect(status().isUnauthorized()); + } + + @Test + void givenUserIsAuthenticated_whenGetGreet_thenOk() throws Exception { + final var greeting = "Whatever the service returns"; + when(messageService.greet()).thenReturn(greeting); + + api.perform(get("/greet").with(jwt().authorities(List.of(new SimpleGrantedAuthority("admin"), new SimpleGrantedAuthority("ROLE_AUTHORIZED_PERSONNEL"))) + .jwt(jwt -> jwt.claim(StandardClaimNames.PREFERRED_USERNAME, "ch4mpy")))) + .andExpect(status().isOk()) + .andExpect(content().string(greeting)); + + verify(messageService, times(1)).greet(); + } + + /*---------------------------------------------------------------------------------------------------------------------*/ + /* /secured-route */ + /* This end-point is secured with ".requestMatchers("/secured-route").hasRole("AUTHORIZED_PERSONNEL")" in SecurityConf */ + /*---------------------------------------------------------------------------------------------------------------------*/ + + @Test + void givenRequestIsAnonymous_whenGetSecuredRoute_thenUnauthorized() throws Exception { + api.perform(get("/secured-route").with(anonymous())) + .andExpect(status().isUnauthorized()); + } + + @Test + void givenUserIsGrantedWithRoleAuthorizedPersonnel_whenGetSecuredRoute_thenOk() throws Exception { + final var secret = "Secret!"; + when(messageService.getSecret()).thenReturn(secret); + + api.perform(get("/secured-route").with(jwt().authorities(new SimpleGrantedAuthority("ROLE_AUTHORIZED_PERSONNEL")))) + .andExpect(status().isOk()) + .andExpect(content().string(secret)); + } + + @Test + void givenUserIsNotGrantedWithRoleAuthorizedPersonnel_whenGetSecuredRoute_thenForbidden() throws Exception { + api.perform(get("/secured-route").with(jwt().authorities(new SimpleGrantedAuthority("admin")))) + .andExpect(status().isForbidden()); + } + + /*---------------------------------------------------------------------------------------------------------*/ + /* /secured-method */ + /* This end-point is secured with "@PreAuthorize("hasRole('AUTHORIZED_PERSONNEL')")" on @Controller method */ + /*---------------------------------------------------------------------------------------------------------*/ + + @Test + void givenRequestIsAnonymous_whenGetSecuredMethod_thenUnauthorized() throws Exception { + api.perform(get("/secured-method").with(anonymous())) + .andExpect(status().isUnauthorized()); + } + + @Test + void givenUserIsGrantedWithRoleAuthorizedPersonnel_whenGetSecuredMethod_thenOk() throws Exception { + final var secret = "Secret!"; + when(messageService.getSecret()).thenReturn(secret); + + api.perform(get("/secured-method").with(jwt().authorities(new SimpleGrantedAuthority("ROLE_AUTHORIZED_PERSONNEL")))) + .andExpect(status().isOk()) + .andExpect(content().string(secret)); + } + + @Test + void givenUserIsNotGrantedWithRoleAuthorizedPersonnel_whenGetSecuredMethod_thenForbidden() throws Exception { + api.perform(get("/secured-method").with(jwt().authorities(new SimpleGrantedAuthority("admin")))) + .andExpect(status().isForbidden()); + } + +} diff --git a/spring-web-modules/spring-mvc-basics-4/pom.xml b/spring-web-modules/spring-mvc-basics-4/pom.xml index 376e13ed72..455e4e488c 100644 --- a/spring-web-modules/spring-mvc-basics-4/pom.xml +++ b/spring-web-modules/spring-mvc-basics-4/pom.xml @@ -15,26 +15,26 @@ - - com.fasterxml.jackson.core - jackson-databind - - - org.springframework - spring-web - org.springframework.boot spring-boot-starter-validation - javax.servlet - javax.servlet-api - provided + org.springframework.boot + spring-boot-starter-web + 3.0.2 - org.springframework - spring-webmvc + org.apache.tomcat.embed + tomcat-embed-jasper + + + javax.servlet + jstl + + + org.springframework.boot + spring-boot-starter-thymeleaf diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/config/WebConfig.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/config/WebConfig.java new file mode 100644 index 0000000000..e9b59a2b23 --- /dev/null +++ b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/config/WebConfig.java @@ -0,0 +1,44 @@ +package com.baeldung.config; + +import org.springframework.boot.web.server.WebServerFactoryCustomizer; +import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.ViewResolver; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.view.InternalResourceViewResolver; +import org.springframework.web.servlet.view.JstlView; +import org.thymeleaf.spring5.SpringTemplateEngine; +import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver; +import org.thymeleaf.spring5.view.ThymeleafViewResolver; +import org.thymeleaf.templatemode.TemplateMode; +import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver; +import org.thymeleaf.templateresolver.ITemplateResolver; + +import com.baeldung.contexts.Greeting; +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * Web Configuration for the entire app + */ +@Configuration +@EnableWebMvc +public class WebConfig { + + @Bean + public WebServerFactoryCustomizer enableDefaultServlet() { + return factory -> factory.setRegisterDefaultServlet(true); + } + + @Bean + public Greeting greeting() { + Greeting greeting = new Greeting(); + greeting.setMessage("Hello World !!"); + return greeting; + } + + @Bean + public ObjectMapper objectMapper() { + return new ObjectMapper(); + } +} diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/config/AnnotationsBasedApplicationAndServletInitializer.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/config/AnnotationsBasedApplicationAndServletInitializer.java deleted file mode 100644 index 1dffad637a..0000000000 --- a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/config/AnnotationsBasedApplicationAndServletInitializer.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.baeldung.contexts.config; - -import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; - -public class AnnotationsBasedApplicationAndServletInitializer //extends AbstractDispatcherServletInitializer -{ - - //uncomment to run the multiple contexts example - //@Override - protected WebApplicationContext createRootApplicationContext() { - //If this is not the only class declaring a root context, we return null because it would clash - //with other classes, as there can only be a single root context. - - //AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext(); - //rootContext.register(RootApplicationConfig.class); - //return rootContext; - return null; - } - - //@Override - protected WebApplicationContext createServletApplicationContext() { - AnnotationConfigWebApplicationContext normalWebAppContext = new AnnotationConfigWebApplicationContext(); - normalWebAppContext.register(NormalWebAppConfig.class); - return normalWebAppContext; - } - - //@Override - protected String[] getServletMappings() { - return new String[] { "/api/*" }; - } - - //@Override - protected String getServletName() { - return "normal-dispatcher"; - } -} diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/config/AnnotationsBasedApplicationInitializer.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/config/AnnotationsBasedApplicationInitializer.java deleted file mode 100644 index ffa80d58bf..0000000000 --- a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/config/AnnotationsBasedApplicationInitializer.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung.contexts.config; - -import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; - -public class AnnotationsBasedApplicationInitializer //extends AbstractContextLoaderInitializer -{ - //uncomment to run the multiple contexts example - // @Override - protected WebApplicationContext createRootApplicationContext() { - AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext(); - rootContext.register(RootApplicationConfig.class); - return rootContext; - } - -} \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/config/ApplicationInitializer.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/config/ApplicationInitializer.java deleted file mode 100644 index 15a2631cbb..0000000000 --- a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/config/ApplicationInitializer.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.baeldung.contexts.config; - -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.ServletRegistration; - -import org.springframework.context.annotation.Configuration; -import org.springframework.context.support.ClassPathXmlApplicationContext; -import org.springframework.web.WebApplicationInitializer; -import org.springframework.web.context.ContextLoaderListener; -import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; -import org.springframework.web.context.support.XmlWebApplicationContext; -import org.springframework.web.servlet.DispatcherServlet; - -public class ApplicationInitializer //implements WebApplicationInitializer -{ - //uncomment to run the multiple contexts example - //@Override - public void onStartup(ServletContext servletContext) throws ServletException { - //Here, we can define a root context and register servlets, among other things. - //However, since we've later defined other classes to do the same and they would clash, - //we leave this commented out. - - //Root XML Context - //XmlWebApplicationContext rootContext = new XmlWebApplicationContext(); - //rootContext.setConfigLocations("/WEB-INF/rootApplicationContext.xml"); - //Annotations Context - //AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext(); - //rootContext.register(RootApplicationConfig.class); - //Registration - //servletContext.addListener(new ContextLoaderListener(rootContext)); - - //Dispatcher Servlet - //XmlWebApplicationContext normalWebAppContext = new XmlWebApplicationContext(); - //normalWebAppContext.setConfigLocation("/WEB-INF/normal-webapp-servlet.xml"); - //ServletRegistration.Dynamic normal = servletContext.addServlet("normal-webapp", new DispatcherServlet(normalWebAppContext)); - //normal.setLoadOnStartup(1); - //normal.addMapping("/api/*"); - } - -} diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/config/NormalWebAppConfig.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/config/NormalWebAppConfig.java deleted file mode 100644 index 3da3d3beb1..0000000000 --- a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/config/NormalWebAppConfig.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.baeldung.contexts.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.ViewResolver; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; -import org.springframework.web.servlet.view.InternalResourceViewResolver; -import org.springframework.web.servlet.view.JstlView; - -@Configuration -@EnableWebMvc -@ComponentScan(basePackages = { "com.baeldung.contexts.normal" }) -public class NormalWebAppConfig implements WebMvcConfigurer { - - @Bean - public ViewResolver viewResolver() { - InternalResourceViewResolver resolver = new InternalResourceViewResolver(); - resolver.setPrefix("/WEB-INF/view/"); - resolver.setSuffix(".jsp"); - resolver.setViewClass(JstlView.class); - return resolver; - } -} diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/config/RootApplicationConfig.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/config/RootApplicationConfig.java deleted file mode 100644 index 59821076d2..0000000000 --- a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/config/RootApplicationConfig.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.baeldung.contexts.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; - -import com.baeldung.contexts.Greeting; - -@Configuration -@ComponentScan(basePackages = { "com.baeldung.contexts.services" }) -public class RootApplicationConfig { - - @Bean - public Greeting greeting() { - Greeting greeting = new Greeting(); - greeting.setMessage("Hello World !!"); - return greeting; - } -} diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/config/SecureAnnotationsBasedApplicationAndServletInitializer.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/config/SecureAnnotationsBasedApplicationAndServletInitializer.java deleted file mode 100644 index 580e86d2b5..0000000000 --- a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/config/SecureAnnotationsBasedApplicationAndServletInitializer.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.baeldung.contexts.config; - -import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; - -public class SecureAnnotationsBasedApplicationAndServletInitializer// extends AbstractDispatcherServletInitializer -{ - - //uncomment to run the multiple contexts example - //@Override - protected WebApplicationContext createRootApplicationContext() { - return null; - } - - //@Override - protected WebApplicationContext createServletApplicationContext() { - AnnotationConfigWebApplicationContext secureWebAppContext = new AnnotationConfigWebApplicationContext(); - secureWebAppContext.register(SecureWebAppConfig.class); - return secureWebAppContext; - } - - //@Override - protected String[] getServletMappings() { - return new String[] { "/s/api/*" }; - } - - - //@Override - protected String getServletName() { - return "secure-dispatcher"; - } - -} diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/config/SecureWebAppConfig.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/config/SecureWebAppConfig.java deleted file mode 100644 index acc1e3092b..0000000000 --- a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/config/SecureWebAppConfig.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.baeldung.contexts.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.ViewResolver; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; -import org.springframework.web.servlet.view.InternalResourceViewResolver; -import org.springframework.web.servlet.view.JstlView; - -@Configuration -@EnableWebMvc -@ComponentScan(basePackages = { "com.baeldung.contexts.secure" }) -public class SecureWebAppConfig implements WebMvcConfigurer { - - @Bean - public ViewResolver viewResolver() { - InternalResourceViewResolver resolver = new InternalResourceViewResolver(); - resolver.setPrefix("/WEB-INF/secure/view/"); - resolver.setSuffix(".jsp"); - resolver.setViewClass(JstlView.class); - return resolver; - } -} diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/normal/HelloWorldController.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/normal/HelloWorldController.java index 8b58c51eb3..46d1769349 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/normal/HelloWorldController.java +++ b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/normal/HelloWorldController.java @@ -3,9 +3,9 @@ package com.baeldung.contexts.normal; import java.util.Arrays; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.context.ContextLoader; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.servlet.ModelAndView; @@ -19,21 +19,22 @@ public class HelloWorldController { @Autowired private GreeterService greeterService; + + @Autowired + private ApplicationContext applicationContext; private void processContext() { - WebApplicationContext rootContext = ContextLoader.getCurrentWebApplicationContext(); - - System.out.println("root context : " + rootContext); - System.out.println("root context Beans: " + Arrays.asList(rootContext.getBeanDefinitionNames())); + System.out.println("root context : " + applicationContext); + System.out.println("root context Beans: " + Arrays.asList(applicationContext.getBeanDefinitionNames())); System.out.println("context : " + webApplicationContext); System.out.println("context Beans: " + Arrays.asList(webApplicationContext.getBeanDefinitionNames())); } - @RequestMapping(path = "/welcome") + @GetMapping(path = "/welcome") public ModelAndView helloWorld() { processContext(); String message = "
" + "

Normal " + greeterService.greet() + "

"; - return new ModelAndView("welcome", "message", message); + return new ModelAndView("/view/welcome", "message", message); } } diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/secure/HelloWorldSecureController.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/secure/HelloWorldSecureController.java index 4ebf2d55e0..84d7808000 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/secure/HelloWorldSecureController.java +++ b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/secure/HelloWorldSecureController.java @@ -6,8 +6,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.context.ContextLoader; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.servlet.ModelAndView; @@ -31,19 +30,15 @@ public class HelloWorldSecureController { ApplicationContext context = contextUtilService.getApplicationContext(); System.out.println("application context : " + context); System.out.println("application context Beans: " + Arrays.asList(context.getBeanDefinitionNames())); - - WebApplicationContext rootContext = ContextLoader.getCurrentWebApplicationContext(); - System.out.println("context : " + rootContext); - System.out.println("context Beans: " + Arrays.asList(rootContext.getBeanDefinitionNames())); System.out.println("context : " + webApplicationContext); System.out.println("context Beans: " + Arrays.asList(webApplicationContext.getBeanDefinitionNames())); } - @RequestMapping(path = "/welcome") + @GetMapping(path = "/welcome_secure") public ModelAndView helloWorld() { processContext(); String message = "
" + "

Secure " + greeterService.greet() + "

"; - return new ModelAndView("welcome", "message", message); + return new ModelAndView("/secure/view/welcome", "message", message); } } diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/controller/config/StudentControllerConfig.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/controller/config/StudentControllerConfig.java deleted file mode 100644 index b84094132d..0000000000 --- a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/controller/config/StudentControllerConfig.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.baeldung.controller.config; - -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.ServletRegistration; - -import org.springframework.web.context.ContextLoaderListener; -import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; -import org.springframework.web.servlet.DispatcherServlet; - -public class StudentControllerConfig //implements WebApplicationInitializer -{ - - //uncomment to run the student controller example - //@Override - public void onStartup(ServletContext sc) throws ServletException { - AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext(); - root.register(WebConfig.class); - root.setServletContext(sc); - sc.addListener(new ContextLoaderListener(root)); - - DispatcherServlet dv = new DispatcherServlet(root); - - ServletRegistration.Dynamic appServlet = sc.addServlet("test-mvc", dv); - appServlet.setLoadOnStartup(1); - appServlet.addMapping("/test/*"); - } -} diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/controller/config/WebConfig.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/controller/config/WebConfig.java deleted file mode 100644 index 364f042ac7..0000000000 --- a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/controller/config/WebConfig.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.baeldung.controller.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.ViewResolver; -import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; -import org.springframework.web.servlet.view.InternalResourceViewResolver; - -@Configuration -@EnableWebMvc -@ComponentScan(basePackages = { "com.baeldung.controller", "com.baeldung.optionalpathvars" }) -public class WebConfig implements WebMvcConfigurer { - @Override - public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { - configurer.enable(); - } - - @Bean - public ViewResolver viewResolver() { - InternalResourceViewResolver bean = new InternalResourceViewResolver(); - bean.setPrefix("/WEB-INF/"); - bean.setSuffix(".jsp"); - return bean; - } -} \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/controller/controller/GreetingsController.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/controller/controller/GreetingsController.java index fbf78b8a0e..1568b94050 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/controller/controller/GreetingsController.java +++ b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/controller/controller/GreetingsController.java @@ -7,42 +7,26 @@ import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; -@Controller +@RestController public class GreetingsController { - @RequestMapping( - value = "/greetings-with-response-body", - method = RequestMethod.GET, - produces="application/json" - ) - @ResponseBody + @GetMapping(value = "/greetings-with-response-body", produces="application/json") public String getGreetingWhileReturnTypeIsString() { - return "{\"test\": \"Hello using @ResponseBody\"}"; + return "{\"test\": \"Hello\"}"; } - @RequestMapping( - value = "/greetings-with-response-entity", - method = RequestMethod.GET, - produces = "application/json" - ) + @GetMapping(value = "/greetings-with-response-entity", produces = "application/json") public ResponseEntity getGreetingWithResponseEntity() { final HttpHeaders httpHeaders= new HttpHeaders(); httpHeaders.setContentType(MediaType.APPLICATION_JSON); - return new ResponseEntity("{\"test\": \"Hello with ResponseEntity\"}", httpHeaders, HttpStatus.OK); + return new ResponseEntity<>("{\"test\": \"Hello with ResponseEntity\"}", httpHeaders, HttpStatus.OK); } - @RequestMapping( - value = "/greetings-with-map-return-type", - method = RequestMethod.GET, - produces = "application/json" - ) - @ResponseBody + @GetMapping(value = "/greetings-with-map-return-type", produces = "application/json") public Map getGreetingWhileReturnTypeIsMap() { - HashMap map = new HashMap(); + HashMap map = new HashMap<>(); map.put("test", "Hello from map"); return map; } diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/controller/controller/PassParametersController.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/controller/controller/PassParametersController.java index d8330333cb..46b7003f3e 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/controller/controller/PassParametersController.java +++ b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/controller/controller/PassParametersController.java @@ -18,19 +18,19 @@ public class PassParametersController { @GetMapping("/showViewPage") public String passParametersWithModel(Model model) { model.addAttribute("message", "Baeldung"); - return "viewPage"; + return "view/viewPage"; } @GetMapping("/printViewPage") public String passParametersWithModelMap(ModelMap map) { map.addAttribute("welcomeMessage", "welcome"); map.addAttribute("message", "Baeldung"); - return "viewPage"; + return "view/viewPage"; } @GetMapping("/goToViewPage") public ModelAndView passParametersWithModelAndView() { - ModelAndView modelAndView = new ModelAndView("viewPage"); + ModelAndView modelAndView = new ModelAndView("view/viewPage"); modelAndView.addObject("message", "Baeldung"); return modelAndView; } diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/controller/controller/RestController.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/controller/controller/RestController.java index a529faeed3..eead000621 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/controller/controller/RestController.java +++ b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/controller/controller/RestController.java @@ -1,17 +1,15 @@ package com.baeldung.controller.controller; -import com.baeldung.controller.student.Student; -import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.ResponseBody; -@Controller +import com.baeldung.controller.student.Student; + +@org.springframework.web.bind.annotation.RestController public class RestController { @GetMapping(value = "/student/{studentId}") - public @ResponseBody - Student getTestData(@PathVariable Integer studentId) { + public Student getTestData(@PathVariable Integer studentId) { Student student = new Student(); student.setName("Peter"); student.setId(studentId); diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/controller/student/Student.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/controller/student/Student.java index 8a82dd5553..5c2b991312 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/controller/student/Student.java +++ b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/controller/student/Student.java @@ -27,7 +27,14 @@ public class Student { } @Override - public boolean equals(Object obj) { - return this.name.equals(((Student) obj).getName()); + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof Student)) { + return false; + } + Student student = (Student) o; + return getName().equals(student.getName()); } } \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/jsonparams/config/JsonParamsConfig.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/jsonparams/config/JsonParamsConfig.java deleted file mode 100644 index f2049554ab..0000000000 --- a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/jsonparams/config/JsonParamsConfig.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.baeldung.jsonparams.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.ViewResolver; -import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; -import org.springframework.web.servlet.view.InternalResourceViewResolver; - -import com.fasterxml.jackson.databind.ObjectMapper; - -@Configuration -@EnableWebMvc -@ComponentScan(basePackages = { "com.baeldung.jsonparams" }) -public class JsonParamsConfig implements WebMvcConfigurer { - @Override - public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { - configurer.enable(); - } - - @Bean - public ViewResolver viewResolver() { - InternalResourceViewResolver bean = new InternalResourceViewResolver(); - bean.setPrefix("/WEB-INF/"); - bean.setSuffix(".jsp"); - return bean; - } - - @Bean - public ObjectMapper objectMapper() { - return new ObjectMapper(); - } - -} diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/jsonparams/config/JsonParamsInit.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/jsonparams/config/JsonParamsInit.java deleted file mode 100644 index 6db2a92350..0000000000 --- a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/jsonparams/config/JsonParamsInit.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.baeldung.jsonparams.config; - -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.ServletRegistration; - -import org.springframework.web.context.ContextLoaderListener; -import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; -import org.springframework.web.servlet.DispatcherServlet; - -public class JsonParamsInit // implements WebApplicationInitializer -{ - - //uncomment to run the product controller example - //@Override - public void onStartup(ServletContext sc) throws ServletException { - AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext(); - root.register(JsonParamsConfig.class); - root.setServletContext(sc); - sc.addListener(new ContextLoaderListener(root)); - - DispatcherServlet dv = new DispatcherServlet(root); - - ServletRegistration.Dynamic appServlet = sc.addServlet("jsonparams-mvc", dv); - appServlet.setLoadOnStartup(1); - appServlet.addMapping("/"); - } - -} diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/jsonparams/controller/ProductController.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/jsonparams/controller/ProductController.java index e4e2ce085d..915731581e 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/jsonparams/controller/ProductController.java +++ b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/jsonparams/controller/ProductController.java @@ -1,7 +1,6 @@ package com.baeldung.jsonparams.controller; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.InitBinder; @@ -9,7 +8,7 @@ import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; import com.baeldung.jsonparams.model.Product; import com.baeldung.jsonparams.propertyeditor.ProductEditor; @@ -17,7 +16,7 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; -@Controller +@RestController @RequestMapping("/products") public class ProductController { @@ -34,21 +33,18 @@ public class ProductController { } @PostMapping("/create") - @ResponseBody public Product createProduct(@RequestBody Product product) { // custom logic return product; } @GetMapping("/get") - @ResponseBody - public Product getProduct(@RequestParam String product) throws JsonMappingException, JsonProcessingException { + public Product getProduct(@RequestParam String product) throws JsonProcessingException { final Product prod = objectMapper.readValue(product, Product.class); return prod; } @GetMapping("/get2") - @ResponseBody public Product get2Product(@RequestParam Product product) { // custom logic return product; diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/jsonparams/propertyeditor/ProductEditor.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/jsonparams/propertyeditor/ProductEditor.java index 11766118cd..41d97bed84 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/jsonparams/propertyeditor/ProductEditor.java +++ b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/jsonparams/propertyeditor/ProductEditor.java @@ -18,7 +18,7 @@ public class ProductEditor extends PropertyEditorSupport { @Override public void setAsText(String text) throws IllegalArgumentException { - if (StringUtils.isEmpty(text)) { + if (!StringUtils.hasText(text)) { setValue(null); } else { Product prod = new Product(); diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/optionalpathvars/ArticleViewerController.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/optionalpathvars/ArticleViewerController.java deleted file mode 100644 index 1876798bd6..0000000000 --- a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/optionalpathvars/ArticleViewerController.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.baeldung.optionalpathvars; - -import static com.baeldung.optionalpathvars.Article.DEFAULT_ARTICLE; - -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -@RestController -public class ArticleViewerController { - - @RequestMapping(value = {"/article", "/article/{id}"}) - public Article getArticle(@PathVariable(name = "id") Integer articleId) { - - if (articleId != null) { - return new Article(articleId); - } else { - return DEFAULT_ARTICLE; - } - - } - -} \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/optionalpathvars/ArticleViewerWithRequiredAttributeController.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/optionalpathvars/ArticleViewerWithRequiredAttributeController.java index 7548747f05..786a56c130 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/optionalpathvars/ArticleViewerWithRequiredAttributeController.java +++ b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/optionalpathvars/ArticleViewerWithRequiredAttributeController.java @@ -4,7 +4,7 @@ import static com.baeldung.optionalpathvars.Article.DEFAULT_ARTICLE; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController;; +import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping(value = "/requiredAttribute") diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/validation/listvalidation/SpringListValidationApplication.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/validation/listvalidation/SpringListValidationApplication.java index f16d5f877f..3d518c467c 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/validation/listvalidation/SpringListValidationApplication.java +++ b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/validation/listvalidation/SpringListValidationApplication.java @@ -5,7 +5,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; -@ComponentScan(basePackages = "com.baeldung.validation.listvalidation") +@ComponentScan(basePackages = "com.baeldung") @Configuration @SpringBootApplication public class SpringListValidationApplication { diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/resources/templates/secure/view/welcome.html b/spring-web-modules/spring-mvc-basics-4/src/main/resources/templates/secure/view/welcome.html new file mode 100644 index 0000000000..fac7234f15 --- /dev/null +++ b/spring-web-modules/spring-mvc-basics-4/src/main/resources/templates/secure/view/welcome.html @@ -0,0 +1,11 @@ + + + + Spring Web Contexts + + +
+
Secure Web Application : +
+ + \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/view/viewPage.html b/spring-web-modules/spring-mvc-basics-4/src/main/resources/templates/view/viewPage.html similarity index 58% rename from spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/view/viewPage.html rename to spring-web-modules/spring-mvc-basics-4/src/main/resources/templates/view/viewPage.html index 71f766407e..b520d0dd51 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/view/viewPage.html +++ b/spring-web-modules/spring-mvc-basics-4/src/main/resources/templates/view/viewPage.html @@ -4,6 +4,6 @@ Title -
Web Application. Passed parameter : th:text="${message}"
+
Web Application. Passed parameter :
diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/view/welcome.jsp b/spring-web-modules/spring-mvc-basics-4/src/main/resources/templates/view/welcome.html similarity index 57% rename from spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/view/welcome.jsp rename to spring-web-modules/spring-mvc-basics-4/src/main/resources/templates/view/welcome.html index 4eda3c58e2..291f3b8919 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/view/welcome.jsp +++ b/spring-web-modules/spring-mvc-basics-4/src/main/resources/templates/view/welcome.html @@ -1,11 +1,12 @@ - + + Spring Web Contexts
- Normal Web Application : ${message} + Normal Web Application :
\ No newline at end of file diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/resources/templates/welcome.html b/spring-web-modules/spring-mvc-basics-4/src/main/resources/templates/welcome.html new file mode 100644 index 0000000000..c5b88e135e --- /dev/null +++ b/spring-web-modules/spring-mvc-basics-4/src/main/resources/templates/welcome.html @@ -0,0 +1,10 @@ + + + + + Insert title here + + +Data returned is + + \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/resources/test-mvc.xml b/spring-web-modules/spring-mvc-basics-4/src/main/resources/test-mvc.xml deleted file mode 100644 index 44c300dfc6..0000000000 --- a/spring-web-modules/spring-mvc-basics-4/src/main/resources/test-mvc.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - /WEB-INF/ - - - .jsp - - - \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/greeting.xml b/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/greeting.xml deleted file mode 100644 index 1ad5484d80..0000000000 --- a/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/greeting.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/index.jsp b/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/index.jsp deleted file mode 100644 index c38169bb95..0000000000 --- a/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/index.jsp +++ /dev/null @@ -1,5 +0,0 @@ - - -

Hello World!

- - diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/normal-webapp-servlet.xml b/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/normal-webapp-servlet.xml deleted file mode 100644 index 8addbe3cf3..0000000000 --- a/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/normal-webapp-servlet.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/rootApplicationContext.xml b/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/rootApplicationContext.xml deleted file mode 100644 index 12e5d8f161..0000000000 --- a/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/rootApplicationContext.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/secure-webapp-servlet.xml b/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/secure-webapp-servlet.xml deleted file mode 100644 index 86797ad081..0000000000 --- a/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/secure-webapp-servlet.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/secure/view/welcome.jsp b/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/secure/view/welcome.jsp deleted file mode 100644 index 49ca0f8e87..0000000000 --- a/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/secure/view/welcome.jsp +++ /dev/null @@ -1,11 +0,0 @@ - - - Spring Web Contexts - - -
-
- Secure Web Application : ${message} -
- - \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/view/sample.jsp b/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/view/sample.jsp deleted file mode 100644 index 4c64bf97f2..0000000000 --- a/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/view/sample.jsp +++ /dev/null @@ -1,7 +0,0 @@ - - - - -

This is the body of the sample view

- - \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/view/scopesExample.jsp b/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/view/scopesExample.jsp deleted file mode 100644 index e9abcf194c..0000000000 --- a/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/view/scopesExample.jsp +++ /dev/null @@ -1,10 +0,0 @@ - - - - -

Bean Scopes Examples

-
Previous Message: ${previousMessage } -
Current Message: ${currentMessage } -
- - \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/web-old.xml b/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/web-old.xml deleted file mode 100644 index 1344362d19..0000000000 --- a/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/web-old.xml +++ /dev/null @@ -1,88 +0,0 @@ - - - - - - - - - - - - - - - - - - - normal-webapp-annotations - - org.springframework.web.servlet.DispatcherServlet - - - contextClass - org.springframework.web.context.support.AnnotationConfigWebApplicationContext - - - contextConfigLocation - com.baeldung.contexts.config.NormalWebAppConfig - - 1 - - - normal-webapp-annotations - /api-ann/* - - - - /WEB-INF/index.jsp - - diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/welcome.jsp b/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/welcome.jsp deleted file mode 100644 index c34223b411..0000000000 --- a/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/welcome.jsp +++ /dev/null @@ -1,12 +0,0 @@ -<%@ page language="java" contentType="text/html; charset=UTF-8" - pageEncoding="UTF-8" %> - - - - - Insert title here - - -Data returned is ${data} - - \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/webapp/index.jsp b/spring-web-modules/spring-mvc-basics-4/src/main/webapp/index.jsp deleted file mode 100644 index c38169bb95..0000000000 --- a/spring-web-modules/spring-mvc-basics-4/src/main/webapp/index.jsp +++ /dev/null @@ -1,5 +0,0 @@ - - -

Hello World!

- - diff --git a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/controller/ControllerAnnotationIntegrationTest.java b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/controller/ControllerAnnotationIntegrationTest.java index f378357548..7fd8f0c97f 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/controller/ControllerAnnotationIntegrationTest.java +++ b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/controller/ControllerAnnotationIntegrationTest.java @@ -1,26 +1,24 @@ package com.baeldung.controller; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.baeldung.controller.config.WebConfig; -import com.baeldung.controller.student.Student; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; 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.web.AnnotationConfigWebContextLoader; -import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.servlet.ModelAndView; -@RunWith(SpringJUnit4ClassRunner.class) -@WebAppConfiguration -@ContextConfiguration(classes = { WebConfig.class }, loader = AnnotationConfigWebContextLoader.class) +import com.baeldung.controller.student.Student; +import com.baeldung.validation.listvalidation.SpringListValidationApplication; +import com.fasterxml.jackson.databind.ObjectMapper; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringListValidationApplication.class) public class ControllerAnnotationIntegrationTest { private MockMvc mockMvc; diff --git a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/controller/ControllerIntegrationTest.java b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/controller/ControllerIntegrationTest.java index 7e5cf1532e..a7e6bd6c4b 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/controller/ControllerIntegrationTest.java +++ b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/controller/ControllerIntegrationTest.java @@ -5,9 +5,8 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; 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.web.WebAppConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders; @@ -15,11 +14,11 @@ import org.springframework.web.context.WebApplicationContext; import org.springframework.web.servlet.ModelAndView; import com.baeldung.controller.student.Student; +import com.baeldung.validation.listvalidation.SpringListValidationApplication; import com.fasterxml.jackson.databind.ObjectMapper; -@RunWith(SpringJUnit4ClassRunner.class) -@WebAppConfiguration -@ContextConfiguration({ "classpath:test-mvc.xml" }) +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringListValidationApplication.class) public class ControllerIntegrationTest { private MockMvc mockMvc; diff --git a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/controller/GreetingsControllerUnitTest.java b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/controller/GreetingsControllerUnitTest.java index ee9a8da8d4..4917d68ef4 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/controller/GreetingsControllerUnitTest.java +++ b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/controller/GreetingsControllerUnitTest.java @@ -1,24 +1,21 @@ package com.baeldung.controller; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.baeldung.controller.controller.GreetingsController; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; 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.web.AnnotationConfigWebContextLoader; -import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -@RunWith(SpringJUnit4ClassRunner.class) -@WebAppConfiguration -@ContextConfiguration(classes = { GreetingsController.class }, loader = AnnotationConfigWebContextLoader.class) +import com.baeldung.validation.listvalidation.SpringListValidationApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringListValidationApplication.class) public class GreetingsControllerUnitTest { private MockMvc mockMvc; diff --git a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/controller/PassParametersControllerIntegrationTest.java b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/controller/PassParametersControllerIntegrationTest.java index aa8148c1ef..7408ae825d 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/controller/PassParametersControllerIntegrationTest.java +++ b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/controller/PassParametersControllerIntegrationTest.java @@ -5,24 +5,24 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; 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.web.WebAppConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.servlet.ModelAndView; +import com.baeldung.validation.listvalidation.SpringListValidationApplication; + /** * This is the test class for {@link com.baeldung.controller.controller.PassParametersController} class. * 09/09/2017 * * @author Ahmet Cetin */ -@RunWith(SpringJUnit4ClassRunner.class) -@WebAppConfiguration -@ContextConfiguration({"classpath:test-mvc.xml"}) +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringListValidationApplication.class) public class PassParametersControllerIntegrationTest { private MockMvc mockMvc; @@ -39,7 +39,7 @@ public class PassParametersControllerIntegrationTest { ModelAndView mv = this.mockMvc.perform(MockMvcRequestBuilders.get("/showViewPage")).andReturn().getModelAndView(); //Validate view - Assert.assertEquals(mv.getViewName(), "viewPage"); + Assert.assertEquals(mv.getViewName(), "view/viewPage"); //Validate attribute Assert.assertEquals(mv.getModelMap().get("message").toString(), "Baeldung"); @@ -50,7 +50,7 @@ public class PassParametersControllerIntegrationTest { ModelAndView mv = this.mockMvc.perform(MockMvcRequestBuilders.get("/printViewPage")).andReturn().getModelAndView(); //Validate view - Assert.assertEquals(mv.getViewName(), "viewPage"); + Assert.assertEquals(mv.getViewName(), "view/viewPage"); //Validate attribute Assert.assertEquals(mv.getModelMap().get("message").toString(), "Baeldung"); @@ -61,7 +61,7 @@ public class PassParametersControllerIntegrationTest { ModelAndView mv = this.mockMvc.perform(MockMvcRequestBuilders.get("/goToViewPage")).andReturn().getModelAndView(); //Validate view - Assert.assertEquals(mv.getViewName(), "viewPage"); + Assert.assertEquals(mv.getViewName(), "view/viewPage"); //Validate attribute Assert.assertEquals(mv.getModelMap().get("message").toString(), "Baeldung"); diff --git a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/jsonparams/JsonParamsIntegrationTest.java b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/jsonparams/JsonParamsIntegrationTest.java index bceadc4896..9d414ed4ca 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/jsonparams/JsonParamsIntegrationTest.java +++ b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/jsonparams/JsonParamsIntegrationTest.java @@ -1,26 +1,25 @@ package com.baeldung.jsonparams; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + import org.junit.Before; 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.http.MediaType; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.AnnotationConfigWebContextLoader; -import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; +import com.baeldung.validation.listvalidation.SpringListValidationApplication; -import com.baeldung.jsonparams.config.JsonParamsConfig; - -@RunWith(SpringJUnit4ClassRunner.class) -@WebAppConfiguration -@ContextConfiguration(classes = { JsonParamsConfig.class }, loader = AnnotationConfigWebContextLoader.class) +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringListValidationApplication.class) public class JsonParamsIntegrationTest { private MockMvc mockMvc; diff --git a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerControllerIntegrationTest.java b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerControllerIntegrationTest.java deleted file mode 100644 index 0e2313c2ac..0000000000 --- a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerControllerIntegrationTest.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.baeldung.optionalpathvars; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -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.web.WebAppConfiguration; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; -import org.springframework.test.web.servlet.result.MockMvcResultMatchers; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.web.context.WebApplicationContext; -import com.baeldung.controller.config.WebConfig; - -@RunWith(SpringJUnit4ClassRunner.class) -@WebAppConfiguration -@ContextConfiguration(classes = { WebConfig.class }) -public class ArticleViewerControllerIntegrationTest { - - @Autowired - private WebApplicationContext wac; - - private MockMvc mockMvc; - - @Before - public void setup() throws Exception { - this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); - } - - @Test - public void whenIdPathVariableIsPassed_thenResponseOK() throws Exception { - - int articleId = 5; - - this.mockMvc - .perform(MockMvcRequestBuilders.get("/article/{id}", articleId)) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(MockMvcResultMatchers.jsonPath("$.id").value(articleId)); - - } - - @Test - public void whenIdPathVariableIsNotPassed_thenResponse500() throws Exception { - - this.mockMvc - .perform(MockMvcRequestBuilders.get("/article")) - .andExpect(MockMvcResultMatchers.status().isInternalServerError()); - - } - - -} \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerControllerWithOptionalParamIntegrationTest.java b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerControllerWithOptionalParamIntegrationTest.java index 094995ba67..2685946b4c 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerControllerWithOptionalParamIntegrationTest.java +++ b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerControllerWithOptionalParamIntegrationTest.java @@ -4,19 +4,18 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; 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.web.WebAppConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -import com.baeldung.controller.config.WebConfig; -@RunWith(SpringJUnit4ClassRunner.class) -@WebAppConfiguration -@ContextConfiguration(classes = { WebConfig.class }) +import com.baeldung.validation.listvalidation.SpringListValidationApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringListValidationApplication.class) public class ArticleViewerControllerWithOptionalParamIntegrationTest { @Autowired diff --git a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerControllerWithRequiredAttributeIntegrationTest.java b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerControllerWithRequiredAttributeIntegrationTest.java index a4b12c7163..e7d864d9be 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerControllerWithRequiredAttributeIntegrationTest.java +++ b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerControllerWithRequiredAttributeIntegrationTest.java @@ -12,42 +12,38 @@ import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -import com.baeldung.controller.config.WebConfig; +import com.baeldung.validation.listvalidation.SpringListValidationApplication; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration -@ContextConfiguration(classes = { WebConfig.class }) +@ContextConfiguration(classes = { SpringListValidationApplication.class }) public class ArticleViewerControllerWithRequiredAttributeIntegrationTest { @Autowired private WebApplicationContext wac; - + private MockMvc mockMvc; @Before - public void setup() throws Exception { + public void setup() { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); } @Test - public void givenRequiredAttributeIsFalse_whenIdPathVariableIsPassed_thenResponseOK() throws Exception { - - int articleId = 154; + public void whenIdPathVariableIsPassed_thenResponseOK() throws Exception { + int articleId = 5; this.mockMvc .perform(MockMvcRequestBuilders.get("/requiredAttribute/article/{id}", articleId)) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.jsonPath("$.id").value(articleId)); - } - + @Test - public void givenRequiredAttributeIsFalse_whenIdPathVariableIsNotPassed_thenResponseOK() throws Exception { - + public void whenIdPathVariableIsNotPassed_thenResponseOK() throws Exception { this.mockMvc .perform(MockMvcRequestBuilders.get("/requiredAttribute/article")) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(MockMvcResultMatchers.jsonPath("$.id").value(Article.DEFAULT_ARTICLE.getId())); - + .andExpect(MockMvcResultMatchers.status().isOk()); + } } \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerWithMapParamIntegrationTest.java b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerWithMapParamIntegrationTest.java index 044a1c8bce..2be6d1e679 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerWithMapParamIntegrationTest.java +++ b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerWithMapParamIntegrationTest.java @@ -4,19 +4,18 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; 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.web.WebAppConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -import com.baeldung.controller.config.WebConfig; -@RunWith(SpringJUnit4ClassRunner.class) -@WebAppConfiguration -@ContextConfiguration(classes = { WebConfig.class }) +import com.baeldung.validation.listvalidation.SpringListValidationApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringListValidationApplication.class) public class ArticleViewerWithMapParamIntegrationTest { @Autowired diff --git a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerWithTwoSeparateMethodsIntegrationTest.java b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerWithTwoSeparateMethodsIntegrationTest.java index 1ca926277d..e70ac5e5a6 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerWithTwoSeparateMethodsIntegrationTest.java +++ b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerWithTwoSeparateMethodsIntegrationTest.java @@ -4,19 +4,18 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; 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.web.WebAppConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -import com.baeldung.controller.config.WebConfig; -@RunWith(SpringJUnit4ClassRunner.class) -@WebAppConfiguration -@ContextConfiguration(classes = { WebConfig.class }) +import com.baeldung.validation.listvalidation.SpringListValidationApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringListValidationApplication.class) public class ArticleViewerWithTwoSeparateMethodsIntegrationTest { @Autowired diff --git a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/validation/listvalidation/MovieControllerIntegrationTest.java b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/validation/listvalidation/MovieControllerIntegrationTest.java index cddc6c6bd9..14ceb651d7 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/validation/listvalidation/MovieControllerIntegrationTest.java +++ b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/validation/listvalidation/MovieControllerIntegrationTest.java @@ -34,7 +34,7 @@ public class MovieControllerIntegrationTest { Movie movie = new Movie("Movie3"); movies.add(movie); mvc.perform(MockMvcRequestBuilders.post("/movies") - .contentType(MediaType.APPLICATION_JSON_UTF8) + .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(movies))) .andExpect(MockMvcResultMatchers.status() .isOk()); @@ -44,7 +44,7 @@ public class MovieControllerIntegrationTest { public void givenEmptyMovieList_whenAddingMovieList_thenThrowBadRequest() throws Exception { List movies = new ArrayList<>(); mvc.perform(MockMvcRequestBuilders.post("/movies") - .contentType(MediaType.APPLICATION_JSON_UTF8) + .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(movies))) .andExpect(MockMvcResultMatchers.status() .isBadRequest()); @@ -54,7 +54,7 @@ public class MovieControllerIntegrationTest { public void givenEmptyMovieName_whenAddingMovieList_thenThrowBadRequest() throws Exception { Movie movie = new Movie(""); mvc.perform(MockMvcRequestBuilders.post("/movies") - .contentType(MediaType.APPLICATION_JSON_UTF8) + .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(Arrays.asList(movie)))) .andExpect(MockMvcResultMatchers.status() .isBadRequest()); @@ -74,7 +74,7 @@ public class MovieControllerIntegrationTest { movies.add(movie4); movies.add(movie5); mvc.perform(MockMvcRequestBuilders.post("/movies") - .contentType(MediaType.APPLICATION_JSON_UTF8) + .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(movies))) .andExpect(MockMvcResultMatchers.status() .isBadRequest()); diff --git a/spring-web-modules/spring-mvc-basics-4/src/test/resources/test-mvc.xml b/spring-web-modules/spring-mvc-basics-4/src/test/resources/test-mvc.xml deleted file mode 100644 index f1aa8e9504..0000000000 --- a/spring-web-modules/spring-mvc-basics-4/src/test/resources/test-mvc.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - /WEB-INF/ - - - .jsp - - - \ No newline at end of file diff --git a/testing-modules/instancio/pom.xml b/testing-modules/instancio/pom.xml index 137da91897..7687ce282d 100644 --- a/testing-modules/instancio/pom.xml +++ b/testing-modules/instancio/pom.xml @@ -51,8 +51,8 @@ - 2.6.0 + 2.9.0 2.14.1 5.9.2 - \ No newline at end of file + diff --git a/testing-modules/junit5-annotations/pom.xml b/testing-modules/junit5-annotations/pom.xml index a4035a23f1..847baa827c 100644 --- a/testing-modules/junit5-annotations/pom.xml +++ b/testing-modules/junit5-annotations/pom.xml @@ -15,6 +15,12 @@ + + org.junit.jupiter + junit-jupiter + ${junit-jupiter.version} + test + org.junit.platform junit-platform-engine @@ -39,7 +45,7 @@ - 2.17.1 + 2.19.0 \ No newline at end of file