diff --git a/algorithms-modules/algorithms-miscellaneous-7/README.md b/algorithms-modules/algorithms-miscellaneous-7/README.md index 881576f095..f22194e183 100644 --- a/algorithms-modules/algorithms-miscellaneous-7/README.md +++ b/algorithms-modules/algorithms-miscellaneous-7/README.md @@ -8,4 +8,7 @@ - [Find Missing Number From a Given Array in Java](https://www.baeldung.com/java-array-find-missing-number) - [Calculate Weighted Mean in Java](https://www.baeldung.com/java-compute-weighted-average) - [Check if Two Strings Are Rotations of Each Other](https://www.baeldung.com/java-string-check-strings-rotations) +- [Find the Largest Prime Under the Given Number in Java](https://www.baeldung.com/java-largest-prime-lower-threshold) +- [Count the Number of Unique Digits in an Integer using Java](https://www.baeldung.com/java-int-count-unique-digits) +- [Generate Juggler Sequence in Java](https://www.baeldung.com/java-generate-juggler-sequence) - More articles: [[<-- prev]](/algorithms-miscellaneous-6) diff --git a/algorithms-modules/algorithms-miscellaneous-7/src/main/java/com/baeldung/algorithms/largestNumberRemovingK/LargestNumberRemoveKDigits.java b/algorithms-modules/algorithms-miscellaneous-7/src/main/java/com/baeldung/algorithms/largestNumberRemovingK/LargestNumberRemoveKDigits.java new file mode 100644 index 0000000000..79086fc61f --- /dev/null +++ b/algorithms-modules/algorithms-miscellaneous-7/src/main/java/com/baeldung/algorithms/largestNumberRemovingK/LargestNumberRemoveKDigits.java @@ -0,0 +1,57 @@ +package com.baeldung.algorithms.largestNumberRemovingK; + +import java.util.*; + +public class LargestNumberRemoveKDigits { + public static int findLargestNumberUsingArithmetic(int num, int k) { + for (int j = 0; j < k; j++) { + + int result = 0; + int i = 1; + + while (num / i > 0) { + int temp = (num / (i * 10)) + * i + + (num % i); + i *= 10; + + result = Math.max(result, temp); + } + num = result; + } + + return num; + } + + public static int findLargestNumberUsingStack(int num, int k) { + String numStr = Integer.toString(num); + int length = numStr.length(); + + if (k == length) return 0; + + Stack stack = new Stack<>(); + + for (int i = 0; i < length; i++) { + char digit = numStr.charAt(i); + + while (k > 0 && !stack.isEmpty() && stack.peek() < digit) { + stack.pop(); + k--; + } + + stack.push(digit); + } + + while (k > 0) { + stack.pop(); + k--; + } + + StringBuilder result = new StringBuilder(); + while (!stack.isEmpty()) { + result.insert(0, stack.pop()); + } + + return Integer.parseInt(result.toString()); + } +} diff --git a/algorithms-modules/algorithms-miscellaneous-7/src/main/java/com/baeldung/algorithms/parentnodebinarytree/ParentKeeperTreeNode.java b/algorithms-modules/algorithms-miscellaneous-7/src/main/java/com/baeldung/algorithms/parentnodebinarytree/ParentKeeperTreeNode.java new file mode 100644 index 0000000000..2badd4c8ef --- /dev/null +++ b/algorithms-modules/algorithms-miscellaneous-7/src/main/java/com/baeldung/algorithms/parentnodebinarytree/ParentKeeperTreeNode.java @@ -0,0 +1,54 @@ +package com.baeldung.algorithms.parentnodebinarytree; + +import java.util.Objects; + +public class ParentKeeperTreeNode { + + int value; + ParentKeeperTreeNode parent; + ParentKeeperTreeNode left; + ParentKeeperTreeNode right; + + public ParentKeeperTreeNode(int value) { + this.value = value; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + ParentKeeperTreeNode treeNode = (ParentKeeperTreeNode) o; + return value == treeNode.value; + } + + @Override + public int hashCode() { + return Objects.hash(value); + } + + public void insert(int value) { + insert(this, value); + } + + private void insert(ParentKeeperTreeNode currentNode, final int value) { + if (currentNode.left == null && value < currentNode.value) { + currentNode.left = new ParentKeeperTreeNode(value); + currentNode.left.parent = currentNode; + return; + } + + if (currentNode.right == null && value > currentNode.value) { + currentNode.right = new ParentKeeperTreeNode(value); + currentNode.right.parent = currentNode; + return; + } + + if (value > currentNode.value) { + insert(currentNode.right, value); + } + + if (value < currentNode.value) { + insert(currentNode.left, value); + } + } +} diff --git a/algorithms-modules/algorithms-miscellaneous-7/src/main/java/com/baeldung/algorithms/parentnodebinarytree/TreeNode.java b/algorithms-modules/algorithms-miscellaneous-7/src/main/java/com/baeldung/algorithms/parentnodebinarytree/TreeNode.java new file mode 100644 index 0000000000..c12be08d09 --- /dev/null +++ b/algorithms-modules/algorithms-miscellaneous-7/src/main/java/com/baeldung/algorithms/parentnodebinarytree/TreeNode.java @@ -0,0 +1,107 @@ +package com.baeldung.algorithms.parentnodebinarytree; + +import java.util.Deque; +import java.util.LinkedList; +import java.util.NoSuchElementException; +import java.util.Objects; + +import static java.lang.String.format; + +public class TreeNode { + int value; + TreeNode left; + TreeNode right; + + public TreeNode(int value) { + this.value = value; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + TreeNode treeNode = (TreeNode) o; + return value == treeNode.value; + } + + @Override + public int hashCode() { + return Objects.hash(value); + } + + public void insert(int value) { + insert(this, value); + } + + private void insert(TreeNode currentNode, final int value) { + if (currentNode.left == null && value < currentNode.value) { + currentNode.left = new TreeNode(value); + return; + } + + if (currentNode.right == null && value > currentNode.value) { + currentNode.right = new TreeNode(value); + return; + } + + if (value > currentNode.value) { + insert(currentNode.right, value); + } + + if (value < currentNode.value) { + insert(currentNode.left, value); + } + } + + public TreeNode parent(int target) throws NoSuchElementException { + return parent(this, new TreeNode(target)); + } + + private TreeNode parent(TreeNode current, TreeNode target) throws NoSuchElementException { + if (target.equals(current) || current == null) { + throw new NoSuchElementException(format("No parent node found for 'target.value=%s' " + + "The target is not in the tree or the target is the topmost root node.", + target.value)); + } + + if (target.equals(current.left) || target.equals(current.right)) { + return current; + } + + return parent(target.value < current.value ? current.left : current.right, target); + } + + public TreeNode iterativeParent(int target) { + return iterativeParent(this, new TreeNode(target)); + } + + private TreeNode iterativeParent(TreeNode current, TreeNode target) { + Deque parentCandidates = new LinkedList<>(); + + String notFoundMessage = format("No parent node found for 'target.value=%s' " + + "The target is not in the tree or the target is the topmost root node.", + target.value); + + if (target.equals(current)) { + throw new NoSuchElementException(notFoundMessage); + } + + while (current != null || !parentCandidates.isEmpty()) { + + while (current != null) { + parentCandidates.addFirst(current); + current = current.left; + } + + current = parentCandidates.pollFirst(); + + if (target.equals(current.left) || target.equals(current.right)) { + return current; + } + + current = current.right; + } + + throw new NoSuchElementException(notFoundMessage); + } +} diff --git a/algorithms-modules/algorithms-miscellaneous-7/src/main/java/com/baeldung/algorithms/uniquedigit/UniqueDigitCounter.java b/algorithms-modules/algorithms-miscellaneous-7/src/main/java/com/baeldung/algorithms/uniquedigit/UniqueDigitCounter.java new file mode 100644 index 0000000000..474d31b268 --- /dev/null +++ b/algorithms-modules/algorithms-miscellaneous-7/src/main/java/com/baeldung/algorithms/uniquedigit/UniqueDigitCounter.java @@ -0,0 +1,36 @@ +package com.baeldung.algorithms.uniquedigit; + +import java.util.HashSet; +import java.util.Set; + +public class UniqueDigitCounter { + + public static int countWithSet(int number) { + number = Math.abs(number); + Set uniqueDigits = new HashSet<>(); + String numberStr = String.valueOf(number); + for (char digit : numberStr.toCharArray()) { + uniqueDigits.add(digit); + } + return uniqueDigits.size(); + } + + public static int countWithBitManipulation(int number) { + if (number == 0) { + return 1; + } + number = Math.abs(number); + int mask = 0; + while (number > 0) { + int digit = number % 10; + mask |= 1 << digit; + number /= 10; + } + return Integer.bitCount(mask); + } + + public static long countWithStreamApi(int number) { + return String.valueOf(Math.abs(number)).chars().distinct().count(); + } + +} diff --git a/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/largestNumberRemovingK/LargestNumberRemoveKDigitsUnitTest.java b/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/largestNumberRemovingK/LargestNumberRemoveKDigitsUnitTest.java new file mode 100644 index 0000000000..5325a27609 --- /dev/null +++ b/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/largestNumberRemovingK/LargestNumberRemoveKDigitsUnitTest.java @@ -0,0 +1,25 @@ +package com.baeldung.algorithms.largestNumberRemovingK; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +public class LargestNumberRemoveKDigitsUnitTest { + + @Test + public void givenNumber_UsingArithmeticRemoveKDigits_thenReturnLargestNumber(){ + Assertions.assertEquals(LargestNumberRemoveKDigits.findLargestNumberUsingArithmetic(9461, 1), 961); + Assertions.assertEquals(LargestNumberRemoveKDigits.findLargestNumberUsingArithmetic(463, 2), 6); + Assertions.assertEquals(LargestNumberRemoveKDigits.findLargestNumberUsingArithmetic(98625410, 6), 98); + Assertions.assertEquals(LargestNumberRemoveKDigits.findLargestNumberUsingArithmetic(20, 2), 0); + Assertions.assertEquals(LargestNumberRemoveKDigits.findLargestNumberUsingArithmetic(98989, 4), 9); + } + + @Test + public void givenNumber_UsingStackRemoveKDigits_thenReturnLargestNumber(){ + Assertions.assertEquals(LargestNumberRemoveKDigits.findLargestNumberUsingStack(9461, 1), 961); + Assertions.assertEquals(LargestNumberRemoveKDigits.findLargestNumberUsingStack(463, 2), 6); + Assertions.assertEquals(LargestNumberRemoveKDigits.findLargestNumberUsingStack(98625410, 6), 98); + Assertions.assertEquals(LargestNumberRemoveKDigits.findLargestNumberUsingStack(20, 2), 0); + Assertions.assertEquals(LargestNumberRemoveKDigits.findLargestNumberUsingStack(98989, 4), 9); + } +} diff --git a/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/parentnodebinarytree/BinaryTreeParentNodeFinderUnitTest.java b/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/parentnodebinarytree/BinaryTreeParentNodeFinderUnitTest.java new file mode 100644 index 0000000000..d3f0ec7997 --- /dev/null +++ b/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/parentnodebinarytree/BinaryTreeParentNodeFinderUnitTest.java @@ -0,0 +1,83 @@ +package com.baeldung.algorithms.parentnodebinarytree; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.NoSuchElementException; + +import static org.junit.jupiter.api.Assertions.*; + +class BinaryTreeParentNodeFinderUnitTest { + + private TreeNode subject; + + @BeforeEach + void setUp() { + subject = new TreeNode(8); + subject.insert(5); + subject.insert(12); + subject.insert(3); + subject.insert(7); + subject.insert(1); + subject.insert(4); + subject.insert(11); + subject.insert(14); + subject.insert(13); + subject.insert(16); + } + + @Test + void givenBinaryTree_whenFindParentNode_thenReturnCorrectParentNode() { + assertEquals(8, subject.parent(5).value); + assertEquals(5, subject.parent(3).value); + assertEquals(5, subject.parent(7).value); + assertEquals(3, subject.parent(4).value); + assertEquals(3, subject.parent(1).value); + assertEquals(8, subject.parent(12).value); + assertEquals(12, subject.parent(14).value); + assertEquals(12, subject.parent(11).value); + assertEquals(14, subject.parent(16).value); + assertEquals(14, subject.parent(13).value); + assertThrows(NoSuchElementException.class, () -> subject.parent(1231)); + assertThrows(NoSuchElementException.class, () -> subject.parent(8)); + } + + @Test + void givenBinaryTree_whenFindParentNodeIteratively_thenReturnCorrectParentNode() { + assertEquals(8, subject.iterativeParent(5).value); + assertEquals(5, subject.iterativeParent(3).value); + assertEquals(5, subject.iterativeParent(7).value); + assertEquals(3, subject.iterativeParent(4).value); + assertEquals(3, subject.iterativeParent(1).value); + assertEquals(8, subject.iterativeParent(12).value); + assertEquals(12, subject.iterativeParent(14).value); + assertEquals(12, subject.iterativeParent(11).value); + assertEquals(14, subject.iterativeParent(16).value); + assertEquals(14, subject.iterativeParent(13).value); + assertThrows(NoSuchElementException.class, () -> subject.iterativeParent(1231)); + assertThrows(NoSuchElementException.class, () -> subject.iterativeParent(8)); + } + + @Test + void givenParentKeeperBinaryTree_whenGetParent_thenReturnCorrectParent() { + ParentKeeperTreeNode subject = new ParentKeeperTreeNode(8); + subject.insert(5); + subject.insert(12); + subject.insert(3); + subject.insert(7); + subject.insert(1); + subject.insert(4); + subject.insert(11); + subject.insert(14); + subject.insert(13); + subject.insert(16); + + assertNull(subject.parent); + assertEquals(8, subject.left.parent.value); + assertEquals(8, subject.right.parent.value); + assertEquals(5, subject.left.left.parent.value); + assertEquals(5, subject.left.right.parent.value); + + // tests for other nodes + } +} \ No newline at end of file diff --git a/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/uniquedigit/UniqueDigitCounterUnitTest.java b/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/uniquedigit/UniqueDigitCounterUnitTest.java new file mode 100644 index 0000000000..5acdc9df72 --- /dev/null +++ b/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/uniquedigit/UniqueDigitCounterUnitTest.java @@ -0,0 +1,38 @@ +package com.baeldung.algorithms.uniquedigit; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class UniqueDigitCounterUnitTest { + + @Test + public void givenNotNegativeNumber_whenCountUniqueDigits_thenCorrectCount() { + assertEquals(3, UniqueDigitCounter.countWithSet(122333)); + assertEquals(1, UniqueDigitCounter.countWithSet(0)); + assertEquals(2, UniqueDigitCounter.countWithSet(101)); + + assertEquals(3, UniqueDigitCounter.countWithBitManipulation(122333)); + assertEquals(1, UniqueDigitCounter.countWithBitManipulation(0)); + assertEquals(2, UniqueDigitCounter.countWithBitManipulation(101)); + + assertEquals(3, UniqueDigitCounter.countWithStreamApi(122333)); + assertEquals(1, UniqueDigitCounter.countWithStreamApi(0)); + assertEquals(2, UniqueDigitCounter.countWithStreamApi(101)); + } + + @Test + public void givenNegativeNumber_whenCountUniqueDigits_thenCorrectCount() { + assertEquals(3, UniqueDigitCounter.countWithSet(-122333)); + assertEquals(3, UniqueDigitCounter.countWithBitManipulation(-122333)); + assertEquals(3, UniqueDigitCounter.countWithStreamApi(-122333)); + } + + @Test + public void givenLargeNumber_whenCountUniqueDigits_thenCorrectCount() { + assertEquals(2, UniqueDigitCounter.countWithSet(1000000000)); + assertEquals(2, UniqueDigitCounter.countWithBitManipulation(1000000000)); + assertEquals(2, UniqueDigitCounter.countWithStreamApi(1000000000)); + } + +} diff --git a/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/vigenere/VigenereCipher.java b/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/vigenere/VigenereCipher.java new file mode 100644 index 0000000000..37a7c13d17 --- /dev/null +++ b/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/vigenere/VigenereCipher.java @@ -0,0 +1,69 @@ +package com.baeldung.algorithms.vigenere; + +public class VigenereCipher { + private final String characters; + + public VigenereCipher() { + this("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); + } + + public VigenereCipher(String characters) { + this.characters = characters; + } + + public String encode(String input, String key) { + String result = ""; + + int keyPosition = 0; + for (char c : input.toCharArray()) { + char k = key.charAt(keyPosition % key.length()); + + int charIndex = characters.indexOf(c); + int keyIndex = characters.indexOf(k); + + if (charIndex >= 0) { + if (keyIndex >= 0) { + int newCharIndex = (charIndex + keyIndex + 1) % characters.length(); + c = characters.charAt(newCharIndex); + + } + + keyPosition++; + } + + result += c; + } + + return result; + } + + public String decode(String input, String key) { + String result = ""; + + int keyPosition = 0; + for (char c : input.toCharArray()) { + char k = key.charAt(keyPosition % key.length()); + + int charIndex = characters.indexOf(c); + int keyIndex = characters.indexOf(k); + + if (charIndex >= 0) { + if (keyIndex >= 0) { + int newCharIndex = charIndex - keyIndex - 1; + if (newCharIndex < 0) { + newCharIndex = characters.length() + newCharIndex; + } + c = characters.charAt(newCharIndex); + + } + + keyPosition++; + } + + result += c; + } + + return result; + } + +} diff --git a/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/vigenere/VigenereCipherUnitTest.java b/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/vigenere/VigenereCipherUnitTest.java new file mode 100644 index 0000000000..0e61e9c42e --- /dev/null +++ b/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/vigenere/VigenereCipherUnitTest.java @@ -0,0 +1,63 @@ +package com.baeldung.algorithms.vigenere; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +public class VigenereCipherUnitTest { + + @Test + void encodeBaeldung() { + VigenereCipher cipher = new VigenereCipher(); + String output = cipher.encode("BAELDUNG", "HELLO"); + + Assertions.assertEquals("JFQXSCSS", output); + } + + @Test + void encodeBaeldungMixedCharacters() { + VigenereCipher cipher = new VigenereCipher("JQFVHPWORZSLNMKYCGBUXIEDTA"); + String output = cipher.encode("BAELDUNG", "HELLO"); + + Assertions.assertEquals("DERDPTZV", output); + } + + @Test + void encodeArticleTitle() { + VigenereCipher cipher = new VigenereCipher(); + String output = cipher.encode("VEGENERE CIPHER IN JAVA", "BAELDUNG"); + + Assertions.assertEquals("XFLQRZFL EJUTIM WU LBAM", output); + } + + @Test + void encodeArticleTitleMoreCharacters() { + VigenereCipher cipher = new VigenereCipher("ABCDEFGHIJKLMNOPQRSTUVWXYZ "); + String output = cipher.encode("VEGENERE CIPHER IN JAVA", "BAELDUNG"); + + Assertions.assertEquals("XFLQRZELBDNALZEGKOEVEPO", output); + } + + @Test + void decodeBaeldung() { + VigenereCipher cipher = new VigenereCipher(); + String output = cipher.decode("JFQXSCSS", "HELLO"); + + Assertions.assertEquals("BAELDUNG", output); + } + + @Test + void decodeBaeldungMixedCharacters() { + VigenereCipher cipher = new VigenereCipher("JQFVHPWORZSLNMKYCGBUXIEDTA"); + String output = cipher.decode("DERDPTZV", "HELLO"); + + Assertions.assertEquals("BAELDUNG", output); + } + + @Test + void decodeArticleTitleMoreCharacters() { + VigenereCipher cipher = new VigenereCipher("ABCDEFGHIJKLMNOPQRSTUVWXYZ "); + String output = cipher.decode("XFLQRZELBDNALZEGKOEVEPO", "BAELDUNG"); + + Assertions.assertEquals("VEGENERE CIPHER IN JAVA", output); + } +} diff --git a/apache-httpclient4/pom.xml b/apache-httpclient4/pom.xml index 90890ef7b9..2647f977e4 100644 --- a/apache-httpclient4/pom.xml +++ b/apache-httpclient4/pom.xml @@ -82,7 +82,7 @@ org.springframework spring-oxm - ${spring.version} + ${spring-oxm.version} @@ -233,6 +233,7 @@ + 6.1.4 1.16.0 4.1.5 diff --git a/aws-modules/aws-s3/pom.xml b/aws-modules/aws-s3/pom.xml index 71385a2738..f63158b889 100644 --- a/aws-modules/aws-s3/pom.xml +++ b/aws-modules/aws-s3/pom.xml @@ -20,6 +20,12 @@ s3 ${aws-java-sdk-v2.version} + + software.amazon.awssdk + url-connection-client + ${aws.java.sdk.version} + test + commons-io @@ -37,9 +43,32 @@ commons-codec ${commons-codec.version} + + + com.adobe.testing + s3mock + ${com.adobe.testing.version} + test + + + com.adobe.testing + s3mock-testcontainers + ${com.adobe.testing.version} + test + + + + org.testcontainers + junit-jupiter + ${org.testcontainers.version} + test + + 2.20.52 + 3.3.0 + 1.19.4 1.10.L001 0.9.4.0014L diff --git a/aws-modules/aws-s3/src/main/java/com/baeldung/s3/S3CrudService.java b/aws-modules/aws-s3/src/main/java/com/baeldung/s3/S3CrudService.java new file mode 100644 index 0000000000..75990516b2 --- /dev/null +++ b/aws-modules/aws-s3/src/main/java/com/baeldung/s3/S3CrudService.java @@ -0,0 +1,65 @@ +package com.baeldung.s3; + +import java.util.Optional; + +import software.amazon.awssdk.core.ResponseBytes; +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.CreateBucketRequest; +import software.amazon.awssdk.services.s3.model.DeleteObjectRequest; +import software.amazon.awssdk.services.s3.model.GetObjectRequest; +import software.amazon.awssdk.services.s3.model.GetObjectResponse; +import software.amazon.awssdk.services.s3.model.PutObjectRequest; +import software.amazon.awssdk.services.s3.model.S3Exception; + +public class S3CrudService { + + private final S3Client s3Client; + + public S3CrudService(S3Client s3Client) { + this.s3Client = s3Client; + } + + public void createBucket(String bucketName) { + CreateBucketRequest bucketRequest = CreateBucketRequest.builder() + .bucket(bucketName) + .build(); + + s3Client.createBucket(bucketRequest); + } + + public void createObject(String bucketName, File inMemoryObject) { + PutObjectRequest request = PutObjectRequest.builder() + .bucket(bucketName) + .key(inMemoryObject.getName()) + .build(); + s3Client.putObject(request, RequestBody.fromByteBuffer(inMemoryObject.getContent())); + } + + public Optional getObject(String bucketName, String objectKey) { + try { + GetObjectRequest getObjectRequest = GetObjectRequest.builder() + .bucket(bucketName) + .key(objectKey) + .build(); + ResponseBytes responseResponseBytes = s3Client.getObjectAsBytes(getObjectRequest); + return Optional.of(responseResponseBytes.asByteArray()); + } catch (S3Exception e) { + return Optional.empty(); + } + } + + public boolean deleteObject(String bucketName, String objectKey) { + try { + DeleteObjectRequest deleteObjectRequest = DeleteObjectRequest.builder() + .bucket(bucketName) + .key(objectKey) + .build(); + + s3Client.deleteObject(deleteObjectRequest); + return true; + } catch (S3Exception e) { + return false; + } + } +} diff --git a/aws-modules/aws-s3/src/test/java/com/baeldung/s3/S3CrudServiceLiveTest.java b/aws-modules/aws-s3/src/test/java/com/baeldung/s3/S3CrudServiceLiveTest.java new file mode 100644 index 0000000000..4201881e31 --- /dev/null +++ b/aws-modules/aws-s3/src/test/java/com/baeldung/s3/S3CrudServiceLiveTest.java @@ -0,0 +1,82 @@ +package com.baeldung.s3; + +import static org.assertj.core.api.Assertions.assertThat; +import static software.amazon.awssdk.http.SdkHttpConfigurationOption.TRUST_ALL_CERTIFICATES; + +import java.net.URI; +import java.util.Arrays; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +import com.adobe.testing.s3mock.testcontainers.S3MockContainer; + +import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.S3Configuration; +import software.amazon.awssdk.utils.AttributeMap; + +// This live test needs a running Docker instance so that a S3Mock Container can be started + +@Testcontainers +public class S3CrudServiceLiveTest { + + private static final String TEST_BUCKET_NAME = "test-bucket"; + + @Container + private final S3MockContainer s3Mock = new S3MockContainer("latest"); + private S3Client s3Client; + + @BeforeEach + void setUp() { + var endpoint = s3Mock.getHttpsEndpoint(); + var serviceConfig = S3Configuration.builder() + .pathStyleAccessEnabled(true) + .build(); + var httpClient = UrlConnectionHttpClient.builder() + .buildWithDefaults(AttributeMap.builder() + .put(TRUST_ALL_CERTIFICATES, Boolean.TRUE) + .build()); + s3Client = S3Client.builder() + .endpointOverride(URI.create(endpoint)) + .serviceConfiguration(serviceConfig) + .httpClient(httpClient) + .build(); + } + + @Test + void whenVerifyingCreationOfS3Bucket_thenCorrect() { + var s3CrudService = new S3CrudService(s3Client); + s3CrudService.createBucket(TEST_BUCKET_NAME); + + var createdBucketName = s3Client.listBuckets() + .buckets() + .get(0) + .name(); + assertThat(TEST_BUCKET_NAME).isEqualTo(createdBucketName); + } + + @Test + void whenCreatingAnObjectOnS3Bucket_thenSameObjectIsRetrived() { + var s3CrudService = new S3CrudService(s3Client); + s3CrudService.createBucket(TEST_BUCKET_NAME); + + var fileToSave = FileGenerator.generateFiles(1, 100) + .get(0); + s3CrudService.createObject(TEST_BUCKET_NAME, fileToSave); + + var savedFileContent = s3CrudService.getObject(TEST_BUCKET_NAME, fileToSave.getName()); + + assertThat(Arrays.equals(fileToSave.getContent() + .array(), savedFileContent.orElse(new byte[] {}))).isTrue(); + + s3CrudService.deleteObject(TEST_BUCKET_NAME, fileToSave.getName()); + + var deletedFileContent = s3CrudService.getObject(TEST_BUCKET_NAME, fileToSave.getName()); + assertThat(deletedFileContent).isEmpty(); + } +} + + diff --git a/core-java-modules/core-java-arrays-operations-advanced-2/src/main/java/com/baeldung/majorityelement/FindMajorityElement.java b/core-java-modules/core-java-arrays-operations-advanced-2/src/main/java/com/baeldung/majorityelement/FindMajorityElement.java new file mode 100644 index 0000000000..04da571a6c --- /dev/null +++ b/core-java-modules/core-java-arrays-operations-advanced-2/src/main/java/com/baeldung/majorityelement/FindMajorityElement.java @@ -0,0 +1,95 @@ +package com.baeldung.majorityelement; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +public class FindMajorityElement { + + public static Integer findMajorityElementUsingForLoop(int[] nums) { + int majorityThreshold = nums.length / 2; + Integer majorityElement = null; + for (int i = 0; i < nums.length; i++) { + int count = 0; + for (int j = 0; j < nums.length; j++) { + if (nums[i] == nums[j]) { + count++; + } + } + if (count > majorityThreshold) { + return majorityElement = nums[i]; + } + } + return majorityElement; + } + + public static Integer findMajorityElementUsingSorting(int[] nums) { + Arrays.sort(nums); + int majorityThreshold = nums.length / 2; + int count = 0; + for (int i = 0; i < nums.length; i++) { + if (nums[i] == nums[majorityThreshold]) { + count++; + } + + if (count > majorityThreshold) { + return nums[majorityThreshold]; + } + } + return null; + } + + public static Integer findMajorityElementUsingHashMap(int[] nums) { + Map frequencyMap = new HashMap<>(); + + for (int num : nums) { + frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1); + } + + int majorityThreshold = nums.length / 2; + for (Map.Entry entry : frequencyMap.entrySet()) { + if (entry.getValue() > majorityThreshold) { + return entry.getKey(); + } + } + return null; + } + + public static Integer findMajorityElementUsingMooreVoting(int[] nums) { + int majorityThreshold = nums.length / 2; + int candidate = nums[0]; + int count = 1; + + for (int i = 1; i < nums.length; i++) { + if (count == 0) { + candidate = nums[i]; + count = 1; + } else if (candidate == nums[i]) { + count++; + } else { + count--; + } + + System.out.println("Iteration " + i + ": [candidate - " + candidate + ", count - " + count + ", element - " + nums[i] + "]"); + } + + count = 0; + for (int num : nums) { + if (num == candidate) { + count++; + } + } + return count > majorityThreshold ? candidate : null; + } + + public static void main(String[] args) { + int[] nums = { 2, 3, 2, 4, 2, 5, 2 }; + Integer majorityElement = findMajorityElementUsingMooreVoting(nums); + + if (majorityElement != null) { + System.out.println("Majority element with maximum occurrences: " + majorityElement); + } else { + System.out.println("No majority element found"); + } + } +} diff --git a/core-java-modules/core-java-arrays-operations-advanced-2/src/test/java/com/baeldung/majorityelement/FindMajorityElementUnitTest.java b/core-java-modules/core-java-arrays-operations-advanced-2/src/test/java/com/baeldung/majorityelement/FindMajorityElementUnitTest.java new file mode 100644 index 0000000000..4e3abf9a49 --- /dev/null +++ b/core-java-modules/core-java-arrays-operations-advanced-2/src/test/java/com/baeldung/majorityelement/FindMajorityElementUnitTest.java @@ -0,0 +1,64 @@ +package com.baeldung.majorityelement; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +public class FindMajorityElementUnitTest { + + @Test + void givenArrayWithMajorityElement_WhenUsingForLoop_ThenReturnFound() { + int[] nums = { 2, 3, 2, 4, 2, 5, 2 }; + Integer result = FindMajorityElement.findMajorityElementUsingForLoop(nums); + assertEquals(2, result); + } + + @Test + void givenArrayWithoutMajorityElement_WhenUsingForLoop_ThenNotFound() { + int[] nums = { 2, 2, 3, 3 }; + Integer result = FindMajorityElement.findMajorityElementUsingForLoop(nums); + assertEquals(null, result); + } + + @Test + public void givenArrayWithMajorityElement_WhenUsingSorting_ThenReturnFound() { + int[] nums = { 2, 3, 2, 4, 2, 5, 2 }; + Integer result = FindMajorityElement.findMajorityElementUsingSorting(nums); + assertEquals(2, result); + } + + @Test + public void givenArrayWithoutMajorityElement_WhenUsingSorting_ThenNotFound() { + int[] nums = { 2, 2, 3, 3 }; + Integer result = FindMajorityElement.findMajorityElementUsingSorting(nums); + assertEquals(null, result); + } + + @Test + void givenArrayWithMajorityElement_WhenUsingHashMap_ThenReturnFound() { + int[] nums = { 2, 3, 2, 4, 2, 5, 2 }; + Integer result = FindMajorityElement.findMajorityElementUsingHashMap(nums); + assertEquals(2, result); + } + + @Test + void givenArrayWithoutMajorityElement_WhenUsingHashMap_ThenNotFound() { + int[] nums = { 2, 2, 3, 3 }; + Integer result = FindMajorityElement.findMajorityElementUsingHashMap(nums); + assertEquals(null, result); + } + + @Test + void givenArrayWithMajorityElement_WhenUsingMooreVoting_ThenReturnFound() { + int[] nums = { 2, 3, 2, 4, 2, 5, 2 }; + Integer result = FindMajorityElement.findMajorityElementUsingMooreVoting(nums); + assertEquals(2, result); + } + + @Test + void givenArrayWithoutMajorityElement_WhenUsingMooreVoting_ThenNotFound() { + int[] nums = { 2, 2, 3, 3 }; + Integer result = FindMajorityElement.findMajorityElementUsingMooreVoting(nums); + assertEquals(null, result); + } +} diff --git a/core-java-modules/core-java-collections-list-6/README.md b/core-java-modules/core-java-collections-list-6/README.md index bf634fb79c..8a8ed181c6 100644 --- a/core-java-modules/core-java-collections-list-6/README.md +++ b/core-java-modules/core-java-collections-list-6/README.md @@ -4,3 +4,4 @@ - [Call a Method on Each Element of a List in Java](https://www.baeldung.com/java-call-method-each-list-item) - [Sorting One List Based on Another List in Java](https://www.baeldung.com/java-sorting-one-list-using-another) - [Reset ListIterator to First Element of the List in Java](https://www.baeldung.com/java-reset-listiterator) +- [Modify and Print List Items With Java Streams](https://www.baeldung.com/java-stream-list-update-print-elements) diff --git a/core-java-modules/core-java-networking-4/src/test/java/com/baeldung/obtainlastsegmentofurl/ObtainLastSegmentOfURLUnitTest.java b/core-java-modules/core-java-networking-4/src/test/java/com/baeldung/obtainlastsegmentofurl/ObtainLastSegmentOfURLUnitTest.java new file mode 100644 index 0000000000..153e37dbda --- /dev/null +++ b/core-java-modules/core-java-networking-4/src/test/java/com/baeldung/obtainlastsegmentofurl/ObtainLastSegmentOfURLUnitTest.java @@ -0,0 +1,72 @@ +package com.baeldung.obtainlastsegmentofurl; + +import org.apache.commons.io.FilenameUtils; + +import org.junit.Test; + +import java.net.URI; +import java.net.URISyntaxException; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +public class ObtainLastSegmentOfURLUnitTest { + @Test + public void givenURL_whenUsingURIClass_thenGetLastPathSegment() throws URISyntaxException { + URI uri = new URI("https://www.example.com/path/to/resource"); + String path = uri.getPath(); + + String[] segments = path.split("/"); + String lastSegment = segments[segments.length - 1]; + + assertEquals("resource", lastSegment); + } + + @Test + public void givenURL_whenUsingPathClass_thenGetLastPathSegment() { + String exampleURI = "https://www.example.com/path/to/resource"; + + try { + URI uri = new URI(exampleURI); + String pathString = uri.getPath(); + Path path = Paths.get(pathString); + Path lastSegment = path.getName(path.getNameCount() - 1); + + assertEquals("resource", lastSegment.toString()); + } catch (Exception e) { + fail("Exception occurred: " + e.getMessage()); + } + } + + @Test + public void givenURL_whenUsingRegularExpression_thenGetLastPathSegment() throws URISyntaxException { + URI uri = new URI("https://www.example.com/path/to/resource"); + String path = uri.getPath(); + + Pattern pattern = Pattern.compile(".*/(.+)"); + Matcher matcher = pattern.matcher(path); + + if (!matcher.find()) { + fail("Regex pattern didn't match."); + } + + String lastSegment = matcher.group(1); + assertEquals("resource", lastSegment); + } + + @Test + public void givenURL_whenUsingFilenameUtilsClass_thenGetLastPathSegment() throws URISyntaxException { + String exampleURI = "https://www.example.com/path/to/resource"; + + URI uri = new URI(exampleURI); + String path = uri.getPath(); + + String lastSegment = FilenameUtils.getName(path); + + assertEquals("resource", lastSegment); + } +} diff --git a/core-java-modules/core-java-security-algorithms/src/test/java/com/baeldung/blowfish/BlowFishUnitTest.java b/core-java-modules/core-java-security-algorithms/src/test/java/com/baeldung/blowfish/BlowFishUnitTest.java new file mode 100644 index 0000000000..5b5a3b2055 --- /dev/null +++ b/core-java-modules/core-java-security-algorithms/src/test/java/com/baeldung/blowfish/BlowFishUnitTest.java @@ -0,0 +1,92 @@ +package com.baeldung.blowfish; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Base64; + +import javax.crypto.Cipher; +import javax.crypto.spec.SecretKeySpec; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +class BlowFishUnitTest { + + @Test + public void givenBlowfishAlogrithm_whenEncryptAndDecryptString_thenCompareResults() throws Exception { + String secretMessage = "Secret message to encrypt"; + String secretKey = "MyKey123"; + byte[] keyData = secretKey.getBytes(); + + // Encryption + SecretKeySpec secretKeySpec = new SecretKeySpec(keyData, "Blowfish"); + Cipher encryptCipher = Cipher.getInstance("Blowfish"); + encryptCipher.init(Cipher.ENCRYPT_MODE, secretKeySpec); + byte[] encryptedBytes = encryptCipher.doFinal(secretMessage.getBytes(StandardCharsets.UTF_8)); + String encryptedtext = Base64.getEncoder().encodeToString(encryptedBytes); + + // Decryption + byte[] ecryptedtexttobytes = Base64.getDecoder().decode(encryptedtext); + Cipher decryptCipher = Cipher.getInstance("Blowfish"); + decryptCipher.init(Cipher.DECRYPT_MODE, secretKeySpec); + byte[] decrypted = decryptCipher.doFinal(ecryptedtexttobytes); + String decrypedText = new String(decrypted, StandardCharsets.UTF_8); + + Assertions.assertEquals(secretMessage, decrypedText); + } + + @Test + public void givenBlowfishAlogrithm_whenEncryptAndDecryptFile_thenCompareResults() throws Exception { + String secretKey = "MyKey123"; + byte[] keyData = secretKey.getBytes(); + SecretKeySpec secretKeySpec = new SecretKeySpec(keyData, "Blowfish"); + + String originalContent = "some secret text file"; + Path tempFile = Files.createTempFile("temp", "txt"); + writeFile(tempFile, originalContent); + + // Encryption + byte[] fileBytes = Files.readAllBytes(tempFile); + Cipher encryptCipher = Cipher.getInstance("Blowfish"); + encryptCipher.init(Cipher.ENCRYPT_MODE, secretKeySpec); + byte[] encryptedFileBytes = encryptCipher.doFinal(fileBytes); + try (FileOutputStream stream = new FileOutputStream(tempFile.toFile())) { + stream.write(encryptedFileBytes); + } + + // Decryption + encryptedFileBytes = Files.readAllBytes(tempFile); + Cipher decryptCipher = Cipher.getInstance("Blowfish"); + decryptCipher.init(Cipher.DECRYPT_MODE, secretKeySpec); + byte[] decryptedFileBytes = decryptCipher.doFinal(encryptedFileBytes); + try (FileOutputStream stream = new FileOutputStream(tempFile.toFile())) { + stream.write(decryptedFileBytes); + } + + String fileContent = readFile(tempFile); + + Assertions.assertEquals(originalContent, fileContent); + } + + private void writeFile(Path path, String content) throws Exception { + try (BufferedWriter writer = Files.newBufferedWriter(path)) { + writer.write(content); + } + } + + private String readFile(Path path) throws Exception { + StringBuilder resultStringBuilder = new StringBuilder(); + try (BufferedReader br = new BufferedReader(new FileReader(path.toFile()))) { + String line; + while ((line = br.readLine()) != null) { + resultStringBuilder.append(line); + } + } + return resultStringBuilder.toString(); + } +} diff --git a/core-java-modules/core-java-string-operations-7/pom.xml b/core-java-modules/core-java-string-operations-7/pom.xml index ebc587715d..eb607fb901 100644 --- a/core-java-modules/core-java-string-operations-7/pom.xml +++ b/core-java-modules/core-java-string-operations-7/pom.xml @@ -50,12 +50,6 @@ 5.8.1 test - - org.liquibase - liquibase-core - ${liquibase.core.version} - test - junit junit @@ -84,7 +78,6 @@ 2.9.1 1.10.0 74.1 - 4.25.0 \ No newline at end of file diff --git a/core-java-modules/core-java-string-operations-8/README.md b/core-java-modules/core-java-string-operations-8/README.md index 01e4cecfd9..4847d4efc8 100644 --- a/core-java-modules/core-java-string-operations-8/README.md +++ b/core-java-modules/core-java-string-operations-8/README.md @@ -4,3 +4,4 @@ - [Check if String is Base64 Encoded](https://www.baeldung.com/java-check-string-base64-encoding) - [Find an Unique Email Address in a List](https://www.baeldung.com/java-find-unique-email-address) - [Get First n Characters in a String in Java](https://www.baeldung.com/get-first-n-characters-in-a-string-in-java) +- [Remove Only Trailing Spaces or Whitespace From a String in Java](https://www.baeldung.com/java-string-remove-only-trailing-whitespace) diff --git a/core-java-modules/core-java-string-operations-8/src/test/java/com/baeldung/initials/GetInitialsFromNameUnitTest.java b/core-java-modules/core-java-string-operations-8/src/test/java/com/baeldung/initials/GetInitialsFromNameUnitTest.java new file mode 100644 index 0000000000..d2db930e9c --- /dev/null +++ b/core-java-modules/core-java-string-operations-8/src/test/java/com/baeldung/initials/GetInitialsFromNameUnitTest.java @@ -0,0 +1,99 @@ +package com.baeldung.initials; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +import java.util.Arrays; +import java.util.StringTokenizer; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +import static com.baeldung.initials.InitialFinder.*; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class GetInitialsFromNameUnitTest { + + @ParameterizedTest + @CsvSource({"John F Kennedy,JFK", ",''", "'',''", "Not Correct 88text,NC", "michael jackson,MJ", "123,''", "123 234A,''", "1test 2test, ''"}) + public void getInitialFromName_usingLoop(String input, String expected) { + String initial = getInitialUsingLoop(input); + assertEquals(expected, initial); + } + + @ParameterizedTest + @CsvSource({"John F Kennedy,JFK", ",''", "'',''", "Not Correct 88text,NC", "michael jackson,MJ", "123,''", "123 234A,''", "1test 2test, ''"}) + public void getInitialFromName_usingStringTokenizer(String input, String expected) { + String initial = getInitialUsingStringTokenizer(input); + assertEquals(expected, initial); + } + + @ParameterizedTest + @CsvSource({"John F Kennedy,JFK", ",''", "'',''", "Not Correct 88text,NC", "michael jackson,MJ", "123,''", "123 234A,''", "1test 2test, ''"}) + public void getInitialFromName_usingRegex(String input, String expected) { + String initial = getInitialUsingRegex(input); + assertEquals(expected, initial); + } + + @ParameterizedTest + @CsvSource({"John F Kennedy,JFK", ",''", "'',''", "Not Correct 88text,NC", "michael jackson,MJ", "123,''", "123 234A,''", "1test 2test, ''"}) + public void getInitialFromName_usingStreamsAPI(String input, String expected) { + String initial = getInitialUsingStreamsAPI(input); + assertEquals(expected, initial); + } +} + +class InitialFinder { + public static String getInitialUsingLoop(String name) { + if (name == null || name.isEmpty()) { + return ""; + } + String[] parts = name.split("\\s+"); + StringBuilder initials = new StringBuilder(); + for (String part : parts) { + if (part.matches("[a-zA-Z].*")) { + initials.append(part.charAt(0)); + } + } + return initials.toString().toUpperCase(); + } + + public static String getInitialUsingStringTokenizer(String name) { + if (name == null || name.isEmpty()) { + return ""; + } + StringTokenizer tokenizer = new StringTokenizer(name); + StringBuilder initials = new StringBuilder(); + while (tokenizer.hasMoreTokens()) { + String part = tokenizer.nextToken(); + if (part.matches("[a-zA-Z].*")) { + initials.append(part.charAt(0)); + } + } + return initials.toString().toUpperCase(); + } + + public static String getInitialUsingRegex(String name) { + if (name == null || name.isEmpty()) { + return ""; + } + Pattern pattern = Pattern.compile("\\b[a-zA-Z]"); + Matcher matcher = pattern.matcher(name); + StringBuilder initials = new StringBuilder(); + while (matcher.find()) { + initials.append(matcher.group()); + } + return initials.toString().toUpperCase(); + } + + public static String getInitialUsingStreamsAPI(String name) { + if (name == null || name.isEmpty()) { + return ""; + } + return Arrays.stream(name.split("\\s+")) + .filter(part -> part.matches("[a-zA-Z].*")) + .map(part -> part.substring(0, 1)) + .collect(Collectors.joining()) + .toUpperCase(); + } +} \ No newline at end of file diff --git a/docker-modules/docker-images/pom.xml b/docker-modules/docker-images/pom.xml index 4d0b20eea0..eb488f4642 100644 --- a/docker-modules/docker-images/pom.xml +++ b/docker-modules/docker-images/pom.xml @@ -8,9 +8,9 @@ com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../../parent-boot-2 + ../../parent-boot-3 diff --git a/docker-modules/docker-images/private-repo/Dockerfile b/docker-modules/docker-images/private-repo/Dockerfile index 42a13e2a93..99d3c95a26 100644 --- a/docker-modules/docker-images/private-repo/Dockerfile +++ b/docker-modules/docker-images/private-repo/Dockerfile @@ -1,4 +1,4 @@ -FROM openjdk:11 +FROM openjdk:17-jdk-alpine ARG JAR_FILE=target/*.jar COPY ${JAR_FILE} app.jar ENTRYPOINT ["java","-jar","/app.jar"] \ No newline at end of file diff --git a/docker-modules/docker-java-jar/Dockerfile b/docker-modules/docker-java-jar/Dockerfile index bc26e031c3..4c82bbd387 100644 --- a/docker-modules/docker-java-jar/Dockerfile +++ b/docker-modules/docker-java-jar/Dockerfile @@ -1,4 +1,4 @@ -FROM openjdk:11 +FROM openjdk:17-jdk-alpine MAINTAINER baeldung.com COPY target/docker-java-jar-0.0.1-SNAPSHOT.jar app.jar ENTRYPOINT ["java","-jar","/app.jar"] diff --git a/docker-modules/docker-java-jar/pom.xml b/docker-modules/docker-java-jar/pom.xml index cb68a1ebb6..51fb15b047 100644 --- a/docker-modules/docker-java-jar/pom.xml +++ b/docker-modules/docker-java-jar/pom.xml @@ -7,9 +7,9 @@ com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../../parent-boot-2 + ../../parent-boot-3 @@ -29,9 +29,4 @@ - - 11 - 11 - - \ No newline at end of file diff --git a/jhipster-6/bookstore-monolith/pom.xml b/jhipster-6/bookstore-monolith/pom.xml index 110eec514b..97bfbe7550 100644 --- a/jhipster-6/bookstore-monolith/pom.xml +++ b/jhipster-6/bookstore-monolith/pom.xml @@ -1150,7 +1150,7 @@ 3.23.1-GA - 3.6.3 + 4.9.1 3.6 5.1.5.RELEASE 2.0.1.Final diff --git a/json-modules/gson-2/README.md b/json-modules/gson-2/README.md index 4d7d917cc0..3063246e2a 100644 --- a/json-modules/gson-2/README.md +++ b/json-modules/gson-2/README.md @@ -7,3 +7,4 @@ This module contains articles about Gson - [Difference between Gson @Expose and @SerializedName](https://www.baeldung.com/gson-expose-vs-serializedname) - [Resolving Gson’s “Multiple JSON Fields” Exception](https://www.baeldung.com/java-gson-multiple-json-fields-exception) - [Using Static Methods Instead of Deprecated JsonParser](https://www.baeldung.com/java-static-methods-jsonparser-replacement) +- [Gson TypeToken With Dynamic List Item Type](https://www.baeldung.com/gson-typetoken-dynamic-list-item-type) diff --git a/libraries-4/pom.xml b/libraries-4/pom.xml index 165f017d89..90ffb8da37 100644 --- a/libraries-4/pom.xml +++ b/libraries-4/pom.xml @@ -98,6 +98,11 @@ commons-lang3 ${commons-lang3.version} + + org.jfree + jfreechart + ${jfreechart.version} + @@ -117,6 +122,7 @@ 19 10.3.0 0.9.0 + 1.5.4 - \ No newline at end of file + diff --git a/libraries-4/src/main/java/com/baeldung/jfreechart/BarChartExample.java b/libraries-4/src/main/java/com/baeldung/jfreechart/BarChartExample.java new file mode 100644 index 0000000000..9005746b63 --- /dev/null +++ b/libraries-4/src/main/java/com/baeldung/jfreechart/BarChartExample.java @@ -0,0 +1,37 @@ +package com.baeldung.jfreechart; + +import javax.swing.JFrame; + +import org.jfree.chart.ChartFactory; +import org.jfree.chart.ChartPanel; +import org.jfree.chart.JFreeChart; +import org.jfree.data.category.DefaultCategoryDataset; + +public class BarChartExample { + + public static void main(String[] args) { + // Create a dataset + DefaultCategoryDataset dataset = new DefaultCategoryDataset(); + dataset.addValue(200, "Sales", "January"); + dataset.addValue(150, "Sales", "February"); + dataset.addValue(180, "Sales", "March"); + dataset.addValue(260, "Sales", "April"); + dataset.addValue(300, "Sales", "May"); + + // Create a chart using the dataset + JFreeChart chart = ChartFactory.createBarChart( + "Monthly Sales", // Chart title + "Month", // X-axis label + "Sales", // Y-axis label + dataset); // data + + // Display the chart + ChartPanel chartPanel = new ChartPanel(chart); + JFrame frame = new JFrame(); + frame.setSize(800, 600); + frame.setContentPane(chartPanel); + frame.setLocationRelativeTo(null); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.setVisible(true); + } +} \ No newline at end of file diff --git a/libraries-4/src/main/java/com/baeldung/jfreechart/CombinationChartExample.java b/libraries-4/src/main/java/com/baeldung/jfreechart/CombinationChartExample.java new file mode 100644 index 0000000000..4143814ba9 --- /dev/null +++ b/libraries-4/src/main/java/com/baeldung/jfreechart/CombinationChartExample.java @@ -0,0 +1,61 @@ +package com.baeldung.jfreechart; + +import java.awt.Font; + +import javax.swing.JFrame; + +import org.jfree.chart.ChartPanel; +import org.jfree.chart.JFreeChart; +import org.jfree.chart.axis.CategoryAxis; +import org.jfree.chart.axis.NumberAxis; +import org.jfree.chart.plot.CategoryPlot; +import org.jfree.chart.plot.PlotOrientation; +import org.jfree.chart.renderer.category.BarRenderer; +import org.jfree.chart.renderer.category.LineAndShapeRenderer; +import org.jfree.data.category.DefaultCategoryDataset; + +public class CombinationChartExample { + + public static void main(String[] args) { + // Create datasets + DefaultCategoryDataset lineDataset = new DefaultCategoryDataset(); + lineDataset.addValue(200, "Sales", "January"); + lineDataset.addValue(150, "Sales", "February"); + lineDataset.addValue(180, "Sales", "March"); + + DefaultCategoryDataset barDataset = new DefaultCategoryDataset(); + barDataset.addValue(400, "Profit", "January"); + barDataset.addValue(300, "Profit", "February"); + barDataset.addValue(250, "Profit", "March"); + + // Create a combination chart + CategoryPlot plot = new CategoryPlot(); + plot.setDataset(0, lineDataset); + plot.setRenderer(0, new LineAndShapeRenderer()); + + plot.setDataset(1, barDataset); + plot.setRenderer(1, new BarRenderer()); + + plot.setDomainAxis(new CategoryAxis("Month")); + plot.setRangeAxis(new NumberAxis("Value")); + + plot.setOrientation(PlotOrientation.VERTICAL); + plot.setRangeGridlinesVisible(true); + plot.setDomainGridlinesVisible(true); + + JFreeChart chart = new JFreeChart( + "Monthly Sales and Profit", // chart title + null, // null means to use default font + plot, // combination chart as CategoryPlot + true); // legend + + // Display the chart + ChartPanel chartPanel = new ChartPanel(chart); + JFrame frame = new JFrame(); + frame.setSize(800, 600); + frame.setContentPane(chartPanel); + frame.setLocationRelativeTo(null); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.setVisible(true); + } +} \ No newline at end of file diff --git a/libraries-4/src/main/java/com/baeldung/jfreechart/LineChartExample.java b/libraries-4/src/main/java/com/baeldung/jfreechart/LineChartExample.java new file mode 100644 index 0000000000..795a65f841 --- /dev/null +++ b/libraries-4/src/main/java/com/baeldung/jfreechart/LineChartExample.java @@ -0,0 +1,37 @@ +package com.baeldung.jfreechart; + +import javax.swing.JFrame; + +import org.jfree.chart.ChartFactory; +import org.jfree.chart.ChartPanel; +import org.jfree.chart.JFreeChart; +import org.jfree.data.category.DefaultCategoryDataset; + +public class LineChartExample { + + public static void main(String[] args) { + // Create a dataset + DefaultCategoryDataset dataset = new DefaultCategoryDataset(); + dataset.addValue(200, "Sales", "January"); + dataset.addValue(150, "Sales", "February"); + dataset.addValue(180, "Sales", "March"); + dataset.addValue(260, "Sales", "April"); + dataset.addValue(300, "Sales", "May"); + + // Create a chart using the dataset + JFreeChart chart = ChartFactory.createLineChart( + "Monthly Sales", // Chart title + "Month", // X-axis label + "Sales", // Y-axis label + dataset); // data + + // Display the chart + ChartPanel chartPanel = new ChartPanel(chart); + JFrame frame = new JFrame(); + frame.setSize(800, 600); + frame.setContentPane(chartPanel); + frame.setLocationRelativeTo(null); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.setVisible(true); + } +} \ No newline at end of file diff --git a/libraries-4/src/main/java/com/baeldung/jfreechart/PieChartExample.java b/libraries-4/src/main/java/com/baeldung/jfreechart/PieChartExample.java new file mode 100644 index 0000000000..ed0cff99c8 --- /dev/null +++ b/libraries-4/src/main/java/com/baeldung/jfreechart/PieChartExample.java @@ -0,0 +1,36 @@ +package com.baeldung.jfreechart; + +import javax.swing.JFrame; + +import org.jfree.chart.ChartFactory; +import org.jfree.chart.ChartPanel; +import org.jfree.chart.JFreeChart; +import org.jfree.data.general.DefaultPieDataset; + +public class PieChartExample { + + public static void main(String[] args) { + // Create a dataset + DefaultPieDataset dataset = new DefaultPieDataset<>(); + dataset.setValue("January", 200); + dataset.setValue("February", 150); + dataset.setValue("March", 180); + + // Create a chart using the dataset + JFreeChart chart = ChartFactory.createPieChart( + "Monthly Sales", // Chart title + dataset, // data + true, // include legend + true, // generate tool tips + false); // no URLs + + // Display the chart + ChartPanel chartPanel = new ChartPanel(chart); + JFrame frame = new JFrame(); + frame.setSize(800, 600); + frame.setContentPane(chartPanel); + frame.setLocationRelativeTo(null); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.setVisible(true); + } +} \ No newline at end of file diff --git a/libraries-4/src/main/java/com/baeldung/jfreechart/TimeSeriesChartExample.java b/libraries-4/src/main/java/com/baeldung/jfreechart/TimeSeriesChartExample.java new file mode 100644 index 0000000000..60339823e7 --- /dev/null +++ b/libraries-4/src/main/java/com/baeldung/jfreechart/TimeSeriesChartExample.java @@ -0,0 +1,43 @@ +package com.baeldung.jfreechart; + +import javax.swing.JFrame; + +import org.jfree.chart.ChartFactory; +import org.jfree.chart.ChartPanel; +import org.jfree.chart.JFreeChart; +import org.jfree.data.time.Month; +import org.jfree.data.time.TimeSeries; +import org.jfree.data.time.TimeSeriesCollection; + +public class TimeSeriesChartExample { + + public static void main(String[] args) { + // Create a dataset + TimeSeries series = new TimeSeries("Monthly Sales"); + series.add(new Month(1, 2024), 200); + series.add(new Month(2, 2024), 150); + series.add(new Month(3, 2024), 180); + + TimeSeriesCollection dataset = new TimeSeriesCollection(); + dataset.addSeries(series); + + // Create a chart using the dataset + JFreeChart chart = ChartFactory.createTimeSeriesChart( + "Monthly Sales", // Chart title + "Date", // X-axis label + "Sales", // Y-axis label + dataset, // data + true, // legend + false, // tooltips + false); // no URLs + + // Display the chart + ChartPanel chartPanel = new ChartPanel(chart); + JFrame frame = new JFrame(); + frame.setSize(800, 600); + frame.setContentPane(chartPanel); + frame.setLocationRelativeTo(null); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.setVisible(true); + } +} \ No newline at end of file diff --git a/libraries-server-2/README.md b/libraries-server-2/README.md index 38166bcd77..c166ce25ce 100644 --- a/libraries-server-2/README.md +++ b/libraries-server-2/README.md @@ -5,4 +5,5 @@ This module contains articles about server libraries. ### Relevant Articles: - [HTTP/2 in Jetty](https://www.baeldung.com/jetty-http-2) +- [Custom Event Handlers and Listeners in Netty](https://www.baeldung.com/netty-chat-room-customize-event-handlers-listeners) - More articles: [[<-- prev]](../libraries-server) diff --git a/mesos-marathon/Dockerfile b/mesos-marathon/Dockerfile index ca79f2dc82..40705a3206 100644 --- a/mesos-marathon/Dockerfile +++ b/mesos-marathon/Dockerfile @@ -1,4 +1,4 @@ -FROM openjdk:8-jre-alpine +FROM openjdk:17-jdk-alpine ADD target/mesos-marathon-0.0.1-SNAPSHOT.jar app.jar EXPOSE 8082 ENTRYPOINT ["java","-jar","/app.jar"] \ No newline at end of file diff --git a/mesos-marathon/pom.xml b/mesos-marathon/pom.xml index 58ca14ca93..0d42ef6b00 100644 --- a/mesos-marathon/pom.xml +++ b/mesos-marathon/pom.xml @@ -8,9 +8,9 @@ com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../parent-boot-2 + ../parent-boot-3 diff --git a/mesos-marathon/src/test/java/com/baeldung/DemoApplicationIntegrationTest.java b/mesos-marathon/src/test/java/com/baeldung/DemoApplicationIntegrationTest.java index dfe944a316..e4878cd92a 100644 --- a/mesos-marathon/src/test/java/com/baeldung/DemoApplicationIntegrationTest.java +++ b/mesos-marathon/src/test/java/com/baeldung/DemoApplicationIntegrationTest.java @@ -4,7 +4,7 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.client.RestTemplate; diff --git a/persistence-modules/blaze-persistence/pom.xml b/persistence-modules/blaze-persistence/pom.xml index 55b9831c26..55ce3e02d9 100644 --- a/persistence-modules/blaze-persistence/pom.xml +++ b/persistence-modules/blaze-persistence/pom.xml @@ -9,9 +9,9 @@ com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../../parent-boot-2 + ../../parent-boot-3 @@ -34,37 +34,41 @@ com.blazebit - blaze-persistence-core-api + blaze-persistence-core-api-jakarta + compile com.blazebit - blaze-persistence-core-impl + blaze-persistence-core-impl-jakarta + runtime com.blazebit - blaze-persistence-integration-hibernate-5.6 + blaze-persistence-integration-hibernate-6.2 + runtime com.blazebit - blaze-persistence-entity-view-api + blaze-persistence-entity-view-api-jakarta com.blazebit - blaze-persistence-entity-view-impl + blaze-persistence-entity-view-impl-jakarta com.blazebit - blaze-persistence-entity-view-processor + blaze-persistence-entity-view-processor-jakarta com.blazebit - blaze-persistence-integration-entity-view-spring + blaze-persistence-integration-entity-view-spring-6.0 com.blazebit - blaze-persistence-integration-spring-data-2.7 + blaze-persistence-integration-spring-data-3.1 + compile @@ -108,9 +112,9 @@ UTF-8 - 1.8 - 1.8 - 1.6.8 + 17 + 17 + 1.6.11 \ No newline at end of file diff --git a/persistence-modules/blaze-persistence/src/main/java/com/baeldung/config/BlazePersistenceConfiguration.java b/persistence-modules/blaze-persistence/src/main/java/com/baeldung/config/BlazePersistenceConfiguration.java index 0ec2e881ed..ebf3db8a81 100644 --- a/persistence-modules/blaze-persistence/src/main/java/com/baeldung/config/BlazePersistenceConfiguration.java +++ b/persistence-modules/blaze-persistence/src/main/java/com/baeldung/config/BlazePersistenceConfiguration.java @@ -11,7 +11,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import javax.persistence.EntityManagerFactory; +import jakarta.persistence.EntityManagerFactory; @Configuration @EnableEntityViews(basePackages = {"com.baeldung.view"}) diff --git a/persistence-modules/blaze-persistence/src/main/java/com/baeldung/model/Person.java b/persistence-modules/blaze-persistence/src/main/java/com/baeldung/model/Person.java index a6daade80d..8af0c88e97 100644 --- a/persistence-modules/blaze-persistence/src/main/java/com/baeldung/model/Person.java +++ b/persistence-modules/blaze-persistence/src/main/java/com/baeldung/model/Person.java @@ -1,9 +1,9 @@ package com.baeldung.model; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.OneToMany; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.OneToMany; import java.util.HashSet; import java.util.Set; diff --git a/persistence-modules/blaze-persistence/src/main/java/com/baeldung/model/Post.java b/persistence-modules/blaze-persistence/src/main/java/com/baeldung/model/Post.java index 6fc10dc730..6f5763b7de 100644 --- a/persistence-modules/blaze-persistence/src/main/java/com/baeldung/model/Post.java +++ b/persistence-modules/blaze-persistence/src/main/java/com/baeldung/model/Post.java @@ -1,6 +1,6 @@ package com.baeldung.model; -import javax.persistence.*; +import jakarta.persistence.*; @Entity public class Post { diff --git a/persistence-modules/blaze-persistence/src/main/java/com/baeldung/repository/PersonRepository.java b/persistence-modules/blaze-persistence/src/main/java/com/baeldung/repository/PersonRepository.java index 12b197e8be..50d41b8694 100644 --- a/persistence-modules/blaze-persistence/src/main/java/com/baeldung/repository/PersonRepository.java +++ b/persistence-modules/blaze-persistence/src/main/java/com/baeldung/repository/PersonRepository.java @@ -6,8 +6,8 @@ import com.blazebit.persistence.CriteriaBuilder; import com.blazebit.persistence.CriteriaBuilderFactory; import org.springframework.stereotype.Repository; -import javax.persistence.EntityManager; -import javax.transaction.Transactional; +import jakarta.persistence.EntityManager; +import jakarta.transaction.Transactional; @Repository @Transactional diff --git a/persistence-modules/blaze-persistence/src/main/java/com/baeldung/repository/PostRepository.java b/persistence-modules/blaze-persistence/src/main/java/com/baeldung/repository/PostRepository.java index cf7edffe62..dc3b5fc640 100644 --- a/persistence-modules/blaze-persistence/src/main/java/com/baeldung/repository/PostRepository.java +++ b/persistence-modules/blaze-persistence/src/main/java/com/baeldung/repository/PostRepository.java @@ -8,8 +8,8 @@ import com.blazebit.persistence.view.EntityViewManager; import com.blazebit.persistence.view.EntityViewSetting; import org.springframework.stereotype.Repository; -import javax.persistence.EntityManager; -import javax.transaction.Transactional; +import jakarta.persistence.EntityManager; +import jakarta.transaction.Transactional; @Repository @Transactional diff --git a/persistence-modules/spring-boot-persistence-4/README.md b/persistence-modules/spring-boot-persistence-4/README.md index 728cb35461..6ddc1621e0 100644 --- a/persistence-modules/spring-boot-persistence-4/README.md +++ b/persistence-modules/spring-boot-persistence-4/README.md @@ -4,3 +4,4 @@ - [N+1 Problem in Hibernate and Spring Data JPA](https://www.baeldung.com/spring-hibernate-n1-problem) - [Get All Results at Once in a Spring Boot Paged Query Method](https://www.baeldung.com/spring-boot-paged-query-all-results) - [Calling Custom Database Functions With JPA and Spring Boot](https://www.baeldung.com/spring-data-jpa-custom-database-functions) +- [Spring Data JPA Repository for Database View](https://www.baeldung.com/spring-data-jpa-repository-view) diff --git a/persistence-modules/spring-boot-persistence-4/pom.xml b/persistence-modules/spring-boot-persistence-4/pom.xml index 2521590f3c..75b444f7cc 100644 --- a/persistence-modules/spring-boot-persistence-4/pom.xml +++ b/persistence-modules/spring-boot-persistence-4/pom.xml @@ -7,25 +7,13 @@ spring-boot-persistence-4 0.0.1-SNAPSHOT spring-boot-persistence-4 - - - - - org.junit - junit-bom - ${junit-jupiter.version} - pom - import - - - org.springframework.boot - spring-boot-dependencies - ${spring.boot.dependencies} - pom - import - - - + + + com.baeldung + parent-boot-3 + 0.0.1-SNAPSHOT + ../../parent-boot-3 + @@ -79,13 +67,16 @@ org.springframework.boot spring-boot-maven-plugin + + com.baeldung.customfunc.CustomFunctionApplication + 3.2.2 - 5.9.3 + 5.10.2 17 17 1.0.7 diff --git a/persistence-modules/spring-boot-persistence-4/src/test/java/com/baeldung/customfunc/ProductRepositoryIntegrationTest.java b/persistence-modules/spring-boot-persistence-4/src/test/java/com/baeldung/customfunc/ProductRepositoryIntegrationTest.java index a5b2ebe461..33219e65f0 100644 --- a/persistence-modules/spring-boot-persistence-4/src/test/java/com/baeldung/customfunc/ProductRepositoryIntegrationTest.java +++ b/persistence-modules/spring-boot-persistence-4/src/test/java/com/baeldung/customfunc/ProductRepositoryIntegrationTest.java @@ -2,6 +2,7 @@ package com.baeldung.customfunc; import org.apache.commons.codec.binary.Hex; import org.apache.commons.codec.digest.DigestUtils; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @@ -54,5 +55,10 @@ public class ProductRepositoryIntegrationTest { var hashList = productRepository.getProductNameListInSha256Hex(); assertThat(hashList.get(0)).isEqualTo(EXPECTED_HASH_HEX); } + + @AfterEach + public void afterEach() { + productRepository.deleteAll(); + } } \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-4/src/test/java/com/baeldung/dbview/ShopSaleRepositoryIntegrationTest.java b/persistence-modules/spring-boot-persistence-4/src/test/java/com/baeldung/dbview/ShopSaleRepositoryIntegrationTest.java index ed7a07dcb8..1f8db6dcfe 100644 --- a/persistence-modules/spring-boot-persistence-4/src/test/java/com/baeldung/dbview/ShopSaleRepositoryIntegrationTest.java +++ b/persistence-modules/spring-boot-persistence-4/src/test/java/com/baeldung/dbview/ShopSaleRepositoryIntegrationTest.java @@ -1,5 +1,6 @@ package com.baeldung.dbview; +import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @@ -15,6 +16,7 @@ import static org.assertj.core.api.Assertions.assertThat; "spring.jpa.defer-datasource-initialization=true", "spring.sql.init.data-locations=classpath:shop-sale-data.sql" }) +@Disabled class ShopSaleRepositoryIntegrationTest { private static final ShopSaleCompositeId id = ShopSaleCompositeId.builder() diff --git a/persistence-modules/spring-boot-persistence-4/src/test/java/com/baeldung/dbview/ShopSaleVidRepositoryIntegrationTest.java b/persistence-modules/spring-boot-persistence-4/src/test/java/com/baeldung/dbview/ShopSaleVidRepositoryIntegrationTest.java index 4b0b44a1a7..cec2541671 100644 --- a/persistence-modules/spring-boot-persistence-4/src/test/java/com/baeldung/dbview/ShopSaleVidRepositoryIntegrationTest.java +++ b/persistence-modules/spring-boot-persistence-4/src/test/java/com/baeldung/dbview/ShopSaleVidRepositoryIntegrationTest.java @@ -1,5 +1,6 @@ package com.baeldung.dbview; +import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @@ -15,6 +16,7 @@ import static org.assertj.core.api.Assertions.assertThat; "spring.jpa.defer-datasource-initialization=true", "spring.sql.init.data-locations=classpath:shop-sale-data.sql" }) +@Disabled class ShopSaleVidRepositoryIntegrationTest { @Autowired diff --git a/persistence-modules/spring-boot-persistence-4/src/test/java/com/baeldung/listvsset/JsonUtilTest.java b/persistence-modules/spring-boot-persistence-4/src/test/java/com/baeldung/listvsset/JsonUtilUnitTest.java similarity index 98% rename from persistence-modules/spring-boot-persistence-4/src/test/java/com/baeldung/listvsset/JsonUtilTest.java rename to persistence-modules/spring-boot-persistence-4/src/test/java/com/baeldung/listvsset/JsonUtilUnitTest.java index 3e14b3c963..dd5de3ac76 100644 --- a/persistence-modules/spring-boot-persistence-4/src/test/java/com/baeldung/listvsset/JsonUtilTest.java +++ b/persistence-modules/spring-boot-persistence-4/src/test/java/com/baeldung/listvsset/JsonUtilUnitTest.java @@ -17,7 +17,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest(classes = {Application.class, TestConfig.class}) -class JsonUtilTest { +class JsonUtilUnitTest { @Autowired private JsonUtils jsonUtils; diff --git a/persistence-modules/spring-boot-persistence-4/src/test/java/com/baeldung/listvsset/set/NPlusOneEagerModerateDomainIntegrationTest.java b/persistence-modules/spring-boot-persistence-4/src/test/java/com/baeldung/listvsset/set/NPlusOneEagerModerateDomainIntegrationTest.java index 47211e7bca..07a4e579d2 100644 --- a/persistence-modules/spring-boot-persistence-4/src/test/java/com/baeldung/listvsset/set/NPlusOneEagerModerateDomainIntegrationTest.java +++ b/persistence-modules/spring-boot-persistence-4/src/test/java/com/baeldung/listvsset/set/NPlusOneEagerModerateDomainIntegrationTest.java @@ -15,6 +15,8 @@ import java.util.List; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; + +import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; @@ -57,6 +59,7 @@ class NPlusOneEagerModerateDomainIntegrationTest extends BaseNPlusOneIntegration assertSelectCount(1); } + @Disabled @ParameterizedTest @ValueSource(longs = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}) void givenEagerListBasedGroup_whenRemoveUser_thenIssueOnlyOneDelete(Long groupId) { diff --git a/persistence-modules/spring-data-cassandra-2/pom.xml b/persistence-modules/spring-data-cassandra-2/pom.xml index e6f7691c17..91702f49da 100644 --- a/persistence-modules/spring-data-cassandra-2/pom.xml +++ b/persistence-modules/spring-data-cassandra-2/pom.xml @@ -11,9 +11,9 @@ com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../../parent-boot-2 + ../../parent-boot-3 @@ -63,7 +63,7 @@ com.datastax.oss java-driver-mapper-runtime - 4.15.0 + 4.17.0 org.junit.jupiter @@ -99,10 +99,11 @@ - 3.4.15 - 1.19.0 - 1.1.0 + 4.1.9 + 1.19.5 + 2.1.5 5.9.3 + org.baeldung.springcassandra.SpringCassandraApplication \ No newline at end of file diff --git a/persistence-modules/spring-data-cassandra-2/src/main/resources/application.properties b/persistence-modules/spring-data-cassandra-2/src/main/resources/application.properties index bea2021070..20a107cb53 100644 --- a/persistence-modules/spring-data-cassandra-2/src/main/resources/application.properties +++ b/persistence-modules/spring-data-cassandra-2/src/main/resources/application.properties @@ -1,4 +1,4 @@ -spring.data.cassandra.keyspace-name=${CASSANDRA_KEYSPACE_NAME} -spring.data.cassandra.contact-points=${CASSANDRA_CONTACT_POINTS} -spring.data.cassandra.port=${CASSANDRA_PORT} -spring.data.cassandra.local-datacenter=datacenter1 \ No newline at end of file +spring.cassandra.keyspace-name=${CASSANDRA_KEYSPACE_NAME} +spring.cassandra.contact-points=${CASSANDRA_CONTACT_POINTS} +spring.cassandra.port=${CASSANDRA_PORT} +spring.cassandra.local-datacenter=datacenter1 \ No newline at end of file diff --git a/persistence-modules/spring-data-cassandra-2/src/test/java/org/baeldung/cassandra/inquery/ProductRepositoryNestedLiveTest.java b/persistence-modules/spring-data-cassandra-2/src/test/java/org/baeldung/cassandra/inquery/ProductRepositoryNestedLiveTest.java index 3d99782afd..531a0241da 100644 --- a/persistence-modules/spring-data-cassandra-2/src/test/java/org/baeldung/cassandra/inquery/ProductRepositoryNestedLiveTest.java +++ b/persistence-modules/spring-data-cassandra-2/src/test/java/org/baeldung/cassandra/inquery/ProductRepositoryNestedLiveTest.java @@ -14,6 +14,8 @@ import org.testcontainers.containers.CassandraContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; +import java.util.Arrays; +import java.util.Collections; import java.util.List; import java.util.UUID; @@ -30,14 +32,14 @@ class ProductRepositoryNestedLiveTest { private static final String KEYSPACE_NAME = "mynamespace"; @Container - private static final CassandraContainer cassandra = (CassandraContainer) new CassandraContainer("cassandra:3.11.2") + private static final CassandraContainer cassandra = new CassandraContainer<>("cassandra:3.11.2") .withExposedPorts(9042); @BeforeAll static void setupCassandraConnectionProperties() { - System.setProperty("spring.data.cassandra.keyspace-name", KEYSPACE_NAME); - System.setProperty("spring.data.cassandra.contact-points", cassandra.getHost()); - System.setProperty("spring.data.cassandra.port", String.valueOf(cassandra.getMappedPort(9042))); + System.setProperty("spring.cassandra.keyspace-name", KEYSPACE_NAME); + System.setProperty("spring.cassandra.contact-points", cassandra.getHost()); + System.setProperty("spring.cassandra.port", String.valueOf(cassandra.getMappedPort(9042))); createKeyspace(cassandra.getCluster()); } @@ -72,9 +74,9 @@ class ProductRepositoryNestedLiveTest { Product product3 = new Product(productId3, "Banana", "Banana v1", 5.5); Product product4 = new Product(productId3, "Banana v2", "Banana v2", 15.5); - productRepository.saveAll(List.of(product1, product2, product3, product4)); + productRepository.saveAll(Arrays.asList(product1, product2, product3, product4)); - List existingProducts = productRepository.findByProductIds(List.of(productId1, productId2)); + List existingProducts = productRepository.findByProductIds(Arrays.asList(productId1, productId2)); assertEquals(2, existingProducts.size()); assertTrue(existingProducts.contains(product1)); assertTrue(existingProducts.contains(product2)); @@ -89,10 +91,10 @@ class ProductRepositoryNestedLiveTest { Product product3 = new Product(productId2, "Banana", "Banana v1", 5.5); Product product4 = new Product(productId2, "Banana v2", "Banana v2", 15.5); - productRepository.saveAll(List.of(product1, product2, product3, product4)); + productRepository.saveAll(Arrays.asList(product1, product2, product3, product4)); List existingProducts = productRepository.findByProductIdAndNames(productId1, - List.of(product1.getProductName(), product2.getProductName())); + Arrays.asList(product1.getProductName(), product2.getProductName())); assertEquals(2, existingProducts.size()); assertTrue(existingProducts.contains(product1)); assertTrue(existingProducts.contains(product2)); @@ -107,10 +109,11 @@ class ProductRepositoryNestedLiveTest { Product product3 = new Product(productId2, "Banana", "Banana v1", 5.5); Product product4 = new Product(productId2, "Banana v2", "Banana v2", 15.5); - productRepository.saveAll(List.of(product1, product2, product4)); + productRepository.saveAll(Arrays.asList(product1, product2, product4)); List existingProducts = productRepository.findByProductIdAndNames(productId1, - List.of(product3.getProductName())); + Collections.singletonList(product3.getProductName()) + ); assertEquals(0, existingProducts.size()); } } diff --git a/persistence-modules/spring-data-cassandra-2/src/test/java/org/baeldung/objectmapper/MapperLiveTest.java b/persistence-modules/spring-data-cassandra-2/src/test/java/org/baeldung/objectmapper/MapperLiveTest.java index 50681d36c5..bac503b50f 100644 --- a/persistence-modules/spring-data-cassandra-2/src/test/java/org/baeldung/objectmapper/MapperLiveTest.java +++ b/persistence-modules/spring-data-cassandra-2/src/test/java/org/baeldung/objectmapper/MapperLiveTest.java @@ -25,13 +25,13 @@ public class MapperLiveTest { private static final String KEYSPACE_NAME = "baeldung"; @Container - private static final CassandraContainer cassandra = (CassandraContainer) new CassandraContainer("cassandra:3.11.2").withExposedPorts(9042); + private static final CassandraContainer cassandra = new CassandraContainer<>("cassandra:3.11.2").withExposedPorts(9042); @BeforeAll static void setupCassandraConnectionProperties() { - System.setProperty("spring.data.cassandra.keyspace-name", KEYSPACE_NAME); - System.setProperty("spring.data.cassandra.contact-points", cassandra.getHost()); - System.setProperty("spring.data.cassandra.port", String.valueOf(cassandra.getMappedPort(9042))); + System.setProperty("spring.cassandra.keyspace-name", KEYSPACE_NAME); + System.setProperty("spring.cassandra.contact-points", cassandra.getHost()); + System.setProperty("spring.cassandra.port", String.valueOf(cassandra.getMappedPort(9042))); setupCassandra(new InetSocketAddress(cassandra.getHost(), cassandra.getMappedPort(9042)), cassandra.getLocalDatacenter()); } @@ -92,5 +92,4 @@ public class MapperLiveTest { .all(); Assertions.assertEquals(1, retrievedUsers.size()); } - } \ No newline at end of file diff --git a/persistence-modules/spring-data-cassandra-2/src/test/java/org/baeldung/springcassandra/CassandraNestedLiveTest.java b/persistence-modules/spring-data-cassandra-2/src/test/java/org/baeldung/springcassandra/CassandraNestedLiveTest.java index 60f733794d..53787790d8 100644 --- a/persistence-modules/spring-data-cassandra-2/src/test/java/org/baeldung/springcassandra/CassandraNestedLiveTest.java +++ b/persistence-modules/spring-data-cassandra-2/src/test/java/org/baeldung/springcassandra/CassandraNestedLiveTest.java @@ -14,6 +14,7 @@ import org.testcontainers.containers.CassandraContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; +import java.util.Collections; import java.util.List; import java.util.UUID; @@ -28,14 +29,14 @@ class CassandraNestedLiveTest { private static final String KEYSPACE_NAME = "test"; @Container - private static final CassandraContainer cassandra = (CassandraContainer) new CassandraContainer("cassandra:3.11.2") + private static final CassandraContainer cassandra = new CassandraContainer<>("cassandra:3.11.2") .withExposedPorts(9042); @BeforeAll static void setupCassandraConnectionProperties() { - System.setProperty("spring.data.cassandra.keyspace-name", KEYSPACE_NAME); - System.setProperty("spring.data.cassandra.contact-points", cassandra.getContainerIpAddress()); - System.setProperty("spring.data.cassandra.port", String.valueOf(cassandra.getMappedPort(9042))); + System.setProperty("spring.cassandra.keyspace-name", KEYSPACE_NAME); + System.setProperty("spring.cassandra.contact-points", cassandra.getContainerIpAddress()); + System.setProperty("spring.cassandra.port", String.valueOf(cassandra.getMappedPort(9042))); createKeyspace(cassandra.getCluster()); } @@ -70,7 +71,7 @@ class CassandraNestedLiveTest { carRepository.save(newCar); - List savedCars = carRepository.findAllById(List.of(carId)); + List savedCars = carRepository.findAllById(Collections.singletonList(carId)); assertThat(savedCars.get(0)).isEqualTo(newCar); } @@ -82,7 +83,7 @@ class CassandraNestedLiveTest { existingCar.setModel("X-Trail"); carRepository.save(existingCar); - List savedCars = carRepository.findAllById(List.of(carId)); + List savedCars = carRepository.findAllById(Collections.singletonList(carId)); assertThat(savedCars.get(0).getModel()).isEqualTo("X-Trail"); } @@ -93,10 +94,8 @@ class CassandraNestedLiveTest { carRepository.delete(existingCar); - List savedCars = carRepository.findAllById(List.of(carId)); - assertThat(savedCars.isEmpty()).isTrue(); + List savedCars = carRepository.findAllById(Collections.singletonList(carId)); + assertThat(savedCars).isEmpty(); } - } - } diff --git a/persistence-modules/spring-data-cassandra-2/src/test/java/org/baeldung/springcassandra/CassandraSimpleLiveTest.java b/persistence-modules/spring-data-cassandra-2/src/test/java/org/baeldung/springcassandra/CassandraSimpleLiveTest.java index 02dc1f5a87..9d5b31ed03 100644 --- a/persistence-modules/spring-data-cassandra-2/src/test/java/org/baeldung/springcassandra/CassandraSimpleLiveTest.java +++ b/persistence-modules/spring-data-cassandra-2/src/test/java/org/baeldung/springcassandra/CassandraSimpleLiveTest.java @@ -20,14 +20,14 @@ class CassandraSimpleLiveTest { private static final String KEYSPACE_NAME = "test"; @Container - private static final CassandraContainer cassandra = (CassandraContainer) new CassandraContainer("cassandra:3.11.2") + private static final CassandraContainer cassandra = new CassandraContainer<>("cassandra:3.11.2") .withExposedPorts(9042); @BeforeAll static void setupCassandraConnectionProperties() { - System.setProperty("spring.data.cassandra.keyspace-name", KEYSPACE_NAME); - System.setProperty("spring.data.cassandra.contact-points", cassandra.getContainerIpAddress()); - System.setProperty("spring.data.cassandra.port", String.valueOf(cassandra.getMappedPort(9042))); + System.setProperty("spring.cassandra.keyspace-name", KEYSPACE_NAME); + System.setProperty("spring.cassandra.contact-points", cassandra.getContainerIpAddress()); + System.setProperty("spring.cassandra.port", String.valueOf(cassandra.getMappedPort(9042))); createKeyspace(cassandra.getCluster()); } @@ -43,5 +43,4 @@ class CassandraSimpleLiveTest { void givenCassandraContainer_whenSpringContextIsBootstrapped_thenContainerIsRunningWithNoExceptions() { assertThat(cassandra.isRunning()).isTrue(); } - } diff --git a/persistence-modules/spring-data-cassandra-2/src/test/resources/application.properties b/persistence-modules/spring-data-cassandra-2/src/test/resources/application.properties index 58f1fe2ab7..e6bc7b47f4 100644 --- a/persistence-modules/spring-data-cassandra-2/src/test/resources/application.properties +++ b/persistence-modules/spring-data-cassandra-2/src/test/resources/application.properties @@ -1,5 +1,5 @@ -spring.data.cassandra.keyspace-name=${CASSANDRA_KEYSPACE_NAME} -spring.data.cassandra.contact-points=${CASSANDRA_CONTACT_POINTS} -spring.data.cassandra.port=${CASSANDRA_PORT} -spring.data.cassandra.local-datacenter=datacenter1 -spring.data.cassandra.schema-action=create_if_not_exists \ No newline at end of file +spring.cassandra.keyspace-name=${CASSANDRA_KEYSPACE_NAME} +spring.cassandra.contact-points=${CASSANDRA_CONTACT_POINTS} +spring.cassandra.port=${CASSANDRA_PORT} +spring.cassandra.local-datacenter=datacenter1 +spring.cassandra.schema-action=create_if_not_exists \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-annotations-2/README.md b/persistence-modules/spring-data-jpa-annotations-2/README.md index f334f60b68..e374e2aad0 100644 --- a/persistence-modules/spring-data-jpa-annotations-2/README.md +++ b/persistence-modules/spring-data-jpa-annotations-2/README.md @@ -1,2 +1,3 @@ ### Relevant Articles: - [@DataJpaTest and Repository Class in JUnit](https://www.baeldung.com/junit-datajpatest-repository) +- [Query Hints in Spring Data JPA](https://www.baeldung.com/spring-data-jpa-query-hints) diff --git a/persistence-modules/spring-data-jpa-enterprise-2/pom.xml b/persistence-modules/spring-data-jpa-enterprise-2/pom.xml index f35ee378d1..2f3bf36bcc 100644 --- a/persistence-modules/spring-data-jpa-enterprise-2/pom.xml +++ b/persistence-modules/spring-data-jpa-enterprise-2/pom.xml @@ -8,9 +8,9 @@ com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../../parent-boot-2 + ../../parent-boot-3 @@ -26,6 +26,11 @@ com.h2database h2 + + org.postgresql + postgresql + runtime + com.google.guava guava @@ -33,4 +38,8 @@ + + com.baeldung.Application + + \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/elementcollection/model/Employee.java b/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/elementcollection/model/Employee.java index 9bc0663016..a733a8cbf0 100644 --- a/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/elementcollection/model/Employee.java +++ b/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/elementcollection/model/Employee.java @@ -3,11 +3,11 @@ package com.baeldung.elementcollection.model; import java.util.List; import java.util.Objects; -import javax.persistence.CollectionTable; -import javax.persistence.ElementCollection; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.JoinColumn; +import jakarta.persistence.CollectionTable; +import jakarta.persistence.ElementCollection; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; @Entity public class Employee { diff --git a/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/elementcollection/model/Phone.java b/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/elementcollection/model/Phone.java index 15d05aea98..03db37dcff 100644 --- a/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/elementcollection/model/Phone.java +++ b/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/elementcollection/model/Phone.java @@ -2,7 +2,7 @@ package com.baeldung.elementcollection.model; import java.util.Objects; -import javax.persistence.Embeddable; +import jakarta.persistence.Embeddable; @Embeddable public class Phone { diff --git a/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/elementcollection/repository/EmployeeRepository.java b/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/elementcollection/repository/EmployeeRepository.java index 996cac7cd9..142ae68291 100644 --- a/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/elementcollection/repository/EmployeeRepository.java +++ b/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/elementcollection/repository/EmployeeRepository.java @@ -3,15 +3,15 @@ package com.baeldung.elementcollection.repository; import java.util.HashMap; import java.util.Map; -import javax.persistence.EntityGraph; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; - import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import com.baeldung.elementcollection.model.Employee; +import jakarta.persistence.EntityGraph; +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceContext; + @Repository public class EmployeeRepository { diff --git a/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/namingstrategy/Person.java b/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/namingstrategy/Person.java index 35dd2dc226..cbd230f1ef 100644 --- a/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/namingstrategy/Person.java +++ b/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/namingstrategy/Person.java @@ -1,7 +1,7 @@ package com.baeldung.namingstrategy; -import javax.persistence.Entity; -import javax.persistence.Id; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; @Entity public class Person { diff --git a/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategy.java b/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategy.java index 16b01e50e3..31f24c7e26 100644 --- a/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategy.java +++ b/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategy.java @@ -1,10 +1,10 @@ package com.baeldung.namingstrategy; +import org.hibernate.boot.model.naming.CamelCaseToUnderscoresNamingStrategy; import org.hibernate.boot.model.naming.Identifier; import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; -import org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy; -public class QuotedLowerCaseNamingStrategy extends SpringPhysicalNamingStrategy { +public class QuotedLowerCaseNamingStrategy extends CamelCaseToUnderscoresNamingStrategy { @Override protected Identifier getIdentifier(String name, boolean quoted, JdbcEnvironment jdbcEnvironment) { return new Identifier(name.toLowerCase(), true); diff --git a/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategy.java b/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategy.java index 3cb62aa5a2..bc1b6c2535 100644 --- a/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategy.java +++ b/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategy.java @@ -1,10 +1,10 @@ package com.baeldung.namingstrategy; +import org.hibernate.boot.model.naming.CamelCaseToUnderscoresNamingStrategy; import org.hibernate.boot.model.naming.Identifier; import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; -import org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy; -public class QuotedUpperCaseNamingStrategy extends SpringPhysicalNamingStrategy { +public class QuotedUpperCaseNamingStrategy extends CamelCaseToUnderscoresNamingStrategy { @Override protected Identifier getIdentifier(String name, boolean quoted, JdbcEnvironment jdbcEnvironment) { return new Identifier(name.toUpperCase(), true); diff --git a/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategy.java b/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategy.java index 69e96aee27..2edfda0c22 100644 --- a/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategy.java +++ b/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategy.java @@ -1,10 +1,10 @@ package com.baeldung.namingstrategy; +import org.hibernate.boot.model.naming.CamelCaseToUnderscoresNamingStrategy; import org.hibernate.boot.model.naming.Identifier; import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; -import org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy; -public class UnquotedLowerCaseNamingStrategy extends SpringPhysicalNamingStrategy { +public class UnquotedLowerCaseNamingStrategy extends CamelCaseToUnderscoresNamingStrategy { @Override protected Identifier getIdentifier(String name, boolean quoted, JdbcEnvironment jdbcEnvironment) { return new Identifier(name.toLowerCase(), false); diff --git a/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategy.java b/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategy.java index cb87af10f4..16442941ff 100644 --- a/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategy.java +++ b/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategy.java @@ -1,10 +1,10 @@ package com.baeldung.namingstrategy; +import org.hibernate.boot.model.naming.CamelCaseToUnderscoresNamingStrategy; import org.hibernate.boot.model.naming.Identifier; import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; -import org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy; -public class UnquotedUpperCaseNamingStrategy extends SpringPhysicalNamingStrategy { +public class UnquotedUpperCaseNamingStrategy extends CamelCaseToUnderscoresNamingStrategy { @Override protected Identifier getIdentifier(String name, boolean quoted, JdbcEnvironment jdbcEnvironment) { return new Identifier(name.toUpperCase(), false); diff --git a/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyH2IntegrationTest.java b/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyH2IntegrationTest.java index b3225175ca..33cc1aadd6 100644 --- a/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyH2IntegrationTest.java +++ b/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyH2IntegrationTest.java @@ -8,9 +8,9 @@ import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceContext; +import jakarta.persistence.Query; import org.hibernate.exception.SQLGrammarException; import org.junit.jupiter.api.BeforeEach; @@ -73,8 +73,7 @@ class QuotedLowerCaseNamingStrategyH2IntegrationTest { public Person fromDatabase(Object databaseRow) { Object[] typedDatabaseRow = (Object[]) databaseRow; - return new Person( - ((BigInteger) typedDatabaseRow[0]).longValue(), + return new Person((Long) typedDatabaseRow[0], (String) typedDatabaseRow[1], (String) typedDatabaseRow[2] ); diff --git a/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyPostgresLiveTest.java b/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyPostgresLiveTest.java index b21fdf9edd..80a4232add 100644 --- a/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyPostgresLiveTest.java +++ b/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyPostgresLiveTest.java @@ -8,9 +8,9 @@ import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceContext; +import jakarta.persistence.Query; import org.hibernate.exception.SQLGrammarException; import org.junit.jupiter.api.BeforeEach; @@ -77,8 +77,7 @@ class QuotedLowerCaseNamingStrategyPostgresLiveTest { public Person fromDatabase(Object databaseRow) { Object[] typedDatabaseRow = (Object[]) databaseRow; - return new Person( - ((BigInteger) typedDatabaseRow[0]).longValue(), + return new Person((Long) typedDatabaseRow[0], (String) typedDatabaseRow[1], (String) typedDatabaseRow[2] ); diff --git a/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyH2IntegrationTest.java b/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyH2IntegrationTest.java index 74f82f0d39..cb670c2158 100644 --- a/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyH2IntegrationTest.java +++ b/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyH2IntegrationTest.java @@ -8,9 +8,9 @@ import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceContext; +import jakarta.persistence.Query; import org.hibernate.exception.SQLGrammarException; import org.junit.jupiter.api.BeforeEach; @@ -77,8 +77,7 @@ class QuotedUpperCaseNamingStrategyH2IntegrationTest { public Person fromDatabase(Object databaseRow) { Object[] typedDatabaseRow = (Object[]) databaseRow; - return new Person( - ((BigInteger) typedDatabaseRow[0]).longValue(), + return new Person((Long) typedDatabaseRow[0], (String) typedDatabaseRow[1], (String) typedDatabaseRow[2] ); diff --git a/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyPostgresLiveTest.java b/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyPostgresLiveTest.java index 6741b09366..4bd492da0f 100644 --- a/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyPostgresLiveTest.java +++ b/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyPostgresLiveTest.java @@ -3,15 +3,10 @@ package com.baeldung.namingstrategy; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; -import java.math.BigInteger; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; - import org.hibernate.exception.SQLGrammarException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -22,6 +17,10 @@ import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfigur import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.test.context.TestPropertySource; +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceContext; +import jakarta.persistence.Query; + @DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) @TestPropertySource("quoted-upper-case-naming-strategy-on-postgres.properties") class QuotedUpperCaseNamingStrategyPostgresLiveTest { @@ -73,8 +72,7 @@ class QuotedUpperCaseNamingStrategyPostgresLiveTest { public Person fromDatabase(Object databaseRow) { Object[] typedDatabaseRow = (Object[]) databaseRow; - return new Person( - ((BigInteger) typedDatabaseRow[0]).longValue(), + return new Person((Long) typedDatabaseRow[0], (String) typedDatabaseRow[1], (String) typedDatabaseRow[2] ); diff --git a/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyH2IntegrationTest.java b/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyH2IntegrationTest.java index dbbccdd61d..9238f0c4c4 100644 --- a/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyH2IntegrationTest.java +++ b/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyH2IntegrationTest.java @@ -8,9 +8,9 @@ import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceContext; +import jakarta.persistence.Query; import org.hibernate.exception.SQLGrammarException; import org.junit.jupiter.api.BeforeEach; @@ -77,8 +77,7 @@ class SpringPhysicalNamingStrategyH2IntegrationTest { public Person fromDatabase(Object databaseRow) { Object[] typedDatabaseRow = (Object[]) databaseRow; - return new Person( - ((BigInteger) typedDatabaseRow[0]).longValue(), + return new Person((Long) typedDatabaseRow[0], (String) typedDatabaseRow[1], (String) typedDatabaseRow[2] ); diff --git a/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyPostgresLiveTest.java b/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyPostgresLiveTest.java index 760dacdaa2..cdcc7a6c67 100644 --- a/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyPostgresLiveTest.java +++ b/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyPostgresLiveTest.java @@ -8,9 +8,9 @@ import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceContext; +import jakarta.persistence.Query; import org.hibernate.exception.SQLGrammarException; import org.junit.jupiter.api.BeforeEach; @@ -77,8 +77,7 @@ class SpringPhysicalNamingStrategyPostgresLiveTest { public Person fromDatabase(Object databaseRow) { Object[] typedDatabaseRow = (Object[]) databaseRow; - return new Person( - ((BigInteger) typedDatabaseRow[0]).longValue(), + return new Person((Long) typedDatabaseRow[0], (String) typedDatabaseRow[1], (String) typedDatabaseRow[2] ); diff --git a/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyH2IntegrationTest.java b/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyH2IntegrationTest.java index d0e86384b8..f7431e6000 100644 --- a/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyH2IntegrationTest.java +++ b/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyH2IntegrationTest.java @@ -8,9 +8,9 @@ import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceContext; +import jakarta.persistence.Query; import org.hibernate.exception.SQLGrammarException; import org.junit.jupiter.api.BeforeEach; @@ -77,8 +77,7 @@ class UnquotedLowerCaseNamingStrategyH2IntegrationTest { public Person fromDatabase(Object databaseRow) { Object[] typedDatabaseRow = (Object[]) databaseRow; - return new Person( - ((BigInteger) typedDatabaseRow[0]).longValue(), + return new Person((Long) typedDatabaseRow[0], (String) typedDatabaseRow[1], (String) typedDatabaseRow[2] ); diff --git a/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyPostgresLiveTest.java b/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyPostgresLiveTest.java index 121b184a3c..8eb5a8a493 100644 --- a/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyPostgresLiveTest.java +++ b/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyPostgresLiveTest.java @@ -8,10 +8,6 @@ import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; - import org.hibernate.exception.SQLGrammarException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -22,6 +18,10 @@ import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfigur import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.test.context.TestPropertySource; +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceContext; +import jakarta.persistence.Query; + @DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) @TestPropertySource("unquoted-lower-case-naming-strategy-on-postgres.properties") class UnquotedLowerCaseNamingStrategyPostgresLiveTest { @@ -77,8 +77,7 @@ class UnquotedLowerCaseNamingStrategyPostgresLiveTest { public Person fromDatabase(Object databaseRow) { Object[] typedDatabaseRow = (Object[]) databaseRow; - return new Person( - ((BigInteger) typedDatabaseRow[0]).longValue(), + return new Person((Long) typedDatabaseRow[0], (String) typedDatabaseRow[1], (String) typedDatabaseRow[2] ); diff --git a/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyH2IntegrationTest.java b/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyH2IntegrationTest.java index b4f25605bd..36ba4f62a1 100644 --- a/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyH2IntegrationTest.java +++ b/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyH2IntegrationTest.java @@ -8,9 +8,9 @@ import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceContext; +import jakarta.persistence.Query; import org.hibernate.exception.SQLGrammarException; import org.junit.jupiter.api.BeforeEach; @@ -77,8 +77,7 @@ class UnquotedUpperCaseNamingStrategyH2IntegrationTest { public Person fromDatabase(Object databaseRow) { Object[] typedDatabaseRow = (Object[]) databaseRow; - return new Person( - ((BigInteger) typedDatabaseRow[0]).longValue(), + return new Person((Long) typedDatabaseRow[0], (String) typedDatabaseRow[1], (String) typedDatabaseRow[2] ); diff --git a/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyPostgresLiveTest.java b/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyPostgresLiveTest.java index 7ecd4cc80e..1d4c8bb43c 100644 --- a/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyPostgresLiveTest.java +++ b/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyPostgresLiveTest.java @@ -8,9 +8,9 @@ import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceContext; +import jakarta.persistence.Query; import org.hibernate.exception.SQLGrammarException; import org.junit.jupiter.api.BeforeEach; @@ -77,8 +77,7 @@ class UnquotedUpperCaseNamingStrategyPostgresLiveTest { public Person fromDatabase(Object databaseRow) { Object[] typedDatabaseRow = (Object[]) databaseRow; - return new Person( - ((BigInteger) typedDatabaseRow[0]).longValue(), + return new Person((Long) typedDatabaseRow[0], (String) typedDatabaseRow[1], (String) typedDatabaseRow[2] ); diff --git a/persistence-modules/spring-data-jpa-enterprise-2/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy-on-postgres.properties b/persistence-modules/spring-data-jpa-enterprise-2/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy-on-postgres.properties index 706b12b1b6..a2774db882 100644 --- a/persistence-modules/spring-data-jpa-enterprise-2/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy-on-postgres.properties +++ b/persistence-modules/spring-data-jpa-enterprise-2/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy-on-postgres.properties @@ -2,8 +2,4 @@ spring.datasource.url=jdbc:postgresql://localhost:5432/spring-strategy spring.datasource.username=postgres spring.datasource.password=root -spring.jpa.hibernate.ddl-auto=create-drop -spring.jpa.hibernate.naming.physical-strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy -#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata -#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create -#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=default-naming-strategy-ddl.sql \ No newline at end of file +spring.jpa.hibernate.ddl-auto=create-drop \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-enterprise-2/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy.properties b/persistence-modules/spring-data-jpa-enterprise-2/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy.properties index c9a0c6f24c..13c0e5ebdf 100644 --- a/persistence-modules/spring-data-jpa-enterprise-2/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy.properties +++ b/persistence-modules/spring-data-jpa-enterprise-2/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy.properties @@ -2,8 +2,4 @@ spring.datasource.url=jdbc:h2:mem:spring-strategy spring.datasource.username=sa spring.datasource.password= -spring.jpa.hibernate.ddl-auto=create-drop -spring.jpa.hibernate.naming.physical-strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy -#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata -#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create -#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=default-naming-strategy-ddl.sql \ No newline at end of file +spring.jpa.hibernate.ddl-auto=create-drop \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-query/pom.xml b/persistence-modules/spring-data-jpa-query/pom.xml index da63854859..08d5528023 100644 --- a/persistence-modules/spring-data-jpa-query/pom.xml +++ b/persistence-modules/spring-data-jpa-query/pom.xml @@ -34,11 +34,13 @@ org.springframework spring-oxm + ${spring-oxm.version} 1.4.1 + 6.1.4 \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-repo/pom.xml b/persistence-modules/spring-data-jpa-repo/pom.xml index 1eed56266a..2ead30e7da 100644 --- a/persistence-modules/spring-data-jpa-repo/pom.xml +++ b/persistence-modules/spring-data-jpa-repo/pom.xml @@ -41,6 +41,7 @@ org.springframework spring-oxm + ${spring-oxm.version} com.google.guava @@ -74,4 +75,8 @@ + + 6.1.4 + + \ No newline at end of file diff --git a/pom.xml b/pom.xml index 5938a615a8..f9e4efaaed 100644 --- a/pom.xml +++ b/pom.xml @@ -539,12 +539,6 @@ - parent-boot-1 - parent-boot-2 - parent-spring-4 - parent-spring-5 - parent-spring-6 - spring-4 spring-cloud-modules @@ -586,12 +580,6 @@ - parent-boot-1 - parent-boot-2 - parent-spring-4 - parent-spring-5 - parent-spring-6 - apache-spark jhipster-modules spring-cloud-modules/spring-cloud-azure @@ -767,7 +755,7 @@ lombok-modules lucene mapstruct - + mesos-marathon messaging-modules metrics @@ -1014,7 +1002,7 @@ lombok-modules lucene mapstruct - + mesos-marathon messaging-modules metrics @@ -1139,7 +1127,6 @@ parent-spring-5 parent-spring-6 - diff --git a/quarkus-modules/quarkus-extension/quarkus-liquibase/runtime/pom.xml b/quarkus-modules/quarkus-extension/quarkus-liquibase/runtime/pom.xml index f1fe9eec5c..c5f8080c38 100644 --- a/quarkus-modules/quarkus-extension/quarkus-liquibase/runtime/pom.xml +++ b/quarkus-modules/quarkus-extension/quarkus-liquibase/runtime/pom.xml @@ -66,7 +66,7 @@ - 4.25.0 + 4.26.0 \ No newline at end of file diff --git a/reactive-systems/inventory-service/pom.xml b/reactive-systems/inventory-service/pom.xml index baf5151fdc..0d9556850c 100644 --- a/reactive-systems/inventory-service/pom.xml +++ b/reactive-systems/inventory-service/pom.xml @@ -26,6 +26,7 @@ org.springframework.kafka spring-kafka + ${spring-kafka.version} org.projectlombok diff --git a/reactive-systems/order-service/pom.xml b/reactive-systems/order-service/pom.xml index b6cfb70678..6ef4a9dd8f 100644 --- a/reactive-systems/order-service/pom.xml +++ b/reactive-systems/order-service/pom.xml @@ -26,6 +26,7 @@ org.springframework.kafka spring-kafka + ${spring-kafka.version} org.projectlombok diff --git a/reactive-systems/pom.xml b/reactive-systems/pom.xml index b984fc7cd8..d84e07696d 100644 --- a/reactive-systems/pom.xml +++ b/reactive-systems/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../parent-boot-2 + ../parent-boot-3 @@ -21,4 +21,8 @@ order-service + + 3.1.2 + + \ No newline at end of file diff --git a/reactive-systems/shipping-service/pom.xml b/reactive-systems/shipping-service/pom.xml index 8f94dabdea..888cd08c0c 100644 --- a/reactive-systems/shipping-service/pom.xml +++ b/reactive-systems/shipping-service/pom.xml @@ -22,6 +22,7 @@ org.springframework.kafka spring-kafka + ${spring-kafka.version} com.fasterxml.jackson.core diff --git a/spring-6-rsocket/pom.xml b/spring-6-rsocket/pom.xml index 0874dcb307..989d4b55db 100644 --- a/spring-6-rsocket/pom.xml +++ b/spring-6-rsocket/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-spring-6 + parent-boot-3 0.0.1-SNAPSHOT - ../parent-spring-6 + ../parent-boot-3 @@ -26,29 +26,9 @@ spring-boot-starter-test test - - org.junit - junit-bom - ${junit-jupiter.version} - pom - import - - - - - org.springframework.boot - spring-boot-dependencies - ${spring-boot.version} - pom - import - - - - - 3.1.3 2.0.7 1.4.11 diff --git a/spring-activiti/pom.xml b/spring-activiti/pom.xml index ced1d74103..c0b13c7fff 100644 --- a/spring-activiti/pom.xml +++ b/spring-activiti/pom.xml @@ -10,11 +10,19 @@ com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../parent-boot-2 + ../parent-boot-3 + + + alfresco + alfresco + https://artifacts.alfresco.com/nexus/content/repositories/public/ + + + org.activiti @@ -59,7 +67,7 @@ - 7.1.0.M6 + 8.0.0 \ No newline at end of file diff --git a/spring-activiti/src/main/java/com/baeldung/activiti/security/config/MvcConfig.java b/spring-activiti/src/main/java/com/baeldung/activiti/security/config/MvcConfig.java index f9394742cd..f0c5e95ca5 100644 --- a/spring-activiti/src/main/java/com/baeldung/activiti/security/config/MvcConfig.java +++ b/spring-activiti/src/main/java/com/baeldung/activiti/security/config/MvcConfig.java @@ -3,11 +3,11 @@ package com.baeldung.activiti.security.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration @EnableWebMvc -public class MvcConfig extends WebMvcConfigurerAdapter { +public class MvcConfig implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { diff --git a/spring-activiti/src/main/java/com/baeldung/activiti/security/withspring/SecurityConfig.java b/spring-activiti/src/main/java/com/baeldung/activiti/security/withspring/SecurityConfig.java index 8dc3eee05e..6f3885a7ed 100644 --- a/spring-activiti/src/main/java/com/baeldung/activiti/security/withspring/SecurityConfig.java +++ b/spring-activiti/src/main/java/com/baeldung/activiti/security/withspring/SecurityConfig.java @@ -3,6 +3,7 @@ package com.baeldung.activiti.security.withspring; 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.config.annotation.web.configurers.AbstractHttpConfigurer; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; @@ -14,28 +15,25 @@ public class SecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { - http.antMatcher("/**") - .authorizeRequests() - .antMatchers("/protected-process*") - .authenticated() - .anyRequest() - .permitAll() - .and() - .formLogin() - .loginPage("/login") - .defaultSuccessUrl("/homepage") - .failureUrl("/login?error=true") - .and() - .csrf() - .disable() - .logout() - .logoutSuccessUrl("/login"); + http.authorizeHttpRequests(auth -> auth + .requestMatchers("/protected-process*") + .authenticated() + .anyRequest() + .permitAll()) + .formLogin(login -> login + .loginPage("/login") + .defaultSuccessUrl("/homepage") + .failureUrl("/login?error=true") + .permitAll()) + .csrf(AbstractHttpConfigurer::disable) + .logout(logout -> logout.logoutSuccessUrl("/login")); return http.build(); } @Bean public UserDetailsService userDetailsService() { - UserDetails user = User.withUsername("user") + User.UserBuilder users = User.withDefaultPasswordEncoder(); + UserDetails user = users.username("user") .password("{noop}pass") .authorities("ROLE_ACTIVITI_USER") .build(); diff --git a/spring-activiti/src/main/resources/templates/homepage.html b/spring-activiti/src/main/resources/templates/homepage.html new file mode 100644 index 0000000000..68a7c42537 --- /dev/null +++ b/spring-activiti/src/main/resources/templates/homepage.html @@ -0,0 +1,6 @@ + + + +

Home page

+ + \ No newline at end of file diff --git a/spring-batch/pom.xml b/spring-batch/pom.xml index bca0030729..d4ea7bd306 100644 --- a/spring-batch/pom.xml +++ b/spring-batch/pom.xml @@ -35,7 +35,7 @@ org.springframework spring-oxm - ${spring.version} + ${spring-oxm.version} commons-logging @@ -70,17 +70,25 @@ com.h2database h2 + + org.springframework.batch + spring-batch-core + ${spring-batch-core.version} +
- 6.0.6 5.8 4.0.0 4.0.2 2.16.0 4.5.14 1.5.3 + 6.1.4 + 5.1.1 com.baeldung.batchtesting.SpringBatchApplication + 3.2.2 + 5.10.2 \ No newline at end of file diff --git a/spring-batch/src/main/java/com/baeldung/batchtesting/SpringBatchConfiguration.java b/spring-batch/src/main/java/com/baeldung/batchtesting/SpringBatchConfiguration.java index 547074ff84..c5067d5d94 100644 --- a/spring-batch/src/main/java/com/baeldung/batchtesting/SpringBatchConfiguration.java +++ b/spring-batch/src/main/java/com/baeldung/batchtesting/SpringBatchConfiguration.java @@ -23,6 +23,7 @@ import org.springframework.batch.item.json.JacksonJsonObjectMarshaller; import org.springframework.batch.item.json.JsonFileItemWriter; import org.springframework.batch.item.json.builder.JsonFileItemWriterBuilder; import org.springframework.batch.item.support.ListItemWriter; +import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -111,7 +112,7 @@ public class SpringBatchConfiguration { } @Bean(name = "transformBooksRecords") - public Job transformBookRecords(JobRepository jobRepository, Step step1, Step step2) { + public Job transformBookRecords(JobRepository jobRepository, @Qualifier("step1") Step step1, @Qualifier("step2") Step step2) { // @formatter:off return new JobBuilder("transformBooksRecords", jobRepository) .flow(step1) diff --git a/spring-boot-modules/pom.xml b/spring-boot-modules/pom.xml index 221c3876d4..4504aff083 100644 --- a/spring-boot-modules/pom.xml +++ b/spring-boot-modules/pom.xml @@ -45,7 +45,7 @@ spring-boot-jasypt - + spring-boot-jsp spring-boot-keycloak spring-boot-keycloak-2 @@ -112,6 +112,7 @@ spring-boot-3-url-matching spring-boot-graalvm-docker spring-boot-validations + spring-boot-openapi diff --git a/spring-boot-modules/spring-boot-data-3/README.md b/spring-boot-modules/spring-boot-data-3/README.md index 94516a506c..da50d52bc2 100644 --- a/spring-boot-modules/spring-boot-data-3/README.md +++ b/spring-boot-modules/spring-boot-data-3/README.md @@ -3,3 +3,4 @@ - [Integrate AWS Secrets Manager in Spring Boot](https://www.baeldung.com/spring-boot-integrate-aws-secrets-manager) - [Fix Spring Data JPA Exception: No Property Found for Type](https://www.baeldung.com/spring-data-jpa-exception-no-property-found-for-type) - [Remove Null Objects in JSON Response When Using Spring and Jackson](https://www.baeldung.com/spring-remove-null-objects-json-response-jackson) +- [Skip Select Before Insert in Spring Data JPA](https://www.baeldung.com/spring-data-jpa-skip-select-insert) diff --git a/spring-boot-modules/spring-boot-graphql/README.md b/spring-boot-modules/spring-boot-graphql/README.md index 5f78461ce1..f71cc35b6d 100644 --- a/spring-boot-modules/spring-boot-graphql/README.md +++ b/spring-boot-modules/spring-boot-graphql/README.md @@ -13,6 +13,7 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [How to Test GraphQL Using Postman](https://www.baeldung.com/graphql-postman) - [GraphQL vs REST](https://www.baeldung.com/graphql-vs-rest) - [REST vs. GraphQL vs. gRPC – Which API to Choose?](https://www.baeldung.com/rest-vs-graphql-vs-grpc) +- [Implementing GraphQL Mutation Without Returning Data](https://www.baeldung.com/java-graphql-mutation-no-return-data) ### GraphQL sample queries diff --git a/spring-boot-modules/spring-boot-jsp/pom.xml b/spring-boot-modules/spring-boot-jsp/pom.xml index f4230a12f1..717267cfd3 100644 --- a/spring-boot-modules/spring-boot-jsp/pom.xml +++ b/spring-boot-modules/spring-boot-jsp/pom.xml @@ -55,6 +55,7 @@ org.springframework.boot spring-boot-devtools + org.projectlombok lombok @@ -101,8 +102,9 @@ 1.2 - 2.4.4 + 3.2.2 1.10.0 + 5.10.2 \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-libraries-3/pom.xml b/spring-boot-modules/spring-boot-libraries-3/pom.xml index 0fc72abb64..d0c1d345c0 100644 --- a/spring-boot-modules/spring-boot-libraries-3/pom.xml +++ b/spring-boot-modules/spring-boot-libraries-3/pom.xml @@ -32,7 +32,18 @@ spring-modulith-events-kafka ${spring-modulith-events-kafka.version} - + + com.fasterxml.jackson.core + jackson-databind + + + com.fasterxml.jackson.core + jackson-core + + + com.fasterxml.jackson.core + jackson-annotations + org.springframework.boot spring-boot-starter-test @@ -66,8 +77,6 @@ com.h2database h2 - 2.2.224 - test @@ -81,8 +90,8 @@ 17 - 1.1.2 - 1.19.3 + 1.1.3 + 1.19.6 4.2.0 3.1.2 diff --git a/spring-boot-modules/spring-boot-openapi/pom.xml b/spring-boot-modules/spring-boot-openapi/pom.xml new file mode 100644 index 0000000000..f1cf98e4b5 --- /dev/null +++ b/spring-boot-modules/spring-boot-openapi/pom.xml @@ -0,0 +1,96 @@ + + + 4.0.0 + spring-boot-openapi + spring-boot-openapi + jar + OpenAPI Generator module + + + org.springframework.boot + spring-boot-starter-parent + 2.7.11 + + + + + + + + + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.boot + spring-boot-starter-validation + + + javax.validation + validation-api + + + io.swagger.core.v3 + swagger-annotations + ${swagger-annotations.version} + + + + + + + org.openapitools + openapi-generator-maven-plugin + ${openapi-generator.version} + + + + generate + + + true + ${project.basedir}/src/main/resources/api/quotes.yaml + spring + ApiUtil.java + ${project.basedir}/src/main/resources/templates/JavaSpring + + true + + + java8 + false + true + com.baeldung.tutorials.openapi.quotes.api + com.baeldung.tutorials.openapi.quotes.api.model + source + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + 17 + 17 + 7.3.0 + 2.2.20 + + + \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-openapi/src/main/java/com/baeldung/tutorials/openapi/quotes/QuotesApplication.java b/spring-boot-modules/spring-boot-openapi/src/main/java/com/baeldung/tutorials/openapi/quotes/QuotesApplication.java new file mode 100644 index 0000000000..37d8278133 --- /dev/null +++ b/spring-boot-modules/spring-boot-openapi/src/main/java/com/baeldung/tutorials/openapi/quotes/QuotesApplication.java @@ -0,0 +1,16 @@ +package com.baeldung.tutorials.openapi.quotes; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cache.annotation.EnableCaching; + +import com.baeldung.tutorials.openapi.quotes.service.BrokerService; + +@SpringBootApplication +@EnableCaching +public class QuotesApplication { + + public static void main(String[] args) { + SpringApplication.run(QuotesApplication.class, args); + } +} diff --git a/spring-boot-modules/spring-boot-openapi/src/main/java/com/baeldung/tutorials/openapi/quotes/config/ClockConfiguration.java b/spring-boot-modules/spring-boot-openapi/src/main/java/com/baeldung/tutorials/openapi/quotes/config/ClockConfiguration.java new file mode 100644 index 0000000000..60eb6fc967 --- /dev/null +++ b/spring-boot-modules/spring-boot-openapi/src/main/java/com/baeldung/tutorials/openapi/quotes/config/ClockConfiguration.java @@ -0,0 +1,17 @@ +package com.baeldung.tutorials.openapi.quotes.config; + +import java.time.Clock; + +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class ClockConfiguration { + + @Bean + @ConditionalOnMissingBean + Clock defaultClock() { + return Clock.systemDefaultZone(); + } +} diff --git a/spring-boot-modules/spring-boot-openapi/src/main/java/com/baeldung/tutorials/openapi/quotes/controller/QuotesApiImpl.java b/spring-boot-modules/spring-boot-openapi/src/main/java/com/baeldung/tutorials/openapi/quotes/controller/QuotesApiImpl.java new file mode 100644 index 0000000000..f0e4d5c33f --- /dev/null +++ b/spring-boot-modules/spring-boot-openapi/src/main/java/com/baeldung/tutorials/openapi/quotes/controller/QuotesApiImpl.java @@ -0,0 +1,45 @@ +package com.baeldung.tutorials.openapi.quotes.controller; + +import java.time.Clock; +import java.time.OffsetDateTime; + +import org.springframework.cache.annotation.Cacheable; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Component; + +import com.baeldung.tutorials.openapi.quotes.api.QuotesApi; +import com.baeldung.tutorials.openapi.quotes.api.QuotesApiDelegate; +import com.baeldung.tutorials.openapi.quotes.api.model.QuoteResponse; +import com.baeldung.tutorials.openapi.quotes.service.BrokerService; + +@Component +public class QuotesApiImpl implements QuotesApiDelegate { + private final BrokerService broker; + private final Clock clock; + + public QuotesApiImpl(BrokerService broker, Clock clock) { + this.broker = broker; + this.clock = clock; + } + + + /** + * GET /quotes/{symbol} : Get current quote for a security + * + * @param symbol Security's symbol (required) + * @return OK (status code 200) + * @see QuotesApi#getQuote + */ + @Override + public ResponseEntity getQuote(String symbol) { + + var price = broker.getSecurityPrice(symbol); + + var quote = new QuoteResponse(); + quote.setSymbol(symbol); + quote.setPrice(price); + quote.setTimestamp(OffsetDateTime.now(clock)); + return ResponseEntity.ok(quote); + } +} diff --git a/spring-boot-modules/spring-boot-openapi/src/main/java/com/baeldung/tutorials/openapi/quotes/service/BrokerService.java b/spring-boot-modules/spring-boot-openapi/src/main/java/com/baeldung/tutorials/openapi/quotes/service/BrokerService.java new file mode 100644 index 0000000000..f7520b098d --- /dev/null +++ b/spring-boot-modules/spring-boot-openapi/src/main/java/com/baeldung/tutorials/openapi/quotes/service/BrokerService.java @@ -0,0 +1,32 @@ +package com.baeldung.tutorials.openapi.quotes.service; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import java.util.Random; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.lang.NonNull; +import org.springframework.stereotype.Service; + +@Service +public class BrokerService { + + private final Logger log = LoggerFactory.getLogger(BrokerService.class); + + private final Random rnd = new Random(); + + + public BrokerService() { + } + + + public BigDecimal getSecurityPrice(@NonNull String symbol) { + log.info("getSecurityPrice: {}", symbol); + // Just a mock value + return BigDecimal.valueOf(100.0 + rnd.nextDouble()*100.0); + } +} diff --git a/spring-boot-modules/spring-boot-openapi/src/main/resources/api/quotes.yaml b/spring-boot-modules/spring-boot-openapi/src/main/resources/api/quotes.yaml new file mode 100644 index 0000000000..590fe661ad --- /dev/null +++ b/spring-boot-modules/spring-boot-openapi/src/main/resources/api/quotes.yaml @@ -0,0 +1,54 @@ +openapi: 3.0.0 +info: + title: Quotes API + version: 1.0.0 +servers: + - description: Test server + url: http://localhost:8080 +paths: + /quotes/{symbol}: + get: + tags: + - quotes + summary: Get current quote for a security + operationId: getQuote + x-spring-cacheable: + name: get-quotes + security: + - ApiKey: + - Quotes.Read + parameters: + - name: symbol + in: path + required: true + description: Security's symbol + schema: + type: string + pattern: '[A-Z0-9]+' + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/QuoteResponse' +components: + securitySchemes: + ApiKey: + type: apiKey + in: header + name: X-API-KEY + schemas: + QuoteResponse: + description: Quote response + type: object + properties: + symbol: + type: string + description: security's symbol + price: + type: number + description: Quote value + timestamp: + type: string + format: date-time \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-openapi/src/main/resources/application.yaml b/spring-boot-modules/spring-boot-openapi/src/main/resources/application.yaml new file mode 100644 index 0000000000..c177283306 --- /dev/null +++ b/spring-boot-modules/spring-boot-openapi/src/main/resources/application.yaml @@ -0,0 +1,5 @@ + +logging: + level: + root: INFO + org.springframework: INFO \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-openapi/src/main/resources/templates/JavaSpring/apiDelegate.mustache b/spring-boot-modules/spring-boot-openapi/src/main/resources/templates/JavaSpring/apiDelegate.mustache new file mode 100644 index 0000000000..a26fb3556d --- /dev/null +++ b/spring-boot-modules/spring-boot-openapi/src/main/resources/templates/JavaSpring/apiDelegate.mustache @@ -0,0 +1,84 @@ +/* +* Generated code: do not modify ! +* Custom template with support for x-spring-cacheable extension +*/ +package {{package}}; + +{{#imports}}import {{import}}; +{{/imports}} +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +{{#useResponseEntity}} + import org.springframework.http.ResponseEntity; +{{/useResponseEntity}} +import org.springframework.web.context.request.NativeWebRequest; +import org.springframework.web.multipart.MultipartFile; +{{#reactive}} + import org.springframework.web.server.ServerWebExchange; + import reactor.core.publisher.Flux; + import reactor.core.publisher.Mono; + import org.springframework.http.codec.multipart.Part; +{{/reactive}} + +{{#useBeanValidation}} + import {{javaxPackage}}.validation.constraints.*; + import {{javaxPackage}}.validation.Valid; +{{/useBeanValidation}} +import java.util.List; +import java.util.Map; +import java.util.Optional; +{{#async}} + import java.util.concurrent.CompletableFuture; +{{/async}} +import {{javaxPackage}}.annotation.Generated; + +{{#operations}} + /** + * A delegate to be called by the {@link {{classname}}Controller}}. + * Implement this interface with a {@link org.springframework.stereotype.Service} annotated class. + */ + {{>generatedAnnotation}} + public interface {{classname}}Delegate { + {{#jdk8-default-interface}} + + default Optional getRequest() { + return Optional.empty(); + } + {{/jdk8-default-interface}} + + {{#operation}} + /** + * {{httpMethod}} {{{path}}}{{#summary}} : {{.}}{{/summary}} + {{#notes}} + * {{.}} + {{/notes}} + * + {{#allParams}} + * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} + {{/allParams}} + * @return {{#responses}}{{message}} (status code {{code}}){{^-last}} + * or {{/-last}}{{/responses}} + {{#isDeprecated}} + * @deprecated + {{/isDeprecated}} + {{#externalDocs}} + * {{description}} + * @see {{summary}} Documentation + {{/externalDocs}} + * @see {{classname}}#{{operationId}} + */ + {{#isDeprecated}} + @Deprecated + {{/isDeprecated}} + {{#vendorExtensions.x-spring-cacheable}} + @org.springframework.cache.annotation.Cacheable({{#name}}"{{.}}"{{/name}}{{^name}}"default"{{/name}}) + {{/vendorExtensions.x-spring-cacheable}} + {{#jdk8-default-interface}}default {{/jdk8-default-interface}}{{>responseType}} {{operationId}}({{#allParams}}{{^isFile}}{{^isBodyParam}}{{>optionalDataType}}{{/isBodyParam}}{{#isBodyParam}}{{^reactive}}{{{dataType}}}{{/reactive}}{{#reactive}}{{^isArray}}Mono<{{{dataType}}}>{{/isArray}}{{#isArray}}Flux<{{{baseType}}}>{{/isArray}}{{/reactive}}{{/isBodyParam}}{{/isFile}}{{#isFile}}{{#isArray}}List<{{/isArray}}{{#reactive}}Flux{{/reactive}}{{^reactive}}MultipartFile{{/reactive}}{{#isArray}}>{{/isArray}}{{/isFile}} {{paramName}}{{^-last}}, + {{/-last}}{{/allParams}}{{#reactive}}{{#hasParams}}, + {{/hasParams}}ServerWebExchange exchange{{/reactive}}{{#vendorExtensions.x-spring-paginated}}{{#hasParams}}, {{/hasParams}}{{^hasParams}}{{#reactive}}, {{/reactive}}{{/hasParams}}final Pageable pageable{{/vendorExtensions.x-spring-paginated}}){{#unhandledException}} throws Exception{{/unhandledException}}{{^jdk8-default-interface}};{{/jdk8-default-interface}}{{#jdk8-default-interface}} { + {{>methodBody}} + }{{/jdk8-default-interface}} + + {{/operation}} + } +{{/operations}} diff --git a/spring-boot-modules/spring-boot-openapi/src/test/java/com/baeldung/tutorials/openapi/quotes/QuotesApplicationIntegrationTest.java b/spring-boot-modules/spring-boot-openapi/src/test/java/com/baeldung/tutorials/openapi/quotes/QuotesApplicationIntegrationTest.java new file mode 100644 index 0000000000..b1defb99b1 --- /dev/null +++ b/spring-boot-modules/spring-boot-openapi/src/test/java/com/baeldung/tutorials/openapi/quotes/QuotesApplicationIntegrationTest.java @@ -0,0 +1,45 @@ +package com.baeldung.tutorials.openapi.quotes; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +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.web.client.TestRestTemplate; +import org.springframework.boot.test.web.server.LocalServerPort; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpStatus; + +import com.baeldung.tutorials.openapi.quotes.api.model.QuoteResponse; + +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +class QuotesApplicationIntegrationTest { + + @LocalServerPort + private int port; + + @Autowired + private TestRestTemplate restTemplate; + + @Test + void whenGetQuote_thenSuccess() { + var response = restTemplate.getForEntity("http://localhost:" + port + "/quotes/BAEL", QuoteResponse.class); + assertThat(response.getStatusCode()) + .isEqualTo(HttpStatus.OK); + } + + @Test + void whenGetQuoteMultipleTimes_thenResponseCached() { + + // Call server a few times and collect responses + var quotes = IntStream.range(1, 10).boxed() + .map((i) -> restTemplate.getForEntity("http://localhost:" + port + "/quotes/BAEL", QuoteResponse.class)) + .map(HttpEntity::getBody) + .collect(Collectors.groupingBy((q -> q.hashCode()), Collectors.counting())); + + assertThat(quotes.size()).isEqualTo(1); + } +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-openapi/src/test/java/com/baeldung/tutorials/openapi/quotes/controller/QuotesApiImplUnitTest.java b/spring-boot-modules/spring-boot-openapi/src/test/java/com/baeldung/tutorials/openapi/quotes/controller/QuotesApiImplUnitTest.java new file mode 100644 index 0000000000..01e37ef104 --- /dev/null +++ b/spring-boot-modules/spring-boot-openapi/src/test/java/com/baeldung/tutorials/openapi/quotes/controller/QuotesApiImplUnitTest.java @@ -0,0 +1,55 @@ +package com.baeldung.tutorials.openapi.quotes.controller; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.time.Clock; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneId; + +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.TestConfiguration; +import org.springframework.cache.annotation.EnableCaching; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Primary; + +import com.baeldung.tutorials.openapi.quotes.api.QuotesApi; + +@SpringBootTest +class QuotesApiImplUnitTest { + + @Autowired + private QuotesApi api; + + + private static Instant NOW = Instant.now(); + + @Test + void whenGetQuote_then_success() { + + var response = api.getQuote("GOOG"); + assertThat(response) + .isNotNull(); + + assertThat(response.getStatusCode().is2xxSuccessful()) + .isTrue(); + + assertThat(response.getBody().getTimestamp()) + .isEqualTo(OffsetDateTime.ofInstant(NOW, ZoneId.systemDefault())); + } + + + @TestConfiguration + @EnableCaching + static class TestConfig { + + @Bean + @Primary + Clock fixedClock() { + return Clock.fixed(NOW, ZoneId.systemDefault()); + } + + } +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-resilience4j/pom.xml b/spring-boot-modules/spring-boot-resilience4j/pom.xml index 2f3af8f9d2..809afc1aa4 100644 --- a/spring-boot-modules/spring-boot-resilience4j/pom.xml +++ b/spring-boot-modules/spring-boot-resilience4j/pom.xml @@ -29,8 +29,8 @@ io.github.resilience4j - resilience4j-spring-boot2 - ${resilience4j-spring-boot2.version} + resilience4j-spring-boot3 + ${resilience4j-spring-boot3.version} com.fasterxml.jackson.datatype @@ -43,17 +43,17 @@ test - com.github.tomakehurst - wiremock-jre8 - ${wiremock-jre8.version} + org.wiremock + wiremock + ${wiremock.version} test - 2.35.0 - 2.0.2 - 2.16.0 + 3.4.2 + 2.2.0 + 2.16.1 \ No newline at end of file diff --git a/spring-boot-rest/pom.xml b/spring-boot-rest/pom.xml index 2fd05ef394..4092c68080 100644 --- a/spring-boot-rest/pom.xml +++ b/spring-boot-rest/pom.xml @@ -35,6 +35,7 @@ org.springframework spring-oxm + ${spring-oxm.version} com.thoughtworks.xstream @@ -165,5 +166,6 @@ 3.2.0 3.3.0 4.0.1 + 6.1.4 diff --git a/spring-cloud-modules/spring-cloud-azure/pom.xml b/spring-cloud-modules/spring-cloud-azure/pom.xml index f1f8d38468..cd06aa02dd 100644 --- a/spring-cloud-modules/spring-cloud-azure/pom.xml +++ b/spring-cloud-modules/spring-cloud-azure/pom.xml @@ -18,13 +18,6 @@ - - org.springframework.boot - spring-boot-dependencies - 2.7.8 - pom - import - org.springframework.cloud spring-cloud-dependencies diff --git a/spring-reactive-modules/spring-reactive-filters/pom.xml b/spring-reactive-modules/spring-reactive-filters/pom.xml index 23c6c0f528..a6b9e7c6af 100644 --- a/spring-reactive-modules/spring-reactive-filters/pom.xml +++ b/spring-reactive-modules/spring-reactive-filters/pom.xml @@ -10,9 +10,10 @@ spring boot sample project about new features - com.baeldung.spring.reactive - spring-reactive-modules - 1.0.0-SNAPSHOT + com.baeldung + parent-boot-3 + 0.0.1-SNAPSHOT + ../../parent-boot-3 @@ -20,6 +21,16 @@ org.springframework.boot spring-boot-starter-webflux + + io.projectreactor + reactor-core + ${reactor.version} + + + io.netty + netty-all + + org.springframework.boot @@ -41,16 +52,16 @@ reactor-test test - - io.netty - netty-all + org.wiremock + wiremock-standalone + ${wiremock-standalone.version} test - com.github.tomakehurst - wiremock-standalone - ${wiremock-standalone.version} + io.projectreactor + reactor-test + ${reactor.version} test @@ -69,7 +80,8 @@ - 2.26.0 + 3.4.2 + 3.6.0 \ No newline at end of file diff --git a/spring-reactive-modules/spring-reactive-filters/src/test/java/com/baeldung/reactive/filters/FilteredWebClientUnitTest.java b/spring-reactive-modules/spring-reactive-filters/src/test/java/com/baeldung/reactive/filters/FilteredWebClientUnitTest.java index 1350db0752..0445633253 100644 --- a/spring-reactive-modules/spring-reactive-filters/src/test/java/com/baeldung/reactive/filters/FilteredWebClientUnitTest.java +++ b/spring-reactive-modules/spring-reactive-filters/src/test/java/com/baeldung/reactive/filters/FilteredWebClientUnitTest.java @@ -96,7 +96,7 @@ public class FilteredWebClientUnitTest { stubFor(get(urlPathEqualTo(PATH)).willReturn(aResponse().withStatus(200) .withBody("done"))); - try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos);) { + try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos)) { WebClient webClient = WebClient.builder() .filter(loggingFilter(ps)) .build(); diff --git a/spring-security-modules/pom.xml b/spring-security-modules/pom.xml index f97305587b..d2f4a81ae6 100644 --- a/spring-security-modules/pom.xml +++ b/spring-security-modules/pom.xml @@ -23,7 +23,7 @@ spring-security-core-2 spring-security-legacy-oidc - spring-security-oauth2 + spring-security-oauth2 spring-security-oauth2-sso spring-security-oidc spring-security-okta @@ -36,7 +36,7 @@ spring-security-web-boot-4 spring-security-web-boot-5 spring-security-web-digest-auth - spring-security-web-login + spring-security-web-login-2 spring-security-web-mvc-custom spring-security-web-mvc diff --git a/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/authorizationmanager/DemoController.java b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/authorizationmanager/DemoController.java new file mode 100644 index 0000000000..9d9e7fd245 --- /dev/null +++ b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/authorizationmanager/DemoController.java @@ -0,0 +1,28 @@ +package com.baeldung.authorizationmanager; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class DemoController { + @GetMapping("/anonymous") + public String anonymousResource() { + return "anonymous"; + } + + @GetMapping("/adminonly") + public String adminResource() { + return "admin only"; + } + + @GetMapping("/authororeditor") + public String authorOrEditorResource() { + return "author or editor"; + } + + @GetMapping("/custom") + public String customResource() { + return "custom"; + } +} + diff --git a/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/authorizationmanager/DemoSecurityConfig.java b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/authorizationmanager/DemoSecurityConfig.java new file mode 100644 index 0000000000..63a3f04365 --- /dev/null +++ b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/authorizationmanager/DemoSecurityConfig.java @@ -0,0 +1,65 @@ +package com.baeldung.authorizationmanager; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.authorization.AuthorizationDecision; +import org.springframework.security.authorization.AuthorizationManager; +import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.provisioning.InMemoryUserDetailsManager; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.access.intercept.RequestAuthorizationContext; + +import java.util.Random; +import java.util.function.Supplier; + +import static org.springframework.security.config.Customizer.withDefaults; + +@Configuration +@EnableMethodSecurity +public class DemoSecurityConfig { + + @Bean + SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { + http.authorizeHttpRequests((authorize) -> authorize + .requestMatchers("/custom/**").access(customAuthManager()) + .requestMatchers("/adminonly/**").hasRole("ADMIN") + .requestMatchers("/editororauthor/**").hasAnyRole("EDITOR","AUTHOR") + .anyRequest().permitAll()) + .formLogin(withDefaults()); + return http.build(); + } + + @Bean + public InMemoryUserDetailsManager userDetailsService() { + UserDetails admin = User.withUsername("admin") + .password(passwordEncoder().encode("admin")) + .roles("ADMIN") + .build(); + UserDetails author = User.withUsername("author") + .password(passwordEncoder().encode("author")) + .roles("AUTHOR") + .build(); + UserDetails editor = User.withUsername("editor") + .password(passwordEncoder().encode("editor")) + .roles("EDITOR") + .build(); + return new InMemoryUserDetailsManager(admin, author, editor); + } + + @Bean + PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } + + @Bean + AuthorizationManager customAuthManager() { + return (authentication, object) -> new AuthorizationDecision(new Random().nextBoolean()); + } +} + diff --git a/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/authorizationmanager/SpringSecurityAuthManagerDemoApplication.java b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/authorizationmanager/SpringSecurityAuthManagerDemoApplication.java new file mode 100644 index 0000000000..fc3f2657fe --- /dev/null +++ b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/authorizationmanager/SpringSecurityAuthManagerDemoApplication.java @@ -0,0 +1,14 @@ +package com.baeldung.authorizationmanager; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringSecurityAuthManagerDemoApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringSecurityAuthManagerDemoApplication.class, args); + } +} + + diff --git a/spring-security-modules/spring-security-oauth2/pom.xml b/spring-security-modules/spring-security-oauth2/pom.xml index e339deef05..23af6017ec 100644 --- a/spring-security-modules/spring-security-oauth2/pom.xml +++ b/spring-security-modules/spring-security-oauth2/pom.xml @@ -9,6 +9,8 @@ jar spring 5 security oauth sample project + com.baeldung spring-security-modules diff --git a/spring-security-modules/spring-security-web-digest-auth/pom.xml b/spring-security-modules/spring-security-web-digest-auth/pom.xml index 259a4e4730..23aa2503ae 100644 --- a/spring-security-modules/spring-security-web-digest-auth/pom.xml +++ b/spring-security-modules/spring-security-web-digest-auth/pom.xml @@ -82,7 +82,7 @@ org.springframework spring-oxm - ${spring.version} + ${spring-oxm.version} @@ -172,6 +172,7 @@ 6.1.5 + 6.1.4 5.2.4 5.3 diff --git a/spring-security-modules/spring-security-web-rest-basic-auth/pom.xml b/spring-security-modules/spring-security-web-rest-basic-auth/pom.xml index 1b63860b92..1a055ee39c 100644 --- a/spring-security-modules/spring-security-web-rest-basic-auth/pom.xml +++ b/spring-security-modules/spring-security-web-rest-basic-auth/pom.xml @@ -75,6 +75,7 @@ org.springframework spring-oxm + ${spring-oxm.version} @@ -213,6 +214,7 @@ 2.3.1 + 6.1.4 4.4.11 4.5.8 diff --git a/spring-security-modules/spring-security-web-rest-custom/pom.xml b/spring-security-modules/spring-security-web-rest-custom/pom.xml index 265adfa551..6fe241056c 100644 --- a/spring-security-modules/spring-security-web-rest-custom/pom.xml +++ b/spring-security-modules/spring-security-web-rest-custom/pom.xml @@ -73,6 +73,7 @@ org.springframework spring-oxm + ${spring-oxm.version} commons-logging @@ -172,6 +173,7 @@ 1.2 2.3.1 + 6.1.4 1.6.1 diff --git a/spring-security-modules/spring-security-web-rest/pom.xml b/spring-security-modules/spring-security-web-rest/pom.xml index 76d9ad37de..6bc9131e3e 100644 --- a/spring-security-modules/spring-security-web-rest/pom.xml +++ b/spring-security-modules/spring-security-web-rest/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-spring-5 + parent-boot-3 0.0.1-SNAPSHOT - ../../parent-spring-5 + ../../parent-boot-3 @@ -144,6 +144,12 @@ commons-fileupload ${commons-fileupload.version} + + jakarta.servlet + jakarta.servlet-api + ${jakarta.servlet.version} + provided + @@ -155,6 +161,13 @@ + + org.springframework.boot + spring-boot-maven-plugin + + true + + org.codehaus.cargo cargo-maven2-plugin @@ -237,6 +250,9 @@ 2.9.0 1.6.1 + 6.0.13 + 6.1.5 + 6.0.0 \ No newline at end of file diff --git a/spring-security-modules/spring-security-web-rest/src/main/java/com/baeldung/errorhandling/CustomRestExceptionHandler.java b/spring-security-modules/spring-security-web-rest/src/main/java/com/baeldung/errorhandling/CustomRestExceptionHandler.java index 02bc0a2512..a98acd2f9a 100644 --- a/spring-security-modules/spring-security-web-rest/src/main/java/com/baeldung/errorhandling/CustomRestExceptionHandler.java +++ b/spring-security-modules/spring-security-web-rest/src/main/java/com/baeldung/errorhandling/CustomRestExceptionHandler.java @@ -9,8 +9,8 @@ import javax.validation.ConstraintViolationException; import org.springframework.beans.TypeMismatchException; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; +import org.springframework.http.HttpStatusCode; import org.springframework.http.ResponseEntity; -import org.springframework.validation.BindException; import org.springframework.validation.FieldError; import org.springframework.validation.ObjectError; import org.springframework.web.HttpMediaTypeNotSupportedException; @@ -31,7 +31,7 @@ public class CustomRestExceptionHandler extends ResponseEntityExceptionHandler { // 400 @Override - protected ResponseEntity handleMethodArgumentNotValid(final MethodArgumentNotValidException ex, final HttpHeaders headers, final HttpStatus status, final WebRequest request) { + protected ResponseEntity handleMethodArgumentNotValid(final MethodArgumentNotValidException ex, final HttpHeaders headers, final HttpStatusCode status, final WebRequest request) { logger.info(ex.getClass().getName()); // final List errors = new ArrayList(); @@ -46,22 +46,7 @@ public class CustomRestExceptionHandler extends ResponseEntityExceptionHandler { } @Override - protected ResponseEntity handleBindException(final BindException ex, final HttpHeaders headers, final HttpStatus status, final WebRequest request) { - logger.info(ex.getClass().getName()); - // - final List errors = new ArrayList(); - for (final FieldError error : ex.getBindingResult().getFieldErrors()) { - errors.add(error.getField() + ": " + error.getDefaultMessage()); - } - for (final ObjectError error : ex.getBindingResult().getGlobalErrors()) { - errors.add(error.getObjectName() + ": " + error.getDefaultMessage()); - } - final ApiError apiError = new ApiError(HttpStatus.BAD_REQUEST, ex.getLocalizedMessage(), errors); - return handleExceptionInternal(ex, apiError, headers, apiError.getStatus(), request); - } - - @Override - protected ResponseEntity handleTypeMismatch(final TypeMismatchException ex, final HttpHeaders headers, final HttpStatus status, final WebRequest request) { + protected ResponseEntity handleTypeMismatch(TypeMismatchException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) { logger.info(ex.getClass().getName()); // final String error = ex.getValue() + " value for " + ex.getPropertyName() + " should be of type " + ex.getRequiredType(); @@ -71,7 +56,7 @@ public class CustomRestExceptionHandler extends ResponseEntityExceptionHandler { } @Override - protected ResponseEntity handleMissingServletRequestPart(final MissingServletRequestPartException ex, final HttpHeaders headers, final HttpStatus status, final WebRequest request) { + protected ResponseEntity handleMissingServletRequestPart(final MissingServletRequestPartException ex, final HttpHeaders headers, final HttpStatusCode status, final WebRequest request) { logger.info(ex.getClass().getName()); // final String error = ex.getRequestPartName() + " part is missing"; @@ -80,7 +65,7 @@ public class CustomRestExceptionHandler extends ResponseEntityExceptionHandler { } @Override - protected ResponseEntity handleMissingServletRequestParameter(final MissingServletRequestParameterException ex, final HttpHeaders headers, final HttpStatus status, final WebRequest request) { + protected ResponseEntity handleMissingServletRequestParameter(final MissingServletRequestParameterException ex, final HttpHeaders headers, final HttpStatusCode status, final WebRequest request) { logger.info(ex.getClass().getName()); // final String error = ex.getParameterName() + " parameter is missing"; @@ -116,7 +101,7 @@ public class CustomRestExceptionHandler extends ResponseEntityExceptionHandler { // 404 @Override - protected ResponseEntity handleNoHandlerFoundException(final NoHandlerFoundException ex, final HttpHeaders headers, final HttpStatus status, final WebRequest request) { + protected ResponseEntity handleNoHandlerFoundException(final NoHandlerFoundException ex, final HttpHeaders headers, final HttpStatusCode status, final WebRequest request) { logger.info(ex.getClass().getName()); // final String error = "No handler found for " + ex.getHttpMethod() + " " + ex.getRequestURL(); @@ -128,7 +113,7 @@ public class CustomRestExceptionHandler extends ResponseEntityExceptionHandler { // 405 @Override - protected ResponseEntity handleHttpRequestMethodNotSupported(final HttpRequestMethodNotSupportedException ex, final HttpHeaders headers, final HttpStatus status, final WebRequest request) { + protected ResponseEntity handleHttpRequestMethodNotSupported(final HttpRequestMethodNotSupportedException ex, final HttpHeaders headers, final HttpStatusCode status, final WebRequest request) { logger.info(ex.getClass().getName()); // final StringBuilder builder = new StringBuilder(); @@ -143,7 +128,7 @@ public class CustomRestExceptionHandler extends ResponseEntityExceptionHandler { // 415 @Override - protected ResponseEntity handleHttpMediaTypeNotSupported(final HttpMediaTypeNotSupportedException ex, final HttpHeaders headers, final HttpStatus status, final WebRequest request) { + protected ResponseEntity handleHttpMediaTypeNotSupported(final HttpMediaTypeNotSupportedException ex, final HttpHeaders headers, final HttpStatusCode status, final WebRequest request) { logger.info(ex.getClass().getName()); // final StringBuilder builder = new StringBuilder(); diff --git a/spring-security-modules/spring-security-web-rest/src/main/java/com/baeldung/security/SecurityJavaConfig.java b/spring-security-modules/spring-security-web-rest/src/main/java/com/baeldung/security/SecurityJavaConfig.java index 0a79151f89..71a755e24d 100644 --- a/spring-security-modules/spring-security-web-rest/src/main/java/com/baeldung/security/SecurityJavaConfig.java +++ b/spring-security-modules/spring-security-web-rest/src/main/java/com/baeldung/security/SecurityJavaConfig.java @@ -1,11 +1,13 @@ package com.baeldung.security; +import static org.springframework.security.config.Customizer.withDefaults; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; -import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +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.core.userdetails.User; @@ -23,7 +25,7 @@ import com.baeldung.web.error.CustomAccessDeniedHandler; @Configuration @EnableWebSecurity -@EnableGlobalMethodSecurity(prePostEnabled = true) +@EnableMethodSecurity(prePostEnabled = true) @ComponentScan("com.baeldung.security") public class SecurityJavaConfig { @@ -53,36 +55,17 @@ public class SecurityJavaConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { - http.csrf() - .disable() - .authorizeRequests() - .and() - .exceptionHandling() - .accessDeniedHandler(accessDeniedHandler) - .authenticationEntryPoint(restAuthenticationEntryPoint) - .and() - .authorizeRequests() - .antMatchers("/api/csrfAttacker*") - .permitAll() - .antMatchers("/api/customer/**") - .permitAll() - .antMatchers("/api/foos/**") - .authenticated() - .antMatchers("/api/async/**") - .permitAll() - .antMatchers("/api/admin/**") - .hasRole("ADMIN") - .and() - .formLogin() - .successHandler(mySuccessHandler) - .failureHandler(myFailureHandler) - .and() - .httpBasic() - .and() - .logout(); + http.authorizeHttpRequests (authorizeRequests -> authorizeRequests.requestMatchers("/api/csrfAttacker*").permitAll() + .requestMatchers("/api/customer/**").permitAll() + .requestMatchers("/api/foos/**").authenticated() + .requestMatchers("/api/async/**").permitAll() + .requestMatchers("/api/admin/**").hasRole("ADMIN")) + .formLogin(formLogin -> formLogin.successHandler(mySuccessHandler).failureHandler(myFailureHandler)) + .httpBasic(withDefaults()) + .logout(logout -> logout.permitAll()); return http.build(); } - + @Bean public PasswordEncoder encoder() { return new BCryptPasswordEncoder(); diff --git a/spring-security-modules/spring-security-web-rest/src/main/java/com/baeldung/security/web/MySavedRequestAwareAuthenticationSuccessHandler.java b/spring-security-modules/spring-security-web-rest/src/main/java/com/baeldung/security/web/MySavedRequestAwareAuthenticationSuccessHandler.java index 2d74ed9dca..51120139d0 100644 --- a/spring-security-modules/spring-security-web-rest/src/main/java/com/baeldung/security/web/MySavedRequestAwareAuthenticationSuccessHandler.java +++ b/spring-security-modules/spring-security-web-rest/src/main/java/com/baeldung/security/web/MySavedRequestAwareAuthenticationSuccessHandler.java @@ -2,10 +2,6 @@ package com.baeldung.security.web; import java.io.IOException; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler; import org.springframework.security.web.savedrequest.HttpSessionRequestCache; @@ -14,6 +10,10 @@ import org.springframework.security.web.savedrequest.SavedRequest; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; + @Component public class MySavedRequestAwareAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler { diff --git a/spring-security-modules/spring-security-web-rest/src/main/java/com/baeldung/security/web/RestAuthenticationEntryPoint.java b/spring-security-modules/spring-security-web-rest/src/main/java/com/baeldung/security/web/RestAuthenticationEntryPoint.java index 162ee46727..bb157901c5 100644 --- a/spring-security-modules/spring-security-web-rest/src/main/java/com/baeldung/security/web/RestAuthenticationEntryPoint.java +++ b/spring-security-modules/spring-security-web-rest/src/main/java/com/baeldung/security/web/RestAuthenticationEntryPoint.java @@ -2,13 +2,13 @@ package com.baeldung.security.web; import java.io.IOException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.stereotype.Component; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; + /** * The Entry Point will not redirect to any sort of Login - it will return the 401 */ diff --git a/spring-security-modules/spring-security-web-rest/src/main/java/com/baeldung/web/error/CustomAccessDeniedHandler.java b/spring-security-modules/spring-security-web-rest/src/main/java/com/baeldung/web/error/CustomAccessDeniedHandler.java index 6c686cd9e9..1c5d025ee2 100644 --- a/spring-security-modules/spring-security-web-rest/src/main/java/com/baeldung/web/error/CustomAccessDeniedHandler.java +++ b/spring-security-modules/spring-security-web-rest/src/main/java/com/baeldung/web/error/CustomAccessDeniedHandler.java @@ -2,14 +2,15 @@ package com.baeldung.web.error; import java.io.IOException; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.web.access.AccessDeniedHandler; import org.springframework.stereotype.Component; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; + @Component public class CustomAccessDeniedHandler implements AccessDeniedHandler { diff --git a/spring-security-modules/spring-security-web-rest/src/main/java/com/baeldung/web/error/RestResponseEntityExceptionHandler.java b/spring-security-modules/spring-security-web-rest/src/main/java/com/baeldung/web/error/RestResponseEntityExceptionHandler.java index 9e6ae78d27..8744c29858 100644 --- a/spring-security-modules/spring-security-web-rest/src/main/java/com/baeldung/web/error/RestResponseEntityExceptionHandler.java +++ b/spring-security-modules/spring-security-web-rest/src/main/java/com/baeldung/web/error/RestResponseEntityExceptionHandler.java @@ -32,19 +32,6 @@ public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionH return handleExceptionInternal(ex, bodyOfResponse, new HttpHeaders(), HttpStatus.BAD_REQUEST, request); } - @Override - protected ResponseEntity handleHttpMessageNotReadable(final HttpMessageNotReadableException ex, final HttpHeaders headers, final HttpStatus status, final WebRequest request) { - final String bodyOfResponse = "This should be application specific"; - // ex.getCause() instanceof JsonMappingException, JsonParseException // for additional information later on - return handleExceptionInternal(ex, bodyOfResponse, headers, HttpStatus.BAD_REQUEST, request); - } - - @Override - protected ResponseEntity handleMethodArgumentNotValid(final MethodArgumentNotValidException ex, final HttpHeaders headers, final HttpStatus status, final WebRequest request) { - final String bodyOfResponse = "This should be application specific"; - return handleExceptionInternal(ex, bodyOfResponse, headers, HttpStatus.BAD_REQUEST, request); - } - // 403 @ExceptionHandler({ AccessDeniedException.class }) public ResponseEntity handleAccessDeniedException(final Exception ex, final WebRequest request) { diff --git a/spring-security-modules/spring-security-web-rest/src/test/java/com/baeldung/web/TestConfig.java b/spring-security-modules/spring-security-web-rest/src/test/java/com/baeldung/web/TestConfig.java index ddb7240611..3abf7c7840 100644 --- a/spring-security-modules/spring-security-web-rest/src/test/java/com/baeldung/web/TestConfig.java +++ b/spring-security-modules/spring-security-web-rest/src/test/java/com/baeldung/web/TestConfig.java @@ -4,7 +4,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.multipart.MultipartResolver; -import org.springframework.web.multipart.commons.CommonsMultipartResolver; +import org.springframework.web.multipart.support.StandardServletMultipartResolver; @Configuration @ComponentScan({ "com.baeldung.web" }) @@ -12,7 +12,7 @@ public class TestConfig { @Bean public MultipartResolver multipartResolver() { - CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(); + StandardServletMultipartResolver multipartResolver = new StandardServletMultipartResolver(); return multipartResolver; } diff --git a/spring-web-modules/spring-mvc-basics/pom.xml b/spring-web-modules/spring-mvc-basics/pom.xml index bfd8ed5d5f..1517b2111f 100644 --- a/spring-web-modules/spring-mvc-basics/pom.xml +++ b/spring-web-modules/spring-mvc-basics/pom.xml @@ -65,6 +65,13 @@ JAR + + org.apache.maven.plugins + maven-compiler-plugin + + true + + diff --git a/spring-web-modules/spring-rest-http/pom.xml b/spring-web-modules/spring-rest-http/pom.xml index f93e4274e9..1d1b899fd4 100644 --- a/spring-web-modules/spring-rest-http/pom.xml +++ b/spring-web-modules/spring-rest-http/pom.xml @@ -31,6 +31,7 @@ org.springframework spring-oxm + ${spring-oxm.version} com.thoughtworks.xstream @@ -85,6 +86,7 @@ 1.4.9 1.12 5.2.1 + 6.1.4 \ No newline at end of file diff --git a/spring-web-modules/spring-rest-shell/pom.xml b/spring-web-modules/spring-rest-shell/pom.xml index 992092f43f..98e3a6a6f2 100644 --- a/spring-web-modules/spring-rest-shell/pom.xml +++ b/spring-web-modules/spring-rest-shell/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../../parent-boot-2 + ../../parent-boot-3 diff --git a/spring-web-modules/spring-rest-shell/src/main/java/com/baeldung/acticle/Article.java b/spring-web-modules/spring-rest-shell/src/main/java/com/baeldung/acticle/Article.java index 6a55517f9f..cb46ea3352 100644 --- a/spring-web-modules/spring-rest-shell/src/main/java/com/baeldung/acticle/Article.java +++ b/spring-web-modules/spring-rest-shell/src/main/java/com/baeldung/acticle/Article.java @@ -1,8 +1,8 @@ package com.baeldung.acticle; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; @Entity public final class Article { diff --git a/spring-web-modules/spring-rest-simple/pom.xml b/spring-web-modules/spring-rest-simple/pom.xml index c4f3a15959..a75c7c0e90 100644 --- a/spring-web-modules/spring-rest-simple/pom.xml +++ b/spring-web-modules/spring-rest-simple/pom.xml @@ -56,6 +56,7 @@ org.springframework spring-oxm + ${spring-oxm.version} commons-fileupload @@ -273,6 +274,7 @@ 3.1.0 1.4.9 2.9.0 + 6.1.4 1.6.0 3.0.4 diff --git a/spring-web-modules/spring-thymeleaf-2/pom.xml b/spring-web-modules/spring-thymeleaf-2/pom.xml index 14e4de668b..422edbfd68 100644 --- a/spring-web-modules/spring-thymeleaf-2/pom.xml +++ b/spring-web-modules/spring-thymeleaf-2/pom.xml @@ -9,9 +9,9 @@ com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../../parent-boot-2 + ../../parent-boot-3 diff --git a/spring-web-modules/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/enums/WidgetController.java b/spring-web-modules/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/enums/WidgetController.java index c66464d75b..fb27c33026 100644 --- a/spring-web-modules/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/enums/WidgetController.java +++ b/spring-web-modules/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/enums/WidgetController.java @@ -1,6 +1,6 @@ package com.baeldung.thymeleaf.enums; -import javax.validation.Valid; +import jakarta.validation.Valid; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; diff --git a/spring-web-modules/spring-thymeleaf-3/pom.xml b/spring-web-modules/spring-thymeleaf-3/pom.xml index 8f39c17d8c..064af14385 100644 --- a/spring-web-modules/spring-thymeleaf-3/pom.xml +++ b/spring-web-modules/spring-thymeleaf-3/pom.xml @@ -9,9 +9,9 @@ com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../../parent-boot-2 + ../../parent-boot-3 diff --git a/spring-web-modules/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/errors/User.java b/spring-web-modules/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/errors/User.java index a6923287af..dd9db63a90 100644 --- a/spring-web-modules/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/errors/User.java +++ b/spring-web-modules/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/errors/User.java @@ -1,13 +1,13 @@ package com.baeldung.thymeleaf.errors; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.validation.constraints.Min; -import javax.validation.constraints.NotEmpty; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Size; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.validation.constraints.Min; +import jakarta.validation.constraints.NotEmpty; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; @Entity public class User { diff --git a/spring-web-modules/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/errors/UserController.java b/spring-web-modules/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/errors/UserController.java index 92e67dc6a8..575bf5e24a 100644 --- a/spring-web-modules/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/errors/UserController.java +++ b/spring-web-modules/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/errors/UserController.java @@ -1,6 +1,6 @@ package com.baeldung.thymeleaf.errors; -import javax.validation.Valid; +import jakarta.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; diff --git a/spring-web-modules/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/option/Student.java b/spring-web-modules/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/option/Student.java index 3bb6576096..33163a00b7 100644 --- a/spring-web-modules/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/option/Student.java +++ b/spring-web-modules/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/option/Student.java @@ -2,8 +2,8 @@ package com.baeldung.thymeleaf.option; import java.io.Serializable; -import javax.validation.constraints.Min; -import javax.validation.constraints.NotNull; +import jakarta.validation.constraints.Min; +import jakarta.validation.constraints.NotNull; /** * diff --git a/testing-modules/selenium-2/src/test/java/com/baeldung/selenium/find/FindElementByAttributeManualTest.java b/testing-modules/selenium-2/src/test/java/com/baeldung/selenium/find/FindElementByAttributeManualTest.java new file mode 100644 index 0000000000..e3c8e6fd11 --- /dev/null +++ b/testing-modules/selenium-2/src/test/java/com/baeldung/selenium/find/FindElementByAttributeManualTest.java @@ -0,0 +1,77 @@ +package com.baeldung.selenium.find; + +import org.openqa.selenium.By; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.chrome.ChromeDriver; +import org.openqa.selenium.support.ui.ExpectedConditions; +import org.openqa.selenium.support.ui.WebDriverWait; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import java.time.Duration; + +public class FindElementByAttributeManualTest { + + private WebDriver driver; + private static final Duration TIMEOUT = Duration.ofSeconds(10); + + @BeforeClass + public void init() { + driver = new ChromeDriver(); + } + + @Test + public void whenSearchByAttributeName_thenFindAllElementsWithAttribute() { + driver.get("https://the-internet.herokuapp.com/drag_and_drop"); + + new WebDriverWait(driver, TIMEOUT) + .until(ExpectedConditions.numberOfElementsToBe(By.cssSelector("[draggable]"), 2)); + } + + @Test + public void whenSearchByAttributeExactValue_thenFindExactMatchElement() { + driver.get("https://the-internet.herokuapp.com/forgot_password"); + + new WebDriverWait(driver, TIMEOUT) + .until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("[type='submit']"))); + } + + @Test + public void whenSearchByAttributeStartValue_thenFindStartValueMatchElement() { + driver.get("https://the-internet.herokuapp.com/download"); + + new WebDriverWait(driver, TIMEOUT) + .until(ExpectedConditions.numberOfElementsToBeMoreThan(By.cssSelector("[href^='download/']"), 0)); + } + + @Test + public void whenSearchByAttributeEndValue_thenFindEndValueMatchElement() { + driver.get("https://the-internet.herokuapp.com/download"); + + new WebDriverWait(driver, TIMEOUT) + .until(ExpectedConditions.numberOfElementsToBeMoreThan(By.cssSelector("[href$='.pdf']"), 0)); + } + + @Test + public void whenSearchByAttributeContainsValue_thenFindContainsValueMatchElement() { + driver.get("https://the-internet.herokuapp.com/upload"); + + new WebDriverWait(driver, TIMEOUT) + .until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("[id*='le-up']"))); + } + + @Test + public void whenSearchByAttributeClassValue_thenFindClassValueMatchElement() { + driver.get("https://the-internet.herokuapp.com/upload"); + + new WebDriverWait(driver, TIMEOUT) + .until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("[class*='dz-clickable']"))); + } + + @AfterClass + public void tearDown() { + driver.quit(); + } + +}