Merge branch 'eugenp:master' into master

This commit is contained in:
sIvanovKonstantyn 2024-03-11 12:36:31 +01:00 committed by GitHub
commit db287faace
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
158 changed files with 2470 additions and 648 deletions

View File

@ -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)

View File

@ -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<Character> 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());
}
}

View File

@ -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);
}
}
}

View File

@ -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<TreeNode> 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);
}
}

View File

@ -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<Character> 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();
}
}

View File

@ -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);
}
}

View File

@ -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
}
}

View File

@ -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));
}
}

View File

@ -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;
}
}

View File

@ -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);
}
}

View File

@ -82,7 +82,7 @@
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${spring.version}</version>
<version>${spring-oxm.version}</version>
</dependency>
<!-- marshalling -->
<dependency>
@ -233,6 +233,7 @@
</profiles>
<properties>
<spring-oxm.version>6.1.4</spring-oxm.version>
<!-- util -->
<commons-codec.version>1.16.0</commons-codec.version>
<httpasyncclient.version>4.1.5</httpasyncclient.version>

View File

@ -20,6 +20,12 @@
<artifactId>s3</artifactId>
<version>${aws-java-sdk-v2.version}</version>
</dependency>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>url-connection-client</artifactId>
<version>${aws.java.sdk.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-io</groupId>
@ -37,9 +43,32 @@
<artifactId>commons-codec</artifactId>
<version>${commons-codec.version}</version>
</dependency>
<!-- adobe s3mock -->
<dependency>
<groupId>com.adobe.testing</groupId>
<artifactId>s3mock</artifactId>
<version>${com.adobe.testing.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.adobe.testing</groupId>
<artifactId>s3mock-testcontainers</artifactId>
<version>${com.adobe.testing.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${org.testcontainers.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<aws.java.sdk.version>2.20.52</aws.java.sdk.version>
<com.adobe.testing.version>3.3.0</com.adobe.testing.version>
<org.testcontainers.version>1.19.4</org.testcontainers.version>
<commons-codec.version>1.10.L001</commons-codec.version>
<jets3t.version>0.9.4.0014L</jets3t.version>
</properties>

View File

@ -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<byte[]> getObject(String bucketName, String objectKey) {
try {
GetObjectRequest getObjectRequest = GetObjectRequest.builder()
.bucket(bucketName)
.key(objectKey)
.build();
ResponseBytes<GetObjectResponse> 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;
}
}
}

View File

@ -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();
}
}

View File

@ -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<Integer, Integer> frequencyMap = new HashMap<>();
for (int num : nums) {
frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1);
}
int majorityThreshold = nums.length / 2;
for (Map.Entry<Integer, Integer> 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");
}
}
}

View File

@ -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);
}
}

View File

@ -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)

View File

@ -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);
}
}

View File

@ -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();
}
}

View File

@ -50,12 +50,6 @@
<version>5.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.liquibase</groupId>
<artifactId>liquibase-core</artifactId>
<version>${liquibase.core.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
@ -84,7 +78,6 @@
<apache.tika.version>2.9.1</apache.tika.version>
<commons-text.version>1.10.0</commons-text.version>
<icu4j.version>74.1</icu4j.version>
<liquibase.core.version>4.25.0</liquibase.core.version>
</properties>
</project>

View File

@ -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)

View File

@ -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();
}
}

View File

@ -5,12 +5,13 @@
<modelVersion>4.0.0</modelVersion>
<artifactId>docker-compose-2</artifactId>
<description>Demo project for Spring Boot and Docker - Module docker-compose-2</description>
<packaging>pom</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<artifactId>parent-boot-3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-2</relativePath>
<relativePath>../../parent-boot-3</relativePath>
</parent>
</project>

View File

@ -8,9 +8,9 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<artifactId>parent-boot-3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-2</relativePath>
<relativePath>../../parent-boot-3</relativePath>
</parent>
<dependencies>

View File

@ -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"]

View File

@ -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"]

View File

