Merge pull request #14819 from panos-kakos/JAVA-23452

[JAVA-23452]
This commit is contained in:
Kasra Madadipouya 2023-10-11 22:10:28 +02:00 committed by GitHub
commit c478a97e04
15 changed files with 402 additions and 254 deletions

2
aws-modules/aws-dynamodb/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
/target/
.idea/

View File

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

View File

@ -0,0 +1,87 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>aws-dynamodb</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>aws-dynamodb</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>aws-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk</artifactId>
<version>${aws-java-sdk.version}</version>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>DynamoDBLocal</artifactId>
<version>${dynamodblocal.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${gson.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>${maven-shade-plugin.version}</version>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>${maven-plugins-version}</version>
<executions>
<execution>
<id>copy</id>
<phase>compile</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<includeScope></includeScope>
<includeTypes>so,dll,dylib</includeTypes>
<outputDirectory>native-libs</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<properties>
<gson.version>2.8.0</gson.version>
<dynamodblocal.version>1.21.1</dynamodblocal.version>
<maven-plugins-version>3.1.1</maven-plugins-version>
</properties>
</project>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -16,31 +16,9 @@
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>com.amazonaws</groupId> <groupId>software.amazon.awssdk</groupId>
<artifactId>aws-java-sdk</artifactId> <artifactId>aws-sdk-java</artifactId>
<version>${aws-java-sdk.version}</version> <version>${aws-java-sdk-v2.version}</version>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-core</artifactId>
<version>${aws-lambda-java-core.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-events</artifactId>
<version>${aws-lambda-java-events.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency> </dependency>
<dependency> <dependency>
<groupId>commons-io</groupId> <groupId>commons-io</groupId>
@ -52,12 +30,6 @@
<artifactId>gson</artifactId> <artifactId>gson</artifactId>
<version>${gson.version}</version> <version>${gson.version}</version>
</dependency> </dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>DynamoDBLocal</artifactId>
<version>${dynamodblocal.version}</version>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>
@ -101,8 +73,6 @@
</build> </build>
<properties> <properties>
<aws-lambda-java-events.version>1.3.0</aws-lambda-java-events.version>
<aws-lambda-java-core.version>1.1.0</aws-lambda-java-core.version>
<gson.version>2.8.0</gson.version> <gson.version>2.8.0</gson.version>
<dynamodblocal.version>1.21.1</dynamodblocal.version> <dynamodblocal.version>1.21.1</dynamodblocal.version>
<commons-codec-version>1.10.L001</commons-codec-version> <commons-codec-version>1.10.L001</commons-codec-version>

View File

@ -2,136 +2,148 @@ package com.baeldung.ec2;
import java.util.Arrays; import java.util.Arrays;
import com.amazonaws.auth.AWSCredentials; import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import com.amazonaws.auth.AWSStaticCredentialsProvider; import software.amazon.awssdk.regions.Region;
import com.amazonaws.auth.BasicAWSCredentials; import software.amazon.awssdk.services.ec2.Ec2Client;
import com.amazonaws.regions.Regions; import software.amazon.awssdk.services.ec2.model.AuthorizeSecurityGroupIngressRequest;
import com.amazonaws.services.ec2.AmazonEC2; import software.amazon.awssdk.services.ec2.model.CreateKeyPairRequest;
import com.amazonaws.services.ec2.AmazonEC2ClientBuilder; import software.amazon.awssdk.services.ec2.model.CreateKeyPairResponse;
import com.amazonaws.services.ec2.model.AuthorizeSecurityGroupIngressRequest; import software.amazon.awssdk.services.ec2.model.CreateSecurityGroupRequest;
import com.amazonaws.services.ec2.model.CreateKeyPairRequest; import software.amazon.awssdk.services.ec2.model.DescribeInstancesRequest;
import com.amazonaws.services.ec2.model.CreateKeyPairResult; import software.amazon.awssdk.services.ec2.model.DescribeInstancesResponse;
import com.amazonaws.services.ec2.model.CreateSecurityGroupRequest; import software.amazon.awssdk.services.ec2.model.DescribeKeyPairsRequest;
import com.amazonaws.services.ec2.model.DescribeInstancesRequest; import software.amazon.awssdk.services.ec2.model.DescribeKeyPairsResponse;
import com.amazonaws.services.ec2.model.DescribeInstancesResult; import software.amazon.awssdk.services.ec2.model.IpPermission;
import com.amazonaws.services.ec2.model.DescribeKeyPairsRequest; import software.amazon.awssdk.services.ec2.model.IpRange;
import com.amazonaws.services.ec2.model.DescribeKeyPairsResult; import software.amazon.awssdk.services.ec2.model.MonitorInstancesRequest;
import com.amazonaws.services.ec2.model.IpPermission; import software.amazon.awssdk.services.ec2.model.RebootInstancesRequest;
import com.amazonaws.services.ec2.model.IpRange; import software.amazon.awssdk.services.ec2.model.RunInstancesRequest;
import com.amazonaws.services.ec2.model.MonitorInstancesRequest; import software.amazon.awssdk.services.ec2.model.RunInstancesResponse;
import com.amazonaws.services.ec2.model.RebootInstancesRequest; import software.amazon.awssdk.services.ec2.model.StartInstancesRequest;
import com.amazonaws.services.ec2.model.RunInstancesRequest; import software.amazon.awssdk.services.ec2.model.StartInstancesResponse;
import com.amazonaws.services.ec2.model.StartInstancesRequest; import software.amazon.awssdk.services.ec2.model.StopInstancesRequest;
import com.amazonaws.services.ec2.model.StopInstancesRequest; import software.amazon.awssdk.services.ec2.model.UnmonitorInstancesRequest;
import com.amazonaws.services.ec2.model.UnmonitorInstancesRequest;
public class EC2Application { public class EC2Application {
private static final AWSCredentials credentials;
static {
// put your accesskey and secretkey here
credentials = new BasicAWSCredentials(
"<AWS accesskey>",
"<AWS secretkey>"
);
}
public static void main(String[] args) { public static void main(String[] args) {
// Set up the client // Set up the client
AmazonEC2 ec2Client = AmazonEC2ClientBuilder.standard() Ec2Client ec2Client = Ec2Client.builder()
.withCredentials(new AWSStaticCredentialsProvider(credentials)) .credentialsProvider(ProfileCredentialsProvider.create("default"))
.withRegion(Regions.US_EAST_1) .region(Region.US_EAST_1)
.build(); .build();
// Create a security group // Create a security group
CreateSecurityGroupRequest createSecurityGroupRequest = new CreateSecurityGroupRequest().withGroupName("BaeldungSecurityGroup") CreateSecurityGroupRequest createSecurityGroupRequest = CreateSecurityGroupRequest.builder()
.withDescription("Baeldung Security Group"); .groupName("BaeldungSecurityGroup")
.description("Baeldung Security Group")
.build();
ec2Client.createSecurityGroup(createSecurityGroupRequest); ec2Client.createSecurityGroup(createSecurityGroupRequest);
// Allow HTTP and SSH traffic // 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 })) IpPermission ipPermission1 = IpPermission.builder()
.withIpProtocol("tcp") .ipRanges(Arrays.asList(ipRange1))
.withFromPort(80) .ipProtocol("tcp")
.withToPort(80); .fromPort(80)
.toPort(80)
.build();
IpPermission ipPermission2 = new IpPermission().withIpv4Ranges(Arrays.asList(new IpRange[] { ipRange1 })) IpPermission ipPermission2 = IpPermission.builder()
.withIpProtocol("tcp") .ipRanges(Arrays.asList(ipRange1))
.withFromPort(22) .ipProtocol("tcp")
.withToPort(22); .fromPort(22)
.toPort(22)
.build();
AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest = new AuthorizeSecurityGroupIngressRequest() AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest = AuthorizeSecurityGroupIngressRequest
.withGroupName("BaeldungSecurityGroup") .builder()
.withIpPermissions(ipPermission1, ipPermission2); .groupName("BaeldungSecurityGroup")
.ipPermissions(ipPermission1, ipPermission2)
.build();
ec2Client.authorizeSecurityGroupIngress(authorizeSecurityGroupIngressRequest); ec2Client.authorizeSecurityGroupIngress(authorizeSecurityGroupIngressRequest);
// Create KeyPair // Create KeyPair
CreateKeyPairRequest createKeyPairRequest = new CreateKeyPairRequest() CreateKeyPairRequest createKeyPairRequest = CreateKeyPairRequest.builder()
.withKeyName("baeldung-key-pair"); .keyName("baeldung-key-pair")
CreateKeyPairResult createKeyPairResult = ec2Client.createKeyPair(createKeyPairRequest); .build();
String privateKey = createKeyPairResult
.getKeyPair() CreateKeyPairResponse createKeyPairResponse = ec2Client.createKeyPair(createKeyPairRequest);
.getKeyMaterial(); // make sure you keep it, the private key, Amazon doesn't store the private key 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 // See what key-pairs you've got
DescribeKeyPairsRequest describeKeyPairsRequest = new DescribeKeyPairsRequest(); DescribeKeyPairsRequest describeKeyPairsRequest = DescribeKeyPairsRequest.builder()
DescribeKeyPairsResult describeKeyPairsResult = ec2Client.describeKeyPairs(describeKeyPairsRequest); .build();
DescribeKeyPairsResponse describeKeyPairsResponse = ec2Client.describeKeyPairs(describeKeyPairsRequest);
// Launch an Amazon Instance // 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 RunInstancesRequest runInstancesRequest = RunInstancesRequest.builder()
.withInstanceType("t2.micro") // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html .imageId("ami-97785bed")
.withMinCount(1) .instanceType("t2.micro") // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html
.withMaxCount(1) .minCount(1)
.withKeyName("baeldung-key-pair") // optional - if not present, can't connect to instance .maxCount(1)
.withSecurityGroups("BaeldungSecurityGroup"); .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 // Start an Instance
StartInstancesRequest startInstancesRequest = new StartInstancesRequest() StartInstancesRequest startInstancesRequest = StartInstancesRequest.builder()
.withInstanceIds(yourInstanceId); .instanceIds(yourInstanceId)
.build();
StartInstancesResponse startInstancesResponse = ec2Client.startInstances(startInstancesRequest);
ec2Client.startInstances(startInstancesRequest);
// Monitor Instances // Monitor Instances
MonitorInstancesRequest monitorInstancesRequest = new MonitorInstancesRequest() MonitorInstancesRequest monitorInstancesRequest = MonitorInstancesRequest.builder()
.withInstanceIds(yourInstanceId); .instanceIds(yourInstanceId)
.build();
ec2Client.monitorInstances(monitorInstancesRequest); ec2Client.monitorInstances(monitorInstancesRequest);
UnmonitorInstancesRequest unmonitorInstancesRequest = new UnmonitorInstancesRequest() UnmonitorInstancesRequest unmonitorInstancesRequest = UnmonitorInstancesRequest.builder()
.withInstanceIds(yourInstanceId); .instanceIds(yourInstanceId)
.build();
ec2Client.unmonitorInstances(unmonitorInstancesRequest); ec2Client.unmonitorInstances(unmonitorInstancesRequest);
// Reboot an Instance // Reboot an Instance
RebootInstancesRequest rebootInstancesRequest = RebootInstancesRequest.builder()
RebootInstancesRequest rebootInstancesRequest = new RebootInstancesRequest() .instanceIds(yourInstanceId)
.withInstanceIds(yourInstanceId); .build();
ec2Client.rebootInstances(rebootInstancesRequest); ec2Client.rebootInstances(rebootInstancesRequest);
// Stop an Instance // Stop an Instance
StopInstancesRequest stopInstancesRequest = new StopInstancesRequest() StopInstancesRequest stopInstancesRequest = StopInstancesRequest.builder()
.withInstanceIds(yourInstanceId); .instanceIds(yourInstanceId)
.build();
ec2Client.stopInstances(stopInstancesRequest) ec2Client.stopInstances(stopInstancesRequest)
.getStoppingInstances() .stoppingInstances()
.get(0) .get(0)
.getPreviousState() .previousState()
.getName(); .name();
// Describe an Instance // Describe an Instance
DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest(); DescribeInstancesRequest describeInstancesRequest = DescribeInstancesRequest.builder().build();
DescribeInstancesResult response = ec2Client.describeInstances(describeInstancesRequest); DescribeInstancesResponse response = ec2Client.describeInstances(describeInstancesRequest);
System.out.println(response.getReservations() System.out.println(response.reservations()
.get(0) .get(0)
.getInstances() .instances()
.get(0) .get(0)
.getKernelId()); .kernelId());
} }
} }

View File

@ -1,13 +1,5 @@
package com.baeldung.rds; 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.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.sql.*; import java.sql.*;
@ -16,12 +8,22 @@ import java.util.Properties;
import java.util.UUID; import java.util.UUID;
import java.util.logging.Logger; 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 { public class AWSRDSService {
final static Logger logger = Logger.getLogger(AWSRDSService.class.getName()); final static Logger logger = Logger.getLogger(AWSRDSService.class.getName());
private AWSCredentialsProvider credentials; private RdsClient rdsClient;
private AmazonRDS amazonRDS;
private String db_username; private String db_username;
private String db_password; private String db_password;
private String db_database; private String db_database;
@ -34,22 +36,17 @@ public class AWSRDSService {
* **/ * **/
public AWSRDSService() throws IOException { public AWSRDSService() throws IOException {
//Init RDS client with credentials and region. //Init RDS client with credentials and region.
credentials = new
AWSStaticCredentialsProvider(new
BasicAWSCredentials("<ACCESS_KEY>",
"<SECRET_KEY>"));
amazonRDS = AmazonRDSClientBuilder.standard().withCredentials(credentials)
.withRegion(Regions.AP_SOUTHEAST_2).build();
Properties prop = new Properties(); Properties prop = new Properties();
InputStream input = AWSRDSService.class.getClassLoader().getResourceAsStream("db.properties"); InputStream input = AWSRDSService.class.getClassLoader().getResourceAsStream("db.properties");
prop.load(input); prop.load(input);
db_username = prop.getProperty("db_username"); db_username = prop.getProperty("db_username");
db_password = prop.getProperty("db_password"); db_password = prop.getProperty("db_password");
db_database = prop.getProperty("db_database"); db_database = prop.getProperty("db_database");
}
public AWSRDSService(AmazonRDS amazonRDS){ rdsClient = RdsClient.builder()
this.amazonRDS = amazonRDS; .region(Region.AP_SOUTHEAST_2)
.credentialsProvider(ProfileCredentialsProvider.create("default"))
.build();
} }
/** /**
@ -60,29 +57,29 @@ public class AWSRDSService {
public String launchInstance() { public String launchInstance() {
String identifier = ""; String identifier = "";
CreateDBInstanceRequest request = new CreateDBInstanceRequest(); CreateDbInstanceRequest instanceRequest = CreateDbInstanceRequest.builder()
// RDS instance name .dbInstanceIdentifier("Sydney")
request.setDBInstanceIdentifier("Sydney"); .engine("postgres")
request.setEngine("postgres"); .multiAZ(false)
request.setMultiAZ(false); .masterUsername(db_username)
request.setMasterUsername(db_username); .masterUserPassword(db_password)
request.setMasterUserPassword(db_password); .dbName(db_database)
request.setDBName(db_database); .storageType("gp2")
request.setStorageType("gp2"); .allocatedStorage(10)
request.setAllocatedStorage(10); .build();
DBInstance instance = amazonRDS.createDBInstance(request); CreateDbInstanceResponse createDbInstanceResponse = rdsClient.createDBInstance(instanceRequest);
// Information about the new RDS instance // Information about the new RDS instance
identifier = instance.getDBInstanceIdentifier(); identifier = createDbInstanceResponse.dbInstance().dbInstanceIdentifier();
String status = instance.getDBInstanceStatus(); String status = createDbInstanceResponse.dbInstance().dbInstanceStatus();
Endpoint endpoint = instance.getEndpoint(); Endpoint endpoint = createDbInstanceResponse.dbInstance().endpoint();
String endpoint_url = "Endpoint URL not available yet."; String endpointUrl = "Endpoint URL not available yet.";
if (endpoint != null) { if (endpoint != null) {
endpoint_url = endpoint.toString(); endpointUrl = endpoint.toString();
} }
logger.info(identifier + "\t" + status); logger.info(identifier + "\t" + status);
logger.info(endpoint_url); logger.info(endpointUrl);
return identifier; return identifier;
@ -90,44 +87,44 @@ public class AWSRDSService {
// Describe DB instances // Describe DB instances
public void listInstances() { public void listInstances() {
DescribeDBInstancesResult result = amazonRDS.describeDBInstances(); DescribeDbInstancesResponse response = rdsClient.describeDBInstances();
List<DBInstance> instances = result.getDBInstances(); List<DBInstance> instances = response.dbInstances();
for (DBInstance instance : instances) { for (DBInstance instance : instances) {
// Information about each RDS instance // Information about each RDS instance
String identifier = instance.getDBInstanceIdentifier(); String identifier = instance.dbInstanceIdentifier();
String engine = instance.getEngine(); String engine = instance.engine();
String status = instance.getDBInstanceStatus(); String status = instance.dbInstanceStatus();
Endpoint endpoint = instance.getEndpoint(); Endpoint endpoint = instance.endpoint();
String endpoint_url = "Endpoint URL not available yet."; String endpointUrl = "Endpoint URL not available yet.";
if (endpoint != null) { if (endpoint != null) {
endpoint_url = endpoint.toString(); endpointUrl = endpoint.toString();
} }
logger.info(identifier + "\t" + engine + "\t" + status); logger.info(identifier + "\t" + engine + "\t" + status);
logger.info("\t" + endpoint_url); logger.info("\t" + endpointUrl);
} }
} }
//Delete RDS instance //Delete RDS instance
public void terminateInstance(String identifier) { public void terminateInstance(String identifier) {
DeleteDBInstanceRequest request = new DeleteDBInstanceRequest(); DeleteDbInstanceRequest request = DeleteDbInstanceRequest.builder()
request.setDBInstanceIdentifier(identifier); .dbInstanceIdentifier(identifier)
request.setSkipFinalSnapshot(true); .skipFinalSnapshot(true)
.build();
// Delete the RDS instance // Delete the RDS instance
DBInstance instance = amazonRDS.deleteDBInstance(request); DeleteDbInstanceResponse response = rdsClient.deleteDBInstance(request);
// Information about the RDS instance being deleted // Information about the RDS instance being deleted
String status = instance.getDBInstanceStatus(); String status = response.dbInstance().dbInstanceStatus();
Endpoint endpoint = instance.getEndpoint(); Endpoint endpoint = response.dbInstance().endpoint();
String endpoint_url = "Endpoint URL not available yet."; String endpointUrl = "Endpoint URL not available yet.";
if (endpoint != null) { if (endpoint != null) {
endpoint_url = endpoint.toString(); endpointUrl = endpoint.toString();
} }
logger.info(identifier + "\t" + status); logger.info(identifier + "\t" + status);
logger.info(endpoint_url); logger.info(endpointUrl);
} }

View File

@ -5,140 +5,190 @@ import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import com.amazonaws.auth.AWSCredentials; import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import com.amazonaws.auth.AWSStaticCredentialsProvider; import software.amazon.awssdk.regions.Region;
import com.amazonaws.auth.BasicAWSCredentials; import software.amazon.awssdk.services.sqs.SqsClient;
import com.amazonaws.regions.Regions; import software.amazon.awssdk.services.sqs.model.CreateQueueRequest;
import com.amazonaws.services.sqs.AmazonSQSClientBuilder; import software.amazon.awssdk.services.sqs.model.DeleteMessageRequest;
import com.amazonaws.services.sqs.model.CreateQueueRequest; import software.amazon.awssdk.services.sqs.model.GetQueueAttributesRequest;
import com.amazonaws.services.sqs.model.DeleteMessageRequest; import software.amazon.awssdk.services.sqs.model.GetQueueAttributesResponse;
import com.amazonaws.services.sqs.model.GetQueueAttributesRequest; import software.amazon.awssdk.services.sqs.model.GetQueueUrlRequest;
import com.amazonaws.services.sqs.model.GetQueueAttributesResult; import software.amazon.awssdk.services.sqs.model.GetQueueUrlResponse;
import com.amazonaws.services.sqs.model.MessageAttributeValue; import software.amazon.awssdk.services.sqs.model.Message;
import com.amazonaws.services.sqs.model.ReceiveMessageRequest; import software.amazon.awssdk.services.sqs.model.MessageAttributeValue;
import com.amazonaws.services.sqs.model.SendMessageBatchRequest; import software.amazon.awssdk.services.sqs.model.QueueAttributeName;
import com.amazonaws.services.sqs.model.SendMessageRequest; import software.amazon.awssdk.services.sqs.model.ReceiveMessageRequest;
import com.amazonaws.services.sqs.model.SetQueueAttributesRequest; import software.amazon.awssdk.services.sqs.model.SendMessageBatchRequest;
import com.amazonaws.services.sqs.model.SendMessageBatchRequestEntry; import software.amazon.awssdk.services.sqs.model.SendMessageBatchRequestEntry;
import com.amazonaws.services.sqs.model.Message; import software.amazon.awssdk.services.sqs.model.SendMessageRequest;
import com.amazonaws.services.sqs.AmazonSQS; import software.amazon.awssdk.services.sqs.model.SetQueueAttributesRequest;
public class SQSApplication { 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";
static { private static final String DEAD_LETTER_QUEUE_NAME = "baeldung-dead-letter-queue";
// put your accesskey and secretkey here
credentials = new BasicAWSCredentials(
"<AWS accesskey>",
"<AWS secretkey>"
);
}
public static void main(String[] args) { public static void main(String[] args) {
// Set up the client // Set up the client
AmazonSQS sqs = AmazonSQSClientBuilder.standard() SqsClient sqsClient = SqsClient.builder()
.withCredentials(new AWSStaticCredentialsProvider(credentials)) .region(Region.US_EAST_1)
.withRegion(Regions.US_EAST_1) .credentialsProvider(ProfileCredentialsProvider.create())
.build(); .build();
// Create a standard queue // Create a standard queue
CreateQueueRequest createStandardQueueRequest = CreateQueueRequest.builder()
.queueName(STANDARD_QUEUE_NAME)
.build();
CreateQueueRequest createStandardQueueRequest = new CreateQueueRequest("baeldung-queue"); sqsClient.createQueue(createStandardQueueRequest);
String standardQueueUrl = sqs.createQueue(createStandardQueueRequest)
.getQueueUrl(); 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); System.out.println(standardQueueUrl);
// Create a fifo queue // Create a fifo queue
Map<QueueAttributeName, String> queueAttributes = new HashMap<>();
queueAttributes.put(QueueAttributeName.FIFO_QUEUE, "true");
queueAttributes.put(QueueAttributeName.CONTENT_BASED_DEDUPLICATION, "true");
Map<String, String> queueAttributes = new HashMap<String, String>(); CreateQueueRequest createFifoQueueRequest = CreateQueueRequest.builder()
queueAttributes.put("FifoQueue", "true"); .queueName(FIFO_QUEUE_NAME)
queueAttributes.put("ContentBasedDeduplication", "true"); .attributes(queueAttributes)
.build();
CreateQueueRequest createFifoQueueRequest = new CreateQueueRequest("baeldung-queue.fifo").withAttributes(queueAttributes); sqsClient.createQueue(createFifoQueueRequest);
String fifoQueueUrl = sqs.createQueue(createFifoQueueRequest)
.getQueueUrl(); GetQueueUrlResponse getFifoQueueUrlResponse = sqsClient.getQueueUrl(GetQueueUrlRequest.builder()
.queueName(FIFO_QUEUE_NAME)
.build());
String fifoQueueUrl = getFifoQueueUrlResponse.queueUrl();
System.out.println(fifoQueueUrl); System.out.println(fifoQueueUrl);
// Set up a dead letter queue // Set up a dead letter queue
CreateQueueRequest createDeadLetterQueueRequest = CreateQueueRequest.builder()
.queueName(DEAD_LETTER_QUEUE_NAME)
.build();
String deadLetterQueueUrl = sqs.createQueue("baeldung-dead-letter-queue") String deadLetterQueueUrl = sqsClient.createQueue(createDeadLetterQueueRequest)
.getQueueUrl(); .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"); .get("QueueArn");
SetQueueAttributesRequest queueAttributesRequest = new SetQueueAttributesRequest().withQueueUrl(standardQueueUrl) Map<QueueAttributeName, String> attributes = new HashMap<>();
.addAttributesEntry("RedrivePolicy", "{\"maxReceiveCount\":\"2\", " + "\"deadLetterTargetArn\":\"" + deadLetterQueueARN + "\"}"); attributes.put(QueueAttributeName.REDRIVE_POLICY, "{\"maxReceiveCount\":\"5\", \"deadLetterTargetArn\":\"" + deadLetterQueueARN + "\"}");
sqs.setQueueAttributes(queueAttributesRequest); SetQueueAttributesRequest queueAttributesRequest = SetQueueAttributesRequest.builder()
.queueUrl(standardQueueUrl)
.attributes(attributes)
.build();
sqsClient.setQueueAttributes(queueAttributesRequest);
// Send a message to a standard queue // Send a message to a standard queue
Map<String, MessageAttributeValue> messageAttributes = new HashMap<>(); Map<String, MessageAttributeValue> 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") messageAttributes.put("AttributeOne", messageAttributeValue);
.withDataType("String"));
SendMessageRequest sendMessageStandardQueue = new SendMessageRequest().withQueueUrl(standardQueueUrl) SendMessageRequest sendMessageStandardQueue = SendMessageRequest.builder()
.withMessageBody("A simple message.") .queueUrl(standardQueueUrl)
.withDelaySeconds(30) // Message will arrive in the queue after 30 seconds. We can use this only in standard queues .messageBody("A simple message.")
.withMessageAttributes(messageAttributes); .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 // Send a message to a fifo queue
SendMessageRequest sendMessageFifoQueue = new SendMessageRequest().withQueueUrl(fifoQueueUrl) SendMessageRequest sendMessageFifoQueue = SendMessageRequest.builder()
.withMessageBody("FIFO Queue") .queueUrl(fifoQueueUrl)
.withMessageGroupId("baeldung-group-1") .messageBody("FIFO Queue")
.withMessageAttributes(messageAttributes); .messageGroupId("baeldung-group-1")
.messageAttributes(messageAttributes)
.build();
sqs.sendMessage(sendMessageFifoQueue); sqsClient.sendMessage(sendMessageFifoQueue);
// Send multiple messages // Send multiple messages
List<SendMessageBatchRequestEntry> messageEntries = new ArrayList<>(); List<SendMessageBatchRequestEntry> messageEntries = new ArrayList<>();
messageEntries.add(new SendMessageBatchRequestEntry().withId("id-1") SendMessageBatchRequestEntry messageBatchRequestEntry1 = SendMessageBatchRequestEntry.builder()
.withMessageBody("batch-1") .id("id-1")
.withMessageGroupId("baeldung-group-1")); .messageBody("batch-1")
messageEntries.add(new SendMessageBatchRequestEntry().withId("id-2") .messageGroupId("baeldung-group-1")
.withMessageBody("batch-2") .build();
.withMessageGroupId("baeldung-group-1"));
SendMessageBatchRequest sendMessageBatchRequest = new SendMessageBatchRequest(fifoQueueUrl, messageEntries); SendMessageBatchRequestEntry messageBatchRequestEntry2 = SendMessageBatchRequestEntry.builder()
sqs.sendMessageBatch(sendMessageBatchRequest); .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 // Read a message from a queue
ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(fifoQueueUrl).withWaitTimeSeconds(10) // Long polling; ReceiveMessageRequest receiveMessageRequest = ReceiveMessageRequest.builder()
.withMaxNumberOfMessages(1); // Max is 10 .waitTimeSeconds(10)
.maxNumberOfMessages(10)
.build();
List<Message> sqsMessages = sqs.receiveMessage(receiveMessageRequest) List<Message> sqsMessages = sqsClient.receiveMessage(receiveMessageRequest)
.getMessages(); .messages();
sqsMessages.get(0) sqsMessages.get(0)
.getAttributes(); .attributes();
sqsMessages.get(0) sqsMessages.get(0)
.getBody(); .body();
// Delete a message from a queue // Delete a message from a queue
DeleteMessageRequest deleteMessageRequest = DeleteMessageRequest.builder()
.queueUrl(fifoQueueUrl)
.receiptHandle(sqsMessages.get(0)
.receiptHandle())
.build();
sqs.deleteMessage(new DeleteMessageRequest().withQueueUrl(fifoQueueUrl) sqsClient.deleteMessage(deleteMessageRequest);
.withReceiptHandle(sqsMessages.get(0)
.getReceiptHandle()));
// Monitoring // Monitoring
GetQueueAttributesRequest getQueueAttributesRequest = new GetQueueAttributesRequest(standardQueueUrl).withAttributeNames("All"); GetQueueAttributesRequest getQueueAttributesRequestForMonitoring = GetQueueAttributesRequest.builder()
GetQueueAttributesResult getQueueAttributesResult = sqs.getQueueAttributes(getQueueAttributesRequest); .queueUrl(standardQueueUrl)
System.out.println(String.format("The number of messages on the queue: %s", getQueueAttributesResult.getAttributes() .build();
GetQueueAttributesResponse attributesResponse = sqsClient.getQueueAttributes(getQueueAttributesRequestForMonitoring);
System.out.println(String.format("The number of messages on the queue: %s", attributesResponse.attributes()
.get("ApproximateNumberOfMessages"))); .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"))); .get("ApproximateNumberOfMessagesNotVisible")));
} }

View File

@ -5,6 +5,14 @@
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>aws-modules</artifactId> <artifactId>aws-modules</artifactId>
<name>aws-modules</name> <name>aws-modules</name>
<dependencies>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-dynamodb</artifactId>
<version>1.12.523</version>
<scope>compile</scope>
</dependency>
</dependencies>
<packaging>pom</packaging> <packaging>pom</packaging>
<parent> <parent>
@ -15,6 +23,7 @@
<modules> <modules>
<module>aws-app-sync</module> <module>aws-app-sync</module>
<module>aws-dynamodb</module>
<module>aws-lambda-modules</module> <module>aws-lambda-modules</module>
<module>aws-miscellaneous</module> <module>aws-miscellaneous</module>
<module>aws-reactive</module> <module>aws-reactive</module>
@ -24,6 +33,7 @@
<properties> <properties>
<aws-java-sdk.version>1.12.331</aws-java-sdk.version> <aws-java-sdk.version>1.12.331</aws-java-sdk.version>
<aws-java-sdk-v2.version>2.20.147</aws-java-sdk-v2.version>
<maven-shade-plugin.version>3.0.0</maven-shade-plugin.version> <maven-shade-plugin.version>3.0.0</maven-shade-plugin.version>
</properties> </properties>