From a567d3187141f582d891442bb09ec935ec1dcfcd Mon Sep 17 00:00:00 2001 From: "@hangga" Date: Tue, 31 Oct 2023 18:15:47 +0700 Subject: [PATCH 001/228] add some methods --- .../com/baeldung/uuid/UUIDLongGenerator.java | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 core-java-modules/core-java-uuid/src/main/java/com/baeldung/uuid/UUIDLongGenerator.java diff --git a/core-java-modules/core-java-uuid/src/main/java/com/baeldung/uuid/UUIDLongGenerator.java b/core-java-modules/core-java-uuid/src/main/java/com/baeldung/uuid/UUIDLongGenerator.java new file mode 100644 index 0000000000..8ac71b1ce6 --- /dev/null +++ b/core-java-modules/core-java-uuid/src/main/java/com/baeldung/uuid/UUIDLongGenerator.java @@ -0,0 +1,58 @@ +package com.baeldung.uuid; + +import java.nio.ByteBuffer; +import java.util.UUID; + +public class UUIDLongGenerator { + public long getLeastSignificantBits(){ + return UUID.randomUUID().getLeastSignificantBits(); + } + + public long getMostSignificantBits(){ + return UUID.randomUUID().getMostSignificantBits(); + } + + public long gethashCode(){ + return UUID.randomUUID().toString().hashCode(); + } + + public long combineByteBuffer(){ + UUID uuid = UUID.randomUUID(); + ByteBuffer bb = ByteBuffer.wrap(new byte[16]); + bb.putLong(uuid.getMostSignificantBits()); + bb.putLong(uuid.getLeastSignificantBits()); + bb.rewind(); // Kembalikan posisi buffer ke awal + return bb.getLong(); + } + + public long combineBitwise(){ + UUID uniqueUUID; + uniqueUUID = UUID.randomUUID(); + return (uniqueUUID.getMostSignificantBits() << 32) | (uniqueUUID.getLeastSignificantBits() & 0xFFFFFFFFL); + } + + public long combineDirect(){ + UUID uniqueUUID = UUID.randomUUID(); + long mostSignificantBits = uniqueUUID.getMostSignificantBits(); + long leastSignificantBits = uniqueUUID.getLeastSignificantBits(); + return mostSignificantBits ^ (leastSignificantBits >> 1); + } + + public long combinePermutation(){ + UUID uuid = UUID.randomUUID(); + long mostSigBits = uuid.getMostSignificantBits(); + long leastSigBits = uuid.getLeastSignificantBits(); + byte[] uuidBytes = new byte[16]; + + for (int i = 0; i < 8; i++) { + uuidBytes[i] = (byte) (mostSigBits >>> (8 * (7 - i))); + uuidBytes[i + 8] = (byte) (leastSigBits >>> (8 * (7 - i))); + } + + long result = 0; + for (byte b : uuidBytes) { + result = (result << 8) | (b & 0xFF); + } + return result; + } +} From ece5cdeb6ee96e85f29d556ed080f7ce13e8a2f8 Mon Sep 17 00:00:00 2001 From: "@hangga" Date: Tue, 31 Oct 2023 18:17:54 +0700 Subject: [PATCH 002/228] add unit test --- .../uuid/UUIDLongGeneratorUnitTest.java | 63 +++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDLongGeneratorUnitTest.java diff --git a/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDLongGeneratorUnitTest.java b/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDLongGeneratorUnitTest.java new file mode 100644 index 0000000000..24add0a14a --- /dev/null +++ b/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDLongGeneratorUnitTest.java @@ -0,0 +1,63 @@ +package com.baeldung.uuid; + +import org.junit.jupiter.api.Test; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.text.DecimalFormat; +import java.util.HashSet; +import java.util.Set; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.IntStream; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class UUIDLongGeneratorUnitTest { + final static int n = 1000000; + UUIDLongGenerator uuidLongGenerator = new UUIDLongGenerator(); + + @Test + void whenForeachGenerateLongValue_thenCollisionsCheck() { + printTableHeader(); + for (Method method : uuidLongGenerator.getClass().getDeclaredMethods()) { + collisionAndNegativeCheck(method); + } + } + + private void printTableHeader() { + System.out.format("%-30s %-15s %-15s %-15s %-15s%n", "Approach", "collisions", "negatives", "collision", "negative"); + System.out.format("%-30s %-15s %-15s %-15s %-15s%n", "(method name)", "count", "count", "probability", "probability"); + System.out.println("--------------------------------------------------------------------------------------------"); + } + + private void printOutput(String method, int collisionsCount, int negativeCount, double collisionsProbability, double negativeProbability) { + DecimalFormat decimalFormat = new DecimalFormat("#.#####"); + System.out.format("%-30s %-15s %-15s %-15s %-15s%n", method, collisionsCount, negativeCount, decimalFormat.format(collisionsProbability), decimalFormat.format(negativeProbability)); + } + + private void collisionAndNegativeCheck(Method method) { + Set uniqueValues = new HashSet<>(); + AtomicInteger collisions = new AtomicInteger(0); + AtomicInteger negative = new AtomicInteger(0); + + IntStream.range(0, n).forEach(i -> { + try { + long uniqueValue = (long) method.invoke(uuidLongGenerator); + if (!uniqueValues.add(uniqueValue)) { + collisions.incrementAndGet(); + } + if (uniqueValue < 0) { + negative.incrementAndGet(); + } + } catch (IllegalAccessException | InvocationTargetException e) { + throw new RuntimeException(e); + } + }); + + double collisionsProbability = (double) collisions.get() / n; + double negativeProbability = (double) negative.get() / n; + printOutput(method.getName(), collisions.get(), negative.get(), collisionsProbability, negativeProbability); + + assertTrue(collisionsProbability <= 0.001); // threshold = 0.001 + } +} From 016579337010ab145058a3b25dc8b437f8c6f1b6 Mon Sep 17 00:00:00 2001 From: Hangga Aji Sayekti Date: Wed, 1 Nov 2023 10:36:43 +0700 Subject: [PATCH 003/228] Update core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDLongGeneratorUnitTest.java IntStream to loop Co-authored-by: Liam Williams --- .../uuid/UUIDLongGeneratorUnitTest.java | 22 ++++++++----------- 1 file changed, 9 insertions(+), 13 deletions(-) diff --git a/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDLongGeneratorUnitTest.java b/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDLongGeneratorUnitTest.java index 24add0a14a..6d2dff959c 100644 --- a/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDLongGeneratorUnitTest.java +++ b/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDLongGeneratorUnitTest.java @@ -37,20 +37,16 @@ public class UUIDLongGeneratorUnitTest { private void collisionAndNegativeCheck(Method method) { Set uniqueValues = new HashSet<>(); - AtomicInteger collisions = new AtomicInteger(0); - AtomicInteger negative = new AtomicInteger(0); + int collisions = 0; + int negative = 0; - IntStream.range(0, n).forEach(i -> { - try { - long uniqueValue = (long) method.invoke(uuidLongGenerator); - if (!uniqueValues.add(uniqueValue)) { - collisions.incrementAndGet(); - } - if (uniqueValue < 0) { - negative.incrementAndGet(); - } - } catch (IllegalAccessException | InvocationTargetException e) { - throw new RuntimeException(e); + for (int i = 0; i < n; i++) { + long uniqueValue = (long) method.invoke(uuidLongGenerator); + if (!uniqueValues.add(uniqueValue)) { + collisions++; + } + if (uniqueValue < 0) { + negative++; } }); From b55db89b5fb10e1fb4d678505f86fe54a82b355c Mon Sep 17 00:00:00 2001 From: "@hangga" Date: Wed, 1 Nov 2023 10:37:14 +0700 Subject: [PATCH 004/228] update --- ...or.java => UUIDPositiveLongGenerator.java} | 22 ++++--- .../uuid/UUIDLongGeneratorUnitTest.java | 63 ------------------- .../UUIDPositiveLongGeneratorUnitTest.java | 60 ++++++++++++++++++ 3 files changed, 73 insertions(+), 72 deletions(-) rename core-java-modules/core-java-uuid/src/main/java/com/baeldung/uuid/{UUIDLongGenerator.java => UUIDPositiveLongGenerator.java} (68%) delete mode 100644 core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDLongGeneratorUnitTest.java create mode 100644 core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java diff --git a/core-java-modules/core-java-uuid/src/main/java/com/baeldung/uuid/UUIDLongGenerator.java b/core-java-modules/core-java-uuid/src/main/java/com/baeldung/uuid/UUIDPositiveLongGenerator.java similarity index 68% rename from core-java-modules/core-java-uuid/src/main/java/com/baeldung/uuid/UUIDLongGenerator.java rename to core-java-modules/core-java-uuid/src/main/java/com/baeldung/uuid/UUIDPositiveLongGenerator.java index 8ac71b1ce6..bc8177837c 100644 --- a/core-java-modules/core-java-uuid/src/main/java/com/baeldung/uuid/UUIDLongGenerator.java +++ b/core-java-modules/core-java-uuid/src/main/java/com/baeldung/uuid/UUIDPositiveLongGenerator.java @@ -3,17 +3,21 @@ package com.baeldung.uuid; import java.nio.ByteBuffer; import java.util.UUID; -public class UUIDLongGenerator { +/** + * Methods are called by reflection in the unit test + */ +@SuppressWarnings("unused") +public class UUIDPositiveLongGenerator { public long getLeastSignificantBits(){ - return UUID.randomUUID().getLeastSignificantBits(); + return Math.abs(UUID.randomUUID().getLeastSignificantBits()); } public long getMostSignificantBits(){ - return UUID.randomUUID().getMostSignificantBits(); + return Math.abs(UUID.randomUUID().getMostSignificantBits()); } public long gethashCode(){ - return UUID.randomUUID().toString().hashCode(); + return Math.abs(UUID.randomUUID().toString().hashCode()); } public long combineByteBuffer(){ @@ -21,21 +25,21 @@ public class UUIDLongGenerator { ByteBuffer bb = ByteBuffer.wrap(new byte[16]); bb.putLong(uuid.getMostSignificantBits()); bb.putLong(uuid.getLeastSignificantBits()); - bb.rewind(); // Kembalikan posisi buffer ke awal - return bb.getLong(); + bb.rewind(); + return Math.abs(bb.getLong()); } public long combineBitwise(){ UUID uniqueUUID; uniqueUUID = UUID.randomUUID(); - return (uniqueUUID.getMostSignificantBits() << 32) | (uniqueUUID.getLeastSignificantBits() & 0xFFFFFFFFL); + return Math.abs((uniqueUUID.getMostSignificantBits() << 32) | (uniqueUUID.getLeastSignificantBits() & 0xFFFFFFFFL)); } public long combineDirect(){ UUID uniqueUUID = UUID.randomUUID(); long mostSignificantBits = uniqueUUID.getMostSignificantBits(); long leastSignificantBits = uniqueUUID.getLeastSignificantBits(); - return mostSignificantBits ^ (leastSignificantBits >> 1); + return Math.abs(mostSignificantBits ^ (leastSignificantBits >> 1)); } public long combinePermutation(){ @@ -53,6 +57,6 @@ public class UUIDLongGenerator { for (byte b : uuidBytes) { result = (result << 8) | (b & 0xFF); } - return result; + return Math.abs(result); } } diff --git a/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDLongGeneratorUnitTest.java b/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDLongGeneratorUnitTest.java deleted file mode 100644 index 24add0a14a..0000000000 --- a/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDLongGeneratorUnitTest.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.baeldung.uuid; - -import org.junit.jupiter.api.Test; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.text.DecimalFormat; -import java.util.HashSet; -import java.util.Set; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.stream.IntStream; - -import static org.junit.jupiter.api.Assertions.assertTrue; - -public class UUIDLongGeneratorUnitTest { - final static int n = 1000000; - UUIDLongGenerator uuidLongGenerator = new UUIDLongGenerator(); - - @Test - void whenForeachGenerateLongValue_thenCollisionsCheck() { - printTableHeader(); - for (Method method : uuidLongGenerator.getClass().getDeclaredMethods()) { - collisionAndNegativeCheck(method); - } - } - - private void printTableHeader() { - System.out.format("%-30s %-15s %-15s %-15s %-15s%n", "Approach", "collisions", "negatives", "collision", "negative"); - System.out.format("%-30s %-15s %-15s %-15s %-15s%n", "(method name)", "count", "count", "probability", "probability"); - System.out.println("--------------------------------------------------------------------------------------------"); - } - - private void printOutput(String method, int collisionsCount, int negativeCount, double collisionsProbability, double negativeProbability) { - DecimalFormat decimalFormat = new DecimalFormat("#.#####"); - System.out.format("%-30s %-15s %-15s %-15s %-15s%n", method, collisionsCount, negativeCount, decimalFormat.format(collisionsProbability), decimalFormat.format(negativeProbability)); - } - - private void collisionAndNegativeCheck(Method method) { - Set uniqueValues = new HashSet<>(); - AtomicInteger collisions = new AtomicInteger(0); - AtomicInteger negative = new AtomicInteger(0); - - IntStream.range(0, n).forEach(i -> { - try { - long uniqueValue = (long) method.invoke(uuidLongGenerator); - if (!uniqueValues.add(uniqueValue)) { - collisions.incrementAndGet(); - } - if (uniqueValue < 0) { - negative.incrementAndGet(); - } - } catch (IllegalAccessException | InvocationTargetException e) { - throw new RuntimeException(e); - } - }); - - double collisionsProbability = (double) collisions.get() / n; - double negativeProbability = (double) negative.get() / n; - printOutput(method.getName(), collisions.get(), negative.get(), collisionsProbability, negativeProbability); - - assertTrue(collisionsProbability <= 0.001); // threshold = 0.001 - } -} diff --git a/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java b/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java new file mode 100644 index 0000000000..2df49b20fd --- /dev/null +++ b/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java @@ -0,0 +1,60 @@ +package com.baeldung.uuid; + +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.text.DecimalFormat; +import java.util.HashSet; +import java.util.Set; + +import static org.assertj.core.api.Assertions.assertThat; + +public class UUIDPositiveLongGeneratorUnitTest { + private final static int n = 1000000; + private final UUIDPositiveLongGenerator uuidLongGenerator = new UUIDPositiveLongGenerator(); + private final Logger logger = LoggerFactory.getLogger(UUIDPositiveLongGeneratorUnitTest.class); + + @Test + void whenForeachGenerateLongValue_thenCollisionsCheck() throws InvocationTargetException, IllegalAccessException { + printTableHeader(); + for (Method method : uuidLongGenerator.getClass().getDeclaredMethods()) { + collisionAndNegativeCheck(method); + } + } + + + private void printTableHeader() { + logger.info(String.format("%-30s %-15s %-15s %-15s %-15s", "Approach", "collisions", "negatives", "collision", "negative")); + logger.info(String.format("%-30s %-15s %-15s %-15s %-15s", "(method name)", "count", "count", "probability", "probability")); + logger.info("--------------------------------------------------------------------------------------------"); + } + + private void printOutput(String method, int collisionsCount, int negativeCount, double collisionsProbability, double negativeProbability) { + DecimalFormat decimalFormat = new DecimalFormat("#.#####"); + //logger.info(String.format("%-30s %-15s %-15s %-15s %-15s", method, collisionsCount, negativeCount, decimalFormat.format(collisionsProbability), decimalFormat.format(negativeProbability))); + logger.info("%-30s{} %-15s{} %-15s{} %-15s{} %-15s{}", method, collisionsCount, negativeCount, decimalFormat.format(collisionsProbability), decimalFormat.format(negativeProbability)); + } + + + private void collisionAndNegativeCheck(Method method) throws InvocationTargetException, IllegalAccessException { + Set uniqueValues = new HashSet<>(); + int collisions = 0; + int negative = 0; + for (int i = 0; i < n; i++) { + long uniqueValue = (long) method.invoke(uuidLongGenerator); + if (!uniqueValues.add(uniqueValue)) { + collisions++; + } + if (uniqueValue < 0) { + negative++; + } + } + double collisionsProbability = (double) collisions / n; + double negativeProbability = (double) negative / n; + printOutput(method.getName(), collisions, negative, collisionsProbability, negativeProbability); + assertThat(collisionsProbability).isLessThan(0.001); + } +} From 579f35981e6910a3b9957f6a95300edcd5ce7015 Mon Sep 17 00:00:00 2001 From: "@hangga" Date: Wed, 1 Nov 2023 11:01:27 +0700 Subject: [PATCH 005/228] update, rename class --- .../uuid/UUIDLongGeneratorUnitTest.java | 60 ------------------- .../UUIDPositiveLongGeneratorUnitTest.java | 6 +- 2 files changed, 3 insertions(+), 63 deletions(-) delete mode 100644 core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDLongGeneratorUnitTest.java diff --git a/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDLongGeneratorUnitTest.java b/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDLongGeneratorUnitTest.java deleted file mode 100644 index fde726d259..0000000000 --- a/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDLongGeneratorUnitTest.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.baeldung.uuid; - -import org.apache.log4j.Logger; -import org.junit.jupiter.api.Test; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.text.DecimalFormat; -import java.util.HashSet; -import java.util.Set; - -import static org.assertj.core.api.Assertions.assertThat; - -public class UUIDLongGeneratorUnitTest { - private final static int n = 1000000; - private final static double COLLISION_THRESHOLD = 0.001; - private static final Logger logger = Logger.getLogger(UUIDLongGeneratorUnitTest.class); - private final UUIDPositiveLongGenerator uuidLongGenerator = new UUIDPositiveLongGenerator(); - - @Test - void whenForeachGenerateLongValue_thenCollisionsCheck() throws InvocationTargetException, IllegalAccessException { - printTableHeader(); - for (Method method : uuidLongGenerator.getClass().getDeclaredMethods()) { - collisionAndNegativeCheck(method); - } - } - - private void printTableHeader() { - logger.info(String.format("%-30s %-15s %-15s %-15s %-15s%n", "Approach", "collisions", "negatives", "collision", "negative")); - logger.info(String.format("%-30s %-15s %-15s %-15s %-15s%n", "(method name)", "count", "count", "probability", "probability")); - System.out.println("--------------------------------------------------------------------------------------------"); - } - - private void printOutput(String method, int collisionsCount, int negativeCount, double collisionsProbability, double negativeProbability) { - DecimalFormat decimalFormat = new DecimalFormat("#.#####"); - logger.info(String.format("%-30s %-15s %-15s %-15s %-15s", method, collisionsCount, negativeCount, decimalFormat.format(collisionsProbability), decimalFormat.format(negativeProbability))); - } - - private void collisionAndNegativeCheck(Method method) throws InvocationTargetException, IllegalAccessException { - Set uniqueValues = new HashSet<>(); - int collisions = 0; - int negative = 0; - - for (int i = 0; i < n; i++) { - long uniqueValue = (long) method.invoke(uuidLongGenerator); - if (!uniqueValues.add(uniqueValue)) { - collisions++; - } - if (uniqueValue < 0) { - negative++; - } - } - - double collisionsProbability = (double) collisions / n; - double negativeProbability = (double) negative / n; - printOutput(method.getName(), collisions, negative, collisionsProbability, negativeProbability); - - assertThat(collisionsProbability).isLessThan(COLLISION_THRESHOLD); - } -} diff --git a/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java b/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java index 2df49b20fd..c910a6eb16 100644 --- a/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java +++ b/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java @@ -14,6 +14,7 @@ import static org.assertj.core.api.Assertions.assertThat; public class UUIDPositiveLongGeneratorUnitTest { private final static int n = 1000000; + private final static double COLLISION_THRESHOLD = 0.001; private final UUIDPositiveLongGenerator uuidLongGenerator = new UUIDPositiveLongGenerator(); private final Logger logger = LoggerFactory.getLogger(UUIDPositiveLongGeneratorUnitTest.class); @@ -34,8 +35,7 @@ public class UUIDPositiveLongGeneratorUnitTest { private void printOutput(String method, int collisionsCount, int negativeCount, double collisionsProbability, double negativeProbability) { DecimalFormat decimalFormat = new DecimalFormat("#.#####"); - //logger.info(String.format("%-30s %-15s %-15s %-15s %-15s", method, collisionsCount, negativeCount, decimalFormat.format(collisionsProbability), decimalFormat.format(negativeProbability))); - logger.info("%-30s{} %-15s{} %-15s{} %-15s{} %-15s{}", method, collisionsCount, negativeCount, decimalFormat.format(collisionsProbability), decimalFormat.format(negativeProbability)); + logger.info(String.format("%-30s %-15s %-15s %-15s %-15s", method, collisionsCount, negativeCount, decimalFormat.format(collisionsProbability), decimalFormat.format(negativeProbability))); } @@ -55,6 +55,6 @@ public class UUIDPositiveLongGeneratorUnitTest { double collisionsProbability = (double) collisions / n; double negativeProbability = (double) negative / n; printOutput(method.getName(), collisions, negative, collisionsProbability, negativeProbability); - assertThat(collisionsProbability).isLessThan(0.001); + assertThat(collisionsProbability).isLessThan(COLLISION_THRESHOLD); } } From 10ddc978542620d06d1ab34cf0ce71e6c5b56210 Mon Sep 17 00:00:00 2001 From: "@hangga" Date: Wed, 1 Nov 2023 12:44:04 +0700 Subject: [PATCH 006/228] update --- .../com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java b/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java index c910a6eb16..5847ef44fb 100644 --- a/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java +++ b/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java @@ -22,7 +22,7 @@ public class UUIDPositiveLongGeneratorUnitTest { void whenForeachGenerateLongValue_thenCollisionsCheck() throws InvocationTargetException, IllegalAccessException { printTableHeader(); for (Method method : uuidLongGenerator.getClass().getDeclaredMethods()) { - collisionAndNegativeCheck(method); + collisionCheck(method); } } @@ -39,7 +39,7 @@ public class UUIDPositiveLongGeneratorUnitTest { } - private void collisionAndNegativeCheck(Method method) throws InvocationTargetException, IllegalAccessException { + private void collisionCheck(Method method) throws InvocationTargetException, IllegalAccessException { Set uniqueValues = new HashSet<>(); int collisions = 0; int negative = 0; From e0ca0be76af2e7b8a96a5d4e1c5165b1a0967b9d Mon Sep 17 00:00:00 2001 From: "@hangga" Date: Wed, 1 Nov 2023 16:27:09 +0700 Subject: [PATCH 007/228] positive --- .../uuid/UUIDPositiveLongGeneratorUnitTest.java | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) diff --git a/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java b/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java index 5847ef44fb..cd538af523 100644 --- a/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java +++ b/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java @@ -28,33 +28,27 @@ public class UUIDPositiveLongGeneratorUnitTest { private void printTableHeader() { - logger.info(String.format("%-30s %-15s %-15s %-15s %-15s", "Approach", "collisions", "negatives", "collision", "negative")); - logger.info(String.format("%-30s %-15s %-15s %-15s %-15s", "(method name)", "count", "count", "probability", "probability")); - logger.info("--------------------------------------------------------------------------------------------"); + logger.info(String.format("%-30s %-15s %-15s", "Approach(method name)", "collisions", "probability")); + logger.info("-----------------------------------------------------------------------"); } - private void printOutput(String method, int collisionsCount, int negativeCount, double collisionsProbability, double negativeProbability) { + private void printOutput(String method, int collisionsCount, double collisionsProbability) { DecimalFormat decimalFormat = new DecimalFormat("#.#####"); - logger.info(String.format("%-30s %-15s %-15s %-15s %-15s", method, collisionsCount, negativeCount, decimalFormat.format(collisionsProbability), decimalFormat.format(negativeProbability))); + logger.info(String.format("%-30s %-15s %-15s", method, collisionsCount, decimalFormat.format(collisionsProbability))); } private void collisionCheck(Method method) throws InvocationTargetException, IllegalAccessException { Set uniqueValues = new HashSet<>(); int collisions = 0; - int negative = 0; for (int i = 0; i < n; i++) { long uniqueValue = (long) method.invoke(uuidLongGenerator); if (!uniqueValues.add(uniqueValue)) { collisions++; } - if (uniqueValue < 0) { - negative++; - } } double collisionsProbability = (double) collisions / n; - double negativeProbability = (double) negative / n; - printOutput(method.getName(), collisions, negative, collisionsProbability, negativeProbability); + printOutput(method.getName(), collisions, collisionsProbability); assertThat(collisionsProbability).isLessThan(COLLISION_THRESHOLD); } } From 3286aab10c4b7a438e5b24c0a80bd368d7ad89e5 Mon Sep 17 00:00:00 2001 From: "@hangga" Date: Wed, 1 Nov 2023 18:24:02 +0700 Subject: [PATCH 008/228] bit 16 to 64 --- .../main/java/com/baeldung/uuid/UUIDPositiveLongGenerator.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-modules/core-java-uuid/src/main/java/com/baeldung/uuid/UUIDPositiveLongGenerator.java b/core-java-modules/core-java-uuid/src/main/java/com/baeldung/uuid/UUIDPositiveLongGenerator.java index bc8177837c..bb3e0223f3 100644 --- a/core-java-modules/core-java-uuid/src/main/java/com/baeldung/uuid/UUIDPositiveLongGenerator.java +++ b/core-java-modules/core-java-uuid/src/main/java/com/baeldung/uuid/UUIDPositiveLongGenerator.java @@ -22,7 +22,7 @@ public class UUIDPositiveLongGenerator { public long combineByteBuffer(){ UUID uuid = UUID.randomUUID(); - ByteBuffer bb = ByteBuffer.wrap(new byte[16]); + ByteBuffer bb = ByteBuffer.wrap(new byte[64]); bb.putLong(uuid.getMostSignificantBits()); bb.putLong(uuid.getLeastSignificantBits()); bb.rewind(); From 039753af1fc5b661ba0a15524814d9b650988264 Mon Sep 17 00:00:00 2001 From: "@hangga" Date: Wed, 1 Nov 2023 18:26:54 +0700 Subject: [PATCH 009/228] back to 16 --- .../main/java/com/baeldung/uuid/UUIDPositiveLongGenerator.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-modules/core-java-uuid/src/main/java/com/baeldung/uuid/UUIDPositiveLongGenerator.java b/core-java-modules/core-java-uuid/src/main/java/com/baeldung/uuid/UUIDPositiveLongGenerator.java index bb3e0223f3..bc8177837c 100644 --- a/core-java-modules/core-java-uuid/src/main/java/com/baeldung/uuid/UUIDPositiveLongGenerator.java +++ b/core-java-modules/core-java-uuid/src/main/java/com/baeldung/uuid/UUIDPositiveLongGenerator.java @@ -22,7 +22,7 @@ public class UUIDPositiveLongGenerator { public long combineByteBuffer(){ UUID uuid = UUID.randomUUID(); - ByteBuffer bb = ByteBuffer.wrap(new byte[64]); + ByteBuffer bb = ByteBuffer.wrap(new byte[16]); bb.putLong(uuid.getMostSignificantBits()); bb.putLong(uuid.getLeastSignificantBits()); bb.rewind(); From b946f580f48f8dd33a12f192544aea0176a6846b Mon Sep 17 00:00:00 2001 From: Hangga Aji Sayekti Date: Thu, 2 Nov 2023 09:39:17 +0700 Subject: [PATCH 010/228] Update core-java-modules/core-java-uuid/src/main/java/com/baeldung/uuid/UUIDPositiveLongGenerator.java Minor style issue: put a space between () and { in each of these methods Co-authored-by: Liam Williams --- .../main/java/com/baeldung/uuid/UUIDPositiveLongGenerator.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-modules/core-java-uuid/src/main/java/com/baeldung/uuid/UUIDPositiveLongGenerator.java b/core-java-modules/core-java-uuid/src/main/java/com/baeldung/uuid/UUIDPositiveLongGenerator.java index bc8177837c..b47fee1968 100644 --- a/core-java-modules/core-java-uuid/src/main/java/com/baeldung/uuid/UUIDPositiveLongGenerator.java +++ b/core-java-modules/core-java-uuid/src/main/java/com/baeldung/uuid/UUIDPositiveLongGenerator.java @@ -8,7 +8,7 @@ import java.util.UUID; */ @SuppressWarnings("unused") public class UUIDPositiveLongGenerator { - public long getLeastSignificantBits(){ + public long getLeastSignificantBits() { return Math.abs(UUID.randomUUID().getLeastSignificantBits()); } From 9fe75192ecea51637320985266159328aca02c4a Mon Sep 17 00:00:00 2001 From: Hangga Aji Sayekti Date: Thu, 2 Nov 2023 09:39:43 +0700 Subject: [PATCH 011/228] Update core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java assert that the value is positive Co-authored-by: Liam Williams --- .../com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java b/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java index cd538af523..854279446b 100644 --- a/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java +++ b/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java @@ -43,6 +43,7 @@ public class UUIDPositiveLongGeneratorUnitTest { int collisions = 0; for (int i = 0; i < n; i++) { long uniqueValue = (long) method.invoke(uuidLongGenerator); + assertThat(uniqueValue).isPositive(); if (!uniqueValues.add(uniqueValue)) { collisions++; } From f25f06795b20c4d8947efcbaf779a02bc25b32e3 Mon Sep 17 00:00:00 2001 From: Hangga Aji Sayekti Date: Thu, 2 Nov 2023 09:40:04 +0700 Subject: [PATCH 012/228] Update core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java Simplify the throws clause Co-authored-by: Liam Williams --- .../com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java b/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java index 854279446b..90ba11984f 100644 --- a/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java +++ b/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java @@ -38,7 +38,7 @@ public class UUIDPositiveLongGeneratorUnitTest { } - private void collisionCheck(Method method) throws InvocationTargetException, IllegalAccessException { + private void collisionCheck(Method method) throws Exception { Set uniqueValues = new HashSet<>(); int collisions = 0; for (int i = 0; i < n; i++) { From a5d0a15419cfcfeb3d0843e381188a58996bbe3e Mon Sep 17 00:00:00 2001 From: Hangga Aji Sayekti Date: Thu, 2 Nov 2023 09:40:20 +0700 Subject: [PATCH 013/228] Update core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java Simplify the throws clause Co-authored-by: Liam Williams --- .../com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java b/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java index 90ba11984f..ebb061216b 100644 --- a/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java +++ b/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java @@ -19,7 +19,7 @@ public class UUIDPositiveLongGeneratorUnitTest { private final Logger logger = LoggerFactory.getLogger(UUIDPositiveLongGeneratorUnitTest.class); @Test - void whenForeachGenerateLongValue_thenCollisionsCheck() throws InvocationTargetException, IllegalAccessException { + void whenForeachGenerateLongValue_thenCollisionsCheck() throws Exception { printTableHeader(); for (Method method : uuidLongGenerator.getClass().getDeclaredMethods()) { collisionCheck(method); From 8f1a091a431bcd423d59343327f8a9b8540fc9df Mon Sep 17 00:00:00 2001 From: "@hangga" Date: Thu, 2 Nov 2023 09:42:31 +0700 Subject: [PATCH 014/228] update : add space after () --- .../com/baeldung/uuid/UUIDPositiveLongGenerator.java | 12 ++++++------ .../uuid/UUIDPositiveLongGeneratorUnitTest.java | 7 +++---- 2 files changed, 9 insertions(+), 10 deletions(-) diff --git a/core-java-modules/core-java-uuid/src/main/java/com/baeldung/uuid/UUIDPositiveLongGenerator.java b/core-java-modules/core-java-uuid/src/main/java/com/baeldung/uuid/UUIDPositiveLongGenerator.java index b47fee1968..7b98c05684 100644 --- a/core-java-modules/core-java-uuid/src/main/java/com/baeldung/uuid/UUIDPositiveLongGenerator.java +++ b/core-java-modules/core-java-uuid/src/main/java/com/baeldung/uuid/UUIDPositiveLongGenerator.java @@ -12,15 +12,15 @@ public class UUIDPositiveLongGenerator { return Math.abs(UUID.randomUUID().getLeastSignificantBits()); } - public long getMostSignificantBits(){ + public long getMostSignificantBits() { return Math.abs(UUID.randomUUID().getMostSignificantBits()); } - public long gethashCode(){ + public long gethashCode() { return Math.abs(UUID.randomUUID().toString().hashCode()); } - public long combineByteBuffer(){ + public long combineByteBuffer() { UUID uuid = UUID.randomUUID(); ByteBuffer bb = ByteBuffer.wrap(new byte[16]); bb.putLong(uuid.getMostSignificantBits()); @@ -29,20 +29,20 @@ public class UUIDPositiveLongGenerator { return Math.abs(bb.getLong()); } - public long combineBitwise(){ + public long combineBitwise() { UUID uniqueUUID; uniqueUUID = UUID.randomUUID(); return Math.abs((uniqueUUID.getMostSignificantBits() << 32) | (uniqueUUID.getLeastSignificantBits() & 0xFFFFFFFFL)); } - public long combineDirect(){ + public long combineDirect() { UUID uniqueUUID = UUID.randomUUID(); long mostSignificantBits = uniqueUUID.getMostSignificantBits(); long leastSignificantBits = uniqueUUID.getLeastSignificantBits(); return Math.abs(mostSignificantBits ^ (leastSignificantBits >> 1)); } - public long combinePermutation(){ + public long combinePermutation() { UUID uuid = UUID.randomUUID(); long mostSigBits = uuid.getMostSignificantBits(); long leastSigBits = uuid.getLeastSignificantBits(); diff --git a/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java b/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java index ebb061216b..cc377254c4 100644 --- a/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java +++ b/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java @@ -4,7 +4,6 @@ import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.text.DecimalFormat; import java.util.HashSet; @@ -13,7 +12,7 @@ import java.util.Set; import static org.assertj.core.api.Assertions.assertThat; public class UUIDPositiveLongGeneratorUnitTest { - private final static int n = 1000000; + private final static int N = 1000000; private final static double COLLISION_THRESHOLD = 0.001; private final UUIDPositiveLongGenerator uuidLongGenerator = new UUIDPositiveLongGenerator(); private final Logger logger = LoggerFactory.getLogger(UUIDPositiveLongGeneratorUnitTest.class); @@ -41,14 +40,14 @@ public class UUIDPositiveLongGeneratorUnitTest { private void collisionCheck(Method method) throws Exception { Set uniqueValues = new HashSet<>(); int collisions = 0; - for (int i = 0; i < n; i++) { + for (int i = 0; i < N; i++) { long uniqueValue = (long) method.invoke(uuidLongGenerator); assertThat(uniqueValue).isPositive(); if (!uniqueValues.add(uniqueValue)) { collisions++; } } - double collisionsProbability = (double) collisions / n; + double collisionsProbability = (double) collisions / N; printOutput(method.getName(), collisions, collisionsProbability); assertThat(collisionsProbability).isLessThan(COLLISION_THRESHOLD); } From 69d17b634d22690d4a7981287126e9837a5c9e6d Mon Sep 17 00:00:00 2001 From: "@hangga" Date: Thu, 2 Nov 2023 11:25:19 +0700 Subject: [PATCH 015/228] N to NUMBER_OF_CHECKS --- .../baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java b/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java index cc377254c4..9db7a2f271 100644 --- a/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java +++ b/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java @@ -12,7 +12,7 @@ import java.util.Set; import static org.assertj.core.api.Assertions.assertThat; public class UUIDPositiveLongGeneratorUnitTest { - private final static int N = 1000000; + private final static int NUMBER_OF_CHECKS = 1000000; private final static double COLLISION_THRESHOLD = 0.001; private final UUIDPositiveLongGenerator uuidLongGenerator = new UUIDPositiveLongGenerator(); private final Logger logger = LoggerFactory.getLogger(UUIDPositiveLongGeneratorUnitTest.class); @@ -40,14 +40,14 @@ public class UUIDPositiveLongGeneratorUnitTest { private void collisionCheck(Method method) throws Exception { Set uniqueValues = new HashSet<>(); int collisions = 0; - for (int i = 0; i < N; i++) { + for (int i = 0; i < NUMBER_OF_CHECKS; i++) { long uniqueValue = (long) method.invoke(uuidLongGenerator); assertThat(uniqueValue).isPositive(); if (!uniqueValues.add(uniqueValue)) { collisions++; } } - double collisionsProbability = (double) collisions / N; + double collisionsProbability = (double) collisions / NUMBER_OF_CHECKS; printOutput(method.getName(), collisions, collisionsProbability); assertThat(collisionsProbability).isLessThan(COLLISION_THRESHOLD); } From 0f222559dc3a77c7e557682b7b410bc2305058e2 Mon Sep 17 00:00:00 2001 From: "@hangga" Date: Thu, 2 Nov 2023 14:16:43 +0700 Subject: [PATCH 016/228] simplyfying log --- .../core-java-uuid/src/test/resources/logback.xml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/core-java-modules/core-java-uuid/src/test/resources/logback.xml b/core-java-modules/core-java-uuid/src/test/resources/logback.xml index 56af2d397e..092215ceed 100644 --- a/core-java-modules/core-java-uuid/src/test/resources/logback.xml +++ b/core-java-modules/core-java-uuid/src/test/resources/logback.xml @@ -2,8 +2,8 @@ - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - + %d{HH:mm:ss} - %msg%n + @@ -12,6 +12,7 @@ + From 7cc4de47ef85d2002fd9a13db57e3c455fd9e2c6 Mon Sep 17 00:00:00 2001 From: "@hangga" Date: Thu, 2 Nov 2023 16:55:49 +0700 Subject: [PATCH 017/228] remove some space --- .../com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java b/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java index 9db7a2f271..fab07df2a0 100644 --- a/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java +++ b/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java @@ -25,7 +25,6 @@ public class UUIDPositiveLongGeneratorUnitTest { } } - private void printTableHeader() { logger.info(String.format("%-30s %-15s %-15s", "Approach(method name)", "collisions", "probability")); logger.info("-----------------------------------------------------------------------"); @@ -36,7 +35,6 @@ public class UUIDPositiveLongGeneratorUnitTest { logger.info(String.format("%-30s %-15s %-15s", method, collisionsCount, decimalFormat.format(collisionsProbability))); } - private void collisionCheck(Method method) throws Exception { Set uniqueValues = new HashSet<>(); int collisions = 0; From 18220b12af536a7c75860210c86ec9ea6ba0dc55 Mon Sep 17 00:00:00 2001 From: Hangga Aji Sayekti Date: Thu, 2 Nov 2023 21:05:07 +0700 Subject: [PATCH 018/228] Update core-java-modules/core-java-uuid/src/test/resources/logback.xml Ok.. Co-authored-by: Liam Williams --- core-java-modules/core-java-uuid/src/test/resources/logback.xml | 1 - 1 file changed, 1 deletion(-) diff --git a/core-java-modules/core-java-uuid/src/test/resources/logback.xml b/core-java-modules/core-java-uuid/src/test/resources/logback.xml index 092215ceed..8d3b4ff505 100644 --- a/core-java-modules/core-java-uuid/src/test/resources/logback.xml +++ b/core-java-modules/core-java-uuid/src/test/resources/logback.xml @@ -12,7 +12,6 @@ - From 39bc0b9eaad2eb6a2ee06d30a965496252ffeccf Mon Sep 17 00:00:00 2001 From: "@hangga" Date: Thu, 2 Nov 2023 21:08:06 +0700 Subject: [PATCH 019/228] logback --- .../core-java-uuid/src/test/resources/logback.xml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/core-java-modules/core-java-uuid/src/test/resources/logback.xml b/core-java-modules/core-java-uuid/src/test/resources/logback.xml index 8d3b4ff505..a076f8db47 100644 --- a/core-java-modules/core-java-uuid/src/test/resources/logback.xml +++ b/core-java-modules/core-java-uuid/src/test/resources/logback.xml @@ -2,8 +2,7 @@ - %d{HH:mm:ss} - %msg%n - + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n From 899700f27e7357cdb27653c0cb7be1a06323888d Mon Sep 17 00:00:00 2001 From: "@hangga" Date: Fri, 3 Nov 2023 15:45:12 +0700 Subject: [PATCH 020/228] [Update] add time field --- .../UUIDPositiveLongGeneratorUnitTest.java | 44 ++++++++++++++++--- 1 file changed, 37 insertions(+), 7 deletions(-) diff --git a/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java b/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java index fab07df2a0..62b059f0e5 100644 --- a/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java +++ b/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java @@ -6,8 +6,7 @@ import org.slf4j.LoggerFactory; import java.lang.reflect.Method; import java.text.DecimalFormat; -import java.util.HashSet; -import java.util.Set; +import java.util.*; import static org.assertj.core.api.Assertions.assertThat; @@ -17,8 +16,11 @@ public class UUIDPositiveLongGeneratorUnitTest { private final UUIDPositiveLongGenerator uuidLongGenerator = new UUIDPositiveLongGenerator(); private final Logger logger = LoggerFactory.getLogger(UUIDPositiveLongGeneratorUnitTest.class); + List times = new ArrayList<>(); + @Test void whenForeachGenerateLongValue_thenCollisionsCheck() throws Exception { + times.clear(); printTableHeader(); for (Method method : uuidLongGenerator.getClass().getDeclaredMethods()) { collisionCheck(method); @@ -26,16 +28,17 @@ public class UUIDPositiveLongGeneratorUnitTest { } private void printTableHeader() { - logger.info(String.format("%-30s %-15s %-15s", "Approach(method name)", "collisions", "probability")); - logger.info("-----------------------------------------------------------------------"); + logger.info(String.format("%-30s %15s %15s %15s", "Approach(method name)", "collisions", "probability","Time")); + logger.info("--------------------------------------------------------------------------------"); } - private void printOutput(String method, int collisionsCount, double collisionsProbability) { + private void printOutput(String method, int collisionsCount, double collisionsProbability, String time) { DecimalFormat decimalFormat = new DecimalFormat("#.#####"); - logger.info(String.format("%-30s %-15s %-15s", method, collisionsCount, decimalFormat.format(collisionsProbability))); + logger.info(String.format("%-30s %15s %15s %15s", method, collisionsCount, decimalFormat.format(collisionsProbability),time)); } private void collisionCheck(Method method) throws Exception { + long start = System.currentTimeMillis(); Set uniqueValues = new HashSet<>(); int collisions = 0; for (int i = 0; i < NUMBER_OF_CHECKS; i++) { @@ -46,7 +49,34 @@ public class UUIDPositiveLongGeneratorUnitTest { } } double collisionsProbability = (double) collisions / NUMBER_OF_CHECKS; - printOutput(method.getName(), collisions, collisionsProbability); + long end = System.currentTimeMillis(); + String time = convertMillisToTime(end - start); + printOutput(method.getName(), collisions, collisionsProbability, time); assertThat(collisionsProbability).isLessThan(COLLISION_THRESHOLD); + + } + + private String convertMillisToTime(long currentTimeMillis) { + + long totalMilliseconds = currentTimeMillis % 1000; + times.add(totalMilliseconds); + long totalSeconds = (currentTimeMillis / 1000) % 60; + long totalMinutes = (currentTimeMillis / 60000) % 60; + long hours = (currentTimeMillis / 3600000); + StringJoiner stringBuffer = new StringJoiner(""); + + if (hours > 0){ + stringBuffer.add(hours+"h "); + } + if (totalMinutes > 0){ + stringBuffer.add(totalMinutes+" m "); + } + if (totalSeconds > 0){ + stringBuffer.add(totalSeconds+" s "); + } + if (totalMilliseconds > 0){ + stringBuffer.add(totalMilliseconds+" ms"); + } + return stringBuffer.toString(); } } From b7bc968da2a4f81850e2c7415e22ed0ccc4c6cd7 Mon Sep 17 00:00:00 2001 From: Hangga Aji Sayekti Date: Fri, 3 Nov 2023 17:13:48 +0700 Subject: [PATCH 021/228] Update core-java-modules/core-java-uuid/src/main/java/com/baeldung/uuid/UUIDPositiveLongGenerator.java Oh yeah.. Co-authored-by: Liam Williams --- .../main/java/com/baeldung/uuid/UUIDPositiveLongGenerator.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-modules/core-java-uuid/src/main/java/com/baeldung/uuid/UUIDPositiveLongGenerator.java b/core-java-modules/core-java-uuid/src/main/java/com/baeldung/uuid/UUIDPositiveLongGenerator.java index 7b98c05684..13b32be856 100644 --- a/core-java-modules/core-java-uuid/src/main/java/com/baeldung/uuid/UUIDPositiveLongGenerator.java +++ b/core-java-modules/core-java-uuid/src/main/java/com/baeldung/uuid/UUIDPositiveLongGenerator.java @@ -16,7 +16,7 @@ public class UUIDPositiveLongGenerator { return Math.abs(UUID.randomUUID().getMostSignificantBits()); } - public long gethashCode() { + public long getHashCode() { return Math.abs(UUID.randomUUID().toString().hashCode()); } From 32940c41e4a6f0db1a29e2093f7c79ae83e7e2d9 Mon Sep 17 00:00:00 2001 From: "@hangga" Date: Sat, 4 Nov 2023 15:28:49 +0700 Subject: [PATCH 022/228] update time test --- .../com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java b/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java index 62b059f0e5..70b47df163 100644 --- a/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java +++ b/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java @@ -28,13 +28,13 @@ public class UUIDPositiveLongGeneratorUnitTest { } private void printTableHeader() { - logger.info(String.format("%-30s %15s %15s %15s", "Approach(method name)", "collisions", "probability","Time")); + logger.info(String.format("%-25s %15s %15s %15s", "Approach(method name)", "collisions", "probability","Testing Time")); logger.info("--------------------------------------------------------------------------------"); } private void printOutput(String method, int collisionsCount, double collisionsProbability, String time) { DecimalFormat decimalFormat = new DecimalFormat("#.#####"); - logger.info(String.format("%-30s %15s %15s %15s", method, collisionsCount, decimalFormat.format(collisionsProbability),time)); + logger.info(String.format("%-25s %15s %15s %15s", method, collisionsCount, decimalFormat.format(collisionsProbability),time)); } private void collisionCheck(Method method) throws Exception { From faa689f0181bd108de1d1a880d4e71bfcead45d4 Mon Sep 17 00:00:00 2001 From: Kai Yuan Date: Fri, 10 Nov 2023 08:15:20 +0100 Subject: [PATCH 023/228] [map-sort-by-value] sort map by value --- .../map/LinkedHashMapSortByValueUnitTest.java | 142 ++++++++++++++++++ 1 file changed, 142 insertions(+) create mode 100644 core-java-modules/core-java-collections-maps-7/src/test/java/com/baeldung/map/LinkedHashMapSortByValueUnitTest.java diff --git a/core-java-modules/core-java-collections-maps-7/src/test/java/com/baeldung/map/LinkedHashMapSortByValueUnitTest.java b/core-java-modules/core-java-collections-maps-7/src/test/java/com/baeldung/map/LinkedHashMapSortByValueUnitTest.java new file mode 100644 index 0000000000..2508c1416d --- /dev/null +++ b/core-java-modules/core-java-collections-maps-7/src/test/java/com/baeldung/map/LinkedHashMapSortByValueUnitTest.java @@ -0,0 +1,142 @@ +package com.baeldung.map; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +import org.junit.jupiter.api.Test; + +class Player { + private String name; + private Integer score = 0; + + public Player(String name, Integer score) { + this.name = name; + this.score = score; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof Player)) { + return false; + } + + Player player = (Player) o; + + if (!Objects.equals(name, player.name)) { + return false; + } + return Objects.equals(score, player.score); + } + + @Override + public int hashCode() { + int result = name != null ? name.hashCode() : 0; + result = 31 * result + (score != null ? score.hashCode() : 0); + return result; + } + + public String getName() { + return name; + } + + public int getScore() { + return score; + } +} + +public class LinkedHashMapSortByValueUnitTest { + private static LinkedHashMap MY_MAP = new LinkedHashMap(); + + static { + MY_MAP.put("key a", 4); + MY_MAP.put("key b", 1); + MY_MAP.put("key c", 3); + MY_MAP.put("key d", 2); + MY_MAP.put("key e", 5); + } + + private static LinkedHashMap EXPECTED_MY_MAP = new LinkedHashMap(); + + static { + EXPECTED_MY_MAP.put("key b", 1); + EXPECTED_MY_MAP.put("key d", 2); + EXPECTED_MY_MAP.put("key c", 3); + EXPECTED_MY_MAP.put("key a", 4); + EXPECTED_MY_MAP.put("key e", 5); + } + + private static final LinkedHashMap PLAYERS = new LinkedHashMap(); + + static { + PLAYERS.put("player a", new Player("Eric", 9)); + PLAYERS.put("player b", new Player("Kai", 7)); + PLAYERS.put("player c", new Player("Amanda", 20)); + PLAYERS.put("player d", new Player("Kevin", 4)); + } + + private static final LinkedHashMap EXPECTED_PLAYERS = new LinkedHashMap(); + + static { + EXPECTED_PLAYERS.put("player d", new Player("Kevin", 4)); + EXPECTED_PLAYERS.put("player b", new Player("Kai", 7)); + EXPECTED_PLAYERS.put("player a", new Player("Eric", 9)); + EXPECTED_PLAYERS.put("player c", new Player("Amanda", 20)); + } + + @Test + void whenUsingCollectionSort_thenGetExpectedResult() { + List> entryList = new ArrayList<>(MY_MAP.entrySet()); + Collections.sort(entryList, new Comparator>() { + @Override + public int compare(Map.Entry o1, Map.Entry o2) { + return o1.getValue() + .compareTo(o2.getValue()); + } + }); + + LinkedHashMap result = new LinkedHashMap<>(); + for (Map.Entry e : entryList) { + result.put(e.getKey(), e.getValue()); + } + assertEquals(EXPECTED_MY_MAP, result); + } + + @Test + void whenUsingEntrycomparingByValueAndFillAMap_thenGetExpectedResult() { + LinkedHashMap result = new LinkedHashMap<>(); + MY_MAP.entrySet() + .stream() + .sorted(Map.Entry.comparingByValue()) + .forEachOrdered(entry -> result.put(entry.getKey(), entry.getValue())); + assertEquals(EXPECTED_MY_MAP, result); + } + + @Test + void whenUsingEntrycomparingByValueAndCollect_thenGetExpectedResult() { + LinkedHashMap result = MY_MAP.entrySet() + .stream() + .sorted(Map.Entry.comparingByValue()) + .collect(LinkedHashMap::new, (map, entry) -> map.put(entry.getKey(), entry.getValue()), Map::putAll); + assertEquals(EXPECTED_MY_MAP, result); + } + + @Test + void whenUsingEntrycomparingByValueAndComparator_thenGetExpectedResult() { + LinkedHashMap result = PLAYERS.entrySet() + .stream() + .sorted(Map.Entry.comparingByValue(Comparator.comparing(Player::getScore))) + .collect(LinkedHashMap::new, (map, entry) -> map.put(entry.getKey(), entry.getValue()), Map::putAll); + assertEquals(EXPECTED_PLAYERS, result); + } + +} \ No newline at end of file From 88926bba03b587cfbe8a7145e4246973a9d4a4f9 Mon Sep 17 00:00:00 2001 From: Kai Yuan Date: Tue, 14 Nov 2023 22:21:47 +0100 Subject: [PATCH 024/228] [map-sort-by-value] add missing diamonds --- .../baeldung/map/LinkedHashMapSortByValueUnitTest.java | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/core-java-modules/core-java-collections-maps-7/src/test/java/com/baeldung/map/LinkedHashMapSortByValueUnitTest.java b/core-java-modules/core-java-collections-maps-7/src/test/java/com/baeldung/map/LinkedHashMapSortByValueUnitTest.java index 2508c1416d..8fd62cc20b 100644 --- a/core-java-modules/core-java-collections-maps-7/src/test/java/com/baeldung/map/LinkedHashMapSortByValueUnitTest.java +++ b/core-java-modules/core-java-collections-maps-7/src/test/java/com/baeldung/map/LinkedHashMapSortByValueUnitTest.java @@ -55,7 +55,7 @@ class Player { } public class LinkedHashMapSortByValueUnitTest { - private static LinkedHashMap MY_MAP = new LinkedHashMap(); + private static LinkedHashMap MY_MAP = new LinkedHashMap<>(); static { MY_MAP.put("key a", 4); @@ -65,7 +65,7 @@ public class LinkedHashMapSortByValueUnitTest { MY_MAP.put("key e", 5); } - private static LinkedHashMap EXPECTED_MY_MAP = new LinkedHashMap(); + private static LinkedHashMap EXPECTED_MY_MAP = new LinkedHashMap<>(); static { EXPECTED_MY_MAP.put("key b", 1); @@ -75,8 +75,7 @@ public class LinkedHashMapSortByValueUnitTest { EXPECTED_MY_MAP.put("key e", 5); } - private static final LinkedHashMap PLAYERS = new LinkedHashMap(); - + private static final LinkedHashMap PLAYERS = new LinkedHashMap<>(); static { PLAYERS.put("player a", new Player("Eric", 9)); PLAYERS.put("player b", new Player("Kai", 7)); @@ -84,7 +83,7 @@ public class LinkedHashMapSortByValueUnitTest { PLAYERS.put("player d", new Player("Kevin", 4)); } - private static final LinkedHashMap EXPECTED_PLAYERS = new LinkedHashMap(); + private static final LinkedHashMap EXPECTED_PLAYERS = new LinkedHashMap<>(); static { EXPECTED_PLAYERS.put("player d", new Player("Kevin", 4)); From 0c8b5bd210b716979891651a7af36582987c6183 Mon Sep 17 00:00:00 2001 From: "@hangga" Date: Sat, 18 Nov 2023 06:09:14 +0700 Subject: [PATCH 025/228] retry with colision --- .../baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java b/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java index 70b47df163..27ac4fe51e 100644 --- a/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java +++ b/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java @@ -56,6 +56,13 @@ public class UUIDPositiveLongGeneratorUnitTest { } + private boolean isUnique(long value) { + // Implementasikan logika pengecekan keunikan, misalnya, dengan memeriksa dalam database + // Mengembalikan true jika nilai unik, false jika ada tumbukan + return true; // Implementasikan sesuai kebutuhan aplikasi Anda + } + + private String convertMillisToTime(long currentTimeMillis) { long totalMilliseconds = currentTimeMillis % 1000; From f90651c5f9619f156c5d04b0018a815a64d5b04e Mon Sep 17 00:00:00 2001 From: parthiv39731 <70740707+parthiv39731@users.noreply.github.com> Date: Sat, 18 Nov 2023 12:34:13 +0530 Subject: [PATCH 026/228] BAEL-7200 Modify Request Body Before Reaching Controller in Spring Boot --- spring-boot-modules/spring-boot-mvc-5/pom.xml | 12 +++ .../modifyrequest/ModifyRequestApp.java | 11 +++ .../modifyrequest/aop/EscapeHtmlAspect.java | 74 +++++++++++++++++++ .../config/WebMvcConfiguration.java | 25 +++++++ .../controller/UserController.java | 23 ++++++ .../filter/EscapeHtmlFilter.java | 27 +++++++ .../EscapeHtmlRequestInterceptor.java | 19 +++++ .../EscapeHtmlRequestWrapper.java | 68 +++++++++++++++++ .../modifyrequest/filter-sequence-design.puml | 31 ++++++++ .../interceptor-sequence-design.puml | 33 +++++++++ .../EscapeHtmlAspectIntegrationTest.java | 52 +++++++++++++ .../EscapeHtmlFilterIntegrationTest.java | 51 +++++++++++++ .../EscapeHtmlInterceptorIntegrationTest.java | 46 ++++++++++++ 13 files changed, 472 insertions(+) create mode 100644 spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/ModifyRequestApp.java create mode 100644 spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/aop/EscapeHtmlAspect.java create mode 100644 spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/config/WebMvcConfiguration.java create mode 100644 spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/controller/UserController.java create mode 100644 spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/filter/EscapeHtmlFilter.java create mode 100644 spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/interceptor/EscapeHtmlRequestInterceptor.java create mode 100644 spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/requestwrapper/EscapeHtmlRequestWrapper.java create mode 100644 spring-boot-modules/spring-boot-mvc-5/src/main/resources/modifyrequest/filter-sequence-design.puml create mode 100644 spring-boot-modules/spring-boot-mvc-5/src/main/resources/modifyrequest/interceptor-sequence-design.puml create mode 100644 spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/modifyrequest/EscapeHtmlAspectIntegrationTest.java create mode 100644 spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/modifyrequest/EscapeHtmlFilterIntegrationTest.java create mode 100644 spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/modifyrequest/EscapeHtmlInterceptorIntegrationTest.java diff --git a/spring-boot-modules/spring-boot-mvc-5/pom.xml b/spring-boot-modules/spring-boot-mvc-5/pom.xml index a516cab049..10a58a6a59 100644 --- a/spring-boot-modules/spring-boot-mvc-5/pom.xml +++ b/spring-boot-modules/spring-boot-mvc-5/pom.xml @@ -49,6 +49,10 @@ commons-configuration ${commons-configuration.version} + + org.springframework.boot + spring-boot-starter-aop + @@ -61,6 +65,14 @@ JAR + + org.apache.maven.plugins + maven-compiler-plugin + + 9 + 9 + + diff --git a/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/ModifyRequestApp.java b/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/ModifyRequestApp.java new file mode 100644 index 0000000000..7dd937d5b8 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/ModifyRequestApp.java @@ -0,0 +1,11 @@ +package com.baeldung.modifyrequest; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication(scanBasePackages = "com.baeldung.modifyrequest") +public class ModifyRequestApp { + public static void main(String[] args) { + SpringApplication.run(ModifyRequestApp.class, args); + } +} diff --git a/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/aop/EscapeHtmlAspect.java b/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/aop/EscapeHtmlAspect.java new file mode 100644 index 0000000000..fb31abe11b --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/aop/EscapeHtmlAspect.java @@ -0,0 +1,74 @@ +package com.baeldung.modifyrequest.aop; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.annotation.Profile; +import org.springframework.core.MethodParameter; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpInputMessage; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice; + +import java.io.*; +import java.lang.reflect.Type; +import java.nio.charset.StandardCharsets; + +@RestControllerAdvice +@Profile("aspectExample") +public class EscapeHtmlAspect implements RequestBodyAdvice { + private static final Logger logger = LoggerFactory.getLogger(EscapeHtmlAspect.class); + + @Override + public boolean supports(MethodParameter methodParameter, Type targetType, Class> converterType) { + //Apply this to all Controllers + return true; + } + + @Override + public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class> converterType) throws IOException { + logger.info("beforeBodyRead called"); + InputStream inputStream = inputMessage.getBody(); + return new HttpInputMessage() { + @Override + public InputStream getBody() throws IOException { + return new ByteArrayInputStream(escapeHtml(inputStream).getBytes(StandardCharsets.UTF_8)); + } + + @Override + public HttpHeaders getHeaders() { + return inputMessage.getHeaders(); + } + }; + } + + @Override + public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class> converterType) { + // Return the modified object after reading the body + return body; + } + + @Override + public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class> converterType) { + //return the original body + return body; + } + + private String escapeHtml(InputStream inputStream) throws IOException { + StringBuilder stringBuilder = new StringBuilder(); + BufferedReader bufferedReader = null; + try (inputStream) { + bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); + char[] charBuffer = new char[128]; + int bytesRead = -1; + while ((bytesRead = bufferedReader.read(charBuffer)) > 0) { + stringBuilder.append(charBuffer, 0, bytesRead); + } + } + String input = stringBuilder.toString(); + // Escape HTML characters + return input.replaceAll("&", "&") + .replaceAll("<", "<") + .replaceAll(">", ">"); + } +} diff --git a/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/config/WebMvcConfiguration.java b/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/config/WebMvcConfiguration.java new file mode 100644 index 0000000000..bd76fd5e55 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/config/WebMvcConfiguration.java @@ -0,0 +1,25 @@ +package com.baeldung.modifyrequest.config; + +import com.baeldung.modifyrequest.interceptor.EscapeHtmlRequestInterceptor; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +@Profile("interceptorExample") +public class WebMvcConfiguration implements WebMvcConfigurer { + private static final Logger logger = LoggerFactory.getLogger(WebMvcConfiguration.class); + + @Override + public void addInterceptors(InterceptorRegistry registry) { + logger.info("addInterceptors() called"); + registry.addInterceptor(new EscapeHtmlRequestInterceptor()) + .addPathPatterns("/save"); + + WebMvcConfigurer.super.addInterceptors(registry); + } +} + diff --git a/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/controller/UserController.java b/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/controller/UserController.java new file mode 100644 index 0000000000..26450dd70d --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/controller/UserController.java @@ -0,0 +1,23 @@ +package com.baeldung.modifyrequest.controller; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/") +public class UserController { + Logger logger = LoggerFactory.getLogger(UserController.class); + + @PostMapping(value = "save") + public ResponseEntity saveUser(@RequestBody String user) { + logger.info("save user info into database"); + ResponseEntity responseEntity = new ResponseEntity<>(user, HttpStatus.CREATED); + return responseEntity; + } +} diff --git a/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/filter/EscapeHtmlFilter.java b/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/filter/EscapeHtmlFilter.java new file mode 100644 index 0000000000..45cad3be1c --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/filter/EscapeHtmlFilter.java @@ -0,0 +1,27 @@ +package com.baeldung.modifyrequest.filter; + +import com.baeldung.modifyrequest.requestwrapper.EscapeHtmlRequestWrapper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.annotation.Profile; +import org.springframework.core.annotation.Order; +import org.springframework.stereotype.Component; + +import javax.servlet.*; +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; + +@Component +@Order(1) +@Profile("filterExample") +public class EscapeHtmlFilter implements Filter { + Logger logger = LoggerFactory.getLogger(EscapeHtmlFilter.class); + + @Override + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) + throws IOException, ServletException { + logger.info("Modify the request"); + + filterChain.doFilter(new EscapeHtmlRequestWrapper((HttpServletRequest) servletRequest), servletResponse); + } +} diff --git a/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/interceptor/EscapeHtmlRequestInterceptor.java b/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/interceptor/EscapeHtmlRequestInterceptor.java new file mode 100644 index 0000000000..1ad39605e5 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/interceptor/EscapeHtmlRequestInterceptor.java @@ -0,0 +1,19 @@ +package com.baeldung.modifyrequest.interceptor; + +import com.baeldung.modifyrequest.requestwrapper.EscapeHtmlRequestWrapper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.web.servlet.HandlerInterceptor; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +public class EscapeHtmlRequestInterceptor implements HandlerInterceptor { + private static final Logger logger = LoggerFactory.getLogger(EscapeHtmlRequestInterceptor.class); + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + EscapeHtmlRequestWrapper escapeHtmlRequestWrapper = new EscapeHtmlRequestWrapper(request); + return true; + } +} diff --git a/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/requestwrapper/EscapeHtmlRequestWrapper.java b/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/requestwrapper/EscapeHtmlRequestWrapper.java new file mode 100644 index 0000000000..65c758d956 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/requestwrapper/EscapeHtmlRequestWrapper.java @@ -0,0 +1,68 @@ +package com.baeldung.modifyrequest.requestwrapper; + +import javax.servlet.ReadListener; +import javax.servlet.ServletInputStream; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletRequestWrapper; +import java.io.*; + +public class EscapeHtmlRequestWrapper extends HttpServletRequestWrapper { + private String body = null; + public EscapeHtmlRequestWrapper(HttpServletRequest request) throws IOException { + super(request); + this.body = this.escapeHtml(request); + } + + private String escapeHtml(HttpServletRequest request) throws IOException { + StringBuilder stringBuilder = new StringBuilder(); + BufferedReader bufferedReader = null; + try (InputStream inputStream = request.getInputStream()) { + bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); + char[] charBuffer = new char[128]; + int bytesRead = -1; + while ((bytesRead = bufferedReader.read(charBuffer)) > 0) { + stringBuilder.append(charBuffer, 0, bytesRead); + } + } + String input = stringBuilder.toString(); + // Escape HTML characters + return input.replaceAll("&", "&") + .replaceAll("<", "<") + .replaceAll(">", ">") + //.replaceAll("\"", """) + .replaceAll("'", "'"); + } + + @Override + public ServletInputStream getInputStream() { + final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes()); + ServletInputStream servletInputStream = new ServletInputStream() { + + @Override + public int read() { + return byteArrayInputStream.read(); + } + + @Override + public boolean isFinished() { + return false; + } + + @Override + public boolean isReady() { + return false; + } + + @Override + public void setReadListener(ReadListener listener) { + + } + }; + return servletInputStream; + } + + @Override + public BufferedReader getReader() throws IOException { + return new BufferedReader(new InputStreamReader(this.getInputStream())); + } +} diff --git a/spring-boot-modules/spring-boot-mvc-5/src/main/resources/modifyrequest/filter-sequence-design.puml b/spring-boot-modules/spring-boot-mvc-5/src/main/resources/modifyrequest/filter-sequence-design.puml new file mode 100644 index 0000000000..41689ac723 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-5/src/main/resources/modifyrequest/filter-sequence-design.puml @@ -0,0 +1,31 @@ +@startuml +'https://plantuml.com/sequence-diagram +skinparam sequenceMessageAlign direction +skinparam handwritten true +skinparam sequence { +ParticipantBackgroundColor beige +ParticipantPadding 50 +} + +autonumber + +Browser -[#63b175]> Filter: HTTP Request +activate Browser +activate Filter +Filter -[#63b175]> Filter: doFilter() +Filter -[#63b175]> DispatcherServlet: HTTP Request +activate DispatcherServlet + + +DispatcherServlet -[#63b175]> Controller: HTTP Request +activate Controller +Controller --[#63b175]> DispatcherServlet: HTTP Response +deactivate Controller + +DispatcherServlet --[#63b175]> Filter: HTTP Response +deactivate DispatcherServlet + +Filter --[#63b175]> Browser: HTTP Response +deactivate Filter +deactivate Browser +@enduml \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc-5/src/main/resources/modifyrequest/interceptor-sequence-design.puml b/spring-boot-modules/spring-boot-mvc-5/src/main/resources/modifyrequest/interceptor-sequence-design.puml new file mode 100644 index 0000000000..429b8182ca --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-5/src/main/resources/modifyrequest/interceptor-sequence-design.puml @@ -0,0 +1,33 @@ +@startuml +'https://plantuml.com/sequence-diagram +skinparam sequenceMessageAlign direction +skinparam handwritten true +skinparam sequence { +ParticipantBackgroundColor beige +ParticipantPadding 50 +} + +autonumber + +Browser -[#63b175]> Filter: Http Request +activate Browser +activate Filter +Filter -[#63b175]> DispatcherServlet: Http Request +activate DispatcherServlet + +DispatcherServlet -[#63b175]> Interceptor: Http Request +activate Interceptor +Interceptor -[#63b175]> Interceptor: preHandle() +Interceptor -[#63b175]> Controller: Http Request +activate Controller +Controller --[#63b175]> Interceptor: Http Response +deactivate Controller +Interceptor --[#63b175]> DispatcherServlet: Http Response +deactivate Interceptor +DispatcherServlet --[#63b175]> Filter: Http Response +deactivate DispatcherServlet + +Filter --[#63b175]> Browser: Http Response +deactivate Filter +deactivate Browser +@enduml \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/modifyrequest/EscapeHtmlAspectIntegrationTest.java b/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/modifyrequest/EscapeHtmlAspectIntegrationTest.java new file mode 100644 index 0000000000..665733c61b --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/modifyrequest/EscapeHtmlAspectIntegrationTest.java @@ -0,0 +1,52 @@ +package com.baeldung.modifyrequest; + +import com.baeldung.modifyrequest.controller.UserController; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.http.MediaType; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; + +import java.net.URI; +import java.util.Map; + +@ExtendWith(SpringExtension.class) +@AutoConfigureMockMvc +@WebMvcTest(UserController.class) +@ActiveProfiles("aspectExample") +public class EscapeHtmlAspectIntegrationTest { + Logger logger = LoggerFactory.getLogger(EscapeHtmlAspectIntegrationTest.class); + + @Autowired + private MockMvc mockMvc; + @Test + void givenAspect_whenEscapeHtmlAspect_thenEscapeHtml() throws Exception { + + Map requestBody = Map.of( + "name", "James Cameron", + "email", "james@gmail.com" + ); + + Map expectedResponseBody = Map.of( + "name", "James Cameron", + "email", "<script>alert()</script>james@gmail.com" + ); + + ObjectMapper objectMapper = new ObjectMapper(); + + mockMvc.perform(MockMvcRequestBuilders.post(URI.create("/save")) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(requestBody))) + .andExpect(MockMvcResultMatchers.status().isCreated()) + .andExpect(MockMvcResultMatchers.content().json(objectMapper.writeValueAsString(expectedResponseBody))); + } +} diff --git a/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/modifyrequest/EscapeHtmlFilterIntegrationTest.java b/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/modifyrequest/EscapeHtmlFilterIntegrationTest.java new file mode 100644 index 0000000000..35254eb151 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/modifyrequest/EscapeHtmlFilterIntegrationTest.java @@ -0,0 +1,51 @@ +package com.baeldung.modifyrequest; + +import com.baeldung.modifyrequest.controller.UserController; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.http.MediaType; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; + +import java.net.URI; +import java.util.Map; + +@ExtendWith(SpringExtension.class) +@AutoConfigureMockMvc +@WebMvcTest(UserController.class) +@ActiveProfiles("filterExample") +public class EscapeHtmlFilterIntegrationTest { + Logger logger = LoggerFactory.getLogger(EscapeHtmlFilterIntegrationTest.class); + + @Autowired + private MockMvc mockMvc; + @Test + void givenFilter_whenEscapeHtmlFilter_thenEscapeHtml() throws Exception { + Map requestBody = Map.of( + "name", "James Cameron", + "email", "james@gmail.com" + ); + + Map expectedResponseBody = Map.of( + "name", "James Cameron", + "email", "<script>alert()</script>james@gmail.com" + ); + + ObjectMapper objectMapper = new ObjectMapper(); + + mockMvc.perform(MockMvcRequestBuilders.post(URI.create("/save")) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(requestBody))) + .andExpect(MockMvcResultMatchers.status().isCreated()) + .andExpect(MockMvcResultMatchers.content().json(objectMapper.writeValueAsString(expectedResponseBody))); + } +} diff --git a/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/modifyrequest/EscapeHtmlInterceptorIntegrationTest.java b/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/modifyrequest/EscapeHtmlInterceptorIntegrationTest.java new file mode 100644 index 0000000000..002481de4f --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/modifyrequest/EscapeHtmlInterceptorIntegrationTest.java @@ -0,0 +1,46 @@ +package com.baeldung.modifyrequest; + +import com.baeldung.modifyrequest.controller.UserController; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.http.MediaType; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; + +import java.net.URI; +import java.util.Map; + + +@ExtendWith(SpringExtension.class) +@AutoConfigureMockMvc +@WebMvcTest(UserController.class) +@ActiveProfiles("interceptorExample") +public class EscapeHtmlInterceptorIntegrationTest { + Logger logger = LoggerFactory.getLogger(EscapeHtmlInterceptorIntegrationTest.class); + + @Autowired + private MockMvc mockMvc; + + @Test + void givenInterceptor_whenEscapeHtmlInterceptor_thenEscapeHtml() throws Exception { + Map requestBody = Map.of( + "name", "James Cameron", + "email", "james@gmail.com" + ); + + ObjectMapper objectMapper = new ObjectMapper(); + mockMvc.perform(MockMvcRequestBuilders.post(URI.create("/save")) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(requestBody))) + .andExpect(MockMvcResultMatchers.status().is4xxClientError()); + } +} From 213fb362a0f94947f85e85eb9dafd4637f1daf1c Mon Sep 17 00:00:00 2001 From: "@hangga" Date: Sat, 18 Nov 2023 14:17:19 +0700 Subject: [PATCH 027/228] simplyfiying test --- .../UUIDPositiveLongGeneratorUnitTest.java | 77 +++---------------- 1 file changed, 10 insertions(+), 67 deletions(-) diff --git a/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java b/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java index 27ac4fe51e..756bee94e6 100644 --- a/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java +++ b/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDPositiveLongGeneratorUnitTest.java @@ -1,89 +1,32 @@ package com.baeldung.uuid; import org.junit.jupiter.api.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.lang.reflect.Method; -import java.text.DecimalFormat; -import java.util.*; +import java.util.HashSet; +import java.util.Set; import static org.assertj.core.api.Assertions.assertThat; public class UUIDPositiveLongGeneratorUnitTest { - private final static int NUMBER_OF_CHECKS = 1000000; - private final static double COLLISION_THRESHOLD = 0.001; - private final UUIDPositiveLongGenerator uuidLongGenerator = new UUIDPositiveLongGenerator(); - private final Logger logger = LoggerFactory.getLogger(UUIDPositiveLongGeneratorUnitTest.class); - List times = new ArrayList<>(); + //private final UUIDPositiveLongGenerator uuidLongGenerator = new UUIDPositiveLongGenerator(); + + Set uniqueValues = new HashSet<>(); @Test void whenForeachGenerateLongValue_thenCollisionsCheck() throws Exception { - times.clear(); - printTableHeader(); + UUIDPositiveLongGenerator uuidLongGenerator = new UUIDPositiveLongGenerator(); for (Method method : uuidLongGenerator.getClass().getDeclaredMethods()) { - collisionCheck(method); - } - } - - private void printTableHeader() { - logger.info(String.format("%-25s %15s %15s %15s", "Approach(method name)", "collisions", "probability","Testing Time")); - logger.info("--------------------------------------------------------------------------------"); - } - - private void printOutput(String method, int collisionsCount, double collisionsProbability, String time) { - DecimalFormat decimalFormat = new DecimalFormat("#.#####"); - logger.info(String.format("%-25s %15s %15s %15s", method, collisionsCount, decimalFormat.format(collisionsProbability),time)); - } - - private void collisionCheck(Method method) throws Exception { - long start = System.currentTimeMillis(); - Set uniqueValues = new HashSet<>(); - int collisions = 0; - for (int i = 0; i < NUMBER_OF_CHECKS; i++) { - long uniqueValue = (long) method.invoke(uuidLongGenerator); + long uniqueValue; + do uniqueValue = (long) method.invoke(uuidLongGenerator); while (!isUnique(uniqueValue)); assertThat(uniqueValue).isPositive(); - if (!uniqueValues.add(uniqueValue)) { - collisions++; - } } - double collisionsProbability = (double) collisions / NUMBER_OF_CHECKS; - long end = System.currentTimeMillis(); - String time = convertMillisToTime(end - start); - printOutput(method.getName(), collisions, collisionsProbability, time); - assertThat(collisionsProbability).isLessThan(COLLISION_THRESHOLD); - } private boolean isUnique(long value) { - // Implementasikan logika pengecekan keunikan, misalnya, dengan memeriksa dalam database - // Mengembalikan true jika nilai unik, false jika ada tumbukan - return true; // Implementasikan sesuai kebutuhan aplikasi Anda + // Implement uniqueness checking logic, for example, by checking in the database + return uniqueValues.add(value); } - - private String convertMillisToTime(long currentTimeMillis) { - - long totalMilliseconds = currentTimeMillis % 1000; - times.add(totalMilliseconds); - long totalSeconds = (currentTimeMillis / 1000) % 60; - long totalMinutes = (currentTimeMillis / 60000) % 60; - long hours = (currentTimeMillis / 3600000); - StringJoiner stringBuffer = new StringJoiner(""); - - if (hours > 0){ - stringBuffer.add(hours+"h "); - } - if (totalMinutes > 0){ - stringBuffer.add(totalMinutes+" m "); - } - if (totalSeconds > 0){ - stringBuffer.add(totalSeconds+" s "); - } - if (totalMilliseconds > 0){ - stringBuffer.add(totalMilliseconds+" ms"); - } - return stringBuffer.toString(); - } } From 0a3b02fd2411eec6b5fd959a30711c6b5a91e031 Mon Sep 17 00:00:00 2001 From: Harry9656 Date: Tue, 21 Nov 2023 05:48:43 +0100 Subject: [PATCH 028/228] JAVA-26765: Update spring-boot-data-3 to new mysql connector --- spring-boot-modules/spring-boot-data-3/pom.xml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/spring-boot-modules/spring-boot-data-3/pom.xml b/spring-boot-modules/spring-boot-data-3/pom.xml index 6c2edbb864..7c0f4b3ffd 100644 --- a/spring-boot-modules/spring-boot-data-3/pom.xml +++ b/spring-boot-modules/spring-boot-data-3/pom.xml @@ -1,7 +1,7 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung spring-boot-data-3 @@ -30,8 +30,8 @@ ${aws-secretsmanager-jdbc.version} - mysql - mysql-connector-java + com.mysql + mysql-connector-j runtime From ddf0c7bef89e971decbfc62f19afdecc5a79ec04 Mon Sep 17 00:00:00 2001 From: Harry9656 Date: Tue, 21 Nov 2023 05:55:12 +0100 Subject: [PATCH 029/228] JAVA-26765: Update design-patterns-architectural to new mysql connector --- patterns-modules/design-patterns-architectural/pom.xml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/patterns-modules/design-patterns-architectural/pom.xml b/patterns-modules/design-patterns-architectural/pom.xml index 4efcca0c6b..addcdfe390 100644 --- a/patterns-modules/design-patterns-architectural/pom.xml +++ b/patterns-modules/design-patterns-architectural/pom.xml @@ -1,7 +1,7 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 design-patterns-architectural 1.0 @@ -36,8 +36,8 @@ ${hibernate-core.version} - mysql - mysql-connector-java + com.mysql + mysql-connector-j ${mysql-connector.version} jar @@ -65,7 +65,7 @@ 5.2.16.Final - 6.0.6 + 8.2.0 2.7.5 5.3.0 2.7.5 From 2dd443b291dd0d7846fd4ff9c14c843e50acf08c Mon Sep 17 00:00:00 2001 From: Harry9656 Date: Tue, 21 Nov 2023 06:00:50 +0100 Subject: [PATCH 030/228] JAVA-26765: Update jhipster-6/bookstore-monolith to new mysql connector --- jhipster-6/bookstore-monolith/pom.xml | 70 +++++++++++++-------------- 1 file changed, 35 insertions(+), 35 deletions(-) diff --git a/jhipster-6/bookstore-monolith/pom.xml b/jhipster-6/bookstore-monolith/pom.xml index a35abb9c19..2a5368c9ac 100644 --- a/jhipster-6/bookstore-monolith/pom.xml +++ b/jhipster-6/bookstore-monolith/pom.xml @@ -90,10 +90,10 @@ io.springfox springfox-bean-validators - - - - + + + + com.zaxxer HikariCP @@ -107,8 +107,8 @@ commons-lang3 - mysql - mysql-connector-java + com.mysql + mysql-connector-j org.assertj @@ -136,10 +136,10 @@ net.logstash.logback logstash-logback-encoder - - - - + + + + org.mapstruct mapstruct @@ -423,28 +423,28 @@ jib-maven-plugin ${jib-maven-plugin.version} - - openjdk:8-jre-alpine - - - bookstore:latest - - - - sh - - chmod +x /entrypoint.sh && sync && /entrypoint.sh - - - 8080 - - - ALWAYS - 0 - - true - - + + openjdk:8-jre-alpine + + + bookstore:latest + + + + sh + + chmod +x /entrypoint.sh && sync && /entrypoint.sh + + + 8080 + + + ALWAYS + 0 + + true + + org.liquibase @@ -1137,9 +1137,9 @@ jdt_apt false - - - + + + 3.0.1 From d4b7888a6e0172568e29185e6b55e6546468f4cb Mon Sep 17 00:00:00 2001 From: Harry9656 Date: Tue, 21 Nov 2023 06:05:05 +0100 Subject: [PATCH 031/228] JAVA-26765: Update spring-cloud-modules/spring-cloud-vault to new mysql connector --- spring-cloud-modules/spring-cloud-vault/pom.xml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/spring-cloud-modules/spring-cloud-vault/pom.xml b/spring-cloud-modules/spring-cloud-vault/pom.xml index e4cf020986..58a28bdf5a 100644 --- a/spring-cloud-modules/spring-cloud-vault/pom.xml +++ b/spring-cloud-modules/spring-cloud-vault/pom.xml @@ -1,7 +1,7 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung.spring.cloud spring-cloud-vault @@ -42,8 +42,8 @@ test - mysql - mysql-connector-java + com.mysql + mysql-connector-j org.springframework.boot From 9b0e3227bee652018b3d51b0772b8d28ec0522f0 Mon Sep 17 00:00:00 2001 From: Harry9656 Date: Tue, 21 Nov 2023 06:08:12 +0100 Subject: [PATCH 032/228] JAVA-26765: Update spring-cloud-modules/spring-cloud-aws to new mysql connector --- spring-cloud-modules/spring-cloud-aws/pom.xml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/spring-cloud-modules/spring-cloud-aws/pom.xml b/spring-cloud-modules/spring-cloud-aws/pom.xml index ff376b02cb..328ddd50de 100644 --- a/spring-cloud-modules/spring-cloud-aws/pom.xml +++ b/spring-cloud-modules/spring-cloud-aws/pom.xml @@ -1,7 +1,7 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung.spring.cloud spring-cloud-aws @@ -69,8 +69,8 @@ postgresql - mysql - mysql-connector-java + com.mysql + mysql-connector-j From ec40d41eb1821ed3e46c59407a3c11c43a95200b Mon Sep 17 00:00:00 2001 From: Harry9656 Date: Tue, 21 Nov 2023 06:14:18 +0100 Subject: [PATCH 033/228] JAVA-26765: Update spring-cloud-modules/spring-cloud-task/springcloudtaskbatch to new mysql connector --- .../spring-cloud-task/springcloudtaskbatch/pom.xml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/spring-cloud-modules/spring-cloud-task/springcloudtaskbatch/pom.xml b/spring-cloud-modules/spring-cloud-task/springcloudtaskbatch/pom.xml index 7dbbb27a77..f7c13e881f 100644 --- a/spring-cloud-modules/spring-cloud-task/springcloudtaskbatch/pom.xml +++ b/spring-cloud-modules/spring-cloud-task/springcloudtaskbatch/pom.xml @@ -1,7 +1,7 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung.cloud springcloudtaskbatch @@ -23,8 +23,8 @@ spring-boot-starter-data-jpa - mysql - mysql-connector-java + com.mysql + mysql-connector-j org.springframework.cloud From 64006c8374890ba880993e3fc86d8e21d6fd90f7 Mon Sep 17 00:00:00 2001 From: Harry9656 Date: Tue, 21 Nov 2023 06:17:34 +0100 Subject: [PATCH 034/228] JAVA-26765: Update web-modules/vraptor to new mysql connector --- web-modules/vraptor/pom.xml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/web-modules/vraptor/pom.xml b/web-modules/vraptor/pom.xml index 25f8b5d5e5..b26a29e004 100644 --- a/web-modules/vraptor/pom.xml +++ b/web-modules/vraptor/pom.xml @@ -1,7 +1,7 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 vraptor vraptor @@ -80,8 +80,8 @@ ${vraptor-hibernate.version} - mysql - mysql-connector-java + com.mysql + mysql-connector-j ${mysql-connector.version} @@ -118,7 +118,7 @@ 8.0.1.Final 4.1.0-RC3 4.0.4 - 8.0.8-dmr + 8.2.0 0.4 2.3.27-incubating 2.1 From 215a61c122e5a78fbfc56dbe5e2cdf6afef2dc79 Mon Sep 17 00:00:00 2001 From: Harry9656 Date: Tue, 21 Nov 2023 06:23:59 +0100 Subject: [PATCH 035/228] JAVA-26765: Update web-modules/java-lite to new mysql connector --- web-modules/java-lite/pom.xml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/web-modules/java-lite/pom.xml b/web-modules/java-lite/pom.xml index 7f1c9182f7..024d38420e 100644 --- a/web-modules/java-lite/pom.xml +++ b/web-modules/java-lite/pom.xml @@ -1,7 +1,7 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 org.baeldung java-lite @@ -22,8 +22,8 @@ ${activeweb.version} - mysql - mysql-connector-java + com.mysql + mysql-connector-j ${mysql.connector.java.version} @@ -88,7 +88,7 @@ 9.4.8.v20171121 1.4.13 1.15 - 5.1.45 + 8.2.0 1.7.0 1.15 From 275de7fd815cbc42fad50e29388f0bb98266a3a7 Mon Sep 17 00:00:00 2001 From: Harry9656 Date: Tue, 21 Nov 2023 06:27:21 +0100 Subject: [PATCH 036/228] JAVA-26765: Update spring-security-web-boot-1 to new mysql connector --- .../spring-security-web-boot-1/pom.xml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/spring-security-modules/spring-security-web-boot-1/pom.xml b/spring-security-modules/spring-security-web-boot-1/pom.xml index 08adb700ec..baa9f8e1e5 100644 --- a/spring-security-modules/spring-security-web-boot-1/pom.xml +++ b/spring-security-modules/spring-security-web-boot-1/pom.xml @@ -1,7 +1,7 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-security-web-boot-1 0.0.1-SNAPSHOT @@ -45,8 +45,8 @@ spring-security-data - mysql - mysql-connector-java + com.mysql + mysql-connector-j runtime From a76341d307fa6c464201edcf7f1a0ec3362394e6 Mon Sep 17 00:00:00 2001 From: Harry9656 Date: Tue, 21 Nov 2023 06:30:57 +0100 Subject: [PATCH 037/228] JAVA-26765: Update spring-security-web-boot-2 to new mysql connector --- .../spring-security-web-boot-2/pom.xml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/spring-security-modules/spring-security-web-boot-2/pom.xml b/spring-security-modules/spring-security-web-boot-2/pom.xml index 2255f8b035..7dcba3cd3e 100644 --- a/spring-security-modules/spring-security-web-boot-2/pom.xml +++ b/spring-security-modules/spring-security-web-boot-2/pom.xml @@ -1,7 +1,7 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-security-web-boot-2 0.0.1-SNAPSHOT @@ -45,8 +45,8 @@ spring-security-data - mysql - mysql-connector-java + com.mysql + mysql-connector-j runtime From fdd20e25a70188403eaed068ca8008d1c0091b5c Mon Sep 17 00:00:00 2001 From: timis1 Date: Tue, 21 Nov 2023 22:32:44 +0200 Subject: [PATCH 038/228] JAVA-26721 Upgrade okhttp, mockwebserver to latest version --- spring-5-webflux-2/pom.xml | 1 + spring-5-webflux/pom.xml | 1 + 2 files changed, 2 insertions(+) diff --git a/spring-5-webflux-2/pom.xml b/spring-5-webflux-2/pom.xml index 34cbda6c18..efb99e06d5 100644 --- a/spring-5-webflux-2/pom.xml +++ b/spring-5-webflux-2/pom.xml @@ -86,6 +86,7 @@ com.squareup.okhttp3 mockwebserver + 4.12.0 diff --git a/spring-5-webflux/pom.xml b/spring-5-webflux/pom.xml index 69de83c227..fe6dbe5292 100644 --- a/spring-5-webflux/pom.xml +++ b/spring-5-webflux/pom.xml @@ -74,6 +74,7 @@ com.squareup.okhttp3 mockwebserver + 4.12.0 From 1379b2dd94d28d646529603050ec8e2026b982c6 Mon Sep 17 00:00:00 2001 From: Harry9656 Date: Tue, 21 Nov 2023 21:50:28 +0100 Subject: [PATCH 039/228] JAVA-26765: Update persistence-modules/hibernate-jpa to new mysql connector --- persistence-modules/hibernate-jpa/pom.xml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/persistence-modules/hibernate-jpa/pom.xml b/persistence-modules/hibernate-jpa/pom.xml index 5a99c1c4d0..603c749e95 100644 --- a/persistence-modules/hibernate-jpa/pom.xml +++ b/persistence-modules/hibernate-jpa/pom.xml @@ -56,8 +56,8 @@ ${hibernate.version} - mysql - mysql-connector-java + com.mysql + mysql-connector-j ${mysql.version} @@ -83,7 +83,7 @@ - 8.0.32 + 8.2.0 2.6.0 3.0.4 2.1.214 From e33de9ef00a5fa3afb796febb0130fa3ae70265e Mon Sep 17 00:00:00 2001 From: Harry9656 Date: Tue, 21 Nov 2023 21:53:11 +0100 Subject: [PATCH 040/228] JAVA-26765: Update persistence-modules/hibernate-libraries to new mysql connector --- persistence-modules/hibernate-libraries/pom.xml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/persistence-modules/hibernate-libraries/pom.xml b/persistence-modules/hibernate-libraries/pom.xml index 3f4da28296..15292689eb 100644 --- a/persistence-modules/hibernate-libraries/pom.xml +++ b/persistence-modules/hibernate-libraries/pom.xml @@ -1,7 +1,7 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 hibernate-libraries 0.0.1-SNAPSHOT @@ -63,8 +63,8 @@ test - mysql - mysql-connector-java + com.mysql + mysql-connector-j ${mysql.version} runtime @@ -168,7 +168,7 @@ 2.0.0 3.8.1 3.8.1 - 8.0.19 + 8.2.0 2.1.3.RELEASE From 30bca1ce27a417c145155e3d15037e6b8577fb21 Mon Sep 17 00:00:00 2001 From: Harry9656 Date: Tue, 21 Nov 2023 21:54:42 +0100 Subject: [PATCH 041/228] JAVA-26765: Update persistence-modules/activejdbc to new mysql connector --- persistence-modules/activejdbc/pom.xml | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/persistence-modules/activejdbc/pom.xml b/persistence-modules/activejdbc/pom.xml index a661fc3abb..602235b892 100644 --- a/persistence-modules/activejdbc/pom.xml +++ b/persistence-modules/activejdbc/pom.xml @@ -1,7 +1,7 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 activejdbc 1.0-SNAPSHOT @@ -28,8 +28,8 @@ - mysql - mysql-connector-java + com.mysql + mysql-connector-j ${mysql.connector.version} @@ -64,8 +64,8 @@ - mysql - mysql-connector-java + com.mysql + mysql-connector-j ${mysql.connector.version} @@ -76,7 +76,7 @@ 3.4-j11 development.test,development - 8.0.32 + 8.2.0 \ No newline at end of file From 6d43ac0b9d619c78e9805a2f8bf2311ec293eda6 Mon Sep 17 00:00:00 2001 From: Harry9656 Date: Tue, 21 Nov 2023 22:00:26 +0100 Subject: [PATCH 042/228] JAVA-26765: Update persistence-modules/spring-data-jpa-repo to new mysql connector --- persistence-modules/spring-data-jpa-repo/pom.xml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/persistence-modules/spring-data-jpa-repo/pom.xml b/persistence-modules/spring-data-jpa-repo/pom.xml index 26fff365a1..debf9690f6 100644 --- a/persistence-modules/spring-data-jpa-repo/pom.xml +++ b/persistence-modules/spring-data-jpa-repo/pom.xml @@ -1,7 +1,7 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-data-jpa-repo spring-data-jpa-repo @@ -27,8 +27,8 @@ spring-boot-starter-data-jdbc - mysql - mysql-connector-java + com.mysql + mysql-connector-j org.postgresql From 97623cf4c612a9af4c221667dc6dae5b766c52ec Mon Sep 17 00:00:00 2001 From: Harry9656 Date: Tue, 21 Nov 2023 22:02:14 +0100 Subject: [PATCH 043/228] JAVA-26765: Update persistence-modules/spring-data-shardingsphere to new mysql connector --- persistence-modules/spring-data-shardingsphere/pom.xml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/persistence-modules/spring-data-shardingsphere/pom.xml b/persistence-modules/spring-data-shardingsphere/pom.xml index c1ca313038..117a3ae7fe 100644 --- a/persistence-modules/spring-data-shardingsphere/pom.xml +++ b/persistence-modules/spring-data-shardingsphere/pom.xml @@ -17,7 +17,7 @@ 5.3.2 - 8.0.33 + 8.2.0 @@ -43,8 +43,8 @@ test - mysql - mysql-connector-java + com.mysql + mysql-connector-j ${mysql.version} From ff96e6a70a25933b4b7d8fccc76fbe61e5dca042 Mon Sep 17 00:00:00 2001 From: Harry9656 Date: Tue, 21 Nov 2023 22:09:19 +0100 Subject: [PATCH 044/228] JAVA-26765: Update persistence-modules/spring-data-rest-querydsl to new mysql connector --- persistence-modules/spring-data-rest-querydsl/pom.xml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/persistence-modules/spring-data-rest-querydsl/pom.xml b/persistence-modules/spring-data-rest-querydsl/pom.xml index dc1cf64006..89db7d24a5 100644 --- a/persistence-modules/spring-data-rest-querydsl/pom.xml +++ b/persistence-modules/spring-data-rest-querydsl/pom.xml @@ -1,7 +1,7 @@ + xmlns="http://maven.apache.org/POM/4.0.0" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-data-rest-querydsl 1.0 @@ -28,8 +28,8 @@ spring-boot-starter-data-jpa - mysql - mysql-connector-java + com.mysql + mysql-connector-j com.querydsl From 8a98a730c65b86d0972a5701391558fe7e62c6e1 Mon Sep 17 00:00:00 2001 From: Harry9656 Date: Tue, 21 Nov 2023 22:14:39 +0100 Subject: [PATCH 045/228] JAVA-26765: Update persistence-modules/spring-jdbc to new mysql connector --- persistence-modules/spring-jdbc/pom.xml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/persistence-modules/spring-jdbc/pom.xml b/persistence-modules/spring-jdbc/pom.xml index 08e43e8292..1aa9f4f851 100644 --- a/persistence-modules/spring-jdbc/pom.xml +++ b/persistence-modules/spring-jdbc/pom.xml @@ -1,7 +1,7 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-jdbc spring-jdbc @@ -27,8 +27,8 @@ h2 - mysql - mysql-connector-java + com.mysql + mysql-connector-j runtime From d250fb85147724fa41ba1a28dbd4f28ba6ce6b09 Mon Sep 17 00:00:00 2001 From: Harry9656 Date: Tue, 21 Nov 2023 22:16:34 +0100 Subject: [PATCH 046/228] JAVA-26765: Update persistence-modules/spring-data-jpa-query-2 to new mysql connector --- persistence-modules/spring-data-jpa-query-2/pom.xml | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/persistence-modules/spring-data-jpa-query-2/pom.xml b/persistence-modules/spring-data-jpa-query-2/pom.xml index 1282d1d8a0..62bf7f0314 100644 --- a/persistence-modules/spring-data-jpa-query-2/pom.xml +++ b/persistence-modules/spring-data-jpa-query-2/pom.xml @@ -36,9 +36,9 @@ ${jta.version} - mysql - mysql-connector-java - 3.1.12 + com.mysql + mysql-connector-j + ${mysql.version} com.google.guava @@ -85,6 +85,7 @@ 9.0.0.M26 1.1 + 8.2.0 \ No newline at end of file From d3426ed5a310d20c928e12bd59b1578054d4b147 Mon Sep 17 00:00:00 2001 From: Harry9656 Date: Tue, 21 Nov 2023 22:19:54 +0100 Subject: [PATCH 047/228] JAVA-26765: Update persistence-modules/spring-enterprise to new mysql connector --- persistence-modules/hibernate-enterprise/pom.xml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/persistence-modules/hibernate-enterprise/pom.xml b/persistence-modules/hibernate-enterprise/pom.xml index 954f8f40d3..caf7b37a41 100644 --- a/persistence-modules/hibernate-enterprise/pom.xml +++ b/persistence-modules/hibernate-enterprise/pom.xml @@ -35,8 +35,8 @@ ${geodb.version} - mysql - mysql-connector-java + com.mysql + mysql-connector-j ${mysql.version} @@ -79,7 +79,7 @@ 6.1.7.Final - 8.0.32 + 8.2.0 2.6.0 0.9 From e78f30f89299e26f15e86eecdaaab3af58c0c961 Mon Sep 17 00:00:00 2001 From: Harry9656 Date: Tue, 21 Nov 2023 22:22:49 +0100 Subject: [PATCH 048/228] JAVA-26765: Update persistence-modules/spring-boot-persistence to new mysql connector --- persistence-modules/spring-boot-persistence/pom.xml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/persistence-modules/spring-boot-persistence/pom.xml b/persistence-modules/spring-boot-persistence/pom.xml index 3c77386ddd..123e21ce59 100644 --- a/persistence-modules/spring-boot-persistence/pom.xml +++ b/persistence-modules/spring-boot-persistence/pom.xml @@ -47,8 +47,8 @@ tomcat-jdbc - mysql - mysql-connector-java + com.mysql + mysql-connector-j ${mysql-connector-java.version} @@ -72,7 +72,7 @@ 2.23.0 2.0.1.Final - 8.0.31 + 8.2.0 com.baeldung.boot.Application From 5f9c8b078b3545ee9862b768fd353bd51e58a847 Mon Sep 17 00:00:00 2001 From: Harry9656 Date: Tue, 21 Nov 2023 22:24:44 +0100 Subject: [PATCH 049/228] JAVA-26765: Update persistence-modules/spring-hibernate-6 to new mysql connector --- persistence-modules/spring-hibernate-6/pom.xml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/persistence-modules/spring-hibernate-6/pom.xml b/persistence-modules/spring-hibernate-6/pom.xml index a13117e68c..f3ea82dfad 100644 --- a/persistence-modules/spring-hibernate-6/pom.xml +++ b/persistence-modules/spring-hibernate-6/pom.xml @@ -1,7 +1,7 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-hibernate-6 0.1-SNAPSHOT @@ -84,8 +84,8 @@ ${hsqldb.version} - mysql - mysql-connector-java + com.mysql + mysql-connector-j ${mysql-connector-java.version} @@ -102,7 +102,7 @@ 6.1.3 6.2.8.Final - 8.0.7-dmr + 8.2.0 9.0.80 From 760481ec043930638a7779652026821cb75d20c9 Mon Sep 17 00:00:00 2001 From: gaepi Date: Wed, 22 Nov 2023 15:41:49 +0100 Subject: [PATCH 050/228] JAVA-27657 | Replacing deprecated WebSecurityConfigurerAdapter --- .../HttpSecurityConfig.java | 10 +++-- .../WebSecurityConfig.java | 43 ++++++++++++------- .../oauth2resttemplate/SecurityConfig.java | 1 - .../saml/config/WebSecurityConfig.java | 36 ++++++---------- .../com/baeldung/spring/SecurityConfig.java | 3 +- 5 files changed, 48 insertions(+), 45 deletions(-) diff --git a/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/HttpSecurityConfig.java b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/HttpSecurityConfig.java index d6361255e5..414f782907 100644 --- a/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/HttpSecurityConfig.java +++ b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/HttpSecurityConfig.java @@ -1,16 +1,17 @@ package com.baeldung.httpsecurityvswebsecurity; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.web.SecurityFilterChain; @Configuration @EnableWebSecurity -public class HttpSecurityConfig extends WebSecurityConfigurerAdapter { +public class HttpSecurityConfig { - @Override - protected void configure(HttpSecurity http) throws Exception { + @Bean + public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { // Given: HttpSecurity configured http.authorizeRequests() @@ -27,5 +28,6 @@ public class HttpSecurityConfig extends WebSecurityConfigurerAdapter { // When: Accessing specific URLs // Then: Access is granted based on defined rules + return http.build(); } } diff --git a/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/WebSecurityConfig.java b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/WebSecurityConfig.java index 46a82918aa..ec50069ba5 100644 --- a/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/WebSecurityConfig.java +++ b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/WebSecurityConfig.java @@ -1,35 +1,48 @@ package com.baeldung.httpsecurityvswebsecurity; +import org.springframework.context.annotation.Bean; +import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.web.SecurityFilterChain; @Configuration -public class WebSecurityConfig extends WebSecurityConfigurerAdapter { +public class WebSecurityConfig { @Autowired private UserDetailsService userDetailsService; - @Override - protected void configure(AuthenticationManagerBuilder auth) throws Exception { - auth - .userDetailsService(userDetailsService) - .passwordEncoder(new BCryptPasswordEncoder()); + @Bean + public BCryptPasswordEncoder bCryptPasswordEncoder() { + return new BCryptPasswordEncoder(); } - @Override - protected void configure(HttpSecurity http) throws Exception { + @Bean + public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { + + AuthenticationManagerBuilder authenticationManagerBuilder = http.getSharedObject(AuthenticationManagerBuilder.class); + authenticationManagerBuilder.userDetailsService(userDetailsService); + AuthenticationManager authenticationManager = authenticationManagerBuilder.build(); + http.authorizeRequests() - .antMatchers("/") - .permitAll() - .anyRequest() - .authenticated() - .and() - .formLogin(); + .antMatchers("/") + .permitAll() + .anyRequest() + .authenticated() + .and() + .formLogin().and() + .authenticationManager(authenticationManager) + .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); + + return http.build(); + } + + protected void configure(HttpSecurity http) throws Exception { + } } diff --git a/spring-security-modules/spring-security-oauth2/src/main/java/com/baeldung/oauth2resttemplate/SecurityConfig.java b/spring-security-modules/spring-security-oauth2/src/main/java/com/baeldung/oauth2resttemplate/SecurityConfig.java index 1fb9a6773a..3a8e037f72 100644 --- a/spring-security-modules/spring-security-oauth2/src/main/java/com/baeldung/oauth2resttemplate/SecurityConfig.java +++ b/spring-security-modules/spring-security-oauth2/src/main/java/com/baeldung/oauth2resttemplate/SecurityConfig.java @@ -8,7 +8,6 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.Ordered; import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.oauth2.client.OAuth2ClientContext; import org.springframework.security.oauth2.client.OAuth2RestTemplate; import org.springframework.security.oauth2.client.filter.OAuth2ClientAuthenticationProcessingFilter; diff --git a/spring-security-modules/spring-security-saml/src/main/java/com/baeldung/saml/config/WebSecurityConfig.java b/spring-security-modules/spring-security-saml/src/main/java/com/baeldung/saml/config/WebSecurityConfig.java index 297c391823..956233dfaf 100644 --- a/spring-security-modules/spring-security-saml/src/main/java/com/baeldung/saml/config/WebSecurityConfig.java +++ b/spring-security-modules/spring-security-saml/src/main/java/com/baeldung/saml/config/WebSecurityConfig.java @@ -10,11 +10,9 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.saml.*; import org.springframework.security.saml.key.KeyManager; import org.springframework.security.saml.metadata.*; @@ -31,7 +29,7 @@ import org.springframework.security.web.util.matcher.AntPathRequestMatcher; @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(securedEnabled = true) -public class WebSecurityConfig extends WebSecurityConfigurerAdapter { +public class WebSecurityConfig { @Value("${saml.sp}") private String samlAudience; @@ -55,8 +53,7 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Bean public SAMLDiscovery samlDiscovery() { - SAMLDiscovery idpDiscovery = new SAMLDiscovery(); - return idpDiscovery; + return new SAMLDiscovery(); } @Autowired @@ -78,19 +75,19 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter { } @Bean - public SAMLProcessingFilter samlWebSSOProcessingFilter() throws Exception { + public SAMLProcessingFilter samlWebSSOProcessingFilter(AuthenticationManager authenticationManager) { SAMLProcessingFilter samlWebSSOProcessingFilter = new SAMLProcessingFilter(); - samlWebSSOProcessingFilter.setAuthenticationManager(authenticationManager()); + samlWebSSOProcessingFilter.setAuthenticationManager(authenticationManager); samlWebSSOProcessingFilter.setAuthenticationSuccessHandler(samlAuthSuccessHandler); samlWebSSOProcessingFilter.setAuthenticationFailureHandler(samlAuthFailureHandler); return samlWebSSOProcessingFilter; } @Bean - public FilterChainProxy samlFilter() throws Exception { + public FilterChainProxy samlFilter(SAMLProcessingFilter samlProcessingFilter) throws Exception { List chains = new ArrayList<>(); chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/SSO/**"), - samlWebSSOProcessingFilter())); + samlProcessingFilter)); chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/discovery/**"), samlDiscovery())); chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/login/**"), @@ -102,19 +99,13 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter { return new FilterChainProxy(chains); } - @Bean - @Override - public AuthenticationManager authenticationManagerBean() throws Exception { - return super.authenticationManagerBean(); - } - @Bean public MetadataGeneratorFilter metadataGeneratorFilter() { return new MetadataGeneratorFilter(metadataGenerator()); } - @Override - protected void configure(HttpSecurity http) throws Exception { + @Bean + public SecurityFilterChain filterChain(HttpSecurity http, SAMLProcessingFilter samlProcessingFilter) throws Exception { http .csrf() .disable(); @@ -125,8 +116,8 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter { http .addFilterBefore(metadataGeneratorFilter(), ChannelProcessingFilter.class) - .addFilterAfter(samlFilter(), BasicAuthenticationFilter.class) - .addFilterBefore(samlFilter(), CsrfFilter.class); + .addFilterAfter(samlProcessingFilter, BasicAuthenticationFilter.class) + .addFilterBefore(samlProcessingFilter, CsrfFilter.class); http .authorizeRequests() @@ -142,11 +133,10 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter { e.printStackTrace(); } }); - } - @Override - protected void configure(AuthenticationManagerBuilder auth) throws Exception { - auth.authenticationProvider(samlAuthenticationProvider); + http.authenticationProvider(samlAuthenticationProvider); + + return http.build(); } } diff --git a/spring-security-modules/spring-security-web-persistent-login/src/main/java/com/baeldung/spring/SecurityConfig.java b/spring-security-modules/spring-security-web-persistent-login/src/main/java/com/baeldung/spring/SecurityConfig.java index d3cfff81cb..0a9c717f5a 100644 --- a/spring-security-modules/spring-security-web-persistent-login/src/main/java/com/baeldung/spring/SecurityConfig.java +++ b/spring-security-modules/spring-security-web-persistent-login/src/main/java/com/baeldung/spring/SecurityConfig.java @@ -3,7 +3,6 @@ package com.baeldung.spring; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; /** * Spring Security Configuration. @@ -11,7 +10,7 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur @Configuration @EnableWebSecurity @ImportResource({ "classpath:webSecurityConfig.xml" }) -public class SecurityConfig extends WebSecurityConfigurerAdapter { +public class SecurityConfig { public SecurityConfig() { super(); From 1f5f4af22ab4f72e00c6bde52946cda4687982cf Mon Sep 17 00:00:00 2001 From: Geoffrey De Smet Date: Tue, 21 Nov 2023 14:09:04 +0100 Subject: [PATCH 051/228] GST-4 Timefold Solver --- pom.xml | 2 + timefold-solver/README.md | 7 +++ timefold-solver/pom.xml | 44 ++++++++++++++ .../com/baeldung/timefoldsolver/Employee.java | 32 +++++++++++ .../com/baeldung/timefoldsolver/Shift.java | 57 +++++++++++++++++++ .../timefoldsolver/ShiftSchedule.java | 47 +++++++++++++++ .../timefoldsolver/ShiftScheduleApp.java | 54 ++++++++++++++++++ .../ShiftScheduleConstraintProvider.java | 37 ++++++++++++ .../ShiftScheduleConstraintProviderTest.java | 50 ++++++++++++++++ 9 files changed, 330 insertions(+) create mode 100644 timefold-solver/README.md create mode 100644 timefold-solver/pom.xml create mode 100644 timefold-solver/src/main/java/com/baeldung/timefoldsolver/Employee.java create mode 100644 timefold-solver/src/main/java/com/baeldung/timefoldsolver/Shift.java create mode 100644 timefold-solver/src/main/java/com/baeldung/timefoldsolver/ShiftSchedule.java create mode 100644 timefold-solver/src/main/java/com/baeldung/timefoldsolver/ShiftScheduleApp.java create mode 100644 timefold-solver/src/main/java/com/baeldung/timefoldsolver/ShiftScheduleConstraintProvider.java create mode 100644 timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleConstraintProviderTest.java diff --git a/pom.xml b/pom.xml index 7099dd8cbc..8729aa8f5c 100644 --- a/pom.xml +++ b/pom.xml @@ -894,6 +894,7 @@ tensorflow-java testing-modules testing-modules/mockito-simple + timefold-solver vaadin vavr-modules vertx-modules @@ -1139,6 +1140,7 @@ tensorflow-java testing-modules testing-modules/mockito-simple + timefold-solver vaadin vavr-modules vertx-modules diff --git a/timefold-solver/README.md b/timefold-solver/README.md new file mode 100644 index 0000000000..b7a2dbe14b --- /dev/null +++ b/timefold-solver/README.md @@ -0,0 +1,7 @@ +## OptaPlanner + +This module contains articles about OptaPlanner. + +### Relevant articles + +- [A Guide to OptaPlanner](https://www.baeldung.com/opta-planner) diff --git a/timefold-solver/pom.xml b/timefold-solver/pom.xml new file mode 100644 index 0000000000..2a219a593c --- /dev/null +++ b/timefold-solver/pom.xml @@ -0,0 +1,44 @@ + + + 4.0.0 + timefold-solver + timefold-solver + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + + ai.timefold.solver + timefold-solver-bom + ${version.ai.timefold.solver} + pom + import + + + + + + ai.timefold.solver + timefold-solver-core + + + ai.timefold.solver + timefold-solver-test + test + + + + + 17 + 17 + 1.4.0 + + + diff --git a/timefold-solver/src/main/java/com/baeldung/timefoldsolver/Employee.java b/timefold-solver/src/main/java/com/baeldung/timefoldsolver/Employee.java new file mode 100644 index 0000000000..c755896201 --- /dev/null +++ b/timefold-solver/src/main/java/com/baeldung/timefoldsolver/Employee.java @@ -0,0 +1,32 @@ +package com.baeldung.timefoldsolver; + +import java.util.Set; + +public class Employee { + + private String name; + private Set skills; + + public Employee(String name, Set skills) { + this.name = name; + this.skills = skills; + } + + @Override + public String toString() { + return name; + } + + // ************************************************************************ + // Getters and setters + // ************************************************************************ + + public String getName() { + return name; + } + + public Set getSkills() { + return skills; + } + +} diff --git a/timefold-solver/src/main/java/com/baeldung/timefoldsolver/Shift.java b/timefold-solver/src/main/java/com/baeldung/timefoldsolver/Shift.java new file mode 100644 index 0000000000..04087134c6 --- /dev/null +++ b/timefold-solver/src/main/java/com/baeldung/timefoldsolver/Shift.java @@ -0,0 +1,57 @@ +package com.baeldung.timefoldsolver; + +import java.time.LocalDateTime; + +import ai.timefold.solver.core.api.domain.entity.PlanningEntity; +import ai.timefold.solver.core.api.domain.variable.PlanningVariable; + +@PlanningEntity +public class Shift { + + private LocalDateTime start; + private LocalDateTime end; + private String requiredSkill; + + @PlanningVariable + private Employee employee; + + // A no-arg constructor is required for @PlanningEntity annotated classes + public Shift() {} + + public Shift(LocalDateTime start, LocalDateTime end, String requiredSkill) { + this(start, end, requiredSkill, null); + } + + public Shift(LocalDateTime start, LocalDateTime end, String requiredSkill, Employee employee) { + this.start = start; + this.end = end; + this.requiredSkill = requiredSkill; + this.employee = employee; + } + + @Override + public String toString() { + return start + " - " + end; + } + + // ************************************************************************ + // Getters and setters + // ************************************************************************ + + public LocalDateTime getStart() { + return start; + } + + public LocalDateTime getEnd() { + return end; + } + + public String getRequiredSkill() { + return requiredSkill; + } + + public Employee getEmployee() { + return employee; + } + +} diff --git a/timefold-solver/src/main/java/com/baeldung/timefoldsolver/ShiftSchedule.java b/timefold-solver/src/main/java/com/baeldung/timefoldsolver/ShiftSchedule.java new file mode 100644 index 0000000000..85abc8eb66 --- /dev/null +++ b/timefold-solver/src/main/java/com/baeldung/timefoldsolver/ShiftSchedule.java @@ -0,0 +1,47 @@ +package com.baeldung.timefoldsolver; + +import java.util.List; + +import ai.timefold.solver.core.api.domain.solution.PlanningEntityCollectionProperty; +import ai.timefold.solver.core.api.domain.solution.PlanningScore; +import ai.timefold.solver.core.api.domain.solution.PlanningSolution; +import ai.timefold.solver.core.api.domain.valuerange.ValueRangeProvider; +import ai.timefold.solver.core.api.score.buildin.hardsoft.HardSoftScore; + +@PlanningSolution +public class ShiftSchedule { + + @ValueRangeProvider + private List employees; + @PlanningEntityCollectionProperty + private List shifts; + + @PlanningScore + private HardSoftScore score = null; + + // A no-arg constructor is required for @PlanningSolution annotated classes + public ShiftSchedule() { + } + + public ShiftSchedule(List employees, List shifts) { + this.employees = employees; + this.shifts = shifts; + } + + // ************************************************************************ + // Getters and setters + // ************************************************************************ + + public List getEmployees() { + return employees; + } + + public List getShifts() { + return shifts; + } + + public HardSoftScore getScore() { + return score; + } + +} diff --git a/timefold-solver/src/main/java/com/baeldung/timefoldsolver/ShiftScheduleApp.java b/timefold-solver/src/main/java/com/baeldung/timefoldsolver/ShiftScheduleApp.java new file mode 100644 index 0000000000..9c25922dea --- /dev/null +++ b/timefold-solver/src/main/java/com/baeldung/timefoldsolver/ShiftScheduleApp.java @@ -0,0 +1,54 @@ +package com.baeldung.timefoldsolver; + +import java.time.Duration; +import java.time.LocalDate; +import java.util.List; +import java.util.Set; + +import ai.timefold.solver.core.api.solver.Solver; +import ai.timefold.solver.core.api.solver.SolverFactory; +import ai.timefold.solver.core.config.solver.SolverConfig; + +public class ShiftScheduleApp { + + public static void main(String[] args) { + SolverFactory solverFactory = SolverFactory.create(new SolverConfig() + .withSolutionClass(ShiftSchedule.class) + .withEntityClasses(Shift.class) + .withConstraintProviderClass(ShiftScheduleConstraintProvider.class) + // The solver runs only for 5 seconds on this small dataset. + // It's recommended to run for at least 5 minutes ("5m") otherwise. + .withTerminationSpentLimit(Duration.ofSeconds(5))); + Solver solver = solverFactory.buildSolver(); + + ShiftSchedule problem = loadProblem(); + ShiftSchedule solution = solver.solve(problem); + printSolution(solution); + } + + private static ShiftSchedule loadProblem() { + LocalDate monday = LocalDate.of(2030, 4, 1); + LocalDate tuesday = LocalDate.of(2030, 4, 2); + return new ShiftSchedule(List.of( + new Employee("Ann", Set.of("Bartender")), + new Employee("Beth", Set.of("Waiter", "Bartender")), + new Employee("Carl", Set.of("Waiter")) + ), List.of( + new Shift(monday.atTime(6, 0), monday.atTime(14, 0), "Waiter"), + new Shift(monday.atTime(9, 0), monday.atTime(17, 0), "Bartender"), + new Shift(monday.atTime(14, 0), monday.atTime(22, 0), "Bartender"), + new Shift(tuesday.atTime(6, 0), tuesday.atTime(14, 0), "Waiter"), + new Shift(tuesday.atTime(14, 0), tuesday.atTime(22, 0), "Bartender") + )); + } + + private static void printSolution(ShiftSchedule solution) { + System.out.println("Shift assignments"); + for (Shift shift : solution.getShifts()) { + System.out.println(" " + shift.getStart().toLocalDate() + + " " + shift.getStart().toLocalTime() + " - " + shift.getEnd().toLocalTime() + + ": " + shift.getEmployee().getName()); + } + } + +} diff --git a/timefold-solver/src/main/java/com/baeldung/timefoldsolver/ShiftScheduleConstraintProvider.java b/timefold-solver/src/main/java/com/baeldung/timefoldsolver/ShiftScheduleConstraintProvider.java new file mode 100644 index 0000000000..0846429460 --- /dev/null +++ b/timefold-solver/src/main/java/com/baeldung/timefoldsolver/ShiftScheduleConstraintProvider.java @@ -0,0 +1,37 @@ +package com.baeldung.timefoldsolver; + +import ai.timefold.solver.core.api.score.buildin.hardsoft.HardSoftScore; +import ai.timefold.solver.core.api.score.stream.Constraint; +import ai.timefold.solver.core.api.score.stream.ConstraintFactory; +import ai.timefold.solver.core.api.score.stream.ConstraintProvider; + +import static ai.timefold.solver.core.api.score.stream.Joiners.equal; + +public class ShiftScheduleConstraintProvider implements ConstraintProvider { + + @Override + public Constraint[] defineConstraints(ConstraintFactory constraintFactory) { + return new Constraint[] { + atMostOneShiftPerDay(constraintFactory), + requiredSkill(constraintFactory) + }; + } + + public Constraint atMostOneShiftPerDay(ConstraintFactory constraintFactory) { + return constraintFactory.forEach(Shift.class) + .join(Shift.class, + equal(shift -> shift.getStart().toLocalDate()), + equal(Shift::getEmployee)) + .filter((shift1, shift2) -> shift1 != shift2) + .penalize(HardSoftScore.ONE_HARD) + .asConstraint("At most one shift per day"); + } + + public Constraint requiredSkill(ConstraintFactory constraintFactory) { + return constraintFactory.forEach(Shift.class) + .filter(shift -> !shift.getEmployee().getSkills().contains(shift.getRequiredSkill())) + .penalize(HardSoftScore.ONE_HARD) + .asConstraint("Required skill"); + } + +} diff --git a/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleConstraintProviderTest.java b/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleConstraintProviderTest.java new file mode 100644 index 0000000000..9979f5d5e0 --- /dev/null +++ b/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleConstraintProviderTest.java @@ -0,0 +1,50 @@ +package com.baeldung.timefoldsolver; + +import java.time.LocalDate; +import java.util.Set; + +import ai.timefold.solver.test.api.score.stream.ConstraintVerifier; +import org.junit.jupiter.api.Test; + +class ShiftScheduleConstraintProviderTest { + + private static final LocalDate MONDAY = LocalDate.of(2030, 4, 1); + private static final LocalDate TUESDAY = LocalDate.of(2030, 4, 2); + + ConstraintVerifier constraintVerifier = ConstraintVerifier.build( + new ShiftScheduleConstraintProvider(), ShiftSchedule.class, Shift.class); + + @Test + void atMostOneShiftPerDay() { + Employee ann = new Employee("Ann", null); + constraintVerifier.verifyThat(ShiftScheduleConstraintProvider::atMostOneShiftPerDay) + .given( + ann, + new Shift(MONDAY.atTime(6, 0), MONDAY.atTime(14, 0), null, ann), + new Shift(MONDAY.atTime(14, 0), MONDAY.atTime(22, 0), null, ann)) + // Penalizes both A-B and B-A. To avoid that, use forEachUniquePair() in the constraint instead. + .penalizesBy(2); + constraintVerifier.verifyThat(ShiftScheduleConstraintProvider::atMostOneShiftPerDay) + .given( + ann, + new Shift(MONDAY.atTime(6, 0), MONDAY.atTime(14, 0), null, ann), + new Shift(TUESDAY.atTime(14, 0), TUESDAY.atTime(22, 0), null, ann)) + .penalizesBy(0); + } + + @Test + void requiredSkill() { + Employee ann = new Employee("Ann", Set.of("Waiter")); + constraintVerifier.verifyThat(ShiftScheduleConstraintProvider::requiredSkill) + .given( + ann, + new Shift(MONDAY.atTime(6, 0), MONDAY.atTime(14, 0), "Cook", ann)) + .penalizesBy(1); + constraintVerifier.verifyThat(ShiftScheduleConstraintProvider::requiredSkill) + .given( + ann, + new Shift(MONDAY.atTime(6, 0), MONDAY.atTime(14, 0), "Waiter", ann)) + .penalizesBy(0); + } + +} From 7deec4a5e050c91e783669f0aebd6a0724f776fb Mon Sep 17 00:00:00 2001 From: Vladyslav Chernov Date: Wed, 22 Nov 2023 16:06:21 -0800 Subject: [PATCH 052/228] BAEL-5755: indention update --- .../baeldung/xml/xml2csv/Xml2CsvExample.java | 18 +++++++++--------- .../xml/xml2csv/Xml2CsvExampleUnitTest.java | 4 ++-- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/xml/src/main/java/com/baeldung/xml/xml2csv/Xml2CsvExample.java b/xml/src/main/java/com/baeldung/xml/xml2csv/Xml2CsvExample.java index 99e5c7c0cb..84098b33f8 100644 --- a/xml/src/main/java/com/baeldung/xml/xml2csv/Xml2CsvExample.java +++ b/xml/src/main/java/com/baeldung/xml/xml2csv/Xml2CsvExample.java @@ -40,7 +40,7 @@ public class Xml2CsvExample { protected static void convertXml2CsvXslt(String xslPath, String xmlPath, String csvPath) throws IOException, TransformerException { StreamSource styleSource = new StreamSource(new File(xslPath)); Transformer transformer = TransformerFactory.newInstance() - .newTransformer(styleSource); + .newTransformer(styleSource); Source source = new StreamSource(new File(xmlPath)); Result outputTarget = new StreamResult(new File(csvPath)); transformer.transform(source, outputTarget); @@ -68,26 +68,26 @@ public class Xml2CsvExample { if ("Bookstore".equals(currentElement)) { bookstoreInfo.setLength(0); bookstoreInfo.append(reader.getAttributeValue(null, "id")) - .append(","); + .append(","); } if ("Book".equals(currentElement)) { csvRow.append(bookstoreInfo) - .append(reader.getAttributeValue(null, "id")) - .append(",") - .append(reader.getAttributeValue(null, "category")) - .append(","); + .append(reader.getAttributeValue(null, "id")) + .append(",") + .append(reader.getAttributeValue(null, "category")) + .append(","); } if ("Author".equals(currentElement)) { csvRow.append(reader.getAttributeValue(null, "id")) - .append(","); + .append(","); } break; case XMLStreamConstants.CHARACTERS: if (!reader.isWhiteSpace()) { csvRow.append(reader.getText() - .trim()) - .append(","); + .trim()) + .append(","); } break; diff --git a/xml/src/test/java/com/baeldung/xml/xml2csv/Xml2CsvExampleUnitTest.java b/xml/src/test/java/com/baeldung/xml/xml2csv/Xml2CsvExampleUnitTest.java index 3fa44b427c..181d284b2d 100644 --- a/xml/src/test/java/com/baeldung/xml/xml2csv/Xml2CsvExampleUnitTest.java +++ b/xml/src/test/java/com/baeldung/xml/xml2csv/Xml2CsvExampleUnitTest.java @@ -91,7 +91,7 @@ public class Xml2CsvExampleUnitTest { Xml2CsvExample.convertXml2CsvXslt(STYLE_XSL, DATA_XML, TEMP_OUTPUT_CSV); File csvFile = new File(TEMP_OUTPUT_CSV); - try(BufferedReader reader = new BufferedReader(new FileReader(csvFile))) { + try (BufferedReader reader = new BufferedReader(new FileReader(csvFile))) { String line; boolean isFirstLine = true; while ((line = reader.readLine()) != null) { @@ -113,7 +113,7 @@ public class Xml2CsvExampleUnitTest { Xml2CsvExample.convertXml2CsvStax(DATA_XML, TEMP_OUTPUT_CSV); File csvFile = new File(TEMP_OUTPUT_CSV); - try(BufferedReader reader = new BufferedReader(new FileReader(csvFile))) { + try (BufferedReader reader = new BufferedReader(new FileReader(csvFile))) { String line; boolean isFirstLine = true; while ((line = reader.readLine()) != null) { From 3e5904ed8cd9ce15beb96fc4df126c2d4a03f12b Mon Sep 17 00:00:00 2001 From: Harry9656 Date: Thu, 23 Nov 2023 04:10:52 +0100 Subject: [PATCH 053/228] JAVA-26765: Update persistence-modules/core-java-persistence to new mysql connector --- persistence-modules/core-java-persistence/pom.xml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/persistence-modules/core-java-persistence/pom.xml b/persistence-modules/core-java-persistence/pom.xml index e8add07fbf..e0300f5b9c 100644 --- a/persistence-modules/core-java-persistence/pom.xml +++ b/persistence-modules/core-java-persistence/pom.xml @@ -1,7 +1,7 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung.core-java-persistence core-java-persistence @@ -53,8 +53,8 @@ ${springframework.boot.spring-boot-starter.version} - mysql - mysql-connector-java + com.mysql + mysql-connector-j ${mysql-connector.version} runtime @@ -66,7 +66,7 @@ 0.9.5.5 3.0.4 6.0.6 - 8.0.32 + 8.2.0 \ No newline at end of file From 8c3b770e4bd1bdc5b6801febc38053301de43250 Mon Sep 17 00:00:00 2001 From: Harry9656 Date: Thu, 23 Nov 2023 04:19:32 +0100 Subject: [PATCH 054/228] JAVA-26765: Update persistence-modules/ibernate-queries to new mysql connector --- persistence-modules/hibernate-queries/pom.xml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/persistence-modules/hibernate-queries/pom.xml b/persistence-modules/hibernate-queries/pom.xml index 76f230a72d..0a736346a4 100644 --- a/persistence-modules/hibernate-queries/pom.xml +++ b/persistence-modules/hibernate-queries/pom.xml @@ -60,8 +60,8 @@ ${hibernate.version} - mysql - mysql-connector-java + com.mysql + mysql-connector-j ${mysql.version} @@ -96,7 +96,7 @@ 6.0.6 3.0.3 9.0.0.M26 - 8.0.32 + 8.2.0 2.6.0 2.1.214 6.3.1.Final From b180714d75ac41a559230e3535f15d80c63ecaa7 Mon Sep 17 00:00:00 2001 From: Harry9656 Date: Thu, 23 Nov 2023 04:21:15 +0100 Subject: [PATCH 055/228] JAVA-26765: Update persistence-modules/spring-jpa to new mysql connector --- persistence-modules/spring-jpa/pom.xml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/persistence-modules/spring-jpa/pom.xml b/persistence-modules/spring-jpa/pom.xml index 10e44c0ce4..91766318e6 100644 --- a/persistence-modules/spring-jpa/pom.xml +++ b/persistence-modules/spring-jpa/pom.xml @@ -1,7 +1,7 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-jpa 0.1-SNAPSHOT @@ -54,8 +54,8 @@ ${javassist.version} - mysql - mysql-connector-java + com.mysql + mysql-connector-j ${mysql-connector-java.version} runtime @@ -117,7 +117,7 @@ 6.0.6 3.29.2-GA - 8.0.33 + 8.2.0 3.1.0 6.0.0 From 78a3c17a3e619d0af3dbe47e702eef5e643d5460 Mon Sep 17 00:00:00 2001 From: Harry9656 Date: Thu, 23 Nov 2023 04:24:44 +0100 Subject: [PATCH 056/228] JAVA-26765: Update persistence-modules/apache-cayenne to new mysql connector --- persistence-modules/apache-cayenne/pom.xml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/persistence-modules/apache-cayenne/pom.xml b/persistence-modules/apache-cayenne/pom.xml index 87bf6fe30b..3715198d84 100644 --- a/persistence-modules/apache-cayenne/pom.xml +++ b/persistence-modules/apache-cayenne/pom.xml @@ -22,8 +22,8 @@ ${cayenne.version} - mysql - mysql-connector-java + com.mysql + mysql-connector-j ${mysql.connector.version} runtime @@ -40,7 +40,7 @@ - 5.1.44 + 8.2.0 4.0.M5 From 6fbaa02f92a0c94badf78fc00593557b828a6d1d Mon Sep 17 00:00:00 2001 From: Harry9656 Date: Thu, 23 Nov 2023 04:28:38 +0100 Subject: [PATCH 057/228] JAVA-26765: Update persistence-modules/core-java-persistence-2 to new mysql connector --- persistence-modules/core-java-persistence-2/pom.xml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/persistence-modules/core-java-persistence-2/pom.xml b/persistence-modules/core-java-persistence-2/pom.xml index 2013bdb6af..dea261adca 100644 --- a/persistence-modules/core-java-persistence-2/pom.xml +++ b/persistence-modules/core-java-persistence-2/pom.xml @@ -28,8 +28,8 @@ test - mysql - mysql-connector-java + com.mysql + mysql-connector-j ${mysql.driver.version} @@ -85,7 +85,7 @@ 8.4.1.jre11 10.2.0.4.0 - 8.0.22 + 8.2.0 3.11.11 20220320 07.00.00-MS-GA From 844e537a5323ab630e471a70adab1de57058d1a0 Mon Sep 17 00:00:00 2001 From: Harry9656 Date: Thu, 23 Nov 2023 04:32:04 +0100 Subject: [PATCH 058/228] JAVA-26765: Update persistence-modules/java-jpa to new mysql connector --- persistence-modules/java-jpa/pom.xml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/persistence-modules/java-jpa/pom.xml b/persistence-modules/java-jpa/pom.xml index b96b24582e..169a2e8fd7 100644 --- a/persistence-modules/java-jpa/pom.xml +++ b/persistence-modules/java-jpa/pom.xml @@ -70,8 +70,8 @@ ${javax.annotation.version} - mysql - mysql-connector-java + com.mysql + mysql-connector-j ${mysql.version} @@ -135,7 +135,7 @@ 2.1.214 4.0.0 1.3.2 - 8.0.33 + 8.2.0 \ No newline at end of file From a8db23aac25d2946102f7a1c894cb850e013ee61 Mon Sep 17 00:00:00 2001 From: Harry9656 Date: Thu, 23 Nov 2023 04:36:50 +0100 Subject: [PATCH 059/228] JAVA-26765: Update persistence-modules/java-jpa-3 to new mysql connector --- persistence-modules/java-jpa-3/pom.xml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/persistence-modules/java-jpa-3/pom.xml b/persistence-modules/java-jpa-3/pom.xml index 0237da7ece..fa3a972623 100644 --- a/persistence-modules/java-jpa-3/pom.xml +++ b/persistence-modules/java-jpa-3/pom.xml @@ -29,8 +29,8 @@ ${h2.version} - mysql - mysql-connector-java + com.mysql + mysql-connector-j ${mysql.version} @@ -86,7 +86,7 @@ 5.4.14.Final 2.7.4 - 8.0.21 + 8.2.0 2.2 3.3.3 3.0.0 From 0f05a581e20ffa31e1fd7d7cf909f4bb43935fde Mon Sep 17 00:00:00 2001 From: Harry9656 Date: Thu, 23 Nov 2023 04:37:13 +0100 Subject: [PATCH 060/228] JAVA-26765: Update persistence-modules/spring-boot-persistence-2 to new mysql connector --- persistence-modules/spring-boot-persistence-2/pom.xml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/persistence-modules/spring-boot-persistence-2/pom.xml b/persistence-modules/spring-boot-persistence-2/pom.xml index 6bca6df2b9..7d6b6909c4 100644 --- a/persistence-modules/spring-boot-persistence-2/pom.xml +++ b/persistence-modules/spring-boot-persistence-2/pom.xml @@ -94,8 +94,8 @@ tomcat-jdbc - mysql - mysql-connector-java + com.mysql + mysql-connector-j ${mysql-connector-java.version} @@ -135,7 +135,7 @@ 2.0.7 1.4.6 - 8.0.33 + 8.2.0 \ No newline at end of file From 15b097bb8af8849eeaf9ef64ec74689bcdd52a20 Mon Sep 17 00:00:00 2001 From: Harry9656 Date: Thu, 23 Nov 2023 04:44:04 +0100 Subject: [PATCH 061/228] JAVA-26765: Update persistence-modules/liquibase to new mysql connector --- persistence-modules/liquibase/pom.xml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/persistence-modules/liquibase/pom.xml b/persistence-modules/liquibase/pom.xml index 2fc5803037..90397aec4d 100644 --- a/persistence-modules/liquibase/pom.xml +++ b/persistence-modules/liquibase/pom.xml @@ -14,8 +14,8 @@ - mysql - mysql-connector-java + com.mysql + mysql-connector-j ${mysql-connector-java.version} @@ -36,7 +36,7 @@ - 5.1.6 + 8.2.0 3.4.2 From e512b83e8bfbf92ca443e35137a75017c459ec3e Mon Sep 17 00:00:00 2001 From: Harry9656 Date: Thu, 23 Nov 2023 04:46:01 +0100 Subject: [PATCH 062/228] JAVA-26765: Update persistence-modules/spring-boto-mysql to new mysql connector --- persistence-modules/spring-boot-mysql/pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/persistence-modules/spring-boot-mysql/pom.xml b/persistence-modules/spring-boot-mysql/pom.xml index de1836797c..5c392d2464 100644 --- a/persistence-modules/spring-boot-mysql/pom.xml +++ b/persistence-modules/spring-boot-mysql/pom.xml @@ -33,8 +33,8 @@ true - mysql - mysql-connector-java + com.mysql + mysql-connector-j From 4245d664b700e8919b2cf8e838453885ba221092 Mon Sep 17 00:00:00 2001 From: Harry9656 Date: Thu, 23 Nov 2023 04:48:44 +0100 Subject: [PATCH 063/228] JAVA-26765: Update persistence-modules/spring-hibernate-5 to new mysql connector --- persistence-modules/spring-hibernate-5/pom.xml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/persistence-modules/spring-hibernate-5/pom.xml b/persistence-modules/spring-hibernate-5/pom.xml index e559fe1394..32441473bb 100644 --- a/persistence-modules/spring-hibernate-5/pom.xml +++ b/persistence-modules/spring-hibernate-5/pom.xml @@ -99,8 +99,8 @@ ${hsqldb.version} - mysql - mysql-connector-java + com.mysql + mysql-connector-j ${mysql-connector-java.version} @@ -133,7 +133,7 @@ 5.2.10.Final 5.8.2.Final - 8.0.7-dmr + 8.2.0 9.0.0.M26 1.1 2.3.0.1 From ac8d8ef5c965d18b08441394a70ba93e20740f39 Mon Sep 17 00:00:00 2001 From: Harry9656 Date: Thu, 23 Nov 2023 04:50:52 +0100 Subject: [PATCH 064/228] JAVA-26765: Update persistence-modules/read-only-transactions to new mysql connector --- persistence-modules/read-only-transactions/pom.xml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/persistence-modules/read-only-transactions/pom.xml b/persistence-modules/read-only-transactions/pom.xml index 9a347fde88..c485a0d2a8 100644 --- a/persistence-modules/read-only-transactions/pom.xml +++ b/persistence-modules/read-only-transactions/pom.xml @@ -38,8 +38,8 @@ test - mysql - mysql-connector-java + com.mysql + mysql-connector-j ${mysql.version} @@ -67,7 +67,7 @@ - 8.0.21 + 8.2.0 4.0.3 5.6.1.Final 2.6.1 From 93ac0a07dc684975f28c8c345c5f7bdaae203518 Mon Sep 17 00:00:00 2001 From: Harry9656 Date: Thu, 23 Nov 2023 04:53:37 +0100 Subject: [PATCH 065/228] JAVA-26765: Update persistence-modules/hibernate5 to new mysql connector --- persistence-modules/hibernate5/pom.xml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/persistence-modules/hibernate5/pom.xml b/persistence-modules/hibernate5/pom.xml index 1a2c65c6ba..f93fe6c9e7 100644 --- a/persistence-modules/hibernate5/pom.xml +++ b/persistence-modules/hibernate5/pom.xml @@ -30,8 +30,8 @@ ${hibernate.version} - mysql - mysql-connector-java + com.mysql + mysql-connector-j ${mysql.version} @@ -58,7 +58,7 @@ 5.4.24.Final - 6.0.6 + 8.2.0 2.2.3 2.1.214 From 2fd61d0f0b43befcc38a10dc79597d690ee03d8d Mon Sep 17 00:00:00 2001 From: Harry9656 Date: Thu, 23 Nov 2023 04:57:36 +0100 Subject: [PATCH 066/228] JAVA-26765: Update persistence-modules/spring-hibernate-3 to new mysql connector --- persistence-modules/spring-hibernate-3/pom.xml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/persistence-modules/spring-hibernate-3/pom.xml b/persistence-modules/spring-hibernate-3/pom.xml index 306c4995d2..61b253d0d2 100644 --- a/persistence-modules/spring-hibernate-3/pom.xml +++ b/persistence-modules/spring-hibernate-3/pom.xml @@ -37,8 +37,8 @@ ${javassist.version} - mysql - mysql-connector-java + com.mysql + mysql-connector-j ${mysql-connector-java.version} runtime @@ -79,7 +79,7 @@ 3.21.0-GA 3.6.10.Final - 5.1.40 + 8.2.0 8.5.8 From b8c35c0c10345346fa67983b1585c71662f47fdc Mon Sep 17 00:00:00 2001 From: Harry9656 Date: Thu, 23 Nov 2023 04:58:58 +0100 Subject: [PATCH 067/228] JAVA-26765: Update persistence-modules/flyway to new mysql connector --- persistence-modules/flyway/pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/persistence-modules/flyway/pom.xml b/persistence-modules/flyway/pom.xml index 18ff9fdb39..df35f85bfb 100644 --- a/persistence-modules/flyway/pom.xml +++ b/persistence-modules/flyway/pom.xml @@ -25,8 +25,8 @@ spring-boot-starter-jdbc - mysql - mysql-connector-java + com.mysql + mysql-connector-j runtime From 9088596b1eeb51e539f6a1e5cc4d1e0ed2761123 Mon Sep 17 00:00:00 2001 From: Harry9656 Date: Thu, 23 Nov 2023 05:18:45 +0100 Subject: [PATCH 068/228] JAVA-26765: Update persistence-modules/parent-boot-2 to new mysql connector --- parent-boot-2/pom.xml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/parent-boot-2/pom.xml b/parent-boot-2/pom.xml index b79be81a66..9b40dbbe8e 100644 --- a/parent-boot-2/pom.xml +++ b/parent-boot-2/pom.xml @@ -25,8 +25,8 @@ import - mysql - mysql-connector-java + com.mysql + mysql-connector-j ${mysql-connector-java.version} @@ -106,7 +106,7 @@ 1.0.22.RELEASE 2.7.11 1.9.20.1 - 8.0.31 + 8.2.0 \ No newline at end of file From 882016134cf95f69e7388b4303e8f45c15414eee Mon Sep 17 00:00:00 2001 From: Harry9656 Date: Thu, 23 Nov 2023 05:20:55 +0100 Subject: [PATCH 069/228] JAVA-26765: Update persistence-modules/spring-exceptions to new mysql connector --- spring-exceptions/pom.xml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/spring-exceptions/pom.xml b/spring-exceptions/pom.xml index e0071a4206..02a531fe18 100644 --- a/spring-exceptions/pom.xml +++ b/spring-exceptions/pom.xml @@ -60,8 +60,8 @@ ${javassist.version} - mysql - mysql-connector-java + com.mysql + mysql-connector-j ${mysql-connector-java.version} runtime @@ -162,7 +162,7 @@ 3.21.0-GA 5.2.5.Final - 5.1.40 + 8.2.0 7.0.73 10.13.1.1 From 13ffae329e11628ab23d65a40e9ae37ac112832e Mon Sep 17 00:00:00 2001 From: Harry9656 Date: Thu, 23 Nov 2023 05:23:41 +0100 Subject: [PATCH 070/228] JAVA-26765: Update persistence-modules/spring-mvc-forms-jsp to new mysql connector --- spring-web-modules/spring-mvc-forms-jsp/pom.xml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/spring-web-modules/spring-mvc-forms-jsp/pom.xml b/spring-web-modules/spring-mvc-forms-jsp/pom.xml index 5096c6e23d..636551b555 100644 --- a/spring-web-modules/spring-mvc-forms-jsp/pom.xml +++ b/spring-web-modules/spring-mvc-forms-jsp/pom.xml @@ -43,8 +43,8 @@ ${jstl.version} - mysql - mysql-connector-java + com.mysql + mysql-connector-j ${mysql-connector-java.version} @@ -104,7 +104,7 @@ 8.0.1.Final 5.2.5.Final - 6.0.6 + 8.2.0 1.3.2 From 349091f9e05b26dd5f648fcf0ee33a0abc02eb5d Mon Sep 17 00:00:00 2001 From: Harry9656 Date: Thu, 23 Nov 2023 05:26:06 +0100 Subject: [PATCH 071/228] JAVA-26765: Update persistence-modules/spring-rest-testing to new mysql connector --- spring-web-modules/spring-rest-testing/pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/spring-web-modules/spring-rest-testing/pom.xml b/spring-web-modules/spring-rest-testing/pom.xml index 67b3115a6f..db1ec6c165 100644 --- a/spring-web-modules/spring-rest-testing/pom.xml +++ b/spring-web-modules/spring-rest-testing/pom.xml @@ -103,8 +103,8 @@ ${javassist.version} - mysql - mysql-connector-java + com.mysql + mysql-connector-j runtime From 4c05325ee09c976dceb48569d4c761d0dbc2b8d6 Mon Sep 17 00:00:00 2001 From: Harry9656 Date: Thu, 23 Nov 2023 05:28:20 +0100 Subject: [PATCH 072/228] JAVA-26765: Update persistence-modules/spring-rest-query-language to new mysql connector --- spring-web-modules/spring-rest-query-language/pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/spring-web-modules/spring-rest-query-language/pom.xml b/spring-web-modules/spring-rest-query-language/pom.xml index 987d678439..b44972603d 100644 --- a/spring-web-modules/spring-rest-query-language/pom.xml +++ b/spring-web-modules/spring-rest-query-language/pom.xml @@ -140,8 +140,8 @@ ${javassist.version} - mysql - mysql-connector-java + com.mysql + mysql-connector-j runtime From cf03d6e96b0311e4df08baa3def4721811d5e0de Mon Sep 17 00:00:00 2001 From: Harry9656 Date: Thu, 23 Nov 2023 05:30:32 +0100 Subject: [PATCH 073/228] JAVA-26765: Update persistence-modules/cas-secured-app to new mysql connector --- security-modules/cas/cas-secured-app/pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/security-modules/cas/cas-secured-app/pom.xml b/security-modules/cas/cas-secured-app/pom.xml index 7c4864b1c0..b5ac123b21 100644 --- a/security-modules/cas/cas-secured-app/pom.xml +++ b/security-modules/cas/cas-secured-app/pom.xml @@ -41,8 +41,8 @@ spring-boot-starter-data-jpa - mysql - mysql-connector-java + com.mysql + mysql-connector-j runtime From e4d65e524fcde125cbfdd36b3f61590b3d823dfd Mon Sep 17 00:00:00 2001 From: Harry9656 Date: Thu, 23 Nov 2023 05:38:17 +0100 Subject: [PATCH 074/228] Fix: spring-boot-mysql --- persistence-modules/spring-boot-mysql/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/persistence-modules/spring-boot-mysql/pom.xml b/persistence-modules/spring-boot-mysql/pom.xml index 5c392d2464..6c19b92314 100644 --- a/persistence-modules/spring-boot-mysql/pom.xml +++ b/persistence-modules/spring-boot-mysql/pom.xml @@ -56,7 +56,7 @@ - 8.0.23 + 8.2.0 \ No newline at end of file From 79e9818bee9d402d6815f7e97643702a7e6e7dd2 Mon Sep 17 00:00:00 2001 From: Harry9656 Date: Thu, 23 Nov 2023 06:21:19 +0100 Subject: [PATCH 075/228] JAVA-26530: Update the RectangleOverlap adding a method without borders check. --- .../rectanglesoverlap/Rectangle.java | 22 ++++++++++++++----- .../rectanglesoverlap/RectangleUnitTest.java | 17 +++++++++++++- 2 files changed, 33 insertions(+), 6 deletions(-) diff --git a/core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/rectanglesoverlap/Rectangle.java b/core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/rectanglesoverlap/Rectangle.java index 38f5edec61..ee43af3eff 100644 --- a/core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/rectanglesoverlap/Rectangle.java +++ b/core-java-modules/core-java-lang-math-2/src/main/java/com/baeldung/algorithms/rectanglesoverlap/Rectangle.java @@ -26,13 +26,25 @@ public class Rectangle { this.topRight = topRight; } - public boolean isOverlapping(Rectangle other) { - // one rectangle is to the top of the other - if (this.topRight.getY() < other.bottomLeft.getY() || this.bottomLeft.getY() > other.topRight.getY()) { + public boolean isOverlapping(Rectangle comparedRectangle) { + // one rectangle is to the top of the comparedRectangle + if (this.topRight.getY() < comparedRectangle.bottomLeft.getY() || this.bottomLeft.getY() > comparedRectangle.topRight.getY()) { return false; } - // one rectangle is to the left of the other - if (this.topRight.getX() < other.bottomLeft.getX() || this.bottomLeft.getX() > other.topRight.getX()) { + // one rectangle is to the left of the comparedRectangle + if (this.topRight.getX() < comparedRectangle.bottomLeft.getX() || this.bottomLeft.getX() > comparedRectangle.topRight.getX()) { + return false; + } + return true; + } + + public boolean isOverlappingWithoutBorders(Rectangle comparedRectangle) { + // one rectangle is to the top of the comparedRectangle + if (this.topRight.getY() <= comparedRectangle.bottomLeft.getY() || this.bottomLeft.getY() >= comparedRectangle.topRight.getY()) { + return false; + } + // one rectangle is to the left of the comparedRectangle + if (this.topRight.getX() <= comparedRectangle.bottomLeft.getX() || this.bottomLeft.getX() >= comparedRectangle.topRight.getX()) { return false; } return true; diff --git a/core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/algorithms/rectanglesoverlap/RectangleUnitTest.java b/core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/algorithms/rectanglesoverlap/RectangleUnitTest.java index e4bb614b48..18186b43b1 100644 --- a/core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/algorithms/rectanglesoverlap/RectangleUnitTest.java +++ b/core-java-modules/core-java-lang-math-2/src/test/java/com/baeldung/algorithms/rectanglesoverlap/RectangleUnitTest.java @@ -1,7 +1,8 @@ package com.baeldung.algorithms.rectanglesoverlap; -import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + import org.junit.Test; public class RectangleUnitTest { @@ -36,4 +37,18 @@ public class RectangleUnitTest { assertFalse(rectangle1.isOverlapping(rectangle2)); } + @Test + public void givenAdjacentRectangles_whensOverlappingCalled_shouldReturnTrue() { +Rectangle rectangle1 = new Rectangle(new Point(0, 0), new Point(5, 14)); +Rectangle rectangle2 = new Rectangle(new Point(5, 0), new Point(17, 14)); +assertTrue(rectangle1.isOverlapping(rectangle2)); + } + + @Test + public void givenAdjacentRectangles_whensOverlappingWithoutBordersCalled_shouldReturnFalse() { + Rectangle rectangle1 = new Rectangle(new Point(0, 0), new Point(5, 14)); + Rectangle rectangle2 = new Rectangle(new Point(5, 0), new Point(17, 14)); + assertFalse(rectangle1.isOverlappingWithoutBorders(rectangle2)); + } + } From 81fe96721a53dff2a8c3ecc28ba53984bb98fd16 Mon Sep 17 00:00:00 2001 From: Kai Yuan Date: Thu, 23 Nov 2023 13:03:09 +0100 Subject: [PATCH 076/228] [negate-int] negate an int in java --- .../baeldung/negate/NegateIntUnitTest.java | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/negate/NegateIntUnitTest.java diff --git a/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/negate/NegateIntUnitTest.java b/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/negate/NegateIntUnitTest.java new file mode 100644 index 0000000000..15fffde6ed --- /dev/null +++ b/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/negate/NegateIntUnitTest.java @@ -0,0 +1,62 @@ +package com.baeldung.negate; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +public class NegateIntUnitTest { + @Test + void whenUsingUnaryMinusOperator_thenGetExpectedResult() { + int x = 42; + assertEquals(-42, -x); + + int z = 0; + assertEquals(0, -z); + + int n = -42; + assertEquals(42, -n); + } + + @Test + void whenUsingBitwiseComplementOperator_thenGetExpectedResult() { + int x = 42; + assertEquals(-42, ~x + 1); + + int z = 0; + assertEquals(0, ~z + 1); + + int n = -42; + assertEquals(42, ~n + 1); + } + + @Test + void whenUsingUnaryMinusOperatorWithMinInt_thenCannotGetExpectedResult() { + int min = Integer.MIN_VALUE; + System.out.println("The value of '-min' is: " + -min); + assertFalse((-min) > 0); + } + + @Test + void whenUsingBitwiseComplementOperatorWithMinInt_thenCannotGetExpectedResult() { + int min = Integer.MIN_VALUE; + int result = ~min + 1; + System.out.println("The value of '~min + 1' is: " + result); + assertFalse(result > 0); + } + + + @Test + void whenUsingUnaryMinusOperatorWithMinInt_thenGetExpectedResult() { + int x = 42; + assertEquals(-42, Math.negateExact(x)); + + int z = 0; + assertEquals(0, Math.negateExact(z)); + + int n = -42; + assertEquals(42, Math.negateExact(n)); + + int min = Integer.MIN_VALUE; + assertThrowsExactly(ArithmeticException.class, () -> Math.negateExact(min)); + } +} \ No newline at end of file From 8d440a419b62770092e4a0a4082763f2031b8609 Mon Sep 17 00:00:00 2001 From: parthiv39731 <70740707+parthiv39731@users.noreply.github.com> Date: Thu, 23 Nov 2023 21:26:53 +0530 Subject: [PATCH 077/228] BAEL-7200 fixed formatting. Used default intellij formatting for Fluent API style. --- .../modifyrequest/EscapeHtmlAspectIntegrationTest.java | 8 ++++---- .../modifyrequest/EscapeHtmlFilterIntegrationTest.java | 8 ++++---- .../EscapeHtmlInterceptorIntegrationTest.java | 6 +++--- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/modifyrequest/EscapeHtmlAspectIntegrationTest.java b/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/modifyrequest/EscapeHtmlAspectIntegrationTest.java index 665733c61b..12520b7e67 100644 --- a/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/modifyrequest/EscapeHtmlAspectIntegrationTest.java +++ b/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/modifyrequest/EscapeHtmlAspectIntegrationTest.java @@ -44,9 +44,9 @@ public class EscapeHtmlAspectIntegrationTest { ObjectMapper objectMapper = new ObjectMapper(); mockMvc.perform(MockMvcRequestBuilders.post(URI.create("/save")) - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(requestBody))) - .andExpect(MockMvcResultMatchers.status().isCreated()) - .andExpect(MockMvcResultMatchers.content().json(objectMapper.writeValueAsString(expectedResponseBody))); + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(requestBody))) + .andExpect(MockMvcResultMatchers.status().isCreated()) + .andExpect(MockMvcResultMatchers.content().json(objectMapper.writeValueAsString(expectedResponseBody))); } } diff --git a/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/modifyrequest/EscapeHtmlFilterIntegrationTest.java b/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/modifyrequest/EscapeHtmlFilterIntegrationTest.java index 35254eb151..3ab7618b05 100644 --- a/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/modifyrequest/EscapeHtmlFilterIntegrationTest.java +++ b/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/modifyrequest/EscapeHtmlFilterIntegrationTest.java @@ -43,9 +43,9 @@ public class EscapeHtmlFilterIntegrationTest { ObjectMapper objectMapper = new ObjectMapper(); mockMvc.perform(MockMvcRequestBuilders.post(URI.create("/save")) - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(requestBody))) - .andExpect(MockMvcResultMatchers.status().isCreated()) - .andExpect(MockMvcResultMatchers.content().json(objectMapper.writeValueAsString(expectedResponseBody))); + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(requestBody))) + .andExpect(MockMvcResultMatchers.status().isCreated()) + .andExpect(MockMvcResultMatchers.content().json(objectMapper.writeValueAsString(expectedResponseBody))); } } diff --git a/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/modifyrequest/EscapeHtmlInterceptorIntegrationTest.java b/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/modifyrequest/EscapeHtmlInterceptorIntegrationTest.java index 002481de4f..d855339bd9 100644 --- a/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/modifyrequest/EscapeHtmlInterceptorIntegrationTest.java +++ b/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/modifyrequest/EscapeHtmlInterceptorIntegrationTest.java @@ -39,8 +39,8 @@ public class EscapeHtmlInterceptorIntegrationTest { ObjectMapper objectMapper = new ObjectMapper(); mockMvc.perform(MockMvcRequestBuilders.post(URI.create("/save")) - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(requestBody))) - .andExpect(MockMvcResultMatchers.status().is4xxClientError()); + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(requestBody))) + .andExpect(MockMvcResultMatchers.status().is4xxClientError()); } } From 6e11ac36a26a1ee5e67bdad3285b58da4589944a Mon Sep 17 00:00:00 2001 From: Harpal Singh Date: Thu, 23 Nov 2023 18:45:27 +0100 Subject: [PATCH 078/228] JAVA-26765: Remove unwanted spaces from bookstore-monolith --- jhipster-6/bookstore-monolith/pom.xml | 66 +++++++++++++-------------- 1 file changed, 33 insertions(+), 33 deletions(-) diff --git a/jhipster-6/bookstore-monolith/pom.xml b/jhipster-6/bookstore-monolith/pom.xml index 2a5368c9ac..efe3d2a118 100644 --- a/jhipster-6/bookstore-monolith/pom.xml +++ b/jhipster-6/bookstore-monolith/pom.xml @@ -90,10 +90,10 @@ io.springfox springfox-bean-validators - - - - + + + + com.zaxxer HikariCP @@ -136,10 +136,10 @@ net.logstash.logback logstash-logback-encoder - - - - + + + + org.mapstruct mapstruct @@ -423,28 +423,28 @@ jib-maven-plugin ${jib-maven-plugin.version} - - openjdk:8-jre-alpine - - - bookstore:latest - - - - sh - - chmod +x /entrypoint.sh && sync && /entrypoint.sh - - - 8080 - - - ALWAYS - 0 - - true - - + + openjdk:8-jre-alpine + + + bookstore:latest + + + + sh + + chmod +x /entrypoint.sh && sync && /entrypoint.sh + + + 8080 + + + ALWAYS + 0 + + true + + org.liquibase @@ -1137,9 +1137,9 @@ jdt_apt false - - - + + + 3.0.1 From 60e843aa61af674f968c6bcaa4cbd16bde97009f Mon Sep 17 00:00:00 2001 From: Harpal Singh Date: Thu, 23 Nov 2023 20:59:14 +0100 Subject: [PATCH 079/228] JAVA-26771: Update core-java-string-operations-7 liquibase-core to 4.25.0 --- core-java-modules/core-java-string-operations-7/pom.xml | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/core-java-modules/core-java-string-operations-7/pom.xml b/core-java-modules/core-java-string-operations-7/pom.xml index a2c7036e34..33a74365bc 100644 --- a/core-java-modules/core-java-string-operations-7/pom.xml +++ b/core-java-modules/core-java-string-operations-7/pom.xml @@ -24,12 +24,6 @@ commons-text ${commons-text.version} - - org.liquibase - liquibase-core - 4.9.1 - test - org.junit.jupiter junit-jupiter @@ -39,7 +33,7 @@ org.liquibase liquibase-core - 4.9.1 + ${liquibase.core.version} test @@ -67,6 +61,7 @@ 11 3.13.0 1.10.0 + 4.25.0 \ No newline at end of file From 851975605c2fa33e3fa113e9ac6ad008294d7aec Mon Sep 17 00:00:00 2001 From: Harpal Singh Date: Thu, 23 Nov 2023 21:06:52 +0100 Subject: [PATCH 080/228] JAVA-26771: Update quarkus-extension liquibase-core to 4.25.0 --- .../quarkus-extension/quarkus-liquibase/runtime/pom.xml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/quarkus-modules/quarkus-extension/quarkus-liquibase/runtime/pom.xml b/quarkus-modules/quarkus-extension/quarkus-liquibase/runtime/pom.xml index 95916932a1..f1fe9eec5c 100644 --- a/quarkus-modules/quarkus-extension/quarkus-liquibase/runtime/pom.xml +++ b/quarkus-modules/quarkus-extension/quarkus-liquibase/runtime/pom.xml @@ -66,8 +66,7 @@ - 3.8.1 - 3.8.1 + 4.25.0 \ No newline at end of file From bb7481a27ac57dcb37806b88815215a365fa9648 Mon Sep 17 00:00:00 2001 From: Harpal Singh Date: Thu, 23 Nov 2023 21:07:17 +0100 Subject: [PATCH 081/228] JAVA-26771: Update persistence-modules/liquibase liquibase-maven-plugin to 4.25.0 --- persistence-modules/liquibase/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/persistence-modules/liquibase/pom.xml b/persistence-modules/liquibase/pom.xml index 2fc5803037..f822c5b320 100644 --- a/persistence-modules/liquibase/pom.xml +++ b/persistence-modules/liquibase/pom.xml @@ -37,7 +37,7 @@ 5.1.6 - 3.4.2 + 4.25.0 \ No newline at end of file From 4f960b65795e16fd29a0dc787453f4c041d436e8 Mon Sep 17 00:00:00 2001 From: Harpal Singh Date: Thu, 23 Nov 2023 21:52:20 +0100 Subject: [PATCH 082/228] JAVA-26771: Fix test core-java-string-operations-7 --- .../java/com/baeldung/centertext/CenteringTextUnitTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/centertext/CenteringTextUnitTest.java b/core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/centertext/CenteringTextUnitTest.java index a3f95b0181..408d7b1a63 100644 --- a/core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/centertext/CenteringTextUnitTest.java +++ b/core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/centertext/CenteringTextUnitTest.java @@ -1,6 +1,6 @@ package com.baeldung.centertext; -import liquibase.repackaged.org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.StringUtils; import org.junit.Assert; import org.junit.jupiter.api.Test; From 179e6e5de26ec55ccbd3dc8194c15f76575bc349 Mon Sep 17 00:00:00 2001 From: Harpal Singh Date: Fri, 24 Nov 2023 00:13:52 +0100 Subject: [PATCH 083/228] JAVA-26765: Remove unwanted spaces from xml --- patterns-modules/design-patterns-architectural/pom.xml | 4 ++-- persistence-modules/activejdbc/pom.xml | 4 ++-- persistence-modules/core-java-persistence/pom.xml | 4 ++-- persistence-modules/hibernate-libraries/pom.xml | 4 ++-- persistence-modules/spring-data-jpa-repo/pom.xml | 4 ++-- persistence-modules/spring-data-rest-querydsl/pom.xml | 4 ++-- persistence-modules/spring-hibernate-6/pom.xml | 4 ++-- persistence-modules/spring-jdbc/pom.xml | 4 ++-- persistence-modules/spring-jpa/pom.xml | 4 ++-- spring-boot-modules/spring-boot-data-3/pom.xml | 4 ++-- spring-cloud-modules/spring-cloud-aws/pom.xml | 4 ++-- .../spring-cloud-task/springcloudtaskbatch/pom.xml | 4 ++-- spring-cloud-modules/spring-cloud-vault/pom.xml | 4 ++-- spring-security-modules/spring-security-web-boot-1/pom.xml | 4 ++-- spring-security-modules/spring-security-web-boot-2/pom.xml | 4 ++-- web-modules/java-lite/pom.xml | 4 ++-- web-modules/vraptor/pom.xml | 4 ++-- 17 files changed, 34 insertions(+), 34 deletions(-) diff --git a/patterns-modules/design-patterns-architectural/pom.xml b/patterns-modules/design-patterns-architectural/pom.xml index addcdfe390..20f320f073 100644 --- a/patterns-modules/design-patterns-architectural/pom.xml +++ b/patterns-modules/design-patterns-architectural/pom.xml @@ -1,7 +1,7 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 design-patterns-architectural 1.0 diff --git a/persistence-modules/activejdbc/pom.xml b/persistence-modules/activejdbc/pom.xml index 602235b892..e41af5c64b 100644 --- a/persistence-modules/activejdbc/pom.xml +++ b/persistence-modules/activejdbc/pom.xml @@ -1,7 +1,7 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 activejdbc 1.0-SNAPSHOT diff --git a/persistence-modules/core-java-persistence/pom.xml b/persistence-modules/core-java-persistence/pom.xml index e0300f5b9c..5d5c36ef01 100644 --- a/persistence-modules/core-java-persistence/pom.xml +++ b/persistence-modules/core-java-persistence/pom.xml @@ -1,7 +1,7 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung.core-java-persistence core-java-persistence diff --git a/persistence-modules/hibernate-libraries/pom.xml b/persistence-modules/hibernate-libraries/pom.xml index 15292689eb..5b1879b78e 100644 --- a/persistence-modules/hibernate-libraries/pom.xml +++ b/persistence-modules/hibernate-libraries/pom.xml @@ -1,7 +1,7 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 hibernate-libraries 0.0.1-SNAPSHOT diff --git a/persistence-modules/spring-data-jpa-repo/pom.xml b/persistence-modules/spring-data-jpa-repo/pom.xml index debf9690f6..1c58b5afa5 100644 --- a/persistence-modules/spring-data-jpa-repo/pom.xml +++ b/persistence-modules/spring-data-jpa-repo/pom.xml @@ -1,7 +1,7 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-data-jpa-repo spring-data-jpa-repo diff --git a/persistence-modules/spring-data-rest-querydsl/pom.xml b/persistence-modules/spring-data-rest-querydsl/pom.xml index 89db7d24a5..0fe9d381cf 100644 --- a/persistence-modules/spring-data-rest-querydsl/pom.xml +++ b/persistence-modules/spring-data-rest-querydsl/pom.xml @@ -1,7 +1,7 @@ + xmlns="http://maven.apache.org/POM/4.0.0" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-data-rest-querydsl 1.0 diff --git a/persistence-modules/spring-hibernate-6/pom.xml b/persistence-modules/spring-hibernate-6/pom.xml index f3ea82dfad..3cd69a963e 100644 --- a/persistence-modules/spring-hibernate-6/pom.xml +++ b/persistence-modules/spring-hibernate-6/pom.xml @@ -1,7 +1,7 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-hibernate-6 0.1-SNAPSHOT diff --git a/persistence-modules/spring-jdbc/pom.xml b/persistence-modules/spring-jdbc/pom.xml index 1aa9f4f851..1cf4c141b3 100644 --- a/persistence-modules/spring-jdbc/pom.xml +++ b/persistence-modules/spring-jdbc/pom.xml @@ -1,7 +1,7 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-jdbc spring-jdbc diff --git a/persistence-modules/spring-jpa/pom.xml b/persistence-modules/spring-jpa/pom.xml index 91766318e6..61950d9c93 100644 --- a/persistence-modules/spring-jpa/pom.xml +++ b/persistence-modules/spring-jpa/pom.xml @@ -1,7 +1,7 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-jpa 0.1-SNAPSHOT diff --git a/spring-boot-modules/spring-boot-data-3/pom.xml b/spring-boot-modules/spring-boot-data-3/pom.xml index 7c0f4b3ffd..4afafe3c19 100644 --- a/spring-boot-modules/spring-boot-data-3/pom.xml +++ b/spring-boot-modules/spring-boot-data-3/pom.xml @@ -1,7 +1,7 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung spring-boot-data-3 diff --git a/spring-cloud-modules/spring-cloud-aws/pom.xml b/spring-cloud-modules/spring-cloud-aws/pom.xml index 328ddd50de..3de0c7146a 100644 --- a/spring-cloud-modules/spring-cloud-aws/pom.xml +++ b/spring-cloud-modules/spring-cloud-aws/pom.xml @@ -1,7 +1,7 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung.spring.cloud spring-cloud-aws diff --git a/spring-cloud-modules/spring-cloud-task/springcloudtaskbatch/pom.xml b/spring-cloud-modules/spring-cloud-task/springcloudtaskbatch/pom.xml index f7c13e881f..53bc37212c 100644 --- a/spring-cloud-modules/spring-cloud-task/springcloudtaskbatch/pom.xml +++ b/spring-cloud-modules/spring-cloud-task/springcloudtaskbatch/pom.xml @@ -1,7 +1,7 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung.cloud springcloudtaskbatch diff --git a/spring-cloud-modules/spring-cloud-vault/pom.xml b/spring-cloud-modules/spring-cloud-vault/pom.xml index 58a28bdf5a..1698b1f357 100644 --- a/spring-cloud-modules/spring-cloud-vault/pom.xml +++ b/spring-cloud-modules/spring-cloud-vault/pom.xml @@ -1,7 +1,7 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung.spring.cloud spring-cloud-vault diff --git a/spring-security-modules/spring-security-web-boot-1/pom.xml b/spring-security-modules/spring-security-web-boot-1/pom.xml index baa9f8e1e5..e93b0b4f03 100644 --- a/spring-security-modules/spring-security-web-boot-1/pom.xml +++ b/spring-security-modules/spring-security-web-boot-1/pom.xml @@ -1,7 +1,7 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-security-web-boot-1 0.0.1-SNAPSHOT diff --git a/spring-security-modules/spring-security-web-boot-2/pom.xml b/spring-security-modules/spring-security-web-boot-2/pom.xml index 7dcba3cd3e..d3684dd282 100644 --- a/spring-security-modules/spring-security-web-boot-2/pom.xml +++ b/spring-security-modules/spring-security-web-boot-2/pom.xml @@ -1,7 +1,7 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-security-web-boot-2 0.0.1-SNAPSHOT diff --git a/web-modules/java-lite/pom.xml b/web-modules/java-lite/pom.xml index 024d38420e..be079d484e 100644 --- a/web-modules/java-lite/pom.xml +++ b/web-modules/java-lite/pom.xml @@ -1,7 +1,7 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 org.baeldung java-lite diff --git a/web-modules/vraptor/pom.xml b/web-modules/vraptor/pom.xml index b26a29e004..d952cd71e5 100644 --- a/web-modules/vraptor/pom.xml +++ b/web-modules/vraptor/pom.xml @@ -1,7 +1,7 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 vraptor vraptor From c519d2be47c15ecad61d3f9e21b3e198c565d352 Mon Sep 17 00:00:00 2001 From: michaelin007 Date: Fri, 24 Nov 2023 09:35:01 +0000 Subject: [PATCH 084/228] https://jira.baeldung.com/browse/BAEL-7268 --- .../baeldung/unixtime/UnixTimeUnitTest.java | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/unixtime/UnixTimeUnitTest.java diff --git a/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/unixtime/UnixTimeUnitTest.java b/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/unixtime/UnixTimeUnitTest.java new file mode 100644 index 0000000000..d1518ceef5 --- /dev/null +++ b/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/unixtime/UnixTimeUnitTest.java @@ -0,0 +1,50 @@ +package com.baeldung.unixtime; + + +import static org.junit.Assert.assertEquals; + +import java.time.Instant; +import java.util.Date; + +import org.joda.time.DateTime; +import org.joda.time.DateTimeZone; +import org.junit.jupiter.api.Test; + +public class UnixTimeUnitTest { + + @Test + public void givenCurrentTimeUsingDateApi_whenConvertedToUnixTime_thenConsistent() { + long marginOfError = 1L; + Date date = new Date(); + long longTime = date.getTime() / 1000L; + + for (int i = 0; i < 10; i++) { + long unixTime = System.currentTimeMillis() / 1000L; + assertEquals(longTime, unixTime, marginOfError); + } + } + + @Test + public void givenCurrentTimeUsingInstantNow_whenConvertedToUnixTime_thenConsistent() { + long marginOfError = 1L; + long longTime = Instant.now().getEpochSecond(); + + for (int i = 0; i < 10; i++) { + long unixTime = System.currentTimeMillis() / 1000L; + assertEquals(longTime, unixTime, marginOfError); + } + } + + @Test + public void givenCurrentTimeUsingJodaTime_whenConvertedToUnixTime_thenConsistent() { + long marginOfError = 1L; + DateTime dateTime = DateTime.now(DateTimeZone.UTC); + long longTime = dateTime.getMillis() / 1000L; + + for (int i = 0; i < 10; i++) { + long unixTime = System.currentTimeMillis() / 1000L; + assertEquals(longTime, unixTime, marginOfError); + } + } + +} From 4e28968b06a6990392971c89717c518882e0d626 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Fri, 24 Nov 2023 21:12:43 +0800 Subject: [PATCH 085/228] Update README.md [skip ci] --- core-java-modules/core-java-concurrency-advanced-5/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-concurrency-advanced-5/README.md b/core-java-modules/core-java-concurrency-advanced-5/README.md index ba845a7c4b..d991b6cc34 100644 --- a/core-java-modules/core-java-concurrency-advanced-5/README.md +++ b/core-java-modules/core-java-concurrency-advanced-5/README.md @@ -1,3 +1,4 @@ ### Relevant Articles: - [Why wait() Requires Synchronization?](https://www.baeldung.com/java-wait-necessary-synchronization) +- [Working with Exceptions in Java CompletableFuture](https://www.baeldung.com/java-exceptions-completablefuture) From 9b36358c6c4405aabeaa8bb8f209cef647e508fe Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Fri, 24 Nov 2023 21:18:13 +0800 Subject: [PATCH 086/228] Update README.md [skip ci] --- spring-kafka-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-kafka-2/README.md b/spring-kafka-2/README.md index 43b2f59147..250927314c 100644 --- a/spring-kafka-2/README.md +++ b/spring-kafka-2/README.md @@ -9,3 +9,4 @@ This module contains articles about Spring with Kafka - [Understanding Kafka Topics and Partitions](https://www.baeldung.com/kafka-topics-partitions) - [How to Subscribe a Kafka Consumer to Multiple Topics](https://www.baeldung.com/kafka-subscribe-consumer-multiple-topics) - [Splitting Streams in Kafka](https://www.baeldung.com/kafka-splitting-streams) +- [Manage Kafka Consumer Groups](https://www.baeldung.com/kafka-manage-consumer-groups) From 33c1b23627c9a8b5f3db4643d36384e8ce95e948 Mon Sep 17 00:00:00 2001 From: mikr Date: Fri, 24 Nov 2023 14:20:26 +0100 Subject: [PATCH 087/228] Update readme --- core-java-modules/core-java-collections-maps-7/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-collections-maps-7/README.md b/core-java-modules/core-java-collections-maps-7/README.md index a62bdda7af..c9f39dd2fa 100644 --- a/core-java-modules/core-java-collections-maps-7/README.md +++ b/core-java-modules/core-java-collections-maps-7/README.md @@ -4,4 +4,5 @@ - [How to Write Hashmap to CSV File](https://www.baeldung.com/java-write-hashmap-csv) - [How to Get First or Last Entry From a LinkedHashMap in Java](https://www.baeldung.com/java-linkedhashmap-first-last-key-value-pair) - [How to Write and Read a File with a Java HashMap](https://www.baeldung.com/java-hashmap-write-read-file) +- [Limiting the Max Size of a HashMap in Java](https://www.baeldung.com/java-hashmap-max-size) - More articles: [[<-- prev]](/core-java-modules/core-java-collections-maps-6) \ No newline at end of file From 6ced5e2c2f8a616d64c6b820ce98d9c170ae8254 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Fri, 24 Nov 2023 21:22:32 +0800 Subject: [PATCH 088/228] Update README.md [skip ci] --- core-java-modules/core-java-datetime-conversion/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-datetime-conversion/README.md b/core-java-modules/core-java-datetime-conversion/README.md index d3a3dae728..c7ba333222 100644 --- a/core-java-modules/core-java-datetime-conversion/README.md +++ b/core-java-modules/core-java-datetime-conversion/README.md @@ -10,3 +10,4 @@ This module contains articles about converting between Java date and time object - [Convert Between LocalDateTime and ZonedDateTime](https://www.baeldung.com/java-localdatetime-zoneddatetime) - [Conversion From 12-Hour Time to 24-Hour Time in Java](https://www.baeldung.com/java-convert-time-format) - [Convert Epoch Time to LocalDate and LocalDateTime](https://www.baeldung.com/java-convert-epoch-localdate) +- [Convert Timestamp String to Long in Java](https://www.baeldung.com/java-convert-timestamp-string-long) From 8b481ed4d43f30989352bee13b19761fa982d948 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Fri, 24 Nov 2023 21:27:11 +0800 Subject: [PATCH 089/228] Update README.md [skip ci] --- core-java-modules/core-java-collections-5/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-collections-5/README.md b/core-java-modules/core-java-collections-5/README.md index acee8154f7..c9fce58ac2 100644 --- a/core-java-modules/core-java-collections-5/README.md +++ b/core-java-modules/core-java-collections-5/README.md @@ -10,4 +10,5 @@ - [Remove Elements From a Queue Using Loop](https://www.baeldung.com/java-remove-elements-queue) - [Intro to Vector Class in Java](https://www.baeldung.com/java-vector-guide) - [HashSet toArray() Method in Java](https://www.baeldung.com/java-hashset-toarray) +- [Time Complexity of Java Collections Sort in Java](https://www.baeldung.com/java-time-complexity-collections-sort) - More articles: [[<-- prev]](/core-java-modules/core-java-collections-4) From ba158d4e7bc459c57a690f6687c14299b5e8ae08 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Fri, 24 Nov 2023 21:31:16 +0800 Subject: [PATCH 090/228] Update README.md [skip ci] --- xml-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/xml-2/README.md b/xml-2/README.md index e9c1a07586..a6762f2840 100644 --- a/xml-2/README.md +++ b/xml-2/README.md @@ -9,3 +9,4 @@ This module contains articles about eXtensible Markup Language (XML) - [Converting JSON to XML in Java](https://www.baeldung.com/java-convert-json-to-xml) - [Convert an XML Object to a String in Java](https://www.baeldung.com/java-convert-xml-object-string) - [Convert String Containing XML to org.w3c.dom.Document](https://www.baeldung.com/java-convert-string-xml-dom) +- [How to Parse XML to HashMap in Java](https://www.baeldung.com/java-xml-read-into-hashmap) From a4c30e423d457ed41b1180a5f8d87a0b75b26154 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Fri, 24 Nov 2023 21:35:59 +0800 Subject: [PATCH 091/228] Update README.md [skip ci] --- core-java-modules/core-java-string-operations-7/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-string-operations-7/README.md b/core-java-modules/core-java-string-operations-7/README.md index 2b9c4c25f3..a05485ccb9 100644 --- a/core-java-modules/core-java-string-operations-7/README.md +++ b/core-java-modules/core-java-string-operations-7/README.md @@ -5,3 +5,4 @@ - [Check if a String Contains Only Unicode Letters](https://www.baeldung.com/java-string-all-unicode-characters) - [Create a Mutable String in Java](https://www.baeldung.com/java-mutable-string) - [Check if a String Contains a Number Value in Java](https://www.baeldung.com/java-string-number-presence) +- [Difference Between String isEmpty() and isBlank()](https://www.baeldung.com/java-string-isempty-vs-isblank) From 9d20500b64b71bfac5a48c85bc416c539050037f Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Fri, 24 Nov 2023 21:38:30 +0800 Subject: [PATCH 092/228] Update README.md [skip ci] --- testing-modules/testing-assertions/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/testing-modules/testing-assertions/README.md b/testing-modules/testing-assertions/README.md index 8f94277791..3e529bc1d3 100644 --- a/testing-modules/testing-assertions/README.md +++ b/testing-modules/testing-assertions/README.md @@ -6,3 +6,4 @@ - [Assert That an Object Is From a Specific Type](https://www.baeldung.com/java-assert-object-of-type) - [Asserting Equality on Two Classes Without an equals() Method](https://www.baeldung.com/java-assert-equality-no-equals) - [Assert Regex Matches in JUnit](https://www.baeldung.com/junit-assert-regex-matches) +- [Asserting Nested Map With JUnit](https://www.baeldung.com/junit-assert-nested-map) From 9b63e853fde797fd85674741aca438156b652003 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Fri, 24 Nov 2023 21:40:18 +0800 Subject: [PATCH 093/228] Update README.md [skip ci] --- core-java-modules/core-java-17/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-17/README.md b/core-java-modules/core-java-17/README.md index 4b1125532d..44a4e760e1 100644 --- a/core-java-modules/core-java-17/README.md +++ b/core-java-modules/core-java-17/README.md @@ -9,3 +9,4 @@ - [Migrate From Java 8 to Java 17](https://www.baeldung.com/java-migrate-8-to-17) - [Format Multiple ‘or’ Conditions in an If Statement in Java](https://www.baeldung.com/java-multiple-or-conditions-if-statement) - [Get All Record Fields and Its Values via Reflection](https://www.baeldung.com/java-reflection-record-fields-values) +- [Context-Specific Deserialization Filters in Java 17](https://www.baeldung.com/java-context-specific-deserialization-filters) From 8cccab08767dac451209f87da3f84a0d4bc9844a Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Fri, 24 Nov 2023 21:46:06 +0800 Subject: [PATCH 094/228] Update README.md [skip ci] --- spring-di-4/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-di-4/README.md b/spring-di-4/README.md index 8e73aff437..bed8b5a78d 100644 --- a/spring-di-4/README.md +++ b/spring-di-4/README.md @@ -7,4 +7,5 @@ This module contains articles about dependency injection with Spring - [Using @Autowired in Abstract Classes](https://www.baeldung.com/spring-autowired-abstract-class) - [Spring @Component Annotation](https://www.baeldung.com/spring-component-annotation) - [Why Is Field Injection Not Recommended?](https://www.baeldung.com/java-spring-field-injection-cons) +- [Setting a Spring Bean to Null](https://www.baeldung.com/spring-setting-bean-null) - More articles: [[<-- prev]](../spring-di-3) From f52997ad42f4e7583406226d96808693c3b8d730 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Fri, 24 Nov 2023 21:53:03 +0800 Subject: [PATCH 095/228] Update README.md [skip ci] --- core-java-modules/core-java-lang-oop-types-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-lang-oop-types-2/README.md b/core-java-modules/core-java-lang-oop-types-2/README.md index f46a1a3306..208e3b7fa7 100644 --- a/core-java-modules/core-java-lang-oop-types-2/README.md +++ b/core-java-modules/core-java-lang-oop-types-2/README.md @@ -10,3 +10,4 @@ This module contains articles about types in Java - [Filling a List With All Enum Values in Java](https://www.baeldung.com/java-enum-values-to-list) - [Comparing a String to an Enum Value in Java](https://www.baeldung.com/java-comparing-string-to-enum) - [Implementing toString() on enums in Java](https://www.baeldung.com/java-enums-tostring) +- [Checking if an Object’s Type Is Enum](https://www.baeldung.com/java-check-object-enum) From 39a7c066059b7db29fb75b98a5cc03a6d7843b5b Mon Sep 17 00:00:00 2001 From: Geoffrey De Smet Date: Fri, 24 Nov 2023 15:08:56 +0100 Subject: [PATCH 096/228] Remove commetn blocks Co-authored-by: Liam Williams --- .../src/main/java/com/baeldung/timefoldsolver/Shift.java | 4 ---- 1 file changed, 4 deletions(-) diff --git a/timefold-solver/src/main/java/com/baeldung/timefoldsolver/Shift.java b/timefold-solver/src/main/java/com/baeldung/timefoldsolver/Shift.java index 04087134c6..9c7b663ecd 100644 --- a/timefold-solver/src/main/java/com/baeldung/timefoldsolver/Shift.java +++ b/timefold-solver/src/main/java/com/baeldung/timefoldsolver/Shift.java @@ -34,10 +34,6 @@ public class Shift { return start + " - " + end; } - // ************************************************************************ - // Getters and setters - // ************************************************************************ - public LocalDateTime getStart() { return start; } From 8e8331376ef326e5efc059a804373beb9b5311de Mon Sep 17 00:00:00 2001 From: Geoffrey De Smet Date: Fri, 24 Nov 2023 15:09:03 +0100 Subject: [PATCH 097/228] Remove commetn blocks Co-authored-by: Liam Williams --- .../src/main/java/com/baeldung/timefoldsolver/Employee.java | 4 ---- 1 file changed, 4 deletions(-) diff --git a/timefold-solver/src/main/java/com/baeldung/timefoldsolver/Employee.java b/timefold-solver/src/main/java/com/baeldung/timefoldsolver/Employee.java index c755896201..ef4752a8c6 100644 --- a/timefold-solver/src/main/java/com/baeldung/timefoldsolver/Employee.java +++ b/timefold-solver/src/main/java/com/baeldung/timefoldsolver/Employee.java @@ -17,10 +17,6 @@ public class Employee { return name; } - // ************************************************************************ - // Getters and setters - // ************************************************************************ - public String getName() { return name; } From 2478475ceae6da380542501956604ff65fc88cd6 Mon Sep 17 00:00:00 2001 From: Geoffrey De Smet Date: Fri, 24 Nov 2023 15:09:14 +0100 Subject: [PATCH 098/228] Remove comment blocks Co-authored-by: Liam Williams --- .../main/java/com/baeldung/timefoldsolver/ShiftSchedule.java | 4 ---- 1 file changed, 4 deletions(-) diff --git a/timefold-solver/src/main/java/com/baeldung/timefoldsolver/ShiftSchedule.java b/timefold-solver/src/main/java/com/baeldung/timefoldsolver/ShiftSchedule.java index 85abc8eb66..7794d46a28 100644 --- a/timefold-solver/src/main/java/com/baeldung/timefoldsolver/ShiftSchedule.java +++ b/timefold-solver/src/main/java/com/baeldung/timefoldsolver/ShiftSchedule.java @@ -28,10 +28,6 @@ public class ShiftSchedule { this.shifts = shifts; } - // ************************************************************************ - // Getters and setters - // ************************************************************************ - public List getEmployees() { return employees; } From 464bf4cda6c028505aaa357afa0d8c5454b9e093 Mon Sep 17 00:00:00 2001 From: Geoffrey De Smet Date: Fri, 24 Nov 2023 15:12:23 +0100 Subject: [PATCH 099/228] Fields default to null. Co-authored-by: Liam Williams --- .../main/java/com/baeldung/timefoldsolver/ShiftSchedule.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/timefold-solver/src/main/java/com/baeldung/timefoldsolver/ShiftSchedule.java b/timefold-solver/src/main/java/com/baeldung/timefoldsolver/ShiftSchedule.java index 7794d46a28..794c31e5b7 100644 --- a/timefold-solver/src/main/java/com/baeldung/timefoldsolver/ShiftSchedule.java +++ b/timefold-solver/src/main/java/com/baeldung/timefoldsolver/ShiftSchedule.java @@ -17,7 +17,7 @@ public class ShiftSchedule { private List shifts; @PlanningScore - private HardSoftScore score = null; + private HardSoftScore score; // A no-arg constructor is required for @PlanningSolution annotated classes public ShiftSchedule() { From a2acd64779fbcea91a52fb97d52e98ecd8fdf07f Mon Sep 17 00:00:00 2001 From: Harry9656 Date: Fri, 24 Nov 2023 16:58:47 +0100 Subject: [PATCH 100/228] =?UTF-8?q?JAVA-26727:=20Update=20the=20resilience?= =?UTF-8?q?4j-timelimiter=C2=A0library=20(#15277)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * JAVA-26727: Update libraries-6 to a new version of resilience4j dependencies. * JAVA-26727: Update spring-rest-http-2 to a new version of resilience4j dependencies. --- libraries-6/pom.xml | 2 +- .../java/com/baeldung/resilence4j/Resilience4jUnitTest.java | 4 ++-- spring-web-modules/spring-rest-http-2/pom.xml | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/libraries-6/pom.xml b/libraries-6/pom.xml index 9fa44d3a32..f073ca424c 100644 --- a/libraries-6/pom.xml +++ b/libraries-6/pom.xml @@ -197,7 +197,7 @@ 1.10.0 2.7.1 4.8.1 - 0.12.1 + 2.1.0 1.15 3.6 3.5-beta72 diff --git a/libraries-6/src/test/java/com/baeldung/resilence4j/Resilience4jUnitTest.java b/libraries-6/src/test/java/com/baeldung/resilence4j/Resilience4jUnitTest.java index 1d69d20bc2..ab4d9dde40 100644 --- a/libraries-6/src/test/java/com/baeldung/resilence4j/Resilience4jUnitTest.java +++ b/libraries-6/src/test/java/com/baeldung/resilence4j/Resilience4jUnitTest.java @@ -43,7 +43,7 @@ public class Resilience4jUnitTest { // Percentage of failures to start short-circuit .failureRateThreshold(20) // Min number of call attempts - .ringBufferSizeInClosedState(5) + .slidingWindowSize(5) .build(); CircuitBreakerRegistry registry = CircuitBreakerRegistry.of(config); CircuitBreaker circuitBreaker = registry.circuitBreaker("my"); @@ -70,7 +70,7 @@ public class Resilience4jUnitTest { Future taskInProgress = callAndBlock(decorated); try { - assertThat(bulkhead.isCallPermitted()).isFalse(); + assertThat(bulkhead.tryAcquirePermission()).isFalse(); } finally { taskInProgress.cancel(true); } diff --git a/spring-web-modules/spring-rest-http-2/pom.xml b/spring-web-modules/spring-rest-http-2/pom.xml index bcacdbbdb1..c6c8cd2010 100644 --- a/spring-web-modules/spring-rest-http-2/pom.xml +++ b/spring-web-modules/spring-rest-http-2/pom.xml @@ -51,7 +51,7 @@ 2.9.2 - 1.6.1 + 2.1.0 1.7.0 From 8abd7a07b583ea7d052c7fe99929055d42d2a28a Mon Sep 17 00:00:00 2001 From: panos-kakos <102670093+panos-kakos@users.noreply.github.com> Date: Fri, 24 Nov 2023 18:18:04 +0200 Subject: [PATCH 101/228] [JAVA-27546] Updated spring-cucumber to spring boot 3 (#15276) --- spring-cucumber/pom.xml | 11 ++++++----- .../cucumberoptions/HealthCheckController.java | 5 +++-- .../test/java/com/baeldung/SpringIntegrationTest.java | 4 +++- .../java/com/baeldung/StepDefsIntegrationTest.java | 3 ++- .../HealthCheckStepDefsIntegrationTest.java | 5 +++-- 5 files changed, 17 insertions(+), 11 deletions(-) diff --git a/spring-cucumber/pom.xml b/spring-cucumber/pom.xml index 042e81971f..0b0e38a2be 100644 --- a/spring-cucumber/pom.xml +++ b/spring-cucumber/pom.xml @@ -11,9 +11,9 @@ com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../parent-boot-2 + ../parent-boot-3 @@ -53,16 +53,17 @@ - org.apache.commons + commons-io commons-io ${commons-io.version} + + com.baeldung.SpringDemoApplication 7.14.0 - 1.3.2 - 5.10.0 + 5.10.1 \ No newline at end of file diff --git a/spring-cucumber/src/main/java/com/baeldung/cucumberoptions/HealthCheckController.java b/spring-cucumber/src/main/java/com/baeldung/cucumberoptions/HealthCheckController.java index 637dbdb540..70a917d999 100644 --- a/spring-cucumber/src/main/java/com/baeldung/cucumberoptions/HealthCheckController.java +++ b/spring-cucumber/src/main/java/com/baeldung/cucumberoptions/HealthCheckController.java @@ -3,6 +3,7 @@ package com.baeldung.cucumberoptions; import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; import org.springframework.http.HttpStatus; +import org.springframework.http.HttpStatusCode; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @@ -11,12 +12,12 @@ import org.springframework.web.bind.annotation.RestController; public class HealthCheckController { @GetMapping(path = "/v1/status", produces = APPLICATION_JSON_VALUE) - public HttpStatus getV1Status() { + public HttpStatusCode getV1Status() { return ResponseEntity.ok().build().getStatusCode(); } @GetMapping(path = "/v2/status", produces = APPLICATION_JSON_VALUE) - public HttpStatus getV2Status() { + public HttpStatusCode getV2Status() { return ResponseEntity.ok().build().getStatusCode(); } } \ No newline at end of file diff --git a/spring-cucumber/src/test/java/com/baeldung/SpringIntegrationTest.java b/spring-cucumber/src/test/java/com/baeldung/SpringIntegrationTest.java index 7b5c4e21ff..f243c68237 100644 --- a/spring-cucumber/src/test/java/com/baeldung/SpringIntegrationTest.java +++ b/spring-cucumber/src/test/java/com/baeldung/SpringIntegrationTest.java @@ -9,6 +9,8 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.HttpStatusCode; import org.springframework.http.client.ClientHttpResponse; import org.springframework.test.context.ContextConfiguration; import org.springframework.web.client.ResponseErrorHandler; @@ -69,7 +71,7 @@ public class SpringIntegrationTest { @Override public boolean hasError(ClientHttpResponse response) throws IOException { - hadError = response.getRawStatusCode() >= 400; + hadError = response.getStatusCode().value() >= 400; return hadError; } diff --git a/spring-cucumber/src/test/java/com/baeldung/StepDefsIntegrationTest.java b/spring-cucumber/src/test/java/com/baeldung/StepDefsIntegrationTest.java index 9611e95dcf..e4e0b2a883 100644 --- a/spring-cucumber/src/test/java/com/baeldung/StepDefsIntegrationTest.java +++ b/spring-cucumber/src/test/java/com/baeldung/StepDefsIntegrationTest.java @@ -5,6 +5,7 @@ import io.cucumber.java.en.Given; import io.cucumber.java.en.Then; import io.cucumber.java.en.When; import org.springframework.http.HttpStatus; +import org.springframework.http.HttpStatusCode; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; @@ -29,7 +30,7 @@ public class StepDefsIntegrationTest extends SpringIntegrationTest { @Then("^the client receives status code of (\\d+)$") public void the_client_receives_status_code_of(int statusCode) throws Throwable { - final HttpStatus currentStatusCode = latestResponse.getTheResponse().getStatusCode(); + final HttpStatusCode currentStatusCode = latestResponse.getTheResponse().getStatusCode(); assertThat("status code is incorrect : " + latestResponse.getBody(), currentStatusCode.value(), is(statusCode)); } diff --git a/spring-cucumber/src/test/java/com/baeldung/cucumberoptions/HealthCheckStepDefsIntegrationTest.java b/spring-cucumber/src/test/java/com/baeldung/cucumberoptions/HealthCheckStepDefsIntegrationTest.java index 999adadbef..7304f269e7 100644 --- a/spring-cucumber/src/test/java/com/baeldung/cucumberoptions/HealthCheckStepDefsIntegrationTest.java +++ b/spring-cucumber/src/test/java/com/baeldung/cucumberoptions/HealthCheckStepDefsIntegrationTest.java @@ -3,7 +3,8 @@ package com.baeldung.cucumberoptions; import io.cucumber.java.en.Then; import io.cucumber.java.en.When; -import org.springframework.http.HttpStatus; + +import org.springframework.http.HttpStatusCode; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; @@ -32,7 +33,7 @@ public class HealthCheckStepDefsIntegrationTest extends SpringIntegrationTest { @Then("^the client receives (\\d+) status code$") public void verifyStatusCode(int statusCode) throws Throwable { - final HttpStatus currentStatusCode = statusResponse.getStatusCode(); + final HttpStatusCode currentStatusCode = statusResponse.getStatusCode(); assertThat(currentStatusCode.value(), is(statusCode)); } } \ No newline at end of file From 789ecf458115869288c3bad28eb65f835e20b365 Mon Sep 17 00:00:00 2001 From: Bipin kumar Date: Fri, 24 Nov 2023 22:03:35 +0530 Subject: [PATCH 102/228] Java 26716 Upgrade flying-saucer-pdf-openpdf, jsoup, openhtmltopdf (#15263) --- core-java-modules/core-java-networking-4/pom.xml | 2 +- jsoup/pom.xml | 2 +- .../com/baeldung/jsoup/PreservingLineBreaksUnitTest.java | 6 +++--- pdf/pom.xml | 8 ++++---- xml/pom.xml | 2 +- 5 files changed, 10 insertions(+), 10 deletions(-) diff --git a/core-java-modules/core-java-networking-4/pom.xml b/core-java-modules/core-java-networking-4/pom.xml index cbe6356d0f..4b49359c8c 100644 --- a/core-java-modules/core-java-networking-4/pom.xml +++ b/core-java-modules/core-java-networking-4/pom.xml @@ -56,7 +56,7 @@ 1.7 - 1.15.4 + 1.16.2 \ No newline at end of file diff --git a/jsoup/pom.xml b/jsoup/pom.xml index 44f8f996f5..d2780424de 100644 --- a/jsoup/pom.xml +++ b/jsoup/pom.xml @@ -22,7 +22,7 @@ - 1.10.2 + 1.16.2 \ No newline at end of file diff --git a/jsoup/src/test/java/com/baeldung/jsoup/PreservingLineBreaksUnitTest.java b/jsoup/src/test/java/com/baeldung/jsoup/PreservingLineBreaksUnitTest.java index 0958fa96e2..e6bd8eccbf 100644 --- a/jsoup/src/test/java/com/baeldung/jsoup/PreservingLineBreaksUnitTest.java +++ b/jsoup/src/test/java/com/baeldung/jsoup/PreservingLineBreaksUnitTest.java @@ -2,7 +2,7 @@ package com.baeldung.jsoup; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; -import org.jsoup.safety.Whitelist; +import org.jsoup.safety.Safelist; import org.junit.Test; import static org.junit.Assert.assertEquals; @@ -13,7 +13,7 @@ public class PreservingLineBreaksUnitTest { String strHTML = "Hello\nworld"; Document.OutputSettings outputSettings = new Document.OutputSettings(); outputSettings.prettyPrint(false); - String strWithNewLines = Jsoup.clean(strHTML, "", Whitelist.none(), outputSettings); + String strWithNewLines = Jsoup.clean(strHTML, "", Safelist.none(), outputSettings); assertEquals("Hello\nworld", strWithNewLines); } @@ -33,7 +33,7 @@ public class PreservingLineBreaksUnitTest { jsoupDoc.select("p").before("\\n"); String str = jsoupDoc.html().replaceAll("\\\\n", "\n"); String strWithNewLines = - Jsoup.clean(str, "", Whitelist.none(), outputSettings); + Jsoup.clean(str, "", Safelist.none(), outputSettings); assertEquals("Hello\nWorld\nParagraph", strWithNewLines); } } diff --git a/pdf/pom.xml b/pdf/pom.xml index 0fe90b6eb5..34094481bf 100644 --- a/pdf/pom.xml +++ b/pdf/pom.xml @@ -112,11 +112,11 @@ 1.8 3.15 3.0.11.RELEASE - 9.1.20 + 9.3.1 1.0.6 - 1.0.6 - 9.1.22 - 1.14.2 + 1.0.10 + 9.2.1 + 1.16.2 \ No newline at end of file diff --git a/xml/pom.xml b/xml/pom.xml index b56b919914..785634e265 100644 --- a/xml/pom.xml +++ b/xml/pom.xml @@ -372,7 +372,7 @@ 0.9.6 1.3.1 - 1.14.3 + 1.16.2 2.25 3.4 6.7.0 From c7ef62ee993ef17c16853c1b0cd6515095c7fdec Mon Sep 17 00:00:00 2001 From: Alexandru Borza Date: Fri, 24 Nov 2023 18:39:21 +0200 Subject: [PATCH 103/228] BAEL-7051 - Catch Common Mistakes with Error-Prone Library in Java (#15278) --- pom.xml | 4 +- .../error-prone-project/.mvn/jvm.config | 10 +++ static-analysis/error-prone-project/pom.xml | 61 ++++++++++++++++ .../main/java/com/baeldung/BuggyClass.java | 12 ++++ .../com/baeldung/ClassWithEmptyMethod.java | 6 ++ static-analysis/my-bugchecker-plugin/pom.xml | 56 +++++++++++++++ .../java/com/baeldung/EmptyMethodChecker.java | 24 +++++++ static-analysis/pmd/pom.xml | 20 ++++++ .../src/main/java/com/baeldung/pmd/Cnt.java | 0 .../src/main/resources/customruleset.xml | 72 +++++++++---------- .../{ => pmd}/src/main/resources/logback.xml | 0 .../java/com/baeldung/pmd/CntUnitTest.java | 0 static-analysis/pom.xml | 14 +++- 13 files changed, 240 insertions(+), 39 deletions(-) create mode 100644 static-analysis/error-prone-project/.mvn/jvm.config create mode 100644 static-analysis/error-prone-project/pom.xml create mode 100644 static-analysis/error-prone-project/src/main/java/com/baeldung/BuggyClass.java create mode 100644 static-analysis/error-prone-project/src/main/java/com/baeldung/ClassWithEmptyMethod.java create mode 100644 static-analysis/my-bugchecker-plugin/pom.xml create mode 100644 static-analysis/my-bugchecker-plugin/src/main/java/com/baeldung/EmptyMethodChecker.java create mode 100644 static-analysis/pmd/pom.xml rename static-analysis/{ => pmd}/src/main/java/com/baeldung/pmd/Cnt.java (100%) rename static-analysis/{ => pmd}/src/main/resources/customruleset.xml (97%) rename static-analysis/{ => pmd}/src/main/resources/logback.xml (100%) rename static-analysis/{ => pmd}/src/test/java/com/baeldung/pmd/CntUnitTest.java (100%) diff --git a/pom.xml b/pom.xml index 7099dd8cbc..3452ae81ee 100644 --- a/pom.xml +++ b/pom.xml @@ -889,7 +889,7 @@ spring-vault spring-web-modules spring-websockets - static-analysis + tablesaw tensorflow-java testing-modules @@ -1134,7 +1134,7 @@ spring-vault spring-web-modules spring-websockets - static-analysis + tablesaw tensorflow-java testing-modules diff --git a/static-analysis/error-prone-project/.mvn/jvm.config b/static-analysis/error-prone-project/.mvn/jvm.config new file mode 100644 index 0000000000..32599cefea --- /dev/null +++ b/static-analysis/error-prone-project/.mvn/jvm.config @@ -0,0 +1,10 @@ +--add-exports jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED +--add-exports jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED +--add-exports jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED +--add-exports jdk.compiler/com.sun.tools.javac.model=ALL-UNNAMED +--add-exports jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED +--add-exports jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED +--add-exports jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED +--add-exports jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED +--add-opens jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED +--add-opens jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED diff --git a/static-analysis/error-prone-project/pom.xml b/static-analysis/error-prone-project/pom.xml new file mode 100644 index 0000000000..59f7bb7270 --- /dev/null +++ b/static-analysis/error-prone-project/pom.xml @@ -0,0 +1,61 @@ + + + 4.0.0 + + com.baeldung + static-analysis + 1.0-SNAPSHOT + + + error-prone-project + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 17 + UTF-8 + true + + -XDcompilePolicy=simple + -Xplugin:ErrorProne + -J--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.model=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED + -J--add-opens=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED + -J--add-opens=jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED + + + + com.google.errorprone + error_prone_core + ${error-prone.version} + + + com.baeldung + my-bugchecker-plugin + 1.0-SNAPSHOT + + + + + + + + + 17 + 17 + UTF-8 + + + diff --git a/static-analysis/error-prone-project/src/main/java/com/baeldung/BuggyClass.java b/static-analysis/error-prone-project/src/main/java/com/baeldung/BuggyClass.java new file mode 100644 index 0000000000..dda432ad48 --- /dev/null +++ b/static-analysis/error-prone-project/src/main/java/com/baeldung/BuggyClass.java @@ -0,0 +1,12 @@ +package com.baeldung; + +public class BuggyClass { + public static void main(String[] args) { + if (args.length == 0 || args[0] != null) { + new IllegalArgumentException(); + } + } + + public void emptyMethod() { + } +} diff --git a/static-analysis/error-prone-project/src/main/java/com/baeldung/ClassWithEmptyMethod.java b/static-analysis/error-prone-project/src/main/java/com/baeldung/ClassWithEmptyMethod.java new file mode 100644 index 0000000000..cc791ecdd4 --- /dev/null +++ b/static-analysis/error-prone-project/src/main/java/com/baeldung/ClassWithEmptyMethod.java @@ -0,0 +1,6 @@ +package com.baeldung; + +public class ClassWithEmptyMethod { + public void theEmptyMethod() { + } +} diff --git a/static-analysis/my-bugchecker-plugin/pom.xml b/static-analysis/my-bugchecker-plugin/pom.xml new file mode 100644 index 0000000000..cbe16b0a14 --- /dev/null +++ b/static-analysis/my-bugchecker-plugin/pom.xml @@ -0,0 +1,56 @@ + + + 4.0.0 + + com.baeldung + static-analysis + 1.0-SNAPSHOT + + jar + my-bugchecker-plugin + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + + + com.google.auto.service + auto-service + ${google-auto-service.version} + + + + + + + + + com.google.errorprone + error_prone_annotation + ${error-prone.version} + + + com.google.errorprone + error_prone_check_api + ${error-prone.version} + + + com.google.auto.service + auto-service-annotations + ${google-auto-service.version} + + + + + 17 + 17 + UTF-8 + + + diff --git a/static-analysis/my-bugchecker-plugin/src/main/java/com/baeldung/EmptyMethodChecker.java b/static-analysis/my-bugchecker-plugin/src/main/java/com/baeldung/EmptyMethodChecker.java new file mode 100644 index 0000000000..f31913c086 --- /dev/null +++ b/static-analysis/my-bugchecker-plugin/src/main/java/com/baeldung/EmptyMethodChecker.java @@ -0,0 +1,24 @@ +package com.baeldung; + +import com.google.auto.service.AutoService; +import com.google.errorprone.BugPattern; +import com.google.errorprone.VisitorState; +import com.google.errorprone.bugpatterns.BugChecker; +import com.google.errorprone.fixes.SuggestedFix; +import com.google.errorprone.matchers.Description; +import com.sun.source.tree.MethodTree; + + +@AutoService(BugChecker.class) +@BugPattern(name = "EmptyMethodCheck", summary = "Empty methods should be deleted", severity = BugPattern.SeverityLevel.ERROR) +public class EmptyMethodChecker extends BugChecker implements BugChecker.MethodTreeMatcher { + @Override + public Description matchMethod(MethodTree methodTree, VisitorState visitorState) { + if (methodTree.getBody() + .getStatements() + .isEmpty()) { + return describeMatch(methodTree, SuggestedFix.delete(methodTree)); + } + return Description.NO_MATCH; + } +} diff --git a/static-analysis/pmd/pom.xml b/static-analysis/pmd/pom.xml new file mode 100644 index 0000000000..31914fe9f0 --- /dev/null +++ b/static-analysis/pmd/pom.xml @@ -0,0 +1,20 @@ + + + 4.0.0 + + com.baeldung + static-analysis + 1.0-SNAPSHOT + + + pmd + + + 17 + 17 + UTF-8 + + + diff --git a/static-analysis/src/main/java/com/baeldung/pmd/Cnt.java b/static-analysis/pmd/src/main/java/com/baeldung/pmd/Cnt.java similarity index 100% rename from static-analysis/src/main/java/com/baeldung/pmd/Cnt.java rename to static-analysis/pmd/src/main/java/com/baeldung/pmd/Cnt.java diff --git a/static-analysis/src/main/resources/customruleset.xml b/static-analysis/pmd/src/main/resources/customruleset.xml similarity index 97% rename from static-analysis/src/main/resources/customruleset.xml rename to static-analysis/pmd/src/main/resources/customruleset.xml index e0a009dd4a..6b1a80334d 100644 --- a/static-analysis/src/main/resources/customruleset.xml +++ b/static-analysis/pmd/src/main/resources/customruleset.xml @@ -1,37 +1,37 @@ - - - - - This ruleset checks my code for bad stuff - - - - - - - - - - - - - - 2 - - - - - - - - - - - - - - + + + + + This ruleset checks my code for bad stuff + + + + + + + + + + + + + + 2 + + + + + + + + + + + + + + \ No newline at end of file diff --git a/static-analysis/src/main/resources/logback.xml b/static-analysis/pmd/src/main/resources/logback.xml similarity index 100% rename from static-analysis/src/main/resources/logback.xml rename to static-analysis/pmd/src/main/resources/logback.xml diff --git a/static-analysis/src/test/java/com/baeldung/pmd/CntUnitTest.java b/static-analysis/pmd/src/test/java/com/baeldung/pmd/CntUnitTest.java similarity index 100% rename from static-analysis/src/test/java/com/baeldung/pmd/CntUnitTest.java rename to static-analysis/pmd/src/test/java/com/baeldung/pmd/CntUnitTest.java diff --git a/static-analysis/pom.xml b/static-analysis/pom.xml index eedf5ba724..176f3dc092 100644 --- a/static-analysis/pom.xml +++ b/static-analysis/pom.xml @@ -6,6 +6,7 @@ static-analysis 1.0-SNAPSHOT static-analysis + pom com.baeldung @@ -29,4 +30,15 @@ - \ No newline at end of file + + pmd + my-bugchecker-plugin + error-prone-project + + + + 2.23.0 + 1.0.1 + + + From b80ceb7cebf411c797015023b37e6815bfda520a Mon Sep 17 00:00:00 2001 From: MohamedHelmyKassab <137485958+MohamedHelmyKassab@users.noreply.github.com> Date: Fri, 24 Nov 2023 18:45:14 +0200 Subject: [PATCH 104/228] This PR is related to BAEL-7188 (#15271) * Update pom.xml Adding core-java-swing * This commit is related to BAEL-7188 This commit aims to add a new module named "core-java-swing". --- core-java-modules/core-java-swing/pom.xml | 21 +++++++ .../com/baeldung/customfont/CustomFonts.java | 55 ++++++++++++++++++ .../target/classes/org/example/Main.class | Bin 0 -> 2912 bytes core-java-modules/pom.xml | 1 + 4 files changed, 77 insertions(+) create mode 100644 core-java-modules/core-java-swing/pom.xml create mode 100644 core-java-modules/core-java-swing/src/main/java/com/baeldung/customfont/CustomFonts.java create mode 100644 core-java-modules/core-java-swing/target/classes/org/example/Main.class diff --git a/core-java-modules/core-java-swing/pom.xml b/core-java-modules/core-java-swing/pom.xml new file mode 100644 index 0000000000..28228ebb29 --- /dev/null +++ b/core-java-modules/core-java-swing/pom.xml @@ -0,0 +1,21 @@ + + + 4.0.0 + core-java-string-swing + core-java-string-swing + jar + + + com.baeldung.core-java-modules + core-java-modules + 0.0.1-SNAPSHOT + + + 20 + 20 + UTF-8 + + + \ No newline at end of file diff --git a/core-java-modules/core-java-swing/src/main/java/com/baeldung/customfont/CustomFonts.java b/core-java-modules/core-java-swing/src/main/java/com/baeldung/customfont/CustomFonts.java new file mode 100644 index 0000000000..28e0da84ae --- /dev/null +++ b/core-java-modules/core-java-swing/src/main/java/com/baeldung/customfont/CustomFonts.java @@ -0,0 +1,55 @@ +package com.baeldung.customfont; + +import javax.swing.*; +import java.awt.*; +import java.io.File; +import java.io.IOException; +import java.util.Arrays; +import java.util.List; + +public class CustomFonts { + public static void main(String[] args) { + usingCustomFonts(); + } + + public static void usingCustomFonts() { + final GraphicsEnvironment GE = GraphicsEnvironment.getLocalGraphicsEnvironment(); + final List AVAILABLE_FONT_FAMILY_NAMES = Arrays.asList(GE.getAvailableFontFamilyNames()); + try { + final List LIST = Arrays.asList( + new File("font/JetBrainsMono/JetBrainsMono-Thin.ttf"), + new File("font/JetBrainsMono/JetBrainsMono-Light.ttf"), + new File("font/Roboto/Roboto-Light.ttf"), + new File("font/Roboto/Roboto-Regular.ttf"), + new File("font/Roboto/Roboto-Medium.ttf") + ); + for (File LIST_ITEM : LIST) { + if (LIST_ITEM.exists()) { + Font FONT = Font.createFont(Font.TRUETYPE_FONT, LIST_ITEM); + if (!AVAILABLE_FONT_FAMILY_NAMES.contains(FONT.getFontName())) { + GE.registerFont(FONT); + } + } + } + } catch (FontFormatException | IOException exception) { + JOptionPane.showMessageDialog(null, exception.getMessage()); + } + + + JFrame frame = new JFrame("Custom Font Example"); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.setLayout(new FlowLayout()); + + JLabel label1 = new JLabel("TEXT1"); + label1.setFont(new Font("Roboto Medium", Font.PLAIN, 17)); + + JLabel label2 = new JLabel("TEXT2"); + label2.setFont(new Font("JetBrainsMono-Thin", Font.PLAIN, 17)); + + frame.add(label1); + frame.add(label2); + + frame.pack(); + frame.setVisible(true); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-swing/target/classes/org/example/Main.class b/core-java-modules/core-java-swing/target/classes/org/example/Main.class new file mode 100644 index 0000000000000000000000000000000000000000..5914458bc4b1b959f8d4cc18270605acd2f4249e GIT binary patch literal 2912 zcmai0+jA3D82@dXWYe$+6hSHlQxI)RN(2FwVzrb614)at7F#cMn{JbZBpY`(wDo?! z-|yi4ikBH@d`ZEMjx#GmpU?u?9t5JZcLkcMSa+_JMV zV@5BO@ETC z^;yGBSs6XQBsbg{N&T08k8rkH!^K$Rnd&>Cn|XaAZzQauo6rkpes(}F7>1Uj3x)`j1X?Yh>D{cZWZV7L}V80BFqa(sti0-Ol zp>8~3Gq*uZFv$M0<64EVIA=KSO{5UU(IFm&hAGh3I>&JL8&i5Y@Al^{#~3ULATkvM zO=mJf4`%JSGLw00I;GEAWdb6HW??C>p#X}v(2~dEz-c&vx0lw7OpDzkES4^eIi*h+ z`5=gX|8V@)VGc?Q9YK@{La!miUMmSGO^XRI!;~&D0g?<@=-#8@UfjoqU`YRl1`dk{ zs{VEa@eo5=G=t>S5yyK(!=reNEu~LRa=0`cY@sv_qj+IcC_ka$NpUIoN_ytF*mzpQ zGkBIzVPqqwV{#sgM2|&A`0BSNxmuAji^f2?Fk#rkVqP;cc@2!{wkg)tO`n@H*%#zp zaNqRMQbFE3YZuMsYJW*jx}Bx&>c+8MWm7pZI4~^2Sk(Wt+LB5R4UZ>><7rN?#XV0g z!Q?gJ?bk<}P%~=X#V&3DalLUU({v!tF}vV#i7Ss%>-$FflBvFZsra~vaXitNPNqi3 z2l~=+wyl3kAfHo3npxZrR1Wa+GxFR2!I#*p^LKCnFV6OCsh08Z1!vpqt!s0ymqspM zTBPw_6=KVWT;d_Em#Vc44OwM7V~9JE`4S%u+eGrw!B2}Oev|;s-~kcf^Es|!d@FqW zyXK&LL!t@K^C{Rs2ruxdc>;J5FLBj^m+=aBgz^slg`DpU)CFDf(Id2)IZ+q%eRvhG zalb`;+j#m-QBnb#2%Ld-sH=k3GfY|VJG75B&-2l`aSq|3QJ_3Z}ns5rC zF0o1-J$?SC)6mjNw1VL?7@f!XXsbSlOgb8Nc-jHHQ-w%u3GvC}#=v4OP-Q+G49JMbnp;eA|zFK{KkMkmgq3qN8jenB_R zVHcore-java-string-algorithms core-java-string-algorithms-2 core-java-string-apis + core-java-swing core-java-string-apis-2 core-java-string-conversions core-java-string-conversions-2 From 783d9dbd0189b6f427190b28db22e5ebe5b123bb Mon Sep 17 00:00:00 2001 From: Geoffrey De Smet Date: Fri, 24 Nov 2023 21:01:28 +0100 Subject: [PATCH 105/228] Use slf4j --- .../com/baeldung/timefoldsolver/ShiftScheduleApp.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/timefold-solver/src/main/java/com/baeldung/timefoldsolver/ShiftScheduleApp.java b/timefold-solver/src/main/java/com/baeldung/timefoldsolver/ShiftScheduleApp.java index 9c25922dea..9170e2363f 100644 --- a/timefold-solver/src/main/java/com/baeldung/timefoldsolver/ShiftScheduleApp.java +++ b/timefold-solver/src/main/java/com/baeldung/timefoldsolver/ShiftScheduleApp.java @@ -8,9 +8,13 @@ import java.util.Set; import ai.timefold.solver.core.api.solver.Solver; import ai.timefold.solver.core.api.solver.SolverFactory; import ai.timefold.solver.core.config.solver.SolverConfig; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class ShiftScheduleApp { + private static final Logger logger = LoggerFactory.getLogger(ShiftScheduleApp.class); + public static void main(String[] args) { SolverFactory solverFactory = SolverFactory.create(new SolverConfig() .withSolutionClass(ShiftSchedule.class) @@ -43,9 +47,9 @@ public class ShiftScheduleApp { } private static void printSolution(ShiftSchedule solution) { - System.out.println("Shift assignments"); + logger.info("Shift assignments"); for (Shift shift : solution.getShifts()) { - System.out.println(" " + shift.getStart().toLocalDate() + logger.info(" " + shift.getStart().toLocalDate() + " " + shift.getStart().toLocalTime() + " - " + shift.getEnd().toLocalTime() + ": " + shift.getEmployee().getName()); } From 3df51484f27a8ee07507d827df34f17c8e80af6f Mon Sep 17 00:00:00 2001 From: Geoffrey De Smet Date: Fri, 24 Nov 2023 21:17:46 +0100 Subject: [PATCH 106/228] improve comment --- .../timefoldsolver/ShiftScheduleConstraintProviderTest.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleConstraintProviderTest.java b/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleConstraintProviderTest.java index 9979f5d5e0..9477e892eb 100644 --- a/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleConstraintProviderTest.java +++ b/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleConstraintProviderTest.java @@ -22,7 +22,8 @@ class ShiftScheduleConstraintProviderTest { ann, new Shift(MONDAY.atTime(6, 0), MONDAY.atTime(14, 0), null, ann), new Shift(MONDAY.atTime(14, 0), MONDAY.atTime(22, 0), null, ann)) - // Penalizes both A-B and B-A. To avoid that, use forEachUniquePair() in the constraint instead. + // Penalizes by 2 because both {shiftA, shiftB} and {shiftB, shiftA} match. + // To avoid that, use forEachUniquePair() in the constraint instead. .penalizesBy(2); constraintVerifier.verifyThat(ShiftScheduleConstraintProvider::atMostOneShiftPerDay) .given( From 07a6999e56bd27aa2d0fc6b1b779245c814663a6 Mon Sep 17 00:00:00 2001 From: Geoffrey De Smet Date: Fri, 24 Nov 2023 21:40:29 +0100 Subject: [PATCH 107/228] format with baeldung style --- .../com/baeldung/timefoldsolver/Shift.java | 3 +- .../timefoldsolver/ShiftScheduleApp.java | 42 +++++++++---------- .../ShiftScheduleConstraintProvider.java | 28 ++++++------- .../ShiftScheduleConstraintProviderTest.java | 37 +++++++--------- 4 files changed, 48 insertions(+), 62 deletions(-) diff --git a/timefold-solver/src/main/java/com/baeldung/timefoldsolver/Shift.java b/timefold-solver/src/main/java/com/baeldung/timefoldsolver/Shift.java index 9c7b663ecd..2ef2f2a1b9 100644 --- a/timefold-solver/src/main/java/com/baeldung/timefoldsolver/Shift.java +++ b/timefold-solver/src/main/java/com/baeldung/timefoldsolver/Shift.java @@ -16,7 +16,8 @@ public class Shift { private Employee employee; // A no-arg constructor is required for @PlanningEntity annotated classes - public Shift() {} + public Shift() { + } public Shift(LocalDateTime start, LocalDateTime end, String requiredSkill) { this(start, end, requiredSkill, null); diff --git a/timefold-solver/src/main/java/com/baeldung/timefoldsolver/ShiftScheduleApp.java b/timefold-solver/src/main/java/com/baeldung/timefoldsolver/ShiftScheduleApp.java index 9170e2363f..24666ac6aa 100644 --- a/timefold-solver/src/main/java/com/baeldung/timefoldsolver/ShiftScheduleApp.java +++ b/timefold-solver/src/main/java/com/baeldung/timefoldsolver/ShiftScheduleApp.java @@ -5,24 +5,24 @@ import java.time.LocalDate; import java.util.List; import java.util.Set; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import ai.timefold.solver.core.api.solver.Solver; import ai.timefold.solver.core.api.solver.SolverFactory; import ai.timefold.solver.core.config.solver.SolverConfig; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; public class ShiftScheduleApp { private static final Logger logger = LoggerFactory.getLogger(ShiftScheduleApp.class); public static void main(String[] args) { - SolverFactory solverFactory = SolverFactory.create(new SolverConfig() - .withSolutionClass(ShiftSchedule.class) - .withEntityClasses(Shift.class) - .withConstraintProviderClass(ShiftScheduleConstraintProvider.class) - // The solver runs only for 5 seconds on this small dataset. - // It's recommended to run for at least 5 minutes ("5m") otherwise. - .withTerminationSpentLimit(Duration.ofSeconds(5))); + SolverFactory solverFactory = SolverFactory.create(new SolverConfig().withSolutionClass(ShiftSchedule.class) + .withEntityClasses(Shift.class) + .withConstraintProviderClass(ShiftScheduleConstraintProvider.class) + // The solver runs only for 5 seconds on this small dataset. + // It's recommended to run for at least 5 minutes ("5m") otherwise. + .withTerminationSpentLimit(Duration.ofSeconds(5))); Solver solver = solverFactory.buildSolver(); ShiftSchedule problem = loadProblem(); @@ -33,25 +33,21 @@ public class ShiftScheduleApp { private static ShiftSchedule loadProblem() { LocalDate monday = LocalDate.of(2030, 4, 1); LocalDate tuesday = LocalDate.of(2030, 4, 2); - return new ShiftSchedule(List.of( - new Employee("Ann", Set.of("Bartender")), - new Employee("Beth", Set.of("Waiter", "Bartender")), - new Employee("Carl", Set.of("Waiter")) - ), List.of( - new Shift(monday.atTime(6, 0), monday.atTime(14, 0), "Waiter"), - new Shift(monday.atTime(9, 0), monday.atTime(17, 0), "Bartender"), - new Shift(monday.atTime(14, 0), monday.atTime(22, 0), "Bartender"), - new Shift(tuesday.atTime(6, 0), tuesday.atTime(14, 0), "Waiter"), - new Shift(tuesday.atTime(14, 0), tuesday.atTime(22, 0), "Bartender") - )); + return new ShiftSchedule( + List.of(new Employee("Ann", Set.of("Bartender")), new Employee("Beth", Set.of("Waiter", "Bartender")), new Employee("Carl", Set.of("Waiter"))), + List.of(new Shift(monday.atTime(6, 0), monday.atTime(14, 0), "Waiter"), new Shift(monday.atTime(9, 0), monday.atTime(17, 0), "Bartender"), + new Shift(monday.atTime(14, 0), monday.atTime(22, 0), "Bartender"), new Shift(tuesday.atTime(6, 0), tuesday.atTime(14, 0), "Waiter"), + new Shift(tuesday.atTime(14, 0), tuesday.atTime(22, 0), "Bartender"))); } private static void printSolution(ShiftSchedule solution) { logger.info("Shift assignments"); for (Shift shift : solution.getShifts()) { - logger.info(" " + shift.getStart().toLocalDate() - + " " + shift.getStart().toLocalTime() + " - " + shift.getEnd().toLocalTime() - + ": " + shift.getEmployee().getName()); + logger.info(" " + shift.getStart() + .toLocalDate() + " " + shift.getStart() + .toLocalTime() + " - " + shift.getEnd() + .toLocalTime() + ": " + shift.getEmployee() + .getName()); } } diff --git a/timefold-solver/src/main/java/com/baeldung/timefoldsolver/ShiftScheduleConstraintProvider.java b/timefold-solver/src/main/java/com/baeldung/timefoldsolver/ShiftScheduleConstraintProvider.java index 0846429460..bd308dacbf 100644 --- a/timefold-solver/src/main/java/com/baeldung/timefoldsolver/ShiftScheduleConstraintProvider.java +++ b/timefold-solver/src/main/java/com/baeldung/timefoldsolver/ShiftScheduleConstraintProvider.java @@ -1,37 +1,35 @@ package com.baeldung.timefoldsolver; +import static ai.timefold.solver.core.api.score.stream.Joiners.equal; + import ai.timefold.solver.core.api.score.buildin.hardsoft.HardSoftScore; import ai.timefold.solver.core.api.score.stream.Constraint; import ai.timefold.solver.core.api.score.stream.ConstraintFactory; import ai.timefold.solver.core.api.score.stream.ConstraintProvider; -import static ai.timefold.solver.core.api.score.stream.Joiners.equal; - public class ShiftScheduleConstraintProvider implements ConstraintProvider { @Override public Constraint[] defineConstraints(ConstraintFactory constraintFactory) { - return new Constraint[] { - atMostOneShiftPerDay(constraintFactory), - requiredSkill(constraintFactory) - }; + return new Constraint[] { atMostOneShiftPerDay(constraintFactory), requiredSkill(constraintFactory) }; } public Constraint atMostOneShiftPerDay(ConstraintFactory constraintFactory) { return constraintFactory.forEach(Shift.class) - .join(Shift.class, - equal(shift -> shift.getStart().toLocalDate()), - equal(Shift::getEmployee)) - .filter((shift1, shift2) -> shift1 != shift2) - .penalize(HardSoftScore.ONE_HARD) - .asConstraint("At most one shift per day"); + .join(Shift.class, equal(shift -> shift.getStart() + .toLocalDate()), equal(Shift::getEmployee)) + .filter((shift1, shift2) -> shift1 != shift2) + .penalize(HardSoftScore.ONE_HARD) + .asConstraint("At most one shift per day"); } public Constraint requiredSkill(ConstraintFactory constraintFactory) { return constraintFactory.forEach(Shift.class) - .filter(shift -> !shift.getEmployee().getSkills().contains(shift.getRequiredSkill())) - .penalize(HardSoftScore.ONE_HARD) - .asConstraint("Required skill"); + .filter(shift -> !shift.getEmployee() + .getSkills() + .contains(shift.getRequiredSkill())) + .penalize(HardSoftScore.ONE_HARD) + .asConstraint("Required skill"); } } diff --git a/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleConstraintProviderTest.java b/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleConstraintProviderTest.java index 9477e892eb..c4741a831b 100644 --- a/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleConstraintProviderTest.java +++ b/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleConstraintProviderTest.java @@ -3,49 +3,40 @@ package com.baeldung.timefoldsolver; import java.time.LocalDate; import java.util.Set; -import ai.timefold.solver.test.api.score.stream.ConstraintVerifier; import org.junit.jupiter.api.Test; +import ai.timefold.solver.test.api.score.stream.ConstraintVerifier; + class ShiftScheduleConstraintProviderTest { private static final LocalDate MONDAY = LocalDate.of(2030, 4, 1); private static final LocalDate TUESDAY = LocalDate.of(2030, 4, 2); - ConstraintVerifier constraintVerifier = ConstraintVerifier.build( - new ShiftScheduleConstraintProvider(), ShiftSchedule.class, Shift.class); + ConstraintVerifier constraintVerifier = ConstraintVerifier.build(new ShiftScheduleConstraintProvider(), + ShiftSchedule.class, Shift.class); @Test void atMostOneShiftPerDay() { Employee ann = new Employee("Ann", null); constraintVerifier.verifyThat(ShiftScheduleConstraintProvider::atMostOneShiftPerDay) - .given( - ann, - new Shift(MONDAY.atTime(6, 0), MONDAY.atTime(14, 0), null, ann), - new Shift(MONDAY.atTime(14, 0), MONDAY.atTime(22, 0), null, ann)) - // Penalizes by 2 because both {shiftA, shiftB} and {shiftB, shiftA} match. - // To avoid that, use forEachUniquePair() in the constraint instead. - .penalizesBy(2); + .given(ann, new Shift(MONDAY.atTime(6, 0), MONDAY.atTime(14, 0), null, ann), new Shift(MONDAY.atTime(14, 0), MONDAY.atTime(22, 0), null, ann)) + // Penalizes by 2 because both {shiftA, shiftB} and {shiftB, shiftA} match. + // To avoid that, use forEachUniquePair() in the constraint instead. + .penalizesBy(2); constraintVerifier.verifyThat(ShiftScheduleConstraintProvider::atMostOneShiftPerDay) - .given( - ann, - new Shift(MONDAY.atTime(6, 0), MONDAY.atTime(14, 0), null, ann), - new Shift(TUESDAY.atTime(14, 0), TUESDAY.atTime(22, 0), null, ann)) - .penalizesBy(0); + .given(ann, new Shift(MONDAY.atTime(6, 0), MONDAY.atTime(14, 0), null, ann), new Shift(TUESDAY.atTime(14, 0), TUESDAY.atTime(22, 0), null, ann)) + .penalizesBy(0); } @Test void requiredSkill() { Employee ann = new Employee("Ann", Set.of("Waiter")); constraintVerifier.verifyThat(ShiftScheduleConstraintProvider::requiredSkill) - .given( - ann, - new Shift(MONDAY.atTime(6, 0), MONDAY.atTime(14, 0), "Cook", ann)) - .penalizesBy(1); + .given(ann, new Shift(MONDAY.atTime(6, 0), MONDAY.atTime(14, 0), "Cook", ann)) + .penalizesBy(1); constraintVerifier.verifyThat(ShiftScheduleConstraintProvider::requiredSkill) - .given( - ann, - new Shift(MONDAY.atTime(6, 0), MONDAY.atTime(14, 0), "Waiter", ann)) - .penalizesBy(0); + .given(ann, new Shift(MONDAY.atTime(6, 0), MONDAY.atTime(14, 0), "Waiter", ann)) + .penalizesBy(0); } } From dfd736183f64d84efdd29ecbbc5f1795cb21ca75 Mon Sep 17 00:00:00 2001 From: Geoffrey De Smet Date: Fri, 24 Nov 2023 21:44:10 +0100 Subject: [PATCH 108/228] Adjust test names --- .../ShiftScheduleConstraintProviderTest.java | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleConstraintProviderTest.java b/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleConstraintProviderTest.java index c4741a831b..0832cd7bdd 100644 --- a/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleConstraintProviderTest.java +++ b/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleConstraintProviderTest.java @@ -16,24 +16,33 @@ class ShiftScheduleConstraintProviderTest { ShiftSchedule.class, Shift.class); @Test - void atMostOneShiftPerDay() { + void whenTwoShiftsOnOneDay_thenPenalize() { Employee ann = new Employee("Ann", null); constraintVerifier.verifyThat(ShiftScheduleConstraintProvider::atMostOneShiftPerDay) .given(ann, new Shift(MONDAY.atTime(6, 0), MONDAY.atTime(14, 0), null, ann), new Shift(MONDAY.atTime(14, 0), MONDAY.atTime(22, 0), null, ann)) // Penalizes by 2 because both {shiftA, shiftB} and {shiftB, shiftA} match. // To avoid that, use forEachUniquePair() in the constraint instead. .penalizesBy(2); + } + @Test + void whenTwoShiftsOnDifferentDays_thenDoNotPenalize() { + Employee ann = new Employee("Ann", null); constraintVerifier.verifyThat(ShiftScheduleConstraintProvider::atMostOneShiftPerDay) .given(ann, new Shift(MONDAY.atTime(6, 0), MONDAY.atTime(14, 0), null, ann), new Shift(TUESDAY.atTime(14, 0), TUESDAY.atTime(22, 0), null, ann)) .penalizesBy(0); } @Test - void requiredSkill() { + void whenEmployeeLacksRequiredSkill_thenPenalize() { Employee ann = new Employee("Ann", Set.of("Waiter")); constraintVerifier.verifyThat(ShiftScheduleConstraintProvider::requiredSkill) .given(ann, new Shift(MONDAY.atTime(6, 0), MONDAY.atTime(14, 0), "Cook", ann)) .penalizesBy(1); + } + + @Test + void whenEmployeeHasRequiredSkill_thenDoNotPenalize() { + Employee ann = new Employee("Ann", Set.of("Waiter")); constraintVerifier.verifyThat(ShiftScheduleConstraintProvider::requiredSkill) .given(ann, new Shift(MONDAY.atTime(6, 0), MONDAY.atTime(14, 0), "Waiter", ann)) .penalizesBy(0); From f4c35c055c48de3e15892bb10237f9cc827f27b7 Mon Sep 17 00:00:00 2001 From: Graham Cox Date: Fri, 24 Nov 2023 21:17:18 +0000 Subject: [PATCH 109/228] BAEL-7218: Inter-Process Communication Methods in Java (#15286) --- core-java-modules/core-java-ipc/pom.xml | 16 ++++++ .../com/baeldung/ipc/DirectoryLiveTest.java | 32 ++++++++++++ .../java/com/baeldung/ipc/JmxLiveTest.java | 52 +++++++++++++++++++ .../com/baeldung/ipc/SocketsLiveTest.java | 38 ++++++++++++++ core-java-modules/pom.xml | 1 + 5 files changed, 139 insertions(+) create mode 100644 core-java-modules/core-java-ipc/pom.xml create mode 100644 core-java-modules/core-java-ipc/src/test/java/com/baeldung/ipc/DirectoryLiveTest.java create mode 100644 core-java-modules/core-java-ipc/src/test/java/com/baeldung/ipc/JmxLiveTest.java create mode 100644 core-java-modules/core-java-ipc/src/test/java/com/baeldung/ipc/SocketsLiveTest.java diff --git a/core-java-modules/core-java-ipc/pom.xml b/core-java-modules/core-java-ipc/pom.xml new file mode 100644 index 0000000000..b7b37afb1d --- /dev/null +++ b/core-java-modules/core-java-ipc/pom.xml @@ -0,0 +1,16 @@ + + + 4.0.0 + core-java-ipc + core-java-ipc + jar + + + com.baeldung.core-java-modules + core-java-modules + 0.0.1-SNAPSHOT + + + diff --git a/core-java-modules/core-java-ipc/src/test/java/com/baeldung/ipc/DirectoryLiveTest.java b/core-java-modules/core-java-ipc/src/test/java/com/baeldung/ipc/DirectoryLiveTest.java new file mode 100644 index 0000000000..ca7b6d2a0e --- /dev/null +++ b/core-java-modules/core-java-ipc/src/test/java/com/baeldung/ipc/DirectoryLiveTest.java @@ -0,0 +1,32 @@ +package com.baeldung.ipc; + +import org.junit.jupiter.api.Test; + +import java.nio.file.FileSystems; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardWatchEventKinds; +import java.nio.file.WatchKey; +import java.nio.file.WatchEvent; +import java.nio.file.WatchService; + + +public class DirectoryLiveTest { + @Test + public void consumer() throws Exception { + WatchService watchService = FileSystems.getDefault().newWatchService(); + // Set this to an appropriate directory. + Path path = Paths.get("/tmp/ipc"); + + path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE); + + WatchKey key; + while ((key = watchService.take()) != null) { + for (WatchEvent event : key.pollEvents()) { + // React to new file. + System.out.println(event); + } + key.reset(); + } + } +} diff --git a/core-java-modules/core-java-ipc/src/test/java/com/baeldung/ipc/JmxLiveTest.java b/core-java-modules/core-java-ipc/src/test/java/com/baeldung/ipc/JmxLiveTest.java new file mode 100644 index 0000000000..8ac16fdfc3 --- /dev/null +++ b/core-java-modules/core-java-ipc/src/test/java/com/baeldung/ipc/JmxLiveTest.java @@ -0,0 +1,52 @@ +package com.baeldung.ipc; + +import org.junit.jupiter.api.Test; + +import javax.management.JMX; +import javax.management.MBeanServer; +import javax.management.ObjectName; +import javax.management.remote.JMXConnector; +import javax.management.remote.JMXConnectorFactory; +import javax.management.remote.JMXServiceURL; +import java.lang.management.ManagementFactory; +import java.util.concurrent.TimeUnit; + +public class JmxLiveTest { + /* + * This test needs to be run with the following system properties defined: + * -Dcom.sun.management.jmxremote=true + * -Dcom.sun.management.jmxremote.port=1234 + * -Dcom.sun.management.jmxremote.authenticate=false + * -Dcom.sun.management.jmxremote.ssl=false + */ + @Test + public void consumer() throws Exception { + ObjectName objectName = new ObjectName("com.baeldung.ipc:type=basic,name=test"); + MBeanServer server = ManagementFactory.getPlatformMBeanServer(); + server.registerMBean(new IPCTest(), objectName); + + TimeUnit.MINUTES.sleep(50); + } + + @Test + public void producer() throws Exception { + JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:1234/jmxrmi"); + try (JMXConnector jmxc = JMXConnectorFactory.connect(url, null)) { + ObjectName objectName = new ObjectName("com.baeldung.ipc:type=basic,name=test"); + + IPCTestMBean mbeanProxy = JMX.newMBeanProxy(jmxc.getMBeanServerConnection(), objectName, IPCTestMBean.class, true); + mbeanProxy.sendMessage("Hello"); + } + } + + public interface IPCTestMBean { + void sendMessage(String message); + } + + class IPCTest implements IPCTestMBean { + @Override + public void sendMessage(String message) { + System.out.println("Received message: " + message); + } + } +} diff --git a/core-java-modules/core-java-ipc/src/test/java/com/baeldung/ipc/SocketsLiveTest.java b/core-java-modules/core-java-ipc/src/test/java/com/baeldung/ipc/SocketsLiveTest.java new file mode 100644 index 0000000000..9b006c110e --- /dev/null +++ b/core-java-modules/core-java-ipc/src/test/java/com/baeldung/ipc/SocketsLiveTest.java @@ -0,0 +1,38 @@ +package com.baeldung.ipc; + +import org.junit.jupiter.api.Test; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.net.ServerSocket; +import java.net.Socket; + +public class SocketsLiveTest { + @Test + public void consumer() throws Exception { + try (ServerSocket serverSocket = new ServerSocket(1234)) { + Socket clientSocket = serverSocket.accept(); + + PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); + BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); + + String line; + while ((line = in.readLine()) != null) { + System.out.println("Received message: " + line); + } + } + } + + @Test + public void producer() throws Exception { + try (Socket clientSocket = new Socket("localhost", 1234)) { + PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); + BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); + + out.println("Hello"); + + String response = in.readLine(); + } + } +} \ No newline at end of file diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml index 9343343b6e..b3ef8167a5 100644 --- a/core-java-modules/pom.xml +++ b/core-java-modules/pom.xml @@ -54,6 +54,7 @@ core-java-concurrency-simple core-java-datetime-string core-java-io-conversions-2 + core-java-ipc core-java-jpms core-java-lang-oop-constructors-2 core-java-methods From fa272d33953eb2b765be896acba462a5f2a28650 Mon Sep 17 00:00:00 2001 From: michaelin007 Date: Sat, 25 Nov 2023 05:25:47 +0000 Subject: [PATCH 110/228] Retrieving Unix Time in Java --- .../baeldung/unixtime/UnixTimeUnitTest.java | 50 ++++++++----------- 1 file changed, 21 insertions(+), 29 deletions(-) diff --git a/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/unixtime/UnixTimeUnitTest.java b/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/unixtime/UnixTimeUnitTest.java index d1518ceef5..eedd897e91 100644 --- a/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/unixtime/UnixTimeUnitTest.java +++ b/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/unixtime/UnixTimeUnitTest.java @@ -1,50 +1,42 @@ package com.baeldung.unixtime; - import static org.junit.Assert.assertEquals; - import java.time.Instant; +import java.time.LocalDate; + +import java.time.Month; +import java.time.ZoneId; import java.util.Date; import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; + import org.junit.jupiter.api.Test; public class UnixTimeUnitTest { @Test - public void givenCurrentTimeUsingDateApi_whenConvertedToUnixTime_thenConsistent() { - long marginOfError = 1L; - Date date = new Date(); - long longTime = date.getTime() / 1000L; - - for (int i = 0; i < 10; i++) { - long unixTime = System.currentTimeMillis() / 1000L; - assertEquals(longTime, unixTime, marginOfError); - } + public void givenTimeUsingDateApi_whenConvertedToUnixTime_thenMatch() { + Date date = new Date(2023 - 1900, 1, 15, 0, 0, 0); + long expected = 1676419200; + long actual = date.getTime() / 1000L; + assertEquals(expected, actual); } @Test - public void givenCurrentTimeUsingInstantNow_whenConvertedToUnixTime_thenConsistent() { - long marginOfError = 1L; - long longTime = Instant.now().getEpochSecond(); - - for (int i = 0; i < 10; i++) { - long unixTime = System.currentTimeMillis() / 1000L; - assertEquals(longTime, unixTime, marginOfError); - } + public void givenTimeUsingJodaTime_whenConvertedToUnixTime_thenMatch() { + DateTime dateTime = new DateTime(2023, 2, 15, 00, 00, 00, 0); + long expected = 1676419200; + long actual = dateTime.getMillis() / 1000L; + assertEquals(expected, actual); } @Test - public void givenCurrentTimeUsingJodaTime_whenConvertedToUnixTime_thenConsistent() { - long marginOfError = 1L; - DateTime dateTime = DateTime.now(DateTimeZone.UTC); - long longTime = dateTime.getMillis() / 1000L; - - for (int i = 0; i < 10; i++) { - long unixTime = System.currentTimeMillis() / 1000L; - assertEquals(longTime, unixTime, marginOfError); - } + public void givenTimeUsingLocalDate_whenConvertedToUnixTime_thenMatch() { + LocalDate date = LocalDate.of(2023, Month.FEBRUARY, 15); + Instant instant = date.atStartOfDay().atZone(ZoneId.of("UTC")).toInstant(); + long expected = 1676419200; + long actual = instant.getEpochSecond(); + assertEquals(expected, actual); } } From 41979445efc0c426dbeb6dbcf86c52d3693de040 Mon Sep 17 00:00:00 2001 From: panos-kakos <102670093+panos-kakos@users.noreply.github.com> Date: Sat, 25 Nov 2023 12:03:07 +0200 Subject: [PATCH 111/228] Java 26374 Identify and move popular Boot articles (#15139) --- .../spring-data-jpa-repo-2/README.md | 2 -- .../spring-data-jpa-repo-2/pom.xml | 5 ----- .../src/test/resources/test-movie-cleanup.sql | 1 - .../src/test/resources/test-movie-data.sql | 7 ------- .../spring-data-jpa-repo/README.md | 3 +++ persistence-modules/spring-data-jpa-repo/pom.xml | 5 +++++ .../main/java/com/baeldung}/repository/Foo.java | 9 +++++++-- .../com/baeldung}/repository/FooService.java | 2 +- .../java/com/baeldung}/repository/IFooDAO.java | 3 ++- .../com/baeldung}/repository/IFooService.java | 2 +- .../baeldung}/repository/PersistenceConfig.java | 14 ++++++++------ .../data/persistence/like/LikeApplication.java | 0 .../data/persistence/like/model/Movie.java | 0 .../like/repository/MovieRepository.java | 5 +++-- .../src/main/resources/persistence.properties | 9 +++++++++ .../src/main/resources/springDataConfig.xml | 2 +- .../repository/FooServiceIntegrationTest.java | 6 +++--- .../like/MovieRepositoryIntegrationTest.java | 16 +++++++++------- .../test/resources/application-test.properties | 4 ++-- .../src/test/resources/test-movie-cleanup.sql | 1 + .../src/test/resources/test-movie-data.sql | 7 +++++++ 21 files changed, 62 insertions(+), 41 deletions(-) delete mode 100644 persistence-modules/spring-data-jpa-repo-2/src/test/resources/test-movie-cleanup.sql delete mode 100644 persistence-modules/spring-data-jpa-repo-2/src/test/resources/test-movie-data.sql rename persistence-modules/{spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence => spring-data-jpa-repo/src/main/java/com/baeldung}/repository/Foo.java (87%) rename persistence-modules/{spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence => spring-data-jpa-repo/src/main/java/com/baeldung}/repository/FooService.java (83%) rename persistence-modules/{spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence => spring-data-jpa-repo/src/main/java/com/baeldung}/repository/IFooDAO.java (82%) rename persistence-modules/{spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence => spring-data-jpa-repo/src/main/java/com/baeldung}/repository/IFooService.java (50%) rename persistence-modules/{spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence => spring-data-jpa-repo/src/main/java/com/baeldung}/repository/PersistenceConfig.java (93%) rename persistence-modules/{spring-data-jpa-repo-2 => spring-data-jpa-repo}/src/main/java/com/baeldung/spring/data/persistence/like/LikeApplication.java (100%) rename persistence-modules/{spring-data-jpa-repo-2 => spring-data-jpa-repo}/src/main/java/com/baeldung/spring/data/persistence/like/model/Movie.java (100%) rename persistence-modules/{spring-data-jpa-repo-2 => spring-data-jpa-repo}/src/main/java/com/baeldung/spring/data/persistence/like/repository/MovieRepository.java (99%) create mode 100644 persistence-modules/spring-data-jpa-repo/src/main/resources/persistence.properties rename persistence-modules/{spring-data-jpa-repo-2 => spring-data-jpa-repo}/src/main/resources/springDataConfig.xml (84%) rename persistence-modules/{spring-data-jpa-repo-2/src/test/java/com/baeldung/spring/data/persistence => spring-data-jpa-repo/src/test/java/com/baeldung}/repository/FooServiceIntegrationTest.java (92%) rename persistence-modules/{spring-data-jpa-repo-2 => spring-data-jpa-repo}/src/test/java/com/baeldung/spring/data/persistence/like/MovieRepositoryIntegrationTest.java (99%) create mode 100644 persistence-modules/spring-data-jpa-repo/src/test/resources/test-movie-cleanup.sql create mode 100644 persistence-modules/spring-data-jpa-repo/src/test/resources/test-movie-data.sql diff --git a/persistence-modules/spring-data-jpa-repo-2/README.md b/persistence-modules/spring-data-jpa-repo-2/README.md index 23134ec02d..8c588405f7 100644 --- a/persistence-modules/spring-data-jpa-repo-2/README.md +++ b/persistence-modules/spring-data-jpa-repo-2/README.md @@ -2,9 +2,7 @@ ### Relevant Articles: -- [Introduction to Spring Data JPA](https://www.baeldung.com/the-persistence-layer-with-spring-data-jpa) - [Performance Difference Between save() and saveAll() in Spring Data](https://www.baeldung.com/spring-data-save-saveall) -- [LIKE Queries in Spring JPA Repositories](https://www.baeldung.com/spring-jpa-like-queries) - [How to Access EntityManager with Spring Data](https://www.baeldung.com/spring-data-entitymanager) - [Difference Between JPA and Spring Data JPA](https://www.baeldung.com/spring-data-jpa-vs-jpa) - [Differences Between Spring Data JPA findFirst() and findTop()](https://www.baeldung.com/spring-data-jpa-findfirst-vs-findtop) diff --git a/persistence-modules/spring-data-jpa-repo-2/pom.xml b/persistence-modules/spring-data-jpa-repo-2/pom.xml index 8186a0f7a5..e39458449c 100644 --- a/persistence-modules/spring-data-jpa-repo-2/pom.xml +++ b/persistence-modules/spring-data-jpa-repo-2/pom.xml @@ -42,11 +42,6 @@ com.querydsl querydsl-jpa - - com.google.guava - guava - ${guava.version} - diff --git a/persistence-modules/spring-data-jpa-repo-2/src/test/resources/test-movie-cleanup.sql b/persistence-modules/spring-data-jpa-repo-2/src/test/resources/test-movie-cleanup.sql deleted file mode 100644 index 0ba0ba0694..0000000000 --- a/persistence-modules/spring-data-jpa-repo-2/src/test/resources/test-movie-cleanup.sql +++ /dev/null @@ -1 +0,0 @@ -DELETE FROM "movie"; \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-repo-2/src/test/resources/test-movie-data.sql b/persistence-modules/spring-data-jpa-repo-2/src/test/resources/test-movie-data.sql deleted file mode 100644 index 0eb9638f43..0000000000 --- a/persistence-modules/spring-data-jpa-repo-2/src/test/resources/test-movie-data.sql +++ /dev/null @@ -1,7 +0,0 @@ -INSERT INTO "movie" ("id", "title", "director", "rating", "duration") VALUES(1, 'Godzilla: King of the Monsters', ' Michael Dougherty', 'PG-13', 132); -INSERT INTO "movie" ("id", "title", "director", "rating", "duration") VALUES(2, 'Avengers: Endgame', 'Anthony Russo', 'PG-13', 181); -INSERT INTO "movie" ("id", "title", "director", "rating", "duration") VALUES(3, 'Captain Marvel', 'Anna Boden', 'PG-13', 123); -INSERT INTO "movie" ("id", "title", "director", "rating", "duration") VALUES(4, 'Dumbo', 'Tim Burton', 'PG', 112); -INSERT INTO "movie" ("id", "title", "director", "rating", "duration") VALUES(5, 'Booksmart', 'Olivia Wilde', 'R', 102); -INSERT INTO "movie" ("id", "title", "director", "rating", "duration") VALUES(6, 'Aladdin', 'Guy Ritchie', 'PG', 128); -INSERT INTO "movie" ("id", "title", "director", "rating", "duration") VALUES(7, 'The Sun Is Also a Star', 'Ry Russo-Young', 'PG-13', 100); diff --git a/persistence-modules/spring-data-jpa-repo/README.md b/persistence-modules/spring-data-jpa-repo/README.md index 43097a8c1e..9587f544f9 100644 --- a/persistence-modules/spring-data-jpa-repo/README.md +++ b/persistence-modules/spring-data-jpa-repo/README.md @@ -3,6 +3,7 @@ This module contains articles about repositories in Spring Data JPA ### Relevant Articles: +- [Introduction to Spring Data JPA](https://www.baeldung.com/the-persistence-layer-with-spring-data-jpa) - [Case Insensitive Queries with Spring Data Repository](https://www.baeldung.com/spring-data-case-insensitive-queries) - [Derived Query Methods in Spring Data JPA Repositories](https://www.baeldung.com/spring-data-derived-queries) - [Spring Data – CrudRepository save() Method](https://www.baeldung.com/spring-data-crud-repository-save) @@ -10,6 +11,8 @@ This module contains articles about repositories in Spring Data JPA - [Spring Data Composable Repositories](https://www.baeldung.com/spring-data-composable-repositories) - [Spring Data JPA Repository Populators](https://www.baeldung.com/spring-data-jpa-repository-populators) - [Calling Stored Procedures from Spring Data JPA Repositories](https://www.baeldung.com/spring-data-jpa-stored-procedures) +- [LIKE Queries in Spring JPA Repositories](https://www.baeldung.com/spring-jpa-like-queries) + - More articles: [[--> next]](../spring-data-jpa-repo-2) ### Eclipse Config diff --git a/persistence-modules/spring-data-jpa-repo/pom.xml b/persistence-modules/spring-data-jpa-repo/pom.xml index 26fff365a1..2b2bf33d7f 100644 --- a/persistence-modules/spring-data-jpa-repo/pom.xml +++ b/persistence-modules/spring-data-jpa-repo/pom.xml @@ -42,6 +42,11 @@ org.springframework spring-oxm + + com.google.guava + guava + ${guava.version} + \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/Foo.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/Foo.java similarity index 87% rename from persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/Foo.java rename to persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/Foo.java index 6833c4c556..27ebcf5875 100644 --- a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/Foo.java +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/Foo.java @@ -1,8 +1,13 @@ -package com.baeldung.spring.data.persistence.repository; +package com.baeldung.repository; -import javax.persistence.*; import java.io.Serializable; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + @Entity public class Foo implements Serializable { @Id diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/FooService.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/FooService.java similarity index 83% rename from persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/FooService.java rename to persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/FooService.java index cb09a92b82..98084240ac 100644 --- a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/FooService.java +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/FooService.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.data.persistence.repository; +package com.baeldung.repository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/IFooDAO.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/IFooDAO.java similarity index 82% rename from persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/IFooDAO.java rename to persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/IFooDAO.java index 20a81e7bfa..6ee74fe26c 100644 --- a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/IFooDAO.java +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/IFooDAO.java @@ -1,8 +1,9 @@ -package com.baeldung.spring.data.persistence.repository; +package com.baeldung.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; public interface IFooDAO extends JpaRepository { diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/IFooService.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/IFooService.java similarity index 50% rename from persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/IFooService.java rename to persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/IFooService.java index 8ce6a2d1ae..6c4d36710c 100644 --- a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/IFooService.java +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/IFooService.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.data.persistence.repository; +package com.baeldung.repository; public interface IFooService { Foo create(Foo foo); diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/PersistenceConfig.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/PersistenceConfig.java similarity index 93% rename from persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/PersistenceConfig.java rename to persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/PersistenceConfig.java index f73ea94658..f3c9301bcf 100644 --- a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/PersistenceConfig.java +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/PersistenceConfig.java @@ -1,6 +1,9 @@ -package com.baeldung.spring.data.persistence.repository; +package com.baeldung.repository; + +import java.util.Properties; + +import javax.sql.DataSource; -import com.google.common.base.Preconditions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; @@ -16,15 +19,14 @@ import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; -import javax.sql.DataSource; -import java.util.Properties; +import com.google.common.base.Preconditions; @Configuration @PropertySource("classpath:persistence.properties") -@ComponentScan("com.baeldung.spring.data.persistence.repository") +@ComponentScan("com.baeldung.repository") //@ImportResource("classpath*:*springDataConfig.xml") @EnableTransactionManagement -@EnableJpaRepositories(basePackages = "com.baeldung.spring.data.persistence.repository") +@EnableJpaRepositories(basePackages = "com.baeldung.repository") public class PersistenceConfig { @Autowired diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/like/LikeApplication.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/spring/data/persistence/like/LikeApplication.java similarity index 100% rename from persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/like/LikeApplication.java rename to persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/spring/data/persistence/like/LikeApplication.java diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/like/model/Movie.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/spring/data/persistence/like/model/Movie.java similarity index 100% rename from persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/like/model/Movie.java rename to persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/spring/data/persistence/like/model/Movie.java diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/like/repository/MovieRepository.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/spring/data/persistence/like/repository/MovieRepository.java similarity index 99% rename from persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/like/repository/MovieRepository.java rename to persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/spring/data/persistence/like/repository/MovieRepository.java index 57befb5943..06e75222a3 100644 --- a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/like/repository/MovieRepository.java +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/spring/data/persistence/like/repository/MovieRepository.java @@ -1,11 +1,12 @@ package com.baeldung.spring.data.persistence.like.repository; -import com.baeldung.spring.data.persistence.like.model.Movie; +import java.util.List; + import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; -import java.util.List; +import com.baeldung.spring.data.persistence.like.model.Movie; public interface MovieRepository extends CrudRepository { diff --git a/persistence-modules/spring-data-jpa-repo/src/main/resources/persistence.properties b/persistence-modules/spring-data-jpa-repo/src/main/resources/persistence.properties new file mode 100644 index 0000000000..05cb7a13b9 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/main/resources/persistence.properties @@ -0,0 +1,9 @@ +# jdbc.X +jdbc.driverClassName=org.h2.Driver +jdbc.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1 +jdbc.user=sa +jdbc.pass=sa + +# hibernate.X +hibernate.hbm2ddl.auto=create-drop +hibernate.dialect=org.hibernate.dialect.H2Dialect diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/resources/springDataConfig.xml b/persistence-modules/spring-data-jpa-repo/src/main/resources/springDataConfig.xml similarity index 84% rename from persistence-modules/spring-data-jpa-repo-2/src/main/resources/springDataConfig.xml rename to persistence-modules/spring-data-jpa-repo/src/main/resources/springDataConfig.xml index b2616d9eae..e581d514a4 100644 --- a/persistence-modules/spring-data-jpa-repo-2/src/main/resources/springDataConfig.xml +++ b/persistence-modules/spring-data-jpa-repo/src/main/resources/springDataConfig.xml @@ -7,5 +7,5 @@ http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd" > - + \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-repo-2/src/test/java/com/baeldung/spring/data/persistence/repository/FooServiceIntegrationTest.java b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/repository/FooServiceIntegrationTest.java similarity index 92% rename from persistence-modules/spring-data-jpa-repo-2/src/test/java/com/baeldung/spring/data/persistence/repository/FooServiceIntegrationTest.java rename to persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/repository/FooServiceIntegrationTest.java index 21990afb5e..9362b4c338 100644 --- a/persistence-modules/spring-data-jpa-repo-2/src/test/java/com/baeldung/spring/data/persistence/repository/FooServiceIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/repository/FooServiceIntegrationTest.java @@ -1,4 +1,6 @@ -package com.baeldung.spring.data.persistence.repository; +package com.baeldung.repository; + +import javax.sql.DataSource; import org.junit.Test; import org.junit.runner.RunWith; @@ -7,8 +9,6 @@ import org.springframework.dao.DataIntegrityViolationException; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; -import javax.sql.DataSource; - @RunWith(SpringRunner.class) @ContextConfiguration(classes = PersistenceConfig.class) public class FooServiceIntegrationTest { diff --git a/persistence-modules/spring-data-jpa-repo-2/src/test/java/com/baeldung/spring/data/persistence/like/MovieRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/spring/data/persistence/like/MovieRepositoryIntegrationTest.java similarity index 99% rename from persistence-modules/spring-data-jpa-repo-2/src/test/java/com/baeldung/spring/data/persistence/like/MovieRepositoryIntegrationTest.java rename to persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/spring/data/persistence/like/MovieRepositoryIntegrationTest.java index 291926c127..dcb87a26a6 100644 --- a/persistence-modules/spring-data-jpa-repo-2/src/test/java/com/baeldung/spring/data/persistence/like/MovieRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/spring/data/persistence/like/MovieRepositoryIntegrationTest.java @@ -1,7 +1,12 @@ package com.baeldung.spring.data.persistence.like; -import com.baeldung.spring.data.persistence.like.model.Movie; -import com.baeldung.spring.data.persistence.like.repository.MovieRepository; +import static org.junit.Assert.assertEquals; +import static org.springframework.test.context.jdbc.Sql.ExecutionPhase.AFTER_TEST_METHOD; + +import java.util.List; + +import javax.sql.DataSource; + import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -9,11 +14,8 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.jdbc.Sql; import org.springframework.test.context.junit4.SpringRunner; -import javax.sql.DataSource; -import java.util.List; - -import static org.junit.Assert.assertEquals; -import static org.springframework.test.context.jdbc.Sql.ExecutionPhase.AFTER_TEST_METHOD; +import com.baeldung.spring.data.persistence.like.model.Movie; +import com.baeldung.spring.data.persistence.like.repository.MovieRepository; @RunWith(SpringRunner.class) @Sql(scripts = { "/test-movie-data.sql" }) diff --git a/persistence-modules/spring-data-jpa-repo/src/test/resources/application-test.properties b/persistence-modules/spring-data-jpa-repo/src/test/resources/application-test.properties index f9497c8f37..6f93e7d79d 100644 --- a/persistence-modules/spring-data-jpa-repo/src/test/resources/application-test.properties +++ b/persistence-modules/spring-data-jpa-repo/src/test/resources/application-test.properties @@ -1,2 +1,2 @@ -spring.jpa.hibernate.ddl-auto=update -spring.datasource.url=jdbc:h2:mem:jpa3 \ No newline at end of file +#spring.jpa.hibernate.ddl-auto=update +#spring.datasource.url=jdbc:h2:mem:jpa3 \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-repo/src/test/resources/test-movie-cleanup.sql b/persistence-modules/spring-data-jpa-repo/src/test/resources/test-movie-cleanup.sql new file mode 100644 index 0000000000..e2e70a6a74 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/test/resources/test-movie-cleanup.sql @@ -0,0 +1 @@ +DELETE FROM movie; \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-repo/src/test/resources/test-movie-data.sql b/persistence-modules/spring-data-jpa-repo/src/test/resources/test-movie-data.sql new file mode 100644 index 0000000000..3b706f14e3 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/test/resources/test-movie-data.sql @@ -0,0 +1,7 @@ +INSERT INTO movie(id,title,director,rating,duration) VALUES(1, 'Godzilla: King of the Monsters', ' Michael Dougherty', 'PG-13', 132); +INSERT INTO movie(id,title,director,rating,duration) VALUES(2, 'Avengers: Endgame', 'Anthony Russo', 'PG-13', 181); +INSERT INTO movie(id,title,director,rating,duration) VALUES(3, 'Captain Marvel', 'Anna Boden', 'PG-13', 123); +INSERT INTO movie(id,title,director,rating,duration) VALUES(4, 'Dumbo', 'Tim Burton', 'PG', 112); +INSERT INTO movie(id,title,director,rating,duration) VALUES(5, 'Booksmart', 'Olivia Wilde', 'R', 102); +INSERT INTO movie(id,title,director,rating,duration) VALUES(6, 'Aladdin', 'Guy Ritchie', 'PG', 128); +INSERT INTO movie(id,title,director,rating,duration) VALUES(7, 'The Sun Is Also a Star', 'Ry Russo-Young', 'PG-13', 100); From 7df2f25fdb836be6b6057ad824ec30931cd00179 Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Sat, 25 Nov 2023 16:35:00 +0530 Subject: [PATCH 112/228] JAVA-26737 Upgarde hibernate ehcache version in spring-hibernate-5 module --- persistence-modules/spring-hibernate-5/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/persistence-modules/spring-hibernate-5/pom.xml b/persistence-modules/spring-hibernate-5/pom.xml index e559fe1394..d3ba647af2 100644 --- a/persistence-modules/spring-hibernate-5/pom.xml +++ b/persistence-modules/spring-hibernate-5/pom.xml @@ -131,7 +131,7 @@ 1.10.6.RELEASE 4.2.1.RELEASE - 5.2.10.Final + 5.6.15.Final 5.8.2.Final 8.0.7-dmr 9.0.0.M26 From ad7f1c7486cc2948af1d09e1512737982c125038 Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Sat, 25 Nov 2023 16:43:03 +0530 Subject: [PATCH 113/228] JAVA-26737 Upgrade hibernate ehcache version in hibernate-libraries module --- persistence-modules/hibernate-libraries/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/persistence-modules/hibernate-libraries/pom.xml b/persistence-modules/hibernate-libraries/pom.xml index 3f4da28296..d701487676 100644 --- a/persistence-modules/hibernate-libraries/pom.xml +++ b/persistence-modules/hibernate-libraries/pom.xml @@ -162,7 +162,7 @@ 1.6 2.9.7 - 5.4.14.Final + 5.6.15.Final 3.27.0-GA 2.3.1 2.0.0 From 6032d3691d56d5196da427b9cb29e2e1bc85e504 Mon Sep 17 00:00:00 2001 From: Harpal Singh Date: Thu, 23 Nov 2023 23:12:42 +0100 Subject: [PATCH 114/228] JAVA-26757: Update pdf to a new version of thymeleaf. --- pdf/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pdf/pom.xml b/pdf/pom.xml index 34094481bf..041f356b9a 100644 --- a/pdf/pom.xml +++ b/pdf/pom.xml @@ -111,7 +111,7 @@ 3.15 1.8 3.15 - 3.0.11.RELEASE + 3.1.2.RELEASE 9.3.1 1.0.6 1.0.10 From 126594bacf59c11a908f8a50e04486678b784e95 Mon Sep 17 00:00:00 2001 From: Harpal Singh Date: Thu, 23 Nov 2023 23:25:37 +0100 Subject: [PATCH 115/228] JAVA-26757: Update spring-thymeleaf-5 to new version of thymeleaf. --- spring-web-modules/spring-thymeleaf-5/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-web-modules/spring-thymeleaf-5/pom.xml b/spring-web-modules/spring-thymeleaf-5/pom.xml index 2d178bd933..e6b0511ce5 100644 --- a/spring-web-modules/spring-thymeleaf-5/pom.xml +++ b/spring-web-modules/spring-thymeleaf-5/pom.xml @@ -135,7 +135,7 @@ 2.3.2.RELEASE - 3.0.11.RELEASE + 3.1.2.RELEASE 3.0.4.RELEASE 2.4.1 2.0.1.Final From e01877df5007d449b7dc2fbd6e9844d3d39ee670 Mon Sep 17 00:00:00 2001 From: Harpal Singh Date: Thu, 23 Nov 2023 23:33:07 +0100 Subject: [PATCH 116/228] JAVA-26757: Update spring-mvc-basics-2 to new version of thymeleaf. --- spring-web-modules/spring-mvc-basics-2/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-web-modules/spring-mvc-basics-2/pom.xml b/spring-web-modules/spring-mvc-basics-2/pom.xml index 613e42dee3..32cf3c9e9f 100644 --- a/spring-web-modules/spring-mvc-basics-2/pom.xml +++ b/spring-web-modules/spring-mvc-basics-2/pom.xml @@ -150,7 +150,7 @@ 8.0.1.Final enter-location-of-server - 3.0.11.RELEASE + 3.1.2.RELEASE 2.4.12 2.3.27-incubating 1.2.5 From 36dfdf283294c3297ba9ca8377ddef33ad6d68f3 Mon Sep 17 00:00:00 2001 From: Harpal Singh Date: Thu, 23 Nov 2023 23:40:08 +0100 Subject: [PATCH 117/228] JAVA-26757: Update spring-thymeleaf to new version of thymeleaf. --- spring-web-modules/spring-thymeleaf/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-web-modules/spring-thymeleaf/pom.xml b/spring-web-modules/spring-thymeleaf/pom.xml index ce0c0a7e21..ca94d4581e 100644 --- a/spring-web-modules/spring-thymeleaf/pom.xml +++ b/spring-web-modules/spring-thymeleaf/pom.xml @@ -136,7 +136,7 @@ 2.3.2.RELEASE - 3.0.11.RELEASE + 3.1.2.RELEASE 3.0.4.RELEASE 2.4.1 2.0.1.Final From 25bfddf417ea1ce8feb994101ccf771f38c4ef02 Mon Sep 17 00:00:00 2001 From: Geoffrey De Smet Date: Sat, 25 Nov 2023 14:15:27 +0100 Subject: [PATCH 118/228] Limit solving duration to 2 seconds --- .../java/com/baeldung/timefoldsolver/ShiftScheduleApp.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/timefold-solver/src/main/java/com/baeldung/timefoldsolver/ShiftScheduleApp.java b/timefold-solver/src/main/java/com/baeldung/timefoldsolver/ShiftScheduleApp.java index 24666ac6aa..e8dc02e2b3 100644 --- a/timefold-solver/src/main/java/com/baeldung/timefoldsolver/ShiftScheduleApp.java +++ b/timefold-solver/src/main/java/com/baeldung/timefoldsolver/ShiftScheduleApp.java @@ -20,9 +20,9 @@ public class ShiftScheduleApp { SolverFactory solverFactory = SolverFactory.create(new SolverConfig().withSolutionClass(ShiftSchedule.class) .withEntityClasses(Shift.class) .withConstraintProviderClass(ShiftScheduleConstraintProvider.class) - // The solver runs only for 5 seconds on this small dataset. - // It's recommended to run for at least 5 minutes ("5m") otherwise. - .withTerminationSpentLimit(Duration.ofSeconds(5))); + // The solver runs only for 2 seconds on this tiny dataset. + // It's recommended to run for at least 5 minutes ("5m") on large datasets. + .withTerminationSpentLimit(Duration.ofSeconds(2))); Solver solver = solverFactory.buildSolver(); ShiftSchedule problem = loadProblem(); From 5df3c5711ada202a685a1f193f0bb2a32986c806 Mon Sep 17 00:00:00 2001 From: Geoffrey De Smet Date: Sat, 25 Nov 2023 14:35:43 +0100 Subject: [PATCH 119/228] Make PMD happy --- ...erTest.java => ShiftScheduleConstraintProviderUnitTest.java} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename timefold-solver/src/test/java/com/baeldung/timefoldsolver/{ShiftScheduleConstraintProviderTest.java => ShiftScheduleConstraintProviderUnitTest.java} (97%) diff --git a/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleConstraintProviderTest.java b/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleConstraintProviderUnitTest.java similarity index 97% rename from timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleConstraintProviderTest.java rename to timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleConstraintProviderUnitTest.java index 0832cd7bdd..3a3f4dc032 100644 --- a/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleConstraintProviderTest.java +++ b/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleConstraintProviderUnitTest.java @@ -7,7 +7,7 @@ import org.junit.jupiter.api.Test; import ai.timefold.solver.test.api.score.stream.ConstraintVerifier; -class ShiftScheduleConstraintProviderTest { +class ShiftScheduleConstraintProviderUnitTest { private static final LocalDate MONDAY = LocalDate.of(2030, 4, 1); private static final LocalDate TUESDAY = LocalDate.of(2030, 4, 2); From d0a2127248b1e7ef0cf13706422b35b620c78042 Mon Sep 17 00:00:00 2001 From: Lucian Snare Date: Sat, 25 Nov 2023 10:35:19 -0500 Subject: [PATCH 120/228] BAEL-7083: Gson class declares multiple fields (#15244) * Add initial classes and tests for Gson multiple fields error * Add test classes and exclusion strategy * Add test cases * Simplify example code --- .../gson/multiplefields/BasicStudent.java | 64 +++++++++++++++++ .../StudentExclusionStrategy.java | 18 +++++ .../gson/multiplefields/StudentV1.java | 34 +++++++++ .../gson/multiplefields/StudentV2.java | 71 +++++++++++++++++++ .../GsonMultipleFieldsUnitTest.java | 65 +++++++++++++++++ 5 files changed, 252 insertions(+) create mode 100644 json-modules/gson-2/src/main/java/com/baeldung/gson/multiplefields/BasicStudent.java create mode 100644 json-modules/gson-2/src/main/java/com/baeldung/gson/multiplefields/StudentExclusionStrategy.java create mode 100644 json-modules/gson-2/src/main/java/com/baeldung/gson/multiplefields/StudentV1.java create mode 100644 json-modules/gson-2/src/main/java/com/baeldung/gson/multiplefields/StudentV2.java create mode 100644 json-modules/gson-2/src/test/java/com/baeldung/gson/multiplefields/GsonMultipleFieldsUnitTest.java diff --git a/json-modules/gson-2/src/main/java/com/baeldung/gson/multiplefields/BasicStudent.java b/json-modules/gson-2/src/main/java/com/baeldung/gson/multiplefields/BasicStudent.java new file mode 100644 index 0000000000..9c8d5f0923 --- /dev/null +++ b/json-modules/gson-2/src/main/java/com/baeldung/gson/multiplefields/BasicStudent.java @@ -0,0 +1,64 @@ +package com.baeldung.gson.multiplefields; + +import java.util.Objects; + +import com.google.gson.annotations.SerializedName; + +public class BasicStudent { + + private String name; + + private transient String major; + + @SerializedName("major") + private String concentration; + + public BasicStudent() { + + } + + public BasicStudent(String name, String major, String concentration) { + this.name = name; + this.major = major; + this.concentration = concentration; + } + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (!(o instanceof BasicStudent)) + return false; + BasicStudent student = (BasicStudent) o; + return Objects.equals(name, student.name) && Objects.equals(major, student.major) && Objects.equals(concentration, student.concentration); + } + + @Override + public int hashCode() { + return Objects.hash(name, major, concentration); + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getMajor() { + return major; + } + + public void setMajor(String major) { + this.major = major; + } + + public String getConcentration() { + return concentration; + } + + public void setConcentration(String concentration) { + this.concentration = concentration; + } +} diff --git a/json-modules/gson-2/src/main/java/com/baeldung/gson/multiplefields/StudentExclusionStrategy.java b/json-modules/gson-2/src/main/java/com/baeldung/gson/multiplefields/StudentExclusionStrategy.java new file mode 100644 index 0000000000..5dad30a138 --- /dev/null +++ b/json-modules/gson-2/src/main/java/com/baeldung/gson/multiplefields/StudentExclusionStrategy.java @@ -0,0 +1,18 @@ +package com.baeldung.gson.multiplefields; + +import com.google.gson.ExclusionStrategy; +import com.google.gson.FieldAttributes; + +public class StudentExclusionStrategy implements ExclusionStrategy { + + @Override + public boolean shouldSkipField(FieldAttributes field) { + // Ignore all field values from V1 type + return field.getDeclaringClass() == StudentV1.class; + } + + @Override + public boolean shouldSkipClass(Class aClass) { + return false; + } +} diff --git a/json-modules/gson-2/src/main/java/com/baeldung/gson/multiplefields/StudentV1.java b/json-modules/gson-2/src/main/java/com/baeldung/gson/multiplefields/StudentV1.java new file mode 100644 index 0000000000..49a09b830c --- /dev/null +++ b/json-modules/gson-2/src/main/java/com/baeldung/gson/multiplefields/StudentV1.java @@ -0,0 +1,34 @@ +package com.baeldung.gson.multiplefields; + +public class StudentV1 { + + private String firstName; + private String lastName; + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + // Default constructor for Gson + public StudentV1() { + + } + + public StudentV1(String firstName, String lastName) { + this.firstName = firstName; + this.lastName = lastName; + } + +} diff --git a/json-modules/gson-2/src/main/java/com/baeldung/gson/multiplefields/StudentV2.java b/json-modules/gson-2/src/main/java/com/baeldung/gson/multiplefields/StudentV2.java new file mode 100644 index 0000000000..e31d33e3fd --- /dev/null +++ b/json-modules/gson-2/src/main/java/com/baeldung/gson/multiplefields/StudentV2.java @@ -0,0 +1,71 @@ +package com.baeldung.gson.multiplefields; + +import java.util.Objects; + +import com.google.gson.annotations.Expose; + +public class StudentV2 extends StudentV1 { + + @Expose + private String firstName; + + @Expose + private String lastName; + + @Expose + private String major; + + @Override + public String getFirstName() { + return firstName; + } + + @Override + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + @Override + public String getLastName() { + return lastName; + } + + @Override + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getMajor() { + return major; + } + + public void setMajor(String major) { + this.major = major; + } + + // Default constructor for Gson + public StudentV2() { + + } + + public StudentV2(String firstName, String lastName, String major) { + this.firstName = firstName; + this.lastName = lastName; + this.major = major; + } + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (!(o instanceof StudentV2)) + return false; + StudentV2 studentV2 = (StudentV2) o; + return Objects.equals(firstName, studentV2.firstName) && Objects.equals(lastName, studentV2.lastName) && Objects.equals(major, studentV2.major); + } + + @Override + public int hashCode() { + return Objects.hash(firstName, lastName, major); + } +} diff --git a/json-modules/gson-2/src/test/java/com/baeldung/gson/multiplefields/GsonMultipleFieldsUnitTest.java b/json-modules/gson-2/src/test/java/com/baeldung/gson/multiplefields/GsonMultipleFieldsUnitTest.java new file mode 100644 index 0000000000..1ee2cd1bd8 --- /dev/null +++ b/json-modules/gson-2/src/test/java/com/baeldung/gson/multiplefields/GsonMultipleFieldsUnitTest.java @@ -0,0 +1,65 @@ +package com.baeldung.gson.multiplefields; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import org.junit.Test; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +public class GsonMultipleFieldsUnitTest { + + @Test + public void givenBasicStudent_whenSerializingWithGson_thenTransientFieldNotSet() { + // Given a class with a transient field + BasicStudent student = new BasicStudent("Henry Winter", "Greek Studies", "Classical Greek Studies"); + + // When serializing using Gson + Gson gson = new Gson(); + String json = gson.toJson(student); + + // Then the deserialized instance doesn't contain the transient field value + BasicStudent deserialized = gson.fromJson(json, BasicStudent.class); + assertThat(deserialized.getMajor()).isNull(); + } + + @Test + public void givenStudentV2_whenSerializingWithGson_thenIllegalArgumentExceptionIsThrown() { + // Given a class with a class hierarchy that defines multiple fields with the same name + StudentV2 student = new StudentV2("Henry", "Winter", "Greek Studies"); + + // When serializing using Gson, then an IllegalArgumentException exception is thrown + Gson gson = new Gson(); + assertThatThrownBy(() -> gson.toJson(student)).isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("declares multiple JSON fields named 'firstName'"); + } + + @Test + public void givenStudentV2_whenSerializingWithGsonExposeAnnotation_thenSerializes() { + // Given a class with a class hierarchy that defines multiple fields with the same name + StudentV2 student = new StudentV2("Henry", "Winter", "Greek Studies"); + + // When serializing using Gson exclude fields without @Expose + Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation() + .create(); + + // Then ensure the student can be serialized, then deserialized back into an equal instance + String json = gson.toJson(student); + assertThat(gson.fromJson(json, StudentV2.class)).isEqualTo(student); + } + + @Test + public void givenStudentV2_whenSerializingWithGsonExclusionStrategy_thenSerializes() { + // Given a class with a class hierarchy that defines multiple fields with the same name + StudentV2 student = new StudentV2("Henry", "Winter", "Greek Studies"); + + // When serializing using Gson add an ExclusionStrategy + Gson gson = new GsonBuilder().setExclusionStrategies(new StudentExclusionStrategy()) + .create(); + + // Then ensure the student can be serialized, then deserialized back into an equal instance + assertThat(gson.fromJson(gson.toJson(student), StudentV2.class)).isEqualTo(student); + } + +} \ No newline at end of file From 2e60ba50079fbe296f326a281cda547ffc7bd2de Mon Sep 17 00:00:00 2001 From: Geoffrey De Smet Date: Sat, 25 Nov 2023 21:09:32 +0100 Subject: [PATCH 121/228] Turn into a unit test to avoid main() --- timefold-solver/pom.xml | 4 ++-- .../ShiftScheduleConstraintProviderUnitTest.java | 1 + .../ShiftScheduleSolverUnitTest.java} | 13 ++++++++----- 3 files changed, 11 insertions(+), 7 deletions(-) rename timefold-solver/src/{main/java/com/baeldung/timefoldsolver/ShiftScheduleApp.java => test/java/com/baeldung/timefoldsolver/ShiftScheduleSolverUnitTest.java} (86%) diff --git a/timefold-solver/pom.xml b/timefold-solver/pom.xml index 2a219a593c..a16afb9e54 100644 --- a/timefold-solver/pom.xml +++ b/timefold-solver/pom.xml @@ -1,7 +1,7 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 timefold-solver timefold-solver diff --git a/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleConstraintProviderUnitTest.java b/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleConstraintProviderUnitTest.java index 3a3f4dc032..3f68ef701e 100644 --- a/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleConstraintProviderUnitTest.java +++ b/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleConstraintProviderUnitTest.java @@ -24,6 +24,7 @@ class ShiftScheduleConstraintProviderUnitTest { // To avoid that, use forEachUniquePair() in the constraint instead. .penalizesBy(2); } + @Test void whenTwoShiftsOnDifferentDays_thenDoNotPenalize() { Employee ann = new Employee("Ann", null); diff --git a/timefold-solver/src/main/java/com/baeldung/timefoldsolver/ShiftScheduleApp.java b/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleSolverUnitTest.java similarity index 86% rename from timefold-solver/src/main/java/com/baeldung/timefoldsolver/ShiftScheduleApp.java rename to timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleSolverUnitTest.java index e8dc02e2b3..45a84b40da 100644 --- a/timefold-solver/src/main/java/com/baeldung/timefoldsolver/ShiftScheduleApp.java +++ b/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleSolverUnitTest.java @@ -5,18 +5,21 @@ import java.time.LocalDate; import java.util.List; import java.util.Set; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ai.timefold.solver.core.api.solver.Solver; import ai.timefold.solver.core.api.solver.SolverFactory; import ai.timefold.solver.core.config.solver.SolverConfig; +import ai.timefold.solver.core.config.solver.termination.TerminationConfig; -public class ShiftScheduleApp { +public class ShiftScheduleSolverUnitTest { - private static final Logger logger = LoggerFactory.getLogger(ShiftScheduleApp.class); + private static final Logger logger = LoggerFactory.getLogger(ShiftScheduleSolverUnitTest.class); - public static void main(String[] args) { + @Test + public void solve() { SolverFactory solverFactory = SolverFactory.create(new SolverConfig().withSolutionClass(ShiftSchedule.class) .withEntityClasses(Shift.class) .withConstraintProviderClass(ShiftScheduleConstraintProvider.class) @@ -30,7 +33,7 @@ public class ShiftScheduleApp { printSolution(solution); } - private static ShiftSchedule loadProblem() { + private ShiftSchedule loadProblem() { LocalDate monday = LocalDate.of(2030, 4, 1); LocalDate tuesday = LocalDate.of(2030, 4, 2); return new ShiftSchedule( @@ -40,7 +43,7 @@ public class ShiftScheduleApp { new Shift(tuesday.atTime(14, 0), tuesday.atTime(22, 0), "Bartender"))); } - private static void printSolution(ShiftSchedule solution) { + private void printSolution(ShiftSchedule solution) { logger.info("Shift assignments"); for (Shift shift : solution.getShifts()) { logger.info(" " + shift.getStart() From 289281024037e63530b434b360816710c014c1da Mon Sep 17 00:00:00 2001 From: DiegoMarti2 <150871541+DiegoMarti2@users.noreply.github.com> Date: Sun, 26 Nov 2023 11:55:41 +0200 Subject: [PATCH 122/228] baeldung-articles: baeldung-articlesBAEL-7234 Commit to a new article (How to convert JsonNode to ObjectNode). Adding a test class (JsonNodeToJsonObjectUnitTest). --- .../JsonNodeToJsonObjectUnitTest.java | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 json-modules/json-conversion/src/test/java/com/baeldung/jsonnodetojsonobject/JsonNodeToJsonObjectUnitTest.java diff --git a/json-modules/json-conversion/src/test/java/com/baeldung/jsonnodetojsonobject/JsonNodeToJsonObjectUnitTest.java b/json-modules/json-conversion/src/test/java/com/baeldung/jsonnodetojsonobject/JsonNodeToJsonObjectUnitTest.java new file mode 100644 index 0000000000..e5a12869ea --- /dev/null +++ b/json-modules/json-conversion/src/test/java/com/baeldung/jsonnodetojsonobject/JsonNodeToJsonObjectUnitTest.java @@ -0,0 +1,28 @@ +package com.baeldung.jsonnodetojsonobject; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.JsonNode; + +import org.junit.Test; + +import static org.junit.Assert.*; + +public class JsonNodeToJsonObjectUnitTest { + public static String jsonString = "{\"name\": \"John\", \"gender\": \"male\", \"company\": \"Baeldung\", \"isEmployee\": true, \"age\": 30}"; + + @Test + public void givenJsonNode_whenConvertingToObjectNode_thenVerifyFieldsIntegrity() throws JsonProcessingException { + + ObjectMapper objectMapper = new ObjectMapper(); + JsonNode jsonNode = objectMapper.readTree(jsonString); + ObjectNode objectNode = objectMapper.createObjectNode().setAll((ObjectNode) jsonNode); + + assertEquals("John", objectNode.get("name").asText()); + assertEquals("male", objectNode.get("gender").asText()); + assertEquals("Baeldung", objectNode.get("company").asText()); + assertTrue(objectNode.get("isEmployee").asBoolean()); + assertEquals(30, objectNode.get("age").asInt()); + } +} From 65676eb275409ded4484e487b4cbde472a5e6793 Mon Sep 17 00:00:00 2001 From: gaepi Date: Sun, 26 Nov 2023 12:50:53 +0100 Subject: [PATCH 123/228] Java-27655 | removing WebSecurityConfigurerAdapter from httpclient4 module --- .../filter/CustomWebSecurityConfigurerAdapter.java | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/apache-httpclient4/src/main/java/com/baeldung/filter/CustomWebSecurityConfigurerAdapter.java b/apache-httpclient4/src/main/java/com/baeldung/filter/CustomWebSecurityConfigurerAdapter.java index fb597e46c8..eaf166a091 100644 --- a/apache-httpclient4/src/main/java/com/baeldung/filter/CustomWebSecurityConfigurerAdapter.java +++ b/apache-httpclient4/src/main/java/com/baeldung/filter/CustomWebSecurityConfigurerAdapter.java @@ -7,14 +7,14 @@ import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; @Configuration @EnableWebSecurity -public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { +public class CustomWebSecurityConfigurerAdapter { @Autowired private RestAuthenticationEntryPoint authenticationEntryPoint; @@ -27,8 +27,8 @@ public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAda .authorities("ROLE_USER"); } - @Override - protected void configure(HttpSecurity http) throws Exception { + @Bean + public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/securityNone") @@ -40,6 +40,8 @@ public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAda .authenticationEntryPoint(authenticationEntryPoint); http.addFilterAfter(new CustomFilter(), BasicAuthenticationFilter.class); + + return http.build(); } @Bean From 033fff1e5ef9e00cec85028a9861c5baf4c51dbc Mon Sep 17 00:00:00 2001 From: gaepi Date: Sun, 26 Nov 2023 13:12:19 +0100 Subject: [PATCH 124/228] Java-27655 | moved jenkins module to more recent implementation of web security --- .../WebSecurityConfiguration.java | 56 ++++++++----------- 1 file changed, 24 insertions(+), 32 deletions(-) diff --git a/jmeter/src/main/java/com/baeldung/configuration/WebSecurityConfiguration.java b/jmeter/src/main/java/com/baeldung/configuration/WebSecurityConfiguration.java index 8700dc3df4..033281e07f 100644 --- a/jmeter/src/main/java/com/baeldung/configuration/WebSecurityConfiguration.java +++ b/jmeter/src/main/java/com/baeldung/configuration/WebSecurityConfiguration.java @@ -1,52 +1,44 @@ package com.baeldung.configuration; +import java.util.HashSet; +import java.util.Set; + +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.crypto.factory.PasswordEncoderFactories; import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.provisioning.InMemoryUserDetailsManager; +import org.springframework.security.web.SecurityFilterChain; @Configuration -public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter { +public class WebSecurityConfiguration { - @Override - protected void configure(AuthenticationManagerBuilder auth) throws Exception { - + @Bean + public InMemoryUserDetailsManager userDetailsService() { PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder(); - - auth.inMemoryAuthentication() - .withUser("admin").password(encoder.encode("admin")).roles("USER", "ADMIN") - .and() - .withUser("user1").password(encoder.encode("password1")).roles("USER") - .and() - .withUser("user2").password(encoder.encode("password2")).roles("USER") - .and() - .withUser("user3").password(encoder.encode("password3")).roles("USER") - .and() - .withUser("user4").password(encoder.encode("password4")).roles("USER") - .and() - .withUser("user5").password(encoder.encode("password5")).roles("USER") - .and() - .withUser("user6").password(encoder.encode("password6")).roles("USER") - .and() - .withUser("user7").password(encoder.encode("password7")).roles("USER") - .and() - .withUser("user8").password(encoder.encode("password8")).roles("USER") - .and() - .withUser("user9").password(encoder.encode("password9")).roles("USER") - .and() - .withUser("user10").password(encoder.encode("password10")).roles("USER"); + + Set users = new HashSet<>(); + users.add(User.withUsername("admin").password(encoder.encode("admin")).roles("USER", "ADMIN").build()); + for(int i=1;i<=10;i++){ + users.add(User.withUsername("user"+i).password(encoder.encode("password")+i).roles("USER").build()); + } + + return new InMemoryUserDetailsManager(users); } - @Override - protected void configure(HttpSecurity http) throws Exception { - + @Bean + public SecurityFilterChain securityFilter(HttpSecurity http) throws Exception { + http .authorizeRequests() .antMatchers("/secured/**").authenticated() .anyRequest().permitAll() .and() .httpBasic(); + + return http.build(); } } From 0973a63e5c2e312c2bf9839c6da8d1f91a13ade3 Mon Sep 17 00:00:00 2001 From: gaepi Date: Sun, 26 Nov 2023 13:33:08 +0100 Subject: [PATCH 125/228] Java-27655 | removed deprecated WebSecurityConfigAdapter from security-modules/jjwt module --- .../jjwtfun/config/WebSecurityConfig.java | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/security-modules/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/config/WebSecurityConfig.java b/security-modules/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/config/WebSecurityConfig.java index 687a827448..e453f33d5e 100644 --- a/security-modules/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/config/WebSecurityConfig.java +++ b/security-modules/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/config/WebSecurityConfig.java @@ -4,9 +4,11 @@ import io.jsonwebtoken.JwtException; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.jjwtfun.service.SecretService; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.csrf.CsrfFilter; import org.springframework.security.web.csrf.CsrfToken; import org.springframework.security.web.csrf.CsrfTokenRepository; @@ -21,19 +23,19 @@ import java.io.IOException; import java.util.Arrays; @Configuration -public class WebSecurityConfig extends WebSecurityConfigurerAdapter { +public class WebSecurityConfig { @Autowired - CsrfTokenRepository jwtCsrfTokenRepository; + private CsrfTokenRepository jwtCsrfTokenRepository; @Autowired - SecretService secretService; + private SecretService secretService; // ordered so we can use binary search below - private String[] ignoreCsrfAntMatchers = { "/dynamic-builder-compress", "/dynamic-builder-general", "/dynamic-builder-specific", "/set-secrets" }; + private final String[] ignoreCsrfAntMatchers = { "/dynamic-builder-compress", "/dynamic-builder-general", "/dynamic-builder-specific", "/set-secrets" }; - @Override - protected void configure(HttpSecurity http) throws Exception { + @Bean + public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.addFilterAfter(new JwtCsrfValidatorFilter(), CsrfFilter.class) .csrf() .csrfTokenRepository(jwtCsrfTokenRepository) @@ -42,6 +44,8 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter { .authorizeRequests() .antMatchers("/**") .permitAll(); + + return http.build(); } private class JwtCsrfValidatorFilter extends OncePerRequestFilter { From 0b2981b94e48a35ea0ad46c0a4091b0ae4f3eba8 Mon Sep 17 00:00:00 2001 From: Kai Yuan Date: Sun, 26 Nov 2023 19:10:19 +0100 Subject: [PATCH 126/228] [negate-int] using logger instead of sys.print.out --- .../com/baeldung/negate/NegateIntUnitTest.java | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/negate/NegateIntUnitTest.java b/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/negate/NegateIntUnitTest.java index 15fffde6ed..3cb93d243d 100644 --- a/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/negate/NegateIntUnitTest.java +++ b/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/negate/NegateIntUnitTest.java @@ -1,10 +1,14 @@ package com.baeldung.negate; import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import static org.junit.jupiter.api.Assertions.*; public class NegateIntUnitTest { + private static Logger LOG = LoggerFactory.getLogger(NegateIntUnitTest.class); + @Test void whenUsingUnaryMinusOperator_thenGetExpectedResult() { int x = 42; @@ -30,18 +34,20 @@ public class NegateIntUnitTest { } @Test - void whenUsingUnaryMinusOperatorWithMinInt_thenCannotGetExpectedResult() { + void givenIntMinValue_whenUsingUnaryMinusOperator_thenCannotGetExpectedResult() { int min = Integer.MIN_VALUE; - System.out.println("The value of '-min' is: " + -min); - assertFalse((-min) > 0); + LOG.info("The value of '-min' is: " + -min); + + assertTrue((-min) < 0); } @Test - void whenUsingBitwiseComplementOperatorWithMinInt_thenCannotGetExpectedResult() { + void givenIntMinValue_whenUsingBitwiseComplementOperator_thenCannotGetExpectedResult() { int min = Integer.MIN_VALUE; int result = ~min + 1; - System.out.println("The value of '~min + 1' is: " + result); - assertFalse(result > 0); + LOG.info("The value of '~min + 1' is: " + result); + + assertTrue(result < 0); } From 62cc5adfbbce8379f7dd5ec8f39162262b133f94 Mon Sep 17 00:00:00 2001 From: Kai Yuan Date: Sun, 26 Nov 2023 20:59:53 +0100 Subject: [PATCH 127/228] [negate-int] add an empty line --- .../src/test/java/com/baeldung/negate/NegateIntUnitTest.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/negate/NegateIntUnitTest.java b/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/negate/NegateIntUnitTest.java index 3cb93d243d..444f4931d3 100644 --- a/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/negate/NegateIntUnitTest.java +++ b/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/negate/NegateIntUnitTest.java @@ -7,7 +7,8 @@ import org.slf4j.LoggerFactory; import static org.junit.jupiter.api.Assertions.*; public class NegateIntUnitTest { - private static Logger LOG = LoggerFactory.getLogger(NegateIntUnitTest.class); + + private static final Logger LOG = LoggerFactory.getLogger(NegateIntUnitTest.class); @Test void whenUsingUnaryMinusOperator_thenGetExpectedResult() { From d69a3ac6bdad86358b3e5c7b55c8779a7bc6143d Mon Sep 17 00:00:00 2001 From: Bhaskar Ghosh Dastidar Date: Mon, 27 Nov 2023 09:13:04 +0530 Subject: [PATCH 128/228] [BAEL-6787] Increment map value benchmark - JMH (#15268) * [BAEL-6787] jmh class added * [BAEL-6787] jmh pom --------- Co-authored-by: Bhaskar --- .../core-java-collections-maps-7/pom.xml | 10 +++ .../BenchmarkMapMethods.java | 2 +- .../BenchmarkMapMethodsJMH.java | 68 +++++++++++++++++++ .../IncrementMapValueWays.java | 2 +- .../IncrementMapValueUnitTest.java | 4 +- 5 files changed, 83 insertions(+), 3 deletions(-) rename core-java-modules/core-java-collections-maps-7/src/main/java/com/baeldung/map/{ => incrementmapkey}/BenchmarkMapMethods.java (99%) create mode 100644 core-java-modules/core-java-collections-maps-7/src/main/java/com/baeldung/map/incrementmapkey/BenchmarkMapMethodsJMH.java rename core-java-modules/core-java-collections-maps-7/src/main/java/com/baeldung/map/{ => incrementmapkey}/IncrementMapValueWays.java (98%) rename core-java-modules/core-java-collections-maps-7/src/test/java/com/baeldung/map/{ => incrementmapkey}/IncrementMapValueUnitTest.java (97%) diff --git a/core-java-modules/core-java-collections-maps-7/pom.xml b/core-java-modules/core-java-collections-maps-7/pom.xml index a05b1b3528..2d08c0a438 100644 --- a/core-java-modules/core-java-collections-maps-7/pom.xml +++ b/core-java-modules/core-java-collections-maps-7/pom.xml @@ -38,6 +38,16 @@ guava 32.1.2-jre + + org.openjdk.jmh + jmh-core + 1.37 + + + org.openjdk.jmh + jmh-generator-annprocess + 1.37 + diff --git a/core-java-modules/core-java-collections-maps-7/src/main/java/com/baeldung/map/BenchmarkMapMethods.java b/core-java-modules/core-java-collections-maps-7/src/main/java/com/baeldung/map/incrementmapkey/BenchmarkMapMethods.java similarity index 99% rename from core-java-modules/core-java-collections-maps-7/src/main/java/com/baeldung/map/BenchmarkMapMethods.java rename to core-java-modules/core-java-collections-maps-7/src/main/java/com/baeldung/map/incrementmapkey/BenchmarkMapMethods.java index eca028efe4..563b2ffdae 100644 --- a/core-java-modules/core-java-collections-maps-7/src/main/java/com/baeldung/map/BenchmarkMapMethods.java +++ b/core-java-modules/core-java-collections-maps-7/src/main/java/com/baeldung/map/incrementmapkey/BenchmarkMapMethods.java @@ -1,4 +1,4 @@ -package com.baeldung.map; +package com.baeldung.map.incrementmapkey; import java.util.HashMap; import java.util.Map; diff --git a/core-java-modules/core-java-collections-maps-7/src/main/java/com/baeldung/map/incrementmapkey/BenchmarkMapMethodsJMH.java b/core-java-modules/core-java-collections-maps-7/src/main/java/com/baeldung/map/incrementmapkey/BenchmarkMapMethodsJMH.java new file mode 100644 index 0000000000..4ddf3886e9 --- /dev/null +++ b/core-java-modules/core-java-collections-maps-7/src/main/java/com/baeldung/map/incrementmapkey/BenchmarkMapMethodsJMH.java @@ -0,0 +1,68 @@ +package com.baeldung.map.incrementmapkey; + +import java.util.concurrent.TimeUnit; + +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.State; + +@State(Scope.Benchmark) +public class BenchmarkMapMethodsJMH { + @Benchmark + @BenchmarkMode(Mode.AverageTime) + @OutputTimeUnit(TimeUnit.NANOSECONDS) + @Fork(value = 1, warmups = 1) + public void benchMarkGuavaMap() { + IncrementMapValueWays im = new IncrementMapValueWays(); + im.charFrequencyUsingAtomicMap(getString()); + } + + @Benchmark + @BenchmarkMode(Mode.AverageTime) + @OutputTimeUnit(TimeUnit.NANOSECONDS) + @Fork(value = 1, warmups = 1) + public void benchContainsKeyMap() { + IncrementMapValueWays im = new IncrementMapValueWays(); + im.charFrequencyUsingContainsKey(getString()); + } + + @Benchmark + @BenchmarkMode(Mode.AverageTime) + @OutputTimeUnit(TimeUnit.NANOSECONDS) + @Fork(value = 1, warmups = 1) + public void benchMarkComputeMethod() { + IncrementMapValueWays im = new IncrementMapValueWays(); + im.charFrequencyUsingCompute(getString()); + } + + @Benchmark + @BenchmarkMode(Mode.AverageTime) + @OutputTimeUnit(TimeUnit.NANOSECONDS) + @Fork(value = 1, warmups = 1) + public void benchMarkMergeMethod() { + IncrementMapValueWays im = new IncrementMapValueWays(); + im.charFrequencyUsingMerge(getString()); + } + + public static void main(String[] args) throws Exception { + org.openjdk.jmh.Main.main(args); + } + + private String getString() { + return + "Once upon a time in a quaint village nestled between rolling hills and whispering forests, there lived a solitary storyteller named Elias. Elias was known for spinning tales that transported listeners to magical realms and awakened forgotten dreams.\n" + + "\n" + + "His favorite spot was beneath an ancient oak tree, its sprawling branches offering shade to those who sought refuge from the bustle of daily life. Villagers of all ages would gather around Elias, their faces illuminated by the warmth of his stories.\n" + + "\n" + "One evening, as dusk painted the sky in hues of orange and purple, a curious young girl named Lily approached Elias. Her eyes sparkled with wonder as she asked for a tale unlike any other.\n" + "\n" + + "Elias smiled, sensing her thirst for adventure, and began a story about a forgotten kingdom veiled by mist, guarded by mystical creatures and enchanted by ancient spells. With each word, the air grew thick with anticipation, and the listeners were transported into a world where magic danced on the edges of reality.\n" + + "\n" + "As Elias weaved the story, Lily's imagination took flight. She envisioned herself as a brave warrior, wielding a shimmering sword against dark forces, her heart fueled by courage and kindness.\n" + "\n" + + "The night wore on, but the spell of the tale held everyone captive. The villagers laughed, gasped, and held their breaths, journeying alongside the characters through trials and triumphs.\n" + "\n" + + "As the final words lingered in the air, a sense of enchantment settled upon the listeners. They thanked Elias for the gift of his storytelling, each carrying a piece of the magical kingdom within their hearts.\n" + "\n" + + "Lily, inspired by the story, vowed to cherish the spirit of adventure and kindness in her own life. With a newfound spark in her eyes, she bid Elias goodnight, already dreaming of the countless adventures awaiting her.\n" + "\n" + + "Under the star-studded sky, Elias remained beneath the ancient oak, his heart aglow with the joy of sharing tales that ignited imagination and inspired dreams. And as the night embraced the village, whispers of the enchanted kingdom lingered in the breeze, promising endless possibilities to those who dared to believe."; + } +} diff --git a/core-java-modules/core-java-collections-maps-7/src/main/java/com/baeldung/map/IncrementMapValueWays.java b/core-java-modules/core-java-collections-maps-7/src/main/java/com/baeldung/map/incrementmapkey/IncrementMapValueWays.java similarity index 98% rename from core-java-modules/core-java-collections-maps-7/src/main/java/com/baeldung/map/IncrementMapValueWays.java rename to core-java-modules/core-java-collections-maps-7/src/main/java/com/baeldung/map/incrementmapkey/IncrementMapValueWays.java index 70b3c6c54d..e15b3aae8e 100644 --- a/core-java-modules/core-java-collections-maps-7/src/main/java/com/baeldung/map/IncrementMapValueWays.java +++ b/core-java-modules/core-java-collections-maps-7/src/main/java/com/baeldung/map/incrementmapkey/IncrementMapValueWays.java @@ -1,4 +1,4 @@ -package com.baeldung.map; +package com.baeldung.map.incrementmapkey; import java.util.HashMap; import java.util.Map; diff --git a/core-java-modules/core-java-collections-maps-7/src/test/java/com/baeldung/map/IncrementMapValueUnitTest.java b/core-java-modules/core-java-collections-maps-7/src/test/java/com/baeldung/map/incrementmapkey/IncrementMapValueUnitTest.java similarity index 97% rename from core-java-modules/core-java-collections-maps-7/src/test/java/com/baeldung/map/IncrementMapValueUnitTest.java rename to core-java-modules/core-java-collections-maps-7/src/test/java/com/baeldung/map/incrementmapkey/IncrementMapValueUnitTest.java index df4f2b787e..64b9e1155d 100644 --- a/core-java-modules/core-java-collections-maps-7/src/test/java/com/baeldung/map/IncrementMapValueUnitTest.java +++ b/core-java-modules/core-java-collections-maps-7/src/test/java/com/baeldung/map/incrementmapkey/IncrementMapValueUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.map; +package com.baeldung.map.incrementmapkey; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @@ -9,6 +9,8 @@ import java.util.stream.Stream; import org.junit.Assert; import org.junit.Test; +import com.baeldung.map.incrementmapkey.IncrementMapValueWays; + public class IncrementMapValueUnitTest { @Test From 5d6b5bf965f49e640726e8df7f707002df8c20fc Mon Sep 17 00:00:00 2001 From: MohamedHelmyKassab <137485958+MohamedHelmyKassab@users.noreply.github.com> Date: Mon, 27 Nov 2023 05:52:14 +0200 Subject: [PATCH 129/228] This commit is related to BAEL-7254 (#15299) This commit aims to add a new test class "ByteToCharArrayUnitTest" that validates the conversion process of a Byte array into a Char array. --- .../conversions/ByteToCharArrayUnitTest.java | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 core-java-modules/core-java-arrays-convert/src/test/java/com/baeldung/array/conversions/ByteToCharArrayUnitTest.java diff --git a/core-java-modules/core-java-arrays-convert/src/test/java/com/baeldung/array/conversions/ByteToCharArrayUnitTest.java b/core-java-modules/core-java-arrays-convert/src/test/java/com/baeldung/array/conversions/ByteToCharArrayUnitTest.java new file mode 100644 index 0000000000..c62520cedc --- /dev/null +++ b/core-java-modules/core-java-arrays-convert/src/test/java/com/baeldung/array/conversions/ByteToCharArrayUnitTest.java @@ -0,0 +1,47 @@ +package com.baeldung.array.conversions; + +import org.junit.Test; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.StandardCharsets; + +import static org.junit.Assert.assertArrayEquals; + +public class ByteToCharArrayUnitTest { + public static byte[] byteArray = {65, 66, 67, 68}; + public static char[] expected = {'A', 'B', 'C', 'D'}; + + @Test + public void givenByteArray_WhenUsingStandardCharsets_thenConvertToCharArray() { + char[] charArray = new String(byteArray, StandardCharsets.UTF_8).toCharArray(); + assertArrayEquals(expected, charArray); + } + + @Test + public void givenByteArray_WhenUsingSUsingStreams_thenConvertToCharArray() throws IOException { + ByteArrayInputStream inputStream = new ByteArrayInputStream(byteArray); + InputStreamReader reader = new InputStreamReader(inputStream); + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + int data; + while ((data = reader.read()) != -1) { + char ch = (char) data; + outputStream.write(ch); + } + char[] charArray = outputStream.toString().toCharArray(); + assertArrayEquals(expected, charArray); + } + + @Test + public void givenByteArray_WhenUsingCharBuffer_thenConvertToCharArray() { + ByteBuffer byteBuffer = ByteBuffer.wrap(byteArray); + CharBuffer charBuffer = StandardCharsets.UTF_8.decode(byteBuffer); + char[] charArray = new char[charBuffer.remaining()]; + charBuffer.get(charArray); + assertArrayEquals(expected, charArray); + } +} From 7284c7462c591bd872241cfc5f4a0543398b5bf7 Mon Sep 17 00:00:00 2001 From: parthiv39731 <70740707+parthiv39731@users.noreply.github.com> Date: Mon, 27 Nov 2023 10:19:12 +0530 Subject: [PATCH 130/228] BAEL-7259 --- persistence-modules/java-harperdb/pom.xml | 61 +++ .../src/main/resources/data-model.puml | 41 ++ .../baledung/harperdb/HarperDBApiService.java | 74 ++++ .../baledung/harperdb/HarperDBContainer.java | 42 +++ .../baledung/harperdb/HarperDBLiveTest.java | 336 +++++++++++++++++ .../harperdb/HarperDBLiveTestOld.java | 356 ++++++++++++++++++ 6 files changed, 910 insertions(+) create mode 100644 persistence-modules/java-harperdb/pom.xml create mode 100644 persistence-modules/java-harperdb/src/main/resources/data-model.puml create mode 100644 persistence-modules/java-harperdb/src/test/java/com/baledung/harperdb/HarperDBApiService.java create mode 100644 persistence-modules/java-harperdb/src/test/java/com/baledung/harperdb/HarperDBContainer.java create mode 100644 persistence-modules/java-harperdb/src/test/java/com/baledung/harperdb/HarperDBLiveTest.java create mode 100644 persistence-modules/java-harperdb/src/test/java/com/baledung/harperdb/HarperDBLiveTestOld.java diff --git a/persistence-modules/java-harperdb/pom.xml b/persistence-modules/java-harperdb/pom.xml new file mode 100644 index 0000000000..896a58f858 --- /dev/null +++ b/persistence-modules/java-harperdb/pom.xml @@ -0,0 +1,61 @@ + + + 4.0.0 + + com.baeldung + java-harperdb + 1.0-SNAPSHOT + + + + org.apache.maven.plugins + maven-compiler-plugin + + 9 + 9 + + + + + + + com.baeldung + persistence-modules + 1.0.0-SNAPSHOT + + + + com.baeldung + java-harperdb + 4.2 + system + ${project.basedir}/lib/cdata.jdbc.harperdb.jar + + + org.testcontainers + testcontainers + test + + + + + + + org.testcontainers + testcontainers-bom + 1.19.3 + pom + import + + + + + + 19 + 19 + UTF-8 + + + \ No newline at end of file diff --git a/persistence-modules/java-harperdb/src/main/resources/data-model.puml b/persistence-modules/java-harperdb/src/main/resources/data-model.puml new file mode 100644 index 0000000000..8e3681c749 --- /dev/null +++ b/persistence-modules/java-harperdb/src/main/resources/data-model.puml @@ -0,0 +1,41 @@ +@startuml +'https://gist.github.com/QuantumGhost/0955a45383a0b6c0bc24f9654b3cb561 +' uncomment the line below if you're using computer with a retina display +' skinparam dpi 300 +!theme sketchy-outline +!define Table(name,desc) class name as "desc" << (T, #63b175) >> +' we use bold for primary key +' green color for unique +' and underscore for not_null +!define primary_key(x) x +!define unique(x) x +!define not_null(x) x +' other tags available: +' +' , where color is a color name or html color code +' (#FFAACC) +' see: http://plantuml.com/classes.html#More +hide methods +hide stereotypes + +' entities + + +Table(Teacher, "Teacher") { + primary_key(Id) Number + Name Varchar + joining_date Date +} +Table(Subject, "Subject") { + primary_key(Id) Number + Name Varchar +} +Table(Teacher_Details, "Teacher_Details") { + primary_key(Id) Number + teacher_id Number + subject_id Number +} + +Teacher_Details "*" -left-> "1" Subject: " " +Teacher "1" -left-> "*" Teacher_Details: " " +@enduml \ No newline at end of file diff --git a/persistence-modules/java-harperdb/src/test/java/com/baledung/harperdb/HarperDBApiService.java b/persistence-modules/java-harperdb/src/test/java/com/baledung/harperdb/HarperDBApiService.java new file mode 100644 index 0000000000..1eedd8648f --- /dev/null +++ b/persistence-modules/java-harperdb/src/test/java/com/baledung/harperdb/HarperDBApiService.java @@ -0,0 +1,74 @@ +package com.baledung.harperdb; + +import com.github.dockerjava.zerodep.shaded.org.apache.hc.client5.http.classic.methods.HttpPost; +import com.github.dockerjava.zerodep.shaded.org.apache.hc.client5.http.impl.classic.CloseableHttpClient; +import com.github.dockerjava.zerodep.shaded.org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; +import com.github.dockerjava.zerodep.shaded.org.apache.hc.client5.http.impl.classic.HttpClientBuilder; +import com.github.dockerjava.zerodep.shaded.org.apache.hc.core5.http.ClassicHttpRequest; +import com.github.dockerjava.zerodep.shaded.org.apache.hc.core5.http.HttpEntity; +import com.github.dockerjava.zerodep.shaded.org.apache.hc.core5.http.io.entity.StringEntity; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.util.Base64; + +public class HarperDBApiService { + private String url; + private String base64auth; + + public HarperDBApiService(String url, String user, String password) { + this.url = url; + this.base64auth = Base64.getEncoder() + .encodeToString(new StringBuilder().append(user).append(":").append(password).toString().getBytes()); + } + + private static final Logger LOGGER = LoggerFactory.getLogger(HarperDBApiService.class); + + public void createSchema(String schema) throws IOException { + String requestBody = "{\"operation\":\"create_schema\", \"" + "schema\":\"" + schema + "\"" + "}"; + executeHttpPostRequest(requestBody); + } + + public void createTable(String schema, String table, String ... attributes) throws IOException { + String createTableReq = "{\"operation\":\"create_table\"," + + "\"schema\":\"" + schema + + "\",\"table\":\"" + table + + "\",\"hash_attribute\":\"id\"" + + "}"; + executeHttpPostRequest(createTableReq); + LOGGER.info("created table:" + table); + for (String attribute : attributes) { + String createAttrReq = "{\"operation\":\"create_attribute\",\"schema\":\"" + + schema + "\",\"table\":\"" + + table + "\",\"attribute\":\"" + + attribute + "\"" + + "}"; + executeHttpPostRequest(createAttrReq); + LOGGER.info("created attribute:" + attribute + " in table:" + table); + } + } + + public void insertRecords(String schema, String table, String records) throws IOException { + String requestBody = "{\"table\":" + "\"" + table + "\"," + + "\"schema\":" + "\"" + schema + "\"" + "," + + "\"operation\":" + "\"" + "insert" + "\"" + "," + + "\"records\":" + records + + "}"; + executeHttpPostRequest(requestBody); + } + + private void executeHttpPostRequest(String httpRequest) throws IOException { + LOGGER.info("Post request body:" + httpRequest); + + try (CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().build()) { + HttpPost request = new HttpPost(this.url); + request.addHeader("Authorization", "Basic " + this.base64auth); + request.addHeader("Content-Type", "application/json"); + request.setEntity((HttpEntity) new StringEntity(httpRequest)); + CloseableHttpResponse response = closeableHttpClient.execute((ClassicHttpRequest) request); + LOGGER.info("REST API response:" + response.toString()); + assert(200 == response.getCode()); + } + } +} diff --git a/persistence-modules/java-harperdb/src/test/java/com/baledung/harperdb/HarperDBContainer.java b/persistence-modules/java-harperdb/src/test/java/com/baledung/harperdb/HarperDBContainer.java new file mode 100644 index 0000000000..79656b1b73 --- /dev/null +++ b/persistence-modules/java-harperdb/src/test/java/com/baledung/harperdb/HarperDBContainer.java @@ -0,0 +1,42 @@ +package com.baledung.harperdb; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testcontainers.containers.GenericContainer; + +import java.util.Map; + +public class HarperDBContainer { + private final static Logger LOGGER = LoggerFactory.getLogger(HarperDBContainer.class); + + + + private static final Map DEFAULT_ENV_MAP = Map.of( + "HDB_ADMIN_USERNAME", "admin", + "HDB_ADMIN_PASSWORD", "password", + "OPERATIONSAPI_NETWORK_PORT", "9925", + "ROOTPATH", "/home/harperdb/hdb", + "LOGGING_STDSTREAMS", "true" + ); + + private static final Integer[] DEFAULT_EXPOSED_PORTS = {9925, 9926}; + + private static final String HARPER_DOCKER_IMAGE = "harperdb/harperdb:latest"; + + public void stop() { + harperDBContainer.stop(); + } + GenericContainer harperDBContainer; + public GenericContainer installHarperDB() { + harperDBContainer = new GenericContainer(HARPER_DOCKER_IMAGE) + .withEnv(DEFAULT_ENV_MAP) + .withExposedPorts(DEFAULT_EXPOSED_PORTS); + return harperDBContainer; + } + + public GenericContainer installHarperDB(String dockerImgage, final Map envMap, final Integer ... exposedPorts) { + return new GenericContainer(dockerImgage) + .withEnv(envMap) + .withExposedPorts(exposedPorts); + } +} diff --git a/persistence-modules/java-harperdb/src/test/java/com/baledung/harperdb/HarperDBLiveTest.java b/persistence-modules/java-harperdb/src/test/java/com/baledung/harperdb/HarperDBLiveTest.java new file mode 100644 index 0000000000..767d9d971b --- /dev/null +++ b/persistence-modules/java-harperdb/src/test/java/com/baledung/harperdb/HarperDBLiveTest.java @@ -0,0 +1,336 @@ +package com.baledung.harperdb; + +import cdata.jdbc.harperdb.HarperDBConnectionPoolDataSource; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testcontainers.containers.GenericContainer; + +import java.io.IOException; +import java.net.URISyntaxException; +import java.sql.*; +import java.util.Properties; + +import static org.junit.jupiter.api.Assertions.*; + +public class HarperDBLiveTest { + private static final Logger logger = LoggerFactory.getLogger(HarperDBLiveTest.class); + + private static String host; + + private static Integer port; + + private static HarperDBContainer harperDBContainer; + private static HarperDBApiService harperDbApiService; + + @BeforeAll + static void setupHarperDB() throws IOException, InterruptedException, URISyntaxException { + installHarperDB(); + initHarperDBApiService(); + setupDB(); + } + + private static void installHarperDB() { + harperDBContainer = new HarperDBContainer(); + + GenericContainer genericContainer = harperDBContainer.installHarperDB(); + + host = genericContainer.getHost(); + genericContainer.start(); + + port = genericContainer.getFirstMappedPort(); + } + + private static void initHarperDBApiService() { + String url = "http://localhost:" + port + "/"; + harperDbApiService = new HarperDBApiService(url, "admin", "password"); + } + + private static void setupDB() throws URISyntaxException, IOException { + harperDbApiService.createSchema("Demo"); + + harperDbApiService.createTable("Demo", "Subject", "name"); + harperDbApiService.createTable("Demo", "Teacher", "name", "joining_date", "subject_id"); + harperDbApiService.createTable("Demo", "Teacher_Details", "teacher_id", "subject_id"); + + insertSubjectRecords(); + insertTeacherRecords(); + insertTeacherDetailsRecords(); + } + + private static void insertSubjectRecords() throws IOException { + String records = "[" + + "{\"id\":1, \"name\":\"English\"}," + + "{\"id\":2, \"name\":\"Maths\"}," + + "{\"id\":3, \"name\":\"Science\"}" + + "]"; + + harperDbApiService.insertRecords("Demo", "Subject", records); + } + + private static void insertTeacherRecords() throws IOException { + String records = "[" + + "{\"id\":1, \"name\":\"Parthiv Pradhan\", \"joining_date\":\"04-05-2000\"}," + + "{\"id\":2, \"name\":\"David Martinez\", \"joining_date\":\"20-10-2005\"}," + + "{\"id\":3, \"name\":\"Liam Williams\", \"joining_date\":\"04-06-1997\"}," + + "{\"id\":4, \"name\":\"Robin Williams\", \"joining_date\":\"01-01-2020\"}," + + "{\"id\":5, \"name\":\"Eric Martin\", \"joining_date\":\"04-05-2022\"}," + + "{\"id\":6, \"name\":\"Sajjan Nagendra\", \"joining_date\":\"02-02-1999\"}" + + "]"; + harperDbApiService.insertRecords("Demo", "Teacher", records); + } + + private static void insertTeacherDetailsRecords() throws IOException { + String records = "[" + + "{\"id\":1, \"teacher_id\":1, \"subject_id\":1}," + + "{\"id\":2, \"teacher_id\":1, \"subject_id\":2}," + + "{\"id\":3, \"teacher_id\":2, \"subject_id\":3 }," + + "{\"id\":4, \"teacher_id\":3, \"subject_id\":1}," + + "{\"id\":5, \"teacher_id\":3, \"subject_id\":3}," + + "{\"id\":6, \"teacher_id\":4, \"subject_id\":2}," + + "{\"id\":7, \"teacher_id\":5, \"subject_id\":3}," + + "{\"id\":8, \"teacher_id\":6, \"subject_id\":1}," + + "{\"id\":9, \"teacher_id\":6, \"subject_id\":2}," + + "{\"id\":15, \"teacher_id\":6, \"subject_id\":3}" + + "]"; + + harperDbApiService.insertRecords("Demo", "Teacher_Details", records); + } + + @AfterAll + static void stopHarperDB() { + harperDBContainer.stop(); + } + + @Test + void whenConnectionInfoInURL_thenConnectSuccess() throws SQLException { + assertDoesNotThrow(() -> { + final String JDBC_URL = "jdbc:harperdb:Server=127.0.0.1:" + port + ";User=admin;Password=password;"; + + try (Connection connection = DriverManager.getConnection(JDBC_URL)) { + connection.createStatement().executeQuery("select 1"); + logger.info("Connection Successful"); + } + }); + } + + @Test + void whenConnectionInfoInProperties_thenConnectSuccess() throws SQLException { + assertDoesNotThrow(() -> { + Properties prop = new Properties(); + prop.setProperty("Server", "127.0.0.1:" + port); + prop.setProperty("User", "admin"); + prop.setProperty("Password", "password"); + + try (Connection connection = DriverManager.getConnection("jdbc:harperdb:", prop)) { + connection.createStatement().executeQuery("select 1"); + logger.info("Connection Successful"); + } + }); + } + + @Test + void whenConnectionPooling_thenConnectSuccess() throws SQLException { + assertDoesNotThrow(() -> { + HarperDBConnectionPoolDataSource harperdbPoolDataSource = new HarperDBConnectionPoolDataSource(); + final String JDBC_URL = "jdbc:harperdb:UseConnectionPooling=true;PoolMaxSize=2;Server=127.0.0.1:" + port + + ";User=admin;Password=password;"; + harperdbPoolDataSource.setURL(JDBC_URL); + + try(Connection connection = harperdbPoolDataSource.getPooledConnection().getConnection()) { + connection.createStatement().executeQuery("select 1"); + logger.info("Connection Pool Successful"); + } + }); + } + + private static Connection getConnection() throws SQLException { + String URL = "jdbc:harperdb:Server=127.0.0.1:" + port + ";User=admin;Password=password;"; + return DriverManager.getConnection(URL); + } + + @Test + void givenStatement_whenFetchRecord_thenSuccess() throws SQLException { + final String SQL_QUERY = "select id, name, grade from Demo.student"; + + try(Connection connection = getConnection()) { + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(SQL_QUERY); + while (resultSet.next()) { + int id = resultSet.getInt("id"); + String name = resultSet.getString("name"); + int grade = resultSet.getInt("grade"); + assertNotNull(Integer.valueOf(id)); + logger.info("Student id:" + id + " Student Name:" + name + " grade:" + grade); + } + } + } + + @Test + void givenStatement_whenInsertRecord_thenSuccess() throws SQLException { + final String INSERT_SQL = "insert into Demo.student(id, name, grade) values (10, 'Barak', 3)"; + + try(Connection connection = getConnection()) { + Statement statement = connection.createStatement(); + assertDoesNotThrow(() -> statement.execute(INSERT_SQL)); + } + } + + @Test + void givenStatement_whenInsertRecordInTableWithoutAttributes_thenSuccess() throws SQLException { + final String INSERT_SQL = "insert into Demo.teacher(id, name, joining_date) " + + "values (7, 'David Sirocco', '04-05-2004'), (8, 'Ali Azmat', '04-10-2000')"; + final String QUERY_SQL = "select name, joining_date from Demo.teacher where name = ?"; + + try(Connection connection = getConnection()) { + Statement statement = connection.createStatement(); + assertDoesNotThrow(() -> statement.execute(INSERT_SQL)); + PreparedStatement preparedStatement = connection.prepareStatement(QUERY_SQL); + preparedStatement.setString(1, "David Sirocco"); + ResultSet resultSet = preparedStatement.executeQuery(); + while (resultSet.next()) { + String teacherName = resultSet.getString("name"); + String joinDate = resultSet.getString("joining_date"); + assertEquals("David Sirocco", teacherName); + assertEquals("04-05-2004", joinDate); + logger.info("name:" + teacherName + " joining date:" + joinDate); + } + } + } + + @Test + void givenStatement_whenUpdateRecord_thenSuccess() throws SQLException { + final String UPDATE_SQL = "update Demo.student set grade = 4 where id = 5"; + + try(Connection connection = getConnection()) { + Statement statement = connection.createStatement(); + assertDoesNotThrow(() -> statement.execute(UPDATE_SQL)); + assertEquals(1, statement.getUpdateCount()); + } + } + + @Test + void givenStatement_whenDeleteRecord_thenSuccess() throws SQLException { + final String DELETE_SQL = "delete from Demo.student where id = 3"; + + try(Connection connection = getConnection()) { + Statement statement = connection.createStatement(); + assertDoesNotThrow(() -> statement.execute(DELETE_SQL)); + assertEquals(1, statement.getUpdateCount()); + } + } + + @Test + void givenPreparedStatement_whenFetchRecord_thenSuccess() throws SQLException { + final String SQL_QUERY = "select id, name, grade from Demo.student where name = ? and grade = ?"; + + try(Connection connection = getConnection()) { + PreparedStatement preparedStatement = connection.prepareStatement(SQL_QUERY); + preparedStatement.setString(1, "Robin"); + preparedStatement.setInt(2, 4); + ResultSet resultSet = preparedStatement.executeQuery(); + while (resultSet.next()) { + int id = resultSet.getInt("id"); + String name = resultSet.getString("name"); + int grade = resultSet.getInt("grade"); + assertNotNull(Integer.valueOf(id)); + assertEquals("Robin", name); + logger.info("Student id:" + id + " Student Name:" + name + " grade:" + grade); + } + } + } + + @Test + void givenPreparedStatement_whenDeleteRecord_thenSuccess() throws SQLException { + final String DELETE_SQL = "delete from Demo.student where name = ?"; + + try(Connection connection = getConnection()) { + PreparedStatement preparedStatement = connection.prepareStatement(DELETE_SQL); + preparedStatement.setString(1, "James"); + assertDoesNotThrow(() -> preparedStatement.execute()); + assertEquals(1, preparedStatement.getUpdateCount()); + } + } + + @Test + void givenPreparedStatement_whenUpdateRecord_thenSuccess() throws SQLException { + final String UPDATE_SQL = "update Demo.student set grade = ? where id = ? and name = ?"; + + try(Connection connection = getConnection()) { + PreparedStatement preparedStatement = connection.prepareStatement(UPDATE_SQL); + preparedStatement.setInt(1, 5); + preparedStatement.setInt(2, 1); + preparedStatement.setString(3, "John"); + assertDoesNotThrow(() -> preparedStatement.execute()); + assertEquals(1, preparedStatement.getUpdateCount()); + } + } + + //@Test + void whenAddtoBatch_thenExecuteBatchIsSuccess() throws SQLException { + final String INSERT_SQL = "insert into Demo.teacher(id, name, joining_date, subject_id)" + + "values(?, ?, ?, ?)"; + + try(Connection connection = getConnection()) { + PreparedStatement preparedStatement = connection.prepareStatement(INSERT_SQL); + preparedStatement.setInt(1, 9); + preparedStatement.setString(2, "Bret Lee"); + preparedStatement.setString(3, "07-08-2002"); + preparedStatement.setString(4, "[1, 3]"); + preparedStatement.addBatch(); + + preparedStatement.setInt(1, 10); + preparedStatement.setString(2, "Sarah Glimmer"); + preparedStatement.setString(3, "07-08-1997"); + preparedStatement.setString(4, "[1, 2]"); + + preparedStatement.addBatch(); + + assertDoesNotThrow(() -> preparedStatement.executeBatch()); + } + } + + + @Test + void whenExecuteJoinQuery_thenResultSuccess() throws SQLException { + final String JOIN_QUERY = "SELECT t.name as teacher_name, s.name as subject_name " + + "from Demo.teacher AS t INNER JOIN Demo.subject AS s ON t.subject_id = s.id"; + + try(Connection connection = getConnection()) { + Statement statement = connection.createStatement(); + + + ResultSet resultSet = statement.executeQuery(JOIN_QUERY); + while (resultSet.next()) { + logger.info("Teacher Name:" + resultSet.getString("teacher_name") + " Subject Name:" + + resultSet.getString("subject_name")); + } + + + } + + } + + @Test + void whenExecuteStoredToCreateTable_thenSuccess() throws SQLException { + final String CREATE_TABLE_SQL = "CreateTable"; + try(Connection connection = getConnection()) { + CallableStatement callableStatement = connection.prepareCall(CREATE_TABLE_SQL); + + callableStatement.setString("SchemaName", "prod"); //schema gets created too + callableStatement.setString("TableName", "subject"); + callableStatement.setString("PrimaryKey", "id"); + Boolean result = callableStatement.execute(); + + ResultSet resultSet = callableStatement.getResultSet(); + + while(resultSet.next()) { + String tableCreated = resultSet.getString("Success"); + assertEquals("true", tableCreated); + logger.info("result of the callable execute:" + tableCreated); + } + } + } +} diff --git a/persistence-modules/java-harperdb/src/test/java/com/baledung/harperdb/HarperDBLiveTestOld.java b/persistence-modules/java-harperdb/src/test/java/com/baledung/harperdb/HarperDBLiveTestOld.java new file mode 100644 index 0000000000..8becea76a5 --- /dev/null +++ b/persistence-modules/java-harperdb/src/test/java/com/baledung/harperdb/HarperDBLiveTestOld.java @@ -0,0 +1,356 @@ +package com.baledung.harperdb; + +import cdata.jdbc.harperdb.HarperDBConnectionPoolDataSource; +import com.github.dockerjava.zerodep.shaded.org.apache.hc.client5.http.classic.methods.HttpPost; +import com.github.dockerjava.zerodep.shaded.org.apache.hc.client5.http.impl.classic.CloseableHttpClient; +import com.github.dockerjava.zerodep.shaded.org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; +import com.github.dockerjava.zerodep.shaded.org.apache.hc.client5.http.impl.classic.HttpClientBuilder; +import com.github.dockerjava.zerodep.shaded.org.apache.hc.core5.http.ClassicHttpRequest; +import com.github.dockerjava.zerodep.shaded.org.apache.hc.core5.http.HttpEntity; +import com.github.dockerjava.zerodep.shaded.org.apache.hc.core5.http.io.entity.StringEntity; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testcontainers.containers.GenericContainer; + +import java.io.IOException; +import java.net.URISyntaxException; +import java.sql.*; +import java.util.Map; +import java.util.Properties; + +import static org.junit.jupiter.api.Assertions.*; + +public class HarperDBLiveTestOld { + private static final Logger logger = LoggerFactory.getLogger(HarperDBLiveTestOld.class); + + private static String host; + + private static Integer port; + + private static GenericContainer harperDBContainer; + + @BeforeAll + static void setupHarperDB() throws IOException, InterruptedException, URISyntaxException { + installHarperDB(); + setupDB(); + } + + private static void installHarperDB() { + Map envMap = Map.of( + "HDB_ADMIN_USERNAME", "admin", + "HDB_ADMIN_PASSWORD", "password", + "OPERATIONSAPI_NETWORK_PORT", "9925", + "ROOTPATH", "/home/harperdb/hdb", + "LOGGING_STDSTREAMS", "true" + ); + + harperDBContainer = new GenericContainer("harperdb/harperdb:latest") + .withEnv(envMap) + .withExposedPorts(9925, 9926); + host = harperDBContainer.getHost(); + harperDBContainer.start(); + port = harperDBContainer.getFirstMappedPort(); + logger.info("DB Host:" + host + "\n DB Port:" + port); + } + + private static void setupDB() throws URISyntaxException, IOException { + setupSchema("demo"); + createTable("demo", "student", "name", "grade", "subject_id"); + createTable("demo", "teacher", "name", "joining_date", "subject_id"); + insertRecords(); + } + + private static void setupSchema(String schema) throws URISyntaxException, IOException { + String requestBody = "{\"operation\":\"create_schema\", \"" + "schema\":\"" + schema + "\"" + "}"; + executeHttpPostRequest(requestBody); + } + + private static void executeHttpPostRequest(String httpRequest) throws IOException { + logger.info("Post request body:" + httpRequest); + + try (CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().build()) { + HttpPost request = new HttpPost("http://localhost:" + port + "/"); + request.addHeader("Authorization", "Basic YWRtaW46cGFzc3dvcmQ="); + request.addHeader("Content-Type", "application/json"); + request.setEntity((HttpEntity) new StringEntity(httpRequest)); + CloseableHttpResponse response = closeableHttpClient.execute((ClassicHttpRequest) request); + logger.info("REST API response:" + response.toString()); + assertEquals(200, response.getCode()); + } + } + + private void insertStudentRecords() { + + } + + private void insertSubjectRecords() { + + } + + private void insertTeacherRecords() { + + } + + private static void createTable(String schemaName, String tableName, String... attributes) throws IOException { + String createTableReq = "{\"operation\":\"create_table\",\"schema\":\"" + + schemaName + "\",\"table\":\"" + + tableName + "\",\"hash_attribute\":\"id\"" + + "}"; + executeHttpPostRequest(createTableReq); + logger.info("created table:" + tableName); + for (String attribute : attributes) { + String createAttrReq = "{\"operation\":\"create_attribute\",\"schema\":\"" + + schemaName + "\",\"table\":\"" + + tableName + "\",\"attribute\":\"" + + attribute + "\"" + + "}"; + executeHttpPostRequest(createAttrReq); + logger.info("created attribute:" + attribute + " in table:" + tableName); + } + } + + private static void insertRecords() throws IOException { + + String table = "student"; + String schema = "demo"; + String operation = "insert"; + String records = "[" + + "{\"id\":1, \"name\":\"John\", \"grade\":4}," + + "{\"id\":2, \"name\":\"James\", \"grade\":1}," + + "{\"id\":3, \"name\":\"Williams\", \"grade\":1}," + + "{\"id\":4, \"name\":\"Robin\", \"grade\":4}," + + "{\"id\":5, \"name\":\"Torry\", \"grade\":3}," + + "{\"id\":6, \"name\":\"Nancy\", \"grade\":5}," + + "{\"id\":7, \"name\":\"Mary\", \"grade\":5}," + + "{\"id\":8, \"name\":\"Jenny\", \"grade\":6}," + + "{\"id\":9, \"name\":\"Katy\", \"grade\":6}," + + "{\"id\":15, \"name\":\"Michael\", \"grade\":6}" + + "]"; + String requestBody = "{\"table\":" + "\"" + table + "\"," + + "\"schema\":" + "\"" + schema + "\"" + "," + + "\"operation\":" + "\"" + operation + "\"" + "," + + "\"records\":" + records + + "}"; + String sql = "{" + + "\"operation\":\"sql\", " + + "\"sql\":\"insert into demo.student(id, name, grade) values" + + "(1, 'John', 4), (2, 'James', 1), (3, 'Williams', 1), (4, 'Robin', 4), (5, 'Torry', 3)," + + " (6, 'Nancy', 5), (7, 'Mary', 5), (8, 'Jenny', 6), (9, 'Katy', 6)\"" + + "}"; + executeHttpPostRequest(requestBody); + } + + @AfterAll + static void stopHarperDB() { + harperDBContainer.stop(); + } + + @Test + void whenConnectionInfoInURL_thenConnectSuccess() throws SQLException { + assertDoesNotThrow(() -> { + String URL = "jdbc:harperdb:Server=127.0.0.1:" + port + ";User=admin;Password=password;"; + + try (Connection connection = DriverManager.getConnection(URL)) { + connection.createStatement().executeQuery("select 1"); + logger.info("Connection Successful"); + } + }); + } + + @Test + void whenConnectionInfoInProperties_thenConnectSuccess() throws SQLException { + assertDoesNotThrow(() -> { + Properties prop = new Properties(); + prop.setProperty("Server", "127.0.0.1:" + port); + prop.setProperty("User", "admin"); + prop.setProperty("Password", "password"); + + try (Connection connection = DriverManager.getConnection("jdbc:harperdb:", prop)) { + connection.createStatement().executeQuery("select 1"); + logger.info("Connection Successful"); + } + }); + } + + @Test + void whenConnectionPooling_thenConnectSuccess() throws SQLException { + assertDoesNotThrow(() -> { + HarperDBConnectionPoolDataSource harperdbPoolDataSource = new HarperDBConnectionPoolDataSource(); + String URL = "jdbc:harperdb:UseConnectionPooling=true;PoolMaxSize=2;Server=127.0.0.1:" + port + + ";User=admin;Password=1234;"; + harperdbPoolDataSource.setURL(URL); + + try(Connection connection = harperdbPoolDataSource.getPooledConnection().getConnection()) { + connection.createStatement().executeQuery("select 1"); + logger.info("Connection Successful"); + } + }); + } + + private static Connection getConnection() throws SQLException { + String URL = "jdbc:harperdb:Server=127.0.0.1:" + port + ";User=admin;Password=password;"; + return DriverManager.getConnection(URL); + } + + @Test + void givenStatement_whenFetchRecord_thenSuccess() throws SQLException { + final String SQL_QUERY = "select id, name, grade from demo.student"; + + try(Connection connection = getConnection()) { + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(SQL_QUERY); + while (resultSet.next()) { + int id = resultSet.getInt("id"); + String name = resultSet.getString("name"); + int grade = resultSet.getInt("grade"); + assertNotNull(Integer.valueOf(id)); + logger.info("Student id:" + id + " Student Name:" + name + " grade:" + grade); + } + } + } + + @Test + void givenStatement_whenInsertRecord_thenSuccess() throws SQLException { + final String INSERT_SQL = "insert into demo.student(id, name, grade) values (10, 'Barak', 3)"; + + try(Connection connection = getConnection()) { + Statement statement = connection.createStatement(); + assertDoesNotThrow(() -> statement.execute(INSERT_SQL)); + } + } + + @Test + void givenStatement_whenInsertRecordInTableWithoutAttributes_thenSuccess() throws SQLException { + final String INSERT_SQL = "insert into demo.teacher(id, name, joining_date) " + + "values (1, 'David Martinez', '04-05-2004'), (2, 'Eric Martin', '04-10-2000')"; + final String QUERY_SQL = "select name, joining_date from demo.teacher where name = ?"; + + try(Connection connection = getConnection()) { + Statement statement = connection.createStatement(); + assertDoesNotThrow(() -> statement.execute(INSERT_SQL)); + PreparedStatement preparedStatement = connection.prepareStatement(QUERY_SQL); + preparedStatement.setString(1, "Eric Martin"); + ResultSet resultSet = preparedStatement.executeQuery(); + while (resultSet.next()) { + String teacherName = resultSet.getString("name"); + String joinDate = resultSet.getString("joining_date"); + assertEquals("Eric Martin", teacherName); + assertEquals("04-10-2000", joinDate); + logger.info("name:" + teacherName + " joining date:" + joinDate); + } + } + } + + @Test + void givenStatement_whenUpdateRecord_thenSuccess() throws SQLException { + final String UPDATE_SQL = "update demo.student set grade = 4 where id = 5"; + + try(Connection connection = getConnection()) { + Statement statement = connection.createStatement(); + assertDoesNotThrow(() -> statement.execute(UPDATE_SQL)); + assertEquals(1, statement.getUpdateCount()); + } + } + + @Test + void givenStatement_whenDeleteRecord_thenSuccess() throws SQLException { + final String DELETE_SQL = "delete from demo.student where id = 3"; + + try(Connection connection = getConnection()) { + Statement statement = connection.createStatement(); + assertDoesNotThrow(() -> statement.execute(DELETE_SQL)); + assertEquals(1, statement.getUpdateCount()); + } + } + + @Test + void givenPreparedStatement_whenFetchRecord_thenSuccess() throws SQLException { + final String SQL_QUERY = "select id, name, grade from demo.student where name = ? and grade = ?"; + + try(Connection connection = getConnection()) { + PreparedStatement preparedStatement = connection.prepareStatement(SQL_QUERY); + preparedStatement.setString(1, "Robin"); + preparedStatement.setInt(2, 4); + ResultSet resultSet = preparedStatement.executeQuery(); + while (resultSet.next()) { + int id = resultSet.getInt("id"); + String name = resultSet.getString("name"); + int grade = resultSet.getInt("grade"); + assertNotNull(Integer.valueOf(id)); + assertEquals("Robin", name); + logger.info("Student id:" + id + " Student Name:" + name + " grade:" + grade); + } + } + } + + @Test + void givenPreparedStatement_whenDeleteRecord_thenSuccess() throws SQLException { + final String DELETE_SQL = "delete from demo.student where name = ?"; + + try(Connection connection = getConnection()) { + PreparedStatement preparedStatement = connection.prepareStatement(DELETE_SQL); + preparedStatement.setString(1, "James"); + assertDoesNotThrow(() -> preparedStatement.execute()); + assertEquals(1, preparedStatement.getUpdateCount()); + } + } + + @Test + void givenPreparedStatement_whenUpdateRecord_thenSuccess() throws SQLException { + final String UPDATE_SQL = "update demo.student set grade = ? where id = ? and name = ?"; + + try(Connection connection = getConnection()) { + PreparedStatement preparedStatement = connection.prepareStatement(UPDATE_SQL); + preparedStatement.setInt(1, 5); + preparedStatement.setInt(2, 1); + preparedStatement.setString(3, "John"); + assertDoesNotThrow(() -> preparedStatement.execute()); + assertEquals(1, preparedStatement.getUpdateCount()); + } + } + + @Test + void whenAddtoBatch_thenExecuteBatchIsSuccess() throws SQLException { + final String INSERT_SQL = "insert into demo.teacher(id, name, joining_date)" + + "values(?, ?, ?)"; + + try(Connection connection = getConnection()) { + PreparedStatement preparedStatement = connection.prepareStatement(INSERT_SQL); + preparedStatement.setInt(1, 1); + preparedStatement.setString(2, "Bret Lee"); + preparedStatement.setString(3, "07-08-2002"); + preparedStatement.addBatch(); + + preparedStatement.setInt(1, 2); + preparedStatement.setString(2, "Sarah Glimmer"); + preparedStatement.setString(3, "07-08-1997"); + preparedStatement.addBatch(); + + assertDoesNotThrow(() -> preparedStatement.executeBatch()); + } + } + + @Test + void whenExecuteStoredToCreateTable_thenSuccess() throws SQLException { + final String CREATE_TABLE_SQL = "CreateTable"; + try(Connection connection = getConnection()) { + CallableStatement callableStatement = connection.prepareCall(CREATE_TABLE_SQL); + + callableStatement.setString("SchemaName", "prod"); //schema gets created too + callableStatement.setString("TableName", "subject"); + callableStatement.setString("PrimaryKey", "id"); + Boolean result = callableStatement.execute(); + + ResultSet resultSet = callableStatement.getResultSet(); + + while(resultSet.next()) { + String tableCreated = resultSet.getString("Success"); + assertEquals("true", tableCreated); + logger.info("result of the callable execute:" + tableCreated); + } + } + } +} From 1a63be903582dd95c93499039a363f91c678d281 Mon Sep 17 00:00:00 2001 From: parthiv39731 <70740707+parthiv39731@users.noreply.github.com> Date: Mon, 27 Nov 2023 10:27:27 +0530 Subject: [PATCH 131/228] BAEL-7259 --- .../baledung/harperdb/HarperDBApiService.java | 38 +++--- .../baledung/harperdb/HarperDBContainer.java | 32 ++--- .../baledung/harperdb/HarperDBLiveTest.java | 123 ++++++++---------- 3 files changed, 89 insertions(+), 104 deletions(-) diff --git a/persistence-modules/java-harperdb/src/test/java/com/baledung/harperdb/HarperDBApiService.java b/persistence-modules/java-harperdb/src/test/java/com/baledung/harperdb/HarperDBApiService.java index 1eedd8648f..15178f9769 100644 --- a/persistence-modules/java-harperdb/src/test/java/com/baledung/harperdb/HarperDBApiService.java +++ b/persistence-modules/java-harperdb/src/test/java/com/baledung/harperdb/HarperDBApiService.java @@ -14,17 +14,20 @@ import java.io.IOException; import java.util.Base64; public class HarperDBApiService { + private static final Logger LOGGER = LoggerFactory.getLogger(HarperDBApiService.class); private String url; private String base64auth; public HarperDBApiService(String url, String user, String password) { this.url = url; this.base64auth = Base64.getEncoder() - .encodeToString(new StringBuilder().append(user).append(":").append(password).toString().getBytes()); + .encodeToString(new StringBuilder().append(user) + .append(":") + .append(password) + .toString() + .getBytes()); } - private static final Logger LOGGER = LoggerFactory.getLogger(HarperDBApiService.class); - public void createSchema(String schema) throws IOException { String requestBody = "{\"operation\":\"create_schema\", \"" + "schema\":\"" + schema + "\"" + "}"; executeHttpPostRequest(requestBody); @@ -32,18 +35,18 @@ public class HarperDBApiService { public void createTable(String schema, String table, String ... attributes) throws IOException { String createTableReq = "{\"operation\":\"create_table\"," - + "\"schema\":\"" + schema - + "\",\"table\":\"" + table - + "\",\"hash_attribute\":\"id\"" - + "}"; + + "\"schema\":\"" + schema + + "\",\"table\":\"" + table + + "\",\"hash_attribute\":\"id\"" + + "}"; executeHttpPostRequest(createTableReq); LOGGER.info("created table:" + table); for (String attribute : attributes) { String createAttrReq = "{\"operation\":\"create_attribute\",\"schema\":\"" - + schema + "\",\"table\":\"" - + table + "\",\"attribute\":\"" - + attribute + "\"" - + "}"; + + schema + "\",\"table\":\"" + + table + "\",\"attribute\":\"" + + attribute + "\"" + + "}"; executeHttpPostRequest(createAttrReq); LOGGER.info("created attribute:" + attribute + " in table:" + table); } @@ -51,24 +54,25 @@ public class HarperDBApiService { public void insertRecords(String schema, String table, String records) throws IOException { String requestBody = "{\"table\":" + "\"" + table + "\"," - + "\"schema\":" + "\"" + schema + "\"" + "," - + "\"operation\":" + "\"" + "insert" + "\"" + "," - + "\"records\":" + records - + "}"; + + "\"schema\":" + "\"" + schema + "\"" + "," + + "\"operation\":" + "\"" + "insert" + "\"" + "," + + "\"records\":" + records + + "}"; executeHttpPostRequest(requestBody); } private void executeHttpPostRequest(String httpRequest) throws IOException { LOGGER.info("Post request body:" + httpRequest); - try (CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().build()) { + try (CloseableHttpClient closeableHttpClient = HttpClientBuilder.create() + .build()) { HttpPost request = new HttpPost(this.url); request.addHeader("Authorization", "Basic " + this.base64auth); request.addHeader("Content-Type", "application/json"); request.setEntity((HttpEntity) new StringEntity(httpRequest)); CloseableHttpResponse response = closeableHttpClient.execute((ClassicHttpRequest) request); LOGGER.info("REST API response:" + response.toString()); - assert(200 == response.getCode()); + assert (200 == response.getCode()); } } } diff --git a/persistence-modules/java-harperdb/src/test/java/com/baledung/harperdb/HarperDBContainer.java b/persistence-modules/java-harperdb/src/test/java/com/baledung/harperdb/HarperDBContainer.java index 79656b1b73..5ce6e069ce 100644 --- a/persistence-modules/java-harperdb/src/test/java/com/baledung/harperdb/HarperDBContainer.java +++ b/persistence-modules/java-harperdb/src/test/java/com/baledung/harperdb/HarperDBContainer.java @@ -1,42 +1,36 @@ package com.baledung.harperdb; +import java.util.Map; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testcontainers.containers.GenericContainer; -import java.util.Map; - public class HarperDBContainer { + private final static Logger LOGGER = LoggerFactory.getLogger(HarperDBContainer.class); + private static final Map DEFAULT_ENV_MAP = Map.of("HDB_ADMIN_USERNAME", "admin", "HDB_ADMIN_PASSWORD", "password", + "OPERATIONSAPI_NETWORK_PORT", "9925", "ROOTPATH", "/home/harperdb/hdb", "LOGGING_STDSTREAMS", "true"); - - private static final Map DEFAULT_ENV_MAP = Map.of( - "HDB_ADMIN_USERNAME", "admin", - "HDB_ADMIN_PASSWORD", "password", - "OPERATIONSAPI_NETWORK_PORT", "9925", - "ROOTPATH", "/home/harperdb/hdb", - "LOGGING_STDSTREAMS", "true" - ); - - private static final Integer[] DEFAULT_EXPOSED_PORTS = {9925, 9926}; + private static final Integer[] DEFAULT_EXPOSED_PORTS = { 9925, 9926 }; private static final String HARPER_DOCKER_IMAGE = "harperdb/harperdb:latest"; public void stop() { harperDBContainer.stop(); } + GenericContainer harperDBContainer; + public GenericContainer installHarperDB() { - harperDBContainer = new GenericContainer(HARPER_DOCKER_IMAGE) - .withEnv(DEFAULT_ENV_MAP) - .withExposedPorts(DEFAULT_EXPOSED_PORTS); + harperDBContainer = new GenericContainer(HARPER_DOCKER_IMAGE).withEnv(DEFAULT_ENV_MAP) + .withExposedPorts(DEFAULT_EXPOSED_PORTS); return harperDBContainer; } - public GenericContainer installHarperDB(String dockerImgage, final Map envMap, final Integer ... exposedPorts) { - return new GenericContainer(dockerImgage) - .withEnv(envMap) - .withExposedPorts(exposedPorts); + public GenericContainer installHarperDB(String dockerImgage, final Map envMap, final Integer... exposedPorts) { + return new GenericContainer(dockerImgage).withEnv(envMap) + .withExposedPorts(exposedPorts); } } diff --git a/persistence-modules/java-harperdb/src/test/java/com/baledung/harperdb/HarperDBLiveTest.java b/persistence-modules/java-harperdb/src/test/java/com/baledung/harperdb/HarperDBLiveTest.java index 767d9d971b..42ef04dadf 100644 --- a/persistence-modules/java-harperdb/src/test/java/com/baledung/harperdb/HarperDBLiveTest.java +++ b/persistence-modules/java-harperdb/src/test/java/com/baledung/harperdb/HarperDBLiveTest.java @@ -1,6 +1,7 @@ package com.baledung.harperdb; import cdata.jdbc.harperdb.HarperDBConnectionPoolDataSource; + import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -16,6 +17,7 @@ import java.util.Properties; import static org.junit.jupiter.api.Assertions.*; public class HarperDBLiveTest { + private static final Logger logger = LoggerFactory.getLogger(HarperDBLiveTest.class); private static String host; @@ -61,40 +63,27 @@ public class HarperDBLiveTest { } private static void insertSubjectRecords() throws IOException { - String records = "[" - + "{\"id\":1, \"name\":\"English\"}," - + "{\"id\":2, \"name\":\"Maths\"}," - + "{\"id\":3, \"name\":\"Science\"}" - + "]"; + String records = "[" + "{\"id\":1, \"name\":\"English\"}," + "{\"id\":2, \"name\":\"Maths\"}," + "{\"id\":3, \"name\":\"Science\"}" + "]"; harperDbApiService.insertRecords("Demo", "Subject", records); } - private static void insertTeacherRecords() throws IOException { - String records = "[" + - "{\"id\":1, \"name\":\"Parthiv Pradhan\", \"joining_date\":\"04-05-2000\"}," - + "{\"id\":2, \"name\":\"David Martinez\", \"joining_date\":\"20-10-2005\"}," - + "{\"id\":3, \"name\":\"Liam Williams\", \"joining_date\":\"04-06-1997\"}," - + "{\"id\":4, \"name\":\"Robin Williams\", \"joining_date\":\"01-01-2020\"}," - + "{\"id\":5, \"name\":\"Eric Martin\", \"joining_date\":\"04-05-2022\"}," - + "{\"id\":6, \"name\":\"Sajjan Nagendra\", \"joining_date\":\"02-02-1999\"}" - + "]"; + private static void insertTeacherRecords() throws IOException { + String records = "[" + "{\"id\":1, \"name\":\"Parthiv Pradhan\", \"joining_date\":\"04-05-2000\"}," + + "{\"id\":2, \"name\":\"David Martinez\", \"joining_date\":\"20-10-2005\"}," + + "{\"id\":3, \"name\":\"Liam Williams\", \"joining_date\":\"04-06-1997\"}," + + "{\"id\":4, \"name\":\"Robin Williams\", \"joining_date\":\"01-01-2020\"}," + + "{\"id\":5, \"name\":\"Eric Martin\", \"joining_date\":\"04-05-2022\"}," + + "{\"id\":6, \"name\":\"Sajjan Nagendra\", \"joining_date\":\"02-02-1999\"}" + "]"; harperDbApiService.insertRecords("Demo", "Teacher", records); } private static void insertTeacherDetailsRecords() throws IOException { - String records = "[" - + "{\"id\":1, \"teacher_id\":1, \"subject_id\":1}," - + "{\"id\":2, \"teacher_id\":1, \"subject_id\":2}," - + "{\"id\":3, \"teacher_id\":2, \"subject_id\":3 }," - + "{\"id\":4, \"teacher_id\":3, \"subject_id\":1}," - + "{\"id\":5, \"teacher_id\":3, \"subject_id\":3}," - + "{\"id\":6, \"teacher_id\":4, \"subject_id\":2}," - + "{\"id\":7, \"teacher_id\":5, \"subject_id\":3}," - + "{\"id\":8, \"teacher_id\":6, \"subject_id\":1}," - + "{\"id\":9, \"teacher_id\":6, \"subject_id\":2}," - + "{\"id\":15, \"teacher_id\":6, \"subject_id\":3}" - + "]"; + String records = "[" + "{\"id\":1, \"teacher_id\":1, \"subject_id\":1}," + "{\"id\":2, \"teacher_id\":1, \"subject_id\":2}," + + "{\"id\":3, \"teacher_id\":2, \"subject_id\":3 }," + "{\"id\":4, \"teacher_id\":3, \"subject_id\":1}," + + "{\"id\":5, \"teacher_id\":3, \"subject_id\":3}," + "{\"id\":6, \"teacher_id\":4, \"subject_id\":2}," + + "{\"id\":7, \"teacher_id\":5, \"subject_id\":3}," + "{\"id\":8, \"teacher_id\":6, \"subject_id\":1}," + + "{\"id\":9, \"teacher_id\":6, \"subject_id\":2}," + "{\"id\":15, \"teacher_id\":6, \"subject_id\":3}" + "]"; harperDbApiService.insertRecords("Demo", "Teacher_Details", records); } @@ -110,7 +99,8 @@ public class HarperDBLiveTest { final String JDBC_URL = "jdbc:harperdb:Server=127.0.0.1:" + port + ";User=admin;Password=password;"; try (Connection connection = DriverManager.getConnection(JDBC_URL)) { - connection.createStatement().executeQuery("select 1"); + connection.createStatement() + .executeQuery("select 1"); logger.info("Connection Successful"); } }); @@ -125,7 +115,8 @@ public class HarperDBLiveTest { prop.setProperty("Password", "password"); try (Connection connection = DriverManager.getConnection("jdbc:harperdb:", prop)) { - connection.createStatement().executeQuery("select 1"); + connection.createStatement() + .executeQuery("select 1"); logger.info("Connection Successful"); } }); @@ -135,12 +126,13 @@ public class HarperDBLiveTest { void whenConnectionPooling_thenConnectSuccess() throws SQLException { assertDoesNotThrow(() -> { HarperDBConnectionPoolDataSource harperdbPoolDataSource = new HarperDBConnectionPoolDataSource(); - final String JDBC_URL = "jdbc:harperdb:UseConnectionPooling=true;PoolMaxSize=2;Server=127.0.0.1:" + port - + ";User=admin;Password=password;"; + final String JDBC_URL = "jdbc:harperdb:UseConnectionPooling=true;PoolMaxSize=2;Server=127.0.0.1:" + port + ";User=admin;Password=password;"; harperdbPoolDataSource.setURL(JDBC_URL); - try(Connection connection = harperdbPoolDataSource.getPooledConnection().getConnection()) { - connection.createStatement().executeQuery("select 1"); + try (Connection connection = harperdbPoolDataSource.getPooledConnection() + .getConnection()) { + connection.createStatement() + .executeQuery("select 1"); logger.info("Connection Pool Successful"); } }); @@ -155,7 +147,7 @@ public class HarperDBLiveTest { void givenStatement_whenFetchRecord_thenSuccess() throws SQLException { final String SQL_QUERY = "select id, name, grade from Demo.student"; - try(Connection connection = getConnection()) { + try (Connection connection = getConnection()) { Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(SQL_QUERY); while (resultSet.next()) { @@ -172,7 +164,7 @@ public class HarperDBLiveTest { void givenStatement_whenInsertRecord_thenSuccess() throws SQLException { final String INSERT_SQL = "insert into Demo.student(id, name, grade) values (10, 'Barak', 3)"; - try(Connection connection = getConnection()) { + try (Connection connection = getConnection()) { Statement statement = connection.createStatement(); assertDoesNotThrow(() -> statement.execute(INSERT_SQL)); } @@ -180,11 +172,11 @@ public class HarperDBLiveTest { @Test void givenStatement_whenInsertRecordInTableWithoutAttributes_thenSuccess() throws SQLException { - final String INSERT_SQL = "insert into Demo.teacher(id, name, joining_date) " - + "values (7, 'David Sirocco', '04-05-2004'), (8, 'Ali Azmat', '04-10-2000')"; + final String INSERT_SQL = + "insert into Demo.teacher(id, name, joining_date) " + "values (7, 'David Sirocco', '04-05-2004'), (8, 'Ali Azmat', '04-10-2000')"; final String QUERY_SQL = "select name, joining_date from Demo.teacher where name = ?"; - try(Connection connection = getConnection()) { + try (Connection connection = getConnection()) { Statement statement = connection.createStatement(); assertDoesNotThrow(() -> statement.execute(INSERT_SQL)); PreparedStatement preparedStatement = connection.prepareStatement(QUERY_SQL); @@ -204,7 +196,7 @@ public class HarperDBLiveTest { void givenStatement_whenUpdateRecord_thenSuccess() throws SQLException { final String UPDATE_SQL = "update Demo.student set grade = 4 where id = 5"; - try(Connection connection = getConnection()) { + try (Connection connection = getConnection()) { Statement statement = connection.createStatement(); assertDoesNotThrow(() -> statement.execute(UPDATE_SQL)); assertEquals(1, statement.getUpdateCount()); @@ -215,7 +207,7 @@ public class HarperDBLiveTest { void givenStatement_whenDeleteRecord_thenSuccess() throws SQLException { final String DELETE_SQL = "delete from Demo.student where id = 3"; - try(Connection connection = getConnection()) { + try (Connection connection = getConnection()) { Statement statement = connection.createStatement(); assertDoesNotThrow(() -> statement.execute(DELETE_SQL)); assertEquals(1, statement.getUpdateCount()); @@ -226,27 +218,27 @@ public class HarperDBLiveTest { void givenPreparedStatement_whenFetchRecord_thenSuccess() throws SQLException { final String SQL_QUERY = "select id, name, grade from Demo.student where name = ? and grade = ?"; - try(Connection connection = getConnection()) { - PreparedStatement preparedStatement = connection.prepareStatement(SQL_QUERY); - preparedStatement.setString(1, "Robin"); - preparedStatement.setInt(2, 4); - ResultSet resultSet = preparedStatement.executeQuery(); - while (resultSet.next()) { - int id = resultSet.getInt("id"); - String name = resultSet.getString("name"); - int grade = resultSet.getInt("grade"); - assertNotNull(Integer.valueOf(id)); - assertEquals("Robin", name); - logger.info("Student id:" + id + " Student Name:" + name + " grade:" + grade); - } - } + try (Connection connection = getConnection()) { + PreparedStatement preparedStatement = connection.prepareStatement(SQL_QUERY); + preparedStatement.setString(1, "Robin"); + preparedStatement.setInt(2, 4); + ResultSet resultSet = preparedStatement.executeQuery(); + while (resultSet.next()) { + int id = resultSet.getInt("id"); + String name = resultSet.getString("name"); + int grade = resultSet.getInt("grade"); + assertNotNull(Integer.valueOf(id)); + assertEquals("Robin", name); + logger.info("Student id:" + id + " Student Name:" + name + " grade:" + grade); + } + } } @Test void givenPreparedStatement_whenDeleteRecord_thenSuccess() throws SQLException { final String DELETE_SQL = "delete from Demo.student where name = ?"; - try(Connection connection = getConnection()) { + try (Connection connection = getConnection()) { PreparedStatement preparedStatement = connection.prepareStatement(DELETE_SQL); preparedStatement.setString(1, "James"); assertDoesNotThrow(() -> preparedStatement.execute()); @@ -258,7 +250,7 @@ public class HarperDBLiveTest { void givenPreparedStatement_whenUpdateRecord_thenSuccess() throws SQLException { final String UPDATE_SQL = "update Demo.student set grade = ? where id = ? and name = ?"; - try(Connection connection = getConnection()) { + try (Connection connection = getConnection()) { PreparedStatement preparedStatement = connection.prepareStatement(UPDATE_SQL); preparedStatement.setInt(1, 5); preparedStatement.setInt(2, 1); @@ -270,10 +262,9 @@ public class HarperDBLiveTest { //@Test void whenAddtoBatch_thenExecuteBatchIsSuccess() throws SQLException { - final String INSERT_SQL = "insert into Demo.teacher(id, name, joining_date, subject_id)" - + "values(?, ?, ?, ?)"; + final String INSERT_SQL = "insert into Demo.teacher(id, name, joining_date, subject_id)" + "values(?, ?, ?, ?)"; - try(Connection connection = getConnection()) { + try (Connection connection = getConnection()) { PreparedStatement preparedStatement = connection.prepareStatement(INSERT_SQL); preparedStatement.setInt(1, 9); preparedStatement.setString(2, "Bret Lee"); @@ -292,23 +283,19 @@ public class HarperDBLiveTest { } } - @Test void whenExecuteJoinQuery_thenResultSuccess() throws SQLException { - final String JOIN_QUERY = "SELECT t.name as teacher_name, s.name as subject_name " + - "from Demo.teacher AS t INNER JOIN Demo.subject AS s ON t.subject_id = s.id"; + final String JOIN_QUERY = + "SELECT t.name as teacher_name, s.name as subject_name " + "from Demo.teacher AS t INNER JOIN Demo.subject AS s ON t.subject_id = s.id"; - try(Connection connection = getConnection()) { + try (Connection connection = getConnection()) { Statement statement = connection.createStatement(); - ResultSet resultSet = statement.executeQuery(JOIN_QUERY); while (resultSet.next()) { - logger.info("Teacher Name:" + resultSet.getString("teacher_name") + " Subject Name:" - + resultSet.getString("subject_name")); + logger.info("Teacher Name:" + resultSet.getString("teacher_name") + " Subject Name:" + resultSet.getString("subject_name")); } - } } @@ -316,7 +303,7 @@ public class HarperDBLiveTest { @Test void whenExecuteStoredToCreateTable_thenSuccess() throws SQLException { final String CREATE_TABLE_SQL = "CreateTable"; - try(Connection connection = getConnection()) { + try (Connection connection = getConnection()) { CallableStatement callableStatement = connection.prepareCall(CREATE_TABLE_SQL); callableStatement.setString("SchemaName", "prod"); //schema gets created too @@ -326,7 +313,7 @@ public class HarperDBLiveTest { ResultSet resultSet = callableStatement.getResultSet(); - while(resultSet.next()) { + while (resultSet.next()) { String tableCreated = resultSet.getString("Success"); assertEquals("true", tableCreated); logger.info("result of the callable execute:" + tableCreated); From d58102e32c745da8eb903b60aef4ad18e6f3c78f Mon Sep 17 00:00:00 2001 From: parthiv39731 <70740707+parthiv39731@users.noreply.github.com> Date: Mon, 27 Nov 2023 10:54:21 +0530 Subject: [PATCH 132/228] BAEL-7200 fixed formatting --- .../modifyrequest/aop/EscapeHtmlAspect.java | 14 +++++++++----- .../config/WebMvcConfiguration.java | 3 ++- .../EscapeHtmlRequestWrapper.java | 7 +++---- .../EscapeHtmlAspectIntegrationTest.java | 10 ++++++---- .../EscapeHtmlFilterIntegrationTest.java | 18 ++++++++++-------- .../EscapeHtmlInterceptorIntegrationTest.java | 11 ++++++----- 6 files changed, 36 insertions(+), 27 deletions(-) diff --git a/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/aop/EscapeHtmlAspect.java b/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/aop/EscapeHtmlAspect.java index fb31abe11b..d4533dcf0b 100644 --- a/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/aop/EscapeHtmlAspect.java +++ b/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/aop/EscapeHtmlAspect.java @@ -17,6 +17,7 @@ import java.nio.charset.StandardCharsets; @RestControllerAdvice @Profile("aspectExample") public class EscapeHtmlAspect implements RequestBodyAdvice { + private static final Logger logger = LoggerFactory.getLogger(EscapeHtmlAspect.class); @Override @@ -26,7 +27,8 @@ public class EscapeHtmlAspect implements RequestBodyAdvice { } @Override - public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class> converterType) throws IOException { + public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, + Class> converterType) throws IOException { logger.info("beforeBodyRead called"); InputStream inputStream = inputMessage.getBody(); return new HttpInputMessage() { @@ -43,13 +45,15 @@ public class EscapeHtmlAspect implements RequestBodyAdvice { } @Override - public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class> converterType) { + public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, + Class> converterType) { // Return the modified object after reading the body return body; } @Override - public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class> converterType) { + public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, + Class> converterType) { //return the original body return body; } @@ -68,7 +72,7 @@ public class EscapeHtmlAspect implements RequestBodyAdvice { String input = stringBuilder.toString(); // Escape HTML characters return input.replaceAll("&", "&") - .replaceAll("<", "<") - .replaceAll(">", ">"); + .replaceAll("<", "<") + .replaceAll(">", ">"); } } diff --git a/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/config/WebMvcConfiguration.java b/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/config/WebMvcConfiguration.java index bd76fd5e55..2fc1fbc310 100644 --- a/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/config/WebMvcConfiguration.java +++ b/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/config/WebMvcConfiguration.java @@ -1,6 +1,7 @@ package com.baeldung.modifyrequest.config; import com.baeldung.modifyrequest.interceptor.EscapeHtmlRequestInterceptor; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Configuration; @@ -17,7 +18,7 @@ public class WebMvcConfiguration implements WebMvcConfigurer { public void addInterceptors(InterceptorRegistry registry) { logger.info("addInterceptors() called"); registry.addInterceptor(new EscapeHtmlRequestInterceptor()) - .addPathPatterns("/save"); + .addPathPatterns("/save"); WebMvcConfigurer.super.addInterceptors(registry); } diff --git a/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/requestwrapper/EscapeHtmlRequestWrapper.java b/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/requestwrapper/EscapeHtmlRequestWrapper.java index 65c758d956..e7b3abbc1f 100644 --- a/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/requestwrapper/EscapeHtmlRequestWrapper.java +++ b/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/modifyrequest/requestwrapper/EscapeHtmlRequestWrapper.java @@ -27,10 +27,9 @@ public class EscapeHtmlRequestWrapper extends HttpServletRequestWrapper { String input = stringBuilder.toString(); // Escape HTML characters return input.replaceAll("&", "&") - .replaceAll("<", "<") - .replaceAll(">", ">") - //.replaceAll("\"", """) - .replaceAll("'", "'"); + .replaceAll("<", "<") + .replaceAll(">", ">") + .replaceAll("'", "'"); } @Override diff --git a/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/modifyrequest/EscapeHtmlAspectIntegrationTest.java b/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/modifyrequest/EscapeHtmlAspectIntegrationTest.java index 12520b7e67..ef18591ccb 100644 --- a/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/modifyrequest/EscapeHtmlAspectIntegrationTest.java +++ b/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/modifyrequest/EscapeHtmlAspectIntegrationTest.java @@ -44,9 +44,11 @@ public class EscapeHtmlAspectIntegrationTest { ObjectMapper objectMapper = new ObjectMapper(); mockMvc.perform(MockMvcRequestBuilders.post(URI.create("/save")) - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(requestBody))) - .andExpect(MockMvcResultMatchers.status().isCreated()) - .andExpect(MockMvcResultMatchers.content().json(objectMapper.writeValueAsString(expectedResponseBody))); + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(requestBody))) + .andExpect(MockMvcResultMatchers.status() + .isCreated()) + .andExpect(MockMvcResultMatchers.content() + .json(objectMapper.writeValueAsString(expectedResponseBody))); } } diff --git a/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/modifyrequest/EscapeHtmlFilterIntegrationTest.java b/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/modifyrequest/EscapeHtmlFilterIntegrationTest.java index 3ab7618b05..d84ced5e1a 100644 --- a/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/modifyrequest/EscapeHtmlFilterIntegrationTest.java +++ b/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/modifyrequest/EscapeHtmlFilterIntegrationTest.java @@ -31,21 +31,23 @@ public class EscapeHtmlFilterIntegrationTest { @Test void givenFilter_whenEscapeHtmlFilter_thenEscapeHtml() throws Exception { Map requestBody = Map.of( - "name", "James Cameron", - "email", "james@gmail.com" + "name", "James Cameron", + "email", "james@gmail.com" ); Map expectedResponseBody = Map.of( - "name", "James Cameron", - "email", "<script>alert()</script>james@gmail.com" + "name", "James Cameron", + "email", "<script>alert()</script>james@gmail.com" ); ObjectMapper objectMapper = new ObjectMapper(); mockMvc.perform(MockMvcRequestBuilders.post(URI.create("/save")) - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(requestBody))) - .andExpect(MockMvcResultMatchers.status().isCreated()) - .andExpect(MockMvcResultMatchers.content().json(objectMapper.writeValueAsString(expectedResponseBody))); + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(requestBody))) + .andExpect(MockMvcResultMatchers.status() + .isCreated()) + .andExpect(MockMvcResultMatchers.content() + .json(objectMapper.writeValueAsString(expectedResponseBody))); } } diff --git a/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/modifyrequest/EscapeHtmlInterceptorIntegrationTest.java b/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/modifyrequest/EscapeHtmlInterceptorIntegrationTest.java index d855339bd9..06aff5db3b 100644 --- a/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/modifyrequest/EscapeHtmlInterceptorIntegrationTest.java +++ b/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/modifyrequest/EscapeHtmlInterceptorIntegrationTest.java @@ -33,14 +33,15 @@ public class EscapeHtmlInterceptorIntegrationTest { @Test void givenInterceptor_whenEscapeHtmlInterceptor_thenEscapeHtml() throws Exception { Map requestBody = Map.of( - "name", "James Cameron", - "email", "james@gmail.com" + "name", "James Cameron", + "email", "james@gmail.com" ); ObjectMapper objectMapper = new ObjectMapper(); mockMvc.perform(MockMvcRequestBuilders.post(URI.create("/save")) - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(requestBody))) - .andExpect(MockMvcResultMatchers.status().is4xxClientError()); + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(requestBody))) + .andExpect(MockMvcResultMatchers.status() + .is4xxClientError()); } } From 526a90bc8c8340925f04628eafaa3155077cdd05 Mon Sep 17 00:00:00 2001 From: parthiv39731 <70740707+parthiv39731@users.noreply.github.com> Date: Mon, 27 Nov 2023 10:58:12 +0530 Subject: [PATCH 133/228] BAEL-7200 fixed formatting --- .../modifyrequest/EscapeHtmlFilterIntegrationTest.java | 10 ++++------ .../EscapeHtmlInterceptorIntegrationTest.java | 7 +++---- 2 files changed, 7 insertions(+), 10 deletions(-) diff --git a/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/modifyrequest/EscapeHtmlFilterIntegrationTest.java b/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/modifyrequest/EscapeHtmlFilterIntegrationTest.java index d84ced5e1a..c813827422 100644 --- a/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/modifyrequest/EscapeHtmlFilterIntegrationTest.java +++ b/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/modifyrequest/EscapeHtmlFilterIntegrationTest.java @@ -43,11 +43,9 @@ public class EscapeHtmlFilterIntegrationTest { ObjectMapper objectMapper = new ObjectMapper(); mockMvc.perform(MockMvcRequestBuilders.post(URI.create("/save")) - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(requestBody))) - .andExpect(MockMvcResultMatchers.status() - .isCreated()) - .andExpect(MockMvcResultMatchers.content() - .json(objectMapper.writeValueAsString(expectedResponseBody))); + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(requestBody))).andExpect(MockMvcResultMatchers.status() + .isCreated()).andExpect(MockMvcResultMatchers.content() + .json(objectMapper.writeValueAsString(expectedResponseBody))); } } diff --git a/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/modifyrequest/EscapeHtmlInterceptorIntegrationTest.java b/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/modifyrequest/EscapeHtmlInterceptorIntegrationTest.java index 06aff5db3b..9afc7f7e5a 100644 --- a/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/modifyrequest/EscapeHtmlInterceptorIntegrationTest.java +++ b/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/modifyrequest/EscapeHtmlInterceptorIntegrationTest.java @@ -39,9 +39,8 @@ public class EscapeHtmlInterceptorIntegrationTest { ObjectMapper objectMapper = new ObjectMapper(); mockMvc.perform(MockMvcRequestBuilders.post(URI.create("/save")) - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(requestBody))) - .andExpect(MockMvcResultMatchers.status() - .is4xxClientError()); + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(requestBody))).andExpect(MockMvcResultMatchers.status() + .is4xxClientError()); } } From 367e9e6c2a0c332b774320bef8ee8818a3fce200 Mon Sep 17 00:00:00 2001 From: Geoffrey De Smet Date: Mon, 27 Nov 2023 08:45:03 +0100 Subject: [PATCH 134/228] Assert the solution --- .../ShiftScheduleConstraintProviderUnitTest.java | 2 +- .../timefoldsolver/ShiftScheduleSolverUnitTest.java | 12 +++++++++--- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleConstraintProviderUnitTest.java b/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleConstraintProviderUnitTest.java index 3f68ef701e..fbe6ebccaf 100644 --- a/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleConstraintProviderUnitTest.java +++ b/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleConstraintProviderUnitTest.java @@ -21,7 +21,7 @@ class ShiftScheduleConstraintProviderUnitTest { constraintVerifier.verifyThat(ShiftScheduleConstraintProvider::atMostOneShiftPerDay) .given(ann, new Shift(MONDAY.atTime(6, 0), MONDAY.atTime(14, 0), null, ann), new Shift(MONDAY.atTime(14, 0), MONDAY.atTime(22, 0), null, ann)) // Penalizes by 2 because both {shiftA, shiftB} and {shiftB, shiftA} match. - // To avoid that, use forEachUniquePair() in the constraint instead. + // To avoid that, use forEachUniquePair() in the constraint instead of forEach().join() in the implementation. .penalizesBy(2); } diff --git a/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleSolverUnitTest.java b/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleSolverUnitTest.java index 45a84b40da..8b57fb42b6 100644 --- a/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleSolverUnitTest.java +++ b/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleSolverUnitTest.java @@ -1,5 +1,7 @@ package com.baeldung.timefoldsolver; +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; + import java.time.Duration; import java.time.LocalDate; import java.util.List; @@ -23,13 +25,17 @@ public class ShiftScheduleSolverUnitTest { SolverFactory solverFactory = SolverFactory.create(new SolverConfig().withSolutionClass(ShiftSchedule.class) .withEntityClasses(Shift.class) .withConstraintProviderClass(ShiftScheduleConstraintProvider.class) - // The solver runs only for 2 seconds on this tiny dataset. - // It's recommended to run for at least 5 minutes ("5m") on large datasets. - .withTerminationSpentLimit(Duration.ofSeconds(2))); + // For this dataset, we know the optimal score in advance (which is normally not the case). + // So we can use .withBestScoreLimit() instead of .withTerminationSpentLimit(). + .withTerminationConfig(new TerminationConfig().withBestScoreLimit("0hard/0soft"))); Solver solver = solverFactory.buildSolver(); ShiftSchedule problem = loadProblem(); ShiftSchedule solution = solver.solve(problem); + assertThat(solution.getShifts().size()).isNotZero(); + for (Shift shift : solution.getShifts()) { + assertThat(shift.getEmployee()).isNotNull(); + } printSolution(solution); } From a0b5fb344309cd0a23b05ab119f4b9ffb937811d Mon Sep 17 00:00:00 2001 From: panos-kakos <102670093+panos-kakos@users.noreply.github.com> Date: Mon, 27 Nov 2023 11:14:38 +0200 Subject: [PATCH 135/228] [JAVA-27545] Upgraded spring-jinq to spring-boot 3 (#15300) --- spring-jinq/pom.xml | 12 +++++++++--- .../jinq/config/JinqProviderConfiguration.java | 2 +- .../com/baeldung/spring/jinq/entities/Car.java | 16 +++++++++------- .../spring/jinq/entities/Manufacturer.java | 11 +++++------ .../repositories/BaseJinqRepositoryImpl.java | 4 ++-- .../java/com/baeldung/SpringContextTest.java | 1 - 6 files changed, 26 insertions(+), 20 deletions(-) diff --git a/spring-jinq/pom.xml b/spring-jinq/pom.xml index 14ac366e74..c1dee7fa9f 100644 --- a/spring-jinq/pom.xml +++ b/spring-jinq/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../parent-boot-2 + ../parent-boot-3 @@ -35,6 +35,11 @@ org.springframework spring-orm + + org.hibernate.orm + hibernate-core + ${hibernate-core.version} + org.springframework.boot @@ -58,7 +63,8 @@ - 1.8.29 + 2.0.1 + 6.4.0.Final \ No newline at end of file diff --git a/spring-jinq/src/main/java/com/baeldung/spring/jinq/config/JinqProviderConfiguration.java b/spring-jinq/src/main/java/com/baeldung/spring/jinq/config/JinqProviderConfiguration.java index 6d921045b7..01e16cf0f7 100644 --- a/spring-jinq/src/main/java/com/baeldung/spring/jinq/config/JinqProviderConfiguration.java +++ b/spring-jinq/src/main/java/com/baeldung/spring/jinq/config/JinqProviderConfiguration.java @@ -1,6 +1,6 @@ package com.baeldung.spring.jinq.config; -import javax.persistence.EntityManagerFactory; +import jakarta.persistence.EntityManagerFactory; import org.jinq.jpa.JinqJPAStreamProvider; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-jinq/src/main/java/com/baeldung/spring/jinq/entities/Car.java b/spring-jinq/src/main/java/com/baeldung/spring/jinq/entities/Car.java index 263e6c7622..a0b9620629 100644 --- a/spring-jinq/src/main/java/com/baeldung/spring/jinq/entities/Car.java +++ b/spring-jinq/src/main/java/com/baeldung/spring/jinq/entities/Car.java @@ -1,19 +1,23 @@ package com.baeldung.spring.jinq.entities; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.OneToOne; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; + + @Entity(name = "CAR") public class Car { + @Id private String model; private String description; private int year; private String engine; + @ManyToOne + @JoinColumn(name = "name") private Manufacturer manufacturer; - @Id public String getModel() { return model; } @@ -46,8 +50,6 @@ public class Car { this.engine = engine; } - @OneToOne - @JoinColumn(name = "name") public Manufacturer getManufacturer() { return manufacturer; } diff --git a/spring-jinq/src/main/java/com/baeldung/spring/jinq/entities/Manufacturer.java b/spring-jinq/src/main/java/com/baeldung/spring/jinq/entities/Manufacturer.java index f6e5fd23de..0021e45658 100644 --- a/spring-jinq/src/main/java/com/baeldung/spring/jinq/entities/Manufacturer.java +++ b/spring-jinq/src/main/java/com/baeldung/spring/jinq/entities/Manufacturer.java @@ -2,18 +2,19 @@ package com.baeldung.spring.jinq.entities; import java.util.List; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.OneToMany; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.OneToMany; @Entity(name = "MANUFACTURER") public class Manufacturer { + @Id private String name; private String city; + @OneToMany(mappedBy = "model") private List cars; - @Id public String getName() { return name; } @@ -30,7 +31,6 @@ public class Manufacturer { this.city = city; } - @OneToMany(mappedBy = "model") public List getCars() { return cars; } @@ -38,5 +38,4 @@ public class Manufacturer { public void setCars(List cars) { this.cars = cars; } - } diff --git a/spring-jinq/src/main/java/com/baeldung/spring/jinq/repositories/BaseJinqRepositoryImpl.java b/spring-jinq/src/main/java/com/baeldung/spring/jinq/repositories/BaseJinqRepositoryImpl.java index 42b81ecc59..e85231f537 100644 --- a/spring-jinq/src/main/java/com/baeldung/spring/jinq/repositories/BaseJinqRepositoryImpl.java +++ b/spring-jinq/src/main/java/com/baeldung/spring/jinq/repositories/BaseJinqRepositoryImpl.java @@ -1,7 +1,7 @@ package com.baeldung.spring.jinq.repositories; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceContext; import org.jinq.jpa.JPAJinqStream; import org.jinq.jpa.JinqJPAStreamProvider; diff --git a/spring-jinq/src/test/java/com/baeldung/SpringContextTest.java b/spring-jinq/src/test/java/com/baeldung/SpringContextTest.java index 1a486d1003..7c65a831c4 100644 --- a/spring-jinq/src/test/java/com/baeldung/SpringContextTest.java +++ b/spring-jinq/src/test/java/com/baeldung/SpringContextTest.java @@ -4,7 +4,6 @@ import com.baeldung.spring.jinq.JinqApplication; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; -import com.baeldung.spring.jinq.JinqApplication; @SpringBootTest(classes = JinqApplication.class) public class SpringContextTest { From 8548b42b8483a9be917303c72d680da7730825f7 Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Mon, 27 Nov 2023 01:40:35 -0800 Subject: [PATCH 136/228] JAVA-27792 Move atomikos module to persistence-modules (#15301) --- {atomikos => persistence-modules/atomikos}/README.md | 0 {atomikos => persistence-modules/atomikos}/pom.xml | 2 +- .../src/main/java/com/baeldung/atomikos/direct/Application.java | 0 .../src/main/java/com/baeldung/atomikos/spring/Application.java | 0 .../main/java/com/baeldung/atomikos/spring/config/Config.java | 0 .../main/java/com/baeldung/atomikos/spring/jpa/Application.java | 0 .../java/com/baeldung/atomikos/spring/jpa/config/Config.java | 0 .../com/baeldung/atomikos/spring/jpa/inventory/Inventory.java | 0 .../baeldung/atomikos/spring/jpa/inventory/InventoryConfig.java | 0 .../atomikos/spring/jpa/inventory/InventoryRepository.java | 0 .../main/java/com/baeldung/atomikos/spring/jpa/order/Order.java | 0 .../com/baeldung/atomikos/spring/jpa/order/OrderConfig.java | 0 .../com/baeldung/atomikos/spring/jpa/order/OrderRepository.java | 0 .../atomikos}/src/main/resources/logback.xml | 0 .../atomikos}/src/main/resources/schema.sql | 0 .../atomikos}/src/main/resources/transactions.properties | 0 .../java/com/baeldung/atomikos/direct/ApplicationUnitTest.java | 0 .../java/com/baeldung/atomikos/spring/ApplicationUnitTest.java | 0 .../com/baeldung/atomikos/spring/jpa/ApplicationUnitTest.java | 0 .../atomikos}/src/test/resources/logback.xml | 0 .../atomikos}/src/test/resources/transactions.properties | 0 persistence-modules/pom.xml | 1 + pom.xml | 2 -- 23 files changed, 2 insertions(+), 3 deletions(-) rename {atomikos => persistence-modules/atomikos}/README.md (100%) rename {atomikos => persistence-modules/atomikos}/pom.xml (98%) rename {atomikos => persistence-modules/atomikos}/src/main/java/com/baeldung/atomikos/direct/Application.java (100%) rename {atomikos => persistence-modules/atomikos}/src/main/java/com/baeldung/atomikos/spring/Application.java (100%) rename {atomikos => persistence-modules/atomikos}/src/main/java/com/baeldung/atomikos/spring/config/Config.java (100%) rename {atomikos => persistence-modules/atomikos}/src/main/java/com/baeldung/atomikos/spring/jpa/Application.java (100%) rename {atomikos => persistence-modules/atomikos}/src/main/java/com/baeldung/atomikos/spring/jpa/config/Config.java (100%) rename {atomikos => persistence-modules/atomikos}/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/Inventory.java (100%) rename {atomikos => persistence-modules/atomikos}/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/InventoryConfig.java (100%) rename {atomikos => persistence-modules/atomikos}/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/InventoryRepository.java (100%) rename {atomikos => persistence-modules/atomikos}/src/main/java/com/baeldung/atomikos/spring/jpa/order/Order.java (100%) rename {atomikos => persistence-modules/atomikos}/src/main/java/com/baeldung/atomikos/spring/jpa/order/OrderConfig.java (100%) rename {atomikos => persistence-modules/atomikos}/src/main/java/com/baeldung/atomikos/spring/jpa/order/OrderRepository.java (100%) rename {atomikos => persistence-modules/atomikos}/src/main/resources/logback.xml (100%) rename {atomikos => persistence-modules/atomikos}/src/main/resources/schema.sql (100%) rename {atomikos => persistence-modules/atomikos}/src/main/resources/transactions.properties (100%) rename {atomikos => persistence-modules/atomikos}/src/test/java/com/baeldung/atomikos/direct/ApplicationUnitTest.java (100%) rename {atomikos => persistence-modules/atomikos}/src/test/java/com/baeldung/atomikos/spring/ApplicationUnitTest.java (100%) rename {atomikos => persistence-modules/atomikos}/src/test/java/com/baeldung/atomikos/spring/jpa/ApplicationUnitTest.java (100%) rename {atomikos => persistence-modules/atomikos}/src/test/resources/logback.xml (100%) rename {atomikos => persistence-modules/atomikos}/src/test/resources/transactions.properties (100%) diff --git a/atomikos/README.md b/persistence-modules/atomikos/README.md similarity index 100% rename from atomikos/README.md rename to persistence-modules/atomikos/README.md diff --git a/atomikos/pom.xml b/persistence-modules/atomikos/pom.xml similarity index 98% rename from atomikos/pom.xml rename to persistence-modules/atomikos/pom.xml index 2cbc106268..c1748f7dac 100644 --- a/atomikos/pom.xml +++ b/persistence-modules/atomikos/pom.xml @@ -8,7 +8,7 @@ com.baeldung - parent-modules + persistence-modules 1.0.0-SNAPSHOT diff --git a/atomikos/src/main/java/com/baeldung/atomikos/direct/Application.java b/persistence-modules/atomikos/src/main/java/com/baeldung/atomikos/direct/Application.java similarity index 100% rename from atomikos/src/main/java/com/baeldung/atomikos/direct/Application.java rename to persistence-modules/atomikos/src/main/java/com/baeldung/atomikos/direct/Application.java diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/Application.java b/persistence-modules/atomikos/src/main/java/com/baeldung/atomikos/spring/Application.java similarity index 100% rename from atomikos/src/main/java/com/baeldung/atomikos/spring/Application.java rename to persistence-modules/atomikos/src/main/java/com/baeldung/atomikos/spring/Application.java diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/config/Config.java b/persistence-modules/atomikos/src/main/java/com/baeldung/atomikos/spring/config/Config.java similarity index 100% rename from atomikos/src/main/java/com/baeldung/atomikos/spring/config/Config.java rename to persistence-modules/atomikos/src/main/java/com/baeldung/atomikos/spring/config/Config.java diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/Application.java b/persistence-modules/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/Application.java similarity index 100% rename from atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/Application.java rename to persistence-modules/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/Application.java diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/config/Config.java b/persistence-modules/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/config/Config.java similarity index 100% rename from atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/config/Config.java rename to persistence-modules/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/config/Config.java diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/Inventory.java b/persistence-modules/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/Inventory.java similarity index 100% rename from atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/Inventory.java rename to persistence-modules/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/Inventory.java diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/InventoryConfig.java b/persistence-modules/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/InventoryConfig.java similarity index 100% rename from atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/InventoryConfig.java rename to persistence-modules/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/InventoryConfig.java diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/InventoryRepository.java b/persistence-modules/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/InventoryRepository.java similarity index 100% rename from atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/InventoryRepository.java rename to persistence-modules/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/InventoryRepository.java diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/Order.java b/persistence-modules/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/Order.java similarity index 100% rename from atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/Order.java rename to persistence-modules/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/Order.java diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/OrderConfig.java b/persistence-modules/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/OrderConfig.java similarity index 100% rename from atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/OrderConfig.java rename to persistence-modules/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/OrderConfig.java diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/OrderRepository.java b/persistence-modules/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/OrderRepository.java similarity index 100% rename from atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/OrderRepository.java rename to persistence-modules/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/OrderRepository.java diff --git a/atomikos/src/main/resources/logback.xml b/persistence-modules/atomikos/src/main/resources/logback.xml similarity index 100% rename from atomikos/src/main/resources/logback.xml rename to persistence-modules/atomikos/src/main/resources/logback.xml diff --git a/atomikos/src/main/resources/schema.sql b/persistence-modules/atomikos/src/main/resources/schema.sql similarity index 100% rename from atomikos/src/main/resources/schema.sql rename to persistence-modules/atomikos/src/main/resources/schema.sql diff --git a/atomikos/src/main/resources/transactions.properties b/persistence-modules/atomikos/src/main/resources/transactions.properties similarity index 100% rename from atomikos/src/main/resources/transactions.properties rename to persistence-modules/atomikos/src/main/resources/transactions.properties diff --git a/atomikos/src/test/java/com/baeldung/atomikos/direct/ApplicationUnitTest.java b/persistence-modules/atomikos/src/test/java/com/baeldung/atomikos/direct/ApplicationUnitTest.java similarity index 100% rename from atomikos/src/test/java/com/baeldung/atomikos/direct/ApplicationUnitTest.java rename to persistence-modules/atomikos/src/test/java/com/baeldung/atomikos/direct/ApplicationUnitTest.java diff --git a/atomikos/src/test/java/com/baeldung/atomikos/spring/ApplicationUnitTest.java b/persistence-modules/atomikos/src/test/java/com/baeldung/atomikos/spring/ApplicationUnitTest.java similarity index 100% rename from atomikos/src/test/java/com/baeldung/atomikos/spring/ApplicationUnitTest.java rename to persistence-modules/atomikos/src/test/java/com/baeldung/atomikos/spring/ApplicationUnitTest.java diff --git a/atomikos/src/test/java/com/baeldung/atomikos/spring/jpa/ApplicationUnitTest.java b/persistence-modules/atomikos/src/test/java/com/baeldung/atomikos/spring/jpa/ApplicationUnitTest.java similarity index 100% rename from atomikos/src/test/java/com/baeldung/atomikos/spring/jpa/ApplicationUnitTest.java rename to persistence-modules/atomikos/src/test/java/com/baeldung/atomikos/spring/jpa/ApplicationUnitTest.java diff --git a/atomikos/src/test/resources/logback.xml b/persistence-modules/atomikos/src/test/resources/logback.xml similarity index 100% rename from atomikos/src/test/resources/logback.xml rename to persistence-modules/atomikos/src/test/resources/logback.xml diff --git a/atomikos/src/test/resources/transactions.properties b/persistence-modules/atomikos/src/test/resources/transactions.properties similarity index 100% rename from atomikos/src/test/resources/transactions.properties rename to persistence-modules/atomikos/src/test/resources/transactions.properties diff --git a/persistence-modules/pom.xml b/persistence-modules/pom.xml index 6823b460b2..d9ee7e358c 100644 --- a/persistence-modules/pom.xml +++ b/persistence-modules/pom.xml @@ -18,6 +18,7 @@ apache-bookkeeper apache-cayenne apache-derby + atomikos blaze-persistence core-java-persistence core-java-persistence-2 diff --git a/pom.xml b/pom.xml index 3452ae81ee..c6abc0d4d8 100644 --- a/pom.xml +++ b/pom.xml @@ -710,7 +710,6 @@ apache-velocity asciidoctor asm - atomikos atomix aws-modules azure @@ -955,7 +954,6 @@ apache-velocity asciidoctor asm - atomikos atomix aws-modules azure From 2e6b17b85336d0338afb8426ae53188812407edc Mon Sep 17 00:00:00 2001 From: gaepi Date: Mon, 27 Nov 2023 11:31:41 +0100 Subject: [PATCH 137/228] JAVA-27656 | spring-boot-modules fix --- .../baeldung/caffeine/SecurityConfiguration.java | 13 +++++++------ .../boot/management/logging/SecurityConfig.java | 14 ++++++++------ 2 files changed, 15 insertions(+), 12 deletions(-) diff --git a/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/caffeine/SecurityConfiguration.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/caffeine/SecurityConfiguration.java index 7f3ad7988f..e63726c926 100644 --- a/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/caffeine/SecurityConfiguration.java +++ b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/caffeine/SecurityConfiguration.java @@ -1,9 +1,10 @@ package com.baeldung.caffeine; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.web.SecurityFilterChain; /** * Because the POM imports Spring Security, we need a simple security @@ -11,14 +12,14 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur */ @Configuration @EnableWebSecurity -public class SecurityConfiguration extends WebSecurityConfigurerAdapter { +public class SecurityConfiguration { - @Override - protected void configure(HttpSecurity http) throws Exception { + @Bean + public SecurityFilterChain securityFilter(HttpSecurity http) throws Exception { http.csrf().disable(); - http.authorizeRequests() + return http.authorizeRequests() .antMatchers("/**") - .permitAll(); + .permitAll().and().build(); } } diff --git a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/logging/SecurityConfig.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/logging/SecurityConfig.java index 45cc1ebb33..6870f4e6bb 100644 --- a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/logging/SecurityConfig.java +++ b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/logging/SecurityConfig.java @@ -1,14 +1,16 @@ package com.baeldung.spring.boot.management.logging; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.web.SecurityFilterChain; @Configuration -public class SecurityConfig extends WebSecurityConfigurerAdapter { - @Override - protected void configure(HttpSecurity http) throws Exception { - http.csrf() - .ignoringAntMatchers("/actuator/**"); +public class SecurityConfig { + @Bean + public SecurityFilterChain securityFilter(HttpSecurity http) throws Exception { + return http.csrf() + .ignoringAntMatchers("/actuator/**").and() + .build(); } } From 8dd4651db582818e56bcd2c812ee76ef8996db47 Mon Sep 17 00:00:00 2001 From: gaepi Date: Mon, 27 Nov 2023 11:48:10 +0100 Subject: [PATCH 138/228] JAVA-27656 | removing WebSecurityConfigurerAdapter from spring-web-modules/spring-thymeleaf --- .../thymeleaf/config/WebMVCSecurity.java | 41 ++++++++----------- 1 file changed, 18 insertions(+), 23 deletions(-) diff --git a/spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCSecurity.java b/spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCSecurity.java index ea51ca3cd9..074cc20be1 100644 --- a/spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCSecurity.java +++ b/spring-web-modules/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCSecurity.java @@ -2,42 +2,37 @@ package com.baeldung.thymeleaf.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.security.authentication.AuthenticationManager; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.provisioning.InMemoryUserDetailsManager; +import org.springframework.security.web.SecurityFilterChain; @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true) -public class WebMVCSecurity extends WebSecurityConfigurerAdapter { +public class WebMVCSecurity { @Bean - @Override - public AuthenticationManager authenticationManagerBean() throws Exception { - return super.authenticationManagerBean(); + public InMemoryUserDetailsManager userDetailsService() { + UserDetails user = User.withUsername("user1") + .password("{noop}user1Pass") + .authorities("USER") + .build(); + return new InMemoryUserDetailsManager(user); } - public WebMVCSecurity() { - super(); + @Bean + public WebSecurityCustomizer webSecurityCustomizer() { + return (web) -> web.ignoring().antMatchers("/resources/**"); } - @Override - protected void configure(final AuthenticationManagerBuilder auth) throws Exception { - auth.inMemoryAuthentication().withUser("user1").password("{noop}user1Pass").authorities("ROLE_USER"); - } - - @Override - public void configure(final WebSecurity web) throws Exception { - web.ignoring().antMatchers("/resources/**"); - } - - @Override - protected void configure(final HttpSecurity http) throws Exception { - http.authorizeRequests().anyRequest().authenticated().and().httpBasic(); + @Bean + public SecurityFilterChain filterChain(final HttpSecurity http) throws Exception { + return http.authorizeRequests().anyRequest().authenticated().and().httpBasic().and().build(); } } From 4151b9ce706ae13764d445df9c28d28f8488ecb3 Mon Sep 17 00:00:00 2001 From: gaepi Date: Mon, 27 Nov 2023 12:00:26 +0100 Subject: [PATCH 139/228] JAVA-27656 | removing WebSecurityConfigurerAdapter --- .../OAuth2WebSecurityConfigurerAdapter.java | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/oauthfeign/OAuth2WebSecurityConfigurerAdapter.java b/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/oauthfeign/OAuth2WebSecurityConfigurerAdapter.java index af60c3849b..6efacc03b1 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/oauthfeign/OAuth2WebSecurityConfigurerAdapter.java +++ b/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/oauthfeign/OAuth2WebSecurityConfigurerAdapter.java @@ -1,19 +1,23 @@ package com.baeldung.cloud.openfeign.oauthfeign; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.web.SecurityFilterChain; @Configuration -public class OAuth2WebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { +public class OAuth2WebSecurityConfigurerAdapter { - @Override - protected void configure(HttpSecurity http) throws Exception { + @Bean + public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .csrf() .disable() .oauth2Client(); + http .authorizeRequests().anyRequest().permitAll(); + + return http.build(); } } From cf74ed5628699d725c5994604a60c33b03d64d8f Mon Sep 17 00:00:00 2001 From: panos-kakos Date: Mon, 27 Nov 2023 13:15:33 +0200 Subject: [PATCH 140/228] [JAVA-27818] --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index c6abc0d4d8..f5aedd091e 100644 --- a/pom.xml +++ b/pom.xml @@ -701,7 +701,7 @@ apache-kafka apache-libraries-2 apache-libraries - apache-olingo + apache-olingo apache-poi-2 apache-poi-3 apache-poi @@ -945,7 +945,7 @@ apache-kafka apache-libraries-2 apache-libraries - apache-olingo + apache-olingo apache-poi-2 apache-poi-3 apache-poi From e78928e37646d2aef20118dc2c27e42cc89ea4d1 Mon Sep 17 00:00:00 2001 From: DiegoMarti2 <150871541+DiegoMarti2@users.noreply.github.com> Date: Mon, 27 Nov 2023 14:15:25 +0200 Subject: [PATCH 141/228] Update JsonNodeToJsonObjectUnitTest.java --- .../jsonnodetojsonobject/JsonNodeToJsonObjectUnitTest.java | 1 + 1 file changed, 1 insertion(+) diff --git a/json-modules/json-conversion/src/test/java/com/baeldung/jsonnodetojsonobject/JsonNodeToJsonObjectUnitTest.java b/json-modules/json-conversion/src/test/java/com/baeldung/jsonnodetojsonobject/JsonNodeToJsonObjectUnitTest.java index e5a12869ea..38d097e5b8 100644 --- a/json-modules/json-conversion/src/test/java/com/baeldung/jsonnodetojsonobject/JsonNodeToJsonObjectUnitTest.java +++ b/json-modules/json-conversion/src/test/java/com/baeldung/jsonnodetojsonobject/JsonNodeToJsonObjectUnitTest.java @@ -10,6 +10,7 @@ import org.junit.Test; import static org.junit.Assert.*; public class JsonNodeToJsonObjectUnitTest { + public static String jsonString = "{\"name\": \"John\", \"gender\": \"male\", \"company\": \"Baeldung\", \"isEmployee\": true, \"age\": 30}"; @Test From 43fd0973ddeec97155f6c787336d05e05d0f8144 Mon Sep 17 00:00:00 2001 From: parthiv39731 <70740707+parthiv39731@users.noreply.github.com> Date: Mon, 27 Nov 2023 23:15:13 +0530 Subject: [PATCH 142/228] BAEL-7259 --- .../baledung/harperdb/HarperDBLiveTest.java | 349 +++++++++--------- 1 file changed, 177 insertions(+), 172 deletions(-) diff --git a/persistence-modules/java-harperdb/src/test/java/com/baledung/harperdb/HarperDBLiveTest.java b/persistence-modules/java-harperdb/src/test/java/com/baledung/harperdb/HarperDBLiveTest.java index 42ef04dadf..1cd377dc6d 100644 --- a/persistence-modules/java-harperdb/src/test/java/com/baledung/harperdb/HarperDBLiveTest.java +++ b/persistence-modules/java-harperdb/src/test/java/com/baledung/harperdb/HarperDBLiveTest.java @@ -12,6 +12,7 @@ import org.testcontainers.containers.GenericContainer; import java.io.IOException; import java.net.URISyntaxException; import java.sql.*; +import java.util.Arrays; import java.util.Properties; import static org.junit.jupiter.api.Assertions.*; @@ -63,18 +64,22 @@ public class HarperDBLiveTest { } private static void insertSubjectRecords() throws IOException { - String records = "[" + "{\"id\":1, \"name\":\"English\"}," + "{\"id\":2, \"name\":\"Maths\"}," + "{\"id\":3, \"name\":\"Science\"}" + "]"; + String records = "[" + + "{\"id\":1, \"name\":\"English\"}," + + "{\"id\":2, \"name\":\"Maths\"}," + + "{\"id\":3, \"name\":\"Science\"}" + + "]"; harperDbApiService.insertRecords("Demo", "Subject", records); } private static void insertTeacherRecords() throws IOException { - String records = "[" + "{\"id\":1, \"name\":\"Parthiv Pradhan\", \"joining_date\":\"04-05-2000\"}," + - "{\"id\":2, \"name\":\"David Martinez\", \"joining_date\":\"20-10-2005\"}," + - "{\"id\":3, \"name\":\"Liam Williams\", \"joining_date\":\"04-06-1997\"}," + + String records = "[" + "{\"id\":1, \"name\":\"James Cameron\", \"joining_date\":\"04-05-2000\"}," + + "{\"id\":2, \"name\":\"Joe Biden\", \"joining_date\":\"20-10-2005\"}," + + "{\"id\":3, \"name\":\"Jessie Williams\", \"joining_date\":\"04-06-1997\"}," + "{\"id\":4, \"name\":\"Robin Williams\", \"joining_date\":\"01-01-2020\"}," + - "{\"id\":5, \"name\":\"Eric Martin\", \"joining_date\":\"04-05-2022\"}," + - "{\"id\":6, \"name\":\"Sajjan Nagendra\", \"joining_date\":\"02-02-1999\"}" + "]"; + "{\"id\":5, \"name\":\"Eric Johnson\", \"joining_date\":\"04-05-2022\"}," + + "{\"id\":6, \"name\":\"Raghu Yadav\", \"joining_date\":\"02-02-1999\"}" + "]"; harperDbApiService.insertRecords("Demo", "Teacher", records); } @@ -138,175 +143,13 @@ public class HarperDBLiveTest { }); } - private static Connection getConnection() throws SQLException { - String URL = "jdbc:harperdb:Server=127.0.0.1:" + port + ";User=admin;Password=password;"; - return DriverManager.getConnection(URL); - } - - @Test - void givenStatement_whenFetchRecord_thenSuccess() throws SQLException { - final String SQL_QUERY = "select id, name, grade from Demo.student"; - - try (Connection connection = getConnection()) { - Statement statement = connection.createStatement(); - ResultSet resultSet = statement.executeQuery(SQL_QUERY); - while (resultSet.next()) { - int id = resultSet.getInt("id"); - String name = resultSet.getString("name"); - int grade = resultSet.getInt("grade"); - assertNotNull(Integer.valueOf(id)); - logger.info("Student id:" + id + " Student Name:" + name + " grade:" + grade); - } - } - } - - @Test - void givenStatement_whenInsertRecord_thenSuccess() throws SQLException { - final String INSERT_SQL = "insert into Demo.student(id, name, grade) values (10, 'Barak', 3)"; - - try (Connection connection = getConnection()) { - Statement statement = connection.createStatement(); - assertDoesNotThrow(() -> statement.execute(INSERT_SQL)); - } - } - - @Test - void givenStatement_whenInsertRecordInTableWithoutAttributes_thenSuccess() throws SQLException { - final String INSERT_SQL = - "insert into Demo.teacher(id, name, joining_date) " + "values (7, 'David Sirocco', '04-05-2004'), (8, 'Ali Azmat', '04-10-2000')"; - final String QUERY_SQL = "select name, joining_date from Demo.teacher where name = ?"; - - try (Connection connection = getConnection()) { - Statement statement = connection.createStatement(); - assertDoesNotThrow(() -> statement.execute(INSERT_SQL)); - PreparedStatement preparedStatement = connection.prepareStatement(QUERY_SQL); - preparedStatement.setString(1, "David Sirocco"); - ResultSet resultSet = preparedStatement.executeQuery(); - while (resultSet.next()) { - String teacherName = resultSet.getString("name"); - String joinDate = resultSet.getString("joining_date"); - assertEquals("David Sirocco", teacherName); - assertEquals("04-05-2004", joinDate); - logger.info("name:" + teacherName + " joining date:" + joinDate); - } - } - } - - @Test - void givenStatement_whenUpdateRecord_thenSuccess() throws SQLException { - final String UPDATE_SQL = "update Demo.student set grade = 4 where id = 5"; - - try (Connection connection = getConnection()) { - Statement statement = connection.createStatement(); - assertDoesNotThrow(() -> statement.execute(UPDATE_SQL)); - assertEquals(1, statement.getUpdateCount()); - } - } - - @Test - void givenStatement_whenDeleteRecord_thenSuccess() throws SQLException { - final String DELETE_SQL = "delete from Demo.student where id = 3"; - - try (Connection connection = getConnection()) { - Statement statement = connection.createStatement(); - assertDoesNotThrow(() -> statement.execute(DELETE_SQL)); - assertEquals(1, statement.getUpdateCount()); - } - } - - @Test - void givenPreparedStatement_whenFetchRecord_thenSuccess() throws SQLException { - final String SQL_QUERY = "select id, name, grade from Demo.student where name = ? and grade = ?"; - - try (Connection connection = getConnection()) { - PreparedStatement preparedStatement = connection.prepareStatement(SQL_QUERY); - preparedStatement.setString(1, "Robin"); - preparedStatement.setInt(2, 4); - ResultSet resultSet = preparedStatement.executeQuery(); - while (resultSet.next()) { - int id = resultSet.getInt("id"); - String name = resultSet.getString("name"); - int grade = resultSet.getInt("grade"); - assertNotNull(Integer.valueOf(id)); - assertEquals("Robin", name); - logger.info("Student id:" + id + " Student Name:" + name + " grade:" + grade); - } - } - } - - @Test - void givenPreparedStatement_whenDeleteRecord_thenSuccess() throws SQLException { - final String DELETE_SQL = "delete from Demo.student where name = ?"; - - try (Connection connection = getConnection()) { - PreparedStatement preparedStatement = connection.prepareStatement(DELETE_SQL); - preparedStatement.setString(1, "James"); - assertDoesNotThrow(() -> preparedStatement.execute()); - assertEquals(1, preparedStatement.getUpdateCount()); - } - } - - @Test - void givenPreparedStatement_whenUpdateRecord_thenSuccess() throws SQLException { - final String UPDATE_SQL = "update Demo.student set grade = ? where id = ? and name = ?"; - - try (Connection connection = getConnection()) { - PreparedStatement preparedStatement = connection.prepareStatement(UPDATE_SQL); - preparedStatement.setInt(1, 5); - preparedStatement.setInt(2, 1); - preparedStatement.setString(3, "John"); - assertDoesNotThrow(() -> preparedStatement.execute()); - assertEquals(1, preparedStatement.getUpdateCount()); - } - } - - //@Test - void whenAddtoBatch_thenExecuteBatchIsSuccess() throws SQLException { - final String INSERT_SQL = "insert into Demo.teacher(id, name, joining_date, subject_id)" + "values(?, ?, ?, ?)"; - - try (Connection connection = getConnection()) { - PreparedStatement preparedStatement = connection.prepareStatement(INSERT_SQL); - preparedStatement.setInt(1, 9); - preparedStatement.setString(2, "Bret Lee"); - preparedStatement.setString(3, "07-08-2002"); - preparedStatement.setString(4, "[1, 3]"); - preparedStatement.addBatch(); - - preparedStatement.setInt(1, 10); - preparedStatement.setString(2, "Sarah Glimmer"); - preparedStatement.setString(3, "07-08-1997"); - preparedStatement.setString(4, "[1, 2]"); - - preparedStatement.addBatch(); - - assertDoesNotThrow(() -> preparedStatement.executeBatch()); - } - } - - @Test - void whenExecuteJoinQuery_thenResultSuccess() throws SQLException { - final String JOIN_QUERY = - "SELECT t.name as teacher_name, s.name as subject_name " + "from Demo.teacher AS t INNER JOIN Demo.subject AS s ON t.subject_id = s.id"; - - try (Connection connection = getConnection()) { - Statement statement = connection.createStatement(); - - ResultSet resultSet = statement.executeQuery(JOIN_QUERY); - while (resultSet.next()) { - logger.info("Teacher Name:" + resultSet.getString("teacher_name") + " Subject Name:" + resultSet.getString("subject_name")); - } - - } - - } - @Test void whenExecuteStoredToCreateTable_thenSuccess() throws SQLException { - final String CREATE_TABLE_SQL = "CreateTable"; + final String CREATE_TABLE_PROC = "CreateTable"; try (Connection connection = getConnection()) { - CallableStatement callableStatement = connection.prepareCall(CREATE_TABLE_SQL); + CallableStatement callableStatement = connection.prepareCall(CREATE_TABLE_PROC); - callableStatement.setString("SchemaName", "prod"); //schema gets created too + callableStatement.setString("SchemaName", "prod"); callableStatement.setString("TableName", "subject"); callableStatement.setString("PrimaryKey", "id"); Boolean result = callableStatement.execute(); @@ -316,8 +159,170 @@ public class HarperDBLiveTest { while (resultSet.next()) { String tableCreated = resultSet.getString("Success"); assertEquals("true", tableCreated); - logger.info("result of the callable execute:" + tableCreated); + logger.info("Table Created Successfully"); } } } + + @Test + void givenStatement_whenInsertRecord_thenSuccess() throws SQLException { + final String INSERT_SQL = "insert into Demo.Subject(id, name) values " + + "(4, 'Social Studies')," + + "(5, 'Geography')"; + + try (Connection connection = getConnection()) { + Statement statement = connection.createStatement(); + assertDoesNotThrow(() -> statement.execute(INSERT_SQL)); + assertEquals(2, statement.getUpdateCount()); + } + } + @Test + void givenPrepareStatement_whenAddToBatch_thenSuccess() throws SQLException { + final String INSERT_SQL = "insert into Demo.Teacher(id, name, joining_date) values" + + "(?, ?, ?)"; + + try (Connection connection = getConnection()) { + PreparedStatement preparedStatement = connection.prepareStatement(INSERT_SQL); + preparedStatement.setInt(1, 7); + preparedStatement.setString(2, "Bret Lee"); + preparedStatement.setString(3, "07-08-2002"); + preparedStatement.addBatch(); + + preparedStatement.setInt(1, 8); + preparedStatement.setString(2, "Sarah Glimmer"); + preparedStatement.setString(3, "07-08-1997"); + preparedStatement.addBatch(); + + int[] recordsInserted = preparedStatement.executeBatch(); + + assertEquals(2, Arrays.stream(recordsInserted).sum()); + } + } + + + private static Connection getConnection() throws SQLException { + String URL = "jdbc:harperdb:Server=127.0.0.1:" + port + ";User=admin;Password=password;"; + return DriverManager.getConnection(URL); + } + + @Test + void givenStatement_whenFetchRecord_thenSuccess() throws SQLException { + final String SQL_QUERY = "select id, name from Demo.Subject where name = 'Maths'"; + + try (Connection connection = getConnection()) { + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery(SQL_QUERY); + while (resultSet.next()) { + int id = resultSet.getInt("id"); + String name = resultSet.getString("name"); + assertNotNull(Integer.valueOf(id)); + assertEquals("Maths", name); + logger.info("Subject id:" + id + " Subject Name:" + name); + } + } + } + + @Test + void givenPreparedStatement_whenExecuteJoinQuery_thenSuccess() throws SQLException { + final String JOIN_QUERY = "SELECT t.name as teacher_name, t.joining_date as joining_date, s.name as subject_name " + + "from Demo.Teacher_Details AS td " + + "INNER JOIN Demo.Teacher AS t ON t.id = td.teacher_id " + + "INNER JOIN Demo.Subject AS s on s.id = td.subject_id " + + "where t.name = ?"; + + try (Connection connection = getConnection()) { + PreparedStatement preparedStatement = connection.prepareStatement(JOIN_QUERY); + preparedStatement.setString(1, "Eric Johnson"); + + ResultSet resultSet = preparedStatement.executeQuery(); + while (resultSet.next()) { + String teacherName = resultSet.getString("teacher_name"); + String subjectName = resultSet.getString("subject_name"); + String joiningDate = resultSet.getString("joining_date"); + assertEquals("Eric Johnson", teacherName); + assertEquals("Maths", subjectName); + logger.info("Teacher Name:" + teacherName + " Subject Name:" + subjectName + " Joining Date:" + joiningDate); + } + } + } + @Test + void givenPreparedStatement_whenFetchRecord_thenSuccess() throws SQLException { + final String SQL_QUERY = "select id, name from Demo.Subject where name = ?"; + + try (Connection connection = getConnection()) { + PreparedStatement preparedStatement = connection.prepareStatement(SQL_QUERY); + preparedStatement.setString(1, "Maths"); + + ResultSet resultSet = preparedStatement.executeQuery(); + while (resultSet.next()) { + int id = resultSet.getInt("id"); + String name = resultSet.getString("name"); + assertNotNull(Integer.valueOf(id)); + assertEquals("Maths", name); + logger.info("Subject id:" + id + " Subject Name:" + name); + } + } + } + + + @Test + void givenStatement_whenUpdateRecord_thenSuccess() throws SQLException { + final String UPDATE_SQL = "update Demo.Teacher_Details set subject_id = 2 " + + "where teacher_id in (2, 5)"; + final String UPDATE_SQL_WITH_SUB_QUERY = "update Demo.Teacher_Details " + + "set subject_id = (select id from Demo.Subject where name = 'Maths') " + + "where teacher_id in (select id from Demo.Teacher where name in ('Joe Biden', 'Eric Johnson'))"; + + try (Connection connection = getConnection()) { + Statement statement = connection.createStatement(); + assertDoesNotThrow(() -> statement.execute(UPDATE_SQL)); + assertEquals(2, statement.getUpdateCount()); + } + + try (Connection connection = getConnection()) { + assertThrows(SQLException.class, () -> connection.createStatement().execute(UPDATE_SQL_WITH_SUB_QUERY)); + } + } + + @Test + void givenPreparedStatement_whenUpdateRecord_thenSuccess() throws SQLException { + final String UPDATE_SQL = "update Demo.Teacher_Details set subject_id = ? " + + "where teacher_id in (?, ?)"; + + try (Connection connection = getConnection()) { + PreparedStatement preparedStatement = connection.prepareStatement(UPDATE_SQL); + preparedStatement.setInt(1, 1); + //following is not supported by the HarperDB driver + //Integer[] teacherIds = {4, 5}; + //Array teacherIdArray = connection.createArrayOf(Integer.class.getTypeName(), teacherIds); + preparedStatement.setInt(2, 4); + preparedStatement.setInt(3, 5); + assertDoesNotThrow(() -> preparedStatement.execute()); + assertEquals(2, preparedStatement.getUpdateCount()); + } + } + + @Test + void givenStatement_whenDeleteRecord_thenSuccess() throws SQLException { + final String DELETE_SQL = "delete from Demo.Teacher_Details where teacher_id = 6 and subject_id = 3"; + + try (Connection connection = getConnection()) { + Statement statement = connection.createStatement(); + assertDoesNotThrow(() -> statement.execute(DELETE_SQL)); + assertEquals(1, statement.getUpdateCount()); + } + } + + @Test + void givenPreparedStatement_whenDeleteRecord_thenSuccess() throws SQLException { + final String DELETE_SQL = "delete from Demo.Teacher_Details where teacher_id = ? and subject_id = ?"; + + try (Connection connection = getConnection()) { + PreparedStatement preparedStatement = connection.prepareStatement(DELETE_SQL); + preparedStatement.setInt(1, 6); + preparedStatement.setInt(2, 2); + assertDoesNotThrow(() -> preparedStatement.execute()); + assertEquals(1, preparedStatement.getUpdateCount()); + } + } } From 6164b9c0bafd9fe7080d0429c3a1af07ea5ebf35 Mon Sep 17 00:00:00 2001 From: Sameer Date: Tue, 28 Nov 2023 03:47:00 +0530 Subject: [PATCH 143/228] string vs stringBuffer comparison (#15306) Co-authored-by: Sahil --- .../stringbuffer/ComparePerformance.java | 63 +++++++++++++++++++ .../com/baeldung/stringbuffer/HashCode.java | 24 +++++++ .../stringIterator/StringIteratorTest.java | 4 +- .../stringbuffer/ComparePerformanceTest.java | 32 ++++++++++ .../baeldung/stringbuffer/HashCodeTest.java | 24 +++++++ 5 files changed, 145 insertions(+), 2 deletions(-) create mode 100644 core-java-modules/core-java-strings/src/main/java/com/baeldung/stringbuffer/ComparePerformance.java create mode 100644 core-java-modules/core-java-strings/src/main/java/com/baeldung/stringbuffer/HashCode.java create mode 100644 core-java-modules/core-java-strings/src/test/java/com/baeldung/stringbuffer/ComparePerformanceTest.java create mode 100644 core-java-modules/core-java-strings/src/test/java/com/baeldung/stringbuffer/HashCodeTest.java diff --git a/core-java-modules/core-java-strings/src/main/java/com/baeldung/stringbuffer/ComparePerformance.java b/core-java-modules/core-java-strings/src/main/java/com/baeldung/stringbuffer/ComparePerformance.java new file mode 100644 index 0000000000..28cd2e64e9 --- /dev/null +++ b/core-java-modules/core-java-strings/src/main/java/com/baeldung/stringbuffer/ComparePerformance.java @@ -0,0 +1,63 @@ +package com.baeldung.stringbuffer; + +import java.util.concurrent.TimeUnit; + +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Measurement; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.annotations.Warmup; +import org.openjdk.jmh.runner.Runner; +import org.openjdk.jmh.runner.RunnerException; +import org.openjdk.jmh.runner.options.Options; +import org.openjdk.jmh.runner.options.OptionsBuilder; + +@BenchmarkMode(Mode.SingleShotTime) +@OutputTimeUnit(TimeUnit.MILLISECONDS) +@Measurement(batchSize = 10000, iterations = 10) +@Warmup(batchSize = 1000, iterations = 10) +@State(Scope.Thread) +public class ComparePerformance { + + String strInitial = "springframework"; + String strFinal = ""; + String replacement = "java-"; + + @Benchmark + public String benchmarkStringConcatenation() { + strFinal += strInitial; + return strFinal; + } + + @Benchmark + public StringBuffer benchmarkStringBufferConcatenation() { + StringBuffer stringBuffer = new StringBuffer(strFinal); + stringBuffer.append(strInitial); + return stringBuffer; + } + + @Benchmark + public String benchmarkStringReplacement() { + strFinal = strInitial.replaceFirst("spring", replacement); + return strFinal; + } + + @Benchmark + public StringBuffer benchmarkStringBufferReplacement() { + StringBuffer stringBuffer = new StringBuffer(strInitial); + stringBuffer.replace(0,6, replacement); + return stringBuffer; + } + + public static void main(String[] args) throws RunnerException { + Options options = new OptionsBuilder() + .include(ComparePerformance.class.getSimpleName()).threads(1) + .forks(1).shouldFailOnError(true) + .shouldDoGC(true) + .jvmArgs("-server").build(); + new Runner(options).run(); + } +} diff --git a/core-java-modules/core-java-strings/src/main/java/com/baeldung/stringbuffer/HashCode.java b/core-java-modules/core-java-strings/src/main/java/com/baeldung/stringbuffer/HashCode.java new file mode 100644 index 0000000000..65f17263a9 --- /dev/null +++ b/core-java-modules/core-java-strings/src/main/java/com/baeldung/stringbuffer/HashCode.java @@ -0,0 +1,24 @@ +package com.baeldung.stringbuffer; + +public class HashCode { + + public static long getHashCodeString(String string) { + return string.hashCode(); + } + + public static long getHashCodeSBuffer(StringBuffer strBuff) { + return strBuff.hashCode(); + } + + public static void main(String[] args) { + String str = "Spring"; + System.out.println("String HashCode pre concatenation :" + getHashCodeString(str)); + str += "Framework"; + System.out.println("String HashCode post concatenation :" + getHashCodeString(str)); + + StringBuffer sBuf = new StringBuffer("Spring"); + System.out.println("StringBuffer HashCode pre concatenation :" + getHashCodeSBuffer(sBuf)); + sBuf.append("Framework"); + System.out.println("StringBuffer HashCode post concatenation :" + getHashCodeSBuffer(sBuf)); + } +} diff --git a/core-java-modules/core-java-strings/src/test/java/com/baeldung/stringIterator/StringIteratorTest.java b/core-java-modules/core-java-strings/src/test/java/com/baeldung/stringIterator/StringIteratorTest.java index 585d65d4be..aef7f81da2 100644 --- a/core-java-modules/core-java-strings/src/test/java/com/baeldung/stringIterator/StringIteratorTest.java +++ b/core-java-modules/core-java-strings/src/test/java/com/baeldung/stringIterator/StringIteratorTest.java @@ -17,7 +17,7 @@ public class StringIteratorTest { public void whenUseJavaForLoop_thenIterate() { String input = "Hello, Baeldung!"; String expectedOutput = "Hello, Baeldung!"; - String result = StringIterator.javaForLoop(input); + String result = StringIterator.javaforLoop(input); assertEquals(expectedOutput, result); } @@ -25,7 +25,7 @@ public class StringIteratorTest { public void whenUseForEachMethod_thenIterate() { String input = "Hello, Baeldung!"; String expectedOutput = "Hello, Baeldung!"; - String result = StringIterator.java8ForEach(input); + String result = StringIterator.java8forEach(input); assertEquals(expectedOutput, result); } diff --git a/core-java-modules/core-java-strings/src/test/java/com/baeldung/stringbuffer/ComparePerformanceTest.java b/core-java-modules/core-java-strings/src/test/java/com/baeldung/stringbuffer/ComparePerformanceTest.java new file mode 100644 index 0000000000..696c4bae6b --- /dev/null +++ b/core-java-modules/core-java-strings/src/test/java/com/baeldung/stringbuffer/ComparePerformanceTest.java @@ -0,0 +1,32 @@ +package com.baeldung.stringbuffer; + +import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; + + +public class ComparePerformanceTest { + + ComparePerformance cp = new ComparePerformance(); + + @Test + public void whenStringConcatenated_thenResultAsExpected() { + assertThat(cp.benchmarkStringConcatenation()).isEqualTo("springframework"); + } + + @Test + public void whenStringBufferConcatenated_thenResultAsExpected() { + StringBuffer stringBuffer = new StringBuffer("springframework"); + assertThat(cp.benchmarkStringBufferConcatenation()).isEqualToIgnoringCase(stringBuffer); + } + + @Test + public void whenStringReplaced_thenResultAsExpected() { + assertThat(cp.benchmarkStringReplacement()).isEqualTo("java-framework"); + } + + @Test + public void whenStringBufferReplaced_thenResultAsExpected() { + StringBuffer stringBuffer = new StringBuffer("java-framework"); + assertThat(cp.benchmarkStringBufferReplacement()).isEqualToIgnoringCase(stringBuffer); + } +} diff --git a/core-java-modules/core-java-strings/src/test/java/com/baeldung/stringbuffer/HashCodeTest.java b/core-java-modules/core-java-strings/src/test/java/com/baeldung/stringbuffer/HashCodeTest.java new file mode 100644 index 0000000000..265c4e1e40 --- /dev/null +++ b/core-java-modules/core-java-strings/src/test/java/com/baeldung/stringbuffer/HashCodeTest.java @@ -0,0 +1,24 @@ +package com.baeldung.stringbuffer; + +import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; + +public class HashCodeTest { + + String str = "Spring"; + StringBuffer sBuf = new StringBuffer("Spring"); + + @Test + public void whenStringConcat_thenHashCodeChanges() { + HashCode hc = new HashCode(); + + long initialStringHashCode = hc.getHashCodeString(str); + long initialSBufHashCode = hc.getHashCodeSBuffer(sBuf); + + str += "Framework"; + sBuf.append("Framework"); + + assertThat(initialStringHashCode).isNotEqualTo(hc.getHashCodeString(str)); + assertThat(initialSBufHashCode).isEqualTo(hc.getHashCodeSBuffer(sBuf)); + } +} From 50de40daa27f61c0e5ba52d6c2d11f6e93a6c8a6 Mon Sep 17 00:00:00 2001 From: SGWebFreelancer Date: Tue, 28 Nov 2023 10:19:27 +0800 Subject: [PATCH 144/228] Unit Testing for CompletableFuture class --- .../CompletableFutureTest.java | 150 ++++++++++++++++++ 1 file changed, 150 insertions(+) create mode 100644 core-java-modules/core-java-concurrency-2/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTest.java diff --git a/core-java-modules/core-java-concurrency-2/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTest.java b/core-java-modules/core-java-concurrency-2/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTest.java new file mode 100644 index 0000000000..25e8ea4c81 --- /dev/null +++ b/core-java-modules/core-java-concurrency-2/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTest.java @@ -0,0 +1,150 @@ +package com.baeldung.concurrent.completablefuture; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executor; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.stream.Collectors; + +import org.junit.Test; + +public class CompletableFutureTest { + + @Test + public void givenAsyncTask_whenProcessingAsyncSucceed_thenReturnSuccess() throws ExecutionException, InterruptedException { + Microservice mockMicroserviceA = mock(Microservice.class); + Microservice mockMicroserviceB = mock(Microservice.class); + + when(mockMicroserviceA.retrieveAsync(any())).thenReturn(CompletableFuture.completedFuture("Hello")); + when(mockMicroserviceB.retrieveAsync(any())).thenReturn(CompletableFuture.completedFuture("World")); + + CompletableFuture resultFuture = processAsync(List.of(mockMicroserviceA, mockMicroserviceB)); + + String result = resultFuture.get(); + assertEquals("HelloWorld", result); + } + + @Test + public void givenAsyncTask_whenProcessingAsyncWithException_thenReturnException() throws ExecutionException, InterruptedException { + Microservice mockMicroserviceA = mock(Microservice.class); + Microservice mockMicroserviceB = mock(Microservice.class); + + when(mockMicroserviceA.retrieveAsync(any())).thenReturn(CompletableFuture.completedFuture("Hello")); + when(mockMicroserviceB.retrieveAsync(any())).thenReturn(CompletableFuture.failedFuture(new RuntimeException("Simulated Exception"))); + CompletableFuture resultFuture = processAsync(List.of(mockMicroserviceA, mockMicroserviceB)); + // Use assertThrows to verify that the expected exception is thrown + ExecutionException exception = assertThrows(ExecutionException.class, resultFuture::get); + // Assert the exception message + assertEquals("Simulated Exception", exception.getCause() + .getMessage()); + } + + @Test + public void givenAsyncTask_whenProcessingAsyncWithTimeout_thenHandleTimeoutException() throws ExecutionException, InterruptedException { + Microservice mockMicroserviceA = mock(Microservice.class); + Microservice mockMicroserviceB = mock(Microservice.class); + Executor delayedExecutor = CompletableFuture.delayedExecutor(200, TimeUnit.MILLISECONDS); + when(mockMicroserviceA.retrieveAsync(any())).thenReturn(CompletableFuture.supplyAsync(() -> "Hello", delayedExecutor)); + Executor delayedExecutor2 = CompletableFuture.delayedExecutor(500, TimeUnit.MILLISECONDS); + when(mockMicroserviceB.retrieveAsync(any())).thenReturn(CompletableFuture.supplyAsync(() -> "World", delayedExecutor2)); + CompletableFuture resultFuture = processAsync(List.of(mockMicroserviceA, mockMicroserviceB)); + assertThrows(TimeoutException.class, () -> resultFuture.get(300, TimeUnit.MILLISECONDS)); + } + + @Test + public void givenCompletableFuture_whenCompleted_thenStateIsDone() { + Executor delayedExecutor = CompletableFuture.delayedExecutor(200, TimeUnit.MILLISECONDS); + CompletableFuture cf1 = CompletableFuture.supplyAsync(() -> "Hello", delayedExecutor); + CompletableFuture cf2 = CompletableFuture.supplyAsync(() -> " World"); + CompletableFuture cf3 = CompletableFuture.supplyAsync(() -> "!"); + CompletableFuture[] cfs = new CompletableFuture[] { cf1, cf2, cf3 }; + + CompletableFuture allCf = CompletableFuture.allOf(cfs); + + assertFalse(allCf.isDone()); + allCf.join(); + String result = Arrays.stream(cfs) + .map(CompletableFuture::join) + .collect(Collectors.joining()); + + assertFalse(allCf.isCancelled()); + assertTrue(allCf.isDone()); + assertFalse(allCf.isCompletedExceptionally()); + assertEquals(result, "Hello World!"); + } + + @Test + public void givenCompletableFuture_whenCompletedWithException_thenStateIsCompletedExceptionally() throws ExecutionException, InterruptedException { + Executor delayedExecutor = CompletableFuture.delayedExecutor(200, TimeUnit.MILLISECONDS); + CompletableFuture cf1 = CompletableFuture.supplyAsync(() -> "Hello", delayedExecutor); + CompletableFuture cf2 = CompletableFuture.failedFuture(new RuntimeException("Simulated Exception")); + CompletableFuture cf3 = CompletableFuture.supplyAsync(() -> "!"); + CompletableFuture[] cfs = new CompletableFuture[] { cf1, cf2, cf3 }; + + CompletableFuture allCf = CompletableFuture.allOf(cfs); + + assertFalse(allCf.isDone()); + assertFalse(allCf.isCompletedExceptionally()); + + // Exception is expected, assert the cause + CompletionException exception = assertThrows(CompletionException.class, allCf::join); + + assertEquals("Simulated Exception", exception.getCause() + .getMessage()); + assertTrue(allCf.isCompletedExceptionally()); + assertTrue(allCf.isDone()); + assertFalse(allCf.isCancelled()); + } + + @Test + public void givenCompletableFuture_whenCancelled_thenStateIsCancelled() throws ExecutionException, InterruptedException { + Executor delayedExecutor = CompletableFuture.delayedExecutor(200, TimeUnit.MILLISECONDS); + CompletableFuture cf1 = CompletableFuture.supplyAsync(() -> "Hello", delayedExecutor); + CompletableFuture cf2 = CompletableFuture.supplyAsync(() -> " World"); + CompletableFuture cf3 = CompletableFuture.supplyAsync(() -> "!"); + CompletableFuture[] cfs = new CompletableFuture[] { cf1, cf2, cf3 }; + CompletableFuture allCf = CompletableFuture.allOf(cfs); + assertFalse(allCf.isDone()); + assertFalse(allCf.isCompletedExceptionally()); + allCf.cancel(true); + assertTrue(allCf.isCancelled()); + assertTrue(allCf.isDone()); + } + + CompletableFuture processAsync(List microservices) { + List> dataFetchFutures = fetchDataAsync(microservices); + return combineResults(dataFetchFutures); + } + + private List> fetchDataAsync(List microservices) { + return microservices.stream() + .map(client -> client.retrieveAsync("")) + .collect(Collectors.toList()); + } + + private CompletableFuture combineResults(List> dataFetchFutures) { + return CompletableFuture.allOf(dataFetchFutures.toArray(new CompletableFuture[0])) + .thenApply(v -> dataFetchFutures.stream() + .map(future -> future.exceptionally(ex -> { + throw new CompletionException(ex); + }) + .join()) + .collect(Collectors.joining())); + } + + interface Microservice { + CompletableFuture retrieveAsync(String input); + } +} From 93b63daa27efd5c20a69b5395f09a9c085b060cb Mon Sep 17 00:00:00 2001 From: SGWebFreelancer Date: Tue, 28 Nov 2023 10:24:39 +0800 Subject: [PATCH 145/228] Fix test file name --- ...ompletableFutureTest.java => CompletableFutureUnitTest.java} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename core-java-modules/core-java-concurrency-2/src/test/java/com/baeldung/concurrent/completablefuture/{CompletableFutureTest.java => CompletableFutureUnitTest.java} (99%) diff --git a/core-java-modules/core-java-concurrency-2/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTest.java b/core-java-modules/core-java-concurrency-2/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureUnitTest.java similarity index 99% rename from core-java-modules/core-java-concurrency-2/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTest.java rename to core-java-modules/core-java-concurrency-2/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureUnitTest.java index 25e8ea4c81..5953c6d87a 100644 --- a/core-java-modules/core-java-concurrency-2/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTest.java +++ b/core-java-modules/core-java-concurrency-2/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureUnitTest.java @@ -20,7 +20,7 @@ import java.util.stream.Collectors; import org.junit.Test; -public class CompletableFutureTest { +public class CompletableFutureUnitTest { @Test public void givenAsyncTask_whenProcessingAsyncSucceed_thenReturnSuccess() throws ExecutionException, InterruptedException { From c67139e60ba57b3846e8d8505b93bdf5374443d6 Mon Sep 17 00:00:00 2001 From: panos-kakos Date: Tue, 28 Nov 2023 06:38:53 +0200 Subject: [PATCH 146/228] [JAVA-26727] Upgraded maven-javadoc-plugin to 3.6.2 version --- core-java-modules/core-java-console/pom.xml | 2 +- core-java-modules/core-java-documentation/pom.xml | 2 +- core-java-modules/core-java-io-2/pom.xml | 2 +- core-java-modules/core-java-io/pom.xml | 2 +- core-java-modules/core-java-jar/pom.xml | 2 +- core-java-modules/core-java-serialization/pom.xml | 2 +- core-java-modules/core-java-uuid/pom.xml | 2 +- performance-tests/pom.xml | 2 +- .../spring-openapi-generator-api-client/pom.xml | 2 +- .../spring-swagger-codegen-api-client/pom.xml | 2 +- 10 files changed, 10 insertions(+), 10 deletions(-) diff --git a/core-java-modules/core-java-console/pom.xml b/core-java-modules/core-java-console/pom.xml index 8677b672ea..a761b2749e 100644 --- a/core-java-modules/core-java-console/pom.xml +++ b/core-java-modules/core-java-console/pom.xml @@ -159,7 +159,7 @@ - 3.0.0-M1 + 3.6.2 1.8 1.8 0.3.2 diff --git a/core-java-modules/core-java-documentation/pom.xml b/core-java-modules/core-java-documentation/pom.xml index be18af1b10..23443dd5ea 100644 --- a/core-java-modules/core-java-documentation/pom.xml +++ b/core-java-modules/core-java-documentation/pom.xml @@ -33,7 +33,7 @@ - 3.0.0-M1 + 3.6.2 1.8 1.8 diff --git a/core-java-modules/core-java-io-2/pom.xml b/core-java-modules/core-java-io-2/pom.xml index 8632748baa..830b386fe2 100644 --- a/core-java-modules/core-java-io-2/pom.xml +++ b/core-java-modules/core-java-io-2/pom.xml @@ -61,7 +61,7 @@ - 3.0.0-M1 + 3.6.2 3.3.1 diff --git a/core-java-modules/core-java-io/pom.xml b/core-java-modules/core-java-io/pom.xml index faeddafd81..93c9289fdd 100644 --- a/core-java-modules/core-java-io/pom.xml +++ b/core-java-modules/core-java-io/pom.xml @@ -134,7 +134,7 @@ - 3.5.0 + 3.6.2 2.7.1 2.8.0 diff --git a/core-java-modules/core-java-jar/pom.xml b/core-java-modules/core-java-jar/pom.xml index a46299c669..138827781e 100644 --- a/core-java-modules/core-java-jar/pom.xml +++ b/core-java-modules/core-java-jar/pom.xml @@ -274,7 +274,7 @@ 4.6.1 1.1 - 3.0.0-M1 + 3.6.2 1.4.4 3.1.1 3.3.0 diff --git a/core-java-modules/core-java-serialization/pom.xml b/core-java-modules/core-java-serialization/pom.xml index 63771d2da0..ad0a730514 100644 --- a/core-java-modules/core-java-serialization/pom.xml +++ b/core-java-modules/core-java-serialization/pom.xml @@ -177,7 +177,7 @@ 0.4 1.8.7 1.1 - 3.0.0-M1 + 3.6.2 4.3.20.RELEASE diff --git a/core-java-modules/core-java-uuid/pom.xml b/core-java-modules/core-java-uuid/pom.xml index d46fcd8a65..0a0835ca46 100644 --- a/core-java-modules/core-java-uuid/pom.xml +++ b/core-java-modules/core-java-uuid/pom.xml @@ -154,7 +154,7 @@ - 3.0.0-M1 + 3.6.2 diff --git a/performance-tests/pom.xml b/performance-tests/pom.xml index d22a9cf3ac..7927c518f9 100644 --- a/performance-tests/pom.xml +++ b/performance-tests/pom.xml @@ -164,7 +164,7 @@ 3.2.4 3.0.0-M1 3.2.0 - 3.2.0 + 3.6.2 3.1.0 3.9.1 3.2.1 diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/pom.xml b/spring-swagger-codegen/spring-openapi-generator-api-client/pom.xml index ee2c86238a..1e3b93ae42 100644 --- a/spring-swagger-codegen/spring-openapi-generator-api-client/pom.xml +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/pom.xml @@ -276,7 +276,7 @@ 2.2 1.10 3.6.1 - 2.10.4 + 3.6.2 2.2.1 1.5 diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/pom.xml b/spring-swagger-codegen/spring-swagger-codegen-api-client/pom.xml index 35f4978411..af12f9cef0 100644 --- a/spring-swagger-codegen/spring-swagger-codegen-api-client/pom.xml +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/pom.xml @@ -196,7 +196,7 @@ 2.2 1.5 2.2.1 - 2.10.4 + 3.6.2 1.10 From 331fb9a477be4641a7e7900bcf7e8550e09ff701 Mon Sep 17 00:00:00 2001 From: panos-kakos <102670093+panos-kakos@users.noreply.github.com> Date: Tue, 28 Nov 2023 12:21:36 +0200 Subject: [PATCH 147/228] [JAVA-27680] Upgraded spring-boot-groovy to jdk17 and spring boot 3 (#15292) --- .../spring-boot-groovy/pom.xml | 22 ++++++++++++------- .../springwithgroovy/entity/Todo.groovy | 12 +++++----- 2 files changed, 20 insertions(+), 14 deletions(-) diff --git a/spring-boot-modules/spring-boot-groovy/pom.xml b/spring-boot-modules/spring-boot-groovy/pom.xml index 151160bde5..677e07db2d 100644 --- a/spring-boot-modules/spring-boot-groovy/pom.xml +++ b/spring-boot-modules/spring-boot-groovy/pom.xml @@ -1,7 +1,7 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung.app spring-boot-groovy @@ -10,9 +10,10 @@ Spring Boot Todo Application with Groovy - com.baeldung.spring-boot-modules - spring-boot-modules - 1.0.0-SNAPSHOT + com.baeldung + parent-boot-3 + 0.0.1-SNAPSHOT + ../../parent-boot-3 @@ -25,7 +26,7 @@ spring-boot-starter-web - org.codehaus.groovy + org.apache.groovy groovy ${groovy.version} @@ -39,6 +40,11 @@ h2 runtime + + io.rest-assured + rest-assured + test + @@ -71,8 +77,8 @@ com.baeldung.springwithgroovy.SpringBootGroovyApplication - 3.0.13 - 1.9.0 + 4.0.11 + 3.0.2 \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/entity/Todo.groovy b/spring-boot-modules/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/entity/Todo.groovy index 000d981701..31274e1f07 100644 --- a/spring-boot-modules/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/entity/Todo.groovy +++ b/spring-boot-modules/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/entity/Todo.groovy @@ -1,11 +1,11 @@ package com.baeldung.springwithgroovy.entity -import javax.persistence.Column -import javax.persistence.Entity -import javax.persistence.GeneratedValue -import javax.persistence.GenerationType -import javax.persistence.Id -import javax.persistence.Table +import jakarta.persistence.Column +import jakarta.persistence.Entity +import jakarta.persistence.GeneratedValue +import jakarta.persistence.GenerationType +import jakarta.persistence.Id +import jakarta.persistence.Table @Entity @Table(name = 'todo') From 7b5225e8db05bd236cafa955223212c2db435bc2 Mon Sep 17 00:00:00 2001 From: Ulisses Lima Date: Tue, 28 Nov 2023 12:14:50 -0300 Subject: [PATCH 148/228] BAEL-7022 Why wait must be called in a synchronized block - Changing Boolean to primitive Based on a comment. --- .../com/baeldung/wait_synchronization/ConditionChecker.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core-java-modules/core-java-concurrency-advanced-5/src/main/java/com/baeldung/wait_synchronization/ConditionChecker.java b/core-java-modules/core-java-concurrency-advanced-5/src/main/java/com/baeldung/wait_synchronization/ConditionChecker.java index dca36fe7cb..34e0a7522b 100644 --- a/core-java-modules/core-java-concurrency-advanced-5/src/main/java/com/baeldung/wait_synchronization/ConditionChecker.java +++ b/core-java-modules/core-java-concurrency-advanced-5/src/main/java/com/baeldung/wait_synchronization/ConditionChecker.java @@ -2,7 +2,7 @@ package com.baeldung.wait_synchronization; public class ConditionChecker { - private volatile Boolean jobIsDone; + private volatile boolean jobIsDone; private final Object lock = new Object(); public void ensureCondition() { @@ -21,4 +21,4 @@ public class ConditionChecker { lock.notify(); } } -} \ No newline at end of file +} From 6ecf4f2bd9d8013f83948f58715ee758842bb470 Mon Sep 17 00:00:00 2001 From: Bipin kumar Date: Wed, 29 Nov 2023 17:54:00 +0530 Subject: [PATCH 149/228] JAVA-26778: Changes made for Upgrade jaxb2-maven-plugin to latest version (#15220) --- feign/pom.xml | 14 +++++++++++++- pom.xml | 4 ++-- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/feign/pom.xml b/feign/pom.xml index edb55e7da5..127f6c490c 100644 --- a/feign/pom.xml +++ b/feign/pom.xml @@ -74,6 +74,17 @@ ${wire.mock.version} test + + jakarta.xml.bind + jakarta.xml.bind-api + 4.0.0 + + + com.sun.xml.bind + jaxb-impl + 4.0.0 + runtime + @@ -85,7 +96,7 @@ org.codehaus.mojo jaxb2-maven-plugin - 2.5.0 + 3.1.0 xjc @@ -131,6 +142,7 @@ 3.8.0 3.1.2 2.33.2 + 4.0.0 \ No newline at end of file diff --git a/pom.xml b/pom.xml index f5aedd091e..32b8e8c8c8 100644 --- a/pom.xml +++ b/pom.xml @@ -726,7 +726,7 @@ dozer drools dubbo - + feign gcp-firebase geotools google-auto-project @@ -970,7 +970,7 @@ dozer drools dubbo - + feign gcp-firebase geotools google-auto-project From eac9c4d5e90218a5b5e9f9b53384bc7afc4176b7 Mon Sep 17 00:00:00 2001 From: parthiv39731 <70740707+parthiv39731@users.noreply.github.com> Date: Wed, 29 Nov 2023 19:45:34 +0530 Subject: [PATCH 150/228] BAEL-7259 --- persistence-modules/java-harperdb/pom.xml | 11 +- .../baledung/harperdb/HarperDBLiveTest.java | 109 +++++++++++++----- .../src/test/resources/UserDefinedViews.json | 5 + .../java-harperdb/src/test/resources/test.db | 0 4 files changed, 90 insertions(+), 35 deletions(-) create mode 100644 persistence-modules/java-harperdb/src/test/resources/UserDefinedViews.json create mode 100644 persistence-modules/java-harperdb/src/test/resources/test.db diff --git a/persistence-modules/java-harperdb/pom.xml b/persistence-modules/java-harperdb/pom.xml index 896a58f858..56b63948c9 100644 --- a/persistence-modules/java-harperdb/pom.xml +++ b/persistence-modules/java-harperdb/pom.xml @@ -38,6 +38,11 @@ testcontainers test + + org.apache.derby + derby + 10.13.1.1 + @@ -52,10 +57,4 @@ - - 19 - 19 - UTF-8 - - \ No newline at end of file diff --git a/persistence-modules/java-harperdb/src/test/java/com/baledung/harperdb/HarperDBLiveTest.java b/persistence-modules/java-harperdb/src/test/java/com/baledung/harperdb/HarperDBLiveTest.java index 1cd377dc6d..5908a57560 100644 --- a/persistence-modules/java-harperdb/src/test/java/com/baledung/harperdb/HarperDBLiveTest.java +++ b/persistence-modules/java-harperdb/src/test/java/com/baledung/harperdb/HarperDBLiveTest.java @@ -11,8 +11,10 @@ import org.testcontainers.containers.GenericContainer; import java.io.IOException; import java.net.URISyntaxException; +import java.net.URL; import java.sql.*; import java.util.Arrays; +import java.util.Map; import java.util.Properties; import static org.junit.jupiter.api.Assertions.*; @@ -21,11 +23,10 @@ public class HarperDBLiveTest { private static final Logger logger = LoggerFactory.getLogger(HarperDBLiveTest.class); - private static String host; - private static Integer port; private static HarperDBContainer harperDBContainer; + private static HarperDBApiService harperDbApiService; @BeforeAll @@ -40,7 +41,6 @@ public class HarperDBLiveTest { GenericContainer genericContainer = harperDBContainer.installHarperDB(); - host = genericContainer.getHost(); genericContainer.start(); port = genericContainer.getFirstMappedPort(); @@ -51,7 +51,7 @@ public class HarperDBLiveTest { harperDbApiService = new HarperDBApiService(url, "admin", "password"); } - private static void setupDB() throws URISyntaxException, IOException { + private static void setupDB() throws IOException { harperDbApiService.createSchema("Demo"); harperDbApiService.createTable("Demo", "Subject", "name"); @@ -99,7 +99,7 @@ public class HarperDBLiveTest { } @Test - void whenConnectionInfoInURL_thenConnectSuccess() throws SQLException { + void whenConnectionInfoInURL_thenConnectSuccess() { assertDoesNotThrow(() -> { final String JDBC_URL = "jdbc:harperdb:Server=127.0.0.1:" + port + ";User=admin;Password=password;"; @@ -112,7 +112,7 @@ public class HarperDBLiveTest { } @Test - void whenConnectionInfoInProperties_thenConnectSuccess() throws SQLException { + void whenConnectionInfoInProperties_thenConnectSuccess() { assertDoesNotThrow(() -> { Properties prop = new Properties(); prop.setProperty("Server", "127.0.0.1:" + port); @@ -128,7 +128,7 @@ public class HarperDBLiveTest { } @Test - void whenConnectionPooling_thenConnectSuccess() throws SQLException { + void whenConnectionPooling_thenConnectSuccess() { assertDoesNotThrow(() -> { HarperDBConnectionPoolDataSource harperdbPoolDataSource = new HarperDBConnectionPoolDataSource(); final String JDBC_URL = "jdbc:harperdb:UseConnectionPooling=true;PoolMaxSize=2;Server=127.0.0.1:" + port + ";User=admin;Password=password;"; @@ -176,6 +176,7 @@ public class HarperDBLiveTest { assertEquals(2, statement.getUpdateCount()); } } + @Test void givenPrepareStatement_whenAddToBatch_thenSuccess() throws SQLException { final String INSERT_SQL = "insert into Demo.Teacher(id, name, joining_date) values" @@ -199,12 +200,23 @@ public class HarperDBLiveTest { } } - private static Connection getConnection() throws SQLException { String URL = "jdbc:harperdb:Server=127.0.0.1:" + port + ";User=admin;Password=password;"; return DriverManager.getConnection(URL); } + private static Connection getConnection(Map properties) throws SQLException { + Properties prop = new Properties(); + prop.setProperty("Server", "127.0.0.1:" + port); + prop.setProperty("User", "admin"); + prop.setProperty("Password", "password"); + for (Map.Entry entry : properties.entrySet()) { + prop.setProperty(entry.getKey(), entry.getValue()); + } + + return DriverManager.getConnection("jdbc:harperdb:", prop); + } + @Test void givenStatement_whenFetchRecord_thenSuccess() throws SQLException { final String SQL_QUERY = "select id, name from Demo.Subject where name = 'Maths'"; @@ -213,9 +225,9 @@ public class HarperDBLiveTest { Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(SQL_QUERY); while (resultSet.next()) { - int id = resultSet.getInt("id"); + Integer id = resultSet.getInt("id"); String name = resultSet.getString("name"); - assertNotNull(Integer.valueOf(id)); + assertNotNull(id); assertEquals("Maths", name); logger.info("Subject id:" + id + " Subject Name:" + name); } @@ -245,25 +257,6 @@ public class HarperDBLiveTest { } } } - @Test - void givenPreparedStatement_whenFetchRecord_thenSuccess() throws SQLException { - final String SQL_QUERY = "select id, name from Demo.Subject where name = ?"; - - try (Connection connection = getConnection()) { - PreparedStatement preparedStatement = connection.prepareStatement(SQL_QUERY); - preparedStatement.setString(1, "Maths"); - - ResultSet resultSet = preparedStatement.executeQuery(); - while (resultSet.next()) { - int id = resultSet.getInt("id"); - String name = resultSet.getString("name"); - assertNotNull(Integer.valueOf(id)); - assertEquals("Maths", name); - logger.info("Subject id:" + id + " Subject Name:" + name); - } - } - } - @Test void givenStatement_whenUpdateRecord_thenSuccess() throws SQLException { @@ -325,4 +318,62 @@ public class HarperDBLiveTest { assertEquals(1, preparedStatement.getUpdateCount()); } } + + @Test + void givenTempTable_whenInsertIntoSelectTempTable_thenSuccess() throws SQLException { + try (Connection connection = getConnection()) { + Statement statement = connection.createStatement(); + assertDoesNotThrow(() -> { + statement.execute("insert into Teacher#TEMP(id, name, joining_date) " + + "values('12', 'David Flinch', '04-04-2014')"); + statement.execute("insert into Teacher#TEMP(id, name, joining_date) " + + "values('13', 'Stephen Hawkins', '04-07-2017')"); + statement.execute("insert into Teacher#TEMP(id, name, joining_date) " + + "values('14', 'Albert Einstein', '12-08-2020')"); + statement.execute("insert into Teacher#TEMP(id, name, joining_date) " + + "values('15', 'Leo Tolstoy', '20-08-2022')"); + }); + assertDoesNotThrow(() -> statement.execute("insert into Demo.Teacher(id, name, joining_date) " + + "select id, name, joining_date from Teacher#TEMP")); + ResultSet resultSet = statement.executeQuery("select count(id) as rows from Demo.Teacher where id in" + + " (12, 13, 14, 15)"); + resultSet.next(); + int totalRows = resultSet.getInt("rows"); + logger.info("total number of rows fetched:" + totalRows); + assertEquals(4, totalRows); + } + } + + @Test + void givenUserDefinedView_whenQueryView_thenSuccess() throws SQLException { + URL url = ClassLoader.getSystemClassLoader().getResource("UserDefinedViews.json"); + + String folderPath = url.getPath().substring(0, url.getPath().lastIndexOf('/')); + + try(Connection connection = getConnection(Map.of("Location", folderPath))) { + PreparedStatement preparedStatement = connection.prepareStatement("select teacher_name,subject_name" + + " from UserViews.View_Teacher_Details where subject_name = ?"); + preparedStatement.setString(1, "Science"); + ResultSet resultSet = preparedStatement.executeQuery(); + while(resultSet.next()) { + assertEquals("Science", resultSet.getString("subject_name")); + logger.info("Science Teacher Name:" + resultSet.getString("teacher_name")); + } + } + } + + @Test + void givenAutoCache_whenQuery_thenSuccess() throws SQLException { + URL url = ClassLoader.getSystemClassLoader().getResource("test.db"); + String folderPath = url.getPath().substring(0, url.getPath().lastIndexOf('/')); + logger.info("Cache Location:" + folderPath); + try(Connection connection = getConnection(Map.of("AutoCache", "true", "CacheLocation", folderPath))) { + PreparedStatement preparedStatement = connection.prepareStatement("select id, name from Demo.Subject"); + + ResultSet resultSet = preparedStatement.executeQuery(); + while(resultSet.next()) { + logger.info("Subject Name:" + resultSet.getString("name")); + } + } + } } diff --git a/persistence-modules/java-harperdb/src/test/resources/UserDefinedViews.json b/persistence-modules/java-harperdb/src/test/resources/UserDefinedViews.json new file mode 100644 index 0000000000..fba67def3c --- /dev/null +++ b/persistence-modules/java-harperdb/src/test/resources/UserDefinedViews.json @@ -0,0 +1,5 @@ +{ + "View_Teacher_Details": { + "query": "SELECT t.name as teacher_name, t.joining_date as joining_date, s.name as subject_name from Demo.Teacher_Details AS td INNER JOIN Demo.Teacher AS t ON t.id = td.teacher_id INNER JOIN Demo.Subject AS s on s.id = td.subject_id" + } +} \ No newline at end of file diff --git a/persistence-modules/java-harperdb/src/test/resources/test.db b/persistence-modules/java-harperdb/src/test/resources/test.db new file mode 100644 index 0000000000..e69de29bb2 From 952f1d2cd2f11c88dc9b24584c08acf36805ec44 Mon Sep 17 00:00:00 2001 From: parthiv39731 <70740707+parthiv39731@users.noreply.github.com> Date: Wed, 29 Nov 2023 19:56:38 +0530 Subject: [PATCH 151/228] Deleted unused file --- .../harperdb/HarperDBLiveTestOld.java | 356 ------------------ 1 file changed, 356 deletions(-) delete mode 100644 persistence-modules/java-harperdb/src/test/java/com/baledung/harperdb/HarperDBLiveTestOld.java diff --git a/persistence-modules/java-harperdb/src/test/java/com/baledung/harperdb/HarperDBLiveTestOld.java b/persistence-modules/java-harperdb/src/test/java/com/baledung/harperdb/HarperDBLiveTestOld.java deleted file mode 100644 index 8becea76a5..0000000000 --- a/persistence-modules/java-harperdb/src/test/java/com/baledung/harperdb/HarperDBLiveTestOld.java +++ /dev/null @@ -1,356 +0,0 @@ -package com.baledung.harperdb; - -import cdata.jdbc.harperdb.HarperDBConnectionPoolDataSource; -import com.github.dockerjava.zerodep.shaded.org.apache.hc.client5.http.classic.methods.HttpPost; -import com.github.dockerjava.zerodep.shaded.org.apache.hc.client5.http.impl.classic.CloseableHttpClient; -import com.github.dockerjava.zerodep.shaded.org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; -import com.github.dockerjava.zerodep.shaded.org.apache.hc.client5.http.impl.classic.HttpClientBuilder; -import com.github.dockerjava.zerodep.shaded.org.apache.hc.core5.http.ClassicHttpRequest; -import com.github.dockerjava.zerodep.shaded.org.apache.hc.core5.http.HttpEntity; -import com.github.dockerjava.zerodep.shaded.org.apache.hc.core5.http.io.entity.StringEntity; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.testcontainers.containers.GenericContainer; - -import java.io.IOException; -import java.net.URISyntaxException; -import java.sql.*; -import java.util.Map; -import java.util.Properties; - -import static org.junit.jupiter.api.Assertions.*; - -public class HarperDBLiveTestOld { - private static final Logger logger = LoggerFactory.getLogger(HarperDBLiveTestOld.class); - - private static String host; - - private static Integer port; - - private static GenericContainer harperDBContainer; - - @BeforeAll - static void setupHarperDB() throws IOException, InterruptedException, URISyntaxException { - installHarperDB(); - setupDB(); - } - - private static void installHarperDB() { - Map envMap = Map.of( - "HDB_ADMIN_USERNAME", "admin", - "HDB_ADMIN_PASSWORD", "password", - "OPERATIONSAPI_NETWORK_PORT", "9925", - "ROOTPATH", "/home/harperdb/hdb", - "LOGGING_STDSTREAMS", "true" - ); - - harperDBContainer = new GenericContainer("harperdb/harperdb:latest") - .withEnv(envMap) - .withExposedPorts(9925, 9926); - host = harperDBContainer.getHost(); - harperDBContainer.start(); - port = harperDBContainer.getFirstMappedPort(); - logger.info("DB Host:" + host + "\n DB Port:" + port); - } - - private static void setupDB() throws URISyntaxException, IOException { - setupSchema("demo"); - createTable("demo", "student", "name", "grade", "subject_id"); - createTable("demo", "teacher", "name", "joining_date", "subject_id"); - insertRecords(); - } - - private static void setupSchema(String schema) throws URISyntaxException, IOException { - String requestBody = "{\"operation\":\"create_schema\", \"" + "schema\":\"" + schema + "\"" + "}"; - executeHttpPostRequest(requestBody); - } - - private static void executeHttpPostRequest(String httpRequest) throws IOException { - logger.info("Post request body:" + httpRequest); - - try (CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().build()) { - HttpPost request = new HttpPost("http://localhost:" + port + "/"); - request.addHeader("Authorization", "Basic YWRtaW46cGFzc3dvcmQ="); - request.addHeader("Content-Type", "application/json"); - request.setEntity((HttpEntity) new StringEntity(httpRequest)); - CloseableHttpResponse response = closeableHttpClient.execute((ClassicHttpRequest) request); - logger.info("REST API response:" + response.toString()); - assertEquals(200, response.getCode()); - } - } - - private void insertStudentRecords() { - - } - - private void insertSubjectRecords() { - - } - - private void insertTeacherRecords() { - - } - - private static void createTable(String schemaName, String tableName, String... attributes) throws IOException { - String createTableReq = "{\"operation\":\"create_table\",\"schema\":\"" - + schemaName + "\",\"table\":\"" - + tableName + "\",\"hash_attribute\":\"id\"" - + "}"; - executeHttpPostRequest(createTableReq); - logger.info("created table:" + tableName); - for (String attribute : attributes) { - String createAttrReq = "{\"operation\":\"create_attribute\",\"schema\":\"" - + schemaName + "\",\"table\":\"" - + tableName + "\",\"attribute\":\"" - + attribute + "\"" - + "}"; - executeHttpPostRequest(createAttrReq); - logger.info("created attribute:" + attribute + " in table:" + tableName); - } - } - - private static void insertRecords() throws IOException { - - String table = "student"; - String schema = "demo"; - String operation = "insert"; - String records = "[" + - "{\"id\":1, \"name\":\"John\", \"grade\":4}," - + "{\"id\":2, \"name\":\"James\", \"grade\":1}," - + "{\"id\":3, \"name\":\"Williams\", \"grade\":1}," - + "{\"id\":4, \"name\":\"Robin\", \"grade\":4}," - + "{\"id\":5, \"name\":\"Torry\", \"grade\":3}," - + "{\"id\":6, \"name\":\"Nancy\", \"grade\":5}," - + "{\"id\":7, \"name\":\"Mary\", \"grade\":5}," - + "{\"id\":8, \"name\":\"Jenny\", \"grade\":6}," - + "{\"id\":9, \"name\":\"Katy\", \"grade\":6}," - + "{\"id\":15, \"name\":\"Michael\", \"grade\":6}" - + "]"; - String requestBody = "{\"table\":" + "\"" + table + "\"," - + "\"schema\":" + "\"" + schema + "\"" + "," - + "\"operation\":" + "\"" + operation + "\"" + "," - + "\"records\":" + records - + "}"; - String sql = "{" - + "\"operation\":\"sql\", " - + "\"sql\":\"insert into demo.student(id, name, grade) values" - + "(1, 'John', 4), (2, 'James', 1), (3, 'Williams', 1), (4, 'Robin', 4), (5, 'Torry', 3)," - + " (6, 'Nancy', 5), (7, 'Mary', 5), (8, 'Jenny', 6), (9, 'Katy', 6)\"" - + "}"; - executeHttpPostRequest(requestBody); - } - - @AfterAll - static void stopHarperDB() { - harperDBContainer.stop(); - } - - @Test - void whenConnectionInfoInURL_thenConnectSuccess() throws SQLException { - assertDoesNotThrow(() -> { - String URL = "jdbc:harperdb:Server=127.0.0.1:" + port + ";User=admin;Password=password;"; - - try (Connection connection = DriverManager.getConnection(URL)) { - connection.createStatement().executeQuery("select 1"); - logger.info("Connection Successful"); - } - }); - } - - @Test - void whenConnectionInfoInProperties_thenConnectSuccess() throws SQLException { - assertDoesNotThrow(() -> { - Properties prop = new Properties(); - prop.setProperty("Server", "127.0.0.1:" + port); - prop.setProperty("User", "admin"); - prop.setProperty("Password", "password"); - - try (Connection connection = DriverManager.getConnection("jdbc:harperdb:", prop)) { - connection.createStatement().executeQuery("select 1"); - logger.info("Connection Successful"); - } - }); - } - - @Test - void whenConnectionPooling_thenConnectSuccess() throws SQLException { - assertDoesNotThrow(() -> { - HarperDBConnectionPoolDataSource harperdbPoolDataSource = new HarperDBConnectionPoolDataSource(); - String URL = "jdbc:harperdb:UseConnectionPooling=true;PoolMaxSize=2;Server=127.0.0.1:" + port - + ";User=admin;Password=1234;"; - harperdbPoolDataSource.setURL(URL); - - try(Connection connection = harperdbPoolDataSource.getPooledConnection().getConnection()) { - connection.createStatement().executeQuery("select 1"); - logger.info("Connection Successful"); - } - }); - } - - private static Connection getConnection() throws SQLException { - String URL = "jdbc:harperdb:Server=127.0.0.1:" + port + ";User=admin;Password=password;"; - return DriverManager.getConnection(URL); - } - - @Test - void givenStatement_whenFetchRecord_thenSuccess() throws SQLException { - final String SQL_QUERY = "select id, name, grade from demo.student"; - - try(Connection connection = getConnection()) { - Statement statement = connection.createStatement(); - ResultSet resultSet = statement.executeQuery(SQL_QUERY); - while (resultSet.next()) { - int id = resultSet.getInt("id"); - String name = resultSet.getString("name"); - int grade = resultSet.getInt("grade"); - assertNotNull(Integer.valueOf(id)); - logger.info("Student id:" + id + " Student Name:" + name + " grade:" + grade); - } - } - } - - @Test - void givenStatement_whenInsertRecord_thenSuccess() throws SQLException { - final String INSERT_SQL = "insert into demo.student(id, name, grade) values (10, 'Barak', 3)"; - - try(Connection connection = getConnection()) { - Statement statement = connection.createStatement(); - assertDoesNotThrow(() -> statement.execute(INSERT_SQL)); - } - } - - @Test - void givenStatement_whenInsertRecordInTableWithoutAttributes_thenSuccess() throws SQLException { - final String INSERT_SQL = "insert into demo.teacher(id, name, joining_date) " - + "values (1, 'David Martinez', '04-05-2004'), (2, 'Eric Martin', '04-10-2000')"; - final String QUERY_SQL = "select name, joining_date from demo.teacher where name = ?"; - - try(Connection connection = getConnection()) { - Statement statement = connection.createStatement(); - assertDoesNotThrow(() -> statement.execute(INSERT_SQL)); - PreparedStatement preparedStatement = connection.prepareStatement(QUERY_SQL); - preparedStatement.setString(1, "Eric Martin"); - ResultSet resultSet = preparedStatement.executeQuery(); - while (resultSet.next()) { - String teacherName = resultSet.getString("name"); - String joinDate = resultSet.getString("joining_date"); - assertEquals("Eric Martin", teacherName); - assertEquals("04-10-2000", joinDate); - logger.info("name:" + teacherName + " joining date:" + joinDate); - } - } - } - - @Test - void givenStatement_whenUpdateRecord_thenSuccess() throws SQLException { - final String UPDATE_SQL = "update demo.student set grade = 4 where id = 5"; - - try(Connection connection = getConnection()) { - Statement statement = connection.createStatement(); - assertDoesNotThrow(() -> statement.execute(UPDATE_SQL)); - assertEquals(1, statement.getUpdateCount()); - } - } - - @Test - void givenStatement_whenDeleteRecord_thenSuccess() throws SQLException { - final String DELETE_SQL = "delete from demo.student where id = 3"; - - try(Connection connection = getConnection()) { - Statement statement = connection.createStatement(); - assertDoesNotThrow(() -> statement.execute(DELETE_SQL)); - assertEquals(1, statement.getUpdateCount()); - } - } - - @Test - void givenPreparedStatement_whenFetchRecord_thenSuccess() throws SQLException { - final String SQL_QUERY = "select id, name, grade from demo.student where name = ? and grade = ?"; - - try(Connection connection = getConnection()) { - PreparedStatement preparedStatement = connection.prepareStatement(SQL_QUERY); - preparedStatement.setString(1, "Robin"); - preparedStatement.setInt(2, 4); - ResultSet resultSet = preparedStatement.executeQuery(); - while (resultSet.next()) { - int id = resultSet.getInt("id"); - String name = resultSet.getString("name"); - int grade = resultSet.getInt("grade"); - assertNotNull(Integer.valueOf(id)); - assertEquals("Robin", name); - logger.info("Student id:" + id + " Student Name:" + name + " grade:" + grade); - } - } - } - - @Test - void givenPreparedStatement_whenDeleteRecord_thenSuccess() throws SQLException { - final String DELETE_SQL = "delete from demo.student where name = ?"; - - try(Connection connection = getConnection()) { - PreparedStatement preparedStatement = connection.prepareStatement(DELETE_SQL); - preparedStatement.setString(1, "James"); - assertDoesNotThrow(() -> preparedStatement.execute()); - assertEquals(1, preparedStatement.getUpdateCount()); - } - } - - @Test - void givenPreparedStatement_whenUpdateRecord_thenSuccess() throws SQLException { - final String UPDATE_SQL = "update demo.student set grade = ? where id = ? and name = ?"; - - try(Connection connection = getConnection()) { - PreparedStatement preparedStatement = connection.prepareStatement(UPDATE_SQL); - preparedStatement.setInt(1, 5); - preparedStatement.setInt(2, 1); - preparedStatement.setString(3, "John"); - assertDoesNotThrow(() -> preparedStatement.execute()); - assertEquals(1, preparedStatement.getUpdateCount()); - } - } - - @Test - void whenAddtoBatch_thenExecuteBatchIsSuccess() throws SQLException { - final String INSERT_SQL = "insert into demo.teacher(id, name, joining_date)" - + "values(?, ?, ?)"; - - try(Connection connection = getConnection()) { - PreparedStatement preparedStatement = connection.prepareStatement(INSERT_SQL); - preparedStatement.setInt(1, 1); - preparedStatement.setString(2, "Bret Lee"); - preparedStatement.setString(3, "07-08-2002"); - preparedStatement.addBatch(); - - preparedStatement.setInt(1, 2); - preparedStatement.setString(2, "Sarah Glimmer"); - preparedStatement.setString(3, "07-08-1997"); - preparedStatement.addBatch(); - - assertDoesNotThrow(() -> preparedStatement.executeBatch()); - } - } - - @Test - void whenExecuteStoredToCreateTable_thenSuccess() throws SQLException { - final String CREATE_TABLE_SQL = "CreateTable"; - try(Connection connection = getConnection()) { - CallableStatement callableStatement = connection.prepareCall(CREATE_TABLE_SQL); - - callableStatement.setString("SchemaName", "prod"); //schema gets created too - callableStatement.setString("TableName", "subject"); - callableStatement.setString("PrimaryKey", "id"); - Boolean result = callableStatement.execute(); - - ResultSet resultSet = callableStatement.getResultSet(); - - while(resultSet.next()) { - String tableCreated = resultSet.getString("Success"); - assertEquals("true", tableCreated); - logger.info("result of the callable execute:" + tableCreated); - } - } - } -} From c2b0f73f33cf69030747c5f693bb149ea6f98870 Mon Sep 17 00:00:00 2001 From: parthiv39731 <70740707+parthiv39731@users.noreply.github.com> Date: Wed, 29 Nov 2023 20:01:31 +0530 Subject: [PATCH 152/228] included persistence-modules/java-harperdb --- pom.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/pom.xml b/pom.xml index 7099dd8cbc..219fc19071 100644 --- a/pom.xml +++ b/pom.xml @@ -819,6 +819,7 @@ performance-tests persistence-modules persistence-modules/spring-data-neo4j + persistence-modules/java-harperdb protobuffer quarkus-modules reactive-systems From 44e565ffe82395c5dca2464588b43ac8734e3446 Mon Sep 17 00:00:00 2001 From: panos-kakos Date: Wed, 29 Nov 2023 17:25:49 +0200 Subject: [PATCH 153/228] [JAVA-26711] Upgraded shedlock to latest version(5.10.0) --- spring-boot-modules/spring-boot-libraries/pom.xml | 2 +- .../scheduling/shedlock/BaeldungTaskScheduler.java | 4 ++-- spring-core-2/pom.xml | 12 ------------ 3 files changed, 3 insertions(+), 15 deletions(-) diff --git a/spring-boot-modules/spring-boot-libraries/pom.xml b/spring-boot-modules/spring-boot-libraries/pom.xml index b0f0c780aa..fd3daa1a79 100644 --- a/spring-boot-modules/spring-boot-libraries/pom.xml +++ b/spring-boot-modules/spring-boot-libraries/pom.xml @@ -225,7 +225,7 @@ 2.2.4 3.2.0 0.23.0 - 2.1.0 + 5.10.0 1.5-beta1 2.1 2.6.0 diff --git a/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/BaeldungTaskScheduler.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/BaeldungTaskScheduler.java index cd5f63e962..c03d351c20 100644 --- a/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/BaeldungTaskScheduler.java +++ b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/BaeldungTaskScheduler.java @@ -1,13 +1,13 @@ package com.baeldung.scheduling.shedlock; -import net.javacrumbs.shedlock.core.SchedulerLock; +import net.javacrumbs.shedlock.spring.annotation.SchedulerLock; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component class BaeldungTaskScheduler { @Scheduled(cron = "0 0/15 * * * ?") - @SchedulerLock(name = "TaskScheduler_scheduledTask", lockAtLeastForString = "PT5M", lockAtMostForString = "PT14M") + @SchedulerLock(name = "TaskScheduler_scheduledTask", lockAtLeastFor = "PT5M", lockAtMostFor = "PT14M") public void scheduledTask() { System.out.println("Running ShedLock task"); } diff --git a/spring-core-2/pom.xml b/spring-core-2/pom.xml index f27b16acc3..bed0d730b2 100644 --- a/spring-core-2/pom.xml +++ b/spring-core-2/pom.xml @@ -119,17 +119,6 @@ spring-boot-starter-test test - - - net.javacrumbs.shedlock - shedlock-spring - ${shedlock.version} - - - net.javacrumbs.shedlock - shedlock-provider-jdbc-template - ${shedlock.version} - org.projectlombok lombok @@ -161,7 +150,6 @@ 1.3.2 3.6 - 2.1.0 3.22.0-GA 3.2.2 From 7683cff43d657d890fe8c10b3967f85f20ad0f5a Mon Sep 17 00:00:00 2001 From: gaepi Date: Thu, 30 Nov 2023 10:20:20 +0100 Subject: [PATCH 154/228] JAVA-26724 | kafka testcontainers version update --- apache-kafka-2/pom.xml | 2 +- apache-kafka/pom.xml | 2 +- spring-boot-modules/spring-boot-documentation/pom.xml | 2 +- spring-kafka-2/pom.xml | 2 +- spring-kafka/pom.xml | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/apache-kafka-2/pom.xml b/apache-kafka-2/pom.xml index d1f74e8aae..cd21a60e14 100644 --- a/apache-kafka-2/pom.xml +++ b/apache-kafka-2/pom.xml @@ -62,7 +62,7 @@ 5.7.0 2.8.0 - 1.15.3 + 1.19.3 1.15.3 2.15.2 diff --git a/apache-kafka/pom.xml b/apache-kafka/pom.xml index 494bc94961..22be7a83c6 100644 --- a/apache-kafka/pom.xml +++ b/apache-kafka/pom.xml @@ -182,7 +182,7 @@ 3.4.0 - 1.15.3 + 1.19.3 1.15.3 1.16.1 3.0.0 diff --git a/spring-boot-modules/spring-boot-documentation/pom.xml b/spring-boot-modules/spring-boot-documentation/pom.xml index 3ac2799258..30a82660af 100644 --- a/spring-boot-modules/spring-boot-documentation/pom.xml +++ b/spring-boot-modules/spring-boot-documentation/pom.xml @@ -95,7 +95,7 @@ 2.2.11 0.14.0 0.14.0 - 1.18.3 + 1.19.3 diff --git a/spring-kafka-2/pom.xml b/spring-kafka-2/pom.xml index fdf7da7438..05da9418b7 100644 --- a/spring-kafka-2/pom.xml +++ b/spring-kafka-2/pom.xml @@ -64,7 +64,7 @@ - 1.16.2 + 1.19.3 3.0.12 3.6.0 1.16.2 diff --git a/spring-kafka/pom.xml b/spring-kafka/pom.xml index 7ff7a9710a..ddef3ca180 100644 --- a/spring-kafka/pom.xml +++ b/spring-kafka/pom.xml @@ -92,7 +92,7 @@ 3.0.5 1.10.5 - 1.16.2 + 1.19.3 \ No newline at end of file From 5990aeee283a63ce0146baa756a4bc3843ebf84b Mon Sep 17 00:00:00 2001 From: panos-kakos <102670093+panos-kakos@users.noreply.github.com> Date: Thu, 30 Nov 2023 13:05:22 +0200 Subject: [PATCH 155/228] [JAVA-27742] Replaced aspectj-maven-plugin with dev.aspectj that supports java 17 (#15289) --- spring-di-2/pom.xml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/spring-di-2/pom.xml b/spring-di-2/pom.xml index 0bd6c41a8c..898dd182f1 100644 --- a/spring-di-2/pom.xml +++ b/spring-di-2/pom.xml @@ -55,9 +55,9 @@ - org.codehaus.mojo + dev.aspectj aspectj-maven-plugin - ${aspectj-plugin.version} + ${aspectj-maven-plugin.version} ${java.version} @@ -80,7 +80,7 @@ 3.1.2 - 1.14.0 + 1.13.1 2.17.1 From 57eaebe8d5e116cfc52c9b0c3b5b343db0eef202 Mon Sep 17 00:00:00 2001 From: parthiv39731 <70740707+parthiv39731@users.noreply.github.com> Date: Thu, 30 Nov 2023 19:40:11 +0530 Subject: [PATCH 156/228] BAEL-7259: renamed package --- .../com/{baledung => baeldung}/harperdb/HarperDBApiService.java | 2 +- .../com/{baledung => baeldung}/harperdb/HarperDBContainer.java | 2 +- .../com/{baledung => baeldung}/harperdb/HarperDBLiveTest.java | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) rename persistence-modules/java-harperdb/src/test/java/com/{baledung => baeldung}/harperdb/HarperDBApiService.java (99%) rename persistence-modules/java-harperdb/src/test/java/com/{baledung => baeldung}/harperdb/HarperDBContainer.java (97%) rename persistence-modules/java-harperdb/src/test/java/com/{baledung => baeldung}/harperdb/HarperDBLiveTest.java (99%) diff --git a/persistence-modules/java-harperdb/src/test/java/com/baledung/harperdb/HarperDBApiService.java b/persistence-modules/java-harperdb/src/test/java/com/baeldung/harperdb/HarperDBApiService.java similarity index 99% rename from persistence-modules/java-harperdb/src/test/java/com/baledung/harperdb/HarperDBApiService.java rename to persistence-modules/java-harperdb/src/test/java/com/baeldung/harperdb/HarperDBApiService.java index 15178f9769..361e17bd83 100644 --- a/persistence-modules/java-harperdb/src/test/java/com/baledung/harperdb/HarperDBApiService.java +++ b/persistence-modules/java-harperdb/src/test/java/com/baeldung/harperdb/HarperDBApiService.java @@ -1,4 +1,4 @@ -package com.baledung.harperdb; +package com.baeldung.harperdb; import com.github.dockerjava.zerodep.shaded.org.apache.hc.client5.http.classic.methods.HttpPost; import com.github.dockerjava.zerodep.shaded.org.apache.hc.client5.http.impl.classic.CloseableHttpClient; diff --git a/persistence-modules/java-harperdb/src/test/java/com/baledung/harperdb/HarperDBContainer.java b/persistence-modules/java-harperdb/src/test/java/com/baeldung/harperdb/HarperDBContainer.java similarity index 97% rename from persistence-modules/java-harperdb/src/test/java/com/baledung/harperdb/HarperDBContainer.java rename to persistence-modules/java-harperdb/src/test/java/com/baeldung/harperdb/HarperDBContainer.java index 5ce6e069ce..12ef87fa99 100644 --- a/persistence-modules/java-harperdb/src/test/java/com/baledung/harperdb/HarperDBContainer.java +++ b/persistence-modules/java-harperdb/src/test/java/com/baeldung/harperdb/HarperDBContainer.java @@ -1,4 +1,4 @@ -package com.baledung.harperdb; +package com.baeldung.harperdb; import java.util.Map; diff --git a/persistence-modules/java-harperdb/src/test/java/com/baledung/harperdb/HarperDBLiveTest.java b/persistence-modules/java-harperdb/src/test/java/com/baeldung/harperdb/HarperDBLiveTest.java similarity index 99% rename from persistence-modules/java-harperdb/src/test/java/com/baledung/harperdb/HarperDBLiveTest.java rename to persistence-modules/java-harperdb/src/test/java/com/baeldung/harperdb/HarperDBLiveTest.java index 5908a57560..34d2f8d29b 100644 --- a/persistence-modules/java-harperdb/src/test/java/com/baledung/harperdb/HarperDBLiveTest.java +++ b/persistence-modules/java-harperdb/src/test/java/com/baeldung/harperdb/HarperDBLiveTest.java @@ -1,4 +1,4 @@ -package com.baledung.harperdb; +package com.baeldung.harperdb; import cdata.jdbc.harperdb.HarperDBConnectionPoolDataSource; From 35b88b06afae92c4271eabb5764771731f973c79 Mon Sep 17 00:00:00 2001 From: Maiklins Date: Thu, 30 Nov 2023 16:10:46 +0100 Subject: [PATCH 157/228] Update README.md --- core-java-modules/core-java-8-datetime-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-8-datetime-2/README.md b/core-java-modules/core-java-8-datetime-2/README.md index f7ada52da6..6fe450816e 100644 --- a/core-java-modules/core-java-8-datetime-2/README.md +++ b/core-java-modules/core-java-8-datetime-2/README.md @@ -8,4 +8,5 @@ - [Add Minutes to a Time String in Java](https://www.baeldung.com/java-string-time-add-mins) - [Round the Date in Java](https://www.baeldung.com/java-round-the-date) - [Representing Furthest Possible Date in Java](https://www.baeldung.com/java-date-represent-max) +- [Retrieving Unix Time in Java](https://www.baeldung.com/java-retrieve-unix-time) - [[<-- Prev]](/core-java-modules/core-java-datetime-java8-1) From e076a171eef9c30d47716f3fa81bf4ad6414046a Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Thu, 30 Nov 2023 22:54:02 +0530 Subject: [PATCH 158/228] JAVA-26736 Upgrade jackson to latest version --- core-java-modules/core-java-11-3/pom.xml | 2 +- core-java-modules/core-java-collections-list-5/pom.xml | 2 +- core-java-modules/core-java-collections-maps-6/pom.xml | 2 +- core-java-modules/core-java-string-operations-3/pom.xml | 2 +- .../baeldung/versioncomparison/VersionComparisonUnitTest.java | 2 +- jackson-modules/jackson-polymorphic-deserialization/pom.xml | 4 ++-- jackson-simple/pom.xml | 2 +- persistence-modules/hibernate-mapping/pom.xml | 2 +- persistence-modules/spring-data-elasticsearch/pom.xml | 2 +- pom.xml | 2 +- spring-batch/pom.xml | 2 +- spring-boot-modules/spring-boot-resilience4j/pom.xml | 2 +- .../custom-validations-opeanpi-codegen/pom.xml | 2 +- testing-modules/mocks-2/pom.xml | 2 +- 14 files changed, 15 insertions(+), 15 deletions(-) diff --git a/core-java-modules/core-java-11-3/pom.xml b/core-java-modules/core-java-11-3/pom.xml index 22db9e62ab..0161f4dcca 100644 --- a/core-java-modules/core-java-11-3/pom.xml +++ b/core-java-modules/core-java-11-3/pom.xml @@ -45,7 +45,7 @@ 11 11 - 2.14.1 + 2.16.0 2.10 diff --git a/core-java-modules/core-java-collections-list-5/pom.xml b/core-java-modules/core-java-collections-list-5/pom.xml index b8832df357..c89ad0fad9 100644 --- a/core-java-modules/core-java-collections-list-5/pom.xml +++ b/core-java-modules/core-java-collections-list-5/pom.xml @@ -67,7 +67,7 @@ 1.21 2.2 2.10.1 - 2.15.2 + 2.16.0 20230618 \ No newline at end of file diff --git a/core-java-modules/core-java-collections-maps-6/pom.xml b/core-java-modules/core-java-collections-maps-6/pom.xml index 8c35dcee6e..fd28e9cc57 100644 --- a/core-java-modules/core-java-collections-maps-6/pom.xml +++ b/core-java-modules/core-java-collections-maps-6/pom.xml @@ -20,7 +20,7 @@ com.fasterxml.jackson.core jackson-databind - 2.13.1 + 2.16.0 org.openjdk.jmh diff --git a/core-java-modules/core-java-string-operations-3/pom.xml b/core-java-modules/core-java-string-operations-3/pom.xml index 0558e71a35..59d14805a0 100644 --- a/core-java-modules/core-java-string-operations-3/pom.xml +++ b/core-java-modules/core-java-string-operations-3/pom.xml @@ -72,7 +72,7 @@ 5.3.9 3.6.3 6.1.1 - 2.11.1 + 2.16.0 3.1.0 diff --git a/core-java-modules/core-java-string-operations-3/src/test/java/com/baeldung/versioncomparison/VersionComparisonUnitTest.java b/core-java-modules/core-java-string-operations-3/src/test/java/com/baeldung/versioncomparison/VersionComparisonUnitTest.java index 145e9788e4..a99778201a 100644 --- a/core-java-modules/core-java-string-operations-3/src/test/java/com/baeldung/versioncomparison/VersionComparisonUnitTest.java +++ b/core-java-modules/core-java-string-operations-3/src/test/java/com/baeldung/versioncomparison/VersionComparisonUnitTest.java @@ -87,7 +87,7 @@ public class VersionComparisonUnitTest { assertTrue(version1_1_maven.compareTo(version1_1_gradle) < 0); Version version1_1_snapshot = new Version(1, 1, 0, "snapshot", null, null); - assertEquals(0, version1_1.compareTo(version1_1_snapshot)); + assertEquals(1, version1_1.compareTo(version1_1_snapshot)); assertTrue(version1_1_snapshot.isSnapshot()); } diff --git a/jackson-modules/jackson-polymorphic-deserialization/pom.xml b/jackson-modules/jackson-polymorphic-deserialization/pom.xml index 0d88c19500..cbf67e5013 100644 --- a/jackson-modules/jackson-polymorphic-deserialization/pom.xml +++ b/jackson-modules/jackson-polymorphic-deserialization/pom.xml @@ -16,7 +16,7 @@ com.fasterxml.jackson.core jackson-core - ${jackson-core.version} + ${jackson.version} org.reflections @@ -36,7 +36,7 @@ - 2.15.2 + 2.16.0 0.9.11 diff --git a/jackson-simple/pom.xml b/jackson-simple/pom.xml index 3bf523bbfa..2ba3868ee2 100644 --- a/jackson-simple/pom.xml +++ b/jackson-simple/pom.xml @@ -33,7 +33,7 @@ - 2.15.2 + 2.16.0 17 diff --git a/persistence-modules/hibernate-mapping/pom.xml b/persistence-modules/hibernate-mapping/pom.xml index 0ce112b9e6..45d8e24b41 100644 --- a/persistence-modules/hibernate-mapping/pom.xml +++ b/persistence-modules/hibernate-mapping/pom.xml @@ -86,7 +86,7 @@ 3.0.1-b11 1.1 1.4.2 - 2.14.2 + 2.16.0 \ No newline at end of file diff --git a/persistence-modules/spring-data-elasticsearch/pom.xml b/persistence-modules/spring-data-elasticsearch/pom.xml index 6535b9ac4b..91dc3ee4d2 100644 --- a/persistence-modules/spring-data-elasticsearch/pom.xml +++ b/persistence-modules/spring-data-elasticsearch/pom.xml @@ -60,7 +60,7 @@ 5.1.2 8.9.0 - 2.15.2 + 2.16.0 \ No newline at end of file diff --git a/pom.xml b/pom.xml index 32b8e8c8c8..1c685bc5e3 100644 --- a/pom.xml +++ b/pom.xml @@ -1221,7 +1221,7 @@ 1.2 2.3.3 1.2 - 2.15.2 + 2.16.0 1.5 1.9.2 5.9.2 diff --git a/spring-batch/pom.xml b/spring-batch/pom.xml index 20b0ef6d1c..bca0030729 100644 --- a/spring-batch/pom.xml +++ b/spring-batch/pom.xml @@ -77,7 +77,7 @@ 5.8 4.0.0 4.0.2 - 2.14.2 + 2.16.0 4.5.14 1.5.3 com.baeldung.batchtesting.SpringBatchApplication diff --git a/spring-boot-modules/spring-boot-resilience4j/pom.xml b/spring-boot-modules/spring-boot-resilience4j/pom.xml index 355ef8f92d..2f3af8f9d2 100644 --- a/spring-boot-modules/spring-boot-resilience4j/pom.xml +++ b/spring-boot-modules/spring-boot-resilience4j/pom.xml @@ -53,7 +53,7 @@ 2.35.0 2.0.2 - 2.15.2 + 2.16.0 \ No newline at end of file diff --git a/spring-swagger-codegen/custom-validations-opeanpi-codegen/pom.xml b/spring-swagger-codegen/custom-validations-opeanpi-codegen/pom.xml index 95d3239b96..ded02da62c 100644 --- a/spring-swagger-codegen/custom-validations-opeanpi-codegen/pom.xml +++ b/spring-swagger-codegen/custom-validations-opeanpi-codegen/pom.xml @@ -88,7 +88,7 @@ 2.17.1 1.7.0 3.3.4 - 2.10.0.pr3 + 2.16.0 5.1.0 diff --git a/testing-modules/mocks-2/pom.xml b/testing-modules/mocks-2/pom.xml index 22a5198b8c..2ef1a03dff 100644 --- a/testing-modules/mocks-2/pom.xml +++ b/testing-modules/mocks-2/pom.xml @@ -33,7 +33,7 @@ 1.6.0 - 2.13.4 + 2.16.0 5.3.25 From 339b269caa64a5647d10f66b98815698968ba20f Mon Sep 17 00:00:00 2001 From: michaelin007 Date: Thu, 30 Nov 2023 18:35:21 +0000 Subject: [PATCH 159/228] Update article httpsecurity vs websecurity --- .../WebSecurityConfig.java | 87 ++++++++++++++----- .../controller/AdminController.java | 15 ++++ 2 files changed, 80 insertions(+), 22 deletions(-) create mode 100644 spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/controller/AdminController.java diff --git a/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/WebSecurityConfig.java b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/WebSecurityConfig.java index 46a82918aa..f5b799065b 100644 --- a/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/WebSecurityConfig.java +++ b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/WebSecurityConfig.java @@ -1,35 +1,78 @@ package com.baeldung.httpsecurityvswebsecurity; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; -import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; +import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.provisioning.InMemoryUserDetailsManager; import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.firewall.HttpFirewall; +import org.springframework.security.web.firewall.StrictHttpFirewall; + +import java.util.ArrayList; +import java.util.List; + +import static org.springframework.security.config.Customizer.withDefaults; @Configuration -public class WebSecurityConfig extends WebSecurityConfigurerAdapter { +@EnableWebSecurity +public class WebSecurityConfig { - @Autowired - private UserDetailsService userDetailsService; - - @Override - protected void configure(AuthenticationManagerBuilder auth) throws Exception { - auth - .userDetailsService(userDetailsService) - .passwordEncoder(new BCryptPasswordEncoder()); + @Bean + public HttpFirewall allowHttpMethod() { + List allowedMethods = new ArrayList(); + allowedMethods.add("GET"); + allowedMethods.add("POST"); + StrictHttpFirewall firewall = new StrictHttpFirewall(); + firewall.setAllowedHttpMethods(allowedMethods); + return firewall; } - @Override - protected void configure(HttpSecurity http) throws Exception { - http.authorizeRequests() - .antMatchers("/") - .permitAll() + @Bean + public WebSecurityCustomizer fireWall() { + return (web) -> web.httpFirewall(allowHttpMethod()); + } + + @Bean + public WebSecurityCustomizer ignoringCustomizer() { + return (web) -> web.ignoring().antMatchers("/resources/**", "/static/**"); + } + + @Bean + public WebSecurityCustomizer debugSecurity() { + return (web) -> web.debug(true); + } + + @Bean + public InMemoryUserDetailsManager userDetailsService() { + UserDetails user = User.withUsername("user") + .password(encoder().encode("userPass")) + .roles("ADMIN") + .build(); + return new InMemoryUserDetailsManager(user); + } + + @Bean + public PasswordEncoder encoder() { + return new BCryptPasswordEncoder(); + } + + @Bean + public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { + http.authorizeHttpRequests((authorize) -> authorize.antMatchers("/admin/**") + .hasRole("ADMIN") .anyRequest() - .authenticated() - .and() - .formLogin(); + .permitAll()) + .httpBasic(withDefaults()) + .formLogin(withDefaults()) + .csrf(AbstractHttpConfigurer::disable); + return http.build(); } + } diff --git a/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/controller/AdminController.java b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/controller/AdminController.java new file mode 100644 index 0000000000..cd1daee17e --- /dev/null +++ b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/controller/AdminController.java @@ -0,0 +1,15 @@ +package com.baeldung.httpsecurityvswebsecurity.controller; + +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/admin") +public class AdminController { + + @RequestMapping("/greeting") + public String hello() { + return "Hello Admin"; + } + +} From dea22a68632b94ee4dfe45c64ec631fd350fdba2 Mon Sep 17 00:00:00 2001 From: michaelin007 Date: Thu, 30 Nov 2023 18:42:41 +0000 Subject: [PATCH 160/228] Update article httpsecurity vs websecurity --- .../SecurityConfiguration.java | 78 +++++++++++++++++ .../WebSecurityConfig.java | 87 +++++-------------- 2 files changed, 100 insertions(+), 65 deletions(-) create mode 100644 spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/SecurityConfiguration.java diff --git a/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/SecurityConfiguration.java b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/SecurityConfiguration.java new file mode 100644 index 0000000000..5c0853e6f3 --- /dev/null +++ b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/SecurityConfiguration.java @@ -0,0 +1,78 @@ +package com.baeldung.httpsecurityvswebsecurity; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; +import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.provisioning.InMemoryUserDetailsManager; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.firewall.HttpFirewall; +import org.springframework.security.web.firewall.StrictHttpFirewall; + +import java.util.ArrayList; +import java.util.List; + +import static org.springframework.security.config.Customizer.withDefaults; + +@Configuration +@EnableWebSecurity +public class SecurityConfiguration { + + @Bean + public HttpFirewall allowHttpMethod() { + List allowedMethods = new ArrayList(); + allowedMethods.add("GET"); + allowedMethods.add("POST"); + StrictHttpFirewall firewall = new StrictHttpFirewall(); + firewall.setAllowedHttpMethods(allowedMethods); + return firewall; + } + + @Bean + public WebSecurityCustomizer fireWall() { + return (web) -> web.httpFirewall(allowHttpMethod()); + } + + @Bean + public WebSecurityCustomizer ignoringCustomizer() { + return (web) -> web.ignoring().antMatchers("/resources/**", "/static/**"); + } + + @Bean + public WebSecurityCustomizer debugSecurity() { + return (web) -> web.debug(true); + } + + @Bean + public InMemoryUserDetailsManager userDetailsService() { + UserDetails user = User.withUsername("user") + .password(encoder().encode("userPass")) + .roles("ADMIN") + .build(); + return new InMemoryUserDetailsManager(user); + } + + @Bean + public PasswordEncoder encoder() { + return new BCryptPasswordEncoder(); + } + + @Bean + public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { + http.authorizeHttpRequests((authorize) -> authorize.antMatchers("/admin/**") + .hasRole("ADMIN") + .anyRequest() + .permitAll()) + .httpBasic(withDefaults()) + .formLogin(withDefaults()) + .csrf(AbstractHttpConfigurer::disable); + return http.build(); + } + +} diff --git a/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/WebSecurityConfig.java b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/WebSecurityConfig.java index f5b799065b..46a82918aa 100644 --- a/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/WebSecurityConfig.java +++ b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/WebSecurityConfig.java @@ -1,78 +1,35 @@ package com.baeldung.httpsecurityvswebsecurity; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; -import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer; -import org.springframework.security.core.userdetails.User; -import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; -import org.springframework.security.crypto.password.PasswordEncoder; -import org.springframework.security.provisioning.InMemoryUserDetailsManager; import org.springframework.security.web.SecurityFilterChain; -import org.springframework.security.web.firewall.HttpFirewall; -import org.springframework.security.web.firewall.StrictHttpFirewall; - -import java.util.ArrayList; -import java.util.List; - -import static org.springframework.security.config.Customizer.withDefaults; @Configuration -@EnableWebSecurity -public class WebSecurityConfig { +public class WebSecurityConfig extends WebSecurityConfigurerAdapter { - @Bean - public HttpFirewall allowHttpMethod() { - List allowedMethods = new ArrayList(); - allowedMethods.add("GET"); - allowedMethods.add("POST"); - StrictHttpFirewall firewall = new StrictHttpFirewall(); - firewall.setAllowedHttpMethods(allowedMethods); - return firewall; + @Autowired + private UserDetailsService userDetailsService; + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth + .userDetailsService(userDetailsService) + .passwordEncoder(new BCryptPasswordEncoder()); } - @Bean - public WebSecurityCustomizer fireWall() { - return (web) -> web.httpFirewall(allowHttpMethod()); - } - - @Bean - public WebSecurityCustomizer ignoringCustomizer() { - return (web) -> web.ignoring().antMatchers("/resources/**", "/static/**"); - } - - @Bean - public WebSecurityCustomizer debugSecurity() { - return (web) -> web.debug(true); - } - - @Bean - public InMemoryUserDetailsManager userDetailsService() { - UserDetails user = User.withUsername("user") - .password(encoder().encode("userPass")) - .roles("ADMIN") - .build(); - return new InMemoryUserDetailsManager(user); - } - - @Bean - public PasswordEncoder encoder() { - return new BCryptPasswordEncoder(); - } - - @Bean - public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { - http.authorizeHttpRequests((authorize) -> authorize.antMatchers("/admin/**") - .hasRole("ADMIN") + @Override + protected void configure(HttpSecurity http) throws Exception { + http.authorizeRequests() + .antMatchers("/") + .permitAll() .anyRequest() - .permitAll()) - .httpBasic(withDefaults()) - .formLogin(withDefaults()) - .csrf(AbstractHttpConfigurer::disable); - return http.build(); + .authenticated() + .and() + .formLogin(); } - } From d7bb6bc0a77ae8e4645ee5a582d61a560ad42ded Mon Sep 17 00:00:00 2001 From: MohamedHelmyKassab <137485958+MohamedHelmyKassab@users.noreply.github.com> Date: Fri, 1 Dec 2023 02:59:17 +0200 Subject: [PATCH 161/228] This commit is related to BAEL-7113 (#15331) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This commit adds a new test class "RoundNumberToNearestMultipleUnitTest" that suggests multiplе mеthods for rounding up a numbеr to thе nеarеst multiplе of 5 in Java. --- .../RoundNumberToNearestMultipleUnitTest.java | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/roundnumbertonearestmultiple/RoundNumberToNearestMultipleUnitTest.java diff --git a/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/roundnumbertonearestmultiple/RoundNumberToNearestMultipleUnitTest.java b/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/roundnumbertonearestmultiple/RoundNumberToNearestMultipleUnitTest.java new file mode 100644 index 0000000000..24090be343 --- /dev/null +++ b/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/roundnumbertonearestmultiple/RoundNumberToNearestMultipleUnitTest.java @@ -0,0 +1,41 @@ +package com.baeldung.roundnumbertonearestmultiple; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class RoundNumberToNearestMultipleUnitTest { + + public static int originalNumber = 18; + public static int expectedRoundedNumber = 20; + public static int nearest = 5; + + @Test + public void givenNumber_whenUsingBasicMathOperations_thenRoundUpToNearestMultipleOf5() { + + int roundedNumber = (originalNumber % nearest == 0) ? originalNumber : ((originalNumber / nearest) + 1) * nearest; + assertEquals(expectedRoundedNumber, roundedNumber); + } + + @Test + public void givenNumber_whenUsingMathCeil_thenRoundUpToNearestMultipleOf5() { + + int roundedNumber = (int) (Math.ceil(originalNumber / (float) (nearest)) * nearest); + assertEquals(expectedRoundedNumber, roundedNumber); + } + + @Test + public void givenNumber_whenUsingMathRound_thenRoundUpToNearestMultipleOf5() { + + int roundedNumber = Math.round(originalNumber / (float) (nearest)) * nearest; + assertEquals(expectedRoundedNumber, roundedNumber); + } + + @Test + public void givenNumber_whenUsingMathFloor_thenRoundUpToNearestMultipleOf5() { + + int roundedNumber = (int) (Math.floor((double) (originalNumber + nearest / 2) / nearest) * nearest); + assertEquals(expectedRoundedNumber, roundedNumber); + } + +} From 671957da9b04903a6985460cc36f6b9555b1156f Mon Sep 17 00:00:00 2001 From: Mo Helmy <135069400+BenHelmyBen@users.noreply.github.com> Date: Fri, 1 Dec 2023 03:02:46 +0200 Subject: [PATCH 162/228] This PR is related to BAEL-6315 (#15337) * This commit is related to BAEL-6315 This commit aims to add two classes Contact and Person. * This commit is related to BAEL-6315 This commit aims to add a test class DeserializationUnitTest. --- .../com/baeldung/deserialization/Contact.java | 5 +++ .../com/baeldung/deserialization/Person.java | 5 +++ .../DeserializationUnitTest.java | 39 +++++++++++++++++++ 3 files changed, 49 insertions(+) create mode 100644 core-java-modules/core-java-20/src/main/java/com/baeldung/deserialization/Contact.java create mode 100644 core-java-modules/core-java-20/src/main/java/com/baeldung/deserialization/Person.java create mode 100644 core-java-modules/core-java-20/src/test/java/com/baeldung/deserialization/DeserializationUnitTest.java diff --git a/core-java-modules/core-java-20/src/main/java/com/baeldung/deserialization/Contact.java b/core-java-modules/core-java-20/src/main/java/com/baeldung/deserialization/Contact.java new file mode 100644 index 0000000000..80df1393af --- /dev/null +++ b/core-java-modules/core-java-20/src/main/java/com/baeldung/deserialization/Contact.java @@ -0,0 +1,5 @@ +package com.baeldung.deserialization; + +public record Contact(String email, String phone) { + // Constructor, getters, and other methods are automatically generated +} diff --git a/core-java-modules/core-java-20/src/main/java/com/baeldung/deserialization/Person.java b/core-java-modules/core-java-20/src/main/java/com/baeldung/deserialization/Person.java new file mode 100644 index 0000000000..38e3882668 --- /dev/null +++ b/core-java-modules/core-java-20/src/main/java/com/baeldung/deserialization/Person.java @@ -0,0 +1,5 @@ +package com.baeldung.deserialization; + +public record Person(String name, int age, String address, Contact contact) { + // Constructor, getters, and other methods are automatically generated +} \ No newline at end of file diff --git a/core-java-modules/core-java-20/src/test/java/com/baeldung/deserialization/DeserializationUnitTest.java b/core-java-modules/core-java-20/src/test/java/com/baeldung/deserialization/DeserializationUnitTest.java new file mode 100644 index 0000000000..1256505e0d --- /dev/null +++ b/core-java-modules/core-java-20/src/test/java/com/baeldung/deserialization/DeserializationUnitTest.java @@ -0,0 +1,39 @@ +package com.baeldung.deserialization; + +import com.google.gson.Gson; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +public class DeserializationUnitTest { + + @Test + public void givenJsonString_whenDeserialized_thenPersonRecordCreated() { + String json = "{\"name\":\"John Doe\",\"age\":30,\"address\":\"123 Main St\"}"; + + Person person = new Gson().fromJson(json, Person.class); + + assertEquals("John Doe", person.name()); + assertEquals(30, person.age()); + assertEquals("123 Main St", person.address()); + } + + @Test + public void givenNestedJsonString_whenDeserialized_thenPersonRecordCreated() { + String json = "{\"name\":\"John Doe\",\"age\":30,\"address\":\"123 Main St\",\"contact\":{\"email\":\"john.doe@example.com\",\"phone\":\"555-1234\"}}"; + + Person person = new Gson().fromJson(json, Person.class); + + assertNotNull(person); + assertEquals("John Doe", person.name()); + assertEquals(30, person.age()); + assertEquals("123 Main St", person.address()); + + Contact contact = person.contact(); + + assertNotNull(contact); + assertEquals("john.doe@example.com", contact.email()); + assertEquals("555-1234", contact.phone()); + } +} From 1f7efeddaf524f0d178214c55ef35e2265e509e6 Mon Sep 17 00:00:00 2001 From: Mikhail Polivakha <68962645+Mikhail2048@users.noreply.github.com> Date: Fri, 1 Dec 2023 04:07:18 +0300 Subject: [PATCH 163/228] BAEL-6953 implemented (#15304) * BAEL-6953 implemented * BAEL-6953 added live test * Fixed test --- .../gradle/wrapper/gradle-wrapper.jar | Bin 0 -> 62076 bytes pom.xml | 1 + spring-kafka-3/pom.xml | 36 +++++++++++ .../com/baeldung/spring/kafka/SomeData.java | 37 ++++++++++++ .../spring/kafka/ListenerConfiguration.java | 42 +++++++++++++ .../spring/kafka/ProducerConfiguration.java | 40 ++++++++++++ .../spring/kafka/TrustedPackagesLiveTest.java | 57 ++++++++++++++++++ 7 files changed, 213 insertions(+) create mode 100644 gradle-modules/gradle-7/toolchains-feature/gradle/wrapper/gradle-wrapper.jar create mode 100644 spring-kafka-3/pom.xml create mode 100644 spring-kafka-3/src/main/java/com/baeldung/spring/kafka/SomeData.java create mode 100644 spring-kafka-3/src/test/java/com/baeldung/spring/kafka/ListenerConfiguration.java create mode 100644 spring-kafka-3/src/test/java/com/baeldung/spring/kafka/ProducerConfiguration.java create mode 100644 spring-kafka-3/src/test/java/com/baeldung/spring/kafka/TrustedPackagesLiveTest.java diff --git a/gradle-modules/gradle-7/toolchains-feature/gradle/wrapper/gradle-wrapper.jar b/gradle-modules/gradle-7/toolchains-feature/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000000000000000000000000000000000..c1962a79e29d3e0ab67b14947c167a862655af9b GIT binary patch literal 62076 zcmb5VV{~QRw)Y#`wrv{~+qP{x72B%VwzFc}c2cp;N~)5ZbDrJayPv(!dGEd-##*zr z)#n-$y^sH|_dchh3@8{H5D*j;5D<{i*8l5IFJ|DjL!e)upfGNX(kojugZ3I`oH1PvW`wFW_ske0j@lB9bX zO;2)`y+|!@X(fZ1<2n!Qx*)_^Ai@Cv-dF&(vnudG?0CsddG_&Wtae(n|K59ew)6St z#dj7_(Cfwzh$H$5M!$UDd8=4>IQsD3xV=lXUq($;(h*$0^yd+b{qq63f0r_de#!o_ zXDngc>zy`uor)4A^2M#U*DC~i+dc<)Tb1Tv&~Ev@oM)5iJ4Sn#8iRw16XXuV50BS7 zdBL5Mefch(&^{luE{*5qtCZk$oFr3RH=H!c3wGR=HJ(yKc_re_X9pD` zJ;uxPzUfVpgU>DSq?J;I@a+10l0ONXPcDkiYcihREt5~T5Gb}sT0+6Q;AWHl`S5dV>lv%-p9l#xNNy7ZCr%cyqHY%TZ8Q4 zbp&#ov1*$#grNG#1vg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##kLKRN0uJuK250bXVU zwzT&n@30^dzKnlL^us;wClg?CKWEtiEb#zhPVx{PxFQiwEPp^C53zN21EdZAz?3D& zC6fK|_!S5Mq&0z;xWGLEv}!zjfpRg_orp7|fXMx=uP!@X`yT@5(N_Hza}p5fBk&|)J7fZ`NQ9Nz@5xT? zi?iV$q+bG!2LZUpF)>Yl!u;DEHV3!i{ipcJm_8Gj@Dac%N3|SQVGqRhrJ;WOR|CtrwzPTW^&$A6!A$E)h7xohm>hA8p{PUZ~ z_&zeg@OL3PxPtzkfsNZAqXCZ8Is7yQ+plm~8;}|~DEkv&f@?q5hB*OGQYXuwVQOp0 z?QQ`6qyp|-$47wjuV74IE_x2I17$+grwMBE^25d<5!lYhnszuh|5Yk;RB+Uk*hk=m zu73=E^7ul{40{A^?Rg^fq0ZfZO@C1HupR*_d;J>lkFv6&x&}4N;t}1T@2}~AC^<3b zA}RxFPPZe5R{_6dIN9N-GT29Oa}RzA2ekKuEVZbuMOB?Xf**`N5&m}?)TjigdY(rF z?~+a=`0);TlDa1j)1G`AfW? zRl883QPq=w zbB|bHEx%_u*$t@Yl#Vc;y*?2W^|^NJ)DmioQFr~1&>MSBL_b(YIpGWdDm3bT=Mgm1 e+h0K+-~H6qzyuy}`;+tYAZFmzUSVSYum1yJqxCBQ literal 0 HcmV?d00001 diff --git a/pom.xml b/pom.xml index 32b8e8c8c8..167509d2b3 100644 --- a/pom.xml +++ b/pom.xml @@ -867,6 +867,7 @@ spring-jersey spring-jinq spring-kafka-2 + spring-kafka-3 spring-kafka spring-katharsis spring-mobile diff --git a/spring-kafka-3/pom.xml b/spring-kafka-3/pom.xml new file mode 100644 index 0000000000..972412d18e --- /dev/null +++ b/spring-kafka-3/pom.xml @@ -0,0 +1,36 @@ + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + 4.0.0 + + spring-kafka-3 + jar + + spring-kafka-3 + + + + org.springframework.kafka + spring-kafka + + + com.fasterxml.jackson.core + jackson-databind + + + org.springframework.kafka + spring-kafka-test + test + + + + + 3.0.12 + + diff --git a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/SomeData.java b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/SomeData.java new file mode 100644 index 0000000000..eb2e57c33d --- /dev/null +++ b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/SomeData.java @@ -0,0 +1,37 @@ +package com.baeldung.spring.kafka; + +import java.time.Instant; + +public class SomeData { + + private String id; + private String type; + private String status; + private Instant timestamp; + + public SomeData() { + } + + public SomeData(String id, String type, String status, Instant timestamp) { + this.id = id; + this.type = type; + this.status = status; + this.timestamp = timestamp; + } + + public String getId() { + return id; + } + + public String getType() { + return type; + } + + public String getStatus() { + return status; + } + + public Instant getTimestamp() { + return timestamp; + } +} diff --git a/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/ListenerConfiguration.java b/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/ListenerConfiguration.java new file mode 100644 index 0000000000..e35b1ee415 --- /dev/null +++ b/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/ListenerConfiguration.java @@ -0,0 +1,42 @@ +package com.baeldung.spring.kafka; + +import java.util.Map; + +import org.apache.kafka.clients.consumer.ConsumerConfig; +import org.apache.kafka.common.serialization.StringDeserializer; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory; +import org.springframework.kafka.core.ConsumerFactory; +import org.springframework.kafka.core.DefaultKafkaConsumerFactory; +import org.springframework.kafka.support.serializer.JsonDeserializer; + +@Configuration +public class ListenerConfiguration { + + @Bean("messageListenerContainer") + public ConcurrentKafkaListenerContainerFactory messageListenerContainer() { + ConcurrentKafkaListenerContainerFactory container = new ConcurrentKafkaListenerContainerFactory<>(); + container.setConsumerFactory(someDataConsumerFactory()); + return container; + } + + @Bean + public ConsumerFactory someDataConsumerFactory() { + JsonDeserializer payloadJsonDeserializer = new JsonDeserializer<>(); + payloadJsonDeserializer.trustedPackages("com.baeldung.spring.kafka"); + return new DefaultKafkaConsumerFactory<>( + consumerConfigs(), + new StringDeserializer(), + payloadJsonDeserializer + ); + } + + @Bean + public Map consumerConfigs() { + return Map.of( + ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "PLAINTEXT://localhost:9092", + ConsumerConfig.GROUP_ID_CONFIG, "some-group-id" + ); + } +} \ No newline at end of file diff --git a/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/ProducerConfiguration.java b/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/ProducerConfiguration.java new file mode 100644 index 0000000000..7373424841 --- /dev/null +++ b/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/ProducerConfiguration.java @@ -0,0 +1,40 @@ +package com.baeldung.spring.kafka; + +import org.apache.kafka.clients.producer.ProducerConfig; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.kafka.core.DefaultKafkaProducerFactory; +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.kafka.core.ProducerFactory; +import org.springframework.kafka.support.serializer.JsonSerializer; +import org.springframework.kafka.support.serializer.StringOrBytesSerializer; + +import java.time.Instant; +import java.util.Map; + +@Configuration +public class ProducerConfiguration { + + @Bean + public KafkaTemplate kafkaTemplate() { + return new KafkaTemplate<>(producerFactory()); + } + + @Bean + public ProducerFactory producerFactory() { + JsonSerializer jsonSerializer = new JsonSerializer<>(); + jsonSerializer.setAddTypeInfo(true); + return new DefaultKafkaProducerFactory<>( + producerFactoryConfig(), + new StringOrBytesSerializer(), + jsonSerializer + ); + } + + @Bean + public Map producerFactoryConfig() { + return Map.of( + ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "PLAINTEXT://localhost:9092" + ); + } +} \ No newline at end of file diff --git a/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/TrustedPackagesLiveTest.java b/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/TrustedPackagesLiveTest.java new file mode 100644 index 0000000000..fa4b79cd65 --- /dev/null +++ b/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/TrustedPackagesLiveTest.java @@ -0,0 +1,57 @@ +package com.baeldung.spring.kafka; + +import java.time.Instant; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import org.apache.kafka.clients.producer.ProducerRecord; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.SpyBean; +import org.springframework.kafka.annotation.KafkaListener; +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.stereotype.Component; + +/** + * This test requires a running instance of kafka to be present + */ +@SpringBootTest +public class TrustedPackagesLiveTest { + + @Autowired + private KafkaTemplate kafkaTemplate; + + @SpyBean + TestConsumer testConsumer; + + @Test + void givenMessageInTheTopic_whenTypeInfoPackageIsTrusted_thenMessageIsSuccessfullyConsumed() throws InterruptedException { + CountDownLatch latch = new CountDownLatch(1); + + Mockito.doAnswer(invocationOnMock -> { + try { + latch.countDown(); + return invocationOnMock.callRealMethod(); + } catch (Exception e) { + return null; + } + }).when(testConsumer).onMessage(Mockito.any()); + + SomeData someData = new SomeData("1", "active", "sent", Instant.now()); + kafkaTemplate.send(new ProducerRecord<>("sourceTopic", null, someData)); + + Assertions.assertTrue(latch.await(20L, TimeUnit.SECONDS)); + } + + @Component + static class TestConsumer { + + @KafkaListener(topics = "sourceTopic", containerFactory = "messageListenerContainer") + public void onMessage(SomeData someData) { + + } + } +} From a58783707caf2a8b3c1d27f13393724c92a8b69d Mon Sep 17 00:00:00 2001 From: ovidiu-mihai98 <138307181+ovidiumihaitacu@users.noreply.github.com> Date: Thu, 16 Nov 2023 11:50:18 +0200 Subject: [PATCH 164/228] [BAEL-7067] Difference Between Entity and DTO --- .../entitydtodifferences/Application.java | 12 +++ .../controller/UserController.java | 39 ++++++++ .../entitydtodifferences/dto/BookDto.java | 30 ++++++ .../dto/UserCreationDto.java | 48 ++++++++++ .../dto/UserResponseDto.java | 48 ++++++++++ .../entitydtodifferences/entity/Book.java | 39 ++++++++ .../entitydtodifferences/entity/User.java | 90 ++++++++++++++++++ .../mapper/UserMapper.java | 34 +++++++ .../repository/UserRepository.java | 11 +++ .../ApplicationIntegrationTest.java | 15 +++ .../UserControllerIntegrationTest.java | 93 +++++++++++++++++++ .../entity/BookUnitTest.java | 19 ++++ .../entity/UserUnitTest.java | 51 ++++++++++ .../mapper/UserMapperUnitTest.java | 87 +++++++++++++++++ 14 files changed, 616 insertions(+) create mode 100644 spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/Application.java create mode 100644 spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/controller/UserController.java create mode 100644 spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/dto/BookDto.java create mode 100644 spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/dto/UserCreationDto.java create mode 100644 spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/dto/UserResponseDto.java create mode 100644 spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/entity/Book.java create mode 100644 spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/entity/User.java create mode 100644 spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/mapper/UserMapper.java create mode 100644 spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/repository/UserRepository.java create mode 100644 spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/entitydtodifferences/ApplicationIntegrationTest.java create mode 100644 spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/entitydtodifferences/controller/UserControllerIntegrationTest.java create mode 100644 spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/entitydtodifferences/entity/BookUnitTest.java create mode 100644 spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/entitydtodifferences/entity/UserUnitTest.java create mode 100644 spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/entitydtodifferences/mapper/UserMapperUnitTest.java diff --git a/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/Application.java b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/Application.java new file mode 100644 index 0000000000..4a780ac17a --- /dev/null +++ b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/Application.java @@ -0,0 +1,12 @@ +package com.baeldung.entitydtodifferences; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/controller/UserController.java b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/controller/UserController.java new file mode 100644 index 0000000000..66cecacd9b --- /dev/null +++ b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/controller/UserController.java @@ -0,0 +1,39 @@ +package com.baeldung.entitydtodifferences.controller; + +import java.util.List; +import java.util.stream.Collectors; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.baeldung.entitydtodifferences.dto.UserCreationDto; +import com.baeldung.entitydtodifferences.dto.UserResponseDto; +import com.baeldung.entitydtodifferences.mapper.UserMapper; +import com.baeldung.entitydtodifferences.repository.UserRepository; + +@RestController +@RequestMapping("/users") +public class UserController { + + private final UserRepository userRepository; + + public UserController(UserRepository userRepository) { + this.userRepository = userRepository; + } + + @GetMapping + public List getUsers() { + return userRepository.findAll() + .stream() + .map(UserMapper::toDto) + .collect(Collectors.toList()); + } + + @PostMapping + public UserResponseDto createUser(@RequestBody UserCreationDto userCreationDto) { + return UserMapper.toDto(userRepository.save(UserMapper.toEntity(userCreationDto))); + } +} diff --git a/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/dto/BookDto.java b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/dto/BookDto.java new file mode 100644 index 0000000000..a5ee25f105 --- /dev/null +++ b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/dto/BookDto.java @@ -0,0 +1,30 @@ +package com.baeldung.entitydtodifferences.dto; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class BookDto { + + @JsonProperty("NAME") + private final String name; + + @JsonProperty("AUTHOR") + private final String author; + + // Default constructor for Jackson deserialization + public BookDto() { + this(null, null); + } + + public BookDto(String name, String author) { + this.name = name; + this.author = author; + } + + public String getName() { + return name; + } + + public String getAuthor() { + return author; + } +} diff --git a/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/dto/UserCreationDto.java b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/dto/UserCreationDto.java new file mode 100644 index 0000000000..0859c042cf --- /dev/null +++ b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/dto/UserCreationDto.java @@ -0,0 +1,48 @@ +package com.baeldung.entitydtodifferences.dto; + +import java.util.List; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class UserCreationDto { + + @JsonProperty("FIRST_NAME") + private final String firstName; + + @JsonProperty("LAST_NAME") + private final String lastName; + + @JsonProperty("ADDRESS") + private final String address; + + @JsonProperty("BOOKS") + private final List books; + + // Default constructor for Jackson deserialization + public UserCreationDto() { + this(null, null, null, null); + } + + public UserCreationDto(String firstName, String lastName, String address, List books) { + this.firstName = firstName; + this.lastName = lastName; + this.address = address; + this.books = books; + } + + public String getFirstName() { + return firstName; + } + + public String getLastName() { + return lastName; + } + + public String getAddress() { + return address; + } + + public List getBooks() { + return books; + } +} diff --git a/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/dto/UserResponseDto.java b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/dto/UserResponseDto.java new file mode 100644 index 0000000000..910689dd41 --- /dev/null +++ b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/dto/UserResponseDto.java @@ -0,0 +1,48 @@ +package com.baeldung.entitydtodifferences.dto; + +import java.util.List; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class UserResponseDto { + + @JsonProperty("ID") + private final Long id; + + @JsonProperty("FIRST_NAME") + private final String firstName; + + @JsonProperty("LAST_NAME") + private final String lastName; + + @JsonProperty("BOOKS") + private final List books; + + // Default constructor for Jackson deserialization + public UserResponseDto() { + this(null, null, null, null); + } + + public UserResponseDto(Long id, String firstName, String lastName, List books) { + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + this.books = books; + } + + public Long getId() { + return id; + } + + public String getFirstName() { + return firstName; + } + + public String getLastName() { + return lastName; + } + + public List getBooks() { + return books; + } +} diff --git a/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/entity/Book.java b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/entity/Book.java new file mode 100644 index 0000000000..88e895467a --- /dev/null +++ b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/entity/Book.java @@ -0,0 +1,39 @@ +package com.baeldung.entitydtodifferences.entity; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "books") +public class Book { + + @Id + private String name; + private String author; + + // Default constructor for JPA deserialization + public Book() { + } + + public Book(String name, String author) { + this.name = name; + this.author = author; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/entity/User.java b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/entity/User.java new file mode 100644 index 0000000000..6a404e9f1f --- /dev/null +++ b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/entity/User.java @@ -0,0 +1,90 @@ +package com.baeldung.entitydtodifferences.entity; + +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import javax.persistence.CascadeType; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.OneToMany; +import javax.persistence.Table; + +@Entity +@Table(name = "users") +public class User { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + private String firstName; + private String lastName; + private String address; + + @OneToMany(cascade = CascadeType.ALL) + private List books; + + // Default constructor for JPA deserialization + public User() { + } + + public User(String firstName, String lastName, String address, List books) { + this.firstName = firstName; + this.lastName = lastName; + this.address = address; + this.books = books; + } + + public String getNameOfMostOwnedBook() { + Map bookOwnershipCount = books.stream() + .collect(Collectors.groupingBy(Book::getName, Collectors.counting())); + return bookOwnershipCount.entrySet() + .stream() + .max(Map.Entry.comparingByValue()) + .map(Map.Entry::getKey) + .orElse(null); + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + public List getBooks() { + return books; + } + + public void setBooks(List books) { + this.books = books; + } +} diff --git a/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/mapper/UserMapper.java b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/mapper/UserMapper.java new file mode 100644 index 0000000000..0c6899f98b --- /dev/null +++ b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/mapper/UserMapper.java @@ -0,0 +1,34 @@ +package com.baeldung.entitydtodifferences.mapper; + +import java.util.stream.Collectors; + +import com.baeldung.entitydtodifferences.dto.BookDto; +import com.baeldung.entitydtodifferences.dto.UserCreationDto; +import com.baeldung.entitydtodifferences.dto.UserResponseDto; +import com.baeldung.entitydtodifferences.entity.Book; +import com.baeldung.entitydtodifferences.entity.User; + +public class UserMapper { + + public static UserResponseDto toDto(User entity) { + return new UserResponseDto(entity.getId(), entity.getFirstName(), entity.getLastName(), entity.getBooks() + .stream() + .map(UserMapper::toDto) + .collect(Collectors.toList())); + } + + public static User toEntity(UserCreationDto dto) { + return new User(dto.getFirstName(), dto.getLastName(), dto.getAddress(), dto.getBooks() + .stream() + .map(UserMapper::toEntity) + .collect(Collectors.toList())); + } + + public static BookDto toDto(Book entity) { + return new BookDto(entity.getName(), entity.getAuthor()); + } + + public static Book toEntity(BookDto dto) { + return new Book(dto.getName(), dto.getAuthor()); + } +} diff --git a/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/repository/UserRepository.java b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/repository/UserRepository.java new file mode 100644 index 0000000000..4529de698e --- /dev/null +++ b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/repository/UserRepository.java @@ -0,0 +1,11 @@ +package com.baeldung.entitydtodifferences.repository; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import com.baeldung.entitydtodifferences.entity.User; + +@Repository +public interface UserRepository extends JpaRepository { + +} diff --git a/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/entitydtodifferences/ApplicationIntegrationTest.java b/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/entitydtodifferences/ApplicationIntegrationTest.java new file mode 100644 index 0000000000..839bb381ec --- /dev/null +++ b/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/entitydtodifferences/ApplicationIntegrationTest.java @@ -0,0 +1,15 @@ +package com.baeldung.entitydtodifferences; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class ApplicationIntegrationTest { + + @Test + public void contextLoads() { + } +} diff --git a/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/entitydtodifferences/controller/UserControllerIntegrationTest.java b/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/entitydtodifferences/controller/UserControllerIntegrationTest.java new file mode 100644 index 0000000000..83e359e378 --- /dev/null +++ b/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/entitydtodifferences/controller/UserControllerIntegrationTest.java @@ -0,0 +1,93 @@ +package com.baeldung.entitydtodifferences.controller; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.Arrays; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; + +import com.baeldung.entitydtodifferences.entity.Book; +import com.baeldung.entitydtodifferences.entity.User; +import com.baeldung.entitydtodifferences.repository.UserRepository; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +@SpringBootTest +@AutoConfigureMockMvc +public class UserControllerIntegrationTest { + + @Autowired + private MockMvc mockMvc; + + @Autowired + private UserRepository userRepository; + + @Autowired + private ObjectMapper objectMapper; + + @BeforeEach + public void beforeEach() { + userRepository.deleteAll(); + } + + @Test + public void givenUsersAreExisting_whenGetUsers_thenUsersAreReturned() throws Exception { + //given + Book book1 = new Book("Book1", "Author1"); + Book book2 = new Book("Book2", "Author2"); + User savedUser = userRepository.save(new User("John", "Doe", "123 Main St", Arrays.asList(book1, book2))); + String expectedJson = String.format( + "[{\"ID\":%s,\"FIRST_NAME\":\"John\",\"LAST_NAME\":\"Doe\",\"BOOKS\":[{\"NAME\":\"Book1\",\"AUTHOR\":\"Author1\"},{\"NAME\":\"Book2\",\"AUTHOR\":\"Author2\"}]}]", + savedUser.getId()); + //when + MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/users") + .contentType(MediaType.APPLICATION_JSON)) + .andReturn(); + //then + assertEquals(expectedJson, result.getResponse() + .getContentAsString()); + } + + @Test + public void givenValidUser_whenPostUser_thenUserIsCreated() throws Exception { + //given + String user = "{\"FIRST_NAME\":\"John\",\"LAST_NAME\":\"Doe\",\"BOOKS\":[{\"NAME\":\"Book1\",\"AUTHOR\":\"Author1\"},{\"NAME\":\"Book2\",\"AUTHOR\":\"Author2\"}]}"; + //when + MvcResult result = mockMvc.perform(MockMvcRequestBuilders.post("/users") + .content(user) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) + .andReturn(); + JsonNode responseJson = objectMapper.readTree(result.getResponse() + .getContentAsString()); + //then + assertEquals("John", responseJson.get("FIRST_NAME") + .asText()); + assertEquals("Doe", responseJson.get("LAST_NAME") + .asText()); + assertTrue(responseJson.has("BOOKS")); + JsonNode booksArray = responseJson.get("BOOKS"); + assertEquals(2, booksArray.size()); + assertEquals("Book1", booksArray.get(0) + .get("NAME") + .asText()); + assertEquals("Author1", booksArray.get(0) + .get("AUTHOR") + .asText()); + assertEquals("Book2", booksArray.get(1) + .get("NAME") + .asText()); + assertEquals("Author2", booksArray.get(1) + .get("AUTHOR") + .asText()); + } +} diff --git a/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/entitydtodifferences/entity/BookUnitTest.java b/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/entitydtodifferences/entity/BookUnitTest.java new file mode 100644 index 0000000000..60e229b7c9 --- /dev/null +++ b/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/entitydtodifferences/entity/BookUnitTest.java @@ -0,0 +1,19 @@ +package com.baeldung.entitydtodifferences.entity; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import org.junit.Test; + +public class BookUnitTest { + + @Test + public void whenBookInitialized_thenInitializedCorrectly() { + //when + Book book = new Book("Book1", "Author1"); + //then + assertNotNull(book); + assertEquals("Book1", book.getName()); + assertEquals("Author1", book.getAuthor()); + } +} diff --git a/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/entitydtodifferences/entity/UserUnitTest.java b/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/entitydtodifferences/entity/UserUnitTest.java new file mode 100644 index 0000000000..0d1efe7129 --- /dev/null +++ b/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/entitydtodifferences/entity/UserUnitTest.java @@ -0,0 +1,51 @@ +package com.baeldung.entitydtodifferences.entity; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + +import java.util.Arrays; +import java.util.Collections; + +import org.junit.Test; + +public class UserUnitTest { + + @Test + public void whenUserInitialized_thenInitializedCorrectly() { + //when + Book book1 = new Book("Book1", "Author1"); + Book book2 = new Book("Book2", "Author2"); + User user = new User("John", "Doe", "123 Main St", Arrays.asList(book1, book2)); + //then + assertNotNull(user); + assertEquals("John", user.getFirstName()); + assertEquals("Doe", user.getLastName()); + assertEquals("123 Main St", user.getAddress()); + assertEquals(2, user.getBooks() + .size()); + } + + @Test + public void givenUserOwningMultipleBooks_whenGetNameOfMostOwnedBook_thenComputedCorrectly() { + //given + Book book1 = new Book("Book1", "Author1"); + Book book2 = new Book("Book2", "Author2"); + Book book3 = new Book("Book2", "Author3"); + User user = new User("John", "Doe", "123 Main St", Arrays.asList(book1, book2, book3)); + //when + String mostOwnedBook = user.getNameOfMostOwnedBook(); + //then + assertEquals("Book2", mostOwnedBook); + } + + @Test + public void givenUserWithNoBooks_henGetNameOfMostOwnedBook_thenReturnedNull() { + //given + User user = new User("John", "Doe", "123 Main St", Collections.emptyList()); + //when + String mostOwnedBook = user.getNameOfMostOwnedBook(); + //then + assertNull(mostOwnedBook); + } +} diff --git a/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/entitydtodifferences/mapper/UserMapperUnitTest.java b/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/entitydtodifferences/mapper/UserMapperUnitTest.java new file mode 100644 index 0000000000..5154898877 --- /dev/null +++ b/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/entitydtodifferences/mapper/UserMapperUnitTest.java @@ -0,0 +1,87 @@ +package com.baeldung.entitydtodifferences.mapper; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.Arrays; +import java.util.List; + +import org.junit.Test; + +import com.baeldung.entitydtodifferences.dto.BookDto; +import com.baeldung.entitydtodifferences.dto.UserCreationDto; +import com.baeldung.entitydtodifferences.dto.UserResponseDto; +import com.baeldung.entitydtodifferences.entity.Book; +import com.baeldung.entitydtodifferences.entity.User; + +public class UserMapperUnitTest { + + @Test + public void givenUserEntity_whenMappedToDto_thenMappedCorrectly() { + //given + Book book1 = new Book("Book1", "Author1"); + Book book2 = new Book("Book2", "Author2"); + User user = new User("John", "Doe", "123 Main St", Arrays.asList(book1, book2)); + //when + UserResponseDto userDto = UserMapper.toDto(user); + //then + assertEquals(user.getId(), userDto.getId()); + assertEquals(user.getFirstName(), userDto.getFirstName()); + assertEquals(user.getLastName(), userDto.getLastName()); + List bookDtos = userDto.getBooks(); + assertEquals(2, bookDtos.size()); + assertEquals(book1.getName(), bookDtos.get(0) + .getName()); + assertEquals(book1.getAuthor(), bookDtos.get(0) + .getAuthor()); + assertEquals(book2.getName(), bookDtos.get(1) + .getName()); + assertEquals(book2.getAuthor(), bookDtos.get(1) + .getAuthor()); + } + + @Test + public void givenUserDto_whenMappedToEntity_thenMappedCorrectly() { + //given + BookDto bookDto1 = new BookDto("Book3", "Author3"); + BookDto bookDto2 = new BookDto("Book4", "Author4"); + UserCreationDto userDto = new UserCreationDto("Jane", "Doe", "456 Oak St", Arrays.asList(bookDto1, bookDto2)); + //when + User user = UserMapper.toEntity(userDto); + //then + assertEquals(user.getFirstName(), userDto.getFirstName()); + assertEquals(user.getLastName(), userDto.getLastName()); + assertEquals(user.getAddress(), userDto.getAddress()); + List books = user.getBooks(); + assertEquals(2, books.size()); + assertEquals(bookDto1.getName(), books.get(0) + .getName()); + assertEquals(bookDto1.getAuthor(), books.get(0) + .getAuthor()); + assertEquals(bookDto2.getName(), books.get(1) + .getName()); + assertEquals(bookDto2.getAuthor(), books.get(1) + .getAuthor()); + } + + @Test + public void givenBookEntity_whenMappedToDto_thenMappedCorrectly() { + //given + Book book = new Book("Book5", "Author5"); + //when + BookDto bookDto = UserMapper.toDto(book); + //then + assertEquals(book.getName(), bookDto.getName()); + assertEquals(book.getAuthor(), bookDto.getAuthor()); + } + + @Test + public void givenBookDto_whenMappedToEntity_thenMappedCorrectly() { + //given + BookDto bookDto = new BookDto("Book6", "Author6"); + //when + Book book = UserMapper.toEntity(bookDto); + //then + assertEquals(bookDto.getName(), book.getName()); + assertEquals(bookDto.getAuthor(), book.getAuthor()); + } +} From 720789d02679baac9f3e4d9dd3036c030124e190 Mon Sep 17 00:00:00 2001 From: michaelin007 Date: Fri, 1 Dec 2023 09:14:50 +0000 Subject: [PATCH 165/228] MismatchedInputException: Cannot deserialize instance --- .../mismatchedinputexception/Animals.java | 27 +++++++++++++ .../mismatchedinputexception/Book.java | 27 +++++++++++++ .../MismatchedinputExceptionUnitTest.java | 39 +++++++++++++++++++ 3 files changed, 93 insertions(+) create mode 100644 jackson-modules/jackson-exceptions/src/main/java/com/baeldung/mismatchedinputexception/Animals.java create mode 100644 jackson-modules/jackson-exceptions/src/main/java/com/baeldung/mismatchedinputexception/Book.java create mode 100644 jackson-modules/jackson-exceptions/src/test/java/com/baeldung/mismatchedinputexception/MismatchedinputExceptionUnitTest.java diff --git a/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/mismatchedinputexception/Animals.java b/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/mismatchedinputexception/Animals.java new file mode 100644 index 0000000000..1ad1014414 --- /dev/null +++ b/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/mismatchedinputexception/Animals.java @@ -0,0 +1,27 @@ +package com.baeldung.mismatchedinputexception; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class Animals { + + private final int id; + private String name; + + + public Animals(@JsonProperty("id") int id, @JsonProperty("name")String name) { + this.id = id; + this.name = name; + } + + public int getId() { + return id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/mismatchedinputexception/Book.java b/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/mismatchedinputexception/Book.java new file mode 100644 index 0000000000..28fe118ac5 --- /dev/null +++ b/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/mismatchedinputexception/Book.java @@ -0,0 +1,27 @@ +package com.baeldung.mismatchedinputexception; + +public class Book { + + private int id; + private String title; + + public Book(int id, String title) { + this.id = id; + this.title = title; + } + + public Book() { + } + + public int getId() { + return id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } +} diff --git a/jackson-modules/jackson-exceptions/src/test/java/com/baeldung/mismatchedinputexception/MismatchedinputExceptionUnitTest.java b/jackson-modules/jackson-exceptions/src/test/java/com/baeldung/mismatchedinputexception/MismatchedinputExceptionUnitTest.java new file mode 100644 index 0000000000..178ad1a8db --- /dev/null +++ b/jackson-modules/jackson-exceptions/src/test/java/com/baeldung/mismatchedinputexception/MismatchedinputExceptionUnitTest.java @@ -0,0 +1,39 @@ +package com.baeldung.mismatchedinputexception; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class MismatchedinputExceptionUnitTest { + + @Test + void givenJsonString_whenDeserializingToJavaObjectWithImmutableField_thenIdIsCorrect() throws JsonProcessingException { + String jsonString = "{\"id\":10,\"name\":\"Dog\"}"; + ObjectMapper mapper = new ObjectMapper(); + Animals animal = mapper.readValue(jsonString, Animals.class); + assertEquals(animal.getId(),10); + } + + @Test + void givenJsonString_whenDeserializingToBook_thenIdIsCorrect() throws JsonProcessingException { + String jsonString = "{\"id\":\"10\",\"title\":\"Harry Potter\"}"; + ObjectMapper mapper = new ObjectMapper(); + Book book = mapper.readValue(jsonString, Book.class); + assertEquals(book.getId(),10); + } + + + @Test + void givenJsonString_whenDeserializingToBookList_thenTitleIsCorrect() throws JsonProcessingException { + String jsonString = "[{\"id\":\"10\",\"title\":\"Harry Potter\"}]"; + ObjectMapper mapper = new ObjectMapper(); + List book = mapper.readValue(jsonString, new TypeReference>(){}); + assertEquals(book.get(0).getTitle(),"Harry Potter"); + } + +} \ No newline at end of file From c7118d9960e7734d63f3391404ba4f2087dbcafc Mon Sep 17 00:00:00 2001 From: panos-kakos <102670093+panos-kakos@users.noreply.github.com> Date: Fri, 1 Dec 2023 13:16:51 +0200 Subject: [PATCH 166/228] [JAVA-27541] Upgraded spring-quartz to spring boot 3 (#15322) --- spring-quartz/pom.xml | 4 ++-- .../baeldung/springquartz/basics/scheduler/QrtzScheduler.java | 2 +- .../springquartz/basics/scheduler/SpringQrtzScheduler.java | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/spring-quartz/pom.xml b/spring-quartz/pom.xml index e8919bfadb..ddae53f64f 100644 --- a/spring-quartz/pom.xml +++ b/spring-quartz/pom.xml @@ -11,9 +11,9 @@ com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../parent-boot-2 + ../parent-boot-3 diff --git a/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/QrtzScheduler.java b/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/QrtzScheduler.java index ccf9fca8c1..37bd82ef3b 100644 --- a/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/QrtzScheduler.java +++ b/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/QrtzScheduler.java @@ -6,7 +6,7 @@ import static org.quartz.TriggerBuilder.newTrigger; import java.io.IOException; -import javax.annotation.PostConstruct; +import jakarta.annotation.PostConstruct; import org.baeldung.springquartz.config.AutoWiringSpringBeanJobFactory; import org.quartz.*; diff --git a/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/SpringQrtzScheduler.java b/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/SpringQrtzScheduler.java index f824765efe..c113482c76 100644 --- a/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/SpringQrtzScheduler.java +++ b/spring-quartz/src/main/java/org/baeldung/springquartz/basics/scheduler/SpringQrtzScheduler.java @@ -1,6 +1,6 @@ package org.baeldung.springquartz.basics.scheduler; -import javax.annotation.PostConstruct; +import jakarta.annotation.PostConstruct; import javax.sql.DataSource; import org.baeldung.springquartz.config.AutoWiringSpringBeanJobFactory; From 6508331a74b68db3a1a02ca2ff214f060c30d6f7 Mon Sep 17 00:00:00 2001 From: panos-kakos <102670093+panos-kakos@users.noreply.github.com> Date: Fri, 1 Dec 2023 13:19:46 +0200 Subject: [PATCH 167/228] [JAVA-27538] Upgraded spring-shell to spring boot 3 (#15328) --- spring-shell/pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/spring-shell/pom.xml b/spring-shell/pom.xml index 24fe5b0fb6..bdd495b836 100644 --- a/spring-shell/pom.xml +++ b/spring-shell/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../parent-boot-2 + ../parent-boot-3 From ef76f798fb016a3f2899faf0be2715d7763ac863 Mon Sep 17 00:00:00 2001 From: Singh Harpal Date: Fri, 1 Dec 2023 17:51:41 +0530 Subject: [PATCH 168/228] JAVA-26769: Update/Migrate to new version of Junit4 --- core-java-modules/core-java-collections-maps-6/pom.xml | 2 +- core-java-modules/core-java-numbers-conversions/pom.xml | 2 +- maven-modules/dependency-exclusion/pom.xml | 2 +- microservices-modules/rest-express/pom.xml | 3 +-- 4 files changed, 4 insertions(+), 5 deletions(-) diff --git a/core-java-modules/core-java-collections-maps-6/pom.xml b/core-java-modules/core-java-collections-maps-6/pom.xml index 8c35dcee6e..0d1732edb4 100644 --- a/core-java-modules/core-java-collections-maps-6/pom.xml +++ b/core-java-modules/core-java-collections-maps-6/pom.xml @@ -40,7 +40,7 @@ junit junit - 4.13.1 + ${junit.version} test diff --git a/core-java-modules/core-java-numbers-conversions/pom.xml b/core-java-modules/core-java-numbers-conversions/pom.xml index d014675ead..43809e8453 100644 --- a/core-java-modules/core-java-numbers-conversions/pom.xml +++ b/core-java-modules/core-java-numbers-conversions/pom.xml @@ -27,7 +27,7 @@ junit junit - 4.13.2 + ${junit.version} test diff --git a/maven-modules/dependency-exclusion/pom.xml b/maven-modules/dependency-exclusion/pom.xml index 6e348377b0..6a491e552f 100644 --- a/maven-modules/dependency-exclusion/pom.xml +++ b/maven-modules/dependency-exclusion/pom.xml @@ -62,7 +62,7 @@ junit junit - 4.13 + ${junit.version} diff --git a/microservices-modules/rest-express/pom.xml b/microservices-modules/rest-express/pom.xml index 182d14cfbf..1b22bb8117 100644 --- a/microservices-modules/rest-express/pom.xml +++ b/microservices-modules/rest-express/pom.xml @@ -73,7 +73,7 @@ junit junit - ${junit4.version} + ${junit.version} jar test true @@ -143,7 +143,6 @@ 0.11.3 1.0 0.4.8 - 4.11 2.4.1 2.0 From 76a2939e7db4c9f374d29cb8d860c4e86047eb78 Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Fri, 1 Dec 2023 12:14:25 -0800 Subject: [PATCH 169/228] JAVA-27645 Check article code matches github (#15323) --- .../baeldung/keyword/InstanceOfUnitTest.java | 18 ++++++------ .../libraries/opencsv/Application.java | 28 +++++++++---------- .../opencsv/OpenCsvIntegrationTest.java | 14 +++++----- 3 files changed, 30 insertions(+), 30 deletions(-) diff --git a/core-java-modules/core-java-lang-operators/src/test/java/com/baeldung/keyword/InstanceOfUnitTest.java b/core-java-modules/core-java-lang-operators/src/test/java/com/baeldung/keyword/InstanceOfUnitTest.java index 6ba8ed024c..dc81a0290b 100644 --- a/core-java-modules/core-java-lang-operators/src/test/java/com/baeldung/keyword/InstanceOfUnitTest.java +++ b/core-java-modules/core-java-lang-operators/src/test/java/com/baeldung/keyword/InstanceOfUnitTest.java @@ -11,55 +11,55 @@ import static org.junit.jupiter.api.Assertions.*; public class InstanceOfUnitTest { @Test - void giveWhenInstanceIsCorrect_thenReturnTrue() { + void givenWhenInstanceIsCorrect_thenReturnTrue() { Ring ring = new Ring(); assertTrue(ring instanceof Round); } @Test - void giveWhenObjectIsInstanceOfType_thenReturnTrue() { + void givenWhenObjectIsInstanceOfType_thenReturnTrue() { Circle circle = new Circle(); assertTrue(circle instanceof Circle); } @Test - void giveWhenInstanceIsOfSubtype_thenReturnTrue() { + void givenWhenInstanceIsOfSubtype_thenReturnTrue() { Circle circle = new Circle(); assertTrue(circle instanceof Round); } @Test - void giveWhenTypeIsInterface_thenReturnTrue() { + void givenWhenTypeIsInterface_thenReturnTrue() { Circle circle = new Circle(); assertTrue(circle instanceof Shape); } @Test - void giveWhenTypeIsOfObjectType_thenReturnTrue() { + void givenWhenTypeIsOfObjectType_thenReturnTrue() { Thread thread = new Thread(); assertTrue(thread instanceof Object); } @Test - void giveWhenInstanceValueIsNull_thenReturnFalse() { + void givenWhenInstanceValueIsNull_thenReturnFalse() { Circle circle = null; assertFalse(circle instanceof Round); } @Test - void giveWhenComparingClassInDiffHierarchy_thenCompilationError() { + void givenWhenComparingClassInDiffHierarchy_thenCompilationError() { //assertFalse( circle instanceof Triangle); } @Test - void giveWhenStream_whenCastWithoutInstanceOfChk_thenGetException() { + void givenWhenStream_whenCastWithoutInstanceOfChk_thenGetException() { Stream roundStream = Stream.of(new Ring(), new Ring(), new Circle()); assertThrows(ClassCastException.class, () -> roundStream.map(it -> (Ring) it).collect(Collectors.toList())); } @Test - void giveWhenStream_whenCastAfterInstanceOfChk_thenGetExpectedResult() { + void givenWhenStream_whenCastAfterInstanceOfChk_thenGetExpectedResult() { Stream roundStream = Stream.of(new Ring(), new Ring(), new Circle()); List ringList = roundStream.filter(it -> it instanceof Ring).map(it -> (Ring) it).collect(Collectors.toList()); assertEquals(2, ringList.size()); diff --git a/libraries-data-io/src/main/java/com/baeldung/libraries/opencsv/Application.java b/libraries-data-io/src/main/java/com/baeldung/libraries/opencsv/Application.java index cee73f674e..e18277b328 100644 --- a/libraries-data-io/src/main/java/com/baeldung/libraries/opencsv/Application.java +++ b/libraries-data-io/src/main/java/com/baeldung/libraries/opencsv/Application.java @@ -14,52 +14,52 @@ import java.util.List; public class Application { // CSV Reader Examples - public static List readLineByLineSyncExample() throws Exception { + public static List readLineByLineExample() throws Exception { Path path = Helpers.twoColumnCsvPath(); return CsvReaderExamples.readLineByLine(path); } - public static List readAllLinesSyncExample() throws Exception { + public static List readAllLinesExample() throws Exception { Path path = Helpers.twoColumnCsvPath(); return CsvReaderExamples.readAllLines(path); } // CSV Writer Examples - public static String writeLineByLineSyncExample() throws Exception { + public static String writeLineByLineExample() throws Exception { Path path = Helpers.fileOutOnePath(); return CsvWriterExamples.writeLineByLine(Helpers.fourColumnCsvString(), path); } - public static String writeAllLinesSyncExample() throws Exception { + public static String writeAllLinesExample() throws Exception { Path path = Helpers.fileOutAllPath(); return CsvWriterExamples.writeAllLines(Helpers.fourColumnCsvString(), path); } // Bean Examples - public static List simpleSyncPositionBeanExample() throws Exception { + public static List simplePositionBeanExample() throws Exception { Path path = Helpers.twoColumnCsvPath(); return BeanExamples.beanBuilderExample(path, SimplePositionBean.class); } - public static List namedSyncColumnBeanExample() throws Exception { + public static List namedColumnBeanExample() throws Exception { Path path = Helpers.namedColumnCsvPath(); return BeanExamples.beanBuilderExample(path, NamedColumnBean.class); } - public static String writeSyncCsvFromBeanExample() throws Exception { + public static String writeCsvFromBeanExample() throws Exception { Path path = Helpers.fileOutBeanPath(); return BeanExamples.writeCsvFromBean(path); } public static void main(String[] args) { try { - simpleSyncPositionBeanExample(); - namedSyncColumnBeanExample(); - writeSyncCsvFromBeanExample(); - readLineByLineSyncExample(); - readAllLinesSyncExample(); - writeLineByLineSyncExample(); - writeAllLinesSyncExample(); + simplePositionBeanExample(); + namedColumnBeanExample(); + writeCsvFromBeanExample(); + readLineByLineExample(); + readAllLinesExample(); + writeLineByLineExample(); + writeAllLinesExample(); } catch (Exception e) { throw new RuntimeException("Error during csv processing", e); } diff --git a/libraries-data-io/src/test/java/com/baeldung/libraries/opencsv/OpenCsvIntegrationTest.java b/libraries-data-io/src/test/java/com/baeldung/libraries/opencsv/OpenCsvIntegrationTest.java index 6745b9be7f..c3c85c5baa 100644 --- a/libraries-data-io/src/test/java/com/baeldung/libraries/opencsv/OpenCsvIntegrationTest.java +++ b/libraries-data-io/src/test/java/com/baeldung/libraries/opencsv/OpenCsvIntegrationTest.java @@ -13,7 +13,7 @@ public class OpenCsvIntegrationTest { @Test public void givenSampleData_whenReadUsingPosition_thenContentsRead() throws Exception { - List values = Application.simpleSyncPositionBeanExample(); + List values = Application.simplePositionBeanExample(); assertThat(values) .extracting(Object::toString) @@ -28,7 +28,7 @@ public class OpenCsvIntegrationTest { @Test public void givenSampleData_whenReadUsingNamedColumn_thenContentsRead() throws Exception { - List values = Application.namedSyncColumnBeanExample(); + List values = Application.namedColumnBeanExample(); assertThat(values) .extracting(Object::toString) @@ -41,7 +41,7 @@ public class OpenCsvIntegrationTest { @Test public void givenSampleData_whenReadLineByLine_thenContentsRead() throws Exception { - List lineByLineContents = Application.readLineByLineSyncExample(); + List lineByLineContents = Application.readLineByLineExample(); assertThat(lineByLineContents) .containsExactly( @@ -56,7 +56,7 @@ public class OpenCsvIntegrationTest { @Test public void givenSampleData_whenReadAllLines_thenContentsRead() throws Exception { - List contents = Application.readAllLinesSyncExample(); + List contents = Application.readAllLinesExample(); assertThat(contents) .containsExactly( @@ -70,7 +70,7 @@ public class OpenCsvIntegrationTest { @Test public void givenSampleData_whenWriteCsvUsingBean_thenContentsWritten() throws Exception { - String contents = Application.writeSyncCsvFromBeanExample(); + String contents = Application.writeCsvFromBeanExample(); assertThat(contents.split(NEW_LINE)) .containsExactly( @@ -82,7 +82,7 @@ public class OpenCsvIntegrationTest { @Test public void givenSampleData_whenWriteCsvLineByLine_thenContentsWritten() throws Exception { - String contents = Application.writeLineByLineSyncExample(); + String contents = Application.writeLineByLineExample(); assertThat(contents.split(NEW_LINE)) .containsExactly( @@ -94,7 +94,7 @@ public class OpenCsvIntegrationTest { @Test public void givenSampleData_whenWriteCsvAllLines_thenContentsWritten() throws Exception { - String contents = Application.writeAllLinesSyncExample(); + String contents = Application.writeAllLinesExample(); assertThat(contents.split(NEW_LINE)) .containsExactly( From 0c7025b080732eedc94716cdfaceef634862b556 Mon Sep 17 00:00:00 2001 From: parthiv39731 <70740707+parthiv39731@users.noreply.github.com> Date: Sat, 2 Dec 2023 10:25:25 +0530 Subject: [PATCH 170/228] BAEL-7259: review comments implemented --- persistence-modules/java-harperdb/pom.xml | 6 +++++- pom.xml | 2 +- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/persistence-modules/java-harperdb/pom.xml b/persistence-modules/java-harperdb/pom.xml index 56b63948c9..318f4b7460 100644 --- a/persistence-modules/java-harperdb/pom.xml +++ b/persistence-modules/java-harperdb/pom.xml @@ -29,7 +29,7 @@ com.baeldung java-harperdb - 4.2 + ${haperdb-driver.version} system ${project.basedir}/lib/cdata.jdbc.harperdb.jar @@ -57,4 +57,8 @@ + + 4.2 + + \ No newline at end of file diff --git a/pom.xml b/pom.xml index 219fc19071..27fe5947dd 100644 --- a/pom.xml +++ b/pom.xml @@ -818,8 +818,8 @@ pdf performance-tests persistence-modules + persistence-modules/java-harperdb persistence-modules/spring-data-neo4j - persistence-modules/java-harperdb protobuffer quarkus-modules reactive-systems From c8973d8cf3fab40c82c9dca3eb9a18de209388b4 Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Sat, 2 Dec 2023 13:17:07 +0530 Subject: [PATCH 171/228] JAVA-27357 Improve core-java-os build time --- .../test/java/com/baeldung/example/soundapi/AppUnitTest.java | 2 +- .../java/com/baeldung/java9/process/ProcessApiUnitTest.java | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/core-java-modules/core-java-os/src/test/java/com/baeldung/example/soundapi/AppUnitTest.java b/core-java-modules/core-java-os/src/test/java/com/baeldung/example/soundapi/AppUnitTest.java index 27bc750d8a..849f71dc03 100644 --- a/core-java-modules/core-java-os/src/test/java/com/baeldung/example/soundapi/AppUnitTest.java +++ b/core-java-modules/core-java-os/src/test/java/com/baeldung/example/soundapi/AppUnitTest.java @@ -23,7 +23,7 @@ public class AppUnitTest { soundRecorder.build(af); try { soundRecorder.start(); - Thread.sleep(20000); + Thread.sleep(5000); soundRecorder.stop(); } catch (InterruptedException ex) { fail("Exception: " + ex); diff --git a/core-java-modules/core-java-os/src/test/java/com/baeldung/java9/process/ProcessApiUnitTest.java b/core-java-modules/core-java-os/src/test/java/com/baeldung/java9/process/ProcessApiUnitTest.java index c3f390d8ae..dae1a705ed 100644 --- a/core-java-modules/core-java-os/src/test/java/com/baeldung/java9/process/ProcessApiUnitTest.java +++ b/core-java-modules/core-java-os/src/test/java/com/baeldung/java9/process/ProcessApiUnitTest.java @@ -69,7 +69,7 @@ public class ProcessApiUnitTest { }); }); - Thread.sleep(10000); + Thread.sleep(5000); childProc = ProcessHandle.current().children(); childProc.forEach(procHandle -> { @@ -100,7 +100,7 @@ public class ProcessApiUnitTest { private void waistCPU() throws NoSuchAlgorithmException { ArrayList randArr = new ArrayList(4096); SecureRandom sr = SecureRandom.getInstanceStrong(); - Duration somecpu = Duration.ofMillis(4200L); + Duration somecpu = Duration.ofMillis(2000L); Instant end = Instant.now().plus(somecpu); while (Instant.now().isBefore(end)) { // System.out.println(sr.nextInt()); From 9b744641be519dd9e16ca73b11f25b918f0c3c17 Mon Sep 17 00:00:00 2001 From: panos-kakos Date: Sat, 2 Dec 2023 11:16:12 +0200 Subject: [PATCH 172/228] [JAVA-26711] --- .../src/main/resources/application.yml | 2 +- .../spring-boot-libraries/src/main/resources/schema.sql | 7 +++++++ 2 files changed, 8 insertions(+), 1 deletion(-) create mode 100644 spring-boot-modules/spring-boot-libraries/src/main/resources/schema.sql diff --git a/spring-boot-modules/spring-boot-libraries/src/main/resources/application.yml b/spring-boot-modules/spring-boot-libraries/src/main/resources/application.yml index 3477520208..03c24f7778 100644 --- a/spring-boot-modules/spring-boot-libraries/src/main/resources/application.yml +++ b/spring-boot-modules/spring-boot-libraries/src/main/resources/application.yml @@ -1,6 +1,6 @@ spring: datasource: driverClassName: org.h2.Driver - url: jdbc:h2:mem:shedlock_DB;INIT=CREATE SCHEMA IF NOT EXISTS shedlock;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE + url: jdbc:h2:mem:shedlock_db;INIT=CREATE SCHEMA IF NOT EXISTS shedlock;DATABASE_TO_UPPER=false;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE username: sa password: diff --git a/spring-boot-modules/spring-boot-libraries/src/main/resources/schema.sql b/spring-boot-modules/spring-boot-libraries/src/main/resources/schema.sql new file mode 100644 index 0000000000..d5a5d51b74 --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries/src/main/resources/schema.sql @@ -0,0 +1,7 @@ +CREATE TABLE IF NOT EXISTS shedlock( + name VARCHAR(64) NOT NULL, + lock_until TIMESTAMP NOT NULL, + locked_at TIMESTAMP NOT NULL, + locked_by VARCHAR(255) NOT NULL, + PRIMARY KEY (name) +); \ No newline at end of file From cf033c3934545e5327e0e40e06a58c836b5985e8 Mon Sep 17 00:00:00 2001 From: Geoffrey De Smet Date: Sat, 2 Dec 2023 12:01:10 +0100 Subject: [PATCH 173/228] rename and improve test whenSolve_thenScoreIsOptimalAndAllShiftsAssigned --- .../baeldung/timefoldsolver/ShiftScheduleSolverUnitTest.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleSolverUnitTest.java b/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleSolverUnitTest.java index 8b57fb42b6..f0cf126236 100644 --- a/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleSolverUnitTest.java +++ b/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleSolverUnitTest.java @@ -11,6 +11,7 @@ import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import ai.timefold.solver.core.api.score.buildin.hardsoft.HardSoftScore; import ai.timefold.solver.core.api.solver.Solver; import ai.timefold.solver.core.api.solver.SolverFactory; import ai.timefold.solver.core.config.solver.SolverConfig; @@ -21,7 +22,7 @@ public class ShiftScheduleSolverUnitTest { private static final Logger logger = LoggerFactory.getLogger(ShiftScheduleSolverUnitTest.class); @Test - public void solve() { + public void whenSolve_thenScoreIsOptimalAndAllShiftsAssigned() { SolverFactory solverFactory = SolverFactory.create(new SolverConfig().withSolutionClass(ShiftSchedule.class) .withEntityClasses(Shift.class) .withConstraintProviderClass(ShiftScheduleConstraintProvider.class) @@ -32,6 +33,7 @@ public class ShiftScheduleSolverUnitTest { ShiftSchedule problem = loadProblem(); ShiftSchedule solution = solver.solve(problem); + assertThat(solution.getScore()).isEqualTo(HardSoftScore.ZERO); assertThat(solution.getShifts().size()).isNotZero(); for (Shift shift : solution.getShifts()) { assertThat(shift.getEmployee()).isNotNull(); From 9e8f67ad03ba65f772f390ff6b1035353742091f Mon Sep 17 00:00:00 2001 From: Geoffrey De Smet Date: Sat, 2 Dec 2023 12:03:19 +0100 Subject: [PATCH 174/228] Improve forEachUniquePair comment further --- .../timefoldsolver/ShiftScheduleConstraintProviderUnitTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleConstraintProviderUnitTest.java b/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleConstraintProviderUnitTest.java index fbe6ebccaf..2f929ace34 100644 --- a/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleConstraintProviderUnitTest.java +++ b/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleConstraintProviderUnitTest.java @@ -21,7 +21,7 @@ class ShiftScheduleConstraintProviderUnitTest { constraintVerifier.verifyThat(ShiftScheduleConstraintProvider::atMostOneShiftPerDay) .given(ann, new Shift(MONDAY.atTime(6, 0), MONDAY.atTime(14, 0), null, ann), new Shift(MONDAY.atTime(14, 0), MONDAY.atTime(22, 0), null, ann)) // Penalizes by 2 because both {shiftA, shiftB} and {shiftB, shiftA} match. - // To avoid that, use forEachUniquePair() in the constraint instead of forEach().join() in the implementation. + // To avoid that, use forEachUniquePair(Shift) instead of forEach(Shift).join(Shift) in ShiftScheduleConstraintProvider.atMostOneShiftPerDay(). .penalizesBy(2); } From f2adeb59566c6e9660004e2afc0bba8b9108d40b Mon Sep 17 00:00:00 2001 From: Geoffrey De Smet Date: Sat, 2 Dec 2023 20:20:40 +0100 Subject: [PATCH 175/228] BDD style --- .../ShiftScheduleConstraintProviderUnitTest.java | 8 ++++---- .../timefoldsolver/ShiftScheduleSolverUnitTest.java | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleConstraintProviderUnitTest.java b/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleConstraintProviderUnitTest.java index 2f929ace34..c8ec5b53c4 100644 --- a/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleConstraintProviderUnitTest.java +++ b/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleConstraintProviderUnitTest.java @@ -16,7 +16,7 @@ class ShiftScheduleConstraintProviderUnitTest { ShiftSchedule.class, Shift.class); @Test - void whenTwoShiftsOnOneDay_thenPenalize() { + void givenTwoShiftsOnOneDay_whenApplyingAtMostOneShiftPerDayConstraint_thenPenalize() { Employee ann = new Employee("Ann", null); constraintVerifier.verifyThat(ShiftScheduleConstraintProvider::atMostOneShiftPerDay) .given(ann, new Shift(MONDAY.atTime(6, 0), MONDAY.atTime(14, 0), null, ann), new Shift(MONDAY.atTime(14, 0), MONDAY.atTime(22, 0), null, ann)) @@ -26,7 +26,7 @@ class ShiftScheduleConstraintProviderUnitTest { } @Test - void whenTwoShiftsOnDifferentDays_thenDoNotPenalize() { + void givenTwoShiftsOnDifferentDays_whenApplyingAtMostOneShiftPerDayConstraint_thenDoNotPenalize() { Employee ann = new Employee("Ann", null); constraintVerifier.verifyThat(ShiftScheduleConstraintProvider::atMostOneShiftPerDay) .given(ann, new Shift(MONDAY.atTime(6, 0), MONDAY.atTime(14, 0), null, ann), new Shift(TUESDAY.atTime(14, 0), TUESDAY.atTime(22, 0), null, ann)) @@ -34,7 +34,7 @@ class ShiftScheduleConstraintProviderUnitTest { } @Test - void whenEmployeeLacksRequiredSkill_thenPenalize() { + void givenEmployeeLacksRequiredSkill_whenApplyingRequiredSkillConstraint_thenPenalize() { Employee ann = new Employee("Ann", Set.of("Waiter")); constraintVerifier.verifyThat(ShiftScheduleConstraintProvider::requiredSkill) .given(ann, new Shift(MONDAY.atTime(6, 0), MONDAY.atTime(14, 0), "Cook", ann)) @@ -42,7 +42,7 @@ class ShiftScheduleConstraintProviderUnitTest { } @Test - void whenEmployeeHasRequiredSkill_thenDoNotPenalize() { + void givenEmployeeHasRequiredSkill_whenApplyingRequiredSkillConstraint_thenDoNotPenalize() { Employee ann = new Employee("Ann", Set.of("Waiter")); constraintVerifier.verifyThat(ShiftScheduleConstraintProvider::requiredSkill) .given(ann, new Shift(MONDAY.atTime(6, 0), MONDAY.atTime(14, 0), "Waiter", ann)) diff --git a/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleSolverUnitTest.java b/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleSolverUnitTest.java index f0cf126236..873ce1a853 100644 --- a/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleSolverUnitTest.java +++ b/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleSolverUnitTest.java @@ -22,7 +22,7 @@ public class ShiftScheduleSolverUnitTest { private static final Logger logger = LoggerFactory.getLogger(ShiftScheduleSolverUnitTest.class); @Test - public void whenSolve_thenScoreIsOptimalAndAllShiftsAssigned() { + public void given3Employees5Shifts_whenSolve_thenScoreIsOptimalAndAllShiftsAssigned() { SolverFactory solverFactory = SolverFactory.create(new SolverConfig().withSolutionClass(ShiftSchedule.class) .withEntityClasses(Shift.class) .withConstraintProviderClass(ShiftScheduleConstraintProvider.class) From d8c84e0ea2546fcd6b34e441ebc7f46a80b7c7ab Mon Sep 17 00:00:00 2001 From: Michael Pratt Date: Sat, 2 Dec 2023 19:05:17 -0700 Subject: [PATCH 176/228] [BAEL-7170] Examples of colon character in Java (#15298) --- .../baeldung/colonexamples/ColonExamples.java | 178 ++++++++++++++++++ 1 file changed, 178 insertions(+) create mode 100644 core-java-modules/core-java-lang-operators-2/src/main/java/com/baeldung/colonexamples/ColonExamples.java diff --git a/core-java-modules/core-java-lang-operators-2/src/main/java/com/baeldung/colonexamples/ColonExamples.java b/core-java-modules/core-java-lang-operators-2/src/main/java/com/baeldung/colonexamples/ColonExamples.java new file mode 100644 index 0000000000..873e28c3f6 --- /dev/null +++ b/core-java-modules/core-java-lang-operators-2/src/main/java/com/baeldung/colonexamples/ColonExamples.java @@ -0,0 +1,178 @@ +package com.baeldung.colonexamples; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.sql.Connection; +import java.util.*; +import java.util.stream.Collectors; + +/** + * Examples of the different ways Java uses the colon (:) character. + */ +public class ColonExamples { + + private final static Logger LOG = LoggerFactory.getLogger(ColonExamples.class); + + public void example1_enhancedForLoop() { + + // Original style + for(int i = 0; i < 10; i++) { + // do something + } + + // Using enhanced for loop + int[] numbers = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9}; + for(int i : numbers) { + // do something + } + + // Using List instead of array + List numbersList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9); + for(Integer i : numbersList) { + // do something + } + } + + public void example2_switchStatement(String animal) { + + // Original style + if(animal.equals("cat")) { + System.out.println("meow"); + } + else if(animal.equals("lion")) { + System.out.println("roar"); + } + else if(animal.equals("dog") || animal.equals("seal")) { + System.out.println("bark"); + } + else { + System.out.println("unknown"); + } + + // Using switch statement + switch(animal) { + case "cat": + System.out.println("meow"); + break; + case "lion": + System.out.println("roar"); + break; + case "dog": + case "seal": + System.out.println("bark"); + break; + default: + System.out.println("unknown"); + } + } + + public void example3_labels() { + + // For loops without labels + for(int i = 0; i < 10; i++) { + for (int j = 0; j < 10; j++) { + if (checkSomeCondition()) { + break; + } + } + } + + outterLoop: for(int i = 0; i < 10; i++) { + innerLoop: for (int j = 0; j < 10; j++) { + if (checkSomeCondition()) { + break outterLoop; + } + } + } + } + + public void example4_ternaryOperator() { + + // Original way using if/else + int x; + if(checkSomeCondition()) { + x = 1; + } + else { + x = 2; + } + + // Using ternary operator + x = checkSomeCondition() ? 1 : 2; + + // Using with other statements + boolean remoteCallResult = callRemoteApi(); + LOG.info(String.format( + "The result of the remote API call %s successful", + remoteCallResult ? "was" : "was not" + )); + } + + public void example5_methodReferences() { + // Original way without lambdas and method references + List names = Arrays.asList("ross", "joey", "chandler"); + List upperCaseNames = new ArrayList<>(); + for(String name : names) { + upperCaseNames.add(name.toUpperCase()); + } + + // Using method reference with stream map operation + List petNames = Arrays.asList("ross", "joey", "chandler"); + List petUpperCaseNames = petNames + .stream() + .map(String::toUpperCase) + .collect(Collectors.toList()); + + // Method reference with stream filter + List pets = Arrays.asList(new Cat(), new Dog(), new Parrot()); + List onlyDogs = pets + .stream() + .filter(Dog.class::isInstance) + .collect(Collectors.toList()); + + // Method reference with constructors + Set onlyDogsSet = pets + .stream() + .filter(Dog.class::isInstance) + .collect(Collectors.toCollection(TreeSet::new)); + } + + public void example6_asserttion() { + // Original way without assertions + Connection conn = getConnection(); + if(conn == null) { + throw new RuntimeException("Connection is null"); + } + + // Using assert keyword + assert getConnection() != null : "Connection is null"; + } + + private boolean checkSomeCondition() { + return new Random().nextBoolean(); + } + + private boolean callRemoteApi() { + return new Random().nextBoolean(); + } + + private Connection getConnection() { + return null; + } + + private static interface Animal { + + } + private static class Dog implements Animal { + + } + + private static class Cat implements Animal { + + } + + private static class Parrot implements Animal { + + } +} From 722180e2a84c2d445ba9d9fa75d8da45a5e2a547 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Sun, 3 Dec 2023 11:03:41 +0800 Subject: [PATCH 177/228] Update README.md [skip ci] --- gradle-modules/gradle-7/README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/gradle-modules/gradle-7/README.md b/gradle-modules/gradle-7/README.md index fe05a4b9bc..c452ee8b33 100644 --- a/gradle-modules/gradle-7/README.md +++ b/gradle-modules/gradle-7/README.md @@ -5,4 +5,5 @@ - [Working With Multiple Repositories in Gradle](https://www.baeldung.com/java-gradle-multiple-repositories) - [Different Dependency Version Declarations in Gradle](https://www.baeldung.com/gradle-different-dependency-version-declarations) - [Generating Javadoc With Gradle](https://www.baeldung.com/java-gradle-javadoc) -- [Generating WSDL Stubs With Gradle](https://www.baeldung.com/java-gradle-create-wsdl-stubs) \ No newline at end of file +- [Generating WSDL Stubs With Gradle](https://www.baeldung.com/java-gradle-create-wsdl-stubs) +- [Gradle Proxy Configuration](https://www.baeldung.com/gradle-proxy-configuration) From d080d2f9f7413f3e8d4f9c999e100f84f732d50c Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Sun, 3 Dec 2023 11:11:07 +0800 Subject: [PATCH 178/228] Update README.md [skip ci] --- core-java-modules/core-java-lang-6/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-lang-6/README.md b/core-java-modules/core-java-lang-6/README.md index 91c0e5212c..fe79a8ecd4 100644 --- a/core-java-modules/core-java-lang-6/README.md +++ b/core-java-modules/core-java-lang-6/README.md @@ -9,3 +9,4 @@ This module contains articles about core features in the Java language - [Get a Random Element From a Set in Java](https://www.baeldung.com/java-set-draw-sample) - [Stop Executing Further Code in Java](https://www.baeldung.com/java-stop-running-code) - [Using the Apache Commons Lang 3 for Comparing Objects in Java](https://www.baeldung.com/java-apache-commons-lang-3-compare-objects) +- [Return First Non-null Value in Java](https://www.baeldung.com/java-first-non-null) From 894d87b029508d9d4f2d60194cc477964bdfa3bc Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Sun, 3 Dec 2023 11:13:25 +0800 Subject: [PATCH 179/228] Update README.md [skip ci] --- core-java-modules/core-java-security-4/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-security-4/README.md b/core-java-modules/core-java-security-4/README.md index 236715713b..3c910e50be 100644 --- a/core-java-modules/core-java-security-4/README.md +++ b/core-java-modules/core-java-security-4/README.md @@ -5,4 +5,5 @@ This module contains articles about core Java Security ### Relevant Articles: - [Check if Certificate Is Self-Signed or CA-Signed With Java](https://www.baeldung.com/java-check-certificate-sign) - [Extract CN From X509 Certificate in Java](https://www.baeldung.com/java-extract-common-name-x509-certificate) +- [Check Certificate Name and Alias in Keystore File](https://www.baeldung.com/java-keystore-check-certificate-name-alias) - More articles: [[<-- prev]](/core-java-modules/core-java-security-3) From 2e27265f5a71bb20523c8a5feaf49a0b6ff6512d Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Sun, 3 Dec 2023 11:18:44 +0800 Subject: [PATCH 180/228] Update README.md [skip ci] --- core-java-modules/core-java-collections-maps-7/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core-java-modules/core-java-collections-maps-7/README.md b/core-java-modules/core-java-collections-maps-7/README.md index c9f39dd2fa..7e16f2503d 100644 --- a/core-java-modules/core-java-collections-maps-7/README.md +++ b/core-java-modules/core-java-collections-maps-7/README.md @@ -4,5 +4,5 @@ - [How to Write Hashmap to CSV File](https://www.baeldung.com/java-write-hashmap-csv) - [How to Get First or Last Entry From a LinkedHashMap in Java](https://www.baeldung.com/java-linkedhashmap-first-last-key-value-pair) - [How to Write and Read a File with a Java HashMap](https://www.baeldung.com/java-hashmap-write-read-file) -- [Limiting the Max Size of a HashMap in Java](https://www.baeldung.com/java-hashmap-max-size) -- More articles: [[<-- prev]](/core-java-modules/core-java-collections-maps-6) \ No newline at end of file +- [Limiting the Max Size of a HashMap in Java](https://www.baeldung.com/java-hashmap-size-bound) +- More articles: [[<-- prev]](/core-java-modules/core-java-collections-maps-6) From 3327571ab92e88f573dff57b4bc5928692d5f4d8 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Sun, 3 Dec 2023 11:20:34 +0800 Subject: [PATCH 181/228] Update README.md [skip ci] --- spring-scheduling/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-scheduling/README.md b/spring-scheduling/README.md index 4ee306c0e0..4c42c60c37 100644 --- a/spring-scheduling/README.md +++ b/spring-scheduling/README.md @@ -5,3 +5,4 @@ - [How To Do @Async in Spring](https://www.baeldung.com/spring-async) - [Conditionally Enable Scheduled Jobs in Spring](https://www.baeldung.com/spring-scheduled-enabled-conditionally) - [Remote Debugging with IntelliJ IDEA](https://www.baeldung.com/intellij-remote-debugging) +- [Setup Asynchronous Retry Mechanism in Spring](https://www.baeldung.com/spring-async-retry) From cf341070d7e62f51eb56e3f90741a930fafde874 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Sun, 3 Dec 2023 13:59:00 +0800 Subject: [PATCH 182/228] Update README.md [skip ci] --- spring-boot-modules/spring-boot-mvc-5/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-boot-modules/spring-boot-mvc-5/README.md b/spring-boot-modules/spring-boot-mvc-5/README.md index 782adb7b34..c72d72c84f 100644 --- a/spring-boot-modules/spring-boot-mvc-5/README.md +++ b/spring-boot-modules/spring-boot-mvc-5/README.md @@ -5,3 +5,4 @@ This module contains articles about Spring Web MVC in Spring Boot projects. ### Relevant Articles: - [Enable and Disable Endpoints at Runtime With Spring Boot](https://www.baeldung.com/spring-boot-enable-disable-endpoints-at-runtime) - [Extracting a Custom Header From the Request](https://www.baeldung.com/spring-extract-custom-header-request) +- [Modify Request Body Before Reaching Controller in Spring Boot](https://www.baeldung.com/spring-boot-change-request-body-before-controller) From 3081399bd2a83b9f904d1fe085084214ea5871e8 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Sun, 3 Dec 2023 14:02:45 +0800 Subject: [PATCH 183/228] Update README.md [skip ci] --- core-java-modules/core-java-uuid/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-uuid/README.md b/core-java-modules/core-java-uuid/README.md index bd7bd9d9da..a32c1ae04f 100644 --- a/core-java-modules/core-java-uuid/README.md +++ b/core-java-modules/core-java-uuid/README.md @@ -6,3 +6,4 @@ - [Validate UUID String in Java](https://www.baeldung.com/java-validate-uuid-string) - [Generate the Same UUID From a String in Java](https://www.baeldung.com/java-generate-same-uuid-from-string) - [Generating Time Based UUIDs](https://www.baeldung.com/java-generating-time-based-uuids) +- [Generating Unique Positive long Using UUID in Java](https://www.baeldung.com/java-uuid-unique-long-generation) From f53d91745449f1467d49acdc07c0b039d9d6bf9c Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Sun, 3 Dec 2023 14:07:32 +0800 Subject: [PATCH 184/228] Update README.md [skip ci] --- core-java-modules/core-java-collections-maps-7/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-collections-maps-7/README.md b/core-java-modules/core-java-collections-maps-7/README.md index 7e16f2503d..b4ef933ab8 100644 --- a/core-java-modules/core-java-collections-maps-7/README.md +++ b/core-java-modules/core-java-collections-maps-7/README.md @@ -5,4 +5,5 @@ - [How to Get First or Last Entry From a LinkedHashMap in Java](https://www.baeldung.com/java-linkedhashmap-first-last-key-value-pair) - [How to Write and Read a File with a Java HashMap](https://www.baeldung.com/java-hashmap-write-read-file) - [Limiting the Max Size of a HashMap in Java](https://www.baeldung.com/java-hashmap-size-bound) +- [How to Sort LinkedHashMap By Values in Java](https://www.baeldung.com/java-sort-linkedhashmap-using-values) - More articles: [[<-- prev]](/core-java-modules/core-java-collections-maps-6) From 5eba53af3876c06c9c4357f435505cce60f00db8 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Sun, 3 Dec 2023 14:11:04 +0800 Subject: [PATCH 185/228] Update README.md [skip ci] --- core-java-modules/core-java-datetime-conversion/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-datetime-conversion/README.md b/core-java-modules/core-java-datetime-conversion/README.md index c7ba333222..f30a21f84c 100644 --- a/core-java-modules/core-java-datetime-conversion/README.md +++ b/core-java-modules/core-java-datetime-conversion/README.md @@ -11,3 +11,4 @@ This module contains articles about converting between Java date and time object - [Conversion From 12-Hour Time to 24-Hour Time in Java](https://www.baeldung.com/java-convert-time-format) - [Convert Epoch Time to LocalDate and LocalDateTime](https://www.baeldung.com/java-convert-epoch-localdate) - [Convert Timestamp String to Long in Java](https://www.baeldung.com/java-convert-timestamp-string-long) +- [Convert Long Timestamp to LocalDateTime in Java](https://www.baeldung.com/java-convert-long-timestamp-localdatetime) From 0adcb51cc10771d439ec813e30e944184657f8e8 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Sun, 3 Dec 2023 14:13:05 +0800 Subject: [PATCH 186/228] Update README.md [skip ci] --- core-java-modules/core-java-collections-maps-7/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-collections-maps-7/README.md b/core-java-modules/core-java-collections-maps-7/README.md index b4ef933ab8..73b36394a3 100644 --- a/core-java-modules/core-java-collections-maps-7/README.md +++ b/core-java-modules/core-java-collections-maps-7/README.md @@ -6,4 +6,5 @@ - [How to Write and Read a File with a Java HashMap](https://www.baeldung.com/java-hashmap-write-read-file) - [Limiting the Max Size of a HashMap in Java](https://www.baeldung.com/java-hashmap-size-bound) - [How to Sort LinkedHashMap By Values in Java](https://www.baeldung.com/java-sort-linkedhashmap-using-values) +- [How to Increment a Map Value in Java](https://www.baeldung.com/java-increment-map-value) - More articles: [[<-- prev]](/core-java-modules/core-java-collections-maps-6) From 9b5f00295233df9e7f79dc5f3fad8a1b5aa0f8c0 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Sun, 3 Dec 2023 14:14:17 +0800 Subject: [PATCH 187/228] Update README.md [skip ci] --- javafx/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/javafx/README.md b/javafx/README.md index 7db1478129..d6ea5b226f 100644 --- a/javafx/README.md +++ b/javafx/README.md @@ -7,4 +7,4 @@ This module contains articles about JavaFX. - [Introduction to JavaFx](https://www.baeldung.com/javafx) - [Display Custom Items in JavaFX ListView](https://www.baeldung.com/javafx-listview-display-custom-items) - [Adding EventHandler to JavaFX Button](https://www.baeldung.com/javafx-button-eventhandler) - +- [How to Use a Custom Font in Java](https://www.baeldung.com/java-custom-font) From 692f3b201a8a081664963b039a27ea41f3e5a318 Mon Sep 17 00:00:00 2001 From: michaelin007 Date: Sun, 3 Dec 2023 07:19:26 +0000 Subject: [PATCH 188/228] Final Static Variables in Java --- .../java/com/baeldung/finalstatic/Bike.java | 14 ++++++++++ .../baeldung/finalstatic/BikeUnitTest.java | 28 +++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 core-java-modules/core-java-lang-6/src/main/java/com/baeldung/finalstatic/Bike.java create mode 100644 core-java-modules/core-java-lang-6/src/test/java/com/baeldung/finalstatic/BikeUnitTest.java diff --git a/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/finalstatic/Bike.java b/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/finalstatic/Bike.java new file mode 100644 index 0000000000..6467ccc395 --- /dev/null +++ b/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/finalstatic/Bike.java @@ -0,0 +1,14 @@ +package com.baeldung.finalstatic; + +import java.util.HashMap; + +public class Bike { + public static final int TIRE = 2; + public static final int PEDAL; + public static final HashMap PART = new HashMap<>(); + + static { + PEDAL = 5; + } + +} diff --git a/core-java-modules/core-java-lang-6/src/test/java/com/baeldung/finalstatic/BikeUnitTest.java b/core-java-modules/core-java-lang-6/src/test/java/com/baeldung/finalstatic/BikeUnitTest.java new file mode 100644 index 0000000000..bd7f578a9a --- /dev/null +++ b/core-java-modules/core-java-lang-6/src/test/java/com/baeldung/finalstatic/BikeUnitTest.java @@ -0,0 +1,28 @@ +package com.baeldung.finalstatic; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class BikeUnitTest { + + @Test + void givenTireConstantSetUponDeclaration_whenGetTire_thenReturnTwo() { + assertEquals(2, Bike.TIRE); + } + + @Test + void givenPedalConstantSetByStaticBlock_whenGetPedal_thenReturnFive() { + assertEquals(5, Bike.PEDAL); + } + + @Test + void givenPartConstantObject_whenObjectStateChanged_thenCorrect() { + Bike.PART.put("seat", 1); + assertEquals(1, Bike.PART.get("seat")); + + Bike.PART.put("seat", 5); + assertEquals(5, Bike.PART.get("seat")); + } + +} \ No newline at end of file From f763b57b7a00c3f5653e6076173c28156345dd7c Mon Sep 17 00:00:00 2001 From: michaelin007 Date: Sun, 3 Dec 2023 11:09:55 +0000 Subject: [PATCH 189/228] Final Static Variables in Java --- .../src/test/java/com/baeldung/finalstatic/BikeUnitTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-modules/core-java-lang-6/src/test/java/com/baeldung/finalstatic/BikeUnitTest.java b/core-java-modules/core-java-lang-6/src/test/java/com/baeldung/finalstatic/BikeUnitTest.java index bd7f578a9a..3699a061ab 100644 --- a/core-java-modules/core-java-lang-6/src/test/java/com/baeldung/finalstatic/BikeUnitTest.java +++ b/core-java-modules/core-java-lang-6/src/test/java/com/baeldung/finalstatic/BikeUnitTest.java @@ -2,7 +2,7 @@ package com.baeldung.finalstatic; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; class BikeUnitTest { From 7f1bfe6a875067c655b384aa202f5c43daa93f36 Mon Sep 17 00:00:00 2001 From: Kai Yuan Date: Sun, 3 Dec 2023 17:55:52 +0100 Subject: [PATCH 190/228] [chk-double-is-int] check if doulbe is integer (#15312) --- core-java-modules/core-java-numbers-7/pom.xml | 37 +++++++++ .../CheckDoubleIsAnIntegerUnitTest.java | 83 +++++++++++++++++++ core-java-modules/pom.xml | 2 +- 3 files changed, 121 insertions(+), 1 deletion(-) create mode 100644 core-java-modules/core-java-numbers-7/pom.xml create mode 100644 core-java-modules/core-java-numbers-7/src/test/java/com/baeldung/doubleisint/CheckDoubleIsAnIntegerUnitTest.java diff --git a/core-java-modules/core-java-numbers-7/pom.xml b/core-java-modules/core-java-numbers-7/pom.xml new file mode 100644 index 0000000000..dec3084108 --- /dev/null +++ b/core-java-modules/core-java-numbers-7/pom.xml @@ -0,0 +1,37 @@ + + 4.0.0 + core-java-numbers-7 + core-java-numbers-7 + jar + + + com.baeldung.core-java-modules + core-java-modules + 0.0.1-SNAPSHOT + + + + + org.junit.jupiter + junit-jupiter-engine + ${junit-jupiter.version} + test + + + com.google.guava + guava + ${guava.version} + + + + core-java-numbers-7 + + + src/main/resources + true + + + + \ No newline at end of file diff --git a/core-java-modules/core-java-numbers-7/src/test/java/com/baeldung/doubleisint/CheckDoubleIsAnIntegerUnitTest.java b/core-java-modules/core-java-numbers-7/src/test/java/com/baeldung/doubleisint/CheckDoubleIsAnIntegerUnitTest.java new file mode 100644 index 0000000000..90d2c52595 --- /dev/null +++ b/core-java-modules/core-java-numbers-7/src/test/java/com/baeldung/doubleisint/CheckDoubleIsAnIntegerUnitTest.java @@ -0,0 +1,83 @@ +package com.baeldung.doubleisint; + +import com.google.common.math.DoubleMath; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class CheckDoubleIsAnIntegerUnitTest { + + boolean notNaNOrInfinity(double d) { + return !(Double.isNaN(d) || Double.isInfinite(d)); + } + + @Test + void whenConvertingToInt_thenGetExpectedResult() { + double d1 = 42.0D; + boolean d1IsInteger = notNaNOrInfinity(d1) && (int) d1 == d1; + assertTrue(d1IsInteger); + + double d2 = 42.42D; + boolean d2IsInteger = notNaNOrInfinity(d2) && (int) d2 == d2; + assertFalse(d2IsInteger); + + double d3 = 2.0D * Integer.MAX_VALUE; + boolean d3IsInteger = notNaNOrInfinity(d3) && (int) d3 == d3; + assertTrue(!d3IsInteger); // <-- fails if exceeding Integer's range + } + + @Test + void whenUsingModuloOperator_thenGetExpectedResult() { + double d1 = 42.0D; + boolean d1IsInteger = notNaNOrInfinity(d1) && (d1 % 1) == 0; + assertTrue(d1IsInteger); + + double d2 = 42.42D; + boolean d2IsInteger = notNaNOrInfinity(d2) && (d2 % 1) == 0; + assertFalse(d2IsInteger); + + double d3 = 2.0D * Integer.MAX_VALUE; + boolean d3IsInteger = notNaNOrInfinity(d3) && (d3 % 1) == 0; + assertTrue(d3IsInteger); + + } + + + @Test + void whenCheckingFloorOrCeilingValue_thenGetExpectedResult() { + double d1 = 42.0D; + boolean d1IsInteger = notNaNOrInfinity(d1) && Math.floor(d1) == d1; + assertTrue(d1IsInteger); + + double d2 = 42.42D; + boolean d2IsInteger = notNaNOrInfinity(d2) && Math.floor(d2) == d2; + assertFalse(d2IsInteger); + + double d3 = 2.0D * Integer.MAX_VALUE; + boolean d3IsInteger = notNaNOrInfinity(d3) && Math.floor(d3) == d3; + assertTrue(d3IsInteger); + + } + + @Test + void whenUsingGuava_thenGetExpectedResult() { + double d1 = 42.0D; + boolean d1IsInteger = DoubleMath.isMathematicalInteger(d1); + assertTrue(d1IsInteger); + + double d2 = 42.42D; + boolean d2IsInteger = DoubleMath.isMathematicalInteger(d2); + assertFalse(d2IsInteger); + + double d3 = 2.0D * Integer.MAX_VALUE; + boolean d3IsInteger = DoubleMath.isMathematicalInteger(d3); + assertTrue(d3IsInteger); + + boolean isInfinityInt = DoubleMath.isMathematicalInteger(Double.POSITIVE_INFINITY); + assertFalse(isInfinityInt); + + boolean isNanInt = DoubleMath.isMathematicalInteger(Double.NaN); + assertFalse(isNanInt); + } +} \ No newline at end of file diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml index b3ef8167a5..c0c44eba9a 100644 --- a/core-java-modules/pom.xml +++ b/core-java-modules/pom.xml @@ -166,6 +166,7 @@ core-java-numbers-4 core-java-numbers-5 core-java-numbers-6 + core-java-numbers-7 core-java-optional core-java-perf core-java-properties @@ -225,5 +226,4 @@ - From e6501ada078ccf1c2c281be027168ad69408eee9 Mon Sep 17 00:00:00 2001 From: timis1 <12120641+timis1@users.noreply.github.com> Date: Sun, 3 Dec 2023 21:19:12 +0200 Subject: [PATCH 191/228] JAVA-26705 Upgrade lombok to latest version (#15305) Co-authored-by: timis1 --- aws-modules/aws-reactive/pom.xml | 1 - core-java-modules/core-java-collections-list-5/pom.xml | 2 +- deeplearning4j/pom.xml | 1 - ksqldb/pom.xml | 2 +- kubernetes-modules/k8s-admission-controller/pom.xml | 1 + libraries-data-db/pom.xml | 1 + logging-modules/logback/pom.xml | 1 - messaging-modules/postgres-notify/pom.xml | 1 + .../messaging/postgresql/controller/OrdersController.java | 2 +- .../messaging/postgresql/service/NotificationHandler.java | 2 +- .../baeldung/messaging/postgresql/service/OrdersService.java | 4 ++-- netflix-modules/mantis/pom.xml | 1 + persistence-modules/fauna/pom.xml | 1 + persistence-modules/r2dbc/pom.xml | 1 + persistence-modules/scylladb/pom.xml | 1 + persistence-modules/spring-boot-persistence-2/pom.xml | 1 + persistence-modules/spring-data-cosmosdb/pom.xml | 1 + persistence-modules/spring-data-elasticsearch/pom.xml | 2 +- persistence-modules/spring-data-mongodb-reactive/pom.xml | 1 + persistence-modules/spring-data-redis/pom.xml | 1 + pom.xml | 2 +- reactive-systems/inventory-service/pom.xml | 1 + reactive-systems/order-service/pom.xml | 1 + reactive-systems/shipping-service/pom.xml | 1 + saas-modules/stripe/pom.xml | 1 + security-modules/sql-injection-samples/pom.xml | 1 + spring-4/pom.xml | 1 + spring-5-webflux/pom.xml | 1 + spring-boot-modules/spring-boot-3-2/pom.xml | 1 + spring-boot-modules/spring-boot-graphql/pom.xml | 1 + .../java/com/baeldung/graphql/intro/SpringContextTest.java | 1 - spring-boot-modules/spring-boot-logging-log4j2/pom.xml | 1 + spring-boot-modules/spring-boot-mvc-birt/pom.xml | 1 + spring-boot-modules/spring-boot-mvc/pom.xml | 1 + .../spring-cloud-archaius-dynamodb-config/pom.xml | 1 - .../spring-cloud-archaius-jdbc-config/pom.xml | 4 ---- .../spring-cloud-eureka-feign-client-integration-test/pom.xml | 1 + spring-core-2/pom.xml | 1 + spring-credhub/pom.xml | 1 + spring-kafka-2/pom.xml | 1 + spring-kafka/pom.xml | 1 + spring-reactive-modules/spring-reactive-2/pom.xml | 1 + spring-reactive-modules/spring-reactive-3/pom.xml | 1 + spring-reactive-modules/spring-reactive-client/pom.xml | 1 + .../spring-reactive-data-couchbase/pom.xml | 1 - spring-reactive-modules/spring-reactive-data/pom.xml | 1 + spring-reactive-modules/spring-reactive-security/pom.xml | 1 + spring-security-modules/spring-security-azuread/pom.xml | 1 + spring-security-modules/spring-security-opa/pom.xml | 1 + spring-web-modules/spring-mvc-forms-thymeleaf/pom.xml | 1 + testing-modules/cucumber/pom.xml | 1 + testing-modules/spring-mockito/pom.xml | 1 + 52 files changed, 46 insertions(+), 18 deletions(-) diff --git a/aws-modules/aws-reactive/pom.xml b/aws-modules/aws-reactive/pom.xml index e6b50cadb2..22bd62c2ee 100644 --- a/aws-modules/aws-reactive/pom.xml +++ b/aws-modules/aws-reactive/pom.xml @@ -93,7 +93,6 @@ 2.2.1.RELEASE 2.17.283 - 1.18.20 \ No newline at end of file diff --git a/core-java-modules/core-java-collections-list-5/pom.xml b/core-java-modules/core-java-collections-list-5/pom.xml index c89ad0fad9..c11781eeda 100644 --- a/core-java-modules/core-java-collections-list-5/pom.xml +++ b/core-java-modules/core-java-collections-list-5/pom.xml @@ -39,7 +39,7 @@ org.projectlombok lombok - 1.18.26 + ${lombok.version} provided diff --git a/deeplearning4j/pom.xml b/deeplearning4j/pom.xml index 875d8cdf85..aab19a166d 100644 --- a/deeplearning4j/pom.xml +++ b/deeplearning4j/pom.xml @@ -68,7 +68,6 @@ 0.9.1 4.3.5 - 1.18.20 \ No newline at end of file diff --git a/ksqldb/pom.xml b/ksqldb/pom.xml index e55398d635..ebb3bfa7ee 100644 --- a/ksqldb/pom.xml +++ b/ksqldb/pom.xml @@ -17,7 +17,7 @@ confluent confluent-repo - http://packages.confluent.io/maven/ + https://packages.confluent.io/maven/ diff --git a/kubernetes-modules/k8s-admission-controller/pom.xml b/kubernetes-modules/k8s-admission-controller/pom.xml index 18bf98a830..4c41bf7ca0 100644 --- a/kubernetes-modules/k8s-admission-controller/pom.xml +++ b/kubernetes-modules/k8s-admission-controller/pom.xml @@ -22,6 +22,7 @@ org.projectlombok lombok + ${lombok.version} true diff --git a/libraries-data-db/pom.xml b/libraries-data-db/pom.xml index ed184d72e0..5f1ff489f4 100644 --- a/libraries-data-db/pom.xml +++ b/libraries-data-db/pom.xml @@ -152,6 +152,7 @@ org.projectlombok lombok + ${lombok.version} io.ebean diff --git a/logging-modules/logback/pom.xml b/logging-modules/logback/pom.xml index 8df95c18bb..fbd180c74d 100644 --- a/logging-modules/logback/pom.xml +++ b/logging-modules/logback/pom.xml @@ -121,7 +121,6 @@ 2.0.0 1.4.8 2.0.4 - 1.18.22 \ No newline at end of file diff --git a/messaging-modules/postgres-notify/pom.xml b/messaging-modules/postgres-notify/pom.xml index 876519f40c..571065b98d 100644 --- a/messaging-modules/postgres-notify/pom.xml +++ b/messaging-modules/postgres-notify/pom.xml @@ -41,6 +41,7 @@ org.projectlombok lombok true + ${lombok.version} diff --git a/messaging-modules/postgres-notify/src/main/java/com/baeldung/messaging/postgresql/controller/OrdersController.java b/messaging-modules/postgres-notify/src/main/java/com/baeldung/messaging/postgresql/controller/OrdersController.java index 70daa14abd..4a1db320dc 100644 --- a/messaging-modules/postgres-notify/src/main/java/com/baeldung/messaging/postgresql/controller/OrdersController.java +++ b/messaging-modules/postgres-notify/src/main/java/com/baeldung/messaging/postgresql/controller/OrdersController.java @@ -42,7 +42,7 @@ public class OrdersController { public ResponseEntity getOrderById(@PathVariable Long id) { Optional o = orders.findById(id); - if (o.isEmpty()) { + if (!o.isPresent()) { return ResponseEntity.notFound().build(); } diff --git a/messaging-modules/postgres-notify/src/main/java/com/baeldung/messaging/postgresql/service/NotificationHandler.java b/messaging-modules/postgres-notify/src/main/java/com/baeldung/messaging/postgresql/service/NotificationHandler.java index 61b970f3a2..da333b89ff 100644 --- a/messaging-modules/postgres-notify/src/main/java/com/baeldung/messaging/postgresql/service/NotificationHandler.java +++ b/messaging-modules/postgres-notify/src/main/java/com/baeldung/messaging/postgresql/service/NotificationHandler.java @@ -23,7 +23,7 @@ public class NotificationHandler implements Consumer{ public void accept(PGNotification t) { log.info("Notification received: pid={}, name={}, param={}",t.getPID(),t.getName(),t.getParameter()); Optional order = orders.findById(Long.valueOf(t.getParameter())); - if ( !order.isEmpty()) { + if ( order.isPresent()) { log.info("order details: {}", order.get()); } } diff --git a/messaging-modules/postgres-notify/src/main/java/com/baeldung/messaging/postgresql/service/OrdersService.java b/messaging-modules/postgres-notify/src/main/java/com/baeldung/messaging/postgresql/service/OrdersService.java index cc369c1f3e..038c2f6492 100644 --- a/messaging-modules/postgres-notify/src/main/java/com/baeldung/messaging/postgresql/service/OrdersService.java +++ b/messaging-modules/postgres-notify/src/main/java/com/baeldung/messaging/postgresql/service/OrdersService.java @@ -43,14 +43,14 @@ public class OrdersService { @Transactional(readOnly = true) public Optional findById(Long id) { Optional o = Optional.ofNullable(ordersCache.get(id, Order.class)); - if ( !o.isEmpty() ) { + if ( o.isPresent() ) { log.info("findById: cache hit, id={}",id); return o; } log.info("findById: cache miss, id={}",id); o = repo.findById(id); - if ( o.isEmpty()) { + if ( !o.isPresent()) { return o; } diff --git a/netflix-modules/mantis/pom.xml b/netflix-modules/mantis/pom.xml index 351f079481..ed57eed01e 100644 --- a/netflix-modules/mantis/pom.xml +++ b/netflix-modules/mantis/pom.xml @@ -43,6 +43,7 @@ org.projectlombok lombok + ${lombok.version} org.springframework diff --git a/persistence-modules/fauna/pom.xml b/persistence-modules/fauna/pom.xml index a0626e0cd2..c6350b37d7 100644 --- a/persistence-modules/fauna/pom.xml +++ b/persistence-modules/fauna/pom.xml @@ -44,6 +44,7 @@ org.projectlombok lombok provided + ${lombok.version} diff --git a/persistence-modules/r2dbc/pom.xml b/persistence-modules/r2dbc/pom.xml index 5260bb9860..a2c8e3148d 100644 --- a/persistence-modules/r2dbc/pom.xml +++ b/persistence-modules/r2dbc/pom.xml @@ -52,6 +52,7 @@ org.projectlombok lombok + ${lombok.version} org.springframework.boot diff --git a/persistence-modules/scylladb/pom.xml b/persistence-modules/scylladb/pom.xml index f84db87742..66dd89afa9 100644 --- a/persistence-modules/scylladb/pom.xml +++ b/persistence-modules/scylladb/pom.xml @@ -37,6 +37,7 @@ org.projectlombok lombok true + ${lombok.version} org.springframework.boot diff --git a/persistence-modules/spring-boot-persistence-2/pom.xml b/persistence-modules/spring-boot-persistence-2/pom.xml index 7d6b6909c4..9b22e6902c 100644 --- a/persistence-modules/spring-boot-persistence-2/pom.xml +++ b/persistence-modules/spring-boot-persistence-2/pom.xml @@ -74,6 +74,7 @@ org.projectlombok lombok true + ${lombok.version} org.springframework.boot diff --git a/persistence-modules/spring-data-cosmosdb/pom.xml b/persistence-modules/spring-data-cosmosdb/pom.xml index 30dc4f999c..fbd4af9456 100644 --- a/persistence-modules/spring-data-cosmosdb/pom.xml +++ b/persistence-modules/spring-data-cosmosdb/pom.xml @@ -32,6 +32,7 @@ org.projectlombok lombok + ${lombok.version} diff --git a/persistence-modules/spring-data-elasticsearch/pom.xml b/persistence-modules/spring-data-elasticsearch/pom.xml index 91dc3ee4d2..b8edae68d3 100644 --- a/persistence-modules/spring-data-elasticsearch/pom.xml +++ b/persistence-modules/spring-data-elasticsearch/pom.xml @@ -40,7 +40,7 @@ org.projectlombok lombok - 1.18.28 + ${lombok.version} org.springframework.boot diff --git a/persistence-modules/spring-data-mongodb-reactive/pom.xml b/persistence-modules/spring-data-mongodb-reactive/pom.xml index 85c9a4c4b6..46b2e8067f 100644 --- a/persistence-modules/spring-data-mongodb-reactive/pom.xml +++ b/persistence-modules/spring-data-mongodb-reactive/pom.xml @@ -35,6 +35,7 @@ org.projectlombok lombok + ${lombok.version} io.projectreactor diff --git a/persistence-modules/spring-data-redis/pom.xml b/persistence-modules/spring-data-redis/pom.xml index 052935e215..382cdf83f5 100644 --- a/persistence-modules/spring-data-redis/pom.xml +++ b/persistence-modules/spring-data-redis/pom.xml @@ -27,6 +27,7 @@ org.projectlombok lombok + ${lombok.version} io.projectreactor diff --git a/pom.xml b/pom.xml index cee9d9125b..73a21684e4 100644 --- a/pom.xml +++ b/pom.xml @@ -1234,7 +1234,7 @@ 3.12.2 3.3.0 3.21.0 - 1.18.28 + 1.18.30 2.1.214 32.1.3-jre 3.3.0 diff --git a/reactive-systems/inventory-service/pom.xml b/reactive-systems/inventory-service/pom.xml index 4aeec24922..baf5151fdc 100644 --- a/reactive-systems/inventory-service/pom.xml +++ b/reactive-systems/inventory-service/pom.xml @@ -31,6 +31,7 @@ org.projectlombok lombok true + ${lombok.version} org.springframework.boot diff --git a/reactive-systems/order-service/pom.xml b/reactive-systems/order-service/pom.xml index b9e5d36d3a..b6cfb70678 100644 --- a/reactive-systems/order-service/pom.xml +++ b/reactive-systems/order-service/pom.xml @@ -31,6 +31,7 @@ org.projectlombok lombok true + ${lombok.version} org.springframework.boot diff --git a/reactive-systems/shipping-service/pom.xml b/reactive-systems/shipping-service/pom.xml index 5fac674bbc..8f94dabdea 100644 --- a/reactive-systems/shipping-service/pom.xml +++ b/reactive-systems/shipping-service/pom.xml @@ -31,6 +31,7 @@ org.projectlombok lombok true + ${lombok.version} org.springframework.boot diff --git a/saas-modules/stripe/pom.xml b/saas-modules/stripe/pom.xml index 44bc5be4a8..77bb912b7b 100644 --- a/saas-modules/stripe/pom.xml +++ b/saas-modules/stripe/pom.xml @@ -27,6 +27,7 @@ org.projectlombok lombok + ${lombok.version} com.stripe diff --git a/security-modules/sql-injection-samples/pom.xml b/security-modules/sql-injection-samples/pom.xml index 7953e43ebe..37779e0d14 100644 --- a/security-modules/sql-injection-samples/pom.xml +++ b/security-modules/sql-injection-samples/pom.xml @@ -38,6 +38,7 @@ org.projectlombok lombok + ${lombok.version} provided diff --git a/spring-4/pom.xml b/spring-4/pom.xml index 681747c1f6..ad05123543 100644 --- a/spring-4/pom.xml +++ b/spring-4/pom.xml @@ -57,6 +57,7 @@ org.projectlombok lombok + ${lombok.version} provided diff --git a/spring-5-webflux/pom.xml b/spring-5-webflux/pom.xml index fe6dbe5292..8a381b250a 100644 --- a/spring-5-webflux/pom.xml +++ b/spring-5-webflux/pom.xml @@ -46,6 +46,7 @@ org.projectlombok lombok + ${lombok.version} org.springframework.boot diff --git a/spring-boot-modules/spring-boot-3-2/pom.xml b/spring-boot-modules/spring-boot-3-2/pom.xml index c85488d44b..e48b232a52 100644 --- a/spring-boot-modules/spring-boot-3-2/pom.xml +++ b/spring-boot-modules/spring-boot-3-2/pom.xml @@ -79,6 +79,7 @@ org.projectlombok lombok + ${lombok.version} true diff --git a/spring-boot-modules/spring-boot-graphql/pom.xml b/spring-boot-modules/spring-boot-graphql/pom.xml index d3c122709d..b3f27f1b84 100644 --- a/spring-boot-modules/spring-boot-graphql/pom.xml +++ b/spring-boot-modules/spring-boot-graphql/pom.xml @@ -59,6 +59,7 @@ org.projectlombok lombok + ${lombok.version} com.h2database diff --git a/spring-boot-modules/spring-boot-graphql/src/test/java/com/baeldung/graphql/intro/SpringContextTest.java b/spring-boot-modules/spring-boot-graphql/src/test/java/com/baeldung/graphql/intro/SpringContextTest.java index 87bebf644c..a2e63a96f8 100644 --- a/spring-boot-modules/spring-boot-graphql/src/test/java/com/baeldung/graphql/intro/SpringContextTest.java +++ b/spring-boot-modules/spring-boot-graphql/src/test/java/com/baeldung/graphql/intro/SpringContextTest.java @@ -1,6 +1,5 @@ package com.baeldung.graphql.intro; -import com.baeldung.graphql.intro.GraphqlApplication; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; diff --git a/spring-boot-modules/spring-boot-logging-log4j2/pom.xml b/spring-boot-modules/spring-boot-logging-log4j2/pom.xml index 31c0f4bd02..de21a99ab3 100644 --- a/spring-boot-modules/spring-boot-logging-log4j2/pom.xml +++ b/spring-boot-modules/spring-boot-logging-log4j2/pom.xml @@ -40,6 +40,7 @@ org.projectlombok lombok + ${lombok.version} provided diff --git a/spring-boot-modules/spring-boot-mvc-birt/pom.xml b/spring-boot-modules/spring-boot-mvc-birt/pom.xml index cc4b7f8283..b2cda67974 100644 --- a/spring-boot-modules/spring-boot-mvc-birt/pom.xml +++ b/spring-boot-modules/spring-boot-mvc-birt/pom.xml @@ -48,6 +48,7 @@ org.projectlombok lombok + ${lombok.version} provided diff --git a/spring-boot-modules/spring-boot-mvc/pom.xml b/spring-boot-modules/spring-boot-mvc/pom.xml index 963cda61b9..ab1c867d66 100644 --- a/spring-boot-modules/spring-boot-mvc/pom.xml +++ b/spring-boot-modules/spring-boot-mvc/pom.xml @@ -92,6 +92,7 @@ org.projectlombok lombok + ${lombok.version} diff --git a/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-dynamodb-config/pom.xml b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-dynamodb-config/pom.xml index 600fedc774..371b5c2976 100644 --- a/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-dynamodb-config/pom.xml +++ b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-dynamodb-config/pom.xml @@ -44,7 +44,6 @@ 1.11.407 5.0.3 0.7.6 - 1.18.26 \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-jdbc-config/pom.xml b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-jdbc-config/pom.xml index 2871f129b5..1ef57d4be3 100644 --- a/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-jdbc-config/pom.xml +++ b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-jdbc-config/pom.xml @@ -34,8 +34,4 @@ - - 1.18.26 - - \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-eureka/spring-cloud-eureka-feign-client-integration-test/pom.xml b/spring-cloud-modules/spring-cloud-eureka/spring-cloud-eureka-feign-client-integration-test/pom.xml index 08a85d191a..e540645f30 100644 --- a/spring-cloud-modules/spring-cloud-eureka/spring-cloud-eureka-feign-client-integration-test/pom.xml +++ b/spring-cloud-modules/spring-cloud-eureka/spring-cloud-eureka-feign-client-integration-test/pom.xml @@ -74,6 +74,7 @@ org.projectlombok lombok + ${lombok.version} org.testcontainers diff --git a/spring-core-2/pom.xml b/spring-core-2/pom.xml index f27b16acc3..a3c793b93a 100644 --- a/spring-core-2/pom.xml +++ b/spring-core-2/pom.xml @@ -133,6 +133,7 @@ org.projectlombok lombok + ${lombok.version} diff --git a/spring-credhub/pom.xml b/spring-credhub/pom.xml index defe378b6b..f257d549bf 100644 --- a/spring-credhub/pom.xml +++ b/spring-credhub/pom.xml @@ -23,6 +23,7 @@ org.projectlombok lombok + ${lombok.version} org.springframework.credhub diff --git a/spring-kafka-2/pom.xml b/spring-kafka-2/pom.xml index 05da9418b7..7a4d5a5fea 100644 --- a/spring-kafka-2/pom.xml +++ b/spring-kafka-2/pom.xml @@ -38,6 +38,7 @@ org.projectlombok lombok + ${lombok.version} org.springframework.kafka diff --git a/spring-kafka/pom.xml b/spring-kafka/pom.xml index ddef3ca180..6428734de2 100644 --- a/spring-kafka/pom.xml +++ b/spring-kafka/pom.xml @@ -48,6 +48,7 @@ org.projectlombok lombok + ${lombok.version} org.springframework.kafka diff --git a/spring-reactive-modules/spring-reactive-2/pom.xml b/spring-reactive-modules/spring-reactive-2/pom.xml index 90c5300cc8..a5552bfe51 100644 --- a/spring-reactive-modules/spring-reactive-2/pom.xml +++ b/spring-reactive-modules/spring-reactive-2/pom.xml @@ -37,6 +37,7 @@ org.projectlombok lombok provided + ${lombok.version} org.springframework.boot diff --git a/spring-reactive-modules/spring-reactive-3/pom.xml b/spring-reactive-modules/spring-reactive-3/pom.xml index bf2cdbbf2d..17c9690157 100644 --- a/spring-reactive-modules/spring-reactive-3/pom.xml +++ b/spring-reactive-modules/spring-reactive-3/pom.xml @@ -46,6 +46,7 @@ org.projectlombok lombok + ${lombok.version} org.springframework.boot diff --git a/spring-reactive-modules/spring-reactive-client/pom.xml b/spring-reactive-modules/spring-reactive-client/pom.xml index 5736ce497f..fe53584cc9 100644 --- a/spring-reactive-modules/spring-reactive-client/pom.xml +++ b/spring-reactive-modules/spring-reactive-client/pom.xml @@ -106,6 +106,7 @@ org.projectlombok lombok + ${lombok.version} org.mockito diff --git a/spring-reactive-modules/spring-reactive-data-couchbase/pom.xml b/spring-reactive-modules/spring-reactive-data-couchbase/pom.xml index 2ac8ad19ac..e0b21087fa 100644 --- a/spring-reactive-modules/spring-reactive-data-couchbase/pom.xml +++ b/spring-reactive-modules/spring-reactive-data-couchbase/pom.xml @@ -140,7 +140,6 @@ 2.2.6.RELEASE 2.17.1 - 1.18.26 \ No newline at end of file diff --git a/spring-reactive-modules/spring-reactive-data/pom.xml b/spring-reactive-modules/spring-reactive-data/pom.xml index a598315d5d..576a1d9f86 100644 --- a/spring-reactive-modules/spring-reactive-data/pom.xml +++ b/spring-reactive-modules/spring-reactive-data/pom.xml @@ -53,6 +53,7 @@ org.projectlombok lombok true + ${lombok.version} io.projectreactor diff --git a/spring-reactive-modules/spring-reactive-security/pom.xml b/spring-reactive-modules/spring-reactive-security/pom.xml index cf34b21083..25b9f4c38f 100644 --- a/spring-reactive-modules/spring-reactive-security/pom.xml +++ b/spring-reactive-modules/spring-reactive-security/pom.xml @@ -41,6 +41,7 @@ org.projectlombok lombok compile + ${lombok.version} org.apache.geronimo.specs diff --git a/spring-security-modules/spring-security-azuread/pom.xml b/spring-security-modules/spring-security-azuread/pom.xml index 7e67a7e635..11d6b876c1 100644 --- a/spring-security-modules/spring-security-azuread/pom.xml +++ b/spring-security-modules/spring-security-azuread/pom.xml @@ -48,6 +48,7 @@ org.projectlombok lombok true + ${lombok.version} org.springframework.boot diff --git a/spring-security-modules/spring-security-opa/pom.xml b/spring-security-modules/spring-security-opa/pom.xml index a6240f6e69..81c4709124 100644 --- a/spring-security-modules/spring-security-opa/pom.xml +++ b/spring-security-modules/spring-security-opa/pom.xml @@ -23,6 +23,7 @@ org.projectlombok lombok + ${lombok.version} com.google.guava diff --git a/spring-web-modules/spring-mvc-forms-thymeleaf/pom.xml b/spring-web-modules/spring-mvc-forms-thymeleaf/pom.xml index eb31723798..9c9d6804ae 100644 --- a/spring-web-modules/spring-mvc-forms-thymeleaf/pom.xml +++ b/spring-web-modules/spring-mvc-forms-thymeleaf/pom.xml @@ -27,6 +27,7 @@ org.projectlombok lombok + ${lombok.version} diff --git a/testing-modules/cucumber/pom.xml b/testing-modules/cucumber/pom.xml index 6d178b86a3..c1d99bb492 100644 --- a/testing-modules/cucumber/pom.xml +++ b/testing-modules/cucumber/pom.xml @@ -42,6 +42,7 @@ org.projectlombok lombok provided + ${lombok.version} io.cucumber diff --git a/testing-modules/spring-mockito/pom.xml b/testing-modules/spring-mockito/pom.xml index 6283ea2d1f..8e13f511d2 100644 --- a/testing-modules/spring-mockito/pom.xml +++ b/testing-modules/spring-mockito/pom.xml @@ -29,6 +29,7 @@ org.projectlombok lombok + ${lombok.version} From e6c2c4ab6427cbce20aec559ad37e367fabefc95 Mon Sep 17 00:00:00 2001 From: michaelin007 Date: Mon, 4 Dec 2023 09:15:45 +0000 Subject: [PATCH 192/228] https://jira.baeldung.com/browse/BAEL-7169 --- .../src/test/java/com/baeldung/finalstatic/BikeUnitTest.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/core-java-modules/core-java-lang-6/src/test/java/com/baeldung/finalstatic/BikeUnitTest.java b/core-java-modules/core-java-lang-6/src/test/java/com/baeldung/finalstatic/BikeUnitTest.java index 3699a061ab..7b32b0906c 100644 --- a/core-java-modules/core-java-lang-6/src/test/java/com/baeldung/finalstatic/BikeUnitTest.java +++ b/core-java-modules/core-java-lang-6/src/test/java/com/baeldung/finalstatic/BikeUnitTest.java @@ -25,4 +25,9 @@ class BikeUnitTest { assertEquals(5, Bike.PART.get("seat")); } + @Test + void givenMathClass_whenAccessingPiConstant_thenVerifyPiValueIsCorrect() { + assertEquals(3.141592653589793, Math.PI); + } + } \ No newline at end of file From 67e11e004e464359406396e1b9bb276b00bfb1d6 Mon Sep 17 00:00:00 2001 From: panos-kakos <102670093+panos-kakos@users.noreply.github.com> Date: Mon, 4 Dec 2023 13:11:26 +0200 Subject: [PATCH 193/228] [JAVA-27743] Upgraded spring-integration module to spring 6 & java 17 (#15343) --- spring-integration/pom.xml | 26 +++++++++---------- .../baeldung/dsl/JavaDSLFileCopyConfig.java | 18 ++++++------- 2 files changed, 21 insertions(+), 23 deletions(-) diff --git a/spring-integration/pom.xml b/spring-integration/pom.xml index abf5cfb3d6..315f549c12 100644 --- a/spring-integration/pom.xml +++ b/spring-integration/pom.xml @@ -17,7 +17,6 @@ - org.springframework.integration spring-integration-core @@ -29,11 +28,6 @@ ${javax-activation.version} true - - javax.mail - mail - ${javax-mail.version} - org.springframework.integration spring-integration-twitter @@ -85,16 +79,21 @@ h2 ${h2.version} - - javax.xml.bind - jaxb-api - ${jaxb-api.version} - org.postgresql postgresql ${postgresql.version} + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + + + com.sun.mail + jakarta.mail + ${jakarta.mail.version} + @@ -124,14 +123,13 @@ - 5.1.13.RELEASE + 6.0.0 1.1.4.RELEASE 5.0.13.RELEASE - 1.4.7 1.1.1 2.10 - 2.3.0 42.3.8 + 2.0.1 \ No newline at end of file diff --git a/spring-integration/src/main/java/com/baeldung/dsl/JavaDSLFileCopyConfig.java b/spring-integration/src/main/java/com/baeldung/dsl/JavaDSLFileCopyConfig.java index adaeac5386..8afd39e9ab 100644 --- a/spring-integration/src/main/java/com/baeldung/dsl/JavaDSLFileCopyConfig.java +++ b/spring-integration/src/main/java/com/baeldung/dsl/JavaDSLFileCopyConfig.java @@ -1,6 +1,7 @@ package com.baeldung.dsl; import java.io.File; +import java.time.Duration; import java.util.Scanner; import java.util.concurrent.TimeUnit; @@ -14,7 +15,6 @@ import org.springframework.integration.config.EnableIntegration; import org.springframework.integration.core.GenericSelector; import org.springframework.integration.core.MessageSource; import org.springframework.integration.dsl.IntegrationFlow; -import org.springframework.integration.dsl.IntegrationFlows; import org.springframework.integration.dsl.Pollers; import org.springframework.integration.dsl.MessageChannels; import org.springframework.integration.file.FileReadingMessageSource; @@ -69,7 +69,7 @@ public class JavaDSLFileCopyConfig { @Bean public IntegrationFlow fileMover() { - return IntegrationFlows.from(sourceDirectory(), configurer -> configurer.poller(Pollers.fixedDelay(10000))) + return IntegrationFlow.from(sourceDirectory(), configurer -> configurer.poller(Pollers.fixedDelay(10000))) .filter(onlyJpgs()) .handle(targetDirectory()) .get(); @@ -77,7 +77,7 @@ public class JavaDSLFileCopyConfig { // @Bean public IntegrationFlow fileMoverWithLambda() { - return IntegrationFlows.from(sourceDirectory(), configurer -> configurer.poller(Pollers.fixedDelay(10000))) + return IntegrationFlow.from(sourceDirectory(), configurer -> configurer.poller(Pollers.fixedDelay(10000))) .filter(message -> ((File) message).getName() .endsWith(".jpg")) .handle(targetDirectory()) @@ -92,7 +92,7 @@ public class JavaDSLFileCopyConfig { // @Bean public IntegrationFlow fileMoverWithPriorityChannel() { - return IntegrationFlows.from(sourceDirectory()) + return IntegrationFlow.from(sourceDirectory()) .filter(onlyJpgs()) .channel("alphabetically") .handle(targetDirectory()) @@ -113,7 +113,7 @@ public class JavaDSLFileCopyConfig { // @Bean public IntegrationFlow fileReader() { - return IntegrationFlows.from(sourceDirectory(), configurer -> configurer.poller(Pollers.fixedDelay(10))) + return IntegrationFlow.from(sourceDirectory(), configurer -> configurer.poller(Pollers.fixedDelay(10))) .filter(onlyJpgs()) .channel("holdingTank") .get(); @@ -121,16 +121,16 @@ public class JavaDSLFileCopyConfig { // @Bean public IntegrationFlow fileWriter() { - return IntegrationFlows.from("holdingTank") - .bridge(e -> e.poller(Pollers.fixedRate(1, TimeUnit.SECONDS, 20))) + return IntegrationFlow.from("holdingTank") + .bridge(e -> e.poller(Pollers.fixedRate(Duration.of(1, TimeUnit.SECONDS.toChronoUnit()), Duration.of(20, TimeUnit.SECONDS.toChronoUnit())))) .handle(targetDirectory()) .get(); } // @Bean public IntegrationFlow anotherFileWriter() { - return IntegrationFlows.from("holdingTank") - .bridge(e -> e.poller(Pollers.fixedRate(2, TimeUnit.SECONDS, 10))) + return IntegrationFlow.from("holdingTank") + .bridge(e -> e.poller(Pollers.fixedRate(Duration.of(2, TimeUnit.SECONDS.toChronoUnit()), Duration.of(10, TimeUnit.SECONDS.toChronoUnit())))) .handle(anotherTargetDirectory()) .get(); } From 75afba12d1dcc269cdbeb97060ef6f8a40082b1f Mon Sep 17 00:00:00 2001 From: Sam Gardner Date: Mon, 4 Dec 2023 13:18:04 +0000 Subject: [PATCH 194/228] BAEL-7240 Add example code for verifying lambda calls with mockito --- .../baeldung/lambdacalls/LambdaExample.java | 26 ++++++++++++ .../lambdacalls/LambdaCallsUnitTest.java | 41 +++++++++++++++++++ 2 files changed, 67 insertions(+) create mode 100644 testing-modules/mockito-2/src/main/java/com/baeldung/lambdacalls/LambdaExample.java create mode 100644 testing-modules/mockito-2/src/test/java/com/baeldung/lambdacalls/LambdaCallsUnitTest.java diff --git a/testing-modules/mockito-2/src/main/java/com/baeldung/lambdacalls/LambdaExample.java b/testing-modules/mockito-2/src/main/java/com/baeldung/lambdacalls/LambdaExample.java new file mode 100644 index 0000000000..bc6274eb18 --- /dev/null +++ b/testing-modules/mockito-2/src/main/java/com/baeldung/lambdacalls/LambdaExample.java @@ -0,0 +1,26 @@ +package com.baeldung.lambdacalls; + +import java.util.ArrayList; + +public class LambdaExample { + + private BrickLayer brickLayer = new BrickLayer(); + + static ArrayList bricksList = new ArrayList<>(); + + public void createWall(String bricks){ + Runnable build = () -> brickLayer.layBricks(bricks); + build.run(); + } + + public ArrayList getBricksList(){ + return bricksList; + } + + static class BrickLayer { + void layBricks(String bricks){ + bricksList.add(bricks); + } + } + +} diff --git a/testing-modules/mockito-2/src/test/java/com/baeldung/lambdacalls/LambdaCallsUnitTest.java b/testing-modules/mockito-2/src/test/java/com/baeldung/lambdacalls/LambdaCallsUnitTest.java new file mode 100644 index 0000000000..67127c641c --- /dev/null +++ b/testing-modules/mockito-2/src/test/java/com/baeldung/lambdacalls/LambdaCallsUnitTest.java @@ -0,0 +1,41 @@ +package com.baeldung.lambdacalls; + +import static com.baeldung.lambdacalls.LambdaExample.*; +import static junit.framework.TestCase.assertEquals; +import static org.mockito.Mockito.verify; + +import java.util.ArrayList; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; + +@RunWith(MockitoJUnitRunner.class) +public class LambdaCallsUnitTest { + + @Mock + private/**/ BrickLayer brickLayer; + @InjectMocks + private LambdaExample lambdaExample; + + @Test + public void whenCallingALambda_thenTheInvocationCanBeConfirmedWithCorrectArguments(){ + String bricks = "red bricks"; + lambdaExample.createWall(bricks); + verify(brickLayer).layBricks(bricks); + } + + @Test + public void whenCallingALambda_thenCorrectBehaviourIsPerformed(){ + LambdaExample lambdaExample = new LambdaExample(); + String bricks = "red bricks"; + + lambdaExample.createWall(bricks); + ArrayList bricksList = lambdaExample.getBricksList(); + + assertEquals(bricks, bricksList.get(0)); + } + +} From 9bf766f6195b67bb79127d3855ac110a195cf21d Mon Sep 17 00:00:00 2001 From: Ulisses Lima Date: Mon, 4 Dec 2023 11:37:09 -0300 Subject: [PATCH 195/228] BAEL ???? - Intro to XPath with Java - quick fix Based on email feedback. * Changing `childs` to `childNodes` * Changing `nodeList = (NodeList)` to `NodeList nodeList = (NodeList)` --- xml/src/main/java/com/baeldung/xml/DefaultParser.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/xml/src/main/java/com/baeldung/xml/DefaultParser.java b/xml/src/main/java/com/baeldung/xml/DefaultParser.java index 83280aa0f2..63e4a453c3 100644 --- a/xml/src/main/java/com/baeldung/xml/DefaultParser.java +++ b/xml/src/main/java/com/baeldung/xml/DefaultParser.java @@ -163,10 +163,10 @@ public class DefaultParser { private void clean(Node node) { - NodeList childs = node.getChildNodes(); + NodeList childNodes = node.getChildNodes(); - for (int n = childs.getLength() - 1; n >= 0; n--) { - Node child = childs.item(n); + for (int n = childNodes.getLength() - 1; n >= 0; n--) { + Node child = childNodes.item(n); short nodeType = child.getNodeType(); if (nodeType == Node.ELEMENT_NODE) From e8c97fd6e57ac7902955516c9f027d6132a6c77f Mon Sep 17 00:00:00 2001 From: Niket Agrawal Date: Mon, 4 Dec 2023 22:05:54 +0530 Subject: [PATCH 196/228] BAEL-7062 - Fetching Index from List using Streams (#14914) * Primary Commit * More Cases covered * Indentation Corrections on POM * Merge Conflict Fixed * Updating as per Jira comments * Correction * Review Comment Implementation * Indentation fixes * Review Comment Implementation * Method removal for Iterators * Test Case Update * Review Comment changes * formatting change * Updating map method * Review comment update * Review Comments * Review Comments --- core-java-modules/core-java-streams-5/pom.xml | 5 ++ .../streams/firstmatchingelement/User.java | 21 ++++++ .../FirstMatchingElementUnitTest.java | 72 +++++++++++++++++++ 3 files changed, 98 insertions(+) create mode 100644 core-java-modules/core-java-streams-5/src/main/java/com/baeldung/streams/firstmatchingelement/User.java create mode 100644 core-java-modules/core-java-streams-5/src/test/java/com/baeldung/streams/firstmatchingelement/FirstMatchingElementUnitTest.java diff --git a/core-java-modules/core-java-streams-5/pom.xml b/core-java-modules/core-java-streams-5/pom.xml index e217271f4c..33cd69f761 100644 --- a/core-java-modules/core-java-streams-5/pom.xml +++ b/core-java-modules/core-java-streams-5/pom.xml @@ -48,6 +48,11 @@ guava ${guava.version} + + org.apache.commons + commons-collections4 + ${commons-collections4.version} + diff --git a/core-java-modules/core-java-streams-5/src/main/java/com/baeldung/streams/firstmatchingelement/User.java b/core-java-modules/core-java-streams-5/src/main/java/com/baeldung/streams/firstmatchingelement/User.java new file mode 100644 index 0000000000..cb29af529a --- /dev/null +++ b/core-java-modules/core-java-streams-5/src/main/java/com/baeldung/streams/firstmatchingelement/User.java @@ -0,0 +1,21 @@ +package com.baeldung.streams.firstmatchingelement; + +public class User { + + private String userName; + private Integer userId; + + public User(Integer userId, String userName) { + this.userId = userId; + this.userName = userName; + } + + public String getUserName() { + return userName; + } + + public Integer getUserId() { + return userId; + } + +} diff --git a/core-java-modules/core-java-streams-5/src/test/java/com/baeldung/streams/firstmatchingelement/FirstMatchingElementUnitTest.java b/core-java-modules/core-java-streams-5/src/test/java/com/baeldung/streams/firstmatchingelement/FirstMatchingElementUnitTest.java new file mode 100644 index 0000000000..db9415e94b --- /dev/null +++ b/core-java-modules/core-java-streams-5/src/test/java/com/baeldung/streams/firstmatchingelement/FirstMatchingElementUnitTest.java @@ -0,0 +1,72 @@ +package com.baeldung.streams.firstmatchingelement; + + +import static org.junit.Assert.assertEquals; + +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.IntStream; + +import org.apache.commons.collections4.IterableUtils; +import org.junit.Test; + +import com.google.common.collect.Iterables; + +public class FirstMatchingElementUnitTest { + + private List userList = List.of(new User(1, "David"), new User(2, "John"), new User(3, "Roger"), new User(4, "John")); + private String searchName = "John"; + + @Test + public void whenUsingStream_thenFindFirstMatchingUserIndex() { + AtomicInteger counter = new AtomicInteger(-1); + int index = userList.stream() + .filter(user -> { + counter.getAndIncrement(); + return searchName.equals(user.getUserName()); + }) + .mapToInt(user -> counter.get()) + .findFirst() + .orElse(-1); + + assertEquals(1, index); + } + + @Test + public void whenUsingIntStream_thenFindFirstMatchingUserIndex() { + int index = IntStream.range(0, userList.size() - 1) + .filter(streamIndex -> searchName.equals(userList.get(streamIndex).getUserName())) + .findFirst() + .orElse(-1); + assertEquals(1, index); + } + + @Test + public void whenUsingTakeWhile_thenFindFirstMatchingUserIndex() { + long predicateIndex = userList.stream() + .takeWhile(user -> !user.getUserName().equals(searchName)) + .count(); + assertEquals(1, predicateIndex); + } + + @Test + public void whenUsingTakeWhile_thenFindIndexFromNoMatchingElement() { + List userList = List.of(new User(1, "David"), new User(2, "Vick"), new User(3, "Roger"), new User(4, "James")); + long predicateIndex = userList.stream() + .takeWhile(user -> !user.getUserName().equals(searchName)) + .count(); + assertEquals(4, predicateIndex); + } + + @Test + public void whenUsingGoogleGuava_thenFindFirstMatchingUserIndex() { + int index = Iterables.indexOf(userList, user -> searchName.equals(user.getUserName())); + assertEquals(1, index); + } + + @Test + public void whenUsingApacheCommons_thenFindFirstMatchingUserIndex() { + int index = IterableUtils.indexOf(userList, user -> searchName.equals(user.getUserName())); + assertEquals(1, index); + } +} From cf858a14930d2fa32de16b761f332c9895b1a551 Mon Sep 17 00:00:00 2001 From: panos-kakos <102670093+panos-kakos@users.noreply.github.com> Date: Tue, 5 Dec 2023 07:13:20 +0200 Subject: [PATCH 197/228] Java 27490 (#15217) * [JAVA-27490] Set java.version of JDK 9+ profile to JDK 17 * [JAVA-27490] Removed java.version from modules * [JAVA-27490] Commented modules that are failing * [JAVA-27490] Clean up * [JAVA-27490] Clean up --- .../core-groovy-2/gmavenplus-pom.xml | 1 - core-java-modules/core-java-12/pom.xml | 4 -- core-java-modules/core-java-13/pom.xml | 4 -- core-java-modules/core-java-15/pom.xml | 4 -- .../pom.xml | 1 - core-java-modules/pom.xml | 16 +++--- .../multi-module-caching/pom.xml | 2 - docker-modules/pom.xml | 4 -- httpclient-simple/pom.xml | 1 - jackson-simple/pom.xml | 1 - jhipster-6/bookstore-monolith/pom.xml | 1 - kubernetes-modules/kubernetes-spring/pom.xml | 4 -- lightrun/lightrun-api-service/pom.xml | 4 -- lightrun/lightrun-tasks-service/pom.xml | 4 -- lightrun/lightrun-users-service/pom.xml | 4 -- maven-modules/maven-exec-plugin/pom.xml | 1 - maven-modules/maven-generate-war/pom.xml | 3 - messaging-modules/pom.xml | 4 +- messaging-modules/postgres-notify/pom.xml | 3 - parent-boot-3/pom.xml | 3 - persistence-modules/fauna/pom.xml | 1 - persistence-modules/pom.xml | 10 ++-- persistence-modules/rethinkdb/pom.xml | 4 -- .../spring-data-cassandra-2/pom.xml | 1 - pom.xml | 56 +++++++++---------- .../spring-project/pom.xml | 3 - spring-boot-modules/pom.xml | 2 +- .../spring-boot-cassandre/pom.xml | 1 - spring-boot-modules/spring-boot-redis/pom.xml | 1 - .../spring-boot-telegram/pom.xml | 1 - spring-native/pom-nativeimage.xml | 3 - spring-pulsar/pom.xml | 1 - .../spring-security-azuread/pom.xml | 4 -- .../reactive-resource-server/pom.xml | 4 +- .../servlet-resource-server/pom.xml | 4 +- .../spring-security-saml2/pom.xml | 1 - spring-soap/pom.xml | 1 - .../pom.xml | 1 - spring-vault/pom.xml | 1 - testing-modules/pom.xml | 4 +- 40 files changed, 48 insertions(+), 125 deletions(-) diff --git a/core-groovy-modules/core-groovy-2/gmavenplus-pom.xml b/core-groovy-modules/core-groovy-2/gmavenplus-pom.xml index 975ad6f689..256b5e88ab 100644 --- a/core-groovy-modules/core-groovy-2/gmavenplus-pom.xml +++ b/core-groovy-modules/core-groovy-2/gmavenplus-pom.xml @@ -167,7 +167,6 @@ UTF-8 3.9 - 1.8 1.2.3 diff --git a/core-java-modules/core-java-12/pom.xml b/core-java-modules/core-java-12/pom.xml index 8165549d8c..ae61bdfad0 100644 --- a/core-java-modules/core-java-12/pom.xml +++ b/core-java-modules/core-java-12/pom.xml @@ -21,8 +21,4 @@ - - 17 - - \ No newline at end of file diff --git a/core-java-modules/core-java-13/pom.xml b/core-java-modules/core-java-13/pom.xml index 52cf227583..b8ec8cfdb9 100644 --- a/core-java-modules/core-java-13/pom.xml +++ b/core-java-modules/core-java-13/pom.xml @@ -13,8 +13,4 @@ 0.0.1-SNAPSHOT - - 17 - - \ No newline at end of file diff --git a/core-java-modules/core-java-15/pom.xml b/core-java-modules/core-java-15/pom.xml index 3996c69fa4..e6193b4ea3 100644 --- a/core-java-modules/core-java-15/pom.xml +++ b/core-java-modules/core-java-15/pom.xml @@ -26,8 +26,4 @@ - - 17 - - \ No newline at end of file diff --git a/core-java-modules/core-java-collections-conversions-2/pom.xml b/core-java-modules/core-java-collections-conversions-2/pom.xml index da6b6a564a..7723daa6db 100644 --- a/core-java-modules/core-java-collections-conversions-2/pom.xml +++ b/core-java-modules/core-java-collections-conversions-2/pom.xml @@ -43,7 +43,6 @@ 0.10.3 - 11 3.2.0 \ No newline at end of file diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml index c0c44eba9a..d20a1650b9 100644 --- a/core-java-modules/pom.xml +++ b/core-java-modules/pom.xml @@ -59,16 +59,16 @@ core-java-lang-oop-constructors-2 core-java-methods core-java-networking-3 - core-java-os + core-java-perf-2 core-java-streams-4 core-java-streams-5 core-java-streams-collect core-java-streams-maps core-java-string-algorithms-3 - core-java-string-operations-3 + core-java-string-operations-4 - core-java-string-operations-5 + core-java-time-measurements core-java-annotations @@ -123,13 +123,13 @@ core-java-io core-java-io-2 core-java-io-3 - core-java-io-4 + core-java-io-5 core-java-io-apis core-java-io-apis-2 core-java-io-conversions core-java-jar - core-java-jndi + core-java-jvm core-java-jvm-2 core-java-jvm-3 @@ -144,11 +144,11 @@ core-java-lang-oop-constructors core-java-lang-oop-patterns core-java-lang-oop-generics - core-java-lang-oop-modifiers + core-java-lang-oop-types core-java-lang-oop-types-2 core-java-lang-oop-inheritance - core-java-lang-oop-methods + core-java-lang-oop-others core-java-lang-operators core-java-lang-operators-2 @@ -185,8 +185,8 @@ core-java-string-algorithms core-java-string-algorithms-2 core-java-string-apis + core-java-swing - core-java-string-apis-2 core-java-string-conversions core-java-string-conversions-2 core-java-string-conversions-3 diff --git a/docker-modules/docker-caching/multi-module-caching/pom.xml b/docker-modules/docker-caching/multi-module-caching/pom.xml index bebfb85e8a..f2b52f246d 100644 --- a/docker-modules/docker-caching/multi-module-caching/pom.xml +++ b/docker-modules/docker-caching/multi-module-caching/pom.xml @@ -25,8 +25,6 @@ - UTF-8 - 1.8 32.1.3-jre diff --git a/docker-modules/pom.xml b/docker-modules/pom.xml index b4c5240718..4eeab746eb 100644 --- a/docker-modules/pom.xml +++ b/docker-modules/pom.xml @@ -24,8 +24,4 @@ docker-java-jar - - 11 - - \ No newline at end of file diff --git a/httpclient-simple/pom.xml b/httpclient-simple/pom.xml index a0f2dd6514..e0488bf0b1 100644 --- a/httpclient-simple/pom.xml +++ b/httpclient-simple/pom.xml @@ -203,7 +203,6 @@ - 17 1.16.0 diff --git a/jackson-simple/pom.xml b/jackson-simple/pom.xml index 2ba3868ee2..daa6504709 100644 --- a/jackson-simple/pom.xml +++ b/jackson-simple/pom.xml @@ -34,7 +34,6 @@ 2.16.0 - 17 \ No newline at end of file diff --git a/jhipster-6/bookstore-monolith/pom.xml b/jhipster-6/bookstore-monolith/pom.xml index efe3d2a118..0db1f46b1e 100644 --- a/jhipster-6/bookstore-monolith/pom.xml +++ b/jhipster-6/bookstore-monolith/pom.xml @@ -1125,7 +1125,6 @@ 3.0.0 - 11 2.12.6 v10.15.0 6.4.1 diff --git a/kubernetes-modules/kubernetes-spring/pom.xml b/kubernetes-modules/kubernetes-spring/pom.xml index 05532ab0b0..64322055d1 100644 --- a/kubernetes-modules/kubernetes-spring/pom.xml +++ b/kubernetes-modules/kubernetes-spring/pom.xml @@ -46,8 +46,4 @@ - - 11 - - \ No newline at end of file diff --git a/lightrun/lightrun-api-service/pom.xml b/lightrun/lightrun-api-service/pom.xml index b7ed5f951b..77dbbb8b99 100644 --- a/lightrun/lightrun-api-service/pom.xml +++ b/lightrun/lightrun-api-service/pom.xml @@ -40,8 +40,4 @@ - - 17 - - \ No newline at end of file diff --git a/lightrun/lightrun-tasks-service/pom.xml b/lightrun/lightrun-tasks-service/pom.xml index 2689a9794d..773c81a9d5 100644 --- a/lightrun/lightrun-tasks-service/pom.xml +++ b/lightrun/lightrun-tasks-service/pom.xml @@ -65,8 +65,4 @@ - - 17 - - \ No newline at end of file diff --git a/lightrun/lightrun-users-service/pom.xml b/lightrun/lightrun-users-service/pom.xml index 40594db725..0b3e856069 100644 --- a/lightrun/lightrun-users-service/pom.xml +++ b/lightrun/lightrun-users-service/pom.xml @@ -57,8 +57,4 @@ - - 17 - - \ No newline at end of file diff --git a/maven-modules/maven-exec-plugin/pom.xml b/maven-modules/maven-exec-plugin/pom.xml index 1bac52ae2c..370b344167 100644 --- a/maven-modules/maven-exec-plugin/pom.xml +++ b/maven-modules/maven-exec-plugin/pom.xml @@ -47,7 +47,6 @@ 1.2.6 3.11.0 3.1.0 - 1.8 \ No newline at end of file diff --git a/maven-modules/maven-generate-war/pom.xml b/maven-modules/maven-generate-war/pom.xml index 7de3f15298..d73ffe8b1d 100644 --- a/maven-modules/maven-generate-war/pom.xml +++ b/maven-modules/maven-generate-war/pom.xml @@ -70,10 +70,7 @@ - 11 2.17.1 - 11 - 11 \ No newline at end of file diff --git a/messaging-modules/pom.xml b/messaging-modules/pom.xml index 27524637ab..f96d57b960 100644 --- a/messaging-modules/pom.xml +++ b/messaging-modules/pom.xml @@ -20,8 +20,8 @@ jgroups rabbitmq spring-amqp - spring-apache-camel - spring-jms + + postgres-notify diff --git a/messaging-modules/postgres-notify/pom.xml b/messaging-modules/postgres-notify/pom.xml index 571065b98d..a9b930543b 100644 --- a/messaging-modules/postgres-notify/pom.xml +++ b/messaging-modules/postgres-notify/pom.xml @@ -46,9 +46,6 @@ - - 1.8 - diff --git a/parent-boot-3/pom.xml b/parent-boot-3/pom.xml index 9f9d6f7901..f1ab699c83 100644 --- a/parent-boot-3/pom.xml +++ b/parent-boot-3/pom.xml @@ -233,9 +233,6 @@ 3.1.5 5.8.2 0.9.17 - 17 - ${java.version} - ${java.version} 1.4.4 2.0.3 diff --git a/persistence-modules/fauna/pom.xml b/persistence-modules/fauna/pom.xml index c6350b37d7..4c37c2ae9e 100644 --- a/persistence-modules/fauna/pom.xml +++ b/persistence-modules/fauna/pom.xml @@ -58,7 +58,6 @@ - 17 4.2.0 diff --git a/persistence-modules/pom.xml b/persistence-modules/pom.xml index d9ee7e358c..41ff596ccf 100644 --- a/persistence-modules/pom.xml +++ b/persistence-modules/pom.xml @@ -60,15 +60,15 @@ solr spring-boot-persistence-2 - spring-boot-persistence-3 - spring-boot-mysql + + spring-boot-persistence spring-boot-persistence-h2 spring-boot-persistence-mongodb spring-boot-persistence-mongodb-2 spring-boot-persistence-mongodb-3 spring-data-arangodb - spring-data-cassandra + spring-data-cassandra-test spring-data-cosmosdb spring-data-couchbase-2 @@ -108,8 +108,8 @@ spring-jpa spring-jpa-2 spring-jdbc - spring-jdbc-2 - spring-jooq + spring-jdbc-2 + spring-mybatis spring-persistence-simple spring-data-yugabytedb diff --git a/persistence-modules/rethinkdb/pom.xml b/persistence-modules/rethinkdb/pom.xml index 17c7036ed3..352be80469 100644 --- a/persistence-modules/rethinkdb/pom.xml +++ b/persistence-modules/rethinkdb/pom.xml @@ -46,8 +46,4 @@ - - 17 - - diff --git a/persistence-modules/spring-data-cassandra-2/pom.xml b/persistence-modules/spring-data-cassandra-2/pom.xml index 01b5ce5ed6..6532da7f95 100644 --- a/persistence-modules/spring-data-cassandra-2/pom.xml +++ b/persistence-modules/spring-data-cassandra-2/pom.xml @@ -99,7 +99,6 @@ - 11 3.4.15 1.19.0 1.1.0 diff --git a/pom.xml b/pom.xml index 73a21684e4..6dc2fdb4c3 100644 --- a/pom.xml +++ b/pom.xml @@ -715,7 +715,7 @@ azure bazel checker-framework - core-groovy-modules + core-java-modules custom-pmd data-structures @@ -756,7 +756,7 @@ jersey jetbrains jgit - jhipster-6 + jib jmeter jmh @@ -800,7 +800,7 @@ lombok-modules lucene mapstruct - maven-modules + mesos-marathon messaging-modules metrics @@ -836,19 +836,19 @@ spring-activiti spring-actuator spring-aop-2 - spring-aop + spring-batch-2 spring-batch spring-boot-modules spring-boot-rest spring-cloud-modules/spring-cloud-azure spring-cloud-modules/spring-cloud-circuit-breaker - spring-cloud-modules/spring-cloud-contract - spring-cloud-modules/spring-cloud-data-flow + + spring-cloud-modules/spring-cloud-eureka spring-cloud-modules/spring-cloud-netflix-feign spring-cloud-modules/spring-cloud-security - spring-cloud-modules/spring-cloud-stream-starters + spring-cloud-modules/spring-cloud-zuul-eureka-integration spring-core-2 spring-core-3 @@ -856,14 +856,14 @@ spring-core spring-credhub spring-cucumber - spring-di-2 + spring-di-3 spring-di-4 spring-di spring-drools spring-ejb-modules spring-exceptions - spring-integration + spring-jenkins-pipeline spring-jersey spring-jinq @@ -891,7 +891,7 @@ spring-web-modules spring-websockets - tablesaw + tensorflow-java testing-modules testing-modules/mockito-simple @@ -900,16 +900,16 @@ vertx-modules web-modules webrtc - xml-2 + xml xstream UTF-8 - 11 - 11 - 11 + 17 + 17 + 17 @@ -961,7 +961,7 @@ azure bazel checker-framework - core-groovy-modules + core-java-modules custom-pmd data-structures @@ -1002,7 +1002,7 @@ jersey jetbrains jgit - jhipster-6 + jib jmeter jmh @@ -1046,7 +1046,7 @@ lombok-modules lucene mapstruct - maven-modules + mesos-marathon messaging-modules metrics @@ -1081,19 +1081,19 @@ spring-activiti spring-actuator spring-aop-2 - spring-aop + spring-batch-2 spring-batch spring-boot-modules spring-boot-rest spring-cloud-modules/spring-cloud-azure spring-cloud-modules/spring-cloud-circuit-breaker - spring-cloud-modules/spring-cloud-contract - spring-cloud-modules/spring-cloud-data-flow + + spring-cloud-modules/spring-cloud-eureka spring-cloud-modules/spring-cloud-netflix-feign spring-cloud-modules/spring-cloud-security - spring-cloud-modules/spring-cloud-stream-starters + spring-cloud-modules/spring-cloud-zuul-eureka-integration spring-core-2 spring-core-3 @@ -1101,14 +1101,14 @@ spring-core spring-credhub spring-cucumber - spring-di-2 + spring-di-3 spring-di-4 spring-di spring-drools spring-ejb-modules spring-exceptions - spring-integration + spring-jenkins-pipeline spring-jersey spring-jinq @@ -1135,7 +1135,7 @@ spring-web-modules spring-websockets - tablesaw + tensorflow-java testing-modules testing-modules/mockito-simple @@ -1144,16 +1144,16 @@ vertx-modules web-modules webrtc - xml-2 + xml xstream UTF-8 - 11 - 11 - 11 + 17 + 17 + 17 diff --git a/quarkus-modules/quarkus-vs-springboot/spring-project/pom.xml b/quarkus-modules/quarkus-vs-springboot/spring-project/pom.xml index 74deab3558..c3ee41223f 100644 --- a/quarkus-modules/quarkus-vs-springboot/spring-project/pom.xml +++ b/quarkus-modules/quarkus-vs-springboot/spring-project/pom.xml @@ -253,10 +253,7 @@ 1.17.2 - 11 0.12.1 - 11 - 11 3.1.0 0.9.11 2.0.8 diff --git a/spring-boot-modules/pom.xml b/spring-boot-modules/pom.xml index 433f23f4ba..eaf04cf015 100644 --- a/spring-boot-modules/pom.xml +++ b/spring-boot-modules/pom.xml @@ -42,7 +42,7 @@ spring-boot-exceptions spring-boot-flowable spring-boot-graphql - spring-boot-groovy + spring-boot-jasypt spring-boot-jsp diff --git a/spring-boot-modules/spring-boot-cassandre/pom.xml b/spring-boot-modules/spring-boot-cassandre/pom.xml index e2964183d2..3834d7b88c 100644 --- a/spring-boot-modules/spring-boot-cassandre/pom.xml +++ b/spring-boot-modules/spring-boot-cassandre/pom.xml @@ -40,7 +40,6 @@ - 11 4.2.1 5.0.7 2.5.1 diff --git a/spring-boot-modules/spring-boot-redis/pom.xml b/spring-boot-modules/spring-boot-redis/pom.xml index fa6b5a59c1..57a894e2fc 100644 --- a/spring-boot-modules/spring-boot-redis/pom.xml +++ b/spring-boot-modules/spring-boot-redis/pom.xml @@ -73,7 +73,6 @@ - 15 6.0.3 0.7.3 diff --git a/spring-boot-modules/spring-boot-telegram/pom.xml b/spring-boot-modules/spring-boot-telegram/pom.xml index 9077e90400..a26566819a 100644 --- a/spring-boot-modules/spring-boot-telegram/pom.xml +++ b/spring-boot-modules/spring-boot-telegram/pom.xml @@ -39,7 +39,6 @@ - 17 6.7.0 diff --git a/spring-native/pom-nativeimage.xml b/spring-native/pom-nativeimage.xml index 6d42bedbe1..4fc01e4574 100644 --- a/spring-native/pom-nativeimage.xml +++ b/spring-native/pom-nativeimage.xml @@ -114,9 +114,6 @@ 2.7.1 0.12.1 0.9.17 - 1.8 - 1.8 - 1.8 diff --git a/spring-pulsar/pom.xml b/spring-pulsar/pom.xml index a1c834f830..b2feaddfb1 100644 --- a/spring-pulsar/pom.xml +++ b/spring-pulsar/pom.xml @@ -43,7 +43,6 @@ - 17 0.2.0 diff --git a/spring-security-modules/spring-security-azuread/pom.xml b/spring-security-modules/spring-security-azuread/pom.xml index 11d6b876c1..b32a1eb16a 100644 --- a/spring-security-modules/spring-security-azuread/pom.xml +++ b/spring-security-modules/spring-security-azuread/pom.xml @@ -11,10 +11,6 @@ spring-security-azuread - - 1.8 - - org.springframework.boot diff --git a/spring-security-modules/spring-security-oauth2-testing/reactive-resource-server/pom.xml b/spring-security-modules/spring-security-oauth2-testing/reactive-resource-server/pom.xml index 3d5ff0cb69..a5ce06f4d9 100644 --- a/spring-security-modules/spring-security-oauth2-testing/reactive-resource-server/pom.xml +++ b/spring-security-modules/spring-security-oauth2-testing/reactive-resource-server/pom.xml @@ -12,9 +12,7 @@ reactive-resource-server reactive-resource-server Demo project for Spring Boot reactive resource-server - - 17 - + org.springframework.boot diff --git a/spring-security-modules/spring-security-oauth2-testing/servlet-resource-server/pom.xml b/spring-security-modules/spring-security-oauth2-testing/servlet-resource-server/pom.xml index eb507fc3d3..44403cf341 100644 --- a/spring-security-modules/spring-security-oauth2-testing/servlet-resource-server/pom.xml +++ b/spring-security-modules/spring-security-oauth2-testing/servlet-resource-server/pom.xml @@ -12,9 +12,7 @@ servlet-resource-server servlet-resource-server Demo project for Spring Boot servlet resource-server - - 17 - + org.springframework.boot diff --git a/spring-security-modules/spring-security-saml2/pom.xml b/spring-security-modules/spring-security-saml2/pom.xml index 6de69fd201..64a4e22627 100644 --- a/spring-security-modules/spring-security-saml2/pom.xml +++ b/spring-security-modules/spring-security-saml2/pom.xml @@ -82,7 +82,6 @@ - 17 4.1.1 diff --git a/spring-soap/pom.xml b/spring-soap/pom.xml index 6c49f1f39c..c796b08e9a 100644 --- a/spring-soap/pom.xml +++ b/spring-soap/pom.xml @@ -102,7 +102,6 @@ - 17 4.0.0 3.1.0 0.15.3 diff --git a/spring-swagger-codegen/custom-validations-opeanpi-codegen/pom.xml b/spring-swagger-codegen/custom-validations-opeanpi-codegen/pom.xml index ded02da62c..b1c2bf61f1 100644 --- a/spring-swagger-codegen/custom-validations-opeanpi-codegen/pom.xml +++ b/spring-swagger-codegen/custom-validations-opeanpi-codegen/pom.xml @@ -83,7 +83,6 @@ - 11 3.0.0 2.17.1 1.7.0 diff --git a/spring-vault/pom.xml b/spring-vault/pom.xml index b3690c7b7f..768303cb4b 100644 --- a/spring-vault/pom.xml +++ b/spring-vault/pom.xml @@ -83,7 +83,6 @@ 2.3.4 2.20.140 3.1.3 - 17 \ No newline at end of file diff --git a/testing-modules/pom.xml b/testing-modules/pom.xml index fa72b1e696..b2e73570d5 100644 --- a/testing-modules/pom.xml +++ b/testing-modules/pom.xml @@ -34,8 +34,8 @@ load-testing-comparison mockito - mocks - mocks-2 + + mockserver parallel-tests-junit powermock From d935c4fe23efbfd30039e81b3ce6fd186841922b Mon Sep 17 00:00:00 2001 From: Sameer Date: Tue, 5 Dec 2023 12:04:33 +0530 Subject: [PATCH 198/228] BAEL 7138 Difference between String and StringBuffer in Java (#15351) * string vs stringBuffer comparison * BAEL-7138 Difference between String and StringBuffer in Java --------- Co-authored-by: Sahil --- .../main/java/com/baeldung/stringbuffer/ComparePerformance.java | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-strings/src/main/java/com/baeldung/stringbuffer/ComparePerformance.java b/core-java-modules/core-java-strings/src/main/java/com/baeldung/stringbuffer/ComparePerformance.java index 28cd2e64e9..4d045fe318 100644 --- a/core-java-modules/core-java-strings/src/main/java/com/baeldung/stringbuffer/ComparePerformance.java +++ b/core-java-modules/core-java-strings/src/main/java/com/baeldung/stringbuffer/ComparePerformance.java @@ -28,6 +28,7 @@ public class ComparePerformance { @Benchmark public String benchmarkStringConcatenation() { + strFinal = ""; strFinal += strInitial; return strFinal; } From 11c468f576ae5374cb111718436c57d69bd07533 Mon Sep 17 00:00:00 2001 From: Kai Yuan Date: Wed, 6 Dec 2023 03:18:19 +0100 Subject: [PATCH 199/228] [bigdecimal-zero] bigdecimal zero vs constructor (#15355) --- ...BigDecimalZeroVsNewBigDecimalUnitTest.java | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 core-java-modules/core-java-numbers-7/src/test/java/com/baeldung/bigdecimalzero/BigDecimalZeroVsNewBigDecimalUnitTest.java diff --git a/core-java-modules/core-java-numbers-7/src/test/java/com/baeldung/bigdecimalzero/BigDecimalZeroVsNewBigDecimalUnitTest.java b/core-java-modules/core-java-numbers-7/src/test/java/com/baeldung/bigdecimalzero/BigDecimalZeroVsNewBigDecimalUnitTest.java new file mode 100644 index 0000000000..a10a615e2f --- /dev/null +++ b/core-java-modules/core-java-numbers-7/src/test/java/com/baeldung/bigdecimalzero/BigDecimalZeroVsNewBigDecimalUnitTest.java @@ -0,0 +1,39 @@ +package com.baeldung.bigdecimalzero; + +import org.junit.jupiter.api.Test; + +import java.math.BigDecimal; + +import static org.junit.jupiter.api.Assertions.*; + +public class BigDecimalZeroVsNewBigDecimalUnitTest { + @Test + void whenComparingZeroAndNewBigDecimal_thenGetExpectedResult() { + BigDecimal bd1 = new BigDecimal("42.00"); + BigDecimal bd2 = new BigDecimal("42.0000"); + assertEquals(0, bd1.compareTo(bd2)); + + assertNotEquals(bd1, bd2); + + BigDecimal zero0 = new BigDecimal(0); + assertNotEquals(zero0, new BigDecimal("0.000")); + + BigDecimal zero = BigDecimal.ZERO; + assertEquals(zero, zero0); + } + + @Test + void whenCallingBigDecimalZero_thenAlwaysGetTheSameObject() { + BigDecimal z1 = BigDecimal.ZERO; + BigDecimal z2 = BigDecimal.ZERO; + assertSame(z1, z2); + } + + @Test + void whenCallingNewBigDecimal_thenAlwaysGetTheSameObject() { + BigDecimal z1 = new BigDecimal(0); + BigDecimal z2 = new BigDecimal(0); + assertNotSame(z1, z2); + } + +} \ No newline at end of file From 155389fbc29f6e862104d60bffa1c18cb9e40685 Mon Sep 17 00:00:00 2001 From: panos-kakos <102670093+panos-kakos@users.noreply.github.com> Date: Wed, 6 Dec 2023 14:25:31 +0200 Subject: [PATCH 200/228] [JAVA-27738] (#15363) * [JAVA-27738] Upgraded core-groovy modules to jdk 17 * [JAVA-27738] Re enabled core-groovy modules * [JAVA-27738] Formatting --- core-groovy-modules/core-groovy-2/pom.xml | 11 +++++++++-- pom.xml | 4 ++-- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/core-groovy-modules/core-groovy-2/pom.xml b/core-groovy-modules/core-groovy-2/pom.xml index de750daf0f..cc1d860ad1 100644 --- a/core-groovy-modules/core-groovy-2/pom.xml +++ b/core-groovy-modules/core-groovy-2/pom.xml @@ -13,6 +13,13 @@ 1.0.0-SNAPSHOT + + + groovy-plugins-release + https://groovy.jfrog.io/artifactory/plugins-release-local + + + org.apache.commons @@ -156,8 +163,8 @@ 1.1.3 3.4.2 3.8.1 - 3.7.0 - 3.0.8-01 + 3.9.0 + 3.0.9-03 diff --git a/pom.xml b/pom.xml index 6dc2fdb4c3..eb780e5168 100644 --- a/pom.xml +++ b/pom.xml @@ -715,7 +715,7 @@ azure bazel checker-framework - + core-groovy-modules core-java-modules custom-pmd data-structures @@ -961,7 +961,7 @@ azure bazel checker-framework - + core-groovy-modules core-java-modules custom-pmd data-structures From b6f45db73d3771fdc4b84fa823eb308fc640e869 Mon Sep 17 00:00:00 2001 From: parthiv39731 <70740707+parthiv39731@users.noreply.github.com> Date: Wed, 6 Dec 2023 18:55:46 +0530 Subject: [PATCH 201/228] BAEL-6910, Renamed to LiveTest --- ...Test.java => CassandraConnectionDetailsLiveTest.java} | 9 +++++++-- ...Test.java => CouchbaseConnectionDetailsLiveTest.java} | 7 ++++++- ....java => ElasticsearchConnectionDetailsLiveTest.java} | 9 +++++++-- ...ationTest.java => JdbcConnectionDetailsLiveTest.java} | 9 +++++++-- ...tionTest.java => KafkaConnectionDetailsLiveTest.java} | 7 ++++++- ...onTest.java => MongoDBConnectionDetailsLiveTest.java} | 7 ++++++- ...tionTest.java => Neo4jConnectionDetailsLiveTest.java} | 7 ++++++- ...tionTest.java => R2dbcConnectionDetailsLiveTest.java} | 9 +++++++-- ...nTest.java => RabbitmqConnectionDetailsLiveTest.java} | 9 +++++++-- ...st.java => RedisCacheConnnectionDetailsLiveTest.java} | 9 +++++++-- 10 files changed, 66 insertions(+), 16 deletions(-) rename spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/{CassandraConnectionDetailsIntegrationTest.java => CassandraConnectionDetailsLiveTest.java} (80%) rename spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/{CouchbaseConnectionDetailsIntegrationTest.java => CouchbaseConnectionDetailsLiveTest.java} (77%) rename spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/{ElasticsearchConnectionDetailsIntegrationTest.java => ElasticsearchConnectionDetailsLiveTest.java} (81%) rename spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/{JdbcConnectionDetailsIntegrationTest.java => JdbcConnectionDetailsLiveTest.java} (79%) rename spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/{KafkaConnectionDetailsIntegrationTest.java => KafkaConnectionDetailsLiveTest.java} (78%) rename spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/{MongoDBConnectionDetailsIntegrationTest.java => MongoDBConnectionDetailsLiveTest.java} (85%) rename spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/{Neo4jConnectionDetailsIntegrationTest.java => Neo4jConnectionDetailsLiveTest.java} (81%) rename spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/{R2dbcConnectionDetailsIntegrationTest.java => R2dbcConnectionDetailsLiveTest.java} (80%) rename spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/{RabbitmqConnectionDetailsIntegrationTest.java => RabbitmqConnectionDetailsLiveTest.java} (85%) rename spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/{RedisCacheConnnectionDetailsIntegrationTest.java => RedisCacheConnnectionDetailsLiveTest.java} (76%) diff --git a/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/CassandraConnectionDetailsIntegrationTest.java b/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/CassandraConnectionDetailsLiveTest.java similarity index 80% rename from spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/CassandraConnectionDetailsIntegrationTest.java rename to spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/CassandraConnectionDetailsLiveTest.java index 4130b6cb6b..9198cc1f68 100644 --- a/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/CassandraConnectionDetailsIntegrationTest.java +++ b/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/CassandraConnectionDetailsLiveTest.java @@ -1,3 +1,8 @@ +/** + * These test cases have dependency with docker because they pull the docker images from docker hub + * and run the container. So, please make sure to install docker before running the tests. + * For the image details please look into the docker-compose files under resources/connectiondetails/docker + **/ package com.baeldung.connectiondetails; import com.baeldung.connectiondetails.configuration.CustomCassandraConnectionDetailsConfiguration; @@ -22,8 +27,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue; @ComponentScan(basePackages = "com.baeldung.connectiondetails") @TestPropertySource(locations = {"classpath:connectiondetails/application-cassandra.properties"}) @ActiveProfiles("cassandra") -public class CassandraConnectionDetailsIntegrationTest { - private static final Logger logger = LoggerFactory.getLogger(CassandraConnectionDetailsIntegrationTest.class); +public class CassandraConnectionDetailsLiveTest { + private static final Logger logger = LoggerFactory.getLogger(CassandraConnectionDetailsLiveTest.class); @Autowired private CassandraTemplate cassandraTemplate; @Test diff --git a/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/CouchbaseConnectionDetailsIntegrationTest.java b/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/CouchbaseConnectionDetailsLiveTest.java similarity index 77% rename from spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/CouchbaseConnectionDetailsIntegrationTest.java rename to spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/CouchbaseConnectionDetailsLiveTest.java index 454aad4c6c..6f19382950 100644 --- a/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/CouchbaseConnectionDetailsIntegrationTest.java +++ b/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/CouchbaseConnectionDetailsLiveTest.java @@ -1,3 +1,8 @@ +/** + * These test cases have dependency with docker because they pull the docker images from docker hub + * and run the container. So, please make sure to install docker before running the tests. + * For the image details please look into the docker-compose files under resources/connectiondetails/docker + **/ package com.baeldung.connectiondetails; import com.baeldung.connectiondetails.configuration.CustomCouchBaseConnectionDetailsConfiguration; @@ -20,7 +25,7 @@ import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; @ComponentScan(basePackages = "com.baeldung.connectiondetails") @TestPropertySource(locations = {"classpath:connectiondetails/application-couch.properties"}) @ActiveProfiles("couch") -public class CouchbaseConnectionDetailsIntegrationTest { +public class CouchbaseConnectionDetailsLiveTest { @Autowired private Cluster cluster; @Test diff --git a/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/ElasticsearchConnectionDetailsIntegrationTest.java b/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/ElasticsearchConnectionDetailsLiveTest.java similarity index 81% rename from spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/ElasticsearchConnectionDetailsIntegrationTest.java rename to spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/ElasticsearchConnectionDetailsLiveTest.java index ee698cd6ea..10d0e9d019 100644 --- a/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/ElasticsearchConnectionDetailsIntegrationTest.java +++ b/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/ElasticsearchConnectionDetailsLiveTest.java @@ -1,3 +1,8 @@ +/** + * These test cases have dependency with docker because they pull the docker images from docker hub + * and run the container. So, please make sure to install docker before running the tests. + * For the image details please look into the docker-compose files under resources/connectiondetails/docker + **/ package com.baeldung.connectiondetails; import com.baeldung.connectiondetails.configuration.CustomElasticsearchConnectionDetailsConfiguration; @@ -24,8 +29,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue; @ComponentScan(basePackages = "com.baeldung.connectiondetails") @TestPropertySource(locations = {"classpath:connectiondetails/application-elastic.properties"}) @ActiveProfiles("elastic") -public class ElasticsearchConnectionDetailsIntegrationTest { - private static final Logger logger = LoggerFactory.getLogger(ElasticsearchConnectionDetailsIntegrationTest.class); +public class ElasticsearchConnectionDetailsLiveTest { + private static final Logger logger = LoggerFactory.getLogger(ElasticsearchConnectionDetailsLiveTest.class); @Autowired private ElasticsearchTemplate elasticsearchTemplate; diff --git a/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/JdbcConnectionDetailsIntegrationTest.java b/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/JdbcConnectionDetailsLiveTest.java similarity index 79% rename from spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/JdbcConnectionDetailsIntegrationTest.java rename to spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/JdbcConnectionDetailsLiveTest.java index 748bc27b0b..b074eb9bfd 100644 --- a/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/JdbcConnectionDetailsIntegrationTest.java +++ b/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/JdbcConnectionDetailsLiveTest.java @@ -1,3 +1,8 @@ +/** + * These test cases have dependency with docker because they pull the docker images from docker hub + * and run the container. So, please make sure to install docker before running the tests. + * For the image details please look into the docker-compose files under resources/connectiondetails/docker + **/ package com.baeldung.connectiondetails; import com.baeldung.connectiondetails.configuration.JdbcConnectionDetailsConfiguration; @@ -25,8 +30,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals; @ComponentScan(basePackages = "com.baeldung.connectiondetails") @TestPropertySource(locations = {"classpath:connectiondetails/application-jdbc.properties"}) @ActiveProfiles("jdbc") -public class JdbcConnectionDetailsIntegrationTest { - private static final Logger logger = LoggerFactory.getLogger(JdbcConnectionDetailsIntegrationTest.class); +public class JdbcConnectionDetailsLiveTest { + private static final Logger logger = LoggerFactory.getLogger(JdbcConnectionDetailsLiveTest.class); @Autowired private JdbcTemplate jdbcTemplate; @Test diff --git a/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/KafkaConnectionDetailsIntegrationTest.java b/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/KafkaConnectionDetailsLiveTest.java similarity index 78% rename from spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/KafkaConnectionDetailsIntegrationTest.java rename to spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/KafkaConnectionDetailsLiveTest.java index bc0e174b3f..f23e610d3a 100644 --- a/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/KafkaConnectionDetailsIntegrationTest.java +++ b/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/KafkaConnectionDetailsLiveTest.java @@ -1,3 +1,8 @@ +/** + * These test cases have dependency with docker because they pull the docker images from docker hub + * and run the container. So, please make sure to install docker before running the tests. + * For the image details please look into the docker-compose files under resources/connectiondetails/docker + **/ package com.baeldung.connectiondetails; import com.baeldung.connectiondetails.configuration.CustomKafkaConnectionDetailsConfiguration; @@ -21,7 +26,7 @@ import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; @ComponentScan(basePackages = "com.baeldung.connectiondetails") @TestPropertySource(locations = {"classpath:connectiondetails/application-kafka.properties"}) @ActiveProfiles("kafka") -public class KafkaConnectionDetailsIntegrationTest { +public class KafkaConnectionDetailsLiveTest { @Autowired private KafkaTemplate kafkaTemplate; diff --git a/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/MongoDBConnectionDetailsIntegrationTest.java b/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/MongoDBConnectionDetailsLiveTest.java similarity index 85% rename from spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/MongoDBConnectionDetailsIntegrationTest.java rename to spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/MongoDBConnectionDetailsLiveTest.java index 868ebfea98..e2dceff9ec 100644 --- a/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/MongoDBConnectionDetailsIntegrationTest.java +++ b/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/MongoDBConnectionDetailsLiveTest.java @@ -1,3 +1,8 @@ +/** + * These test cases have dependency with docker because they pull the docker images from docker hub + * and run the container. So, please make sure to install docker before running the tests. + * For the image details please look into the docker-compose files under resources/connectiondetails/docker + **/ package com.baeldung.connectiondetails; import com.baeldung.connectiondetails.configuration.MongoDBConnectionDetailsConfiguration; @@ -26,7 +31,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; @ComponentScan(basePackages = "com.baeldung.connectiondetails") @TestPropertySource(locations = {"classpath:connectiondetails/application-mongo.properties"}) @ActiveProfiles("mongo") -public class MongoDBConnectionDetailsIntegrationTest { +public class MongoDBConnectionDetailsLiveTest { @Autowired private MongoTemplate mongoTemplate; diff --git a/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/Neo4jConnectionDetailsIntegrationTest.java b/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/Neo4jConnectionDetailsLiveTest.java similarity index 81% rename from spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/Neo4jConnectionDetailsIntegrationTest.java rename to spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/Neo4jConnectionDetailsLiveTest.java index 943ed7bdea..8eb9ec44d2 100644 --- a/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/Neo4jConnectionDetailsIntegrationTest.java +++ b/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/Neo4jConnectionDetailsLiveTest.java @@ -1,3 +1,8 @@ +/** + * These test cases have dependency with docker because they pull the docker images from docker hub + * and run the container. So, please make sure to install docker before running the tests. + * For the image details please look into the docker-compose files under resources/connectiondetails/docker + **/ package com.baeldung.connectiondetails; import com.baeldung.connectiondetails.configuration.CustomNeo4jConnectionDetailsConfiguration; @@ -22,7 +27,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; @ComponentScan(basePackages = "com.baeldung.connectiondetails") @TestPropertySource(locations = {"classpath:connectiondetails/application-neo4j.properties"}) @ActiveProfiles("neo4j") -public class Neo4jConnectionDetailsIntegrationTest { +public class Neo4jConnectionDetailsLiveTest { @Autowired private Neo4jTemplate neo4jTemplate; diff --git a/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/R2dbcConnectionDetailsIntegrationTest.java b/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/R2dbcConnectionDetailsLiveTest.java similarity index 80% rename from spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/R2dbcConnectionDetailsIntegrationTest.java rename to spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/R2dbcConnectionDetailsLiveTest.java index 5f8c8349fb..460a48e7ff 100644 --- a/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/R2dbcConnectionDetailsIntegrationTest.java +++ b/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/R2dbcConnectionDetailsLiveTest.java @@ -1,3 +1,8 @@ +/** + * These test cases have dependency with docker because they pull the docker images from docker hub + * and run the container. So, please make sure to install docker before running the tests. + * For the image details please look into the docker-compose files under resources/connectiondetails/docker + **/ package com.baeldung.connectiondetails; import com.baeldung.connectiondetails.configuration.R2dbcPostgresConnectionDetailsConfiguration; @@ -20,8 +25,8 @@ import java.util.List; @Import(R2dbcPostgresConnectionDetailsConfiguration.class) @TestPropertySource(locations = {"classpath:connectiondetails/application-r2dbc.properties"}) @ActiveProfiles("r2dbc") -public class R2dbcConnectionDetailsIntegrationTest { - Logger logger = LoggerFactory.getLogger(R2dbcConnectionDetailsIntegrationTest.class); +public class R2dbcConnectionDetailsLiveTest { + Logger logger = LoggerFactory.getLogger(R2dbcConnectionDetailsLiveTest.class); @Autowired private R2dbcEntityTemplate r2dbcEntityTemplate; diff --git a/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/RabbitmqConnectionDetailsIntegrationTest.java b/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/RabbitmqConnectionDetailsLiveTest.java similarity index 85% rename from spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/RabbitmqConnectionDetailsIntegrationTest.java rename to spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/RabbitmqConnectionDetailsLiveTest.java index 9e10973ed7..5f7eb055eb 100644 --- a/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/RabbitmqConnectionDetailsIntegrationTest.java +++ b/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/RabbitmqConnectionDetailsLiveTest.java @@ -1,3 +1,8 @@ +/** + * These test cases have dependency with docker because they pull the docker images from docker hub + * and run the container. So, please make sure to install docker before running the tests. + * For the image details please look into the docker-compose files under resources/connectiondetails/docker + **/ package com.baeldung.connectiondetails; import com.baeldung.connectiondetails.configuration.RabbitMQConnectionDetailsConfiguration; @@ -25,9 +30,9 @@ import static org.junit.jupiter.api.Assertions.assertEquals; @Import(RabbitMQConnectionDetailsConfiguration.class) @TestPropertySource(locations = {"classpath:connectiondetails/application-rabbitmq.properties"}) @ActiveProfiles("rabbitmq") -public class RabbitmqConnectionDetailsIntegrationTest { +public class RabbitmqConnectionDetailsLiveTest { - private static final Logger logger = LoggerFactory.getLogger(RabbitmqConnectionDetailsIntegrationTest.class); + private static final Logger logger = LoggerFactory.getLogger(RabbitmqConnectionDetailsLiveTest.class); @Autowired private RabbitTemplate rabbitTemplate; diff --git a/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/RedisCacheConnnectionDetailsIntegrationTest.java b/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/RedisCacheConnnectionDetailsLiveTest.java similarity index 76% rename from spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/RedisCacheConnnectionDetailsIntegrationTest.java rename to spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/RedisCacheConnnectionDetailsLiveTest.java index 5dbd2d6c03..919f968323 100644 --- a/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/RedisCacheConnnectionDetailsIntegrationTest.java +++ b/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/connectiondetails/RedisCacheConnnectionDetailsLiveTest.java @@ -1,3 +1,8 @@ +/** + * These test cases have dependency with docker because they pull the docker images from docker hub + * and run the container. So, please make sure to install docker before running the tests. + * For the image details please look into the docker-compose files under resources/connectiondetails/docker + **/ package com.baeldung.connectiondetails; import com.baeldung.connectiondetails.configuration.RedisConnectionDetailsConfiguration; @@ -20,8 +25,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals; @Import(RedisConnectionDetailsConfiguration.class) @TestPropertySource(locations = {"classpath:connectiondetails/application-redis.properties"}) @ActiveProfiles("redis") -public class RedisCacheConnnectionDetailsIntegrationTest { - private static final Logger logger = LoggerFactory.getLogger(RedisCacheConnnectionDetailsIntegrationTest.class); +public class RedisCacheConnnectionDetailsLiveTest { + private static final Logger logger = LoggerFactory.getLogger(RedisCacheConnnectionDetailsLiveTest.class); @Autowired RedisTemplate redisTemplate; From e144d0599bb78ccf86b5e0c62fd8e571180d764b Mon Sep 17 00:00:00 2001 From: Bipin kumar Date: Wed, 6 Dec 2023 21:47:52 +0530 Subject: [PATCH 202/228] Java 28508 Fix formatting of POMs Modules A to C (#15359) --- apache-kafka-2/pom.xml | 2 +- aws-modules/aws-dynamodb/pom.xml | 4 +- aws-modules/pom.xml | 13 ++--- core-java-modules/core-java-20/pom.xml | 54 +++++++++---------- .../pom.xml | 2 +- .../core-java-collections-maps-6/pom.xml | 7 +-- .../core-java-collections-maps-7/pom.xml | 14 ++--- .../core-java-reflection-3/pom.xml | 4 +- .../core-java-string-operations-2/pom.xml | 8 +-- 9 files changed, 56 insertions(+), 52 deletions(-) diff --git a/apache-kafka-2/pom.xml b/apache-kafka-2/pom.xml index cd21a60e14..dedd5df602 100644 --- a/apache-kafka-2/pom.xml +++ b/apache-kafka-2/pom.xml @@ -55,7 +55,7 @@ com.fasterxml.jackson.core jackson-databind - ${jackson.databind.version} + ${jackson.databind.version} diff --git a/aws-modules/aws-dynamodb/pom.xml b/aws-modules/aws-dynamodb/pom.xml index adce036733..155d48c240 100644 --- a/aws-modules/aws-dynamodb/pom.xml +++ b/aws-modules/aws-dynamodb/pom.xml @@ -1,7 +1,7 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 aws-dynamodb 0.1.0-SNAPSHOT diff --git a/aws-modules/pom.xml b/aws-modules/pom.xml index 06cea2f260..ce27a4f2e0 100644 --- a/aws-modules/pom.xml +++ b/aws-modules/pom.xml @@ -5,6 +5,13 @@ 4.0.0 aws-modules aws-modules + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + com.amazonaws @@ -15,12 +22,6 @@ pom - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - aws-app-sync aws-dynamodb diff --git a/core-java-modules/core-java-20/pom.xml b/core-java-modules/core-java-20/pom.xml index ad0a956b80..68c6ca4c93 100644 --- a/core-java-modules/core-java-20/pom.xml +++ b/core-java-modules/core-java-20/pom.xml @@ -3,19 +3,34 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 + core-java-20 + com.baeldung.core-java-modules core-java-modules 0.0.1-SNAPSHOT - core-java-20 - - - 20 - 20 - UTF-8 - + + + jakarta.servlet + jakarta.servlet-api + 6.0.0 + provided + + + org.assertj + assertj-core + 3.24.2 + test + + + org.mockito + mockito-junit-jupiter + 5.2.0 + test + + @@ -41,25 +56,10 @@ - - - jakarta.servlet - jakarta.servlet-api - 6.0.0 - provided - - - org.assertj - assertj-core - 3.24.2 - test - - - org.mockito - mockito-junit-jupiter - 5.2.0 - test - - + + 20 + 20 + UTF-8 + \ No newline at end of file diff --git a/core-java-modules/core-java-arrays-operations-advanced/pom.xml b/core-java-modules/core-java-arrays-operations-advanced/pom.xml index 52787cc0c9..265577f75e 100644 --- a/core-java-modules/core-java-arrays-operations-advanced/pom.xml +++ b/core-java-modules/core-java-arrays-operations-advanced/pom.xml @@ -57,7 +57,7 @@ - + 11 diff --git a/core-java-modules/core-java-collections-maps-6/pom.xml b/core-java-modules/core-java-collections-maps-6/pom.xml index eec59616e7..a0cdc07644 100644 --- a/core-java-modules/core-java-collections-maps-6/pom.xml +++ b/core-java-modules/core-java-collections-maps-6/pom.xml @@ -13,9 +13,6 @@ 0.0.1-SNAPSHOT - - 5.2.5.RELEASE - com.fasterxml.jackson.core @@ -51,4 +48,8 @@ + + 5.2.5.RELEASE + + \ No newline at end of file diff --git a/core-java-modules/core-java-collections-maps-7/pom.xml b/core-java-modules/core-java-collections-maps-7/pom.xml index 2d08c0a438..bd355bea1e 100644 --- a/core-java-modules/core-java-collections-maps-7/pom.xml +++ b/core-java-modules/core-java-collections-maps-7/pom.xml @@ -1,15 +1,11 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 core-java-collections-maps-7 core-java-collections-maps-7 jar - - 2.10.1 - 1.5 - core-java-modules @@ -63,4 +59,10 @@ + + + 2.10.1 + 1.5 + + diff --git a/core-java-modules/core-java-reflection-3/pom.xml b/core-java-modules/core-java-reflection-3/pom.xml index fa5fe897e0..e60652f1f2 100644 --- a/core-java-modules/core-java-reflection-3/pom.xml +++ b/core-java-modules/core-java-reflection-3/pom.xml @@ -1,7 +1,7 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 core-java-reflection-3 core-java-reflection-3 diff --git a/core-java-modules/core-java-string-operations-2/pom.xml b/core-java-modules/core-java-string-operations-2/pom.xml index 27071e5427..76f21aa726 100644 --- a/core-java-modules/core-java-string-operations-2/pom.xml +++ b/core-java-modules/core-java-string-operations-2/pom.xml @@ -44,10 +44,10 @@ commons-codec ${commons-codec.version} - - org.springframework - spring-core - ${spring-core.version} + + org.springframework + spring-core + ${spring-core.version} From b5f48cee006ce961d15a9d72fdc06603e5b21c32 Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Wed, 6 Dec 2023 08:41:19 -0800 Subject: [PATCH 203/228] JAVA-28505 Fix references to parent (#15345) --- .../custom-validations-opeanpi-codegen/pom.xml | 3 +-- spring-swagger-codegen/pom.xml | 1 + .../spring-swagger-codegen-api-client/pom.xml | 1 - spring-swagger-codegen/spring-swagger-codegen-app/pom.xml | 1 - 4 files changed, 2 insertions(+), 4 deletions(-) diff --git a/spring-swagger-codegen/custom-validations-opeanpi-codegen/pom.xml b/spring-swagger-codegen/custom-validations-opeanpi-codegen/pom.xml index b1c2bf61f1..136f5b8907 100644 --- a/spring-swagger-codegen/custom-validations-opeanpi-codegen/pom.xml +++ b/spring-swagger-codegen/custom-validations-opeanpi-codegen/pom.xml @@ -11,9 +11,8 @@ com.baeldung - parent-boot-2 + spring-swagger-codegen 0.0.1-SNAPSHOT - ../../parent-boot-2 diff --git a/spring-swagger-codegen/pom.xml b/spring-swagger-codegen/pom.xml index d4fff7eb63..ce28f28c22 100644 --- a/spring-swagger-codegen/pom.xml +++ b/spring-swagger-codegen/pom.xml @@ -16,6 +16,7 @@ + custom-validations-opeanpi-codegen spring-swagger-codegen-api-client spring-openapi-generator-api-client spring-swagger-codegen-app diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/pom.xml b/spring-swagger-codegen/spring-swagger-codegen-api-client/pom.xml index af12f9cef0..5ad15f6851 100644 --- a/spring-swagger-codegen/spring-swagger-codegen-api-client/pom.xml +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/pom.xml @@ -33,7 +33,6 @@ com.baeldung spring-swagger-codegen 0.0.1-SNAPSHOT - ../../spring-swagger-codegen diff --git a/spring-swagger-codegen/spring-swagger-codegen-app/pom.xml b/spring-swagger-codegen/spring-swagger-codegen-app/pom.xml index d3f57474ef..a7969df518 100644 --- a/spring-swagger-codegen/spring-swagger-codegen-app/pom.xml +++ b/spring-swagger-codegen/spring-swagger-codegen-app/pom.xml @@ -10,7 +10,6 @@ com.baeldung spring-swagger-codegen 0.0.1-SNAPSHOT - ../../spring-swagger-codegen From cab75d510a258d26868fa95867f6afdec553769e Mon Sep 17 00:00:00 2001 From: MohamedHelmyKassab <137485958+MohamedHelmyKassab@users.noreply.github.com> Date: Wed, 6 Dec 2023 23:04:02 +0200 Subject: [PATCH 204/228] This commit is related to BAEL-7104 (#15368) This commit aims to add a test class "SkipInputStreamUnitTest" that provide a test method that utilizes the skip() method. --- .../SkipInputStreamUnitTest.java | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 core-java-modules/core-java-streams/src/test/java/com/baeldung/skipinputstream/SkipInputStreamUnitTest.java diff --git a/core-java-modules/core-java-streams/src/test/java/com/baeldung/skipinputstream/SkipInputStreamUnitTest.java b/core-java-modules/core-java-streams/src/test/java/com/baeldung/skipinputstream/SkipInputStreamUnitTest.java new file mode 100644 index 0000000000..a41e5642fe --- /dev/null +++ b/core-java-modules/core-java-streams/src/test/java/com/baeldung/skipinputstream/SkipInputStreamUnitTest.java @@ -0,0 +1,33 @@ +package com.baeldung.skipinputstream; + +import org.junit.Test; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; + +import static org.junit.Assert.assertArrayEquals; + +public class SkipInputStreamUnitTest { + @Test + public void givenInputStreamWithBytes_whenSkipBytes_thenRemainingBytes() throws IOException { + byte[] inputData = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + InputStream inputStream = new ByteArrayInputStream(inputData); + + long bytesToSkip = 3; + long skippedBytes = inputStream.skip(bytesToSkip); + + assertArrayEquals(new byte[]{4, 5, 6, 7, 8, 9, 10}, readRemainingBytes(inputStream)); + + assert skippedBytes == bytesToSkip : "Incorrect number of bytes skipped"; + } + + private byte[] readRemainingBytes(InputStream inputStream) throws IOException { + byte[] buffer = new byte[inputStream.available()]; + int bytesRead = inputStream.read(buffer); + if (bytesRead == -1) { + throw new IOException("End of stream reached"); + } + return buffer; + } +} From 4e3e693f7109722c9db87d0367e69df527eb77bd Mon Sep 17 00:00:00 2001 From: Mo Helmy <135069400+BenHelmyBen@users.noreply.github.com> Date: Wed, 6 Dec 2023 23:08:38 +0200 Subject: [PATCH 205/228] This commit is related to BAEL-6920 (#15371) This commit aims to add a class "StringMaxLengthMain" showing the string max length. --- .../stringmaxlength/StringMaxLengthMain.java | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 core-java-modules/core-java-string-operations-7/src/main/java/com/baeldung/stringmaxlength/StringMaxLengthMain.java diff --git a/core-java-modules/core-java-string-operations-7/src/main/java/com/baeldung/stringmaxlength/StringMaxLengthMain.java b/core-java-modules/core-java-string-operations-7/src/main/java/com/baeldung/stringmaxlength/StringMaxLengthMain.java new file mode 100644 index 0000000000..42d0c05582 --- /dev/null +++ b/core-java-modules/core-java-string-operations-7/src/main/java/com/baeldung/stringmaxlength/StringMaxLengthMain.java @@ -0,0 +1,35 @@ +package com.baeldung.stringmaxlength; + +public class StringMaxLengthMain { + + public static void main(String[] args) { + displayRuntimeMaxStringLength(); + displayMaxStringLength(); + simulateStringOverflow(); + } + + public static void simulateStringOverflow() { + try { + int maxLength = Integer.MAX_VALUE; + char[] charArray = new char[maxLength]; + for (int i = 0; i < maxLength; i++) { + charArray[i] = 'a'; + } + String longString = new String(charArray); + System.out.println("Successfully created a string of length: " + longString.length()); + } catch (OutOfMemoryError e) { + System.err.println("Overflow error: Attempting to create a string longer than Integer.MAX_VALUE"); + e.printStackTrace(); + } + } + + public static void displayRuntimeMaxStringLength() { + long maxMemory = Runtime.getRuntime().maxMemory(); + System.out.println("Maximum String length based on available memory: " + (maxMemory)); + } + + public static void displayMaxStringLength() { + int maxStringLength = Integer.MAX_VALUE; + System.out.println("Maximum String length based on Integer.MAX_VALUE: " + maxStringLength); + } +} \ No newline at end of file From 97aaeed2c0a9dcf4b72664db6957c3ba8005d324 Mon Sep 17 00:00:00 2001 From: Geoffrey De Smet Date: Thu, 7 Dec 2023 08:21:13 +0100 Subject: [PATCH 206/228] Fix Timefold Solver readme + remove unpublished article --- timefold-solver/README.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/timefold-solver/README.md b/timefold-solver/README.md index b7a2dbe14b..1abc4d4ca0 100644 --- a/timefold-solver/README.md +++ b/timefold-solver/README.md @@ -1,7 +1,6 @@ -## OptaPlanner +## Timefold Solver -This module contains articles about OptaPlanner. +This module contains articles about (Timefold Solver)[https://timefold.ai]. ### Relevant articles -- [A Guide to OptaPlanner](https://www.baeldung.com/opta-planner) From 232730dbbbbab342cf98191015e609f36fa8f76f Mon Sep 17 00:00:00 2001 From: timis1 <12120641+timis1@users.noreply.github.com> Date: Thu, 7 Dec 2023 12:27:02 +0200 Subject: [PATCH 207/228] JAVA-27674 Upgrade apache-httpclient to v5 (#15329) --- apache-httpclient/pom.xml | 12 +++--------- .../baeldung/httpclient/HttpAsyncClientLiveTest.java | 4 ++-- 2 files changed, 5 insertions(+), 11 deletions(-) diff --git a/apache-httpclient/pom.xml b/apache-httpclient/pom.xml index 3b178d4df8..f671c93cfc 100644 --- a/apache-httpclient/pom.xml +++ b/apache-httpclient/pom.xml @@ -63,11 +63,6 @@ ${wiremock.version} test - - org.apache.httpcomponents - httpclient - ${httpclient.version} - @@ -84,10 +79,9 @@ 5.6.1 3.3.1 - 5.2 - 5.2 - 5.2 - 4.5.14 + 5.2.2 + 5.2.2 + 5.2.2 diff --git a/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpAsyncClientLiveTest.java b/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpAsyncClientLiveTest.java index 50cf1b7a64..7b818f871a 100644 --- a/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpAsyncClientLiveTest.java +++ b/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpAsyncClientLiveTest.java @@ -25,6 +25,7 @@ import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManagerBu import org.apache.hc.client5.http.impl.routing.DefaultProxyRoutePlanner; import org.apache.hc.client5.http.protocol.HttpClientContext; import org.apache.hc.client5.http.ssl.ClientTlsStrategyBuilder; +import org.apache.hc.client5.http.ssl.NoopHostnameVerifier; import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.http.HttpResponse; import org.apache.hc.core5.http.nio.ssl.TlsStrategy; @@ -33,7 +34,6 @@ import org.apache.hc.core5.http.protocol.HttpContext; import org.apache.hc.core5.reactor.IOReactorConfig; import org.apache.hc.core5.ssl.SSLContexts; import org.apache.hc.core5.ssl.TrustStrategy; -import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.junit.jupiter.api.Test; @@ -120,7 +120,7 @@ class HttpAsyncClientLiveTest extends GetRequestMockServer { .build(); final TlsStrategy tlsStrategy = ClientTlsStrategyBuilder.create() - .setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER) + .setHostnameVerifier(NoopHostnameVerifier.INSTANCE) .setSslContext(sslContext) .build(); From 19184bdf406461c21b3ba48873626f89b8dfc49f Mon Sep 17 00:00:00 2001 From: panos-kakos <102670093+panos-kakos@users.noreply.github.com> Date: Thu, 7 Dec 2023 13:12:55 +0200 Subject: [PATCH 208/228] [JAVA-27761] Upgraded spring-reactive-2 to spring boot 3 (#15293) --- .../spring-reactive-2/pom.xml | 18 ++++-- ...n.java => Spring6ReactiveApplication.java} | 4 +- .../consumer/ConsumerSSEApplication.java | 7 +- .../reactive/urlmatch/FormHandler.java | 2 +- .../com/baeldung/reactive/util/CpuUtils.java | 2 +- .../staticcontent/StaticContentConfig.java | 2 +- .../FunctionalValidationsApplication.java | 9 +-- .../model/AnnotatedRequestEntity.java | 4 +- .../backpressure/BackpressureUnitTest.java | 64 +++++++++---------- ...ernsUsingHandlerMethodIntegrationTest.java | 4 +- 10 files changed, 60 insertions(+), 56 deletions(-) rename spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/{Spring5ReactiveApplication.java => Spring6ReactiveApplication.java} (77%) diff --git a/spring-reactive-modules/spring-reactive-2/pom.xml b/spring-reactive-modules/spring-reactive-2/pom.xml index a5552bfe51..fac93154c8 100644 --- a/spring-reactive-modules/spring-reactive-2/pom.xml +++ b/spring-reactive-modules/spring-reactive-2/pom.xml @@ -10,9 +10,10 @@ spring sample project about new features - com.baeldung.spring.reactive - spring-reactive-modules - 1.0.0-SNAPSHOT + com.baeldung + parent-boot-3 + 0.0.1-SNAPSHOT + ../../parent-boot-3 @@ -45,8 +46,8 @@ test - com.github.tomakehurst - wiremock-jre8 + org.wiremock + wiremock ${wiremock.version} test @@ -64,6 +65,11 @@ org.springframework.boot spring-boot-starter-tomcat + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + @@ -116,7 +122,7 @@ 1.0.1.RELEASE - 2.24.0 + 3.3.1 \ No newline at end of file diff --git a/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/Spring5ReactiveApplication.java b/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/Spring6ReactiveApplication.java similarity index 77% rename from spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/Spring5ReactiveApplication.java rename to spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/Spring6ReactiveApplication.java index ef862dd957..f716af4a0e 100644 --- a/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/Spring5ReactiveApplication.java +++ b/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/Spring6ReactiveApplication.java @@ -5,10 +5,10 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration; @SpringBootApplication(exclude = { RedisAutoConfiguration.class }) -public class Spring5ReactiveApplication{ +public class Spring6ReactiveApplication { public static void main(String[] args) { - SpringApplication.run(Spring5ReactiveApplication.class, args); + SpringApplication.run(Spring6ReactiveApplication.class, args); } } diff --git a/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/serversentevents/consumer/ConsumerSSEApplication.java b/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/serversentevents/consumer/ConsumerSSEApplication.java index d8edaf7fd5..bec7dd2e0c 100644 --- a/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/serversentevents/consumer/ConsumerSSEApplication.java +++ b/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/serversentevents/consumer/ConsumerSSEApplication.java @@ -22,9 +22,10 @@ public class ConsumerSSEApplication { @Bean public SecurityWebFilterChain sseConsumerSpringSecurityFilterChain(ServerHttpSecurity http) { - http.authorizeExchange() - .anyExchange() - .permitAll(); + http.authorizeExchange(auth -> auth + .anyExchange().permitAll() + ) + .csrf(ServerHttpSecurity.CsrfSpec::disable); return http.build(); } diff --git a/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/urlmatch/FormHandler.java b/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/urlmatch/FormHandler.java index 7b1fb06459..1652e2f25d 100644 --- a/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/urlmatch/FormHandler.java +++ b/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/urlmatch/FormHandler.java @@ -34,7 +34,7 @@ public class FormHandler { private AtomicLong extractData(List dataBuffers) { AtomicLong atomicLong = new AtomicLong(0); - dataBuffers.forEach(d -> atomicLong.addAndGet(d.asByteBuffer() + dataBuffers.forEach(d -> atomicLong.addAndGet(d.toByteBuffer() .array().length)); return atomicLong; } diff --git a/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/util/CpuUtils.java b/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/util/CpuUtils.java index 8d16434920..20cc162cde 100644 --- a/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/util/CpuUtils.java +++ b/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/reactive/util/CpuUtils.java @@ -9,7 +9,7 @@ public class CpuUtils { private static OperatingSystemMXBean operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean(); static Double getUsage() { - return (operatingSystemMXBean.getSystemCpuLoad() / operatingSystemMXBean.getAvailableProcessors()) * 100; + return (operatingSystemMXBean.getCpuLoad() / operatingSystemMXBean.getAvailableProcessors()) * 100; } } diff --git a/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/staticcontent/StaticContentConfig.java b/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/staticcontent/StaticContentConfig.java index 1fbb9958e7..456eec8f84 100644 --- a/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/staticcontent/StaticContentConfig.java +++ b/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/staticcontent/StaticContentConfig.java @@ -23,7 +23,7 @@ public class StaticContentConfig { GET("/"), request -> ok() .contentType(MediaType.TEXT_HTML) - .syncBody(html) + .bodyValue(html) ); } diff --git a/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/validations/functional/FunctionalValidationsApplication.java b/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/validations/functional/FunctionalValidationsApplication.java index 4cbb65dc60..bcbd4d55d7 100644 --- a/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/validations/functional/FunctionalValidationsApplication.java +++ b/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/validations/functional/FunctionalValidationsApplication.java @@ -15,10 +15,11 @@ public class FunctionalValidationsApplication { @Bean public SecurityWebFilterChain functionalValidationsSpringSecurityFilterChain(ServerHttpSecurity http) { - http.authorizeExchange() - .anyExchange() - .permitAll(); - http.csrf().disable(); + http.authorizeExchange(auth -> auth + .anyExchange().permitAll() + ) + .csrf(ServerHttpSecurity.CsrfSpec::disable); + return http.build(); } } diff --git a/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/validations/functional/model/AnnotatedRequestEntity.java b/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/validations/functional/model/AnnotatedRequestEntity.java index 992f07481c..6ca6c369c1 100644 --- a/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/validations/functional/model/AnnotatedRequestEntity.java +++ b/spring-reactive-modules/spring-reactive-2/src/main/java/com/baeldung/validations/functional/model/AnnotatedRequestEntity.java @@ -1,7 +1,7 @@ package com.baeldung.validations.functional.model; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Size; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; import lombok.AllArgsConstructor; import lombok.Getter; diff --git a/spring-reactive-modules/spring-reactive-2/src/test/java/com/baeldung/backpressure/BackpressureUnitTest.java b/spring-reactive-modules/spring-reactive-2/src/test/java/com/baeldung/backpressure/BackpressureUnitTest.java index a12d762fe5..c087e10b3f 100644 --- a/spring-reactive-modules/spring-reactive-2/src/test/java/com/baeldung/backpressure/BackpressureUnitTest.java +++ b/spring-reactive-modules/spring-reactive-2/src/test/java/com/baeldung/backpressure/BackpressureUnitTest.java @@ -24,49 +24,45 @@ public class BackpressureUnitTest { ); StepVerifier.create(limit) - .expectSubscription() - .thenRequest(15) - .expectNext(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) - .expectNext(11, 12, 13, 14, 15) - .thenRequest(10) - .expectNext(16, 17, 18, 19, 20, 21, 22, 23, 24, 25) - .verifyComplete(); + .expectSubscription() + .thenRequest(15) + .expectNext(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) + .expectNext(11, 12, 13, 14, 15) + .thenRequest(10) + .expectNext(16, 17, 18, 19, 20, 21, 22, 23, 24, 25) + .verifyComplete(); } @Test public void whenRequestingChunks10_thenMessagesAreReceived() { Flux request = Flux.range(1, 50); - request.subscribe( - integer -> LOGGER.debug(String.valueOf(integer)), - err -> err.printStackTrace(), - () -> LOGGER.debug("All 50 items have been successfully processed!!!"), - subscription -> { - for (int i = 0; i < 5; i++) { - LOGGER.debug("Requesting the next 10 elements!!!"); - subscription.request(10); - } - } - ); + request.subscribe(integer -> LOGGER.debug(String.valueOf(integer)), err -> err.printStackTrace(), () -> LOGGER.debug("All 50 items have been successfully processed!!!"), subscription -> { + for (int i = 0; i < 5; i++) { + LOGGER.debug("Requesting the next 10 elements!!!"); + subscription.request(10); + } + }); StepVerifier.create(request) - .expectSubscription() - .thenRequest(10) - .expectNext(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) - .thenRequest(10) - .expectNext(11, 12, 13, 14, 15, 16, 17, 18, 19, 20) - .thenRequest(10) - .expectNext(21, 22, 23, 24, 25, 26, 27 , 28, 29 ,30) - .thenRequest(10) - .expectNext(31, 32, 33, 34, 35, 36, 37 , 38, 39 ,40) - .thenRequest(10) - .expectNext(41, 42, 43, 44, 45, 46, 47 , 48, 49 ,50) - .verifyComplete(); + .expectSubscription() + .thenRequest(10) + .expectNext(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) + .thenRequest(10) + .expectNext(11, 12, 13, 14, 15, 16, 17, 18, 19, 20) + .thenRequest(10) + .expectNext(21, 22, 23, 24, 25, 26, 27, 28, 29, 30) + .thenRequest(10) + .expectNext(31, 32, 33, 34, 35, 36, 37, 38, 39, 40) + .thenRequest(10) + .expectNext(41, 42, 43, 44, 45, 46, 47, 48, 49, 50) + .verifyComplete(); } @Test public void whenCancel_thenSubscriptionFinished() { - Flux cancel = Flux.range(1, 10).log(); + Flux cancel = Flux.range(1, 10) + .log(); cancel.subscribe(new BaseSubscriber() { @Override @@ -78,9 +74,9 @@ public class BackpressureUnitTest { }); StepVerifier.create(cancel) - .expectNext(1, 2, 3) - .thenCancel() - .verify(); + .expectNext(1, 2, 3) + .thenCancel() + .verify(); } } diff --git a/spring-reactive-modules/spring-reactive-2/src/test/java/com/baeldung/reactive/urlmatch/PathPatternsUsingHandlerMethodIntegrationTest.java b/spring-reactive-modules/spring-reactive-2/src/test/java/com/baeldung/reactive/urlmatch/PathPatternsUsingHandlerMethodIntegrationTest.java index 0b4607b54a..4069888dcd 100644 --- a/spring-reactive-modules/spring-reactive-2/src/test/java/com/baeldung/reactive/urlmatch/PathPatternsUsingHandlerMethodIntegrationTest.java +++ b/spring-reactive-modules/spring-reactive-2/src/test/java/com/baeldung/reactive/urlmatch/PathPatternsUsingHandlerMethodIntegrationTest.java @@ -8,11 +8,11 @@ import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; -import com.baeldung.reactive.Spring5ReactiveApplication; +import com.baeldung.reactive.Spring6ReactiveApplication; import com.baeldung.reactive.controller.PathPatternController; @RunWith(SpringRunner.class) -@SpringBootTest(classes = Spring5ReactiveApplication.class) +@SpringBootTest(classes = Spring6ReactiveApplication.class) @WithMockUser public class PathPatternsUsingHandlerMethodIntegrationTest { From 183101cd4fb51a0a241bb8202169a35324709bb3 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Thu, 7 Dec 2023 21:51:10 +0800 Subject: [PATCH 209/228] Update README.md [skip ci] --- core-java-modules/core-java-numbers-conversions/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-numbers-conversions/README.md b/core-java-modules/core-java-numbers-conversions/README.md index dead88f025..cb272b0029 100644 --- a/core-java-modules/core-java-numbers-conversions/README.md +++ b/core-java-modules/core-java-numbers-conversions/README.md @@ -4,3 +4,4 @@ - [Convert int to Long in Java](https://www.baeldung.com/java-convert-int-long) - [How To Convert Double To Float In Java](https://www.baeldung.com/java-convert-double-float) - [Converting from float to BigDecimal in Java](https://www.baeldung.com/java-convert-float-bigdecimal) +- [Convert Positive Integer to Negative and Vice Versa in Java](https://www.baeldung.com/java-negating-integer) From d8be8b3bb1c2fbc7bd5b32eb53bf390e6e43a55c Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Thu, 7 Dec 2023 21:54:34 +0800 Subject: [PATCH 210/228] Update README.md [skip ci] --- core-java-modules/core-java-arrays-convert/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-arrays-convert/README.md b/core-java-modules/core-java-arrays-convert/README.md index 2e34829525..118d8e00ed 100644 --- a/core-java-modules/core-java-arrays-convert/README.md +++ b/core-java-modules/core-java-arrays-convert/README.md @@ -11,3 +11,4 @@ This module contains articles about arrays conversion in Java - [Converting an int[] to HashSet in Java](https://www.baeldung.com/java-converting-int-array-to-hashset) - [Convert an ArrayList of String to a String Array in Java](https://www.baeldung.com/java-convert-string-arraylist-array) - [Convert Char Array to Int Array in Java](https://www.baeldung.com/java-convert-char-int-array) +- [How to Convert Byte Array to Char Array](https://www.baeldung.com/java-convert-byte-array-char) From 300b524fdecdcef76aeab7d66a2f94cbb7ed5565 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Thu, 7 Dec 2023 21:58:50 +0800 Subject: [PATCH 211/228] Create README.md [skip ci] --- core-java-modules/core-java-numbers-7/README.md | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 core-java-modules/core-java-numbers-7/README.md diff --git a/core-java-modules/core-java-numbers-7/README.md b/core-java-modules/core-java-numbers-7/README.md new file mode 100644 index 0000000000..42a43fd1fd --- /dev/null +++ b/core-java-modules/core-java-numbers-7/README.md @@ -0,0 +1,2 @@ +## Relevant Articles +- [Check if a double Is an Integer in Java](https://www.baeldung.com/java-check-double-integer) From 983c7190b954358d160e01c8024314a176bd5db8 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Thu, 7 Dec 2023 22:03:42 +0800 Subject: [PATCH 212/228] Update README.md [skip ci] --- json-modules/gson-2/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/json-modules/gson-2/README.md b/json-modules/gson-2/README.md index 3deb61f25d..912f8b0a20 100644 --- a/json-modules/gson-2/README.md +++ b/json-modules/gson-2/README.md @@ -5,4 +5,4 @@ This module contains articles about Gson ### Relevant Articles: - [Solving Gson Parsing Errors](https://www.baeldung.com/gson-parsing-errors) - [Difference between Gson @Expose and @SerializedName](https://www.baeldung.com/gson-expose-vs-serializedname) - +- [Resolving Gson’s “Multiple JSON Fields” Exception](https://www.baeldung.com/java-gson-multiple-json-fields-exception) From 9c8c7ff561f2f0a19b1f06687e7c30c5357ea392 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Thu, 7 Dec 2023 22:09:39 +0800 Subject: [PATCH 213/228] Update README.md [skip ci] --- static-analysis/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/static-analysis/README.md b/static-analysis/README.md index 235b79853b..ea0d797407 100644 --- a/static-analysis/README.md +++ b/static-analysis/README.md @@ -6,3 +6,4 @@ This module contains articles about static program analysis - [Introduction to PMD](https://www.baeldung.com/pmd) - [Java Static Analysis Tools in Eclipse and IntelliJ IDEA](https://www.baeldung.com/java-static-analysis-tools) +- [Catch Common Mistakes with Error Prone Library in Java](https://www.baeldung.com/java-error-prone-library) From fa10ea0e21110d80696bbff5333d29cc13e9333d Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Thu, 7 Dec 2023 22:12:10 +0800 Subject: [PATCH 214/228] Update README.md [skip ci] --- xml/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/xml/README.md b/xml/README.md index 16942c6836..596ddc14aa 100644 --- a/xml/README.md +++ b/xml/README.md @@ -13,3 +13,4 @@ This module contains articles about eXtensible Markup Language (XML) - [Parsing an XML File Using StAX](https://www.baeldung.com/java-stax) - [Parsing an XML File Using SAX Parser](https://www.baeldung.com/java-sax-parser) - [Remove HTML Tags Using Java](https://www.baeldung.com/java-remove-html-tags) +- [Convert an XML File to CSV File](https://www.baeldung.com/java-convert-xml-csv) From 6b41d74e5fa5e3cfd299dafb15b0e87f13a0a2ba Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Thu, 7 Dec 2023 22:15:31 +0800 Subject: [PATCH 215/228] Create README.md [skip ci] --- persistence-modules/java-harperdb/README.md | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 persistence-modules/java-harperdb/README.md diff --git a/persistence-modules/java-harperdb/README.md b/persistence-modules/java-harperdb/README.md new file mode 100644 index 0000000000..99a91e00ed --- /dev/null +++ b/persistence-modules/java-harperdb/README.md @@ -0,0 +1,2 @@ +## Relevant Articles +- [Working With HarperDB and Java](https://www.baeldung.com/java-harperdb) From 5600e16d489cdf80650c648ca562b174cdf10b4b Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Thu, 7 Dec 2023 22:20:24 +0800 Subject: [PATCH 216/228] Update README.md [skip ci] --- json-modules/json/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/json-modules/json/README.md b/json-modules/json/README.md index d643914fc7..d6e1b400f5 100644 --- a/json-modules/json/README.md +++ b/json-modules/json/README.md @@ -12,4 +12,5 @@ This module contains articles about JSON. - [Iterating Over an Instance of org.json.JSONObject](https://www.baeldung.com/jsonobject-iteration) - [Escape JSON String in Java](https://www.baeldung.com/java-json-escaping) - [Reducing JSON Data Size](https://www.baeldung.com/json-reduce-data-size) +- [How to Convert JsonNode to ObjectNode](https://www.baeldung.com/java-jackson-jsonnode-objectnode) - More Articles: [[next -->]](../json-2) From 3adfcb215cd6568caf86d4e007dd704dafad07f5 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Thu, 7 Dec 2023 22:22:56 +0800 Subject: [PATCH 217/228] Update README.md [skip ci] --- core-java-modules/core-java-lang-operators-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-lang-operators-2/README.md b/core-java-modules/core-java-lang-operators-2/README.md index e8b792e634..4b93f8d192 100644 --- a/core-java-modules/core-java-lang-operators-2/README.md +++ b/core-java-modules/core-java-lang-operators-2/README.md @@ -10,3 +10,4 @@ This module contains articles about Java operators - [Check if at Least Two Out of Three Booleans Are True in Java](https://www.baeldung.com/java-check-two-of-three-booleans) - [Alternatives for instanceof Operator in Java](https://www.baeldung.com/java-instanceof-alternatives) - [What Does “––>” Mean in Java?](https://www.baeldung.com/java-minus-minus-greaterthan) +- [All the Ways Java Uses the Colon Character](https://www.baeldung.com/java-colon) From d63b2b5a2ad4b21de2ac2d407cb128526a28642a Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Thu, 7 Dec 2023 22:24:56 +0800 Subject: [PATCH 218/228] Update README.md [skip ci] --- core-java-modules/core-java-numbers-conversions/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-numbers-conversions/README.md b/core-java-modules/core-java-numbers-conversions/README.md index cb272b0029..b5f02a9d47 100644 --- a/core-java-modules/core-java-numbers-conversions/README.md +++ b/core-java-modules/core-java-numbers-conversions/README.md @@ -5,3 +5,4 @@ - [How To Convert Double To Float In Java](https://www.baeldung.com/java-convert-double-float) - [Converting from float to BigDecimal in Java](https://www.baeldung.com/java-convert-float-bigdecimal) - [Convert Positive Integer to Negative and Vice Versa in Java](https://www.baeldung.com/java-negating-integer) +- [Rounding Up a Number to Nearest Multiple of 5 in Java](https://www.baeldung.com/java-round-nearest-multiple-five) From bf1aaf197f9733cfa0e5ccd0c0ada50a8d8b52b4 Mon Sep 17 00:00:00 2001 From: panos-kakos <102670093+panos-kakos@users.noreply.github.com> Date: Fri, 8 Dec 2023 09:51:11 +0200 Subject: [PATCH 219/228] [JAVA-28504] Clean up --- spring-websockets/pom.xml | 6 +++++- static-analysis/error-prone-project/pom.xml | 11 ++++------- static-analysis/my-bugchecker-plugin/pom.xml | 11 +++-------- static-analysis/pmd/pom.xml | 10 ++-------- tablesaw/pom.xml | 5 ----- testing-modules/cucumber/pom.xml | 2 -- testing-modules/gatling-java/pom.xml | 3 --- testing-modules/gatling/pom.xml | 3 --- testing-modules/jqwik/pom.xml | 6 +++++- testing-modules/junit-5-advanced/pom.xml | 3 ++- testing-modules/junit-5-basics-2/pom.xml | 7 ------- testing-modules/junit-5/pom.xml | 1 - testing-modules/load-testing-comparison/pom.xml | 3 --- testing-modules/mockito-2/pom.xml | 3 --- vavr-modules/java-vavr-stream/pom.xml | 6 +----- vavr-modules/pom.xml | 4 ++++ vavr-modules/vavr-2/pom.xml | 4 ---- vertx-modules/pom.xml | 4 ++++ vertx-modules/vertx-and-rxjava/pom.xml | 4 ---- vertx-modules/vertx/pom.xml | 1 - web-modules/apache-tapestry/pom.xml | 8 -------- web-modules/blade/pom.xml | 1 - web-modules/jakarta-ee/pom.xml | 9 ++------- 23 files changed, 32 insertions(+), 83 deletions(-) diff --git a/spring-websockets/pom.xml b/spring-websockets/pom.xml index a28ef8749a..6ca84c4946 100644 --- a/spring-websockets/pom.xml +++ b/spring-websockets/pom.xml @@ -26,7 +26,7 @@ com.github.javafaker javafaker - 1.0.2 + ${javafaker.version} com.google.code.gson @@ -44,4 +44,8 @@ + + 1.0.2 + + \ No newline at end of file diff --git a/static-analysis/error-prone-project/pom.xml b/static-analysis/error-prone-project/pom.xml index 59f7bb7270..2d5706d0d2 100644 --- a/static-analysis/error-prone-project/pom.xml +++ b/static-analysis/error-prone-project/pom.xml @@ -3,14 +3,14 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 + error-prone-project + com.baeldung static-analysis 1.0-SNAPSHOT - error-prone-project - @@ -19,7 +19,6 @@ ${maven-compiler-plugin.version} 17 - UTF-8 true -XDcompilePolicy=simple @@ -44,7 +43,7 @@ com.baeldung my-bugchecker-plugin - 1.0-SNAPSHOT + ${my-bugchecker-plugin.version} @@ -53,9 +52,7 @@ - 17 - 17 - UTF-8 + 1.0-SNAPSHOT diff --git a/static-analysis/my-bugchecker-plugin/pom.xml b/static-analysis/my-bugchecker-plugin/pom.xml index cbe16b0a14..eb11f07b4e 100644 --- a/static-analysis/my-bugchecker-plugin/pom.xml +++ b/static-analysis/my-bugchecker-plugin/pom.xml @@ -3,13 +3,14 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 + my-bugchecker-plugin + jar + com.baeldung static-analysis 1.0-SNAPSHOT - jar - my-bugchecker-plugin @@ -47,10 +48,4 @@ - - 17 - 17 - UTF-8 - - diff --git a/static-analysis/pmd/pom.xml b/static-analysis/pmd/pom.xml index 31914fe9f0..372c122776 100644 --- a/static-analysis/pmd/pom.xml +++ b/static-analysis/pmd/pom.xml @@ -3,18 +3,12 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 + pmd + com.baeldung static-analysis 1.0-SNAPSHOT - pmd - - - 17 - 17 - UTF-8 - - diff --git a/tablesaw/pom.xml b/tablesaw/pom.xml index f38e4cb8b4..c45931a9e2 100644 --- a/tablesaw/pom.xml +++ b/tablesaw/pom.xml @@ -25,11 +25,6 @@ org.apache.maven.plugins maven-compiler-plugin - 3.8.0 - - 17 - 17 - diff --git a/testing-modules/cucumber/pom.xml b/testing-modules/cucumber/pom.xml index c1d99bb492..088a75a941 100644 --- a/testing-modules/cucumber/pom.xml +++ b/testing-modules/cucumber/pom.xml @@ -121,8 +121,6 @@ - 14 - 14 6.10.3 5.4.0 3.141.59 diff --git a/testing-modules/gatling-java/pom.xml b/testing-modules/gatling-java/pom.xml index abe033f298..54dee1fd88 100644 --- a/testing-modules/gatling-java/pom.xml +++ b/testing-modules/gatling-java/pom.xml @@ -72,9 +72,6 @@ - 1.8 - 1.8 - UTF-8 3.9.5 4.3.0 1.0.2 diff --git a/testing-modules/gatling/pom.xml b/testing-modules/gatling/pom.xml index 82ce988bac..e5b1db2bfb 100644 --- a/testing-modules/gatling/pom.xml +++ b/testing-modules/gatling/pom.xml @@ -105,9 +105,6 @@ - 1.8 - 1.8 - UTF-8 2.12.6 3.3.1 4.3.0 diff --git a/testing-modules/jqwik/pom.xml b/testing-modules/jqwik/pom.xml index 6ef9b61a6a..85c4ba571a 100644 --- a/testing-modules/jqwik/pom.xml +++ b/testing-modules/jqwik/pom.xml @@ -17,7 +17,7 @@ net.jqwik jqwik - 1.7.4 + ${jqwik.version} test @@ -53,5 +53,9 @@ + + 1.7.4 + + diff --git a/testing-modules/junit-5-advanced/pom.xml b/testing-modules/junit-5-advanced/pom.xml index 411f189638..fc0349ff8e 100644 --- a/testing-modules/junit-5-advanced/pom.xml +++ b/testing-modules/junit-5-advanced/pom.xml @@ -18,7 +18,7 @@ com.github.stefanbirkner system-lambda - 1.2.1 + ${system-lambda.version} test @@ -79,6 +79,7 @@ + 1.2.1 1.49 3.24.2 1.10.1 diff --git a/testing-modules/junit-5-basics-2/pom.xml b/testing-modules/junit-5-basics-2/pom.xml index b430161380..f03b74f47a 100644 --- a/testing-modules/junit-5-basics-2/pom.xml +++ b/testing-modules/junit-5-basics-2/pom.xml @@ -36,18 +36,11 @@ org.apache.maven.plugins maven-compiler-plugin - - 11 - 11 - - 11 - 11 - UTF-8 1.5.0 5.10.0 5.5.0 diff --git a/testing-modules/junit-5/pom.xml b/testing-modules/junit-5/pom.xml index 8afaa085b1..cdddf90855 100644 --- a/testing-modules/junit-5/pom.xml +++ b/testing-modules/junit-5/pom.xml @@ -107,7 +107,6 @@ org.codehaus.mojo exec-maven-plugin - ${exec-maven-plugin.version} diff --git a/testing-modules/load-testing-comparison/pom.xml b/testing-modules/load-testing-comparison/pom.xml index d5a389d311..af42523ca9 100644 --- a/testing-modules/load-testing-comparison/pom.xml +++ b/testing-modules/load-testing-comparison/pom.xml @@ -66,9 +66,6 @@ - 1.8 - 1.8 - UTF-8 2.12.12 3.4.0 4.4.0 diff --git a/testing-modules/mockito-2/pom.xml b/testing-modules/mockito-2/pom.xml index 0e0f19b6b3..100c9d7015 100644 --- a/testing-modules/mockito-2/pom.xml +++ b/testing-modules/mockito-2/pom.xml @@ -21,9 +21,6 @@ - 8 - 8 - UTF-8 4.8.1 diff --git a/vavr-modules/java-vavr-stream/pom.xml b/vavr-modules/java-vavr-stream/pom.xml index cda9d1f734..e369fa7cf3 100644 --- a/vavr-modules/java-vavr-stream/pom.xml +++ b/vavr-modules/java-vavr-stream/pom.xml @@ -19,12 +19,8 @@ io.vavr vavr - ${io.vavr.version} + ${vavr.version} - - 0.9.2 - - \ No newline at end of file diff --git a/vavr-modules/pom.xml b/vavr-modules/pom.xml index 416c689511..e9a3b121aa 100644 --- a/vavr-modules/pom.xml +++ b/vavr-modules/pom.xml @@ -30,4 +30,8 @@ + + 0.9.2 + + \ No newline at end of file diff --git a/vavr-modules/vavr-2/pom.xml b/vavr-modules/vavr-2/pom.xml index 0063daa518..54f3cb4d71 100644 --- a/vavr-modules/vavr-2/pom.xml +++ b/vavr-modules/vavr-2/pom.xml @@ -21,8 +21,4 @@ - - 0.9.1 - - \ No newline at end of file diff --git a/vertx-modules/pom.xml b/vertx-modules/pom.xml index 7d9614ad61..00f0bc46f5 100644 --- a/vertx-modules/pom.xml +++ b/vertx-modules/pom.xml @@ -30,4 +30,8 @@ + + 3.9.15 + + \ No newline at end of file diff --git a/vertx-modules/vertx-and-rxjava/pom.xml b/vertx-modules/vertx-and-rxjava/pom.xml index 16eaf8ebaa..b68117ddeb 100644 --- a/vertx-modules/vertx-and-rxjava/pom.xml +++ b/vertx-modules/vertx-and-rxjava/pom.xml @@ -40,8 +40,4 @@ - - 3.9.15 - - \ No newline at end of file diff --git a/vertx-modules/vertx/pom.xml b/vertx-modules/vertx/pom.xml index 75df2fae69..d34deca9d8 100644 --- a/vertx-modules/vertx/pom.xml +++ b/vertx-modules/vertx/pom.xml @@ -65,7 +65,6 @@ - 3.9.15 3.2.1 diff --git a/web-modules/apache-tapestry/pom.xml b/web-modules/apache-tapestry/pom.xml index 562cdff00c..bfc7c22415 100644 --- a/web-modules/apache-tapestry/pom.xml +++ b/web-modules/apache-tapestry/pom.xml @@ -78,17 +78,13 @@ org.apache.maven.plugins maven-compiler-plugin - ${compiler.plugin.version} - ${source.version} - ${target.version} true org.apache.maven.plugins maven-surefire-plugin - ${compiler.surefire.version} Qa @@ -118,7 +114,6 @@ org.apache.maven.plugins maven-war-plugin - 3.3.1 @@ -140,9 +135,6 @@ 6.1.16 3.0.0-M5 - 3.8.1 - 11 - 11 5.8.2 2.5 6.8.21 diff --git a/web-modules/blade/pom.xml b/web-modules/blade/pom.xml index 2748c05663..fb0ca13dbe 100644 --- a/web-modules/blade/pom.xml +++ b/web-modules/blade/pom.xml @@ -62,7 +62,6 @@ org.apache.maven.plugins maven-failsafe-plugin - ${maven-failsafe-plugin.version} true diff --git a/web-modules/jakarta-ee/pom.xml b/web-modules/jakarta-ee/pom.xml index 066bc14766..d90e848323 100644 --- a/web-modules/jakarta-ee/pom.xml +++ b/web-modules/jakarta-ee/pom.xml @@ -2,7 +2,6 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung jakarta-ee 1.0-SNAPSHOT jakarta-ee @@ -51,7 +50,7 @@ org.glassfish.maven.plugin maven-glassfish-plugin - 2.1 + ${maven-glassfish-plugin.version} ${local.glassfish.home} admin @@ -76,11 +75,6 @@ org.apache.maven.plugins maven-compiler-plugin - 3.8.0 - - 11 - 11 - org.apache.maven.plugins @@ -104,6 +98,7 @@ ${local.glassfish.home}\\domains\\${local.glassfish.domain}\\config\\domain-passwords + 2.1 \ No newline at end of file From 6f9a2c2dfede5a9ca8746f04af2439a9da6ee464 Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Fri, 8 Dec 2023 00:05:04 -0800 Subject: [PATCH 220/228] JAVA-26279 Improve aws-modules build time (#15370) --- aws-modules/aws-dynamodb/pom.xml | 16 ---------------- aws-modules/aws-miscellaneous/pom.xml | 16 ---------------- aws-modules/aws-s3/pom.xml | 21 --------------------- 3 files changed, 53 deletions(-) diff --git a/aws-modules/aws-dynamodb/pom.xml b/aws-modules/aws-dynamodb/pom.xml index 155d48c240..199b9a187e 100644 --- a/aws-modules/aws-dynamodb/pom.xml +++ b/aws-modules/aws-dynamodb/pom.xml @@ -40,22 +40,6 @@ - - org.apache.maven.plugins - maven-shade-plugin - ${maven-shade-plugin.version} - - false - - - - package - - shade - - - - org.apache.maven.plugins maven-dependency-plugin diff --git a/aws-modules/aws-miscellaneous/pom.xml b/aws-modules/aws-miscellaneous/pom.xml index b6326b6eb1..f04e84e14f 100644 --- a/aws-modules/aws-miscellaneous/pom.xml +++ b/aws-modules/aws-miscellaneous/pom.xml @@ -34,22 +34,6 @@ - - org.apache.maven.plugins - maven-shade-plugin - ${maven-shade-plugin.version} - - false - - - - package - - shade - - - - org.apache.maven.plugins maven-dependency-plugin diff --git a/aws-modules/aws-s3/pom.xml b/aws-modules/aws-s3/pom.xml index e2bc04964a..9ba436b43f 100644 --- a/aws-modules/aws-s3/pom.xml +++ b/aws-modules/aws-s3/pom.xml @@ -39,27 +39,6 @@ - - - - org.apache.maven.plugins - maven-shade-plugin - ${maven-shade-plugin.version} - - false - - - - package - - shade - - - - - - - 2.20.52 1.10.L001 From 18643bc0a02f50b57fcf6fcfeb53ff61e3484fd1 Mon Sep 17 00:00:00 2001 From: Bipin kumar Date: Fri, 8 Dec 2023 16:17:08 +0530 Subject: [PATCH 221/228] JAVA-26717:Changes made for Upgrade snakeyaml to latest version (#15284) --- libraries-data-io/pom.xml | 2 +- .../YAMLToJavaDeserialisationUnitTest.java | 28 ++++++++++++------- 2 files changed, 19 insertions(+), 11 deletions(-) diff --git a/libraries-data-io/pom.xml b/libraries-data-io/pom.xml index c8d895b4e5..9fc2814312 100644 --- a/libraries-data-io/pom.xml +++ b/libraries-data-io/pom.xml @@ -98,7 +98,7 @@ - 1.21 + 2.2 4.0.1 1.7.0 5.8 diff --git a/libraries-data-io/src/test/java/com/baeldung/libraries/snakeyaml/YAMLToJavaDeserialisationUnitTest.java b/libraries-data-io/src/test/java/com/baeldung/libraries/snakeyaml/YAMLToJavaDeserialisationUnitTest.java index 6f32f143a9..4c92bf41e1 100644 --- a/libraries-data-io/src/test/java/com/baeldung/libraries/snakeyaml/YAMLToJavaDeserialisationUnitTest.java +++ b/libraries-data-io/src/test/java/com/baeldung/libraries/snakeyaml/YAMLToJavaDeserialisationUnitTest.java @@ -1,15 +1,19 @@ package com.baeldung.libraries.snakeyaml; -import org.junit.Test; -import org.yaml.snakeyaml.TypeDescription; -import org.yaml.snakeyaml.Yaml; -import org.yaml.snakeyaml.constructor.Constructor; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; import java.io.InputStream; import java.util.Date; import java.util.Map; -import static org.junit.Assert.*; +import org.junit.Test; +import org.yaml.snakeyaml.LoaderOptions; +import org.yaml.snakeyaml.TypeDescription; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.Constructor; +import org.yaml.snakeyaml.inspector.TagInspector; public class YAMLToJavaDeserialisationUnitTest { @@ -27,7 +31,7 @@ public class YAMLToJavaDeserialisationUnitTest { @Test public void whenLoadYAMLDocumentWithTopLevelClass_thenLoadCorrectJavaObject() { - Yaml yaml = new Yaml(new Constructor(Customer.class)); + Yaml yaml = new Yaml(new Constructor(Customer.class,new LoaderOptions())); InputStream inputStream = this.getClass() .getClassLoader() .getResourceAsStream("yaml/customer.yaml"); @@ -39,7 +43,11 @@ public class YAMLToJavaDeserialisationUnitTest { @Test public void whenLoadYAMLDocumentWithAssumedClass_thenLoadCorrectJavaObject() { - Yaml yaml = new Yaml(); + LoaderOptions loaderoptions = new LoaderOptions(); + TagInspector taginspector = tag -> tag.getClassName() + .equals(Customer.class.getName()); + loaderoptions.setTagInspector(taginspector); + Yaml yaml = new Yaml(new Constructor(Customer.class, loaderoptions)); InputStream inputStream = this.getClass() .getClassLoader() .getResourceAsStream("yaml/customer_with_type.yaml"); @@ -61,7 +69,7 @@ public class YAMLToJavaDeserialisationUnitTest { @Test public void whenLoadYAMLDocumentWithTopLevelClass_thenLoadCorrectJavaObjectWithNestedObjects() { - Yaml yaml = new Yaml(new Constructor(Customer.class)); + Yaml yaml = new Yaml(new Constructor(Customer.class, new LoaderOptions())); InputStream inputStream = this.getClass() .getClassLoader() .getResourceAsStream("yaml/customer_with_contact_details_and_address.yaml"); @@ -91,7 +99,7 @@ public class YAMLToJavaDeserialisationUnitTest { @Test public void whenLoadYAMLDocumentWithTypeDescription_thenLoadCorrectJavaObjectWithCorrectGenericType() { - Constructor constructor = new Constructor(Customer.class); + Constructor constructor = new Constructor(Customer.class, new LoaderOptions()); TypeDescription customTypeDescription = new TypeDescription(Customer.class); customTypeDescription.addPropertyParameters("contactDetails", Contact.class); constructor.addTypeDescription(customTypeDescription); @@ -116,7 +124,7 @@ public class YAMLToJavaDeserialisationUnitTest { @Test public void whenLoadMultipleYAMLDocuments_thenLoadCorrectJavaObjects() { - Yaml yaml = new Yaml(new Constructor(Customer.class)); + Yaml yaml = new Yaml(new Constructor(Customer.class, new LoaderOptions())); InputStream inputStream = this.getClass() .getClassLoader() .getResourceAsStream("yaml/customers.yaml"); From e0b7b8c02011f478b5ec2131b82c7968d7c25cb9 Mon Sep 17 00:00:00 2001 From: Gaetano Piazzolla Date: Fri, 8 Dec 2023 13:45:59 +0100 Subject: [PATCH 222/228] JAVA-26710 | Updating HikariCP library to the latest version - 5.1.0 (#15362) --- jhipster-modules/jhipster-microservice/car-app/pom.xml | 2 +- jhipster-modules/jhipster-microservice/dealer-app/pom.xml | 2 +- jhipster-modules/jhipster-microservice/gateway-app/pom.xml | 2 +- jhipster-modules/jhipster-monolithic/pom.xml | 2 +- libraries-data-db/pom.xml | 2 +- persistence-modules/core-java-persistence/pom.xml | 2 +- spring-4/pom.xml | 2 +- spring-5/pom.xml | 2 +- 8 files changed, 8 insertions(+), 8 deletions(-) diff --git a/jhipster-modules/jhipster-microservice/car-app/pom.xml b/jhipster-modules/jhipster-microservice/car-app/pom.xml index f345688939..87c289cb46 100644 --- a/jhipster-modules/jhipster-microservice/car-app/pom.xml +++ b/jhipster-modules/jhipster-microservice/car-app/pom.xml @@ -23,7 +23,7 @@ 0.4.13 1.2 5.2.8.Final - 2.6.0 + 5.1.0 0.7.9 1.8 3.21.0-GA diff --git a/jhipster-modules/jhipster-microservice/dealer-app/pom.xml b/jhipster-modules/jhipster-microservice/dealer-app/pom.xml index 056bd60f33..f660463026 100644 --- a/jhipster-modules/jhipster-microservice/dealer-app/pom.xml +++ b/jhipster-modules/jhipster-microservice/dealer-app/pom.xml @@ -23,7 +23,7 @@ 0.4.13 1.2 5.2.8.Final - 2.6.0 + 5.1.0 0.7.9 3.21.0-GA 1.0.0 diff --git a/jhipster-modules/jhipster-microservice/gateway-app/pom.xml b/jhipster-modules/jhipster-microservice/gateway-app/pom.xml index b90f22f009..7c95704da7 100644 --- a/jhipster-modules/jhipster-microservice/gateway-app/pom.xml +++ b/jhipster-modules/jhipster-microservice/gateway-app/pom.xml @@ -26,7 +26,7 @@ 1.3 1.2 5.2.8.Final - 2.6.0 + 5.1.0 0.7.9 3.21.0-GA 1.0.0 diff --git a/jhipster-modules/jhipster-monolithic/pom.xml b/jhipster-modules/jhipster-monolithic/pom.xml index fbcee8f1ff..bb82c819c4 100644 --- a/jhipster-modules/jhipster-monolithic/pom.xml +++ b/jhipster-modules/jhipster-monolithic/pom.xml @@ -892,7 +892,7 @@ 2.2.1 2.2.3 5.2.8.Final - 2.6.0 + 5.1.0 0.7.9 3.21.0-GA 1.0.0 diff --git a/libraries-data-db/pom.xml b/libraries-data-db/pom.xml index 5f1ff489f4..6ee8daa2a5 100644 --- a/libraries-data-db/pom.xml +++ b/libraries-data-db/pom.xml @@ -300,7 +300,7 @@ 6.0.0-release 6.0.1 3.2.1 - 5.0.1 + 5.1.0 13.15.2 2.1.3.Final 2.2.3 diff --git a/persistence-modules/core-java-persistence/pom.xml b/persistence-modules/core-java-persistence/pom.xml index 5d5c36ef01..20553da4e8 100644 --- a/persistence-modules/core-java-persistence/pom.xml +++ b/persistence-modules/core-java-persistence/pom.xml @@ -62,7 +62,7 @@ 2.9.0 - 5.0.1 + 5.1.0 0.9.5.5 3.0.4 6.0.6 diff --git a/spring-4/pom.xml b/spring-4/pom.xml index ad05123543..9a50319d13 100644 --- a/spring-4/pom.xml +++ b/spring-4/pom.xml @@ -121,7 +121,7 @@ 1.0.1 3.6 2.4.0 - 4.0.3 + 5.1.0 2.17.1 diff --git a/spring-5/pom.xml b/spring-5/pom.xml index 1ac696e7bd..65f1b77520 100644 --- a/spring-5/pom.xml +++ b/spring-5/pom.xml @@ -143,7 +143,7 @@ 1.0 1.5.6 ${project.build.directory}/generated-snippets - 4.0.3 + 5.1.0 \ No newline at end of file From cc649a15860027ba89dffebf3f6d56820a4f2a0c Mon Sep 17 00:00:00 2001 From: Harry9656 Date: Fri, 8 Dec 2023 23:27:33 +0530 Subject: [PATCH 223/228] JAVA-27515: Upgraded spring-session-jdbc to spring-boot-parent-3 (#15326) --- .../spring-session/spring-session-jdbc/pom.xml | 4 ++-- .../controller/SpringSessionJdbcController.java | 5 +++-- .../springsessionjdbc/SpringSessionJdbcIntegrationTest.java | 2 +- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/spring-web-modules/spring-session/spring-session-jdbc/pom.xml b/spring-web-modules/spring-session/spring-session-jdbc/pom.xml index 3cc2b8d18e..24194f5426 100644 --- a/spring-web-modules/spring-session/spring-session-jdbc/pom.xml +++ b/spring-web-modules/spring-session/spring-session-jdbc/pom.xml @@ -11,9 +11,9 @@ com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../../../parent-boot-2 + ../../../parent-boot-3 diff --git a/spring-web-modules/spring-session/spring-session-jdbc/src/main/java/com/baeldung/springsessionjdbc/controller/SpringSessionJdbcController.java b/spring-web-modules/spring-session/spring-session-jdbc/src/main/java/com/baeldung/springsessionjdbc/controller/SpringSessionJdbcController.java index 509a5f292b..a173636ed8 100644 --- a/spring-web-modules/spring-session/spring-session-jdbc/src/main/java/com/baeldung/springsessionjdbc/controller/SpringSessionJdbcController.java +++ b/spring-web-modules/spring-session/spring-session-jdbc/src/main/java/com/baeldung/springsessionjdbc/controller/SpringSessionJdbcController.java @@ -7,11 +7,12 @@ import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; import java.util.ArrayList; import java.util.List; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpSession; + @Controller public class SpringSessionJdbcController { diff --git a/spring-web-modules/spring-session/spring-session-jdbc/src/test/java/com/baeldung/springsessionjdbc/SpringSessionJdbcIntegrationTest.java b/spring-web-modules/spring-session/spring-session-jdbc/src/test/java/com/baeldung/springsessionjdbc/SpringSessionJdbcIntegrationTest.java index 2dcc0b3af8..7133111e4c 100644 --- a/spring-web-modules/spring-session/spring-session-jdbc/src/test/java/com/baeldung/springsessionjdbc/SpringSessionJdbcIntegrationTest.java +++ b/spring-web-modules/spring-session/spring-session-jdbc/src/test/java/com/baeldung/springsessionjdbc/SpringSessionJdbcIntegrationTest.java @@ -9,7 +9,7 @@ import org.junit.runners.MethodSorters; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; From 8ff0949464193a33fb64a339055f2e92b74e29bc Mon Sep 17 00:00:00 2001 From: Azhwani <13301425+azhwani@users.noreply.github.com> Date: Fri, 8 Dec 2023 21:22:40 +0100 Subject: [PATCH 224/228] BAEL-6021: Handling NullPointerException in findFirst() When the First Element It Finds Is Null (#15341) --- ...FindFirstNullPointerExceptionUnitTest.java | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 core-java-modules/core-java-streams-5/src/test/java/com/baeldung/findfirstnullpointerexception/FindFirstNullPointerExceptionUnitTest.java diff --git a/core-java-modules/core-java-streams-5/src/test/java/com/baeldung/findfirstnullpointerexception/FindFirstNullPointerExceptionUnitTest.java b/core-java-modules/core-java-streams-5/src/test/java/com/baeldung/findfirstnullpointerexception/FindFirstNullPointerExceptionUnitTest.java new file mode 100644 index 0000000000..074aec29d6 --- /dev/null +++ b/core-java-modules/core-java-streams-5/src/test/java/com/baeldung/findfirstnullpointerexception/FindFirstNullPointerExceptionUnitTest.java @@ -0,0 +1,42 @@ +package com.baeldung.findfirstnullpointerexception; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.function.Function; + +import org.junit.Test; + +public class FindFirstNullPointerExceptionUnitTest { + + private final List inputs = Arrays.asList(null, "foo", "bar"); + + @Test(expected = NullPointerException.class) + public void givenStream_whenCallingFindFirst_thenThrowNullPointerException() { + Optional firstElement = inputs.stream() + .findFirst(); + } + + @Test + public void givenStream_whenUsingOfNullableBeforeFindFirst_thenCorrect() { + Optional firstElement = inputs.stream() + .map(Optional::ofNullable) + .findFirst() + .flatMap(Function.identity()); + + assertTrue(firstElement.isEmpty()); + } + + @Test + public void givenStream_whenUsingFilterBeforeFindFirst_thenCorrect() { + Optional firstNonNullElement = inputs.stream() + .filter(Objects::nonNull) + .findFirst(); + + assertTrue(firstNonNullElement.isPresent()); + } + +} From c3fe804379cb634d6e32c4e445690ba21b61a6de Mon Sep 17 00:00:00 2001 From: michaelin007 Date: Sat, 9 Dec 2023 00:22:41 +0000 Subject: [PATCH 225/228] https://jira.baeldung.com/browse/BAEL-7169 --- .../java/com/baeldung/{finalstatic => staticfinal}/Bike.java | 2 +- .../com/baeldung/{finalstatic => staticfinal}/BikeUnitTest.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) rename core-java-modules/core-java-lang-6/src/main/java/com/baeldung/{finalstatic => staticfinal}/Bike.java (87%) rename core-java-modules/core-java-lang-6/src/test/java/com/baeldung/{finalstatic => staticfinal}/BikeUnitTest.java (95%) diff --git a/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/finalstatic/Bike.java b/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/staticfinal/Bike.java similarity index 87% rename from core-java-modules/core-java-lang-6/src/main/java/com/baeldung/finalstatic/Bike.java rename to core-java-modules/core-java-lang-6/src/main/java/com/baeldung/staticfinal/Bike.java index 6467ccc395..bde7b44897 100644 --- a/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/finalstatic/Bike.java +++ b/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/staticfinal/Bike.java @@ -1,4 +1,4 @@ -package com.baeldung.finalstatic; +package com.baeldung.staticfinal; import java.util.HashMap; diff --git a/core-java-modules/core-java-lang-6/src/test/java/com/baeldung/finalstatic/BikeUnitTest.java b/core-java-modules/core-java-lang-6/src/test/java/com/baeldung/staticfinal/BikeUnitTest.java similarity index 95% rename from core-java-modules/core-java-lang-6/src/test/java/com/baeldung/finalstatic/BikeUnitTest.java rename to core-java-modules/core-java-lang-6/src/test/java/com/baeldung/staticfinal/BikeUnitTest.java index 7b32b0906c..2201dae4d1 100644 --- a/core-java-modules/core-java-lang-6/src/test/java/com/baeldung/finalstatic/BikeUnitTest.java +++ b/core-java-modules/core-java-lang-6/src/test/java/com/baeldung/staticfinal/BikeUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.finalstatic; +package com.baeldung.staticfinal; import org.junit.jupiter.api.Test; From 36cc0c07eb809450f5683af2f478391ca97bc2c8 Mon Sep 17 00:00:00 2001 From: Pedro Lopes Date: Sat, 9 Dec 2023 12:20:58 -0300 Subject: [PATCH 226/228] fix embedded kafka port (#15296) --- .../ManagingConsumerGroupsIntegrationTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-kafka-2/src/test/java/com/baeldung/spring/kafka/managingkafkaconsumergroups/ManagingConsumerGroupsIntegrationTest.java b/spring-kafka-2/src/test/java/com/baeldung/spring/kafka/managingkafkaconsumergroups/ManagingConsumerGroupsIntegrationTest.java index 1620add9ca..ddbb105a67 100644 --- a/spring-kafka-2/src/test/java/com/baeldung/spring/kafka/managingkafkaconsumergroups/ManagingConsumerGroupsIntegrationTest.java +++ b/spring-kafka-2/src/test/java/com/baeldung/spring/kafka/managingkafkaconsumergroups/ManagingConsumerGroupsIntegrationTest.java @@ -14,7 +14,7 @@ import java.util.Objects; import static org.junit.jupiter.api.Assertions.assertEquals; @SpringBootTest(classes = ManagingConsumerGroupsApplicationKafkaApp.class) -@EmbeddedKafka(partitions = 2, brokerProperties = {"listeners=PLAINTEXT://localhost:9092", "port=9092"}) +@EmbeddedKafka(partitions = 2, brokerProperties = {"listeners=PLAINTEXT://localhost:9098", "port=9098"}) public class ManagingConsumerGroupsIntegrationTest { private static final String CONSUMER_1_IDENTIFIER = "org.springframework.kafka.KafkaListenerEndpointContainer#1"; From bb989a8fe3fa15d0977d48df2a3f1f382f6dbec3 Mon Sep 17 00:00:00 2001 From: panos-kakos <102670093+panos-kakos@users.noreply.github.com> Date: Sat, 9 Dec 2023 20:40:53 +0200 Subject: [PATCH 227/228] [JAVA-27235] Moved article "Spring Custom Property Editor" to spring-boot-data-2 (#15381) --- spring-boot-modules/spring-boot-data-2/README.md | 2 +- .../com/baeldung/propertyeditor/PropertyEditorApplication.java | 0 .../baeldung/propertyeditor/PropertyEditorRestController.java | 0 .../java/com/baeldung/propertyeditor/creditcard/CreditCard.java | 0 .../baeldung/propertyeditor/creditcard/CreditCardEditor.java | 0 .../exotictype/editor/CustomExoticTypeEditor.java | 0 .../baeldung/propertyeditor/exotictype/model/ExoticType.java | 0 .../propertyeditor/creditcard/CreditCardEditorUnitTest.java | 0 spring-boot-modules/spring-boot-data/README.md | 1 - 9 files changed, 1 insertion(+), 2 deletions(-) rename spring-boot-modules/{spring-boot-data => spring-boot-data-2}/src/main/java/com/baeldung/propertyeditor/PropertyEditorApplication.java (100%) rename spring-boot-modules/{spring-boot-data => spring-boot-data-2}/src/main/java/com/baeldung/propertyeditor/PropertyEditorRestController.java (100%) rename spring-boot-modules/{spring-boot-data => spring-boot-data-2}/src/main/java/com/baeldung/propertyeditor/creditcard/CreditCard.java (100%) rename spring-boot-modules/{spring-boot-data => spring-boot-data-2}/src/main/java/com/baeldung/propertyeditor/creditcard/CreditCardEditor.java (100%) rename spring-boot-modules/{spring-boot-data => spring-boot-data-2}/src/main/java/com/baeldung/propertyeditor/exotictype/editor/CustomExoticTypeEditor.java (100%) rename spring-boot-modules/{spring-boot-data => spring-boot-data-2}/src/main/java/com/baeldung/propertyeditor/exotictype/model/ExoticType.java (100%) rename spring-boot-modules/{spring-boot-data => spring-boot-data-2}/src/test/java/com/baeldung/propertyeditor/creditcard/CreditCardEditorUnitTest.java (100%) diff --git a/spring-boot-modules/spring-boot-data-2/README.md b/spring-boot-modules/spring-boot-data-2/README.md index 8e6619dce4..b8f0347453 100644 --- a/spring-boot-modules/spring-boot-data-2/README.md +++ b/spring-boot-modules/spring-boot-data-2/README.md @@ -6,4 +6,4 @@ - [Using JaVers for Data Model Auditing in Spring Data](https://www.baeldung.com/spring-data-javers-audit) - [BootstrapMode for JPA Repositories](https://www.baeldung.com/jpa-bootstrap-mode) - [Dynamic DTO Validation Config Retrieved from the Database](https://www.baeldung.com/spring-dynamic-dto-validation) - +- [Spring Custom Property Editor](https://www.baeldung.com/spring-mvc-custom-property-editor) diff --git a/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/propertyeditor/PropertyEditorApplication.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/propertyeditor/PropertyEditorApplication.java similarity index 100% rename from spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/propertyeditor/PropertyEditorApplication.java rename to spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/propertyeditor/PropertyEditorApplication.java diff --git a/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/propertyeditor/PropertyEditorRestController.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/propertyeditor/PropertyEditorRestController.java similarity index 100% rename from spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/propertyeditor/PropertyEditorRestController.java rename to spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/propertyeditor/PropertyEditorRestController.java diff --git a/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/propertyeditor/creditcard/CreditCard.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/propertyeditor/creditcard/CreditCard.java similarity index 100% rename from spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/propertyeditor/creditcard/CreditCard.java rename to spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/propertyeditor/creditcard/CreditCard.java diff --git a/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/propertyeditor/creditcard/CreditCardEditor.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/propertyeditor/creditcard/CreditCardEditor.java similarity index 100% rename from spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/propertyeditor/creditcard/CreditCardEditor.java rename to spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/propertyeditor/creditcard/CreditCardEditor.java diff --git a/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/propertyeditor/exotictype/editor/CustomExoticTypeEditor.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/propertyeditor/exotictype/editor/CustomExoticTypeEditor.java similarity index 100% rename from spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/propertyeditor/exotictype/editor/CustomExoticTypeEditor.java rename to spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/propertyeditor/exotictype/editor/CustomExoticTypeEditor.java diff --git a/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/propertyeditor/exotictype/model/ExoticType.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/propertyeditor/exotictype/model/ExoticType.java similarity index 100% rename from spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/propertyeditor/exotictype/model/ExoticType.java rename to spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/propertyeditor/exotictype/model/ExoticType.java diff --git a/spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/propertyeditor/creditcard/CreditCardEditorUnitTest.java b/spring-boot-modules/spring-boot-data-2/src/test/java/com/baeldung/propertyeditor/creditcard/CreditCardEditorUnitTest.java similarity index 100% rename from spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/propertyeditor/creditcard/CreditCardEditorUnitTest.java rename to spring-boot-modules/spring-boot-data-2/src/test/java/com/baeldung/propertyeditor/creditcard/CreditCardEditorUnitTest.java diff --git a/spring-boot-modules/spring-boot-data/README.md b/spring-boot-modules/spring-boot-data/README.md index aa745b77a2..49a6eedbed 100644 --- a/spring-boot-modules/spring-boot-data/README.md +++ b/spring-boot-modules/spring-boot-data/README.md @@ -8,7 +8,6 @@ This module contains articles about Spring Boot with Spring Data - [Rendering Exceptions in JSON with Spring](https://www.baeldung.com/spring-exceptions-json) - [Disable Spring Data Auto Configuration](https://www.baeldung.com/spring-data-disable-auto-config) - [Repositories with Multiple Spring Data Modules](https://www.baeldung.com/spring-multiple-data-modules) -- [Spring Custom Property Editor](https://www.baeldung.com/spring-mvc-custom-property-editor) - [Using @JsonComponent in Spring Boot](https://www.baeldung.com/spring-boot-jsoncomponent) - [Guide To Running Logic on Startup in Spring](https://www.baeldung.com/running-setup-logic-on-startup-in-spring) - [Spring Boot: Customize the Jackson ObjectMapper](https://www.baeldung.com/spring-boot-customize-jackson-objectmapper) From f624403a861b0bdb49fa18ead928c0b689ba92f0 Mon Sep 17 00:00:00 2001 From: panos-kakos <102670093+panos-kakos@users.noreply.github.com> Date: Sat, 9 Dec 2023 21:15:35 +0200 Subject: [PATCH 228/228] [JAVA-28185] (#15367) * [JAVA-28185] Moved code for article(Introduction to HtmlUnit) to spring-mvc-java-2 * [JAVA-28185] Moved code for article(Upload and Display Excel Files with Spring MVC) to spring-mvc-java-2 * [JAVA-28185] Clean up * [JAVA-28185] --- .../spring-mvc-java-2/README.md | 2 + spring-web-modules/spring-mvc-java-2/pom.xml | 56 +++++++++++++++++++ .../com/baeldung/excel}/ExcelController.java | 19 ++++--- .../com/baeldung/excel/ExcelPOIHelper.java | 34 +++++------ .../main/java/com/baeldung/excel/MyCell.java | 0 .../java/com/baeldung/excel/WebConfig.java | 32 +++++++++++ .../htmlunit/HtmlUnitAndJUnitLiveTest.java | 0 .../htmlunit/HtmlUnitAndSpringLiveTest.java | 0 .../htmlunit/HtmlUnitWebScrapingLiveTest.java | 0 .../com/baeldung/htmlunit/TestConfig.java | 4 +- spring-web-modules/spring-mvc-java/README.md | 2 - spring-web-modules/spring-mvc-java/pom.xml | 27 +-------- .../baeldung/spring/web/config/WebConfig.java | 6 -- 13 files changed, 121 insertions(+), 61 deletions(-) rename spring-web-modules/{spring-mvc-java/src/main/java/com/baeldung/web/controller => spring-mvc-java-2/src/main/java/com/baeldung/excel}/ExcelController.java (97%) rename spring-web-modules/{spring-mvc-java => spring-mvc-java-2}/src/main/java/com/baeldung/excel/ExcelPOIHelper.java (100%) rename spring-web-modules/{spring-mvc-java => spring-mvc-java-2}/src/main/java/com/baeldung/excel/MyCell.java (100%) create mode 100644 spring-web-modules/spring-mvc-java-2/src/main/java/com/baeldung/excel/WebConfig.java rename spring-web-modules/{spring-mvc-java => spring-mvc-java-2}/src/test/java/com/baeldung/htmlunit/HtmlUnitAndJUnitLiveTest.java (100%) rename spring-web-modules/{spring-mvc-java => spring-mvc-java-2}/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringLiveTest.java (100%) rename spring-web-modules/{spring-mvc-java => spring-mvc-java-2}/src/test/java/com/baeldung/htmlunit/HtmlUnitWebScrapingLiveTest.java (100%) rename spring-web-modules/{spring-mvc-java => spring-mvc-java-2}/src/test/java/com/baeldung/htmlunit/TestConfig.java (99%) diff --git a/spring-web-modules/spring-mvc-java-2/README.md b/spring-web-modules/spring-mvc-java-2/README.md index 1f8231bada..61549b539a 100644 --- a/spring-web-modules/spring-mvc-java-2/README.md +++ b/spring-web-modules/spring-mvc-java-2/README.md @@ -5,3 +5,5 @@ - [A Quick Guide to Spring MVC Matrix Variables](https://www.baeldung.com/spring-mvc-matrix-variables) - [Converting a Spring MultipartFile to a File](https://www.baeldung.com/spring-multipartfile-to-file) - [Testing a Spring Multipart POST Request](https://www.baeldung.com/spring-multipart-post-request-test) +- [Introduction to HtmlUnit](https://www.baeldung.com/htmlunit) +- [Upload and Display Excel Files with Spring MVC](https://www.baeldung.com/spring-mvc-excel-files) diff --git a/spring-web-modules/spring-mvc-java-2/pom.xml b/spring-web-modules/spring-mvc-java-2/pom.xml index b1b5a797f8..a4484ed56d 100644 --- a/spring-web-modules/spring-mvc-java-2/pom.xml +++ b/spring-web-modules/spring-mvc-java-2/pom.xml @@ -46,6 +46,57 @@ commons-fileupload ${commons-fileupload.version} + + net.sourceforge.htmlunit + htmlunit + ${htmlunit.version} + + + commons-logging + commons-logging + + + commons-io + commons-io + + + + + + org.apache.poi + poi-ooxml + ${poi.version} + + + org.glassfish + javax.el + ${javax.el.version} + + + javax.servlet.jsp + javax.servlet.jsp-api + ${javax-servlet-api.version} + + + javax.servlet + jstl + + + org.apache.tomcat.embed + tomcat-embed-jasper + provided + + + + org.thymeleaf + thymeleaf-spring4 + ${thymeleaf.version} + + + org.thymeleaf + thymeleaf + ${thymeleaf.version} + @@ -63,6 +114,11 @@ 5.2.2.RELEASE 2.3.5 1.5 + 2.32 + 3.16-beta1 + 3.0.1-b09 + 2.3.3 + 3.0.9.RELEASE \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-java/src/main/java/com/baeldung/web/controller/ExcelController.java b/spring-web-modules/spring-mvc-java-2/src/main/java/com/baeldung/excel/ExcelController.java similarity index 97% rename from spring-web-modules/spring-mvc-java/src/main/java/com/baeldung/web/controller/ExcelController.java rename to spring-web-modules/spring-mvc-java-2/src/main/java/com/baeldung/excel/ExcelController.java index f76f7441a5..5cb5de7124 100644 --- a/spring-web-modules/spring-mvc-java/src/main/java/com/baeldung/web/controller/ExcelController.java +++ b/spring-web-modules/spring-mvc-java-2/src/main/java/com/baeldung/excel/ExcelController.java @@ -1,18 +1,19 @@ -package com.baeldung.web.controller; +package com.baeldung.excel; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.List; +import java.util.Map; + +import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.multipart.MultipartFile; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import com.baeldung.excel.*; -import java.util.Map; -import java.util.List; -import javax.annotation.Resource; @Controller public class ExcelController { diff --git a/spring-web-modules/spring-mvc-java/src/main/java/com/baeldung/excel/ExcelPOIHelper.java b/spring-web-modules/spring-mvc-java-2/src/main/java/com/baeldung/excel/ExcelPOIHelper.java similarity index 100% rename from spring-web-modules/spring-mvc-java/src/main/java/com/baeldung/excel/ExcelPOIHelper.java rename to spring-web-modules/spring-mvc-java-2/src/main/java/com/baeldung/excel/ExcelPOIHelper.java index 0519a8f3c7..7a213d523b 100644 --- a/spring-web-modules/spring-mvc-java/src/main/java/com/baeldung/excel/ExcelPOIHelper.java +++ b/spring-web-modules/spring-mvc-java-2/src/main/java/com/baeldung/excel/ExcelPOIHelper.java @@ -1,13 +1,14 @@ package com.baeldung.excel; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.xssf.usermodel.XSSFCell; -import org.apache.poi.xssf.usermodel.XSSFCellStyle; -import org.apache.poi.xssf.usermodel.XSSFColor; -import org.apache.poi.xssf.usermodel.XSSFFont; -import org.apache.poi.xssf.usermodel.XSSFRow; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.IntStream; + import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFFont; @@ -15,16 +16,15 @@ import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.util.HSSFColor; +import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.DateUtil; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.util.Map; -import java.util.HashMap; -import java.util.ArrayList; -import java.util.List; -import java.util.stream.IntStream; +import org.apache.poi.xssf.usermodel.XSSFCell; +import org.apache.poi.xssf.usermodel.XSSFCellStyle; +import org.apache.poi.xssf.usermodel.XSSFColor; +import org.apache.poi.xssf.usermodel.XSSFFont; +import org.apache.poi.xssf.usermodel.XSSFRow; +import org.apache.poi.xssf.usermodel.XSSFSheet; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExcelPOIHelper { diff --git a/spring-web-modules/spring-mvc-java/src/main/java/com/baeldung/excel/MyCell.java b/spring-web-modules/spring-mvc-java-2/src/main/java/com/baeldung/excel/MyCell.java similarity index 100% rename from spring-web-modules/spring-mvc-java/src/main/java/com/baeldung/excel/MyCell.java rename to spring-web-modules/spring-mvc-java-2/src/main/java/com/baeldung/excel/MyCell.java diff --git a/spring-web-modules/spring-mvc-java-2/src/main/java/com/baeldung/excel/WebConfig.java b/spring-web-modules/spring-mvc-java-2/src/main/java/com/baeldung/excel/WebConfig.java new file mode 100644 index 0000000000..f6a4d4dba3 --- /dev/null +++ b/spring-web-modules/spring-mvc-java-2/src/main/java/com/baeldung/excel/WebConfig.java @@ -0,0 +1,32 @@ +package com.baeldung.excel; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + + +@EnableWebMvc +@Configuration +@ComponentScan(basePackages = { "com.baeldung.excel" }) +public class WebConfig implements WebMvcConfigurer { + + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + registry.addViewController("/").setViewName("index"); + } + + @Override + public void addResourceHandlers(final ResourceHandlerRegistry registry) { + registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); + } + + + @Bean + public ExcelPOIHelper excelPOIHelper() { + return new ExcelPOIHelper(); + } +} diff --git a/spring-web-modules/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndJUnitLiveTest.java b/spring-web-modules/spring-mvc-java-2/src/test/java/com/baeldung/htmlunit/HtmlUnitAndJUnitLiveTest.java similarity index 100% rename from spring-web-modules/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndJUnitLiveTest.java rename to spring-web-modules/spring-mvc-java-2/src/test/java/com/baeldung/htmlunit/HtmlUnitAndJUnitLiveTest.java diff --git a/spring-web-modules/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringLiveTest.java b/spring-web-modules/spring-mvc-java-2/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringLiveTest.java similarity index 100% rename from spring-web-modules/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringLiveTest.java rename to spring-web-modules/spring-mvc-java-2/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringLiveTest.java diff --git a/spring-web-modules/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitWebScrapingLiveTest.java b/spring-web-modules/spring-mvc-java-2/src/test/java/com/baeldung/htmlunit/HtmlUnitWebScrapingLiveTest.java similarity index 100% rename from spring-web-modules/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitWebScrapingLiveTest.java rename to spring-web-modules/spring-mvc-java-2/src/test/java/com/baeldung/htmlunit/HtmlUnitWebScrapingLiveTest.java diff --git a/spring-web-modules/spring-mvc-java/src/test/java/com/baeldung/htmlunit/TestConfig.java b/spring-web-modules/spring-mvc-java-2/src/test/java/com/baeldung/htmlunit/TestConfig.java similarity index 99% rename from spring-web-modules/spring-mvc-java/src/test/java/com/baeldung/htmlunit/TestConfig.java rename to spring-web-modules/spring-mvc-java-2/src/test/java/com/baeldung/htmlunit/TestConfig.java index 75efd57ae4..6e55f01454 100644 --- a/spring-web-modules/spring-mvc-java/src/test/java/com/baeldung/htmlunit/TestConfig.java +++ b/spring-web-modules/spring-mvc-java-2/src/test/java/com/baeldung/htmlunit/TestConfig.java @@ -20,7 +20,7 @@ public class TestConfig implements WebMvcConfigurer { @Autowired private ServletContext ctx; - + @Bean public ViewResolver thymeleafViewResolver() { final ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); @@ -44,4 +44,4 @@ public class TestConfig implements WebMvcConfigurer { templateEngine.setTemplateResolver(templateResolver()); return templateEngine; } -} +} \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-java/README.md b/spring-web-modules/spring-mvc-java/README.md index 656e415f6a..d89f33fdc1 100644 --- a/spring-web-modules/spring-mvc-java/README.md +++ b/spring-web-modules/spring-mvc-java/README.md @@ -9,8 +9,6 @@ The "REST With Spring" Classes: https://bit.ly/restwithspring ### Relevant Articles: - [Integration Testing in Spring](https://www.baeldung.com/integration-testing-in-spring) - [File Upload with Spring MVC](https://www.baeldung.com/spring-file-upload) -- [Introduction to HtmlUnit](https://www.baeldung.com/htmlunit) -- [Upload and Display Excel Files with Spring MVC](https://www.baeldung.com/spring-mvc-excel-files) - [web.xml vs Initializer with Spring](https://www.baeldung.com/spring-xml-vs-java-config) - [A Java Web Application Without a web.xml](https://www.baeldung.com/java-web-app-without-web-xml) - [Accessing Spring MVC Model Objects in JavaScript](https://www.baeldung.com/spring-mvc-model-objects-js) diff --git a/spring-web-modules/spring-mvc-java/pom.xml b/spring-web-modules/spring-mvc-java/pom.xml index 395b12a278..d4c8f24431 100644 --- a/spring-web-modules/spring-mvc-java/pom.xml +++ b/spring-web-modules/spring-mvc-java/pom.xml @@ -44,21 +44,7 @@ provided - - net.sourceforge.htmlunit - htmlunit - ${htmlunit.version} - - - commons-logging - commons-logging - - - commons-io - commons-io - - - + commons-io commons-io @@ -91,12 +77,7 @@ spring-boot-starter-test test - - - org.apache.poi - poi-ooxml - ${poi.version} - + org.hibernate.validator @@ -221,19 +202,15 @@ 4.4.5 4.5.2 - 2.23 2.7 1.6.1 3.1.0 1.9.1 - - 3.16-beta1 3.0.1-b09 4.0.1 2.3.3 - 2.32 2.8.0 com.baeldung.SpringMVCApplication diff --git a/spring-web-modules/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java b/spring-web-modules/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java index 768fda1c4a..c135164a95 100644 --- a/spring-web-modules/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java +++ b/spring-web-modules/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java @@ -27,7 +27,6 @@ import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver; import org.thymeleaf.spring4.view.ThymeleafViewResolver; import org.thymeleaf.templateresolver.ITemplateResolver; -import com.baeldung.excel.ExcelPOIHelper; @EnableWebMvc @Configuration @@ -118,11 +117,6 @@ public class WebConfig implements WebMvcConfigurer { configurer.setUrlPathHelper(urlPathHelper); } - @Bean - public ExcelPOIHelper excelPOIHelper() { - return new ExcelPOIHelper(); - } - @Bean(name = "multipartResolver") public CommonsMultipartResolver multipartResolver() { CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();