@ -7,9 +7,9 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<artifactId>parent-boot-3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-2</relativePath>
<relativePath>../../parent-boot-3</relativePath>
</parent>
<build>
@ -29,9 +29,4 @@
</plugins>
</build>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
</project>

View File

@ -74,7 +74,7 @@
</build>
<properties>
<io.grpc.version>1.40.1</io.grpc.version>
<io.grpc.version>1.62.2</io.grpc.version>
<protoc.version>3.17.2</protoc.version>
<os-maven-plugin.version>1.6.2</os-maven-plugin.version>
<protobuf-maven-plugin.version>0.6.1</protobuf-maven-plugin.version>

View File

@ -1150,7 +1150,7 @@
<javassist.version>3.23.1-GA</javassist.version>
<!-- The liquibase version should match the one managed by
https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-dependencies/${spring-boot.version} -->
<liquibase.version>3.6.3</liquibase.version>
<liquibase.version>4.9.1</liquibase.version>
<liquibase-hibernate5.version>3.6</liquibase-hibernate5.version>
<spring.version>5.1.5.RELEASE</spring.version>
<validation-api.version>2.0.1.Final</validation-api.version>

View File

@ -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 Gsons “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)

View File

@ -22,14 +22,14 @@ public class JsonNodeToArrayNodeConverterUnitTest {
int count = 0;
String json = "{\"objects\": [\"One\", \"Two\", \"Three\"]}";
final JsonNode arrayNode = new ObjectMapper().readTree(json).get("objects");
assertNotNull(arrayNode, "The 'objects' array should not be null");
assertTrue(arrayNode.isArray(), "The 'objects' should be an array");
if (arrayNode.isArray()) {
for (final JsonNode objNode : arrayNode) {
assertNotNull(objNode, "Array element should not be null");
count++;
}
}
assertNotNull(arrayNode, "The 'objects' array should not be null");
assertTrue(arrayNode.isArray(), "The 'objects' should be an array");
assertEquals(3, count, "The 'objects' array should have 3 elements");
}

View File

@ -98,6 +98,11 @@
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.jfree</groupId>
<artifactId>jfreechart</artifactId>
<version>${jfreechart.version}</version>
</dependency>
</dependencies>
<properties>
@ -117,6 +122,7 @@
<javafx.version>19</javafx.version>
<spoon-core.version>10.3.0</spoon-core.version>
<vavr.version>0.9.0</vavr.version>
<jfreechart.version>1.5.4</jfreechart.version>
</properties>
</project>
</project>

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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<String> 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);
}
}

View File

@ -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);
}
}

View File

@ -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)

View File

@ -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"]

View File

@ -8,9 +8,9 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<artifactId>parent-boot-3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-boot-2</relativePath>
<relativePath>../parent-boot-3</relativePath>
</parent>
<dependencies>

View File

@ -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;

View File

@ -9,9 +9,9 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<artifactId>parent-boot-3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-2</relativePath>
<relativePath>../../parent-boot-3</relativePath>
</parent>
<dependencyManagement>
@ -34,37 +34,41 @@
<!-- Core dependencies -->
<dependency>
<groupId>com.blazebit</groupId>
<artifactId>blaze-persistence-core-api</artifactId>
<artifactId>blaze-persistence-core-api-jakarta</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.blazebit</groupId>
<artifactId>blaze-persistence-core-impl</artifactId>
<artifactId>blaze-persistence-core-impl-jakarta</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.blazebit</groupId>
<artifactId>blaze-persistence-integration-hibernate-5.6</artifactId>
<artifactId>blaze-persistence-integration-hibernate-6.2</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Entity View dependencies -->
<dependency>
<groupId>com.blazebit</groupId>
<artifactId>blaze-persistence-entity-view-api</artifactId>
<artifactId>blaze-persistence-entity-view-api-jakarta</artifactId>
</dependency>
<dependency>
<groupId>com.blazebit</groupId>
<artifactId>blaze-persistence-entity-view-impl</artifactId>
<artifactId>blaze-persistence-entity-view-impl-jakarta</artifactId>
</dependency>
<dependency>
<groupId>com.blazebit</groupId>
<artifactId>blaze-persistence-entity-view-processor</artifactId>
<artifactId>blaze-persistence-entity-view-processor-jakarta</artifactId>
</dependency>
<!-- Spring integration dependencies -->
<dependency>
<groupId>com.blazebit</groupId>
<artifactId>blaze-persistence-integration-entity-view-spring</artifactId>
<artifactId>blaze-persistence-integration-entity-view-spring-6.0</artifactId>
</dependency>
<dependency>
<groupId>com.blazebit</groupId>
<artifactId>blaze-persistence-integration-spring-data-2.7</artifactId>
<artifactId>blaze-persistence-integration-spring-data-3.1</artifactId>
<scope>compile</scope>
</dependency>
<!-- Spring dependencies -->
<dependency>
@ -108,9 +112,9 @@
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<blaze-persistence.version>1.6.8</blaze-persistence.version>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<blaze-persistence.version>1.6.11</blaze-persistence.version>
</properties>
</project>

