From da7c711f25be5f77656cb6d0482ee0030dae08c3 Mon Sep 17 00:00:00 2001 From: panos-kakos Date: Sat, 16 Sep 2023 08:25:35 +0300 Subject: [PATCH 1/5] [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 8a7e667f0dafedea14bf93572c5508823fe80f0d Mon Sep 17 00:00:00 2001 From: panos-kakos Date: Sat, 23 Sep 2023 18:49:37 +0300 Subject: [PATCH 2/5] [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 adcf9b8cbdbc9dfba196fadc82292e48253afd1f Mon Sep 17 00:00:00 2001 From: panos-kakos Date: Sun, 1 Oct 2023 10:19:23 +0300 Subject: [PATCH 3/5] [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 55296d07f484b1f1e794bec261827d9d71b922bd Mon Sep 17 00:00:00 2001 From: panos-kakos Date: Sat, 7 Oct 2023 18:38:44 +0300 Subject: [PATCH 4/5] [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 5/5] [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 { -}