From fa34902b702d98b542bd30207e9b11479d5af23e Mon Sep 17 00:00:00 2001 From: mcasari Date: Sat, 19 Aug 2023 23:42:04 +0200 Subject: [PATCH 01/37] shallow vs deep copy first commit --- shallow-deep-copy/README.md | 7 +++++ shallow-deep-copy/pom.xml | 16 ++++++++++ .../baeldung/shallowdeepcopy/Dependency.java | 23 ++++++++++++++ .../com/baeldung/shallowdeepcopy/Main.java | 31 +++++++++++++++++++ .../src/main/resources/logback.xml | 13 ++++++++ .../ShallowDeepCopyUnitTest.java | 27 ++++++++++++++++ 6 files changed, 117 insertions(+) create mode 100644 shallow-deep-copy/README.md create mode 100644 shallow-deep-copy/pom.xml create mode 100644 shallow-deep-copy/src/main/java/com/baeldung/shallowdeepcopy/Dependency.java create mode 100644 shallow-deep-copy/src/main/java/com/baeldung/shallowdeepcopy/Main.java create mode 100644 shallow-deep-copy/src/main/resources/logback.xml create mode 100644 shallow-deep-copy/src/test/java/com/baeldung/shallowdeepcopy/ShallowDeepCopyUnitTest.java diff --git a/shallow-deep-copy/README.md b/shallow-deep-copy/README.md new file mode 100644 index 0000000000..e1a426a138 --- /dev/null +++ b/shallow-deep-copy/README.md @@ -0,0 +1,7 @@ +## Shallow vs Deep Copy + +This module contains an article about shallow vs deep copy of Java objects + +### Relevant articles: + +- [Creating a deep vs shallow copy of an object in Java](https://drafts.baeldung.com/?p=172294&preview=true) diff --git a/shallow-deep-copy/pom.xml b/shallow-deep-copy/pom.xml new file mode 100644 index 0000000000..01c1430f28 --- /dev/null +++ b/shallow-deep-copy/pom.xml @@ -0,0 +1,16 @@ + + + 4.0.0 + shallow-deep-copy + shallow-deep-copy + jar + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + \ No newline at end of file diff --git a/shallow-deep-copy/src/main/java/com/baeldung/shallowdeepcopy/Dependency.java b/shallow-deep-copy/src/main/java/com/baeldung/shallowdeepcopy/Dependency.java new file mode 100644 index 0000000000..a5da5fc163 --- /dev/null +++ b/shallow-deep-copy/src/main/java/com/baeldung/shallowdeepcopy/Dependency.java @@ -0,0 +1,23 @@ +package com.baeldung.shallowdeepcopy; + +public class Dependency implements Cloneable { + private int value = 13; + + public Dependency(int value) { + super(); + this.value = value; + } + + public int getValue() { + return value; + } + + public void setValue(int value) { + this.value = value; + } + + @Override + protected Object clone() throws CloneNotSupportedException { + return super.clone(); + } +} diff --git a/shallow-deep-copy/src/main/java/com/baeldung/shallowdeepcopy/Main.java b/shallow-deep-copy/src/main/java/com/baeldung/shallowdeepcopy/Main.java new file mode 100644 index 0000000000..fb24007162 --- /dev/null +++ b/shallow-deep-copy/src/main/java/com/baeldung/shallowdeepcopy/Main.java @@ -0,0 +1,31 @@ +package com.baeldung.shallowdeepcopy; + +public class Main implements Cloneable { + private Dependency dependency; + + public Main(Dependency dependency) { + super(); + this.dependency = dependency; + } + + @Override + public Object clone() throws CloneNotSupportedException { + return super.clone(); + } + + public Object deepClone() throws CloneNotSupportedException { + Main dependentClone = (Main) super.clone(); + Dependency dependencyClone = (Dependency) this.dependency.clone(); + dependentClone.setDependency(dependencyClone); + return dependentClone; + } + + public Dependency getDependency() { + return dependency; + } + + public void setDependency(Dependency dependency) { + this.dependency = dependency; + } + +} diff --git a/shallow-deep-copy/src/main/resources/logback.xml b/shallow-deep-copy/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/shallow-deep-copy/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/shallow-deep-copy/src/test/java/com/baeldung/shallowdeepcopy/ShallowDeepCopyUnitTest.java b/shallow-deep-copy/src/test/java/com/baeldung/shallowdeepcopy/ShallowDeepCopyUnitTest.java new file mode 100644 index 0000000000..321c2df327 --- /dev/null +++ b/shallow-deep-copy/src/test/java/com/baeldung/shallowdeepcopy/ShallowDeepCopyUnitTest.java @@ -0,0 +1,27 @@ +package com.baeldung.shallowdeepcopy; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +class ShallowDeepCopyUnitTest { + + @Test + public void givenAnObjectAndADependency_whenShallowClonedAndDepencyChanges_ThenDepencyHasNewValue() throws Exception { + Dependency dependency = new Dependency(13); + Main main = new Main(dependency); + Main shallowClone = (Main) main.clone(); + dependency.setValue(17); + assertEquals(17, shallowClone.getDependency().getValue()); + } + + + @Test + public void givenAnObjectAndADependency_whenDeepClonedAndDepencyChanges_ThenDepencyKeepsOldValue() throws Exception { + Dependency dependency = new Dependency(13); + Main main = new Main(dependency); + Main deepClone = (Main) main.deepClone(); + dependency.setValue(17); + assertEquals(13, deepClone.getDependency().getValue()); + } +} From 8a6e3f233ec0591fe20d82fcf00c80cb8164b577 Mon Sep 17 00:00:00 2001 From: mcasari Date: Tue, 22 Aug 2023 19:49:54 +0200 Subject: [PATCH 02/37] Format content with baeldung formatter --- shallow-deep-copy/pom.xml | 22 ++++----- .../baeldung/shallowdeepcopy/Dependency.java | 32 ++++++------- .../com/baeldung/shallowdeepcopy/Main.java | 48 +++++++++---------- .../src/main/resources/logback.xml | 19 ++++---- .../ShallowDeepCopyUnitTest.java | 37 +++++++------- 5 files changed, 80 insertions(+), 78 deletions(-) diff --git a/shallow-deep-copy/pom.xml b/shallow-deep-copy/pom.xml index 01c1430f28..323f720df3 100644 --- a/shallow-deep-copy/pom.xml +++ b/shallow-deep-copy/pom.xml @@ -1,16 +1,16 @@ - 4.0.0 - shallow-deep-copy - shallow-deep-copy - jar + 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 + shallow-deep-copy + shallow-deep-copy + jar - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + \ No newline at end of file diff --git a/shallow-deep-copy/src/main/java/com/baeldung/shallowdeepcopy/Dependency.java b/shallow-deep-copy/src/main/java/com/baeldung/shallowdeepcopy/Dependency.java index a5da5fc163..2550acd268 100644 --- a/shallow-deep-copy/src/main/java/com/baeldung/shallowdeepcopy/Dependency.java +++ b/shallow-deep-copy/src/main/java/com/baeldung/shallowdeepcopy/Dependency.java @@ -1,23 +1,23 @@ package com.baeldung.shallowdeepcopy; public class Dependency implements Cloneable { - private int value = 13; - - public Dependency(int value) { - super(); - this.value = value; - } + private int value = 13; - public int getValue() { - return value; - } + public Dependency(int value) { + super(); + this.value = value; + } - public void setValue(int value) { - this.value = value; - } + public int getValue() { + return value; + } - @Override - protected Object clone() throws CloneNotSupportedException { - return super.clone(); - } + public void setValue(int value) { + this.value = value; + } + + @Override + protected Object clone() throws CloneNotSupportedException { + return super.clone(); + } } diff --git a/shallow-deep-copy/src/main/java/com/baeldung/shallowdeepcopy/Main.java b/shallow-deep-copy/src/main/java/com/baeldung/shallowdeepcopy/Main.java index fb24007162..33d565bb10 100644 --- a/shallow-deep-copy/src/main/java/com/baeldung/shallowdeepcopy/Main.java +++ b/shallow-deep-copy/src/main/java/com/baeldung/shallowdeepcopy/Main.java @@ -1,31 +1,31 @@ package com.baeldung.shallowdeepcopy; public class Main implements Cloneable { - private Dependency dependency; - - public Main(Dependency dependency) { - super(); - this.dependency = dependency; - } + private Dependency dependency; - @Override - public Object clone() throws CloneNotSupportedException { - return super.clone(); - } + public Main(Dependency dependency) { + super(); + this.dependency = dependency; + } - public Object deepClone() throws CloneNotSupportedException { - Main dependentClone = (Main) super.clone(); - Dependency dependencyClone = (Dependency) this.dependency.clone(); - dependentClone.setDependency(dependencyClone); - return dependentClone; - } - - public Dependency getDependency() { - return dependency; - } + @Override + public Object clone() throws CloneNotSupportedException { + return super.clone(); + } + + public Object deepClone() throws CloneNotSupportedException { + Main dependentClone = (Main) super.clone(); + Dependency dependencyClone = (Dependency) this.dependency.clone(); + dependentClone.setDependency(dependencyClone); + return dependentClone; + } + + public Dependency getDependency() { + return dependency; + } + + public void setDependency(Dependency dependency) { + this.dependency = dependency; + } - public void setDependency(Dependency dependency) { - this.dependency = dependency; - } - } diff --git a/shallow-deep-copy/src/main/resources/logback.xml b/shallow-deep-copy/src/main/resources/logback.xml index 7d900d8ea8..830ab22727 100644 --- a/shallow-deep-copy/src/main/resources/logback.xml +++ b/shallow-deep-copy/src/main/resources/logback.xml @@ -1,13 +1,14 @@ - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + - - - + + + \ No newline at end of file diff --git a/shallow-deep-copy/src/test/java/com/baeldung/shallowdeepcopy/ShallowDeepCopyUnitTest.java b/shallow-deep-copy/src/test/java/com/baeldung/shallowdeepcopy/ShallowDeepCopyUnitTest.java index 321c2df327..f75bbc040b 100644 --- a/shallow-deep-copy/src/test/java/com/baeldung/shallowdeepcopy/ShallowDeepCopyUnitTest.java +++ b/shallow-deep-copy/src/test/java/com/baeldung/shallowdeepcopy/ShallowDeepCopyUnitTest.java @@ -5,23 +5,24 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; class ShallowDeepCopyUnitTest { - - @Test - public void givenAnObjectAndADependency_whenShallowClonedAndDepencyChanges_ThenDepencyHasNewValue() throws Exception { - Dependency dependency = new Dependency(13); - Main main = new Main(dependency); - Main shallowClone = (Main) main.clone(); - dependency.setValue(17); - assertEquals(17, shallowClone.getDependency().getValue()); - } - - @Test - public void givenAnObjectAndADependency_whenDeepClonedAndDepencyChanges_ThenDepencyKeepsOldValue() throws Exception { - Dependency dependency = new Dependency(13); - Main main = new Main(dependency); - Main deepClone = (Main) main.deepClone(); - dependency.setValue(17); - assertEquals(13, deepClone.getDependency().getValue()); - } + @Test + public void givenAnObjectAndADependency_whenShallowClonedAndDepencyChanges_ThenDepencyHasNewValue() throws Exception { + Dependency dependency = new Dependency(13); + Main main = new Main(dependency); + Main shallowClone = (Main) main.clone(); + dependency.setValue(17); + assertEquals(17, shallowClone.getDependency() + .getValue()); + } + + @Test + public void givenAnObjectAndADependency_whenDeepClonedAndDepencyChanges_ThenDepencyKeepsOldValue() throws Exception { + Dependency dependency = new Dependency(13); + Main main = new Main(dependency); + Main deepClone = (Main) main.deepClone(); + dependency.setValue(17); + assertEquals(13, deepClone.getDependency() + .getValue()); + } } From d20c1616c15bc65f73d574630f4f1f7323270eec Mon Sep 17 00:00:00 2001 From: Michael Pratt Date: Sat, 2 Sep 2023 12:21:01 -0600 Subject: [PATCH 03/37] Add form examples to Jersey modules --- jersey/pom.xml | 7 ++- .../server/form/FormExampleResource.java | 61 +++++++++++++++++++ .../main/resources/formexamples/example1.html | 16 +++++ .../main/resources/formexamples/example2.html | 18 ++++++ 4 files changed, 101 insertions(+), 1 deletion(-) create mode 100644 jersey/src/main/java/com/baeldung/jersey/server/form/FormExampleResource.java create mode 100644 jersey/src/main/resources/formexamples/example1.html create mode 100644 jersey/src/main/resources/formexamples/example2.html diff --git a/jersey/pom.xml b/jersey/pom.xml index 005fa85077..d019d31e1e 100644 --- a/jersey/pom.xml +++ b/jersey/pom.xml @@ -76,6 +76,11 @@ jersey-apache-connector ${jersey.version} + + org.glassfish.jersey.media + jersey-media-multipart + ${jersey.version} + @@ -103,4 +108,4 @@ 3.3.2 - \ No newline at end of file + diff --git a/jersey/src/main/java/com/baeldung/jersey/server/form/FormExampleResource.java b/jersey/src/main/java/com/baeldung/jersey/server/form/FormExampleResource.java new file mode 100644 index 0000000000..15e82679ef --- /dev/null +++ b/jersey/src/main/java/com/baeldung/jersey/server/form/FormExampleResource.java @@ -0,0 +1,61 @@ +package com.baeldung.jersey.server.form; + +import jakarta.ws.rs.*; +import jakarta.ws.rs.core.MediaType; +import org.glassfish.jersey.media.multipart.FormDataParam; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStream; + +@Path("form") +public class FormExampleResource +{ + @GET + @Path("/example1") + @Produces({MediaType.TEXT_HTML}) + public InputStream getExample1() throws Exception + { + File f = new File("src/main/resources/html/example1.html"); + return new FileInputStream(f); + } + + @GET + @Path("/example2") + @Produces({MediaType.TEXT_HTML}) + public InputStream getExample2() throws Exception + { + File f = new File("src/main/resources/html/example2.html"); + return new FileInputStream(f); + } + + @POST + @Path("/example1") + public String example1(@FormParam("first_name") String firstName, + @FormParam("last_name") String lastName, + @FormParam("age") String age) + { + return "Got: First = " + firstName + ", Last = " + lastName + ", Age = " + age; + } + + @POST + @Path("/example2") + @Consumes(MediaType.MULTIPART_FORM_DATA) + public String example2(@FormDataParam("first_name") String firstName, + @FormDataParam("last_name") String lastName, + @FormDataParam("age") String age, + @FormDataParam("photo") InputStream photo) + throws Exception + { + int len; + int size = 1024; + byte[] buf; + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + buf = new byte[size]; + while ((len = photo.read(buf, 0, size)) != -1) + bos.write(buf, 0, len); + buf = bos.toByteArray(); + return "Got: First = " + firstName + ", Last = " + lastName + ", Age = " + age + ", Photo (# of bytes) = " + buf.length; + } +} diff --git a/jersey/src/main/resources/formexamples/example1.html b/jersey/src/main/resources/formexamples/example1.html new file mode 100644 index 0000000000..6335dcce08 --- /dev/null +++ b/jersey/src/main/resources/formexamples/example1.html @@ -0,0 +1,16 @@ + + + Example 1 using @FormParam + + +
+ + + + + + + +
+ + diff --git a/jersey/src/main/resources/formexamples/example2.html b/jersey/src/main/resources/formexamples/example2.html new file mode 100644 index 0000000000..4875c652a4 --- /dev/null +++ b/jersey/src/main/resources/formexamples/example2.html @@ -0,0 +1,18 @@ + + + Example 2 using @FormDataParam + + +
+ + + + + + + + + +
+ + From 4e77570581c66ef1e428756f509ad690cbf5db5d Mon Sep 17 00:00:00 2001 From: "emanuel.trandafir" Date: Sun, 3 Sep 2023 14:45:27 +0200 Subject: [PATCH 04/37] BAEL-6923: added comments about docker env --- .../com/baeldung/testcontainers/DynamicPropertiesLiveTest.java | 2 ++ .../java/com/baeldung/testcontainers/LocalDevApplication.java | 3 +++ .../com/baeldung/testcontainers/ServiceConnectionLiveTest.java | 2 ++ 3 files changed, 7 insertions(+) diff --git a/spring-boot-modules/spring-boot-3-testcontainers/src/test/java/com/baeldung/testcontainers/DynamicPropertiesLiveTest.java b/spring-boot-modules/spring-boot-3-testcontainers/src/test/java/com/baeldung/testcontainers/DynamicPropertiesLiveTest.java index e8818c1019..2633f227d4 100644 --- a/spring-boot-modules/spring-boot-3-testcontainers/src/test/java/com/baeldung/testcontainers/DynamicPropertiesLiveTest.java +++ b/spring-boot-modules/spring-boot-3-testcontainers/src/test/java/com/baeldung/testcontainers/DynamicPropertiesLiveTest.java @@ -25,6 +25,8 @@ import com.baeldung.testcontainers.support.MiddleEarthCharactersRepository; @Testcontainers @SpringBootTest(webEnvironment = DEFINED_PORT) @DirtiesContext(classMode = AFTER_CLASS) +// Testcontainers require a valid docker installation. +// When running the tests, ensure you have a valid Docker environment class DynamicPropertiesLiveTest { @Container static MongoDBContainer mongoDBContainer = new MongoDBContainer(DockerImageName.parse("mongo:4.0.10")); diff --git a/spring-boot-modules/spring-boot-3-testcontainers/src/test/java/com/baeldung/testcontainers/LocalDevApplication.java b/spring-boot-modules/spring-boot-3-testcontainers/src/test/java/com/baeldung/testcontainers/LocalDevApplication.java index a94c0f772a..1b6fe32c97 100644 --- a/spring-boot-modules/spring-boot-3-testcontainers/src/test/java/com/baeldung/testcontainers/LocalDevApplication.java +++ b/spring-boot-modules/spring-boot-3-testcontainers/src/test/java/com/baeldung/testcontainers/LocalDevApplication.java @@ -8,6 +8,9 @@ import org.springframework.context.annotation.Bean; import org.testcontainers.containers.MongoDBContainer; import org.testcontainers.utility.DockerImageName; + +// Testcontainers require a valid docker installation. +// When running the app locally, ensure you have a valid Docker environment class LocalDevApplication { public static void main(String[] args) { diff --git a/spring-boot-modules/spring-boot-3-testcontainers/src/test/java/com/baeldung/testcontainers/ServiceConnectionLiveTest.java b/spring-boot-modules/spring-boot-3-testcontainers/src/test/java/com/baeldung/testcontainers/ServiceConnectionLiveTest.java index 838ee127f6..51b69c44b3 100644 --- a/spring-boot-modules/spring-boot-3-testcontainers/src/test/java/com/baeldung/testcontainers/ServiceConnectionLiveTest.java +++ b/spring-boot-modules/spring-boot-3-testcontainers/src/test/java/com/baeldung/testcontainers/ServiceConnectionLiveTest.java @@ -24,6 +24,8 @@ import com.baeldung.testcontainers.support.MiddleEarthCharactersRepository; @Testcontainers @SpringBootTest(webEnvironment = DEFINED_PORT) @DirtiesContext(classMode = AFTER_CLASS) +// Testcontainers require a valid docker installation. +// When running the tests, ensure you have a valid Docker environment class ServiceConnectionLiveTest { @Container From da7c711f25be5f77656cb6d0482ee0030dae08c3 Mon Sep 17 00:00:00 2001 From: panos-kakos Date: Sat, 16 Sep 2023 08:25:35 +0300 Subject: [PATCH 05/37] [JAVA-23452] Upgraded aws-miscellaneous module to latest version of sdk --- aws-modules/aws-miscellaneous/pom.xml | 32 +-- .../java/com/baeldung/ec2/EC2Application.java | 180 ++++++++------- .../java/com/baeldung/rds/AWSRDSService.java | 100 ++++----- .../java/com/baeldung/sqs/SQSApplication.java | 209 +++++++++++------- aws-modules/pom.xml | 1 + 5 files changed, 281 insertions(+), 241 deletions(-) diff --git a/aws-modules/aws-miscellaneous/pom.xml b/aws-modules/aws-miscellaneous/pom.xml index 2fb7e397a0..6e3eca9df2 100644 --- a/aws-modules/aws-miscellaneous/pom.xml +++ b/aws-modules/aws-miscellaneous/pom.xml @@ -16,31 +16,9 @@ - com.amazonaws - aws-java-sdk - ${aws-java-sdk.version} - - - com.amazonaws - aws-lambda-java-core - ${aws-lambda-java-core.version} - - - commons-logging - commons-logging - - - - - com.amazonaws - aws-lambda-java-events - ${aws-lambda-java-events.version} - - - commons-logging - commons-logging - - + software.amazon.awssdk + aws-sdk-java + ${aws-java-sdk-v2.version} commons-io @@ -101,10 +79,8 @@
- 1.3.0 - 1.1.0 2.8.0 - 1.21.1 + 2.0.0 1.10.L001 0.9.4.0006L 3.1.1 diff --git a/aws-modules/aws-miscellaneous/src/main/java/com/baeldung/ec2/EC2Application.java b/aws-modules/aws-miscellaneous/src/main/java/com/baeldung/ec2/EC2Application.java index 6755188fcd..ded7639e02 100644 --- a/aws-modules/aws-miscellaneous/src/main/java/com/baeldung/ec2/EC2Application.java +++ b/aws-modules/aws-miscellaneous/src/main/java/com/baeldung/ec2/EC2Application.java @@ -2,136 +2,150 @@ package com.baeldung.ec2; import java.util.Arrays; -import com.amazonaws.auth.AWSCredentials; -import com.amazonaws.auth.AWSStaticCredentialsProvider; -import com.amazonaws.auth.BasicAWSCredentials; -import com.amazonaws.regions.Regions; -import com.amazonaws.services.ec2.AmazonEC2; -import com.amazonaws.services.ec2.AmazonEC2ClientBuilder; -import com.amazonaws.services.ec2.model.AuthorizeSecurityGroupIngressRequest; -import com.amazonaws.services.ec2.model.CreateKeyPairRequest; -import com.amazonaws.services.ec2.model.CreateKeyPairResult; -import com.amazonaws.services.ec2.model.CreateSecurityGroupRequest; -import com.amazonaws.services.ec2.model.DescribeInstancesRequest; -import com.amazonaws.services.ec2.model.DescribeInstancesResult; -import com.amazonaws.services.ec2.model.DescribeKeyPairsRequest; -import com.amazonaws.services.ec2.model.DescribeKeyPairsResult; -import com.amazonaws.services.ec2.model.IpPermission; -import com.amazonaws.services.ec2.model.IpRange; -import com.amazonaws.services.ec2.model.MonitorInstancesRequest; -import com.amazonaws.services.ec2.model.RebootInstancesRequest; -import com.amazonaws.services.ec2.model.RunInstancesRequest; -import com.amazonaws.services.ec2.model.StartInstancesRequest; -import com.amazonaws.services.ec2.model.StopInstancesRequest; -import com.amazonaws.services.ec2.model.UnmonitorInstancesRequest; +import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.ec2.Ec2Client; +import software.amazon.awssdk.services.ec2.model.AuthorizeSecurityGroupIngressRequest; +import software.amazon.awssdk.services.ec2.model.CreateKeyPairRequest; +import software.amazon.awssdk.services.ec2.model.CreateKeyPairResponse; +import software.amazon.awssdk.services.ec2.model.CreateSecurityGroupRequest; +import software.amazon.awssdk.services.ec2.model.DescribeInstancesRequest; +import software.amazon.awssdk.services.ec2.model.DescribeInstancesResponse; +import software.amazon.awssdk.services.ec2.model.DescribeKeyPairsRequest; +import software.amazon.awssdk.services.ec2.model.DescribeKeyPairsResponse; +import software.amazon.awssdk.services.ec2.model.IpPermission; +import software.amazon.awssdk.services.ec2.model.IpRange; +import software.amazon.awssdk.services.ec2.model.MonitorInstancesRequest; +import software.amazon.awssdk.services.ec2.model.RebootInstancesRequest; +import software.amazon.awssdk.services.ec2.model.RunInstancesRequest; +import software.amazon.awssdk.services.ec2.model.RunInstancesResponse; +import software.amazon.awssdk.services.ec2.model.StartInstancesRequest; +import software.amazon.awssdk.services.ec2.model.StartInstancesResponse; +import software.amazon.awssdk.services.ec2.model.StopInstancesRequest; +import software.amazon.awssdk.services.ec2.model.UnmonitorInstancesRequest; public class EC2Application { - private static final AWSCredentials credentials; - - static { - // put your accesskey and secretkey here - credentials = new BasicAWSCredentials( - "", - "" - ); - } - public static void main(String[] args) { // Set up the client - AmazonEC2 ec2Client = AmazonEC2ClientBuilder.standard() - .withCredentials(new AWSStaticCredentialsProvider(credentials)) - .withRegion(Regions.US_EAST_1) + Ec2Client ec2Client = Ec2Client.builder() + .credentialsProvider(ProfileCredentialsProvider.create("default")) + .region(Region.US_EAST_1) .build(); // Create a security group - CreateSecurityGroupRequest createSecurityGroupRequest = new CreateSecurityGroupRequest().withGroupName("BaeldungSecurityGroup") - .withDescription("Baeldung Security Group"); + CreateSecurityGroupRequest createSecurityGroupRequest = CreateSecurityGroupRequest.builder() + .groupName("BaeldungSecurityGroup") + .description("Baeldung Security Group") + .build(); + ec2Client.createSecurityGroup(createSecurityGroupRequest); // Allow HTTP and SSH traffic - IpRange ipRange1 = new IpRange().withCidrIp("0.0.0.0/0"); + IpRange ipRange1 = IpRange.builder() + .cidrIp("0.0.0.0/0") + .build(); - IpPermission ipPermission1 = new IpPermission().withIpv4Ranges(Arrays.asList(new IpRange[] { ipRange1 })) - .withIpProtocol("tcp") - .withFromPort(80) - .withToPort(80); - IpPermission ipPermission2 = new IpPermission().withIpv4Ranges(Arrays.asList(new IpRange[] { ipRange1 })) - .withIpProtocol("tcp") - .withFromPort(22) - .withToPort(22); + IpPermission ipPermission1 = IpPermission.builder() + .ipRanges(Arrays.asList(ipRange1)) + .ipProtocol("tcp") + .fromPort(80) + .toPort(80) + .build(); - AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest = new AuthorizeSecurityGroupIngressRequest() - .withGroupName("BaeldungSecurityGroup") - .withIpPermissions(ipPermission1, ipPermission2); + IpPermission ipPermission2 = IpPermission.builder() + .ipRanges(Arrays.asList(ipRange1)) + .ipProtocol("tcp") + .fromPort(22) + .toPort(22) + .build(); + + AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest = AuthorizeSecurityGroupIngressRequest + .builder() + .groupName("BaeldungSecurityGroup") + .ipPermissions(ipPermission1, ipPermission2) + .build(); ec2Client.authorizeSecurityGroupIngress(authorizeSecurityGroupIngressRequest); // Create KeyPair - CreateKeyPairRequest createKeyPairRequest = new CreateKeyPairRequest() - .withKeyName("baeldung-key-pair"); - CreateKeyPairResult createKeyPairResult = ec2Client.createKeyPair(createKeyPairRequest); - String privateKey = createKeyPairResult - .getKeyPair() - .getKeyMaterial(); // make sure you keep it, the private key, Amazon doesn't store the private key + CreateKeyPairRequest createKeyPairRequest = CreateKeyPairRequest.builder() + .keyName("baeldung-key-pair") + .build(); + + CreateKeyPairResponse createKeyPairResponse = ec2Client.createKeyPair(createKeyPairRequest); + String privateKey = createKeyPairResponse.keyMaterial(); + // make sure you keep it, the private key, Amazon doesn't store the private key // See what key-pairs you've got - DescribeKeyPairsRequest describeKeyPairsRequest = new DescribeKeyPairsRequest(); - DescribeKeyPairsResult describeKeyPairsResult = ec2Client.describeKeyPairs(describeKeyPairsRequest); + DescribeKeyPairsRequest describeKeyPairsRequest = DescribeKeyPairsRequest.builder() + .build(); + DescribeKeyPairsResponse describeKeyPairsResponse = ec2Client.describeKeyPairs(describeKeyPairsRequest); // Launch an Amazon Instance - RunInstancesRequest runInstancesRequest = new RunInstancesRequest().withImageId("ami-97785bed") // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html | https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/usingsharedamis-finding.html - .withInstanceType("t2.micro") // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html - .withMinCount(1) - .withMaxCount(1) - .withKeyName("baeldung-key-pair") // optional - if not present, can't connect to instance - .withSecurityGroups("BaeldungSecurityGroup"); + RunInstancesRequest runInstancesRequest = RunInstancesRequest.builder() + .instanceType("t2.micro") // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html + .minCount(1) + .maxCount(1) + .keyName("baeldung-key-pair") // optional - if not present, can't connect to instance + .securityGroups("BaeldungSecurityGroup") + .build(); - String yourInstanceId = ec2Client.runInstances(runInstancesRequest).getReservation().getInstances().get(0).getInstanceId(); + RunInstancesResponse runInstancesResponse = ec2Client.runInstances(runInstancesRequest); + String yourInstanceId = runInstancesResponse.instances().get(0).instanceId(); // Start an Instance - StartInstancesRequest startInstancesRequest = new StartInstancesRequest() - .withInstanceIds(yourInstanceId); + StartInstancesRequest startInstancesRequest = StartInstancesRequest.builder() + .instanceIds(yourInstanceId) + .build(); + + StartInstancesResponse startInstancesResponse = ec2Client.startInstances(startInstancesRequest); - ec2Client.startInstances(startInstancesRequest); // Monitor Instances - MonitorInstancesRequest monitorInstancesRequest = new MonitorInstancesRequest() - .withInstanceIds(yourInstanceId); + MonitorInstancesRequest monitorInstancesRequest = MonitorInstancesRequest.builder() + .instanceIds(yourInstanceId) + .build(); + ec2Client.monitorInstances(monitorInstancesRequest); - UnmonitorInstancesRequest unmonitorInstancesRequest = new UnmonitorInstancesRequest() - .withInstanceIds(yourInstanceId); + UnmonitorInstancesRequest unmonitorInstancesRequest = UnmonitorInstancesRequest.builder() + .instanceIds(yourInstanceId) + .build(); ec2Client.unmonitorInstances(unmonitorInstancesRequest); // Reboot an Instance - RebootInstancesRequest rebootInstancesRequest = new RebootInstancesRequest() - .withInstanceIds(yourInstanceId); + RebootInstancesRequest rebootInstancesRequest = RebootInstancesRequest.builder() + .instanceIds(yourInstanceId) + .build(); + ec2Client.rebootInstances(rebootInstancesRequest); // Stop an Instance - StopInstancesRequest stopInstancesRequest = new StopInstancesRequest() - .withInstanceIds(yourInstanceId); + StopInstancesRequest stopInstancesRequest = StopInstancesRequest.builder() + .instanceIds(yourInstanceId) + .build(); + ec2Client.stopInstances(stopInstancesRequest) - .getStoppingInstances() + .stoppingInstances() .get(0) - .getPreviousState() - .getName(); + .previousState() + .name(); // Describe an Instance - DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest(); - DescribeInstancesResult response = ec2Client.describeInstances(describeInstancesRequest); - System.out.println(response.getReservations() + DescribeInstancesRequest describeInstancesRequest = DescribeInstancesRequest.builder().build(); + DescribeInstancesResponse response = ec2Client.describeInstances(describeInstancesRequest); + System.out.println(response.reservations() .get(0) - .getInstances() + .instances() .get(0) - .getKernelId()); + .kernelId()); } } diff --git a/aws-modules/aws-miscellaneous/src/main/java/com/baeldung/rds/AWSRDSService.java b/aws-modules/aws-miscellaneous/src/main/java/com/baeldung/rds/AWSRDSService.java index d4da92f30f..d17f2fc4b1 100644 --- a/aws-modules/aws-miscellaneous/src/main/java/com/baeldung/rds/AWSRDSService.java +++ b/aws-modules/aws-miscellaneous/src/main/java/com/baeldung/rds/AWSRDSService.java @@ -1,13 +1,5 @@ package com.baeldung.rds; -import com.amazonaws.auth.AWSCredentialsProvider; -import com.amazonaws.auth.AWSStaticCredentialsProvider; -import com.amazonaws.auth.BasicAWSCredentials; -import com.amazonaws.regions.Regions; -import com.amazonaws.services.rds.AmazonRDS; -import com.amazonaws.services.rds.AmazonRDSClientBuilder; -import com.amazonaws.services.rds.model.*; - import java.io.IOException; import java.io.InputStream; import java.sql.*; @@ -16,12 +8,22 @@ import java.util.Properties; import java.util.UUID; import java.util.logging.Logger; +import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.rds.RdsClient; +import software.amazon.awssdk.services.rds.model.CreateDbInstanceRequest; +import software.amazon.awssdk.services.rds.model.CreateDbInstanceResponse; +import software.amazon.awssdk.services.rds.model.DBInstance; +import software.amazon.awssdk.services.rds.model.DeleteDbInstanceRequest; +import software.amazon.awssdk.services.rds.model.DeleteDbInstanceResponse; +import software.amazon.awssdk.services.rds.model.DescribeDbInstancesResponse; +import software.amazon.awssdk.services.rds.model.Endpoint; + public class AWSRDSService { final static Logger logger = Logger.getLogger(AWSRDSService.class.getName()); - private AWSCredentialsProvider credentials; - private AmazonRDS amazonRDS; + private RdsClient rdsClient; private String db_username; private String db_password; private String db_database; @@ -34,22 +36,17 @@ public class AWSRDSService { * **/ public AWSRDSService() throws IOException { //Init RDS client with credentials and region. - credentials = new - AWSStaticCredentialsProvider(new - BasicAWSCredentials("", - "")); - amazonRDS = AmazonRDSClientBuilder.standard().withCredentials(credentials) - .withRegion(Regions.AP_SOUTHEAST_2).build(); Properties prop = new Properties(); InputStream input = AWSRDSService.class.getClassLoader().getResourceAsStream("db.properties"); prop.load(input); db_username = prop.getProperty("db_username"); db_password = prop.getProperty("db_password"); db_database = prop.getProperty("db_database"); - } - public AWSRDSService(AmazonRDS amazonRDS){ - this.amazonRDS = amazonRDS; + rdsClient = RdsClient.builder() + .region(Region.AP_SOUTHEAST_2) + .credentialsProvider(ProfileCredentialsProvider.create("default")) + .build(); } /** @@ -60,29 +57,29 @@ public class AWSRDSService { public String launchInstance() { String identifier = ""; - CreateDBInstanceRequest request = new CreateDBInstanceRequest(); - // RDS instance name - request.setDBInstanceIdentifier("Sydney"); - request.setEngine("postgres"); - request.setMultiAZ(false); - request.setMasterUsername(db_username); - request.setMasterUserPassword(db_password); - request.setDBName(db_database); - request.setStorageType("gp2"); - request.setAllocatedStorage(10); + CreateDbInstanceRequest instanceRequest = CreateDbInstanceRequest.builder() + .dbInstanceIdentifier("Sydney") + .engine("postgres") + .multiAZ(false) + .masterUsername(db_username) + .masterUserPassword(db_password) + .dbName(db_database) + .storageType("gp2") + .allocatedStorage(10) + .build(); - DBInstance instance = amazonRDS.createDBInstance(request); + CreateDbInstanceResponse createDbInstanceResponse = rdsClient.createDBInstance(instanceRequest); // Information about the new RDS instance - identifier = instance.getDBInstanceIdentifier(); - String status = instance.getDBInstanceStatus(); - Endpoint endpoint = instance.getEndpoint(); - String endpoint_url = "Endpoint URL not available yet."; + identifier = createDbInstanceResponse.dbInstance().dbInstanceIdentifier(); + String status = createDbInstanceResponse.dbInstance().dbInstanceStatus(); + Endpoint endpoint = createDbInstanceResponse.dbInstance().endpoint(); + String endpointUrl = "Endpoint URL not available yet."; if (endpoint != null) { - endpoint_url = endpoint.toString(); + endpointUrl = endpoint.toString(); } logger.info(identifier + "\t" + status); - logger.info(endpoint_url); + logger.info(endpointUrl); return identifier; @@ -90,20 +87,20 @@ public class AWSRDSService { // Describe DB instances public void listInstances() { - DescribeDBInstancesResult result = amazonRDS.describeDBInstances(); - List instances = result.getDBInstances(); + DescribeDbInstancesResponse response = rdsClient.describeDBInstances(); + List instances = response.dbInstances(); for (DBInstance instance : instances) { // Information about each RDS instance - String identifier = instance.getDBInstanceIdentifier(); - String engine = instance.getEngine(); - String status = instance.getDBInstanceStatus(); - Endpoint endpoint = instance.getEndpoint(); - String endpoint_url = "Endpoint URL not available yet."; + String identifier = instance.dbInstanceIdentifier(); + String engine = instance.engine(); + String status = instance.dbInstanceStatus(); + Endpoint endpoint = instance.endpoint(); + String endpointUrl = "Endpoint URL not available yet."; if (endpoint != null) { - endpoint_url = endpoint.toString(); + endpointUrl = endpoint.toString(); } logger.info(identifier + "\t" + engine + "\t" + status); - logger.info("\t" + endpoint_url); + logger.info("\t" + endpointUrl); } } @@ -111,16 +108,17 @@ public class AWSRDSService { //Delete RDS instance public void terminateInstance(String identifier) { - DeleteDBInstanceRequest request = new DeleteDBInstanceRequest(); - request.setDBInstanceIdentifier(identifier); - request.setSkipFinalSnapshot(true); + DeleteDbInstanceRequest request = DeleteDbInstanceRequest.builder() + .dbInstanceIdentifier(identifier) + .skipFinalSnapshot(true) + .build(); // Delete the RDS instance - DBInstance instance = amazonRDS.deleteDBInstance(request); + DeleteDbInstanceResponse response = rdsClient.deleteDBInstance(request); // Information about the RDS instance being deleted - String status = instance.getDBInstanceStatus(); - Endpoint endpoint = instance.getEndpoint(); + String status = response.dbInstance().dbInstanceStatus(); + Endpoint endpoint = response.dbInstance().endpoint(); String endpoint_url = "Endpoint URL not available yet."; if (endpoint != null) { endpoint_url = endpoint.toString(); diff --git a/aws-modules/aws-miscellaneous/src/main/java/com/baeldung/sqs/SQSApplication.java b/aws-modules/aws-miscellaneous/src/main/java/com/baeldung/sqs/SQSApplication.java index 978506a24f..fda7ec84fc 100644 --- a/aws-modules/aws-miscellaneous/src/main/java/com/baeldung/sqs/SQSApplication.java +++ b/aws-modules/aws-miscellaneous/src/main/java/com/baeldung/sqs/SQSApplication.java @@ -5,140 +5,191 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import com.amazonaws.auth.AWSCredentials; -import com.amazonaws.auth.AWSStaticCredentialsProvider; -import com.amazonaws.auth.BasicAWSCredentials; -import com.amazonaws.regions.Regions; -import com.amazonaws.services.sqs.AmazonSQSClientBuilder; -import com.amazonaws.services.sqs.model.CreateQueueRequest; -import com.amazonaws.services.sqs.model.DeleteMessageRequest; -import com.amazonaws.services.sqs.model.GetQueueAttributesRequest; -import com.amazonaws.services.sqs.model.GetQueueAttributesResult; -import com.amazonaws.services.sqs.model.MessageAttributeValue; -import com.amazonaws.services.sqs.model.ReceiveMessageRequest; -import com.amazonaws.services.sqs.model.SendMessageBatchRequest; -import com.amazonaws.services.sqs.model.SendMessageRequest; -import com.amazonaws.services.sqs.model.SetQueueAttributesRequest; -import com.amazonaws.services.sqs.model.SendMessageBatchRequestEntry; -import com.amazonaws.services.sqs.model.Message; -import com.amazonaws.services.sqs.AmazonSQS; +import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.sqs.SqsClient; +import software.amazon.awssdk.services.sqs.model.CreateQueueRequest; +import software.amazon.awssdk.services.sqs.model.DeleteMessageRequest; +import software.amazon.awssdk.services.sqs.model.GetQueueAttributesRequest; +import software.amazon.awssdk.services.sqs.model.GetQueueAttributesResponse; +import software.amazon.awssdk.services.sqs.model.GetQueueUrlRequest; +import software.amazon.awssdk.services.sqs.model.GetQueueUrlResponse; +import software.amazon.awssdk.services.sqs.model.Message; +import software.amazon.awssdk.services.sqs.model.MessageAttributeValue; +import software.amazon.awssdk.services.sqs.model.QueueAttributeName; +import software.amazon.awssdk.services.sqs.model.ReceiveMessageRequest; +import software.amazon.awssdk.services.sqs.model.SendMessageBatchRequest; +import software.amazon.awssdk.services.sqs.model.SendMessageBatchRequestEntry; +import software.amazon.awssdk.services.sqs.model.SendMessageRequest; +import software.amazon.awssdk.services.sqs.model.SetQueueAttributesRequest; public class SQSApplication { - private static final AWSCredentials credentials; + private static final String STANDARD_QUEUE_NAME = "baeldung-queue"; + private static final String FIFO_QUEUE_NAME = "baeldung-queue.fifo"; + private static final String DEAD_LETTER_QUEUE_NAME = "baeldung-dead-letter-queue"; - static { - // put your accesskey and secretkey here - credentials = new BasicAWSCredentials( - "", - "" - ); - } public static void main(String[] args) { // Set up the client - AmazonSQS sqs = AmazonSQSClientBuilder.standard() - .withCredentials(new AWSStaticCredentialsProvider(credentials)) - .withRegion(Regions.US_EAST_1) + SqsClient sqsClient = SqsClient.builder() + .region(Region.US_EAST_1) + .credentialsProvider(ProfileCredentialsProvider.create()) .build(); // Create a standard queue + CreateQueueRequest createStandardQueueRequest = CreateQueueRequest.builder() + .queueName(STANDARD_QUEUE_NAME) + .build(); - CreateQueueRequest createStandardQueueRequest = new CreateQueueRequest("baeldung-queue"); - String standardQueueUrl = sqs.createQueue(createStandardQueueRequest) - .getQueueUrl(); + sqsClient.createQueue(createStandardQueueRequest); + + System.out.println("\nGet queue url"); + + GetQueueUrlResponse getQueueUrlResponse = sqsClient.getQueueUrl(GetQueueUrlRequest + .builder() + .queueName(STANDARD_QUEUE_NAME) + .build() + ); + String standardQueueUrl = getQueueUrlResponse.queueUrl(); System.out.println(standardQueueUrl); // Create a fifo queue + Map queueAttributes = new HashMap<>(); + queueAttributes.put(QueueAttributeName.FIFO_QUEUE, "true"); + queueAttributes.put(QueueAttributeName.CONTENT_BASED_DEDUPLICATION, "true"); - Map queueAttributes = new HashMap(); - queueAttributes.put("FifoQueue", "true"); - queueAttributes.put("ContentBasedDeduplication", "true"); + CreateQueueRequest createFifoQueueRequest = CreateQueueRequest.builder() + .queueName(FIFO_QUEUE_NAME) + .attributes(queueAttributes) + .build(); - CreateQueueRequest createFifoQueueRequest = new CreateQueueRequest("baeldung-queue.fifo").withAttributes(queueAttributes); - String fifoQueueUrl = sqs.createQueue(createFifoQueueRequest) - .getQueueUrl(); + sqsClient.createQueue(createFifoQueueRequest); + + GetQueueUrlResponse getFifoQueueUrlResponse = sqsClient.getQueueUrl(GetQueueUrlRequest + .builder() + .queueName(FIFO_QUEUE_NAME) + .build()); + + String fifoQueueUrl = getFifoQueueUrlResponse.queueUrl(); System.out.println(fifoQueueUrl); // Set up a dead letter queue + CreateQueueRequest createDeadLetterQueueRequest = CreateQueueRequest.builder() + .queueName(DEAD_LETTER_QUEUE_NAME) + .build(); - String deadLetterQueueUrl = sqs.createQueue("baeldung-dead-letter-queue") - .getQueueUrl(); + String deadLetterQueueUrl = sqsClient.createQueue(createDeadLetterQueueRequest).queueUrl(); - GetQueueAttributesResult deadLetterQueueAttributes = sqs.getQueueAttributes(new GetQueueAttributesRequest(deadLetterQueueUrl).withAttributeNames("QueueArn")); + GetQueueAttributesRequest getQueueAttributesRequest = GetQueueAttributesRequest.builder() + .queueUrl(deadLetterQueueUrl) + .attributeNames(QueueAttributeName.QUEUE_ARN) + .build(); - String deadLetterQueueARN = deadLetterQueueAttributes.getAttributes() + GetQueueAttributesResponse deadLetterQueueAttributes = sqsClient.getQueueAttributes(getQueueAttributesRequest); + + String deadLetterQueueARN = deadLetterQueueAttributes.attributes() .get("QueueArn"); - SetQueueAttributesRequest queueAttributesRequest = new SetQueueAttributesRequest().withQueueUrl(standardQueueUrl) - .addAttributesEntry("RedrivePolicy", "{\"maxReceiveCount\":\"2\", " + "\"deadLetterTargetArn\":\"" + deadLetterQueueARN + "\"}"); + SetQueueAttributesRequest queueAttributesRequest = SetQueueAttributesRequest.builder() + .queueUrl(standardQueueUrl) + .attributes(null) + .build(); +// .addAttributesEntry("RedrivePolicy", "{\"maxReceiveCount\":\"2\", " + "\"deadLetterTargetArn\":\"" + deadLetterQueueARN + "\"}"); - sqs.setQueueAttributes(queueAttributesRequest); + sqsClient.setQueueAttributes(queueAttributesRequest); // Send a message to a standard queue Map messageAttributes = new HashMap<>(); + MessageAttributeValue messageAttributeValue = MessageAttributeValue.builder() + .stringValue("This is an attribute") + .dataType("String") + .build(); - messageAttributes.put("AttributeOne", new MessageAttributeValue().withStringValue("This is an attribute") - .withDataType("String")); + messageAttributes.put("AttributeOne", messageAttributeValue); - SendMessageRequest sendMessageStandardQueue = new SendMessageRequest().withQueueUrl(standardQueueUrl) - .withMessageBody("A simple message.") - .withDelaySeconds(30) // Message will arrive in the queue after 30 seconds. We can use this only in standard queues - .withMessageAttributes(messageAttributes); + SendMessageRequest sendMessageStandardQueue = SendMessageRequest.builder() + .queueUrl(standardQueueUrl) + .messageBody("A simple message.") + .delaySeconds(30) // Message will arrive in the queue after 30 seconds. We can use this only in standard queues + .messageAttributes(messageAttributes) + .build(); - sqs.sendMessage(sendMessageStandardQueue); + sqsClient.sendMessage(sendMessageStandardQueue); // Send a message to a fifo queue - SendMessageRequest sendMessageFifoQueue = new SendMessageRequest().withQueueUrl(fifoQueueUrl) - .withMessageBody("FIFO Queue") - .withMessageGroupId("baeldung-group-1") - .withMessageAttributes(messageAttributes); + SendMessageRequest sendMessageFifoQueue = SendMessageRequest.builder() + .queueUrl(fifoQueueUrl) + .messageBody("FIFO Queue") + .messageGroupId("baeldung-group-1") + .messageAttributes(messageAttributes) + .build(); - sqs.sendMessage(sendMessageFifoQueue); + sqsClient.sendMessage(sendMessageFifoQueue); // Send multiple messages List messageEntries = new ArrayList<>(); - messageEntries.add(new SendMessageBatchRequestEntry().withId("id-1") - .withMessageBody("batch-1") - .withMessageGroupId("baeldung-group-1")); - messageEntries.add(new SendMessageBatchRequestEntry().withId("id-2") - .withMessageBody("batch-2") - .withMessageGroupId("baeldung-group-1")); + SendMessageBatchRequestEntry messageBatchRequestEntry1 = SendMessageBatchRequestEntry.builder() + .id("id-1") + .messageBody("batch-1") + .messageGroupId("baeldung-group-1") + .build(); - SendMessageBatchRequest sendMessageBatchRequest = new SendMessageBatchRequest(fifoQueueUrl, messageEntries); - sqs.sendMessageBatch(sendMessageBatchRequest); + SendMessageBatchRequestEntry messageBatchRequestEntry2 = SendMessageBatchRequestEntry.builder() + .id("id-2") + .messageBody("batch-2") + .messageGroupId("baeldung-group-1") + .build(); + + messageEntries.add(messageBatchRequestEntry1); + messageEntries.add(messageBatchRequestEntry2); + + SendMessageBatchRequest sendMessageBatchRequest = SendMessageBatchRequest.builder() + .queueUrl(fifoQueueUrl) + .entries(messageEntries) + .build(); + + sqsClient.sendMessageBatch(sendMessageBatchRequest); // Read a message from a queue - ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(fifoQueueUrl).withWaitTimeSeconds(10) // Long polling; - .withMaxNumberOfMessages(1); // Max is 10 + ReceiveMessageRequest receiveMessageRequest = ReceiveMessageRequest.builder() + .waitTimeSeconds(10) + .maxNumberOfMessages(1) + .build(); - List sqsMessages = sqs.receiveMessage(receiveMessageRequest) - .getMessages(); - sqsMessages.get(0) - .getAttributes(); - sqsMessages.get(0) - .getBody(); + List sqsMessages = sqsClient.receiveMessage(receiveMessageRequest) + .messages(); + + + sqsMessages.get(0).attributes(); + sqsMessages.get(0).body(); // Delete a message from a queue + DeleteMessageRequest deleteMessageRequest = DeleteMessageRequest.builder() + .queueUrl(fifoQueueUrl) + .receiptHandle(sqsMessages.get(0).receiptHandle()) + .build(); - sqs.deleteMessage(new DeleteMessageRequest().withQueueUrl(fifoQueueUrl) - .withReceiptHandle(sqsMessages.get(0) - .getReceiptHandle())); + sqsClient.deleteMessage(deleteMessageRequest); // Monitoring - GetQueueAttributesRequest getQueueAttributesRequest = new GetQueueAttributesRequest(standardQueueUrl).withAttributeNames("All"); - GetQueueAttributesResult getQueueAttributesResult = sqs.getQueueAttributes(getQueueAttributesRequest); - System.out.println(String.format("The number of messages on the queue: %s", getQueueAttributesResult.getAttributes() + GetQueueAttributesRequest getQueueAttributesRequestForMonitoring = GetQueueAttributesRequest.builder() + .queueUrl(standardQueueUrl) + .build(); + + + GetQueueAttributesResponse attributesResponse = sqsClient.getQueueAttributes(getQueueAttributesRequestForMonitoring); + System.out.println(String.format("The number of messages on the queue: %s", attributesResponse.attributes() .get("ApproximateNumberOfMessages"))); - System.out.println(String.format("The number of messages in flight: %s", getQueueAttributesResult.getAttributes() + System.out.println(String.format("The number of messages in flight: %s", attributesResponse.attributes() .get("ApproximateNumberOfMessagesNotVisible"))); } diff --git a/aws-modules/pom.xml b/aws-modules/pom.xml index b94faafa86..fa16e22c3a 100644 --- a/aws-modules/pom.xml +++ b/aws-modules/pom.xml @@ -24,6 +24,7 @@ 1.12.331 + 2.20.147 3.0.0 From 4ce8b0e70a341783254dcbb718841742f4b47409 Mon Sep 17 00:00:00 2001 From: mcasari Date: Tue, 19 Sep 2023 21:53:05 +0200 Subject: [PATCH 06/37] Test cases for float to BigDecimal conversion - first commit --- convert-float-to-bigdecimal/README.md | 7 +++ convert-float-to-bigdecimal/pom.xml | 16 +++++++ .../src/main/resources/logback.xml | 14 ++++++ .../ConvertFloatToBigDecimalUnitTest.java | 48 +++++++++++++++++++ 4 files changed, 85 insertions(+) create mode 100644 convert-float-to-bigdecimal/README.md create mode 100644 convert-float-to-bigdecimal/pom.xml create mode 100644 convert-float-to-bigdecimal/src/main/resources/logback.xml create mode 100644 convert-float-to-bigdecimal/src/test/java/com/baeldung/convertfloattobigdecimal/ConvertFloatToBigDecimalUnitTest.java diff --git a/convert-float-to-bigdecimal/README.md b/convert-float-to-bigdecimal/README.md new file mode 100644 index 0000000000..e01c981831 --- /dev/null +++ b/convert-float-to-bigdecimal/README.md @@ -0,0 +1,7 @@ +## Shallow vs Deep Copy + +This module contains an article about converting float to BigDecimal in Java + +### Relevant articles: + +- [Converting from Float to BigDecimal in Java](https://drafts.baeldung.com/?p=175240&preview=true) diff --git a/convert-float-to-bigdecimal/pom.xml b/convert-float-to-bigdecimal/pom.xml new file mode 100644 index 0000000000..8fa20b300f --- /dev/null +++ b/convert-float-to-bigdecimal/pom.xml @@ -0,0 +1,16 @@ + + + 4.0.0 + convert-float-to-bigdecimal + convert-float-to-bigdecimal + jar + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + \ No newline at end of file diff --git a/convert-float-to-bigdecimal/src/main/resources/logback.xml b/convert-float-to-bigdecimal/src/main/resources/logback.xml new file mode 100644 index 0000000000..830ab22727 --- /dev/null +++ b/convert-float-to-bigdecimal/src/main/resources/logback.xml @@ -0,0 +1,14 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/convert-float-to-bigdecimal/src/test/java/com/baeldung/convertfloattobigdecimal/ConvertFloatToBigDecimalUnitTest.java b/convert-float-to-bigdecimal/src/test/java/com/baeldung/convertfloattobigdecimal/ConvertFloatToBigDecimalUnitTest.java new file mode 100644 index 0000000000..c43d2ab87a --- /dev/null +++ b/convert-float-to-bigdecimal/src/test/java/com/baeldung/convertfloattobigdecimal/ConvertFloatToBigDecimalUnitTest.java @@ -0,0 +1,48 @@ +package com.baeldung.convertfloattobigdecimal; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +import java.math.BigDecimal; + +import org.junit.jupiter.api.Test; + +class ConvertFloatToBigDecimalUnitTest { + + @Test + public void whenFloatComparedWithDifferentValues_thenCouldMatch() { + assertNotEquals(1.1f, 1.09f); + assertEquals(1.1f, 1.09999999f); + } + + @Test + public void whenCreatedFromFloat_thenCouldNotMatch() { + float floatToConvert = 0.5f; + BigDecimal bdFromFloat = new BigDecimal(floatToConvert); + assertEquals("0.5", bdFromFloat.toString()); + floatToConvert = 1.1f; + bdFromFloat = new BigDecimal(floatToConvert); + assertNotEquals("1.1", bdFromFloat.toString()); + } + + @Test + public void whenCreatedFromString_thenMatches() { + String floatValue = Float.toString(1.1f); + BigDecimal bdFromString = new BigDecimal(floatValue); + assertEquals("1.1", bdFromString.toString()); + } + + @Test + public void whenCreatedByValueOfAndIsFloat_thenDoesNotMatch() { + float floatToConvert = 1.1f; + BigDecimal bdByValueOf = BigDecimal.valueOf(floatToConvert); + assertNotEquals("1.1", bdByValueOf.toString()); + } + + @Test + public void whenCreatedByValueOfAndIsDouble_thenMatches() { + double doubleToConvert = 1.1d; + BigDecimal bdByValueOf = BigDecimal.valueOf(doubleToConvert); + assertEquals("1.1", bdByValueOf.toString()); + } +} From a7940d9658d262bf3671c99753b2d4ab8eead674 Mon Sep 17 00:00:00 2001 From: mcasari Date: Thu, 21 Sep 2023 20:28:15 +0200 Subject: [PATCH 07/37] BAEL-6846 - Convert from float to BigDecimal --- convert-float-to-bigdecimal/README.md | 7 ----- convert-float-to-bigdecimal/pom.xml | 16 ---------- .../src/main/resources/logback.xml | 14 --------- .../FloatToBigDecimalUnitTest.java | 24 ++++++++++---- shallow-deep-copy/README.md | 7 ----- shallow-deep-copy/pom.xml | 16 ---------- .../baeldung/shallowdeepcopy/Dependency.java | 23 -------------- .../com/baeldung/shallowdeepcopy/Main.java | 31 ------------------- .../src/main/resources/logback.xml | 14 --------- .../ShallowDeepCopyUnitTest.java | 28 ----------------- 10 files changed, 18 insertions(+), 162 deletions(-) delete mode 100644 convert-float-to-bigdecimal/README.md delete mode 100644 convert-float-to-bigdecimal/pom.xml delete mode 100644 convert-float-to-bigdecimal/src/main/resources/logback.xml rename convert-float-to-bigdecimal/src/test/java/com/baeldung/convertfloattobigdecimal/ConvertFloatToBigDecimalUnitTest.java => core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/floattobigdecimal/FloatToBigDecimalUnitTest.java (69%) delete mode 100644 shallow-deep-copy/README.md delete mode 100644 shallow-deep-copy/pom.xml delete mode 100644 shallow-deep-copy/src/main/java/com/baeldung/shallowdeepcopy/Dependency.java delete mode 100644 shallow-deep-copy/src/main/java/com/baeldung/shallowdeepcopy/Main.java delete mode 100644 shallow-deep-copy/src/main/resources/logback.xml delete mode 100644 shallow-deep-copy/src/test/java/com/baeldung/shallowdeepcopy/ShallowDeepCopyUnitTest.java diff --git a/convert-float-to-bigdecimal/README.md b/convert-float-to-bigdecimal/README.md deleted file mode 100644 index e01c981831..0000000000 --- a/convert-float-to-bigdecimal/README.md +++ /dev/null @@ -1,7 +0,0 @@ -## Shallow vs Deep Copy - -This module contains an article about converting float to BigDecimal in Java - -### Relevant articles: - -- [Converting from Float to BigDecimal in Java](https://drafts.baeldung.com/?p=175240&preview=true) diff --git a/convert-float-to-bigdecimal/pom.xml b/convert-float-to-bigdecimal/pom.xml deleted file mode 100644 index 8fa20b300f..0000000000 --- a/convert-float-to-bigdecimal/pom.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - 4.0.0 - convert-float-to-bigdecimal - convert-float-to-bigdecimal - jar - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - \ No newline at end of file diff --git a/convert-float-to-bigdecimal/src/main/resources/logback.xml b/convert-float-to-bigdecimal/src/main/resources/logback.xml deleted file mode 100644 index 830ab22727..0000000000 --- a/convert-float-to-bigdecimal/src/main/resources/logback.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file diff --git a/convert-float-to-bigdecimal/src/test/java/com/baeldung/convertfloattobigdecimal/ConvertFloatToBigDecimalUnitTest.java b/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/floattobigdecimal/FloatToBigDecimalUnitTest.java similarity index 69% rename from convert-float-to-bigdecimal/src/test/java/com/baeldung/convertfloattobigdecimal/ConvertFloatToBigDecimalUnitTest.java rename to core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/floattobigdecimal/FloatToBigDecimalUnitTest.java index c43d2ab87a..20422edbd7 100644 --- a/convert-float-to-bigdecimal/src/test/java/com/baeldung/convertfloattobigdecimal/ConvertFloatToBigDecimalUnitTest.java +++ b/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/floattobigdecimal/FloatToBigDecimalUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.convertfloattobigdecimal; +package com.baeldung.floattobigdecimal; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; @@ -7,7 +7,7 @@ import java.math.BigDecimal; import org.junit.jupiter.api.Test; -class ConvertFloatToBigDecimalUnitTest { +class FloatToBigDecimalUnitTest { @Test public void whenFloatComparedWithDifferentValues_thenCouldMatch() { @@ -16,12 +16,16 @@ class ConvertFloatToBigDecimalUnitTest { } @Test - public void whenCreatedFromFloat_thenCouldNotMatch() { + public void whenCreatedFromCertainFloatValues_thenMatches() { float floatToConvert = 0.5f; BigDecimal bdFromFloat = new BigDecimal(floatToConvert); assertEquals("0.5", bdFromFloat.toString()); - floatToConvert = 1.1f; - bdFromFloat = new BigDecimal(floatToConvert); + } + + @Test + public void whenCreatedFromCertainFloatValues_thenDoesNotMatch() { + float floatToConvert = 1.1f; + BigDecimal bdFromFloat = new BigDecimal(floatToConvert); assertNotEquals("1.1", bdFromFloat.toString()); } @@ -39,10 +43,18 @@ class ConvertFloatToBigDecimalUnitTest { assertNotEquals("1.1", bdByValueOf.toString()); } + @Test + public void whenFloatCastToDouble_thenGotADifferentNumber() { + float floatToConvert = 1.1f; + double doubleCast = floatToConvert; + assertEquals("1.100000023841858", Double.toString(doubleCast)); + } + @Test public void whenCreatedByValueOfAndIsDouble_thenMatches() { double doubleToConvert = 1.1d; BigDecimal bdByValueOf = BigDecimal.valueOf(doubleToConvert); assertEquals("1.1", bdByValueOf.toString()); } -} + +} \ No newline at end of file diff --git a/shallow-deep-copy/README.md b/shallow-deep-copy/README.md deleted file mode 100644 index e1a426a138..0000000000 --- a/shallow-deep-copy/README.md +++ /dev/null @@ -1,7 +0,0 @@ -## Shallow vs Deep Copy - -This module contains an article about shallow vs deep copy of Java objects - -### Relevant articles: - -- [Creating a deep vs shallow copy of an object in Java](https://drafts.baeldung.com/?p=172294&preview=true) diff --git a/shallow-deep-copy/pom.xml b/shallow-deep-copy/pom.xml deleted file mode 100644 index 323f720df3..0000000000 --- a/shallow-deep-copy/pom.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - 4.0.0 - shallow-deep-copy - shallow-deep-copy - jar - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - \ No newline at end of file diff --git a/shallow-deep-copy/src/main/java/com/baeldung/shallowdeepcopy/Dependency.java b/shallow-deep-copy/src/main/java/com/baeldung/shallowdeepcopy/Dependency.java deleted file mode 100644 index 2550acd268..0000000000 --- a/shallow-deep-copy/src/main/java/com/baeldung/shallowdeepcopy/Dependency.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.baeldung.shallowdeepcopy; - -public class Dependency implements Cloneable { - private int value = 13; - - public Dependency(int value) { - super(); - this.value = value; - } - - public int getValue() { - return value; - } - - public void setValue(int value) { - this.value = value; - } - - @Override - protected Object clone() throws CloneNotSupportedException { - return super.clone(); - } -} diff --git a/shallow-deep-copy/src/main/java/com/baeldung/shallowdeepcopy/Main.java b/shallow-deep-copy/src/main/java/com/baeldung/shallowdeepcopy/Main.java deleted file mode 100644 index 33d565bb10..0000000000 --- a/shallow-deep-copy/src/main/java/com/baeldung/shallowdeepcopy/Main.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.baeldung.shallowdeepcopy; - -public class Main implements Cloneable { - private Dependency dependency; - - public Main(Dependency dependency) { - super(); - this.dependency = dependency; - } - - @Override - public Object clone() throws CloneNotSupportedException { - return super.clone(); - } - - public Object deepClone() throws CloneNotSupportedException { - Main dependentClone = (Main) super.clone(); - Dependency dependencyClone = (Dependency) this.dependency.clone(); - dependentClone.setDependency(dependencyClone); - return dependentClone; - } - - public Dependency getDependency() { - return dependency; - } - - public void setDependency(Dependency dependency) { - this.dependency = dependency; - } - -} diff --git a/shallow-deep-copy/src/main/resources/logback.xml b/shallow-deep-copy/src/main/resources/logback.xml deleted file mode 100644 index 830ab22727..0000000000 --- a/shallow-deep-copy/src/main/resources/logback.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file diff --git a/shallow-deep-copy/src/test/java/com/baeldung/shallowdeepcopy/ShallowDeepCopyUnitTest.java b/shallow-deep-copy/src/test/java/com/baeldung/shallowdeepcopy/ShallowDeepCopyUnitTest.java deleted file mode 100644 index f75bbc040b..0000000000 --- a/shallow-deep-copy/src/test/java/com/baeldung/shallowdeepcopy/ShallowDeepCopyUnitTest.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.baeldung.shallowdeepcopy; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.junit.jupiter.api.Test; - -class ShallowDeepCopyUnitTest { - - @Test - public void givenAnObjectAndADependency_whenShallowClonedAndDepencyChanges_ThenDepencyHasNewValue() throws Exception { - Dependency dependency = new Dependency(13); - Main main = new Main(dependency); - Main shallowClone = (Main) main.clone(); - dependency.setValue(17); - assertEquals(17, shallowClone.getDependency() - .getValue()); - } - - @Test - public void givenAnObjectAndADependency_whenDeepClonedAndDepencyChanges_ThenDepencyKeepsOldValue() throws Exception { - Dependency dependency = new Dependency(13); - Main main = new Main(dependency); - Main deepClone = (Main) main.deepClone(); - dependency.setValue(17); - assertEquals(13, deepClone.getDependency() - .getValue()); - } -} From c56bc04f95f7b9c9929d32f5c02ee359d8535265 Mon Sep 17 00:00:00 2001 From: mcasari Date: Sat, 23 Sep 2023 17:02:20 +0200 Subject: [PATCH 08/37] BAEL-6846 - change assertNotEquals to assertEquals --- .../baeldung/floattobigdecimal/FloatToBigDecimalUnitTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/floattobigdecimal/FloatToBigDecimalUnitTest.java b/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/floattobigdecimal/FloatToBigDecimalUnitTest.java index 20422edbd7..2d6d1ab5d0 100644 --- a/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/floattobigdecimal/FloatToBigDecimalUnitTest.java +++ b/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/floattobigdecimal/FloatToBigDecimalUnitTest.java @@ -26,7 +26,7 @@ class FloatToBigDecimalUnitTest { public void whenCreatedFromCertainFloatValues_thenDoesNotMatch() { float floatToConvert = 1.1f; BigDecimal bdFromFloat = new BigDecimal(floatToConvert); - assertNotEquals("1.1", bdFromFloat.toString()); + assertEquals("1.10000002384185791015625", bdFromFloat.toString()); } @Test @@ -40,7 +40,7 @@ class FloatToBigDecimalUnitTest { public void whenCreatedByValueOfAndIsFloat_thenDoesNotMatch() { float floatToConvert = 1.1f; BigDecimal bdByValueOf = BigDecimal.valueOf(floatToConvert); - assertNotEquals("1.1", bdByValueOf.toString()); + assertEquals("1.100000023841858", bdByValueOf.toString()); } @Test From 8a7e667f0dafedea14bf93572c5508823fe80f0d Mon Sep 17 00:00:00 2001 From: panos-kakos Date: Sat, 23 Sep 2023 18:49:37 +0300 Subject: [PATCH 09/37] [JAVA-23452] Clean up --- aws-modules/aws-miscellaneous/pom.xml | 7 +++- .../java/com/baeldung/ec2/EC2Application.java | 4 +- .../java/com/baeldung/rds/AWSRDSService.java | 7 ++-- .../java/com/baeldung/sqs/SQSApplication.java | 37 +++++++++---------- 4 files changed, 28 insertions(+), 27 deletions(-) diff --git a/aws-modules/aws-miscellaneous/pom.xml b/aws-modules/aws-miscellaneous/pom.xml index 6e3eca9df2..e582ee6e4d 100644 --- a/aws-modules/aws-miscellaneous/pom.xml +++ b/aws-modules/aws-miscellaneous/pom.xml @@ -36,6 +36,11 @@ ${dynamodblocal.version} test + + com.amazonaws + aws-java-sdk-dynamodb + ${aws-java-sdk.version} + @@ -80,7 +85,7 @@ 2.8.0 - 2.0.0 + 1.21.1 1.10.L001 0.9.4.0006L 3.1.1 diff --git a/aws-modules/aws-miscellaneous/src/main/java/com/baeldung/ec2/EC2Application.java b/aws-modules/aws-miscellaneous/src/main/java/com/baeldung/ec2/EC2Application.java index ded7639e02..e12a38e1de 100644 --- a/aws-modules/aws-miscellaneous/src/main/java/com/baeldung/ec2/EC2Application.java +++ b/aws-modules/aws-miscellaneous/src/main/java/com/baeldung/ec2/EC2Application.java @@ -47,7 +47,6 @@ public class EC2Application { .cidrIp("0.0.0.0/0") .build(); - IpPermission ipPermission1 = IpPermission.builder() .ipRanges(Arrays.asList(ipRange1)) .ipProtocol("tcp") @@ -86,6 +85,7 @@ public class EC2Application { // Launch an Amazon Instance RunInstancesRequest runInstancesRequest = RunInstancesRequest.builder() + .imageId("ami-97785bed") .instanceType("t2.micro") // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html .minCount(1) .maxCount(1) @@ -119,12 +119,10 @@ public class EC2Application { ec2Client.unmonitorInstances(unmonitorInstancesRequest); // Reboot an Instance - RebootInstancesRequest rebootInstancesRequest = RebootInstancesRequest.builder() .instanceIds(yourInstanceId) .build(); - ec2Client.rebootInstances(rebootInstancesRequest); // Stop an Instance diff --git a/aws-modules/aws-miscellaneous/src/main/java/com/baeldung/rds/AWSRDSService.java b/aws-modules/aws-miscellaneous/src/main/java/com/baeldung/rds/AWSRDSService.java index d17f2fc4b1..09309b92bb 100644 --- a/aws-modules/aws-miscellaneous/src/main/java/com/baeldung/rds/AWSRDSService.java +++ b/aws-modules/aws-miscellaneous/src/main/java/com/baeldung/rds/AWSRDSService.java @@ -102,7 +102,6 @@ public class AWSRDSService { logger.info(identifier + "\t" + engine + "\t" + status); logger.info("\t" + endpointUrl); } - } //Delete RDS instance @@ -119,13 +118,13 @@ public class AWSRDSService { // Information about the RDS instance being deleted String status = response.dbInstance().dbInstanceStatus(); Endpoint endpoint = response.dbInstance().endpoint(); - String endpoint_url = "Endpoint URL not available yet."; + String endpointUrl = "Endpoint URL not available yet."; if (endpoint != null) { - endpoint_url = endpoint.toString(); + endpointUrl = endpoint.toString(); } logger.info(identifier + "\t" + status); - logger.info(endpoint_url); + logger.info(endpointUrl); } diff --git a/aws-modules/aws-miscellaneous/src/main/java/com/baeldung/sqs/SQSApplication.java b/aws-modules/aws-miscellaneous/src/main/java/com/baeldung/sqs/SQSApplication.java index fda7ec84fc..3b78d73f60 100644 --- a/aws-modules/aws-miscellaneous/src/main/java/com/baeldung/sqs/SQSApplication.java +++ b/aws-modules/aws-miscellaneous/src/main/java/com/baeldung/sqs/SQSApplication.java @@ -29,7 +29,6 @@ public class SQSApplication { private static final String FIFO_QUEUE_NAME = "baeldung-queue.fifo"; private static final String DEAD_LETTER_QUEUE_NAME = "baeldung-dead-letter-queue"; - public static void main(String[] args) { // Set up the client @@ -47,12 +46,10 @@ public class SQSApplication { System.out.println("\nGet queue url"); - GetQueueUrlResponse getQueueUrlResponse = sqsClient.getQueueUrl(GetQueueUrlRequest - .builder() + GetQueueUrlResponse getQueueUrlResponse = sqsClient.getQueueUrl(GetQueueUrlRequest.builder() .queueName(STANDARD_QUEUE_NAME) - .build() - ); - String standardQueueUrl = getQueueUrlResponse.queueUrl(); + .build()); + String standardQueueUrl = getQueueUrlResponse.queueUrl(); System.out.println(standardQueueUrl); @@ -68,12 +65,11 @@ public class SQSApplication { sqsClient.createQueue(createFifoQueueRequest); - GetQueueUrlResponse getFifoQueueUrlResponse = sqsClient.getQueueUrl(GetQueueUrlRequest - .builder() + GetQueueUrlResponse getFifoQueueUrlResponse = sqsClient.getQueueUrl(GetQueueUrlRequest.builder() .queueName(FIFO_QUEUE_NAME) .build()); - String fifoQueueUrl = getFifoQueueUrlResponse.queueUrl(); + String fifoQueueUrl = getFifoQueueUrlResponse.queueUrl(); System.out.println(fifoQueueUrl); @@ -82,7 +78,8 @@ public class SQSApplication { .queueName(DEAD_LETTER_QUEUE_NAME) .build(); - String deadLetterQueueUrl = sqsClient.createQueue(createDeadLetterQueueRequest).queueUrl(); + String deadLetterQueueUrl = sqsClient.createQueue(createDeadLetterQueueRequest) + .queueUrl(); GetQueueAttributesRequest getQueueAttributesRequest = GetQueueAttributesRequest.builder() .queueUrl(deadLetterQueueUrl) @@ -94,11 +91,13 @@ public class SQSApplication { String deadLetterQueueARN = deadLetterQueueAttributes.attributes() .get("QueueArn"); + Map attributes = new HashMap<>(); + attributes.put(QueueAttributeName.REDRIVE_POLICY, "{\"maxReceiveCount\":\"5\", \"deadLetterTargetArn\":\"" + deadLetterQueueARN + "\"}"); + SetQueueAttributesRequest queueAttributesRequest = SetQueueAttributesRequest.builder() .queueUrl(standardQueueUrl) - .attributes(null) + .attributes(attributes) .build(); -// .addAttributesEntry("RedrivePolicy", "{\"maxReceiveCount\":\"2\", " + "\"deadLetterTargetArn\":\"" + deadLetterQueueARN + "\"}"); sqsClient.setQueueAttributes(queueAttributesRequest); @@ -161,21 +160,22 @@ public class SQSApplication { ReceiveMessageRequest receiveMessageRequest = ReceiveMessageRequest.builder() .waitTimeSeconds(10) - .maxNumberOfMessages(1) + .maxNumberOfMessages(10) .build(); - List sqsMessages = sqsClient.receiveMessage(receiveMessageRequest) .messages(); - - sqsMessages.get(0).attributes(); - sqsMessages.get(0).body(); + sqsMessages.get(0) + .attributes(); + sqsMessages.get(0) + .body(); // Delete a message from a queue DeleteMessageRequest deleteMessageRequest = DeleteMessageRequest.builder() .queueUrl(fifoQueueUrl) - .receiptHandle(sqsMessages.get(0).receiptHandle()) + .receiptHandle(sqsMessages.get(0) + .receiptHandle()) .build(); sqsClient.deleteMessage(deleteMessageRequest); @@ -185,7 +185,6 @@ public class SQSApplication { .queueUrl(standardQueueUrl) .build(); - GetQueueAttributesResponse attributesResponse = sqsClient.getQueueAttributes(getQueueAttributesRequestForMonitoring); System.out.println(String.format("The number of messages on the queue: %s", attributesResponse.attributes() .get("ApproximateNumberOfMessages"))); From a4aa3a69b7207f076b55aa6df27dc29b33dc7ee7 Mon Sep 17 00:00:00 2001 From: panos-kakos Date: Tue, 26 Sep 2023 08:42:23 +0300 Subject: [PATCH 10/37] [JAVA-25490] Package renaming --- .../com/baeldung/config/scope/AppConfigFunctionBean.java | 2 +- .../src/main/java/com/baeldung/scope/AppConfig.java | 8 ++++---- .../main/java/com/baeldung/scope/AppProxyScopeConfig.java | 2 +- .../java/com/baeldung/scope/BeanInjectionStarter.java | 2 +- .../SingletonAppContextBean.java | 2 +- .../scope/{singletone => singleton}/SingletonBean.java | 2 +- .../{singletone => singleton}/SingletonFunctionBean.java | 2 +- .../{singletone => singleton}/SingletonLookupBean.java | 2 +- .../SingletonObjectFactoryBean.java | 2 +- .../{singletone => singleton}/SingletonProviderBean.java | 2 +- .../scope/PrototypeBeanInjectionIntegrationTest.java | 7 +++---- .../scope/PrototypeFunctionBeanIntegrationTest.java | 2 +- 12 files changed, 17 insertions(+), 18 deletions(-) rename spring-core/src/main/java/com/baeldung/scope/{singletone => singleton}/SingletonAppContextBean.java (94%) rename spring-core/src/main/java/com/baeldung/scope/{singletone => singleton}/SingletonBean.java (93%) rename spring-core/src/main/java/com/baeldung/scope/{singletone => singleton}/SingletonFunctionBean.java (91%) rename spring-core/src/main/java/com/baeldung/scope/{singletone => singleton}/SingletonLookupBean.java (88%) rename spring-core/src/main/java/com/baeldung/scope/{singletone => singleton}/SingletonObjectFactoryBean.java (91%) rename spring-core/src/main/java/com/baeldung/scope/{singletone => singleton}/SingletonProviderBean.java (90%) diff --git a/spring-core/src/main/java/com/baeldung/config/scope/AppConfigFunctionBean.java b/spring-core/src/main/java/com/baeldung/config/scope/AppConfigFunctionBean.java index a3c5445698..aa526b5403 100644 --- a/spring-core/src/main/java/com/baeldung/config/scope/AppConfigFunctionBean.java +++ b/spring-core/src/main/java/com/baeldung/config/scope/AppConfigFunctionBean.java @@ -7,7 +7,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Scope; import com.baeldung.scope.prototype.PrototypeBean; -import com.baeldung.scope.singletone.SingletonFunctionBean; +import com.baeldung.scope.singleton.SingletonFunctionBean; @Configuration public class AppConfigFunctionBean { diff --git a/spring-core/src/main/java/com/baeldung/scope/AppConfig.java b/spring-core/src/main/java/com/baeldung/scope/AppConfig.java index 33a9c5c21e..2ef775ee4f 100644 --- a/spring-core/src/main/java/com/baeldung/scope/AppConfig.java +++ b/spring-core/src/main/java/com/baeldung/scope/AppConfig.java @@ -1,10 +1,10 @@ package com.baeldung.scope; import com.baeldung.scope.prototype.PrototypeBean; -import com.baeldung.scope.singletone.SingletonAppContextBean; -import com.baeldung.scope.singletone.SingletonBean; -import com.baeldung.scope.singletone.SingletonObjectFactoryBean; -import com.baeldung.scope.singletone.SingletonProviderBean; +import com.baeldung.scope.singleton.SingletonAppContextBean; +import com.baeldung.scope.singleton.SingletonBean; +import com.baeldung.scope.singleton.SingletonObjectFactoryBean; +import com.baeldung.scope.singleton.SingletonProviderBean; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; diff --git a/spring-core/src/main/java/com/baeldung/scope/AppProxyScopeConfig.java b/spring-core/src/main/java/com/baeldung/scope/AppProxyScopeConfig.java index 9f1874375e..0564dfb3c0 100644 --- a/spring-core/src/main/java/com/baeldung/scope/AppProxyScopeConfig.java +++ b/spring-core/src/main/java/com/baeldung/scope/AppProxyScopeConfig.java @@ -1,7 +1,7 @@ package com.baeldung.scope; import com.baeldung.scope.prototype.PrototypeBean; -import com.baeldung.scope.singletone.SingletonBean; +import com.baeldung.scope.singleton.SingletonBean; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.context.annotation.*; diff --git a/spring-core/src/main/java/com/baeldung/scope/BeanInjectionStarter.java b/spring-core/src/main/java/com/baeldung/scope/BeanInjectionStarter.java index 5cf0c9170c..47014aa2d1 100644 --- a/spring-core/src/main/java/com/baeldung/scope/BeanInjectionStarter.java +++ b/spring-core/src/main/java/com/baeldung/scope/BeanInjectionStarter.java @@ -1,7 +1,7 @@ package com.baeldung.scope; import com.baeldung.scope.prototype.PrototypeBean; -import com.baeldung.scope.singletone.SingletonBean; +import com.baeldung.scope.singleton.SingletonBean; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.util.Assert; diff --git a/spring-core/src/main/java/com/baeldung/scope/singletone/SingletonAppContextBean.java b/spring-core/src/main/java/com/baeldung/scope/singleton/SingletonAppContextBean.java similarity index 94% rename from spring-core/src/main/java/com/baeldung/scope/singletone/SingletonAppContextBean.java rename to spring-core/src/main/java/com/baeldung/scope/singleton/SingletonAppContextBean.java index f4d57a0f63..4f5b3274c8 100644 --- a/spring-core/src/main/java/com/baeldung/scope/singletone/SingletonAppContextBean.java +++ b/spring-core/src/main/java/com/baeldung/scope/singleton/SingletonAppContextBean.java @@ -1,4 +1,4 @@ -package com.baeldung.scope.singletone; +package com.baeldung.scope.singleton; import com.baeldung.scope.prototype.PrototypeBean; import org.springframework.beans.BeansException; diff --git a/spring-core/src/main/java/com/baeldung/scope/singletone/SingletonBean.java b/spring-core/src/main/java/com/baeldung/scope/singleton/SingletonBean.java similarity index 93% rename from spring-core/src/main/java/com/baeldung/scope/singletone/SingletonBean.java rename to spring-core/src/main/java/com/baeldung/scope/singleton/SingletonBean.java index 8d3a09b8fd..9c4cea4439 100644 --- a/spring-core/src/main/java/com/baeldung/scope/singletone/SingletonBean.java +++ b/spring-core/src/main/java/com/baeldung/scope/singleton/SingletonBean.java @@ -1,4 +1,4 @@ -package com.baeldung.scope.singletone; +package com.baeldung.scope.singleton; import com.baeldung.scope.prototype.PrototypeBean; import org.apache.log4j.Logger; diff --git a/spring-core/src/main/java/com/baeldung/scope/singletone/SingletonFunctionBean.java b/spring-core/src/main/java/com/baeldung/scope/singleton/SingletonFunctionBean.java similarity index 91% rename from spring-core/src/main/java/com/baeldung/scope/singletone/SingletonFunctionBean.java rename to spring-core/src/main/java/com/baeldung/scope/singleton/SingletonFunctionBean.java index 8cdc56a6fa..2788af1701 100644 --- a/spring-core/src/main/java/com/baeldung/scope/singletone/SingletonFunctionBean.java +++ b/spring-core/src/main/java/com/baeldung/scope/singleton/SingletonFunctionBean.java @@ -1,4 +1,4 @@ -package com.baeldung.scope.singletone; +package com.baeldung.scope.singleton; import java.util.function.Function; diff --git a/spring-core/src/main/java/com/baeldung/scope/singletone/SingletonLookupBean.java b/spring-core/src/main/java/com/baeldung/scope/singleton/SingletonLookupBean.java similarity index 88% rename from spring-core/src/main/java/com/baeldung/scope/singletone/SingletonLookupBean.java rename to spring-core/src/main/java/com/baeldung/scope/singleton/SingletonLookupBean.java index 4c3c9b69da..e5461826ef 100644 --- a/spring-core/src/main/java/com/baeldung/scope/singletone/SingletonLookupBean.java +++ b/spring-core/src/main/java/com/baeldung/scope/singleton/SingletonLookupBean.java @@ -1,4 +1,4 @@ -package com.baeldung.scope.singletone; +package com.baeldung.scope.singleton; import com.baeldung.scope.prototype.PrototypeBean; import org.springframework.beans.factory.annotation.Lookup; diff --git a/spring-core/src/main/java/com/baeldung/scope/singletone/SingletonObjectFactoryBean.java b/spring-core/src/main/java/com/baeldung/scope/singleton/SingletonObjectFactoryBean.java similarity index 91% rename from spring-core/src/main/java/com/baeldung/scope/singletone/SingletonObjectFactoryBean.java rename to spring-core/src/main/java/com/baeldung/scope/singleton/SingletonObjectFactoryBean.java index 55a91f8202..0e70d12e6e 100644 --- a/spring-core/src/main/java/com/baeldung/scope/singletone/SingletonObjectFactoryBean.java +++ b/spring-core/src/main/java/com/baeldung/scope/singleton/SingletonObjectFactoryBean.java @@ -1,4 +1,4 @@ -package com.baeldung.scope.singletone; +package com.baeldung.scope.singleton; import com.baeldung.scope.prototype.PrototypeBean; import org.springframework.beans.factory.ObjectFactory; diff --git a/spring-core/src/main/java/com/baeldung/scope/singletone/SingletonProviderBean.java b/spring-core/src/main/java/com/baeldung/scope/singleton/SingletonProviderBean.java similarity index 90% rename from spring-core/src/main/java/com/baeldung/scope/singletone/SingletonProviderBean.java rename to spring-core/src/main/java/com/baeldung/scope/singleton/SingletonProviderBean.java index 37d0ad9404..01a4a0ff11 100644 --- a/spring-core/src/main/java/com/baeldung/scope/singletone/SingletonProviderBean.java +++ b/spring-core/src/main/java/com/baeldung/scope/singleton/SingletonProviderBean.java @@ -1,4 +1,4 @@ -package com.baeldung.scope.singletone; +package com.baeldung.scope.singleton; import com.baeldung.scope.prototype.PrototypeBean; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-core/src/test/java/com/baeldung/scope/PrototypeBeanInjectionIntegrationTest.java b/spring-core/src/test/java/com/baeldung/scope/PrototypeBeanInjectionIntegrationTest.java index d0c2733765..df04957992 100644 --- a/spring-core/src/test/java/com/baeldung/scope/PrototypeBeanInjectionIntegrationTest.java +++ b/spring-core/src/test/java/com/baeldung/scope/PrototypeBeanInjectionIntegrationTest.java @@ -1,10 +1,9 @@ package com.baeldung.scope; import com.baeldung.scope.prototype.PrototypeBean; -import com.baeldung.scope.singletone.SingletonFunctionBean; -import com.baeldung.scope.singletone.SingletonLookupBean; -import com.baeldung.scope.singletone.SingletonObjectFactoryBean; -import com.baeldung.scope.singletone.SingletonProviderBean; +import com.baeldung.scope.singleton.SingletonLookupBean; +import com.baeldung.scope.singleton.SingletonObjectFactoryBean; +import com.baeldung.scope.singleton.SingletonProviderBean; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-core/src/test/java/com/baeldung/scope/PrototypeFunctionBeanIntegrationTest.java b/spring-core/src/test/java/com/baeldung/scope/PrototypeFunctionBeanIntegrationTest.java index 1e3c652599..dac3461ceb 100644 --- a/spring-core/src/test/java/com/baeldung/scope/PrototypeFunctionBeanIntegrationTest.java +++ b/spring-core/src/test/java/com/baeldung/scope/PrototypeFunctionBeanIntegrationTest.java @@ -11,7 +11,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; import com.baeldung.config.scope.AppConfigFunctionBean; import com.baeldung.scope.prototype.PrototypeBean; -import com.baeldung.scope.singletone.SingletonFunctionBean; +import com.baeldung.scope.singleton.SingletonFunctionBean; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = AppConfigFunctionBean.class) From 87056d13bc8b6a6b423b0c84b568f39cfeb1fd10 Mon Sep 17 00:00:00 2001 From: balasr3 Date: Sun, 1 Oct 2023 07:28:57 +0530 Subject: [PATCH 11/37] BAEL-7032: Improvement to conditional mapping by using @Condition and added tests --- .../baeldung/expression/dto/LicenseDto.java | 10 +++++++ .../expression/mapper/LicenseMapper.java | 12 +++++++- .../baeldung/expression/model/License.java | 16 ++++++++++- .../mapper/LicenseMapperUnitTest.java | 28 +++++++++++++++++++ 4 files changed, 64 insertions(+), 2 deletions(-) diff --git a/mapstruct/src/main/java/com/baeldung/expression/dto/LicenseDto.java b/mapstruct/src/main/java/com/baeldung/expression/dto/LicenseDto.java index 025df1a4f6..1d7cacaead 100644 --- a/mapstruct/src/main/java/com/baeldung/expression/dto/LicenseDto.java +++ b/mapstruct/src/main/java/com/baeldung/expression/dto/LicenseDto.java @@ -11,6 +11,8 @@ public class LicenseDto { private LocalDateTime endDate; + private String licenseType; + public UUID getId() { return id; } @@ -35,4 +37,12 @@ public class LicenseDto { this.endDate = endDate; } + public String getLicenseType() { + return licenseType; + } + + public void setLicenseType(String licenseType) { + this.licenseType = licenseType; + } + } diff --git a/mapstruct/src/main/java/com/baeldung/expression/mapper/LicenseMapper.java b/mapstruct/src/main/java/com/baeldung/expression/mapper/LicenseMapper.java index 100588b45d..0d8904e220 100644 --- a/mapstruct/src/main/java/com/baeldung/expression/mapper/LicenseMapper.java +++ b/mapstruct/src/main/java/com/baeldung/expression/mapper/LicenseMapper.java @@ -6,6 +6,7 @@ import java.time.OffsetDateTime; import java.time.ZoneOffset; import org.mapstruct.AfterMapping; +import org.mapstruct.Condition; import org.mapstruct.Mapper; import org.mapstruct.Mapping; import org.mapstruct.MappingTarget; @@ -40,4 +41,13 @@ public interface LicenseMapper { .toDays() <= 14; } -} + @Condition + default boolean mapsToExpectedLicenseType(String licenseType) { + try { + return licenseType != null && License.LicenseType.valueOf(licenseType) != null; + } catch (IllegalArgumentException e) { + return false; + } + } + +} \ No newline at end of file diff --git a/mapstruct/src/main/java/com/baeldung/expression/model/License.java b/mapstruct/src/main/java/com/baeldung/expression/model/License.java index 71e4f086c0..550d23eee8 100644 --- a/mapstruct/src/main/java/com/baeldung/expression/model/License.java +++ b/mapstruct/src/main/java/com/baeldung/expression/model/License.java @@ -16,6 +16,8 @@ public class License { private boolean renewalRequired; + private LicenseType licenseType; + public UUID getId() { return id; } @@ -55,4 +57,16 @@ public class License { public void setRenewalRequired(boolean renewalRequired) { this.renewalRequired = renewalRequired; } -} + + public enum LicenseType { + INDIVIDUAL, FAMILY + } + + public LicenseType getLicenseType() { + return licenseType; + } + + public void setLicenseType(LicenseType licenseType) { + this.licenseType = licenseType; + } +} \ No newline at end of file diff --git a/mapstruct/src/test/java/com/baeldung/expression/mapper/LicenseMapperUnitTest.java b/mapstruct/src/test/java/com/baeldung/expression/mapper/LicenseMapperUnitTest.java index dcdda5c1ac..8c015674bc 100644 --- a/mapstruct/src/test/java/com/baeldung/expression/mapper/LicenseMapperUnitTest.java +++ b/mapstruct/src/test/java/com/baeldung/expression/mapper/LicenseMapperUnitTest.java @@ -6,6 +6,7 @@ import java.time.LocalDate; import java.time.LocalDateTime; import java.util.UUID; +import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mapstruct.factory.Mappers; @@ -74,4 +75,31 @@ class LicenseMapperUnitTest { assertThat(license.getId()).isSameAs(id); } + @Test + void givenLicenseDtoWithoutLicenseTypeString_WhenMapperMethodIsInvoked_ThenLicenseShouldBePopulatedWithoutLicenseType() { + LicenseDto licenseDto = new LicenseDto(); + License license = licenseMapper.toLicense(licenseDto); + assertThat(license).isNotNull(); + Assertions.assertNull(license.getLicenseType()); + } + + @Test + void givenLicenseDtoWithInvalidLicenseTypeString_WhenMapperMethodIsInvoked_ThenLicenseShouldBePopulatedWithoutLicenseType() { + LicenseDto licenseDto = new LicenseDto(); + licenseDto.setLicenseType("invalid_license_type"); + License license = licenseMapper.toLicense(licenseDto); + assertThat(license).isNotNull(); + Assertions.assertNull(license.getLicenseType()); + } + + @Test + void givenLicenseDtoWithValidLicenseTypeString_WhenMapperMethodIsInvoked_ThenLicenseShouldBePopulatedWithMatchingLicenseType() { + LicenseDto licenseDto = new LicenseDto(); + licenseDto.setLicenseType("INDIVIDUAL"); + License license = licenseMapper.toLicense(licenseDto); + assertThat(license).isNotNull(); + Assertions.assertNotNull(license.getLicenseType()); + assertThat(license.getLicenseType()).isEqualTo(License.LicenseType.INDIVIDUAL); + } + } \ No newline at end of file From 96de260e1dbfbcc65495dfac7969cc5ef5abb2d9 Mon Sep 17 00:00:00 2001 From: balasr3 Date: Sun, 1 Oct 2023 07:30:17 +0530 Subject: [PATCH 12/37] BAEL-7032: updated formatting --- .../src/main/java/com/baeldung/expression/model/License.java | 1 - 1 file changed, 1 deletion(-) diff --git a/mapstruct/src/main/java/com/baeldung/expression/model/License.java b/mapstruct/src/main/java/com/baeldung/expression/model/License.java index 550d23eee8..e36e278a57 100644 --- a/mapstruct/src/main/java/com/baeldung/expression/model/License.java +++ b/mapstruct/src/main/java/com/baeldung/expression/model/License.java @@ -3,7 +3,6 @@ package com.baeldung.expression.model; import java.time.OffsetDateTime; import java.util.UUID; - public class License { private UUID id; From adcf9b8cbdbc9dfba196fadc82292e48253afd1f Mon Sep 17 00:00:00 2001 From: panos-kakos Date: Sun, 1 Oct 2023 10:19:23 +0300 Subject: [PATCH 13/37] [JAVA-23452] testing --- ...yIntegrationTest.java => ProductInfoRepositoryUnitTest.java} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename aws-modules/aws-miscellaneous/src/test/java/com/baeldung/dynamodb/{ProductInfoRepositoryIntegrationTest.java => ProductInfoRepositoryUnitTest.java} (98%) diff --git a/aws-modules/aws-miscellaneous/src/test/java/com/baeldung/dynamodb/ProductInfoRepositoryIntegrationTest.java b/aws-modules/aws-miscellaneous/src/test/java/com/baeldung/dynamodb/ProductInfoRepositoryUnitTest.java similarity index 98% rename from aws-modules/aws-miscellaneous/src/test/java/com/baeldung/dynamodb/ProductInfoRepositoryIntegrationTest.java rename to aws-modules/aws-miscellaneous/src/test/java/com/baeldung/dynamodb/ProductInfoRepositoryUnitTest.java index 18f55544cd..9fcf237599 100644 --- a/aws-modules/aws-miscellaneous/src/test/java/com/baeldung/dynamodb/ProductInfoRepositoryIntegrationTest.java +++ b/aws-modules/aws-miscellaneous/src/test/java/com/baeldung/dynamodb/ProductInfoRepositoryUnitTest.java @@ -29,7 +29,7 @@ import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsEqual.equalTo; import static org.junit.Assert.assertThat; -public class ProductInfoRepositoryIntegrationTest { +public class ProductInfoRepositoryUnitTest { @ClassRule public static LocalDbCreationRule dynamoDB = new LocalDbCreationRule(); From 39c353c6aeec68b85418da16a3907a98ef9869ea Mon Sep 17 00:00:00 2001 From: mcasari Date: Sun, 1 Oct 2023 21:58:55 +0200 Subject: [PATCH 14/37] BAEL-6846 - updates due to further discussion about float representation --- .../FloatToBigDecimalUnitTest.java | 45 +++++++++---------- 1 file changed, 22 insertions(+), 23 deletions(-) diff --git a/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/floattobigdecimal/FloatToBigDecimalUnitTest.java b/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/floattobigdecimal/FloatToBigDecimalUnitTest.java index 2d6d1ab5d0..8895c01575 100644 --- a/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/floattobigdecimal/FloatToBigDecimalUnitTest.java +++ b/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/floattobigdecimal/FloatToBigDecimalUnitTest.java @@ -16,45 +16,44 @@ class FloatToBigDecimalUnitTest { } @Test - public void whenCreatedFromCertainFloatValues_thenMatches() { - float floatToConvert = 0.5f; - BigDecimal bdFromFloat = new BigDecimal(floatToConvert); - assertEquals("0.5", bdFromFloat.toString()); - } - - @Test - public void whenCreatedFromCertainFloatValues_thenDoesNotMatch() { + public void whenCreatedFromFloat_thenMatchesInternallyStoredValue() { float floatToConvert = 1.1f; BigDecimal bdFromFloat = new BigDecimal(floatToConvert); assertEquals("1.10000002384185791015625", bdFromFloat.toString()); } @Test - public void whenCreatedFromString_thenMatches() { - String floatValue = Float.toString(1.1f); - BigDecimal bdFromString = new BigDecimal(floatValue); + public void whenCreatedFromString_thenPreservesTheOriginal() { + BigDecimal bdFromString = new BigDecimal("1.1"); assertEquals("1.1", bdFromString.toString()); } @Test - public void whenCreatedByValueOfAndIsFloat_thenDoesNotMatch() { - float floatToConvert = 1.1f; - BigDecimal bdByValueOf = BigDecimal.valueOf(floatToConvert); - assertEquals("1.100000023841858", bdByValueOf.toString()); + public void whenCreatedFromFloatConvertedToString_thenFloatInternalValueGetsTruncated() { + String floatValue = Float.toString(1.1f); + BigDecimal bdFromString = new BigDecimal(floatValue); + assertEquals("1.1", floatValue); + assertEquals("1.1", bdFromString.toString()); } @Test - public void whenFloatCastToDouble_thenGotADifferentNumber() { - float floatToConvert = 1.1f; - double doubleCast = floatToConvert; - assertEquals("1.100000023841858", Double.toString(doubleCast)); + public void whenFloatConvertedToString_thenGetsTruncated() { + String floatValue = Float.toString(1.10000002384185791015625f); + assertEquals("1.1", floatValue); } @Test - public void whenCreatedByValueOfAndIsDouble_thenMatches() { - double doubleToConvert = 1.1d; - BigDecimal bdByValueOf = BigDecimal.valueOf(doubleToConvert); - assertEquals("1.1", bdByValueOf.toString()); + public void whenCreatedByValueOf_thenFloatValueGetsTruncated() { + assertEquals("1.100000023841858", BigDecimal.valueOf(1.1f) + .toString()); + assertEquals("1.100000023841858", BigDecimal.valueOf(1.10000002384185791015625f) + .toString()); + } + + @Test + public void whenDoubleConvertsFloatToString_thenFloatValueGetsTruncated() { + assertEquals("1.100000023841858", Double.toString(1.1f)); + assertEquals("1.100000023841858", Double.toString(1.10000002384185791015625f)); } } \ No newline at end of file From 6f085f068a1874b555f971b2109ff88ad78c07e6 Mon Sep 17 00:00:00 2001 From: mcasari Date: Tue, 3 Oct 2023 18:34:40 +0200 Subject: [PATCH 15/37] BAEL-6846 - minor code format fix --- .../floattobigdecimal/FloatToBigDecimalUnitTest.java | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/floattobigdecimal/FloatToBigDecimalUnitTest.java b/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/floattobigdecimal/FloatToBigDecimalUnitTest.java index 8895c01575..fe5dc360e4 100644 --- a/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/floattobigdecimal/FloatToBigDecimalUnitTest.java +++ b/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/floattobigdecimal/FloatToBigDecimalUnitTest.java @@ -44,10 +44,8 @@ class FloatToBigDecimalUnitTest { @Test public void whenCreatedByValueOf_thenFloatValueGetsTruncated() { - assertEquals("1.100000023841858", BigDecimal.valueOf(1.1f) - .toString()); - assertEquals("1.100000023841858", BigDecimal.valueOf(1.10000002384185791015625f) - .toString()); + assertEquals("1.100000023841858", BigDecimal.valueOf(1.1f).toString()); + assertEquals("1.100000023841858", BigDecimal.valueOf(1.10000002384185791015625f).toString()); } @Test From 7e1d5991e61a969ec922f5a7182096ee76002d0f Mon Sep 17 00:00:00 2001 From: mcasari Date: Tue, 3 Oct 2023 23:41:11 +0200 Subject: [PATCH 16/37] BAEL-6846 - tests revision due to article updates --- .../FloatToBigDecimalUnitTest.java | 16 ++++------------ 1 file changed, 4 insertions(+), 12 deletions(-) diff --git a/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/floattobigdecimal/FloatToBigDecimalUnitTest.java b/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/floattobigdecimal/FloatToBigDecimalUnitTest.java index fe5dc360e4..9d125f557d 100644 --- a/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/floattobigdecimal/FloatToBigDecimalUnitTest.java +++ b/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/floattobigdecimal/FloatToBigDecimalUnitTest.java @@ -17,40 +17,32 @@ class FloatToBigDecimalUnitTest { @Test public void whenCreatedFromFloat_thenMatchesInternallyStoredValue() { - float floatToConvert = 1.1f; + float floatToConvert = 1.10000002384185791015625f; BigDecimal bdFromFloat = new BigDecimal(floatToConvert); assertEquals("1.10000002384185791015625", bdFromFloat.toString()); } @Test public void whenCreatedFromString_thenPreservesTheOriginal() { - BigDecimal bdFromString = new BigDecimal("1.1"); - assertEquals("1.1", bdFromString.toString()); + BigDecimal bdFromString = new BigDecimal("1.10000002384185791015625"); + assertEquals("1.10000002384185791015625", bdFromString.toString()); } @Test public void whenCreatedFromFloatConvertedToString_thenFloatInternalValueGetsTruncated() { - String floatValue = Float.toString(1.1f); + String floatValue = Float.toString(1.10000002384185791015625f); BigDecimal bdFromString = new BigDecimal(floatValue); assertEquals("1.1", floatValue); assertEquals("1.1", bdFromString.toString()); } - @Test - public void whenFloatConvertedToString_thenGetsTruncated() { - String floatValue = Float.toString(1.10000002384185791015625f); - assertEquals("1.1", floatValue); - } - @Test public void whenCreatedByValueOf_thenFloatValueGetsTruncated() { - assertEquals("1.100000023841858", BigDecimal.valueOf(1.1f).toString()); assertEquals("1.100000023841858", BigDecimal.valueOf(1.10000002384185791015625f).toString()); } @Test public void whenDoubleConvertsFloatToString_thenFloatValueGetsTruncated() { - assertEquals("1.100000023841858", Double.toString(1.1f)); assertEquals("1.100000023841858", Double.toString(1.10000002384185791015625f)); } From 68fd94288d141c87381ca9deeca3284dfd54cce9 Mon Sep 17 00:00:00 2001 From: mcasari Date: Fri, 6 Oct 2023 21:57:56 +0200 Subject: [PATCH 17/37] change string constructor test case in simpler form --- .../baeldung/floattobigdecimal/FloatToBigDecimalUnitTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/floattobigdecimal/FloatToBigDecimalUnitTest.java b/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/floattobigdecimal/FloatToBigDecimalUnitTest.java index 9d125f557d..f783d00976 100644 --- a/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/floattobigdecimal/FloatToBigDecimalUnitTest.java +++ b/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/floattobigdecimal/FloatToBigDecimalUnitTest.java @@ -24,8 +24,8 @@ class FloatToBigDecimalUnitTest { @Test public void whenCreatedFromString_thenPreservesTheOriginal() { - BigDecimal bdFromString = new BigDecimal("1.10000002384185791015625"); - assertEquals("1.10000002384185791015625", bdFromString.toString()); + BigDecimal bdFromString = new BigDecimal("1.1"); + assertEquals("1.1", bdFromString.toString()); } @Test From 131d6757719ac3e603f94160ffcfde5346d5f292 Mon Sep 17 00:00:00 2001 From: balasr3 Date: Sat, 7 Oct 2023 14:48:34 +0100 Subject: [PATCH 18/37] BAEL-7032: updated with review comment on test --- .../baeldung/expression/mapper/LicenseMapperUnitTest.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/mapstruct/src/test/java/com/baeldung/expression/mapper/LicenseMapperUnitTest.java b/mapstruct/src/test/java/com/baeldung/expression/mapper/LicenseMapperUnitTest.java index 8c015674bc..d7521e81f5 100644 --- a/mapstruct/src/test/java/com/baeldung/expression/mapper/LicenseMapperUnitTest.java +++ b/mapstruct/src/test/java/com/baeldung/expression/mapper/LicenseMapperUnitTest.java @@ -76,7 +76,7 @@ class LicenseMapperUnitTest { } @Test - void givenLicenseDtoWithoutLicenseTypeString_WhenMapperMethodIsInvoked_ThenLicenseShouldBePopulatedWithoutLicenseType() { + void givenLicenseDtoWithoutLicenseTypeString_whenMapperMethodIsInvoked_thenLicenseShouldBePopulatedWithoutLicenseType() { LicenseDto licenseDto = new LicenseDto(); License license = licenseMapper.toLicense(licenseDto); assertThat(license).isNotNull(); @@ -84,7 +84,7 @@ class LicenseMapperUnitTest { } @Test - void givenLicenseDtoWithInvalidLicenseTypeString_WhenMapperMethodIsInvoked_ThenLicenseShouldBePopulatedWithoutLicenseType() { + void givenLicenseDtoWithInvalidLicenseTypeString_whenMapperMethodIsInvoked_thenLicenseShouldBePopulatedWithoutLicenseType() { LicenseDto licenseDto = new LicenseDto(); licenseDto.setLicenseType("invalid_license_type"); License license = licenseMapper.toLicense(licenseDto); @@ -93,7 +93,7 @@ class LicenseMapperUnitTest { } @Test - void givenLicenseDtoWithValidLicenseTypeString_WhenMapperMethodIsInvoked_ThenLicenseShouldBePopulatedWithMatchingLicenseType() { + void givenLicenseDtoWithValidLicenseTypeString_whenMapperMethodIsInvoked_thenLicenseShouldBePopulatedWithMatchingLicenseType() { LicenseDto licenseDto = new LicenseDto(); licenseDto.setLicenseType("INDIVIDUAL"); License license = licenseMapper.toLicense(licenseDto); From 55296d07f484b1f1e794bec261827d9d71b922bd Mon Sep 17 00:00:00 2001 From: panos-kakos Date: Sat, 7 Oct 2023 18:38:44 +0300 Subject: [PATCH 19/37] [JAVA-23452] Moved dynamodb to a separate module --- aws-modules/aws-dynamodb/.gitignore | 2 + aws-modules/aws-dynamodb/README.md | 7 ++ aws-modules/aws-dynamodb/pom.xml | 89 +++++++++++++++++++ .../baeldung/dynamodb/entity/ProductInfo.java | 51 +++++++++++ .../repository/AbstractRepository.java | 49 ++++++++++ .../repository/ProductInfoRepository.java | 6 ++ .../src/main/resources/db.properties | 4 + .../src/main/resources/logback.xml | 13 +++ .../ProductInfoRepositoryUnitTest.java | 8 +- .../dynamodb/rule/LocalDbCreationRule.java | 0 .../src/test/resources/test.properties | 0 aws-modules/aws-miscellaneous/pom.xml | 11 --- aws-modules/pom.xml | 9 ++ 13 files changed, 234 insertions(+), 15 deletions(-) create mode 100644 aws-modules/aws-dynamodb/.gitignore create mode 100644 aws-modules/aws-dynamodb/README.md create mode 100644 aws-modules/aws-dynamodb/pom.xml create mode 100644 aws-modules/aws-dynamodb/src/main/java/com/baeldung/dynamodb/entity/ProductInfo.java create mode 100644 aws-modules/aws-dynamodb/src/main/java/com/baeldung/dynamodb/repository/AbstractRepository.java create mode 100644 aws-modules/aws-dynamodb/src/main/java/com/baeldung/dynamodb/repository/ProductInfoRepository.java create mode 100644 aws-modules/aws-dynamodb/src/main/resources/db.properties create mode 100644 aws-modules/aws-dynamodb/src/main/resources/logback.xml rename aws-modules/{aws-miscellaneous => aws-dynamodb}/src/test/java/com/baeldung/dynamodb/ProductInfoRepositoryUnitTest.java (91%) rename aws-modules/{aws-miscellaneous => aws-dynamodb}/src/test/java/com/baeldung/dynamodb/rule/LocalDbCreationRule.java (100%) rename aws-modules/{aws-miscellaneous => aws-dynamodb}/src/test/resources/test.properties (100%) diff --git a/aws-modules/aws-dynamodb/.gitignore b/aws-modules/aws-dynamodb/.gitignore new file mode 100644 index 0000000000..bf11a4cc38 --- /dev/null +++ b/aws-modules/aws-dynamodb/.gitignore @@ -0,0 +1,2 @@ +/target/ +.idea/ \ No newline at end of file diff --git a/aws-modules/aws-dynamodb/README.md b/aws-modules/aws-dynamodb/README.md new file mode 100644 index 0000000000..68a353e555 --- /dev/null +++ b/aws-modules/aws-dynamodb/README.md @@ -0,0 +1,7 @@ +## AWS DYNAMODB + +This module contains articles about AWS DynamoDB + +### Relevant articles +- [Integration Testing with a Local DynamoDB Instance](https://www.baeldung.com/dynamodb-local-integration-tests) + diff --git a/aws-modules/aws-dynamodb/pom.xml b/aws-modules/aws-dynamodb/pom.xml new file mode 100644 index 0000000000..eee01badf3 --- /dev/null +++ b/aws-modules/aws-dynamodb/pom.xml @@ -0,0 +1,89 @@ + + + 4.0.0 + aws-dynamodb + 0.1.0-SNAPSHOT + aws-dynamodb + jar + + + com.baeldung + aws-modules + 1.0.0-SNAPSHOT + + + + + commons-io + commons-io + ${commons-io.version} + + + com.google.code.gson + gson + ${gson.version} + + + com.amazonaws + DynamoDBLocal + ${dynamodblocal.version} + test + + + com.amazonaws + aws-java-sdk-dynamodb + ${aws-java-sdk.version} + + + + + + + org.apache.maven.plugins + maven-shade-plugin + ${maven-shade-plugin.version} + + false + + + + package + + shade + + + + + + org.apache.maven.plugins + maven-dependency-plugin + ${maven-plugins-version} + + + copy + compile + + copy-dependencies + + + + so,dll,dylib + native-libs + + + + + + + + + 2.8.0 + 1.21.1 + 1.10.L001 + 0.9.4.0006L + 3.1.1 + + + \ No newline at end of file diff --git a/aws-modules/aws-dynamodb/src/main/java/com/baeldung/dynamodb/entity/ProductInfo.java b/aws-modules/aws-dynamodb/src/main/java/com/baeldung/dynamodb/entity/ProductInfo.java new file mode 100644 index 0000000000..9af5d926c9 --- /dev/null +++ b/aws-modules/aws-dynamodb/src/main/java/com/baeldung/dynamodb/entity/ProductInfo.java @@ -0,0 +1,51 @@ +package com.baeldung.dynamodb.entity; + +import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute; +import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAutoGeneratedKey; +import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; +import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; + +@DynamoDBTable(tableName = "ProductInfo") +public class ProductInfo { + + private String id; + private String msrp; + private String cost; + + public ProductInfo() { + } + + public ProductInfo(String cost, String msrp) { + this.msrp = msrp; + this.cost = cost; + } + + @DynamoDBHashKey + @DynamoDBAutoGeneratedKey + public String getId() { + return id; + } + + @DynamoDBAttribute + public String getMsrp() { + return msrp; + } + + @DynamoDBAttribute + public String getCost() { + return cost; + } + + public void setId(String id) { + this.id = id; + } + + public void setMsrp(String msrp) { + this.msrp = msrp; + } + + public void setCost(String cost) { + this.cost = cost; + } + +} diff --git a/aws-modules/aws-dynamodb/src/main/java/com/baeldung/dynamodb/repository/AbstractRepository.java b/aws-modules/aws-dynamodb/src/main/java/com/baeldung/dynamodb/repository/AbstractRepository.java new file mode 100644 index 0000000000..79934c17e9 --- /dev/null +++ b/aws-modules/aws-dynamodb/src/main/java/com/baeldung/dynamodb/repository/AbstractRepository.java @@ -0,0 +1,49 @@ +package com.baeldung.dynamodb.repository; + +import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; +import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBScanExpression; + +import java.io.Serializable; +import java.lang.reflect.ParameterizedType; +import java.util.List; + +public abstract class AbstractRepository { + + protected DynamoDBMapper mapper; + protected Class entityClass; + + protected AbstractRepository() { + ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass(); + + // This entityClass refers to the actual entity class in the subclass declaration. + + // For instance, ProductInfoDAO extends AbstractDAO + // In this case entityClass = ProductInfo, and ID is String type + // which refers to the ProductInfo's partition key string value + this.entityClass = (Class) genericSuperclass.getActualTypeArguments()[0]; + } + + public void save(T t) { + mapper.save(t); + } + + public T findOne(ID id) { + return mapper.load(entityClass, id); + } + + /** + * WARNING: It is not recommended to perform full table scan + * targeting the real production environment. + * + * @return All items + */ + public List findAll() { + DynamoDBScanExpression scanExpression = new DynamoDBScanExpression(); + return mapper.scan(entityClass, scanExpression); + } + + public void setMapper(DynamoDBMapper dynamoDBMapper) { + this.mapper = dynamoDBMapper; + } + +} diff --git a/aws-modules/aws-dynamodb/src/main/java/com/baeldung/dynamodb/repository/ProductInfoRepository.java b/aws-modules/aws-dynamodb/src/main/java/com/baeldung/dynamodb/repository/ProductInfoRepository.java new file mode 100644 index 0000000000..0dfec8e05c --- /dev/null +++ b/aws-modules/aws-dynamodb/src/main/java/com/baeldung/dynamodb/repository/ProductInfoRepository.java @@ -0,0 +1,6 @@ +package com.baeldung.dynamodb.repository; + +import com.baeldung.dynamodb.entity.ProductInfo; + +public class ProductInfoRepository extends AbstractRepository { +} diff --git a/aws-modules/aws-dynamodb/src/main/resources/db.properties b/aws-modules/aws-dynamodb/src/main/resources/db.properties new file mode 100644 index 0000000000..e934611a2b --- /dev/null +++ b/aws-modules/aws-dynamodb/src/main/resources/db.properties @@ -0,0 +1,4 @@ +db_hostname= +db_username=username +db_password=password +db_database=mydb \ No newline at end of file diff --git a/aws-modules/aws-dynamodb/src/main/resources/logback.xml b/aws-modules/aws-dynamodb/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/aws-modules/aws-dynamodb/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/aws-modules/aws-miscellaneous/src/test/java/com/baeldung/dynamodb/ProductInfoRepositoryUnitTest.java b/aws-modules/aws-dynamodb/src/test/java/com/baeldung/dynamodb/ProductInfoRepositoryUnitTest.java similarity index 91% rename from aws-modules/aws-miscellaneous/src/test/java/com/baeldung/dynamodb/ProductInfoRepositoryUnitTest.java rename to aws-modules/aws-dynamodb/src/test/java/com/baeldung/dynamodb/ProductInfoRepositoryUnitTest.java index 9fcf237599..617a35bd00 100644 --- a/aws-modules/aws-miscellaneous/src/test/java/com/baeldung/dynamodb/ProductInfoRepositoryUnitTest.java +++ b/aws-modules/aws-dynamodb/src/test/java/com/baeldung/dynamodb/ProductInfoRepositoryUnitTest.java @@ -49,10 +49,10 @@ public class ProductInfoRepositoryUnitTest { @BeforeClass public static void setupClass() { Properties testProperties = loadFromFileInClasspath("test.properties") - .filter(properties -> !isEmpty(properties.getProperty(AWS_ACCESSKEY))) - .filter(properties -> !isEmpty(properties.getProperty(AWS_SECRETKEY))) - .filter(properties -> !isEmpty(properties.getProperty(DYNAMODB_ENDPOINT))) - .orElseThrow(() -> new RuntimeException("Unable to get all of the required test property values")); + .filter(properties -> !isEmpty(properties.getProperty(AWS_ACCESSKEY))) + .filter(properties -> !isEmpty(properties.getProperty(AWS_SECRETKEY))) + .filter(properties -> !isEmpty(properties.getProperty(DYNAMODB_ENDPOINT))) + .orElseThrow(() -> new RuntimeException("Unable to get all of the required test property values")); String amazonAWSAccessKey = testProperties.getProperty(AWS_ACCESSKEY); String amazonAWSSecretKey = testProperties.getProperty(AWS_SECRETKEY); diff --git a/aws-modules/aws-miscellaneous/src/test/java/com/baeldung/dynamodb/rule/LocalDbCreationRule.java b/aws-modules/aws-dynamodb/src/test/java/com/baeldung/dynamodb/rule/LocalDbCreationRule.java similarity index 100% rename from aws-modules/aws-miscellaneous/src/test/java/com/baeldung/dynamodb/rule/LocalDbCreationRule.java rename to aws-modules/aws-dynamodb/src/test/java/com/baeldung/dynamodb/rule/LocalDbCreationRule.java diff --git a/aws-modules/aws-miscellaneous/src/test/resources/test.properties b/aws-modules/aws-dynamodb/src/test/resources/test.properties similarity index 100% rename from aws-modules/aws-miscellaneous/src/test/resources/test.properties rename to aws-modules/aws-dynamodb/src/test/resources/test.properties diff --git a/aws-modules/aws-miscellaneous/pom.xml b/aws-modules/aws-miscellaneous/pom.xml index e582ee6e4d..4126256fb9 100644 --- a/aws-modules/aws-miscellaneous/pom.xml +++ b/aws-modules/aws-miscellaneous/pom.xml @@ -30,17 +30,6 @@ gson ${gson.version} - - com.amazonaws - DynamoDBLocal - ${dynamodblocal.version} - test - - - com.amazonaws - aws-java-sdk-dynamodb - ${aws-java-sdk.version} - diff --git a/aws-modules/pom.xml b/aws-modules/pom.xml index fa16e22c3a..66fa4bffa1 100644 --- a/aws-modules/pom.xml +++ b/aws-modules/pom.xml @@ -5,6 +5,14 @@ 4.0.0 aws-modules aws-modules + + + com.amazonaws + aws-java-sdk-dynamodb + 1.12.523 + compile + + pom @@ -15,6 +23,7 @@ aws-app-sync + aws-dynamodb aws-lambda-modules aws-miscellaneous aws-reactive From 35be82141f5a61cea29a3dfe9cf0b541fa173065 Mon Sep 17 00:00:00 2001 From: panos-kakos Date: Sat, 7 Oct 2023 18:58:23 +0300 Subject: [PATCH 20/37] [JAVA-23452] Clean up --- aws-modules/aws-dynamodb/pom.xml | 28 +++++----- .../src/main/resources/db.properties | 4 -- ...ProductInfoRepositoryIntegrationTest.java} | 2 +- .../baeldung/dynamodb/entity/ProductInfo.java | 51 ------------------- .../repository/AbstractRepository.java | 49 ------------------ .../repository/ProductInfoRepository.java | 6 --- 6 files changed, 14 insertions(+), 126 deletions(-) delete mode 100644 aws-modules/aws-dynamodb/src/main/resources/db.properties rename aws-modules/aws-dynamodb/src/test/java/com/baeldung/dynamodb/{ProductInfoRepositoryUnitTest.java => ProductInfoRepositoryIntegrationTest.java} (98%) delete mode 100644 aws-modules/aws-miscellaneous/src/main/java/com/baeldung/dynamodb/entity/ProductInfo.java delete mode 100644 aws-modules/aws-miscellaneous/src/main/java/com/baeldung/dynamodb/repository/AbstractRepository.java delete mode 100644 aws-modules/aws-miscellaneous/src/main/java/com/baeldung/dynamodb/repository/ProductInfoRepository.java diff --git a/aws-modules/aws-dynamodb/pom.xml b/aws-modules/aws-dynamodb/pom.xml index eee01badf3..37b88327f4 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 @@ -16,14 +16,9 @@ - commons-io - commons-io - ${commons-io.version} - - - com.google.code.gson - gson - ${gson.version} + com.amazonaws + aws-java-sdk + ${aws-java-sdk.version} com.amazonaws @@ -32,9 +27,14 @@ test - com.amazonaws - aws-java-sdk-dynamodb - ${aws-java-sdk.version} + commons-io + commons-io + ${commons-io.version} + + + com.google.code.gson + gson + ${gson.version} @@ -81,8 +81,6 @@ 2.8.0 1.21.1 - 1.10.L001 - 0.9.4.0006L 3.1.1 diff --git a/aws-modules/aws-dynamodb/src/main/resources/db.properties b/aws-modules/aws-dynamodb/src/main/resources/db.properties deleted file mode 100644 index e934611a2b..0000000000 --- a/aws-modules/aws-dynamodb/src/main/resources/db.properties +++ /dev/null @@ -1,4 +0,0 @@ -db_hostname= -db_username=username -db_password=password -db_database=mydb \ No newline at end of file diff --git a/aws-modules/aws-dynamodb/src/test/java/com/baeldung/dynamodb/ProductInfoRepositoryUnitTest.java b/aws-modules/aws-dynamodb/src/test/java/com/baeldung/dynamodb/ProductInfoRepositoryIntegrationTest.java similarity index 98% rename from aws-modules/aws-dynamodb/src/test/java/com/baeldung/dynamodb/ProductInfoRepositoryUnitTest.java rename to aws-modules/aws-dynamodb/src/test/java/com/baeldung/dynamodb/ProductInfoRepositoryIntegrationTest.java index 617a35bd00..e4dc0c65b8 100644 --- a/aws-modules/aws-dynamodb/src/test/java/com/baeldung/dynamodb/ProductInfoRepositoryUnitTest.java +++ b/aws-modules/aws-dynamodb/src/test/java/com/baeldung/dynamodb/ProductInfoRepositoryIntegrationTest.java @@ -29,7 +29,7 @@ import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsEqual.equalTo; import static org.junit.Assert.assertThat; -public class ProductInfoRepositoryUnitTest { +public class ProductInfoRepositoryIntegrationTest { @ClassRule public static LocalDbCreationRule dynamoDB = new LocalDbCreationRule(); diff --git a/aws-modules/aws-miscellaneous/src/main/java/com/baeldung/dynamodb/entity/ProductInfo.java b/aws-modules/aws-miscellaneous/src/main/java/com/baeldung/dynamodb/entity/ProductInfo.java deleted file mode 100644 index 9af5d926c9..0000000000 --- a/aws-modules/aws-miscellaneous/src/main/java/com/baeldung/dynamodb/entity/ProductInfo.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.baeldung.dynamodb.entity; - -import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute; -import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAutoGeneratedKey; -import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; -import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; - -@DynamoDBTable(tableName = "ProductInfo") -public class ProductInfo { - - private String id; - private String msrp; - private String cost; - - public ProductInfo() { - } - - public ProductInfo(String cost, String msrp) { - this.msrp = msrp; - this.cost = cost; - } - - @DynamoDBHashKey - @DynamoDBAutoGeneratedKey - public String getId() { - return id; - } - - @DynamoDBAttribute - public String getMsrp() { - return msrp; - } - - @DynamoDBAttribute - public String getCost() { - return cost; - } - - public void setId(String id) { - this.id = id; - } - - public void setMsrp(String msrp) { - this.msrp = msrp; - } - - public void setCost(String cost) { - this.cost = cost; - } - -} diff --git a/aws-modules/aws-miscellaneous/src/main/java/com/baeldung/dynamodb/repository/AbstractRepository.java b/aws-modules/aws-miscellaneous/src/main/java/com/baeldung/dynamodb/repository/AbstractRepository.java deleted file mode 100644 index 79934c17e9..0000000000 --- a/aws-modules/aws-miscellaneous/src/main/java/com/baeldung/dynamodb/repository/AbstractRepository.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.baeldung.dynamodb.repository; - -import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; -import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBScanExpression; - -import java.io.Serializable; -import java.lang.reflect.ParameterizedType; -import java.util.List; - -public abstract class AbstractRepository { - - protected DynamoDBMapper mapper; - protected Class entityClass; - - protected AbstractRepository() { - ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass(); - - // This entityClass refers to the actual entity class in the subclass declaration. - - // For instance, ProductInfoDAO extends AbstractDAO - // In this case entityClass = ProductInfo, and ID is String type - // which refers to the ProductInfo's partition key string value - this.entityClass = (Class) genericSuperclass.getActualTypeArguments()[0]; - } - - public void save(T t) { - mapper.save(t); - } - - public T findOne(ID id) { - return mapper.load(entityClass, id); - } - - /** - * WARNING: It is not recommended to perform full table scan - * targeting the real production environment. - * - * @return All items - */ - public List findAll() { - DynamoDBScanExpression scanExpression = new DynamoDBScanExpression(); - return mapper.scan(entityClass, scanExpression); - } - - public void setMapper(DynamoDBMapper dynamoDBMapper) { - this.mapper = dynamoDBMapper; - } - -} diff --git a/aws-modules/aws-miscellaneous/src/main/java/com/baeldung/dynamodb/repository/ProductInfoRepository.java b/aws-modules/aws-miscellaneous/src/main/java/com/baeldung/dynamodb/repository/ProductInfoRepository.java deleted file mode 100644 index 0dfec8e05c..0000000000 --- a/aws-modules/aws-miscellaneous/src/main/java/com/baeldung/dynamodb/repository/ProductInfoRepository.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.baeldung.dynamodb.repository; - -import com.baeldung.dynamodb.entity.ProductInfo; - -public class ProductInfoRepository extends AbstractRepository { -} From b7f3161bc517278aec132fedbd799c63bd896973 Mon Sep 17 00:00:00 2001 From: Kai Yuan Date: Mon, 9 Oct 2023 04:30:55 +0200 Subject: [PATCH 21/37] [bin-int-to-str] zero-padded binary string representation (#14885) --- .../IntegerToBinaryUnitTest.java | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/core-java-modules/core-java-numbers-3/src/test/java/com/baeldung/integerToBinary/IntegerToBinaryUnitTest.java b/core-java-modules/core-java-numbers-3/src/test/java/com/baeldung/integerToBinary/IntegerToBinaryUnitTest.java index 38ae79f2f5..9439f012e3 100644 --- a/core-java-modules/core-java-numbers-3/src/test/java/com/baeldung/integerToBinary/IntegerToBinaryUnitTest.java +++ b/core-java-modules/core-java-numbers-3/src/test/java/com/baeldung/integerToBinary/IntegerToBinaryUnitTest.java @@ -1,6 +1,8 @@ package com.baeldung.integerToBinary; +import org.apache.commons.lang3.StringUtils; import org.junit.Test; + import static org.junit.Assert.assertEquals; public class IntegerToBinaryUnitTest { @@ -24,4 +26,18 @@ public class IntegerToBinaryUnitTest { String binaryString = Integer.toString(n, 2); assertEquals("111", binaryString); } -} + + @Test + public void givenAnInteger_whenFormatAndReplaceCalled_thenZeroPaddedBinaryString() { + int n = 7; + String binaryString = String.format("%8s", Integer.toBinaryString(n)).replace(" ", "0"); + assertEquals("00000111", binaryString); + } + + @Test + public void givenAnInteger_whenUsingApacheStringUtils_thenZeroPaddedBinaryString() { + int n = 7; + String binaryString = StringUtils.leftPad(Integer.toBinaryString(n), 8, "0"); + assertEquals("00000111", binaryString); + } +} \ No newline at end of file From 0e7c032aa8c67fcd06a8e4a5d217ad2f8c4e3e22 Mon Sep 17 00:00:00 2001 From: Rufina Uche <102101377+Finniki@users.noreply.github.com> Date: Mon, 9 Oct 2023 08:53:46 +0100 Subject: [PATCH 22/37] Javadoublevsbigdecimal (#14862) * Create BigDecimalConversionUnitTest.java * Add files via upload * Update BigDecimalConversionUnitTest.java * Update BigDecimalConversionUnitTest.java * Update BigDecimalConversionUnitTest.java --- .../BigDecimalConversionUnitTest.java | 28 +++++++++++++ .../BigDecimalUnitTest.java | 42 +++++++++++++++++++ .../JavaDoubleUnitTest.java | 15 +++++++ 3 files changed, 85 insertions(+) create mode 100644 core-java-modules/core-java-numbers-6/src/test/java/com/baeldung/javadoublevsbigdecimal/BigDecimalConversionUnitTest.java create mode 100644 core-java-modules/core-java-numbers-6/src/test/java/com/baeldung/javadoublevsbigdecimal/BigDecimalUnitTest.java create mode 100644 core-java-modules/core-java-numbers-6/src/test/java/com/baeldung/javadoublevsbigdecimal/JavaDoubleUnitTest.java diff --git a/core-java-modules/core-java-numbers-6/src/test/java/com/baeldung/javadoublevsbigdecimal/BigDecimalConversionUnitTest.java b/core-java-modules/core-java-numbers-6/src/test/java/com/baeldung/javadoublevsbigdecimal/BigDecimalConversionUnitTest.java new file mode 100644 index 0000000000..76c218d85f --- /dev/null +++ b/core-java-modules/core-java-numbers-6/src/test/java/com/baeldung/javadoublevsbigdecimal/BigDecimalConversionUnitTest.java @@ -0,0 +1,28 @@ +package com.baeldung.javadoublevsbigdecimal; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +import java.math.BigDecimal; +import java.math.RoundingMode; + +import org.junit.jupiter.api.Test; + +public class BigDecimalConversionUnitTest { + + @Test + void whenConvertingDoubleToBigDecimal_thenConversionIsCorrect() { + double doubleValue = 123.456; + BigDecimal bigDecimalValue = BigDecimal.valueOf(doubleValue); + BigDecimal expected = new BigDecimal("123.456").setScale(3, RoundingMode.HALF_UP); + assertEquals(expected, bigDecimalValue.setScale(3, RoundingMode.HALF_UP)); + } + + @Test + void givenDecimalPlacesGreaterThan15_whenConvertingBigDecimalToDouble_thenPrecisionIsLost() { + BigDecimal bigDecimalValue = new BigDecimal("789.1234567890123456"); + double doubleValue = bigDecimalValue.doubleValue(); + BigDecimal convertedBackToBigDecimal = BigDecimal.valueOf(doubleValue); + assertNotEquals(bigDecimalValue, convertedBackToBigDecimal); + } +} diff --git a/core-java-modules/core-java-numbers-6/src/test/java/com/baeldung/javadoublevsbigdecimal/BigDecimalUnitTest.java b/core-java-modules/core-java-numbers-6/src/test/java/com/baeldung/javadoublevsbigdecimal/BigDecimalUnitTest.java new file mode 100644 index 0000000000..3ee611f315 --- /dev/null +++ b/core-java-modules/core-java-numbers-6/src/test/java/com/baeldung/javadoublevsbigdecimal/BigDecimalUnitTest.java @@ -0,0 +1,42 @@ +package com.baeldung.javadoublevsbigdecimal; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.math.BigDecimal; +import java.math.RoundingMode; + +import org.junit.jupiter.api.Test; + +public class BigDecimalUnitTest { + + private BigDecimal bigDecimal1 = new BigDecimal("124567890.0987654321"); + private BigDecimal bigDecimal2 = new BigDecimal("987654321.123456789"); + + @Test + public void givenTwoBigDecimals_whenAdd_thenCorrect() { + BigDecimal expected = new BigDecimal("1112222211.2222222211"); + BigDecimal actual = bigDecimal1.add(bigDecimal2); + assertEquals(expected, actual); + } + + @Test + public void givenTwoBigDecimals_whenMultiply_thenCorrect() { + BigDecimal expected = new BigDecimal("123030014929277547.5030955772112635269"); + BigDecimal actual = bigDecimal1.multiply(bigDecimal2); + assertEquals(expected, actual); + } + + @Test + public void givenTwoBigDecimals_whenSubtract_thenCorrect() { + BigDecimal expected = new BigDecimal("-863086431.0246913569"); + BigDecimal actual = bigDecimal1.subtract(bigDecimal2); + assertEquals(expected, actual); + } + + @Test + public void givenTwoBigDecimals_whenDivide_thenCorrect() { + BigDecimal expected = new BigDecimal("0.13"); + BigDecimal actual = bigDecimal1.divide(bigDecimal2, 2, RoundingMode.HALF_UP); + assertEquals(expected, actual); + } +} diff --git a/core-java-modules/core-java-numbers-6/src/test/java/com/baeldung/javadoublevsbigdecimal/JavaDoubleUnitTest.java b/core-java-modules/core-java-numbers-6/src/test/java/com/baeldung/javadoublevsbigdecimal/JavaDoubleUnitTest.java new file mode 100644 index 0000000000..8697e1bfce --- /dev/null +++ b/core-java-modules/core-java-numbers-6/src/test/java/com/baeldung/javadoublevsbigdecimal/JavaDoubleUnitTest.java @@ -0,0 +1,15 @@ +package com.baeldung.javadoublevsbigdecimal; + +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.Test; + +public class JavaDoubleUnitTest { + + @Test + public void givenDoubleLiteral_whenAssigningToDoubleVariable_thenValueIsNotExactlyEqual() { + double doubleValue = 0.1; + double epsilon = 0.0000000000000001; + assertEquals(0.1, doubleValue, epsilon); + } +} From 901951bff763b3cc4df554d077f6d5930425a5e4 Mon Sep 17 00:00:00 2001 From: Harry9656 Date: Mon, 9 Oct 2023 09:53:54 +0200 Subject: [PATCH 23/37] BAEL-6898: Add Debug property for ssl Handshakes (#14822) --- .../java/com/baeldung/ssl/SecureConnection.java | 14 +++++++------- .../com/baeldung/ssl/example/SimpleClient.java | 7 +++---- .../com/baeldung/ssl/example/SimpleServer.java | 8 ++++---- 3 files changed, 14 insertions(+), 15 deletions(-) diff --git a/core-java-modules/core-java-security/src/main/java/com/baeldung/ssl/SecureConnection.java b/core-java-modules/core-java-security/src/main/java/com/baeldung/ssl/SecureConnection.java index 36dee603eb..6f2e3250fc 100644 --- a/core-java-modules/core-java-security/src/main/java/com/baeldung/ssl/SecureConnection.java +++ b/core-java-modules/core-java-security/src/main/java/com/baeldung/ssl/SecureConnection.java @@ -7,7 +7,7 @@ import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; public class SecureConnection { - + public static void main(String[] args) { if (args.length != 2) { System.out.println("Use: SecureConnection host port"); @@ -20,20 +20,20 @@ public class SecureConnection { SSLSocket sslsocket = (SSLSocket) sslsocketfactory.createSocket(host, port); InputStream in = sslsocket.getInputStream(); OutputStream out = sslsocket.getOutputStream(); - + out.write(1); - + while (in.available() > 0) { System.out.print(in.read()); } - + System.out.println("Secured connection performed successfully"); - + } catch (Exception exception) { exception.printStackTrace(); } } - + /** * Get the host from arguments * @param args the arguments @@ -42,7 +42,7 @@ public class SecureConnection { private static String getHost(String[] args) { return args[0]; } - + /** * Get the port from arguments * @param args the arguments diff --git a/core-java-modules/core-java-security/src/main/java/com/baeldung/ssl/example/SimpleClient.java b/core-java-modules/core-java-security/src/main/java/com/baeldung/ssl/example/SimpleClient.java index d6efc34c3e..cf9a76b39a 100644 --- a/core-java-modules/core-java-security/src/main/java/com/baeldung/ssl/example/SimpleClient.java +++ b/core-java-modules/core-java-security/src/main/java/com/baeldung/ssl/example/SimpleClient.java @@ -15,10 +15,8 @@ public class SimpleClient { SocketFactory factory = SSLSocketFactory.getDefault(); try (Socket connection = factory.createSocket(host, port)) { - ((SSLSocket) connection).setEnabledCipherSuites( - new String[] { "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256"}); - ((SSLSocket) connection).setEnabledProtocols( - new String[] { "TLSv1.2"}); + ((SSLSocket) connection).setEnabledCipherSuites(new String[] { "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256" }); + ((SSLSocket) connection).setEnabledProtocols(new String[] { "TLSv1.2" }); SSLParameters sslParams = new SSLParameters(); sslParams.setEndpointIdentificationAlgorithm("HTTPS"); ((SSLSocket) connection).setSSLParameters(sslParams); @@ -28,6 +26,7 @@ public class SimpleClient { } public static void main(String[] args) throws IOException { + System.setProperty("javax.net.debug", "ssl:handshake"); System.out.println(startClient("localhost", 8443)); } } diff --git a/core-java-modules/core-java-security/src/main/java/com/baeldung/ssl/example/SimpleServer.java b/core-java-modules/core-java-security/src/main/java/com/baeldung/ssl/example/SimpleServer.java index 27d15d04d7..83946ccc1f 100644 --- a/core-java-modules/core-java-security/src/main/java/com/baeldung/ssl/example/SimpleServer.java +++ b/core-java-modules/core-java-security/src/main/java/com/baeldung/ssl/example/SimpleServer.java @@ -14,11 +14,10 @@ public class SimpleServer { ServerSocketFactory factory = SSLServerSocketFactory.getDefault(); try (ServerSocket listener = factory.createServerSocket(port)) { + System.setProperty("javax.net.debug", "ssl:handshake"); ((SSLServerSocket) listener).setNeedClientAuth(true); - ((SSLServerSocket) listener).setEnabledCipherSuites( - new String[] { "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256"}); - ((SSLServerSocket) listener).setEnabledProtocols( - new String[] { "TLSv1.2"}); + ((SSLServerSocket) listener).setEnabledCipherSuites(new String[] { "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256" }); + ((SSLServerSocket) listener).setEnabledProtocols(new String[] { "TLSv1.2" }); while (true) { try (Socket socket = listener.accept()) { PrintWriter out = new PrintWriter(socket.getOutputStream(), true); @@ -29,6 +28,7 @@ public class SimpleServer { } public static void main(String[] args) throws IOException { + System.setProperty("javax.net.debug", "ssl:handshake"); startServer(8443); } } \ No newline at end of file From 52f4344bceeece2e05d4a515bac46d7d8fcfb313 Mon Sep 17 00:00:00 2001 From: Azhwani <13301425+azhwani@users.noreply.github.com> Date: Mon, 9 Oct 2023 09:55:29 +0200 Subject: [PATCH 24/37] BAEL-7057: How to convert CharSequence to String? (#14892) --- .../CharSequenceVsStringUnitTest.java | 43 ++++++++++++++++++- 1 file changed, 41 insertions(+), 2 deletions(-) diff --git a/core-java-modules/core-java-string-apis/src/test/java/com/baeldung/charsequence/CharSequenceVsStringUnitTest.java b/core-java-modules/core-java-string-apis/src/test/java/com/baeldung/charsequence/CharSequenceVsStringUnitTest.java index aa15345bcb..13a0407a98 100644 --- a/core-java-modules/core-java-string-apis/src/test/java/com/baeldung/charsequence/CharSequenceVsStringUnitTest.java +++ b/core-java-modules/core-java-string-apis/src/test/java/com/baeldung/charsequence/CharSequenceVsStringUnitTest.java @@ -1,11 +1,11 @@ package com.baeldung.charsequence; -import org.junit.Test; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; +import org.junit.Test; + public class CharSequenceVsStringUnitTest { @Test @@ -44,4 +44,43 @@ public class CharSequenceVsStringUnitTest { assertEquals(firstAddressOfTest, secondAddressOfTest); } + + @Test + public void givenCharSequenceAsString_whenConvertingUsingCasting_thenCorrect() { + String expected = "baeldung"; + CharSequence charSequence = "baeldung"; + String explicitCastedString = (String) charSequence; + + assertEquals(expected, charSequence); + assertEquals(expected, explicitCastedString); + } + + @Test(expected = ClassCastException.class) + public void givenCharSequenceAsStringBuiler_whenConvertingUsingCasting_thenThrowException() { + CharSequence charSequence = new StringBuilder("baeldung"); + String castedString = (String) charSequence; + } + + @Test + public void givenCharSequence_whenConvertingUsingToString_thenCorrect() { + String expected = "baeldung"; + CharSequence charSequence1 = "baeldung"; + CharSequence charSequence2 = new StringBuilder("baeldung"); + + assertEquals(expected, charSequence1.toString()); + assertEquals(expected, charSequence2.toString()); + } + + @Test + public void givenCharSequence_whenConvertingUsingValueOf_thenCorrect() { + String expected = "baeldung"; + CharSequence charSequence1 = "baeldung"; + CharSequence charSequence2 = new StringBuilder("baeldung"); + CharSequence charSequence3 = null; + + assertEquals(expected, String.valueOf(charSequence1)); + assertEquals(expected, String.valueOf(charSequence2)); + assertEquals("null", String.valueOf(charSequence3)); + } + } From 1f3252df75b2381fd8d11016b5925c8d1910ed12 Mon Sep 17 00:00:00 2001 From: Azhwani <13301425+azhwani@users.noreply.github.com> Date: Mon, 9 Oct 2023 09:57:03 +0200 Subject: [PATCH 25/37] BAEL-6714: Convert Char Array to Int Array in Java (#14875) --- .../conversions/CharArrayToIntArrayUtils.java | 67 +++++++++++++++++++ .../CharArrayToIntArrayUtilsUnitTest.java | 54 +++++++++++++++ 2 files changed, 121 insertions(+) create mode 100644 core-java-modules/core-java-arrays-convert/src/main/java/com/baeldung/array/conversions/CharArrayToIntArrayUtils.java create mode 100644 core-java-modules/core-java-arrays-convert/src/test/java/com/baeldung/array/conversions/CharArrayToIntArrayUtilsUnitTest.java diff --git a/core-java-modules/core-java-arrays-convert/src/main/java/com/baeldung/array/conversions/CharArrayToIntArrayUtils.java b/core-java-modules/core-java-arrays-convert/src/main/java/com/baeldung/array/conversions/CharArrayToIntArrayUtils.java new file mode 100644 index 0000000000..fbd76a0113 --- /dev/null +++ b/core-java-modules/core-java-arrays-convert/src/main/java/com/baeldung/array/conversions/CharArrayToIntArrayUtils.java @@ -0,0 +1,67 @@ +package com.baeldung.array.conversions; + +import java.util.Arrays; + +public class CharArrayToIntArrayUtils { + + static int[] usingGetNumericValueMethod(char[] chars) { + if (chars == null) { + return null; + } + + int[] ints = new int[chars.length]; + for (int i = 0; i < chars.length; i++) { + ints[i] = Character.getNumericValue(chars[i]); + } + + return ints; + } + + static int[] usingDigitMethod(char[] chars) { + if (chars == null) { + return null; + } + + int[] ints = new int[chars.length]; + for (int i = 0; i < chars.length; i++) { + ints[i] = Character.digit(chars[i], 10); + } + + return ints; + } + + static int[] usingStreamApiMethod(char[] chars) { + if (chars == null) { + return null; + } + + return new String(chars).chars() + .map(c -> c - 48) + .toArray(); + } + + static int[] usingParseIntMethod(char[] chars) { + if (chars == null) { + return null; + } + + int[] ints = new int[chars.length]; + for (int i = 0; i < chars.length; i++) { + ints[i] = Integer.parseInt(String.valueOf(chars[i])); + } + + return ints; + } + + static int[] usingArraysSetAllMethod(char[] chars) { + if (chars == null) { + return null; + } + + int[] ints = new int[chars.length]; + Arrays.setAll(ints, i -> Character.getNumericValue(chars[i])); + + return ints; + } + +} diff --git a/core-java-modules/core-java-arrays-convert/src/test/java/com/baeldung/array/conversions/CharArrayToIntArrayUtilsUnitTest.java b/core-java-modules/core-java-arrays-convert/src/test/java/com/baeldung/array/conversions/CharArrayToIntArrayUtilsUnitTest.java new file mode 100644 index 0000000000..534dc3893f --- /dev/null +++ b/core-java-modules/core-java-arrays-convert/src/test/java/com/baeldung/array/conversions/CharArrayToIntArrayUtilsUnitTest.java @@ -0,0 +1,54 @@ +package com.baeldung.array.conversions; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; + +import org.junit.jupiter.api.Test; + +class CharArrayToIntArrayUtilsUnitTest { + + @Test + void givenCharArray_whenUsingGetNumericValueMethod_shouldGetIntArray() { + int[] expected = { 2, 3, 4, 5 }; + char[] chars = { '2', '3', '4', '5' }; + int[] result = CharArrayToIntArrayUtils.usingGetNumericValueMethod(chars); + + assertArrayEquals(expected, result); + } + + @Test + void givenCharArray_whenUsingDigitMethod_shouldGetIntArray() { + int[] expected = { 1, 2, 3, 6 }; + char[] chars = { '1', '2', '3', '6' }; + int[] result = CharArrayToIntArrayUtils.usingDigitMethod(chars); + + assertArrayEquals(expected, result); + } + + @Test + void givenCharArray_whenUsingStreamApi_shouldGetIntArray() { + int[] expected = { 9, 8, 7, 6 }; + char[] chars = { '9', '8', '7', '6' }; + int[] result = CharArrayToIntArrayUtils.usingStreamApiMethod(chars); + + assertArrayEquals(expected, result); + } + + @Test + void givenCharArray_whenUsingParseIntMethod_shouldGetIntArray() { + int[] expected = { 9, 8, 7, 6 }; + char[] chars = { '9', '8', '7', '6' }; + int[] result = CharArrayToIntArrayUtils.usingParseIntMethod(chars); + + assertArrayEquals(expected, result); + } + + @Test + void givenCharArray_whenUsingArraysSetAllMethod_shouldGetIntArray() { + int[] expected = { 4, 9, 2, 3 }; + char[] chars = { '4', '9', '2', '3' }; + int[] result = CharArrayToIntArrayUtils.usingArraysSetAllMethod(chars); + + assertArrayEquals(expected, result); + } + +} From bb29bb9dcd1582376ac8bdd67c3d67c192ff39c7 Mon Sep 17 00:00:00 2001 From: Mo Helmy <135069400+BenHelmyBen@users.noreply.github.com> Date: Mon, 9 Oct 2023 14:17:30 +0300 Subject: [PATCH 26/37] Adding the new module to the main pom (#14924) * This commit related to the article BAEL-6877 This commit aims to add a new Java module "core-java-collections-maps-7" * Update pom.xml --- core-java-modules/pom.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml index cd31bb5845..ae9ff59222 100644 --- a/core-java-modules/pom.xml +++ b/core-java-modules/pom.xml @@ -83,6 +83,7 @@ core-java-collections-maps core-java-collections-maps-2 core-java-collections-maps-3 + core-java-collections-maps-7 core-java-compiler core-java-concurrency-2 core-java-concurrency-advanced From ff6d3e73935c9ad1243ff4e7c49a087d84ca9a28 Mon Sep 17 00:00:00 2001 From: mdabrowski-eu <57441874+mdabrowski-eu@users.noreply.github.com> Date: Mon, 9 Oct 2023 13:33:39 +0200 Subject: [PATCH 27/37] BAEL-6911 fix dependencies issues, add missing snipets (#14935) --- spring-boot-modules/spring-boot-3/pom.xml | 8 ++- .../java/com/baeldung/restclient/Article.java | 10 +++ .../restclient/ArticleController.java | 19 ++++-- .../restclient/ArticleNotFoundException.java | 6 ++ .../InvalidArticleResponseException.java | 6 ++ .../restclient/RestClientIntegrationTest.java | 66 +++++++++++++++++-- 6 files changed, 101 insertions(+), 14 deletions(-) create mode 100644 spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/restclient/ArticleNotFoundException.java create mode 100644 spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/restclient/InvalidArticleResponseException.java diff --git a/spring-boot-modules/spring-boot-3/pom.xml b/spring-boot-modules/spring-boot-3/pom.xml index 7dd44c89dc..bb8c5dd53c 100644 --- a/spring-boot-modules/spring-boot-3/pom.xml +++ b/spring-boot-modules/spring-boot-3/pom.xml @@ -60,7 +60,11 @@ org.junit.jupiter junit-jupiter-params ${jupiter.version} - test + + + org.junit.platform + junit-platform-commons + 1.10.0 org.mock-server @@ -204,7 +208,7 @@ 19 1.5.2.Final - 2.0.0 + 2.2.0 3.0.0-M7 com.baeldung.sample.TodoApplication 5.14.0 diff --git a/spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/restclient/Article.java b/spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/restclient/Article.java index a69d5989af..892cf3b5ae 100644 --- a/spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/restclient/Article.java +++ b/spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/restclient/Article.java @@ -6,6 +6,8 @@ public class Article { Integer id; String title; + public Article() {} + public Article(Integer id, String title) { this.id = id; this.title = title; @@ -19,6 +21,14 @@ public class Article { return title; } + public void setId(Integer id) { + this.id = id; + } + + public void setTitle(String title) { + this.title = title; + } + @Override public boolean equals(Object o) { if (this == o) return true; diff --git a/spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/restclient/ArticleController.java b/spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/restclient/ArticleController.java index 62922bdcee..5e1dff6fd7 100644 --- a/spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/restclient/ArticleController.java +++ b/spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/restclient/ArticleController.java @@ -1,5 +1,6 @@ package com.baeldung.restclient; +import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.Collection; @@ -13,13 +14,21 @@ public class ArticleController { Map database = new HashMap<>(); @GetMapping - public Collection
getArticles() { - return database.values(); + public ResponseEntity> getArticles() { + Collection
values = database.values(); + if (values.isEmpty()) { + return ResponseEntity.noContent().build(); + } + return ResponseEntity.ok(values); } @GetMapping("/{id}") - public Article getArticle(@PathVariable Integer id) { - return database.get(id); + public ResponseEntity
getArticle(@PathVariable("id") Integer id) { + Article article = database.get(id); + if (article == null) { + return ResponseEntity.notFound().build(); + } + return ResponseEntity.ok(article); } @PostMapping @@ -28,7 +37,7 @@ public class ArticleController { } @PutMapping("/{id}") - public void updateArticle(@PathVariable Integer id, @RequestBody Article article) { + public void updateArticle(@PathVariable("id") Integer id, @RequestBody Article article) { assert Objects.equals(id, article.getId()); database.remove(id); database.put(id, article); diff --git a/spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/restclient/ArticleNotFoundException.java b/spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/restclient/ArticleNotFoundException.java new file mode 100644 index 0000000000..cdd13b8330 --- /dev/null +++ b/spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/restclient/ArticleNotFoundException.java @@ -0,0 +1,6 @@ +package com.baeldung.restclient; + +public class ArticleNotFoundException extends RuntimeException { + public ArticleNotFoundException() { + } +} diff --git a/spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/restclient/InvalidArticleResponseException.java b/spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/restclient/InvalidArticleResponseException.java new file mode 100644 index 0000000000..26ca75036e --- /dev/null +++ b/spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/restclient/InvalidArticleResponseException.java @@ -0,0 +1,6 @@ +package com.baeldung.restclient; + +public class InvalidArticleResponseException extends RuntimeException { + public InvalidArticleResponseException() { + } +} diff --git a/spring-boot-modules/spring-boot-3/src/test/java/com/baeldung/restclient/RestClientIntegrationTest.java b/spring-boot-modules/spring-boot-3/src/test/java/com/baeldung/restclient/RestClientIntegrationTest.java index 92474c88f0..1a615faf4e 100644 --- a/spring-boot-modules/spring-boot-3/src/test/java/com/baeldung/restclient/RestClientIntegrationTest.java +++ b/spring-boot-modules/spring-boot-3/src/test/java/com/baeldung/restclient/RestClientIntegrationTest.java @@ -1,17 +1,23 @@ package com.baeldung.restclient; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpStatusCode; import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestClient; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @@ -22,7 +28,10 @@ public class RestClientIntegrationTest { private String uriBase; RestClient restClient = RestClient.create(); - @BeforeAll + @Autowired + ObjectMapper objectMapper; + + @BeforeEach public void setup() { uriBase = "http://localhost:" + port; } @@ -42,7 +51,7 @@ public class RestClientIntegrationTest { .retrieve() .body(String.class); - assertThat(articlesAsString).isEqualTo("[]"); + assertThat(articlesAsString).isEqualTo(""); } @Test @@ -63,6 +72,48 @@ public class RestClientIntegrationTest { assertThat(articles).isEqualTo(List.of(article)); } + @Test + void shouldPostAndGetArticlesWithExchange() { + assertThatThrownBy(this::getArticlesWithExchange).isInstanceOf(ArticleNotFoundException.class); + + Article article = new Article(1, "How to use RestClient"); + restClient.post() + .uri(uriBase + "/articles") + .contentType(MediaType.APPLICATION_JSON) + .body(article) + .retrieve() + .toBodilessEntity(); + + List
articles = getArticlesWithExchange(); + + assertThat(articles).isEqualTo(List.of(article)); + } + + private List
getArticlesWithExchange() { + return restClient.get() + .uri(uriBase + "/articles") + .exchange((request, response) -> { + if (response.getStatusCode().isSameCodeAs(HttpStatusCode.valueOf(204))) { + throw new ArticleNotFoundException(); + } else if (response.getStatusCode().isSameCodeAs(HttpStatusCode.valueOf(200))) { + return objectMapper.readValue(response.getBody(), new TypeReference<>() {}); + } else { + throw new InvalidArticleResponseException(); + } + }); + } + + @Test + void shouldPostAndGetArticlesWithErrorHandling() { + assertThatThrownBy(() -> { + restClient.get() + .uri(uriBase + "/articles/1234") + .retrieve() + .onStatus(status -> status.value() == 404, (request, response) -> { throw new ArticleNotFoundException(); }) + .body(new ParameterizedTypeReference<>() {}); + }).isInstanceOf(ArticleNotFoundException.class); + } + @Test void shouldPostAndPutAndGetArticles() { Article article = new Article(1, "How to use RestClient"); @@ -79,7 +130,7 @@ public class RestClientIntegrationTest { .contentType(MediaType.APPLICATION_JSON) .body(articleChanged) .retrieve() - .toBodilessEntity(); + .toBodilessEntity(); List
articles = restClient.get() .uri(uriBase + "/articles") @@ -104,11 +155,12 @@ public class RestClientIntegrationTest { .retrieve() .toBodilessEntity(); - List
articles = restClient.get() + ResponseEntity entity = restClient.get() .uri(uriBase + "/articles") + .accept(MediaType.APPLICATION_JSON) .retrieve() - .body(new ParameterizedTypeReference<>() {}); + .toBodilessEntity(); - assertThat(articles).isEqualTo(List.of()); + assertThat(entity.getStatusCode()).isEqualTo(HttpStatusCode.valueOf(204)); } } From 8ffbb095da59585553a065426dc43ea227cf9a75 Mon Sep 17 00:00:00 2001 From: Bhaskar Ghosh Dastidar Date: Tue, 10 Oct 2023 01:29:52 +0530 Subject: [PATCH 28/37] [BAEL-6955] finalization deprcation (#14932) Co-authored-by: Bhaskar --- core-java-modules/core-java-18/README.md | 0 core-java-modules/core-java-18/pom.xml | 55 +++++++++++++++++++ .../FinalizationExamples.java | 27 +++++++++ .../MyCleanerResourceClass.java | 48 ++++++++++++++++ .../MyCloseableResourceClass.java | 25 +++++++++ .../MyFinalizableResourceClass.java | 24 ++++++++ .../core-java-18/src/main/resources/file.txt | 1 + .../FinalizationCloseableCleanerUnitTest.java | 36 ++++++++++++ 8 files changed, 216 insertions(+) create mode 100644 core-java-modules/core-java-18/README.md create mode 100644 core-java-modules/core-java-18/pom.xml create mode 100644 core-java-modules/core-java-18/src/main/java/com/baeldung/finalization_closeable_cleaner/FinalizationExamples.java create mode 100644 core-java-modules/core-java-18/src/main/java/com/baeldung/finalization_closeable_cleaner/MyCleanerResourceClass.java create mode 100644 core-java-modules/core-java-18/src/main/java/com/baeldung/finalization_closeable_cleaner/MyCloseableResourceClass.java create mode 100644 core-java-modules/core-java-18/src/main/java/com/baeldung/finalization_closeable_cleaner/MyFinalizableResourceClass.java create mode 100644 core-java-modules/core-java-18/src/main/resources/file.txt create mode 100644 core-java-modules/core-java-18/src/test/java/com/baeldung/finalization_closeable_cleaner/FinalizationCloseableCleanerUnitTest.java diff --git a/core-java-modules/core-java-18/README.md b/core-java-modules/core-java-18/README.md new file mode 100644 index 0000000000..e69de29bb2 diff --git a/core-java-modules/core-java-18/pom.xml b/core-java-modules/core-java-18/pom.xml new file mode 100644 index 0000000000..7af6258497 --- /dev/null +++ b/core-java-modules/core-java-18/pom.xml @@ -0,0 +1,55 @@ + + + 4.0.0 + core-java-18 + core-java-18 + jar + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + ../../ + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven.compiler.release} + --enable-preview + ${maven.compiler.source.version} + ${maven.compiler.target.version} + + + + org.apache.maven.plugins + maven-surefire-plugin + ${surefire.plugin.version} + + 1 + + + + org.apache.maven.surefire + surefire-api + ${surefire.plugin.version} + + + + + + + + 18 + 18 + 18 + 3.0.0-M5 + + + \ No newline at end of file diff --git a/core-java-modules/core-java-18/src/main/java/com/baeldung/finalization_closeable_cleaner/FinalizationExamples.java b/core-java-modules/core-java-18/src/main/java/com/baeldung/finalization_closeable_cleaner/FinalizationExamples.java new file mode 100644 index 0000000000..3ff77c37d6 --- /dev/null +++ b/core-java-modules/core-java-18/src/main/java/com/baeldung/finalization_closeable_cleaner/FinalizationExamples.java @@ -0,0 +1,27 @@ +package com.baeldung.finalization_closeable_cleaner; + +import java.io.FileInputStream; +import java.io.IOException; + +public class FinalizationExamples { + FileInputStream fis = null; + + public void readFileOperationWithFinalization() throws IOException { + try { + fis = new FileInputStream("input.txt"); + // perform operation on the file + System.out.println(fis.readAllBytes().length); + + } finally { + if (fis != null) + fis.close(); + } + } + + public void readFileOperationWithTryWith() throws IOException { + try (FileInputStream fis = new FileInputStream("input.txt")) { + // perform operations + System.out.println(fis.readAllBytes().length); + } + } +} diff --git a/core-java-modules/core-java-18/src/main/java/com/baeldung/finalization_closeable_cleaner/MyCleanerResourceClass.java b/core-java-modules/core-java-18/src/main/java/com/baeldung/finalization_closeable_cleaner/MyCleanerResourceClass.java new file mode 100644 index 0000000000..1dcdd216cb --- /dev/null +++ b/core-java-modules/core-java-18/src/main/java/com/baeldung/finalization_closeable_cleaner/MyCleanerResourceClass.java @@ -0,0 +1,48 @@ +package com.baeldung.finalization_closeable_cleaner; + +import java.lang.ref.Cleaner; + +public class MyCleanerResourceClass implements AutoCloseable { + private static Resource resource; + + private static final Cleaner cleaner = Cleaner.create(); + private final Cleaner.Cleanable cleanable; + + public MyCleanerResourceClass() { + resource = new Resource(); + this.cleanable = cleaner.register(this, new CleaningState()); + } + + public void useResource() { + // using the resource here + resource.use(); + } + + @Override + public void close() { + // perform actions to close all underlying resources + this.cleanable.clean(); + } + + static class CleaningState implements Runnable { + CleaningState() { + // constructor + } + + @Override + public void run() { + // some cleanup action + System.out.println("Cleanup done"); + } + } + + static class Resource { + void use() { + System.out.println("Using the resource"); + } + + void close() { + System.out.println("Cleanup done"); + } + } +} diff --git a/core-java-modules/core-java-18/src/main/java/com/baeldung/finalization_closeable_cleaner/MyCloseableResourceClass.java b/core-java-modules/core-java-18/src/main/java/com/baeldung/finalization_closeable_cleaner/MyCloseableResourceClass.java new file mode 100644 index 0000000000..b11cb4e49e --- /dev/null +++ b/core-java-modules/core-java-18/src/main/java/com/baeldung/finalization_closeable_cleaner/MyCloseableResourceClass.java @@ -0,0 +1,25 @@ +package com.baeldung.finalization_closeable_cleaner; + +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; + +public class MyCloseableResourceClass implements AutoCloseable { + + private final FileInputStream fis; + + public MyCloseableResourceClass() throws FileNotFoundException { + this.fis = new FileInputStream("src/main/resources/file.txt"); + + } + + public int getByteLength() throws IOException { + System.out.println("Some operation"); + return this.fis.readAllBytes().length; + } + @Override + public void close() throws IOException { + System.out.println("Finalized object"); + this.fis.close(); + } +} diff --git a/core-java-modules/core-java-18/src/main/java/com/baeldung/finalization_closeable_cleaner/MyFinalizableResourceClass.java b/core-java-modules/core-java-18/src/main/java/com/baeldung/finalization_closeable_cleaner/MyFinalizableResourceClass.java new file mode 100644 index 0000000000..a2c6a123b4 --- /dev/null +++ b/core-java-modules/core-java-18/src/main/java/com/baeldung/finalization_closeable_cleaner/MyFinalizableResourceClass.java @@ -0,0 +1,24 @@ +package com.baeldung.finalization_closeable_cleaner; + +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; + +public class MyFinalizableResourceClass { + private FileInputStream fis; + + public MyFinalizableResourceClass() throws FileNotFoundException { + this.fis = new FileInputStream("src/main/resources/file.txt"); + } + + public int getByteLength() throws IOException { + System.out.println("Some operation"); + return this.fis.readAllBytes().length; + } + + @Override + protected void finalize() throws Throwable { + System.out.println("Finalized object"); + this.fis.close(); + } +} diff --git a/core-java-modules/core-java-18/src/main/resources/file.txt b/core-java-modules/core-java-18/src/main/resources/file.txt new file mode 100644 index 0000000000..af27ff4986 --- /dev/null +++ b/core-java-modules/core-java-18/src/main/resources/file.txt @@ -0,0 +1 @@ +This is a test file. \ No newline at end of file diff --git a/core-java-modules/core-java-18/src/test/java/com/baeldung/finalization_closeable_cleaner/FinalizationCloseableCleanerUnitTest.java b/core-java-modules/core-java-18/src/test/java/com/baeldung/finalization_closeable_cleaner/FinalizationCloseableCleanerUnitTest.java new file mode 100644 index 0000000000..22ff228227 --- /dev/null +++ b/core-java-modules/core-java-18/src/test/java/com/baeldung/finalization_closeable_cleaner/FinalizationCloseableCleanerUnitTest.java @@ -0,0 +1,36 @@ +package com.baeldung.finalization_closeable_cleaner; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import java.io.IOException; + +import org.junit.Assert; +import org.junit.Test; + +public class FinalizationCloseableCleanerUnitTest { + + @Test + public void givenMyFinalizationResource_whenUsingFinalize_thenShouldClean() { + assertDoesNotThrow(() -> { + MyFinalizableResourceClass mfr = new MyFinalizableResourceClass(); + mfr.getByteLength(); + }); + } + @Test + public void givenMyCleanerResource_whenUsingCleanerAPI_thenShouldClean() { + assertDoesNotThrow(() -> { + try (MyCleanerResourceClass myCleanerResourceClass = new MyCleanerResourceClass()) { + myCleanerResourceClass.useResource(); + } + }); + } + + @Test + public void givenCloseableResource_whenUsingTryWith_thenShouldClose() throws IOException { + int length = 0; + try (MyCloseableResourceClass mcr = new MyCloseableResourceClass()) { + length = mcr.getByteLength(); + } + Assert.assertEquals(20, length); + } +} From 150efcec722ddc89b098202593f0015ab86dde3b Mon Sep 17 00:00:00 2001 From: ACHRAF TAITAI <43656331+achraftt@users.noreply.github.com> Date: Mon, 9 Oct 2023 22:01:20 +0200 Subject: [PATCH 29/37] BAEL-6984: Deprecate URL Public Constructors in Java 20 (#14934) --- .../baeldung/networking/url/UrlUnitTest.java | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/core-java-modules/core-java-networking/src/test/java/com/baeldung/networking/url/UrlUnitTest.java b/core-java-modules/core-java-networking/src/test/java/com/baeldung/networking/url/UrlUnitTest.java index 87d9d7a620..ca04263689 100644 --- a/core-java-modules/core-java-networking/src/test/java/com/baeldung/networking/url/UrlUnitTest.java +++ b/core-java-modules/core-java-networking/src/test/java/com/baeldung/networking/url/UrlUnitTest.java @@ -2,10 +2,15 @@ package com.baeldung.networking.url; import static java.util.stream.Collectors.toList; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import java.io.IOException; import java.net.MalformedURLException; +import java.net.URI; import java.net.URISyntaxException; import java.net.URL; +import java.nio.file.Path; +import java.nio.file.Paths; import java.util.Map; import org.apache.http.client.utils.URIBuilder; @@ -149,4 +154,24 @@ public class UrlUnitTest { assertEquals("http://baeldung.com:9090/articles?topic=java&version=8", url.toString()); } + @Test + public void givenURI_whenConvertingToURL_thenCorrect() throws IOException, URISyntaxException { + String aURIString = "http://courses.baeldung.com"; + URI uri = new URI(aURIString); + URL url = uri.toURL(); + assertNotNull(url); + assertEquals(aURIString, url.toString()); + } + + @Test + public void givenPath_whenConvertingToURIAndThenURL_thenCorrect() throws IOException, URISyntaxException { + String finalPath = "file:/D:/baeldung/java-url"; + Path path = Paths.get("/baeldung/java-url"); + URI uri = path.toUri(); + URL url = uri.toURL(); + assertNotNull(url); + // Adapt the finalPath value to match your own path + // assertEquals(finalPath, url.toString()); + } + } \ No newline at end of file From 3bd2e7eb3ef9451ce624723f92194d3c293be51e Mon Sep 17 00:00:00 2001 From: Anton Dalagan Date: Mon, 9 Oct 2023 22:05:03 +0200 Subject: [PATCH 30/37] Bael 6962 convert double to float in java (#14936) * Commit 1 - Anton Dalagan Code for Evaluation article. Contains Unit tests, domain class, and App main method. * BAEL-6962 - Created unit test, and updated pom.xml * BAEL-6962 - Removed files unrelated to the article * BAEL-6962 - Added a declartions for float and double in diff class. Updated unit tests. * BAEL-6962 - Made changes into the unit tests. Removed printlns, and updated isinstance with assertequals --- .../FloatDoubleConversionsTest.java | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/floatdoubleconversions/FloatDoubleConversionsTest.java b/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/floatdoubleconversions/FloatDoubleConversionsTest.java index 10e9fd4c36..9c6b01e9de 100644 --- a/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/floatdoubleconversions/FloatDoubleConversionsTest.java +++ b/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/floatdoubleconversions/FloatDoubleConversionsTest.java @@ -9,25 +9,21 @@ public class FloatDoubleConversionsTest { public void whenDoubleType_thenFloatTypeSuccess(){ double interestRatesYearly = 13.333333333333334; float interest = (float) interestRatesYearly; - System.out.println(interest); //13.333333 - Assert.assertTrue(Float.class.isInstance(interest));//true + Assert.assertEquals(13.333333f, interest, 0.000004f); Double monthlyRates = 2.111111111111112; float rates = monthlyRates.floatValue(); - System.out.println(rates); //2.1111112 - Assert.assertTrue(Float.class.isInstance(rates));//true + Assert.assertEquals(2.1111112f, rates, 0.00000013); } @Test public void whenFloatType_thenDoubleTypeSuccess(){ float gradeAverage =2.05f; double average = gradeAverage; - System.out.println(average); //2.049999952316284 - Assert.assertTrue(Double.class.isInstance(average));//true + Assert.assertEquals(2.05, average, 0.06); Float monthlyRates = 2.1111112f; Double rates = monthlyRates.doubleValue(); - System.out.println(rates); //2.1111112 - Assert.assertTrue(Double.class.isInstance(rates));//true + Assert.assertEquals(2.11111112, rates, 0.0000002);//true } } From a3148b3dd29e283df74e9f47a83826598732ca45 Mon Sep 17 00:00:00 2001 From: Bhaskar Ghosh Dastidar Date: Tue, 10 Oct 2023 01:38:57 +0530 Subject: [PATCH 31/37] [BAEL-7035] improvement to value based class (#14938) Co-authored-by: Bhaskar --- .../main/java/com/baeldung/value_based_class/Point.java | 5 +++++ .../value_based_class/ValueBasedClassUnitTest.java | 9 ++++++--- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/core-java-modules/core-java-16/src/main/java/com/baeldung/value_based_class/Point.java b/core-java-modules/core-java-16/src/main/java/com/baeldung/value_based_class/Point.java index 13e2238274..a3055985af 100644 --- a/core-java-modules/core-java-16/src/main/java/com/baeldung/value_based_class/Point.java +++ b/core-java-modules/core-java-16/src/main/java/com/baeldung/value_based_class/Point.java @@ -30,6 +30,11 @@ public final class Point { return new Point(x, y, z); } + @Override + public String toString() { + return "Point{" + "x=" + x + ", y=" + y + ", z=" + z + '}'; + } + @Override public boolean equals(Object other) { if (other == null || getClass() != other.getClass()) diff --git a/core-java-modules/core-java-16/src/test/java/com/baeldung/value_based_class/ValueBasedClassUnitTest.java b/core-java-modules/core-java-16/src/test/java/com/baeldung/value_based_class/ValueBasedClassUnitTest.java index 781f368982..fe031a652f 100644 --- a/core-java-modules/core-java-16/src/test/java/com/baeldung/value_based_class/ValueBasedClassUnitTest.java +++ b/core-java-modules/core-java-16/src/test/java/com/baeldung/value_based_class/ValueBasedClassUnitTest.java @@ -1,14 +1,17 @@ package com.baeldung.value_based_class; +import java.util.ArrayList; +import java.util.List; + import org.junit.Assert; import org.junit.Test; public class ValueBasedClassUnitTest { @Test public void givenAutoboxedAndPrimitive_whenCompared_thenReturnEquals() { - int primitive_a = 125; - Integer obj_a = 125; // this is autoboxed - Assert.assertSame(primitive_a, obj_a); + List list = new ArrayList<>(); + list.add(1); // this is autoboxed + Assert.assertEquals(list.get(0), Integer.valueOf(1)); } @Test From a74415a7c7698e6412a7573bbc02062741627fc6 Mon Sep 17 00:00:00 2001 From: Kai Yuan Date: Tue, 10 Oct 2023 02:08:53 +0200 Subject: [PATCH 32/37] [rm-linebreaks-inFile] How to Remove Line Breaks From a File in Java (#14917) --- .../RemoveLinebreaksUnitTest.java | 72 +++++++++++++++++++ .../src/test/resources/multiple-line-1.txt | 6 ++ .../src/test/resources/multiple-line-2.txt | 4 ++ 3 files changed, 82 insertions(+) create mode 100644 core-java-modules/core-java-io-5/src/test/java/com/baeldung/rmlinebreaks/RemoveLinebreaksUnitTest.java create mode 100644 core-java-modules/core-java-io-5/src/test/resources/multiple-line-1.txt create mode 100644 core-java-modules/core-java-io-5/src/test/resources/multiple-line-2.txt diff --git a/core-java-modules/core-java-io-5/src/test/java/com/baeldung/rmlinebreaks/RemoveLinebreaksUnitTest.java b/core-java-modules/core-java-io-5/src/test/java/com/baeldung/rmlinebreaks/RemoveLinebreaksUnitTest.java new file mode 100644 index 0000000000..7cfc7ede79 --- /dev/null +++ b/core-java-modules/core-java-io-5/src/test/java/com/baeldung/rmlinebreaks/RemoveLinebreaksUnitTest.java @@ -0,0 +1,72 @@ +package com.baeldung.rmlinebreaks; + +import org.junit.jupiter.api.Test; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +public class RemoveLinebreaksUnitTest { + + private Path file1Path() throws Exception { + return Paths.get(this.getClass().getClassLoader().getResource("multiple-line-1.txt").toURI()); + } + + private Path file2Path() throws Exception { + return Paths.get(this.getClass().getClassLoader().getResource("multiple-line-2.txt").toURI()); + } + + @Test + void whenRemovingLineSeparatorFromFile1_thenGetTheExpectedResult() throws Exception { + String content = Files.readString(file1Path(), StandardCharsets.UTF_8); + + String result = content.replace(System.getProperty("line.separator"), ""); + assertEquals("A, B, C, D, E, F", result); + } + + @Test + void whenRemovingLineSeparatorFromFile2_thenNotGetTheExpectedResult() throws Exception { + String content = Files.readString(file2Path(), StandardCharsets.UTF_8); + + String result = content.replace(System.getProperty("line.separator"), ""); + assertNotEquals("A, B, C, D, E, F", result); // <-- NOT equals assertion! + } + + @Test + void whenRemovingAllLinebreaks_thenGetTheExpectedResult() throws Exception { + String content1 = Files.readString(file1Path(), StandardCharsets.UTF_8); + + // file contains CRLF + String content2 = Files.readString(file2Path(), StandardCharsets.UTF_8); + + String result1 = content1.replace("\r", "").replace("\n", ""); + String result2 = content2.replace("\r", "").replace("\n", ""); + + assertEquals("A, B, C, D, E, F", result1); + assertEquals("A, B, C, D, E, F", result2); + + String resultReplaceAll = content2.replaceAll("[\\n\\r]", ""); + assertEquals("A, B, C, D, E, F", resultReplaceAll); + + } + + @Test + void whenUsingReadAllLinesAndJoin_thenGetExpectedResult() throws Exception { + List lines1 = Files.readAllLines(file1Path(), StandardCharsets.UTF_8); + + // file contains CRLF + List lines2 = Files.readAllLines(file2Path(), StandardCharsets.UTF_8); + + String result1 = String.join("", lines1); + String result2 = String.join("", lines2); + + assertEquals("A, B, C, D, E, F", result1); + assertEquals("A, B, C, D, E, F", result2); + } + +} \ No newline at end of file diff --git a/core-java-modules/core-java-io-5/src/test/resources/multiple-line-1.txt b/core-java-modules/core-java-io-5/src/test/resources/multiple-line-1.txt new file mode 100644 index 0000000000..42e87e734e --- /dev/null +++ b/core-java-modules/core-java-io-5/src/test/resources/multiple-line-1.txt @@ -0,0 +1,6 @@ +A, + B, + C, + D, + E, + F diff --git a/core-java-modules/core-java-io-5/src/test/resources/multiple-line-2.txt b/core-java-modules/core-java-io-5/src/test/resources/multiple-line-2.txt new file mode 100644 index 0000000000..4fe5d5f4ed --- /dev/null +++ b/core-java-modules/core-java-io-5/src/test/resources/multiple-line-2.txt @@ -0,0 +1,4 @@ +A, B, + C, + D, E, + F From 91b80094fc7aaad90d161934a7d3fc3322822fd6 Mon Sep 17 00:00:00 2001 From: timis1 <12120641+timis1@users.noreply.github.com> Date: Tue, 10 Oct 2023 13:02:45 +0300 Subject: [PATCH 33/37] JAVA-25517 Upgrade spring-boot-bootstrap to Spring Boot 3 (#14896) --- spring-boot-modules/spring-boot-bootstrap/pom.xml | 15 ++++++++------- .../java/com/baeldung/config/SecurityConfig.java | 12 ++++++------ .../java/com/baeldung/persistence/model/Book.java | 10 +++++----- 3 files changed, 19 insertions(+), 18 deletions(-) diff --git a/spring-boot-modules/spring-boot-bootstrap/pom.xml b/spring-boot-modules/spring-boot-bootstrap/pom.xml index 4ceae26f60..da16f79a2a 100644 --- a/spring-boot-modules/spring-boot-bootstrap/pom.xml +++ b/spring-boot-modules/spring-boot-bootstrap/pom.xml @@ -9,9 +9,10 @@ Demo project for Spring Boot - com.baeldung.spring-boot-modules - spring-boot-modules - 1.0.0-SNAPSHOT + com.baeldung + parent-boot-3 + 0.0.1-SNAPSHOT + ../../parent-boot-3 @@ -47,13 +48,12 @@ io.rest-assured rest-assured - ${rest-assured.version} test - javax.servlet - javax.servlet-api - ${servlet.version} + org.springframework.boot + spring-boot-starter-cloud-connectors + ${spring-boot-cloud-connectors.version} @@ -332,6 +332,7 @@ 4.0.0 Greenwich.RELEASE 1.0.0.RELEASE + 2.2.13.RELEASE \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-bootstrap/src/main/java/com/baeldung/config/SecurityConfig.java b/spring-boot-modules/spring-boot-bootstrap/src/main/java/com/baeldung/config/SecurityConfig.java index ecb21cdf4b..c876e1c3d4 100644 --- a/spring-boot-modules/spring-boot-bootstrap/src/main/java/com/baeldung/config/SecurityConfig.java +++ b/spring-boot-modules/spring-boot-bootstrap/src/main/java/com/baeldung/config/SecurityConfig.java @@ -4,6 +4,7 @@ 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.web.SecurityFilterChain; @Configuration @@ -12,12 +13,11 @@ public class SecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { - http.authorizeRequests() - .anyRequest() - .permitAll() - .and() - .csrf() - .disable(); + http.authorizeHttpRequests(expressionInterceptUrlRegistry -> + expressionInterceptUrlRegistry + .anyRequest() + .permitAll()) + .csrf(AbstractHttpConfigurer::disable); return http.build(); } } diff --git a/spring-boot-modules/spring-boot-bootstrap/src/main/java/com/baeldung/persistence/model/Book.java b/spring-boot-modules/spring-boot-bootstrap/src/main/java/com/baeldung/persistence/model/Book.java index 6be27d4cf0..d599c64567 100644 --- a/spring-boot-modules/spring-boot-bootstrap/src/main/java/com/baeldung/persistence/model/Book.java +++ b/spring-boot-modules/spring-boot-bootstrap/src/main/java/com/baeldung/persistence/model/Book.java @@ -1,10 +1,10 @@ package com.baeldung.persistence.model; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; @Entity public class Book { From 25263d41258b6ce022b5e9577af618b5cb8ee896 Mon Sep 17 00:00:00 2001 From: Thiago dos Santos Hora Date: Tue, 10 Oct 2023 17:13:55 +0200 Subject: [PATCH 34/37] NO-JIRA: Fix docker test for shardingphere @thiagohora (#14704) * [BAEL-4897] Shardingshere * [BAEL-4897] Fixes * NO-JIRA: Fix docker test for shardingphere --- .../OrderServiceManualTest.java | 90 +++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 persistence-modules/spring-data-shardingsphere/src/test/java/com/baeldung/shardingsphere/OrderServiceManualTest.java diff --git a/persistence-modules/spring-data-shardingsphere/src/test/java/com/baeldung/shardingsphere/OrderServiceManualTest.java b/persistence-modules/spring-data-shardingsphere/src/test/java/com/baeldung/shardingsphere/OrderServiceManualTest.java new file mode 100644 index 0000000000..895dd52afb --- /dev/null +++ b/persistence-modules/spring-data-shardingsphere/src/test/java/com/baeldung/shardingsphere/OrderServiceManualTest.java @@ -0,0 +1,90 @@ +package com.baeldung.shardingsphere; + +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.testcontainers.containers.MySQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +import java.math.BigDecimal; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.time.LocalDate; +import java.util.List; + + +/** + * This Manual test requires: Docker service running. + */ +@Testcontainers +@SpringBootTest +class OrderServiceManualTest { + + @Container + static MySQLContainer mySQLContainer1 = new MySQLContainer<>("mysql:8.0.23") + .withDatabaseName("ds0") + .withUsername("test") + .withPassword("test"); + + @Container + static MySQLContainer mySQLContainer2 = new MySQLContainer<>("mysql:8.0.23") + .withDatabaseName("ds1") + .withUsername("test") + .withPassword("test"); + + static { + mySQLContainer2.setPortBindings(List.of("13307:3306")); + mySQLContainer1.setPortBindings(List.of("13306:3306")); + } + @Autowired + private OrderService orderService; + + @Autowired + private OrderRepository orderRepository; + + @DynamicPropertySource + static void setProperties(DynamicPropertyRegistry registry) { + registry.add("spring.jpa.hibernate.ddl-auto", () -> "create-drop"); + } + + @Test + void shouldFindOrderInCorrectShard() { + // given + Order order1 = new Order(1L, 1L, BigDecimal.TEN, Status.PROCESSING, LocalDate.now(), "123 Main St"); + Order order2 = new Order(2L, 2L, BigDecimal.valueOf(12.5), Status.SHIPPED, LocalDate.now(), "456 Main St"); + + // when + Order savedOrder1 = orderService.createOrder(order1); + Order savedOrder2 = orderService.createOrder(order2); + + // then + // Assuming the sharding strategy is based on the order id, data for order1 should be present only in ds0 + // and data for order2 should be present only in ds1 + Assertions.assertThat(orderService.getOrder(savedOrder1.getOrderId())).isEqualTo(savedOrder1); + Assertions.assertThat(orderService.getOrder(savedOrder2.getOrderId())).isEqualTo(savedOrder2); + + // Verify that the orders are not present in the wrong shards. + // You would need to implement these methods in your OrderService. + // They should use a JdbcTemplate or EntityManager to execute SQL directly against each shard. + Assertions.assertThat(assertOrderInShard(savedOrder1, mySQLContainer2)).isTrue(); + Assertions.assertThat(assertOrderInShard(savedOrder2, mySQLContainer1)).isTrue(); + } + + private boolean assertOrderInShard(Order order, MySQLContainer container) { + try (Connection conn = DriverManager.getConnection(container.getJdbcUrl(), container.getUsername(), container.getPassword())) { + PreparedStatement stmt = conn.prepareStatement("SELECT * FROM `order` WHERE order_id = ?"); + stmt.setLong(1, order.getOrderId()); + ResultSet rs = stmt.executeQuery(); + return rs.next(); + } catch (SQLException ex) { + throw new RuntimeException("Error querying order in shard", ex); + } + } +} From d5b2f61ea084112760fcb8d8ec5ba22cb4f754b7 Mon Sep 17 00:00:00 2001 From: lucaCambi77 Date: Wed, 11 Oct 2023 03:35:10 +0200 Subject: [PATCH 35/37] BAEL-6913 - Rotate array in java (#14861) * feat: rotate array in java * fix: When to when --- .../algorithms/rotatearray/RotateArray.java | 102 ++++++++++++++ .../rotatearray/RotateArrayUnitTest.java | 124 ++++++++++++++++++ 2 files changed, 226 insertions(+) create mode 100644 algorithms-modules/algorithms-miscellaneous-7/src/main/java/com/baeldung/algorithms/rotatearray/RotateArray.java create mode 100644 algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/rotatearray/RotateArrayUnitTest.java diff --git a/algorithms-modules/algorithms-miscellaneous-7/src/main/java/com/baeldung/algorithms/rotatearray/RotateArray.java b/algorithms-modules/algorithms-miscellaneous-7/src/main/java/com/baeldung/algorithms/rotatearray/RotateArray.java new file mode 100644 index 0000000000..36490d4899 --- /dev/null +++ b/algorithms-modules/algorithms-miscellaneous-7/src/main/java/com/baeldung/algorithms/rotatearray/RotateArray.java @@ -0,0 +1,102 @@ +package com.baeldung.algorithms.rotatearray; + +/** + * To speed up the rotation, we narrow k rotations to the remainder of k divided by the array length, or k module the array length. + * Therefore, a large rotation number will be translated into the relative smallest rotation. + * All solutions replace the original array, although they might use an extra array to compute the rotation. + */ +public class RotateArray { + + private RotateArray() { + throw new IllegalStateException("Rotate array algorithm utility methods class"); + } + + /** + * + * @param arr array to apply rotation to + * @param k number of rotations + */ + public static void bruteForce(int[] arr, int k) { + checkInvalidInput(arr, k); + + k %= arr.length; + int temp; + int previous; + for (int i = 0; i < k; i++) { + previous = arr[arr.length - 1]; + for (int j = 0; j < arr.length; j++) { + temp = arr[j]; + arr[j] = previous; + previous = temp; + } + } + } + + /** + * + * @param arr array to apply rotation to + * @param k number of rotations + */ + public static void withExtraArray(int[] arr, int k) { + checkInvalidInput(arr, k); + + int[] extraArray = new int[arr.length]; + for (int i = 0; i < arr.length; i++) { + extraArray[(i + k) % arr.length] = arr[i]; + } + System.arraycopy(extraArray, 0, arr, 0, arr.length); + } + + /** + * + * @param arr array to apply rotation to + * @param k number of rotations + */ + public static void cyclicReplacement(int[] arr, int k) { + checkInvalidInput(arr, k); + + k = k % arr.length; + int count = 0; + for (int start = 0; count < arr.length; start++) { + int current = start; + int prev = arr[start]; + do { + int next = (current + k) % arr.length; + int temp = arr[next]; + arr[next] = prev; + prev = temp; + current = next; + count++; + } while (start != current); + } + } + + /** + * + * @param arr array to apply rotation to + * @param k number of rotations + */ + public static void reverse(int[] arr, int k) { + checkInvalidInput(arr, k); + + k %= arr.length; + reverse(arr, 0, arr.length - 1); + reverse(arr, 0, k - 1); + reverse(arr, k, arr.length - 1); + } + + private static void reverse(int[] nums, int start, int end) { + while (start < end) { + int temp = nums[start]; + nums[start] = nums[end]; + nums[end] = temp; + start++; + end--; + } + } + + private static void checkInvalidInput(int[] arr, int rotation) { + if (rotation < 1 || arr == null) + throw new IllegalArgumentException("Rotation must be greater than zero or array must be not null"); + } +} diff --git a/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/rotatearray/RotateArrayUnitTest.java b/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/rotatearray/RotateArrayUnitTest.java new file mode 100644 index 0000000000..4a98acdb75 --- /dev/null +++ b/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/rotatearray/RotateArrayUnitTest.java @@ -0,0 +1,124 @@ +package com.baeldung.algorithms.rotatearray; + +import static com.baeldung.algorithms.rotatearray.RotateArray.bruteForce; +import static com.baeldung.algorithms.rotatearray.RotateArray.cyclicReplacement; +import static com.baeldung.algorithms.rotatearray.RotateArray.reverse; +import static com.baeldung.algorithms.rotatearray.RotateArray.withExtraArray; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import org.junit.jupiter.api.Test; + +class RotateArrayUnitTest { + + private final int[] arr = { 1, 2, 3, 4, 5, 6 }; + private final int rotationLtArrayLength = 1; + private final int rotationGtArrayLength = arr.length + 2; + private final int[] ltArrayLengthRotation = { 6, 1, 2, 3, 4, 5 }; + private final int[] gtArrayLengthRotation = { 5, 6, 1, 2, 3, 4 }; + + @Test + void givenInputArray_whenNoRotationOrEmptyArray_thenThrowIllegalArgumentException() { + final int noRotation = 0; + final int someRotation = arr.length - 1; + + assertThrows(IllegalArgumentException.class, () -> bruteForce(arr, noRotation)); + assertThrows(IllegalArgumentException.class, () -> withExtraArray(arr, noRotation)); + assertThrows(IllegalArgumentException.class, () -> cyclicReplacement(arr, noRotation)); + assertThrows(IllegalArgumentException.class, () -> reverse(arr, noRotation)); + + assertThrows(IllegalArgumentException.class, () -> bruteForce(null, someRotation)); + assertThrows(IllegalArgumentException.class, () -> withExtraArray(null, someRotation)); + assertThrows(IllegalArgumentException.class, () -> cyclicReplacement(null, someRotation)); + assertThrows(IllegalArgumentException.class, () -> reverse(null, someRotation)); + } + + @Test + void givenInputArray_whenUseBruteForceRotationLtArrayLength_thenRotateArrayOk() { + + bruteForce(arr, rotationLtArrayLength); + assertArrayEquals(ltArrayLengthRotation, arr); + } + + @Test + void givenInputArray_whenUseBruteForceRotationGtArrayLength_thenRotateArrayOk() { + + bruteForce(arr, rotationGtArrayLength); + assertArrayEquals(gtArrayLengthRotation, arr); + } + + @Test + void givenInputArray_whenUseBruteForceRotationEqArrayLength_thenDoNothing() { + int[] expected = arr.clone(); + + bruteForce(arr, arr.length); + assertArrayEquals(expected, arr); + } + + @Test + void givenInputArray_whenUseExtraArrayRotationLtArrayLength_thenRotateArrayOk() { + + withExtraArray(arr, rotationLtArrayLength); + assertArrayEquals(ltArrayLengthRotation, arr); + } + + @Test + void givenInputArray_whenUseExtraArrayRotationGtArrayLength_thenRotateArrayOk() { + + withExtraArray(arr, rotationGtArrayLength); + assertArrayEquals(gtArrayLengthRotation, arr); + } + + @Test + void givenInputArray_whenUseExtraArrayWithRotationEqArrayLength_thenDoNothing() { + int[] clone = arr.clone(); + + withExtraArray(arr, arr.length); + assertArrayEquals(clone, arr); + } + + @Test + void givenInputArray_whenUseCyclicReplacementRotationLtArrayLength_thenRotateArrayOk() { + + cyclicReplacement(arr, rotationLtArrayLength); + assertArrayEquals(ltArrayLengthRotation, arr); + } + + @Test + void givenInputArray_whenUseCyclicReplacementRotationGtArrayLength_thenRotateArrayOk() { + + cyclicReplacement(arr, rotationGtArrayLength); + assertArrayEquals(gtArrayLengthRotation, arr); + } + + @Test + void givenInputArray_whenUseCyclicReplacementRotationEqArrayLength_thenDoNothing() { + int[] clone = arr.clone(); + + cyclicReplacement(arr, arr.length); + assertArrayEquals(clone, arr); + } + + @Test + void givenInputArray_whenUseReverseRotationLtArrayLength_thenRotateArrayOk() { + + reverse(arr, rotationLtArrayLength); + assertArrayEquals(ltArrayLengthRotation, arr); + } + + @Test + void givenInputArray_whenUseReverseRotationGtArrayLength_thenRotateArrayOk() { + + reverse(arr, rotationGtArrayLength); + assertArrayEquals(gtArrayLengthRotation, arr); + } + + @Test + void givenInputArray_whenUseReverseRotationEqArrayLength_thenDoNothing() { + + int[] clone = arr.clone(); + + reverse(arr, arr.length); + assertArrayEquals(clone, arr); + } +} From 1912c8c618831bc4cf58ce52c6e53d95365c1753 Mon Sep 17 00:00:00 2001 From: Gaetano Piazzolla Date: Wed, 11 Oct 2023 09:14:39 +0200 Subject: [PATCH 36/37] JAVA-22296 | Upgrade spring-cloud-modules to JDK 17: Chunk 4 - integration tests fix (#14907) spring-cloud-contract, spring-cloud-data-flow --- pom.xml | 1 + .../spring-cloud-contract/pom.xml | 13 +++++++--- .../spring-cloud-contract-consumer/pom.xml | 24 ++++++++++++------- .../spring-cloud-contract-producer/pom.xml | 22 ++++++++++++----- ...aFlowServerApplicationIntegrationTest.java | 6 +++++ 5 files changed, 49 insertions(+), 17 deletions(-) diff --git a/pom.xml b/pom.xml index 6853b10587..197074c455 100644 --- a/pom.xml +++ b/pom.xml @@ -1005,6 +1005,7 @@ 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-netflix-feign spring-cloud-modules/spring-cloud-stream-starters spring-cloud-modules/spring-cloud-zuul-eureka-integration diff --git a/spring-cloud-modules/spring-cloud-contract/pom.xml b/spring-cloud-modules/spring-cloud-contract/pom.xml index 7a9c8c32cd..f2d0d1b5b0 100644 --- a/spring-cloud-modules/spring-cloud-contract/pom.xml +++ b/spring-cloud-modules/spring-cloud-contract/pom.xml @@ -41,28 +41,35 @@ org.springframework.cloud spring-cloud-contract-wiremock - ${spring-cloud.version} + ${spring-cloud-contract.version} test org.springframework.cloud spring-cloud-contract-stub-runner - ${spring-cloud.version} + ${spring-cloud-contract.version} test org.springframework.cloud spring-cloud-starter-contract-verifier - ${spring-cloud.version} + ${spring-cloud-contract.version} test + + org.codehaus.groovy + groovy + ${groovy.version} + 4.0.3 + 4.0.4 2.1.4.RELEASE 2.17.1 + 2.5.6 \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-contract/spring-cloud-contract-consumer/pom.xml b/spring-cloud-modules/spring-cloud-contract/spring-cloud-contract-consumer/pom.xml index 680e2e1795..a8c3337de5 100644 --- a/spring-cloud-modules/spring-cloud-contract/spring-cloud-contract-consumer/pom.xml +++ b/spring-cloud-modules/spring-cloud-contract/spring-cloud-contract-consumer/pom.xml @@ -16,6 +16,15 @@ + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-data-rest + + org.springframework.cloud spring-cloud-contract-wiremock @@ -26,20 +35,13 @@ spring-cloud-contract-stub-runner test - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-data-rest - com.baeldung.spring.cloud spring-cloud-contract-producer ${project.parent.version} test + io.rest-assured rest-assured @@ -50,6 +52,12 @@ + + + org.codehaus.groovy + groovy + + \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-contract/spring-cloud-contract-producer/pom.xml b/spring-cloud-modules/spring-cloud-contract/spring-cloud-contract-producer/pom.xml index 35dd9596f7..eb80f8d3dd 100644 --- a/spring-cloud-modules/spring-cloud-contract/spring-cloud-contract-producer/pom.xml +++ b/spring-cloud-modules/spring-cloud-contract/spring-cloud-contract-producer/pom.xml @@ -16,19 +16,17 @@ - - org.springframework.cloud - spring-cloud-starter-contract-verifier - test - + org.springframework.boot spring-boot-starter-web + org.springframework.boot spring-boot-starter-data-rest + io.rest-assured rest-assured @@ -39,6 +37,18 @@ + + + org.springframework.cloud + spring-cloud-starter-contract-verifier + test + + + + org.codehaus.groovy + groovy + + @@ -46,7 +56,7 @@ org.springframework.cloud spring-cloud-contract-maven-plugin - 2.1.1.RELEASE + ${spring-cloud-contract.version} true com.baeldung.spring.cloud.springcloudcontractproducer.BaseTestClass diff --git a/spring-cloud-modules/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/data-flow-server/src/test/java/com/baeldung/spring/cloud/DataFlowServerApplicationIntegrationTest.java b/spring-cloud-modules/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/data-flow-server/src/test/java/com/baeldung/spring/cloud/DataFlowServerApplicationIntegrationTest.java index 68f0db60eb..49eb255303 100644 --- a/spring-cloud-modules/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/data-flow-server/src/test/java/com/baeldung/spring/cloud/DataFlowServerApplicationIntegrationTest.java +++ b/spring-cloud-modules/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/data-flow-server/src/test/java/com/baeldung/spring/cloud/DataFlowServerApplicationIntegrationTest.java @@ -9,6 +9,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.serializer.RedisSerializer; +import org.springframework.session.data.redis.config.ConfigureRedisAction; import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; import org.springframework.test.context.junit4.SpringRunner; @@ -39,5 +40,10 @@ public class DataFlowServerApplicationIntegrationTest { return factory; } + + @Bean + public static ConfigureRedisAction configureRedisAction() { + return ConfigureRedisAction.NO_OP; + } } } From 03a3587560110f76117fbb97631224df94be3ad2 Mon Sep 17 00:00:00 2001 From: Gaetano Piazzolla Date: Wed, 11 Oct 2023 10:04:44 +0200 Subject: [PATCH 37/37] JAVA-25157 | minor fixes (#14915) --- .../spring-boot-keycloak/pom.xml | 2 +- ...ingBoot.java => SpringBootKeycloakApp.java} | 5 ++--- .../KeycloakContextIntegrationTest.java | 3 +-- .../swaggerkeycloak/GlobalSecurityConfig.java | 18 +++++++++++------- 4 files changed, 15 insertions(+), 13 deletions(-) rename spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/{SpringBoot.java => SpringBootKeycloakApp.java} (80%) diff --git a/spring-boot-modules/spring-boot-keycloak/pom.xml b/spring-boot-modules/spring-boot-keycloak/pom.xml index bada9ab52d..13339c9de1 100644 --- a/spring-boot-modules/spring-boot-keycloak/pom.xml +++ b/spring-boot-modules/spring-boot-keycloak/pom.xml @@ -102,7 +102,7 @@ - com.baeldung.keycloak.SpringBoot + com.baeldung.keycloak.SpringBootKeycloakApp 4.0.0 1.6.3 2.5.0 diff --git a/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/SpringBoot.java b/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/SpringBootKeycloakApp.java similarity index 80% rename from spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/SpringBoot.java rename to spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/SpringBootKeycloakApp.java index 90d7e774a4..a6f978fb3f 100644 --- a/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/SpringBoot.java +++ b/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/SpringBootKeycloakApp.java @@ -6,11 +6,10 @@ import org.springframework.context.annotation.Bean; import org.springframework.web.client.RestTemplate; @SpringBootApplication - -public class SpringBoot { +public class SpringBootKeycloakApp { public static void main(String[] args) { - SpringApplication.run(SpringBoot.class, args); + SpringApplication.run(SpringBootKeycloakApp.class, args); } @Bean diff --git a/spring-boot-modules/spring-boot-keycloak/src/test/java/com/baeldung/keycloak/KeycloakContextIntegrationTest.java b/spring-boot-modules/spring-boot-keycloak/src/test/java/com/baeldung/keycloak/KeycloakContextIntegrationTest.java index 336c8364aa..116516acfe 100644 --- a/spring-boot-modules/spring-boot-keycloak/src/test/java/com/baeldung/keycloak/KeycloakContextIntegrationTest.java +++ b/spring-boot-modules/spring-boot-keycloak/src/test/java/com/baeldung/keycloak/KeycloakContextIntegrationTest.java @@ -4,10 +4,9 @@ import org.junit.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit.jupiter.SpringExtension; -import com.baeldung.keycloak.SpringBoot; @ExtendWith(SpringExtension.class) -@SpringBootTest(classes = { SpringBoot.class }) +@SpringBootTest(classes = { SpringBootKeycloakApp.class }) public class KeycloakContextIntegrationTest { @Test diff --git a/spring-boot-modules/spring-boot-swagger-keycloak/src/main/java/com/baeldung/swaggerkeycloak/GlobalSecurityConfig.java b/spring-boot-modules/spring-boot-swagger-keycloak/src/main/java/com/baeldung/swaggerkeycloak/GlobalSecurityConfig.java index 5c24368ce6..9a1bf547db 100644 --- a/spring-boot-modules/spring-boot-swagger-keycloak/src/main/java/com/baeldung/swaggerkeycloak/GlobalSecurityConfig.java +++ b/spring-boot-modules/spring-boot-swagger-keycloak/src/main/java/com/baeldung/swaggerkeycloak/GlobalSecurityConfig.java @@ -3,10 +3,11 @@ package com.baeldung.swaggerkeycloak; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; +import org.springframework.security.config.Customizer; 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.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer; +import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; import org.springframework.security.core.session.SessionRegistryImpl; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.session.RegisterSessionAuthenticationStrategy; @@ -24,16 +25,19 @@ public class GlobalSecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { - http.csrf() - .disable() - .authorizeRequests() - .requestMatchers(HttpMethod.OPTIONS) + + http.csrf(AbstractHttpConfigurer::disable) + .authorizeHttpRequests((requests) -> requests.requestMatchers(HttpMethod.OPTIONS) .permitAll() .requestMatchers("/api/**") .authenticated() .anyRequest() - .permitAll(); - http.oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt); + .permitAll()); + + http.oauth2ResourceServer((oauth2) -> oauth2 + .jwt(Customizer.withDefaults()) + ); + return http.build(); }