View File

@ -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"})

View File

@ -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;

View File

@ -1,6 +1,6 @@
package com.baeldung.model;
import javax.persistence.*;
import jakarta.persistence.*;
@Entity
public class Post {

View File

@ -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

View File

@ -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

View File

@ -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)

View File

@ -7,25 +7,13 @@
<artifactId>spring-boot-persistence-4</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-boot-persistence-4</name>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.junit</groupId>
<artifactId>junit-bom</artifactId>
<version>${junit-jupiter.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring.boot.dependencies}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-3</relativePath>
</parent>
<dependencies>
<dependency>
@ -79,13 +67,16 @@
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>com.baeldung.customfunc.CustomFunctionApplication</mainClass>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<spring.boot.dependencies>3.2.2</spring.boot.dependencies>
<junit-jupiter.version>5.9.3</junit-jupiter.version>
<junit-jupiter.version>5.10.2</junit-jupiter.version>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<db.util.version>1.0.7</db.util.version>

View File

@ -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();
}
}

View File

@ -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()

View File

@ -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

View File

@ -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;

View File

@ -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) {

View File

@ -11,9 +11,9 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<artifactId>parent-boot-3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-2</relativePath>
<relativePath>../../parent-boot-3</relativePath>
</parent>
<dependencies>
@ -63,7 +63,7 @@
<dependency>
<groupId>com.datastax.oss</groupId>
<artifactId>java-driver-mapper-runtime</artifactId>
<version>4.15.0</version>
<version>4.17.0</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
@ -99,10 +99,11 @@
</build>
<properties>
<org.springframework.data.version>3.4.15</org.springframework.data.version>
<testcontainers.version>1.19.0</testcontainers.version>
<system.stubs.version>1.1.0</system.stubs.version>
<org.springframework.data.version>4.1.9</org.springframework.data.version>
<testcontainers.version>1.19.5</testcontainers.version>
<system.stubs.version>2.1.5</system.stubs.version>
<junit.jupiter.version>5.9.3</junit.jupiter.version>
<start-class>org.baeldung.springcassandra.SpringCassandraApplication</start-class>
</properties>
</project>

View File

@ -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
spring.cassandra.keyspace-name=${CASSANDRA_KEYSPACE_NAME}
spring.cassandra.contact-points=${CASSANDRA_CONTACT_POINTS}
spring.cassandra.port=${CASSANDRA_PORT}
spring.cassandra.local-datacenter=datacenter1

View File

@ -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<Product> existingProducts = productRepository.findByProductIds(List.of(productId1, productId2));
List<Product> 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<Product> 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<Product> existingProducts = productRepository.findByProductIdAndNames(productId1,
List.of(product3.getProductName()));
Collections.singletonList(product3.getProductName())
);
assertEquals(0, existingProducts.size());
}
}

View File

@ -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());
}
}

View File

@ -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<Car> savedCars = carRepository.findAllById(List.of(carId));
List<Car> 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<Car> savedCars = carRepository.findAllById(List.of(carId));
List<Car> savedCars = carRepository.findAllById(Collections.singletonList(carId));
assertThat(savedCars.get(0).getModel()).isEqualTo("X-Trail");
}
@ -93,10 +94,8 @@ class CassandraNestedLiveTest {
carRepository.delete(existingCar);
List<Car> savedCars = carRepository.findAllById(List.of(carId));
assertThat(savedCars.isEmpty()).isTrue();
List<Car> savedCars = carRepository.findAllById(Collections.singletonList(carId));
assertThat(savedCars).isEmpty();
}
}
}

View File

@ -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();
}
}

View File

@ -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
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

View File

@ -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)

View File

@ -8,9 +8,9 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<artifactId>parent-boot-3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-2</relativePath>
<relativePath>../../parent-boot-3</relativePath>
</parent>
<dependencies>
@ -26,6 +26,11 @@
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
@ -33,4 +38,8 @@
</dependency>
</dependencies>
<properties>
<start-class>com.baeldung.Application</start-class>
</properties>
</project>

View File

@ -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 {

View File

@ -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 {

View File

@ -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 {

View File

@ -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 {

View File

@ -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);

View File

@ -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);

View File

@ -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);

View File

@ -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);

View File

@ -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]
);

View File

@ -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]
);

View File

@ -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]
);

View File

@ -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]
);

View File

@ -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]
);

View File

@ -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]
);

View File

@ -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]
);

View File

@ -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]
);

View File

@ -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]
);

View File

@ -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]
);

View File

@ -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
spring.jpa.hibernate.ddl-auto=create-drop

View File

@ -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
spring.jpa.hibernate.ddl-auto=create-drop

View File

@ -34,11 +34,13 @@
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${spring-oxm.version}</version>
</dependency>
</dependencies>
<properties>
<datasource-proxy.version>1.4.1</datasource-proxy.version>
<spring-oxm.version>6.1.4</spring-oxm.version>
</properties>
</project>

View File

@ -41,6 +41,7 @@
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${spring-oxm.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
@ -74,4 +75,8 @@
</plugins>
</build>
<properties>
<spring-oxm.version>6.1.4</spring-oxm.version>
</properties>
</project>

View File

@ -8,9 +8,9 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<artifactId>parent-boot-3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-2</relativePath>
<relativePath>../../parent-boot-3</relativePath>
</parent>
<dependencies>
@ -78,6 +78,7 @@
<mysema.maven.version>1.1.3</mysema.maven.version>
<projectreactor.version>3.5.4</projectreactor.version>
<embed.mongo.version>4.6.3</embed.mongo.version>
<start-class>com.baeldung.Main</start-class>
</properties>
</project>

View File

@ -1,11 +1,14 @@
package com.baeldung.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractReactiveMongoConfiguration;
import org.springframework.data.mongodb.repository.config.EnableReactiveMongoRepositories;
import com.mongodb.reactivestreams.client.MongoClient;
import com.mongodb.reactivestreams.client.MongoClients;
import org.springframework.transaction.ReactiveTransactionManager;
import org.springframework.transaction.reactive.TransactionalOperator;
@Configuration
@EnableReactiveMongoRepositories(basePackages = "com.baeldung.reactive.repository")
@ -20,4 +23,9 @@ public class MongoReactiveConfig extends AbstractReactiveMongoConfiguration {
protected String getDatabaseName() {
return "reactive";
}
@Bean
public TransactionalOperator transactionalOperator(ReactiveTransactionManager reactiveTransactionManager) {
return TransactionalOperator.create(reactiveTransactionManager);
}
}

View File

@ -6,11 +6,14 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.ReactiveMongoOperations;
import org.springframework.data.mongodb.core.ReactiveMongoTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.baeldung.config.MongoReactiveConfig;
import com.baeldung.model.User;
import org.springframework.transaction.reactive.TransactionalOperator;
import reactor.core.publisher.Mono;
/**
*
@ -25,6 +28,12 @@ public class MongoTransactionReactiveLiveTest {
@Autowired
private ReactiveMongoOperations reactiveOps;
@Autowired
private TransactionalOperator transactionalOperator;
@Autowired
private ReactiveMongoTemplate mongoTemplate;
@Before
public void testSetup() {
if (!reactiveOps.collectionExists(User.class)
@ -45,9 +54,11 @@ public class MongoTransactionReactiveLiveTest {
public void whenPerformTransaction_thenSuccess() {
User user1 = new User("Jane", 23);
User user2 = new User("John", 34);
reactiveOps.inTransaction()
.execute(action -> action.insert(user1)
.then(action.insert(user2)));
Mono<User> saveEntity1 = mongoTemplate.save(user1);
Mono<User> saveEntity2 = mongoTemplate.save(user2);
saveEntity1.then(saveEntity2).then().as(transactionalOperator::transactional);
}
}

17
pom.xml
View File

@ -539,12 +539,6 @@
</build>
<modules>
<module>parent-boot-1</module>
<module>parent-boot-2</module>
<module>parent-spring-4</module>
<module>parent-spring-5</module>
<module>parent-spring-6</module>
<module>spring-4</module>
<module>spring-cloud-modules</module>
@ -586,12 +580,6 @@
</build>
<modules>
<module>parent-boot-1</module>
<module>parent-boot-2</module>
<module>parent-spring-4</module>
<module>parent-spring-5</module>
<module>parent-spring-6</module>
<module>apache-spark</module>
<module>jhipster-modules</module>
<module>spring-cloud-modules/spring-cloud-azure</module>
@ -767,7 +755,7 @@
<module>lombok-modules</module>
<module>lucene</module>
<module>mapstruct</module>
<!--<module>maven-modules</module>--> <!-- failing after upgrading to jdk17-->
<!--<module>maven-modules</module>--> <!-- JAVA-27739 -->
<module>mesos-marathon</module>
<module>messaging-modules</module>
<module>metrics</module>
@ -1014,7 +1002,7 @@
<module>lombok-modules</module>
<module>lucene</module>
<module>mapstruct</module>
<!--<module>maven-modules</module>--> <!-- failing after upgrading to jdk17-->
<!--<module>maven-modules</module>--> <!-- JAVA-27739 -->
<module>mesos-marathon</module>
<module>messaging-modules</module>
<module>metrics</module>
@ -1139,7 +1127,6 @@
<module>parent-spring-5</module>
<module>parent-spring-6</module>
</modules>
</profile>
</profiles>

View File

@ -66,7 +66,7 @@
</build>
<properties>
<liquibase-core.version>4.25.0</liquibase-core.version>
<liquibase-core.version>4.26.0</liquibase-core.version>
</properties>
</project>

View File

@ -1,16 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-project</artifactId>
<version>0.1-SNAPSHOT</version>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../../parent-boot-2</relativePath>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.1.3</version>
</parent>
<dependencyManagement>
@ -35,14 +34,9 @@
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.experimental</groupId>
<artifactId>spring-native</artifactId>
<version>${spring-native.version}</version>
</dependency>
<dependency>
<groupId>com.github.jasync-sql</groupId>
<artifactId>jasync-r2dbc-mysql</artifactId>
<version>${jasync-r2dbc-mysql.version}</version>
<groupId>io.asyncer</groupId>
<artifactId>r2dbc-mysql</artifactId>
<version>${r2dbc-mysql.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
@ -84,197 +78,21 @@
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<classifier>exec</classifier>
<layers>
<enabled>true</enabled>
</layers>
<image>
<builder>paketobuildpacks/builder:tiny</builder>
<env>
<BP_NATIVE_IMAGE>false</BP_NATIVE_IMAGE>
<BPL_JFR_ENABLED>true</BPL_JFR_ENABLED>
</env>
</image>
</configuration>
<groupId>org.graalvm.buildtools</groupId>
<artifactId>native-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.12.1</version>
<configuration>
<source>${maven.compiler.release}</source>
<target>${maven.compiler.release}</target>
</configuration>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-release</id>
<name>Spring release</name>
<url>https://repo.spring.io/release</url>
</repository>
<repository>
<id>spring-milestone</id>
<name>Spring Milestone</name>
<url>https://repo.spring.io/milestone</url>
</repository>
<repository>
<id>spring-snapshot</id>
<name>Spring Snapshot</name>
<url>https://repo.spring.io/snapshot</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-milestone</id>
<name>Spring milestone</name>
<url>https://repo.spring.io/milestone</url>
</pluginRepository>
</pluginRepositories>
<profiles>
<profile>
<id>native</id>
<dependencies>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-launcher</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<layers>
<enabled>true</enabled>
</layers>
<image>
<builder>paketobuildpacks/builder:tiny</builder>
<env>
<BP_NATIVE_IMAGE>true</BP_NATIVE_IMAGE>
<BPL_JFR_ENABLED>true</BPL_JFR_ENABLED>
</env>
</image>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.experimental</groupId>
<artifactId>spring-aot-maven-plugin</artifactId>
<version>${spring-native.version}</version>
<executions>
<execution>
<id>test-generate</id>
<goals>
<goal>test-generate</goal>
</goals>
</execution>
<execution>
<id>generate</id>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>local-native</id>
<properties>
<repackage.classifier>exec</repackage.classifier>
<native-buildtools.version>${native-buildtools.version}</native-buildtools.version>
</properties>
<dependencies>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-launcher</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.experimental</groupId>
<artifactId>spring-aot-maven-plugin</artifactId>
<version>${spring-native.version}</version>
<executions>
<execution>
<id>test-generate</id>
<goals>
<goal>test-generate</goal>
</goals>
</execution>
<execution>
<id>generate</id>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.graalvm.buildtools</groupId>
<artifactId>native-maven-plugin</artifactId>
<version>${native-buildtools.version}</version>
<extensions>true</extensions>
<configuration>
<buildArgs combine.children="append">
<buildArgs>-H:+AllowVMInspection</buildArgs>
</buildArgs>
</configuration>
<executions>
<execution>
<id>build-native</id>
<goals>
<goal>build</goal>
</goals>
<phase>package</phase>
</execution>
<execution>
<id>test-native</id>
<goals>
<goal>test</goal>
</goals>
<phase>test</phase>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<argLine>-DspringAot=true
-agentlib:native-image-agent=access-filter-file=src/test/resources/access-filter.json,config-merge-dir=target/classes/META-INF/native-image
</argLine>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties>
<java.version>17</java.version>
<testcontainers-bom.version>1.17.2</testcontainers-bom.version>
<spring-native.version>0.12.1</spring-native.version>
<maven-surefire-plugin.version>3.1.0</maven-surefire-plugin.version>
<native-buildtools.version>0.9.11</native-buildtools.version>
<jasync-r2dbc-mysql.version>2.0.8</jasync-r2dbc-mysql.version>
<maven.compiler.release>17</maven.compiler.release>
<r2dbc-mysql.version>1.0.2</r2dbc-mysql.version>
</properties>
</project>

View File

@ -0,0 +1,2 @@
DROP TABLE IF EXISTS zipcode;
CREATE TABLE zipcode (zip VARCHAR(100) PRIMARY KEY, type VARCHAR(255) NULL, city VARCHAR(255) NULL, state VARCHAR(255) NULL, county VARCHAR(255) NULL, timezone VARCHAR(255) NULL);

View File

@ -11,16 +11,19 @@ services:
command: [ 'mysqld', '--character-set-server=utf8mb4', '--collation-server=utf8mb4_unicode_ci' ]
healthcheck:
test: mysqladmin ping -h 127.0.0.1 -u $$MYSQL_USER --password=$$MYSQL_PASSWORD
volumes:
- ./schema.sql:/docker-entrypoint-initdb.d/schema.sql
app:
image: docker.io/library/spring-project:0.1-SNAPSHOT
network_mode: "host"
environment:
DB_URL: r2dbc:mysql://localhost:3306/baeldung?useSSL=true&requireSSL=true
HOST_HOSTNAME: ${EXTERNAL_IP}
depends_on:
db:
condition: service_healthy
deploy:
resources:
limits:
cpus: '3.00'
image: docker.io/library/spring-project:0.1-SNAPSHOT
ports:
- '8080:8080'
environment:
DB_URL: r2dbc:mysql://db:3306/baeldung?useSSL=true&requireSSL=true
HOST_HOSTNAME: ${EXTERNAL_IP}
depends_on:
db:
condition: service_healthy
deploy:
resources:
limits:
cpus: '3.00'

View File

@ -4,36 +4,21 @@ import io.r2dbc.spi.ConnectionFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.data.r2dbc.repository.config.EnableR2dbcRepositories;
import org.springframework.r2dbc.connection.R2dbcTransactionManager;
import org.springframework.r2dbc.connection.init.ConnectionFactoryInitializer;
import org.springframework.r2dbc.connection.init.ResourceDatabasePopulator;
import org.springframework.transaction.ReactiveTransactionManager;
@SpringBootApplication
@EnableR2dbcRepositories
public class Startup {
public static void main(String[] args) {
SpringApplication.run(Startup.class, args);
}
public static void main(String[] args) {
SpringApplication.run(Startup.class, args);
}
@Bean
ConnectionFactoryInitializer initializer(ConnectionFactory connectionFactory) {
var initializer = new ConnectionFactoryInitializer();
initializer.setConnectionFactory(connectionFactory);
initializer.setDatabasePopulator(new ResourceDatabasePopulator(new ByteArrayResource((""
+ "DROP TABLE IF EXISTS zipcode;"
+ "CREATE TABLE zipcode (zip VARCHAR(100) PRIMARY KEY, type VARCHAR(255) NULL, city VARCHAR(255) NULL, state VARCHAR(255) NULL, county VARCHAR(255) NULL, timezone VARCHAR(255) NULL);")
.getBytes())));
return initializer;
}
@Bean ReactiveTransactionManager transactionManager(ConnectionFactory connectionFactory) {
return new R2dbcTransactionManager(connectionFactory);
}
@Bean
public ReactiveTransactionManager transactionManager(ConnectionFactory connectionFactory) {
return new R2dbcTransactionManager(connectionFactory);
}
}

View File

@ -26,6 +26,7 @@
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
<version>${spring-kafka.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>

View File

@ -26,6 +26,7 @@
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
<version>${spring-kafka.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>

View File

@ -10,9 +10,9 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<artifactId>parent-boot-3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-boot-2</relativePath>
<relativePath>../parent-boot-3</relativePath>
</parent>
<modules>
@ -21,4 +21,8 @@
<module>order-service</module>
</modules>
<properties>
<spring-kafka.version>3.1.2</spring-kafka.version>
</properties>
</project>

View File

@ -22,6 +22,7 @@
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
<version>${spring-kafka.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>

View File

@ -10,9 +10,9 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-spring-6</artifactId>
<artifactId>parent-boot-3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-spring-6</relativePath>
<relativePath>../parent-boot-3</relativePath>
</parent>
<dependencies>
@ -26,29 +26,9 @@
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit</groupId>
<artifactId>junit-bom</artifactId>
<version>${junit-jupiter.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<properties>
<spring-boot.version>3.1.3</spring-boot.version>
<org.slf4j.version>2.0.7</org.slf4j.version>
<logback.version>1.4.11</logback.version>
</properties>

View File

@ -10,11 +10,19 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<artifactId>parent-boot-3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-boot-2</relativePath>
<relativePath>../parent-boot-3</relativePath>
</parent>
<repositories>
<repository>
<id>alfresco</id>
<name>alfresco</name>
<url>https://artifacts.alfresco.com/nexus/content/repositories/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.activiti</groupId>
@ -59,7 +67,7 @@
</build>
<properties>
<activiti.version>7.1.0.M6</activiti.version>
<activiti.version>8.0.0</activiti.version>
</properties>
</project>

Some files were not shown because too many files have changed in this diff Show More