Aws SDK Documentation
Aws SDK Documentation
Aws SDK Documentation
Developer Guide
Amazon's trademarks and trade dress may not be used in connection with any product or service that is not
Amazon's, in any manner that is likely to cause confusion among customers, or in any manner that disparages or
discredits Amazon. All other trademarks not owned by Amazon are the property of their respective owners, who may
or may not be affiliated with, connected to, or sponsored by Amazon.
AWS SDK for Java version 2 Developer Guide
Table of Contents
AWS SDK for Java 2.0 Developer Guide ............................................................................................... 1
What’s new in version 2 .............................................................................................................. 1
Features not yet in the AWS SDK for Java 2.0 ................................................................................ 1
Additional resources ................................................................................................................... 1
Contributing to the SDK ............................................................................................................. 2
Eclipse IDE support .................................................................................................................... 2
Developing AWS applications for Android ..................................................................................... 2
Getting Started .................................................................................................................................. 3
Sign up for AWS and Create an IAM User ..................................................................................... 3
Download the SDK ..................................................................................................................... 4
Prerequisites ...................................................................................................................... 4
Downloading the SDK into Your Project ................................................................................ 4
Compiling the SDK ............................................................................................................. 4
Installing a Java Development Environment .......................................................................... 5
Choosing a JVM ................................................................................................................. 5
Set up AWS Credentials and Region ............................................................................................. 5
Set AWS credentials ........................................................................................................... 5
Refresh IMDS credentials ..................................................................................................... 6
Set the AWS region ............................................................................................................ 7
Use the SDK with Apache Maven ................................................................................................ 7
Prerequisites ...................................................................................................................... 4
Create a Maven project ....................................................................................................... 8
Configure the Java compiler for Maven ................................................................................. 8
Declare the SDK as a dependency ........................................................................................ 9
Set dependencies for SDK modules ...................................................................................... 9
Build your project ............................................................................................................. 10
Use the SDK with Gradle .......................................................................................................... 10
Using the SDK ................................................................................................................................. 12
Creating Service Clients ........................................................................................................... 12
Obtaining a Client Builder ................................................................................................. 12
Using DefaultClient .......................................................................................................... 13
Client Lifecycle ................................................................................................................. 13
Supplying and Retrieving AWS Credentials ................................................................................. 13
Use the Default Credential Provider Chain ........................................................................... 13
Use a Specific Credential Provider or Provider Chain ............................................................. 15
Supply Credentials Explicitly .............................................................................................. 16
AWS Region Selection .............................................................................................................. 16
Choosing a Region ........................................................................................................... 16
Choosing a Specific Endpoint ............................................................................................. 17
Automatically Determine the AWS Region from the Environment ............................................ 17
Checking for Service Availability in an AWS Region ............................................................... 18
Client Configuration ................................................................................................................. 18
HTTP transport configuration ........................................................................................... 18
Optimize cold start performance for AWS Lambda .............................................................. 20
Asynchronous Programming ..................................................................................................... 20
Non-Streaming Operations ................................................................................................ 21
Streaming Operations ....................................................................................................... 23
Advanced Operations ........................................................................................................ 25
Configure metrics .................................................................................................................... 26
Prerequisites ...................................................................................................................... 4
How to enable metrics collection ....................................................................................... 27
What information is collected? ........................................................................................... 27
Service client metrics ....................................................................................................... 28
Waiters ................................................................................................................................... 30
iii
AWS SDK for Java version 2 Developer Guide
Prerequisites ...................................................................................................................... 4
Using waiters ................................................................................................................... 31
Configuring waiters .......................................................................................................... 31
HTTP/2 Programming .............................................................................................................. 32
Exception Handling ................................................................................................................. 32
Why Unchecked Exceptions? .............................................................................................. 32
SdkServiceException (and Subclasses) ................................................................................. 33
SdkClientException ........................................................................................................... 33
Logging AWS SDK for Java Calls ............................................................................................... 33
Add the Log4J JAR ........................................................................................................... 33
Log4j Configuration file .................................................................................................... 34
Setting the Classpath ........................................................................................................ 34
Service-Specific Errors and Warnings .................................................................................. 34
Request/Response Summary Logging ................................................................................. 35
Verbose Wire Logging ....................................................................................................... 35
Setting the JVM TTL for DNS Name Lookups .............................................................................. 36
How to Set the JVM TTL ................................................................................................... 36
Configure IAM Roles for Amazon EC2 (Advanced) ........................................................................ 37
Default Provider Chain and Amazon EC2 Instance Profiles ..................................................... 37
Walkthrough: Using IAM roles for Amazon EC2 Instances ....................................................... 37
Code Examples ................................................................................................................................ 39
Amazon CloudWatch Examples .................................................................................................. 39
Get metrics from CloudWatch ........................................................................................... 40
Publish custom metric data .............................................................................................. 41
Work with CloudWatch alarms .......................................................................................... 42
Use alarm actions in CloudWatch ...................................................................................... 45
Send events to CloudWatch .............................................................................................. 46
Amazon Cognito Examples ........................................................................................................ 48
Create a user pool ............................................................................................................ 48
List users from a user pool ................................................................................................ 49
Create an identity pool ..................................................................................................... 50
Add an app client ............................................................................................................. 51
Add a third-party identity provider ..................................................................................... 51
Get credentials for an ID ................................................................................................... 52
Amazon DynamoDB Examples .................................................................................................... 53
Work with tables in DynamoDB ........................................................................................ 53
Work with items in DynamoDB ......................................................................................... 60
Map items in DynamoDB tables ........................................................................................ 64
Amazon EC2 Examples .............................................................................................................. 71
Manage Amazon EC2 instances ......................................................................................... 72
Use elastic IP addresses in Amazon EC2 ............................................................................. 76
Use regions and availability zones ..................................................................................... 79
Work with Amazon EC2 key pairs ...................................................................................... 81
Work with security groups in Amazon EC2 .......................................................................... 82
AWS Identity and Access Management (IAM) Examples .................................................................. 85
Manage IAM access keys .................................................................................................. 86
Managing IAM Users ........................................................................................................ 90
Use IAM account aliases ................................................................................................... 93
Work with IAM policies .................................................................................................... 95
Work with IAM server certificates .................................................................................... 100
Amazon Kinesis Examples ........................................................................................................ 103
Subscribing to Amazon Kinesis Data Streams .................................................................... 103
Amazon Lambda Examples ...................................................................................................... 109
Service operations .......................................................................................................... 109
Amazon Pinpoint Examples ...................................................................................................... 111
Create a project ............................................................................................................. 112
Create a dynamic segment .............................................................................................. 112
iv
AWS SDK for Java version 2 Developer Guide
v
AWS SDK for Java version 2 Developer Guide
What’s new in version 2
• High-level libraries
• S3 Transfer manager
• S3 Encryption Client
• DynamoDB document APIs
• DynamoDB Encryption Client
• SQS Client-side Buffering
• Progress Listeners
Additional resources
In addition to this guide, the following are valuable online resources for AWS SDK for Java developers:
1
AWS SDK for Java version 2 Developer Guide
Contributing to the SDK
2
AWS SDK for Java version 2 Developer Guide
Sign up for AWS and Create an IAM User
Topics
• Sign up for AWS and Create an IAM User (p. 3)
• Download the AWS SDK for Java 2.0 (p. 4)
• Set up AWS credentials and region for development (p. 5)
• Use the SDK with Apache Maven (p. 7)
• Use the SDK with Gradle (p. 10)
Next, create an IAM user and download (or copy) its secret access key.
3
AWS SDK for Java version 2 Developer Guide
Download the SDK
Important
There is no way to obtain the secret access key once you close the dialog box. You can,
however, delete its associated access key ID and create a new one.
Next, set your credentials (p. 5) in the AWS shared credentials file or in the environment.
Prerequisites
To use the AWS SDK for Java, you must have:
• Apache Maven– If you use Apache Maven, you can specify only the SDK components you need or
the entire SDK (not recommended) as dependencies in your project. See Use the SDK with Apache
Maven (p. 7).
• Gradle– If you use Gradle, you can import the Maven Bill of Materials (BOM) to your Gradle project to
automatically manage SDK dependencies. See Use the SDK with Gradle (p. 10).
Note
Any build system that supports MavenCentral as an artifact source may be used.
If you are using one the above methods (for example, you are using Maven), then you do not need to
download and install the AWS JAR files (you can skip the following section). If you intend to build your
projects using a different IDE, with Apache Ant or by any other means, then download and extract the
SDK as shown in the next section.
4
AWS SDK for Java version 2 Developer Guide
Installing a Java Development Environment
mvn javadoc:javadoc
The AWS SDK for Java also works with OpenJDK and Amazon Corretto a distribution of the Open Java
Development Kit (OpenJDK). Download the latest OpenJDK version from https://openjdk.java.net/
install/index.html. Download the latest Amazon Corretto 8 or Amazon Corretto 11 version from https://
aws.amazon.com/corretto/.
Choosing a JVM
For the best performance of your server-based applications with the AWS SDK for Java, we recommend
that you use the 64-bit version of the Java Virtual Machine (JVM). This JVM runs only in server mode,
even if you specify the -Client option at run time.
This topic provides basic information about setting up your AWS credentials for local application
development using the AWS SDK for Java. If you need to set up credentials for use within an Amazon
EC2 instance or if you’re using the Eclipse IDE for development, see the following topics instead:
• When using an EC2 instance, create an IAM role and then give your EC2 instance access to that role as
shown in Configure IAM Roles for Amazon EC2 (Advanced) (p. 37).
• Set up AWS credentials within Eclipse using the AWS Toolkit for Eclipse. See Set up AWS Credentials in
the AWS Toolkit for Eclipse User Guide.
5
AWS SDK for Java version 2 Developer Guide
Refresh IMDS credentials
• Set credentials in the AWS credentials profile file on your local system, located at:
• ~/.aws/credentials on Linux, macOS, or Unix
• C:\Users\USERNAME\.aws\credentials on Windows
[default]
aws_access_key_id = your_access_key_id
aws_secret_access_key = your_secret_access_key
Substitute your own AWS credentials values for the values your_access_key_id and
your_secret_access_key.
• Set the AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables.
export AWS_ACCESS_KEY_ID=your_access_key_id
export AWS_SECRET_ACCESS_KEY=your_secret_access_key
set AWS_ACCESS_KEY_ID=your_access_key_id
set AWS_SECRET_ACCESS_KEY=your_secret_access_key
• For an EC2 instance, specify an IAM role and then give your EC2 instance access to that role. See IAM
Roles for Amazon EC2 in the Amazon EC2 User Guide for Linux Instances for a detailed discussion
about how this works.
Once you set your AWS credentials using one of these methods, the AWS SDK for Java loads them
automatically by using the default credential provider chain. For more information about working with
AWS credentials in your Java applications, see Supplying and Retrieving AWS Credentials (p. 13).
1. // Refresh credentials using a background thread, automatically every minute. This will
log an error if IMDS is down during
2. // a refresh, but your service calls will continue using the cached credentials until
the credentials are refreshed
3. // again one minute later.
4.
5. InstanceProfileCredentialsProvider credentials =
6. InstanceProfileCredentialsProvider.builder()
7. .asyncCredentialUpdateEnabled(true)
8. .build();
9.
10. S3Client client = S3Client.builder()
11. .credentialsProvider(credentials)
12. .build();
13.
14. // This is new: When you are done with the credentials provider, you must close it to
release the background thread.
15. credentials.close();
6
AWS SDK for Java version 2 Developer Guide
Set the AWS region
You can use techniques similar to those for setting credentials to set your default AWS Region:
• Set the AWS Region in the AWS config file on your local system, located at:
• ~/.aws/config on Linux, macOS, or Unix
• C:\Users\USERNAME\.aws\config on Windows
[default]
region = your_aws_region
Substitute your desired AWS Region (for example, “us-west-2”) for your_aws_region.
• Set the AWS_REGION environment variable.
export AWS_REGION=your_aws_region
set AWS_REGION=your_aws_region
For information about selecting a region, see AWS Region Selection (p. 16).
Prerequisites
To use the AWS SDK for Java with Maven, you need the following:
• Java 8.0 or later. You can download the latest Java SE Development Kit software from http://
www.oracle.com/technetwork/java/javase/downloads/. The AWS SDK for Java also works with
OpenJDK and Amazon Corretto, a distribution of the Open Java Development Kit (OpenJDK).
Download the latest OpenJDK version from https://openjdk.java.net/install/index.html. Download the
latest Amazon Corretto 8 or Amazon Corretto 11 version from https://aws.amazon.com/corretto/.
• Apache Maven. If you need to install Maven, go to http://maven.apache.org/ to download and install
it.
7
AWS SDK for Java version 2 Developer Guide
Create a Maven project
mvn -B archetype:generate \
-DarchetypeGroupId=software.amazon.awssdk \
-DarchetypeArtifactId=archetype-lambda -Dservice=s3 -Dregion=US_WEST_2 \
-DgroupId=com.example.myapp \
-DartifactId=myapp
Note
Replace com.example.myapp with the full package namespace of your application. Also replace
myapp with your project name. This becomes the name of the directory for your project.
This command creates a Maven project using the AWS Lambda project archetype. This project archetype
is preconfigured to compile with Java SE 8 and includes a dependency to the AWS SDK for Java.
For more information about creating and configuring Maven projects, see the Maven Getting Started
Guide.
To verify that this configuration is present, start by opening the pom.xml file from the project folder
you created (for example, myapp) when you executed the previous command. Look on lines 11 and 12
to see the Java compiler version setting for this Maven project, and the required inclusion of the Maven
compiler plugin on lines 71-75.
<project>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven.compiler.plugin.version}</version>
</plugin>
</plugins>
</build>
</project>
If you create your project with a different archetype or by using another method, you must ensure that
the Maven compiler plugin is part of the build and that its source and target properties are both set to
1.8 in the pom.xml file.
See the previous snippet for one way to configure these required settings.
Alternatively, you can configure the compiler configuration inline with the plugin declaration, as follows.
<project>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
8
AWS SDK for Java version 2 Developer Guide
Declare the SDK as a dependency
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
If you created your project using the project archetype as described earlier, the SDK is already
configured as a dependency in your project. We recommend that you update this configuration to
reference the latest version of the AWS SDK for Java. To do so, open the pom.xml file and change the
aws.java.sdk.version property (on line 16) to the latest version. The following is an example.
<project>
<properties>
<aws.java.sdk.version>2.13.7</aws.java.sdk.version>
</properties>
</project>
Find the latest version of the AWS SDK for Java in the AWS SDK for Java API Reference version 2.x.
If you created your Maven project in a different way, configure the latest version of the SDK for your
project by ensuring that the pom.xml file contains the following.
<project>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>bom</artifactId>
<version>2.X.X</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
</project>
Note
Replace 2.X.X in the pom.xml file with a valid version of the AWS SDK for Java version 2.
Although you can specify the version number for each component, you don’t need to because you
already declared the SDK version in the dependencyManagement section. To load a custom version of a
given module, specify a version number for its dependency.
If you created your project using the project archetype as described earlier, your project is already
configured with multiple dependencies. These include dependences for Lambda and Amazon DynamoDB,
as follows.
9
AWS SDK for Java version 2 Developer Guide
Build your project
<project>
<dependencies>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>dynamodb</artifactId>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-core</artifactId>
<version>1.2.0</version>
</dependency>
</dependencies>
</project>
Add the modules to your project for the AWS service and features you need for your project. The
modules (dependencies) that are managed by the AWS SDK for Java BOM are listed on the Maven central
repository (https://mvnrepository.com/artifact/software.amazon.awssdk/bom/latest).
Note
You can look at the pom.xml file from a code example to determine which dependencies you
need for your project. For example, if you’re interested in the dependencies for the Amazon
S3 service, see this example from the AWS Code Examples Repository on GitHub. (Look for the
pom.xml file file under /java2/example_code/s3.)
<project>
<dependencies>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>aws-sdk-java</artifactId>
<version>2.X.X</version>
</dependency>
</dependencies>
</project>
To build your Maven project from the command line, open a terminal or command prompt window,
navigate to your project directory (for example, myapp), enter or paste the following command, then
press Enter or Return.
mvn package
This creates a single .jar file (JAR) in the target directory (for example, myapp/target). This JAR
contains all of the SDK modules you specified as dependencies in your pom.xml file.
10
AWS SDK for Java version 2 Developer Guide
Use the SDK with Gradle
To manage SDK dependencies for your Gradle project, import the Maven bill of materials (BOM) for the
AWS SDK for Java into the build.gradle file.
Note
In the following examples, replace 2.X.X in the build.gradle file with a valid version of the
AWS SDK for Java v2. Find the latest version in the AWS SDK for Java API Reference version 2.x.
To configure the AWS SDK for Java for Gradle version 5.0 or later
...
dependencies {
implementation platform('software.amazon.awssdk:bom:2.X.X')
2. Specify the SDK modules to use in the dependencies section. For example, the following includes a
dependency for Amazon Kinesis.
...
dependencies {
...
implementation 'software.amazon.awssdk:kinesis'
...
}
Gradle automatically resolves the correct version of your SDK dependencies by using the information
from the BOM.
The following is an example of a complete build.gradle file that includes a dependency for Kinesis.
group 'aws.test'
version '1.0'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
implementation platform('software.amazon.awssdk:bom:2.X.X')
implementation 'software.amazon.awssdk:kinesis'
testImplementation group: 'junit', name: 'junit', version: '4.11'
}
Note
In the previous example, replace the dependency for Kinesis with the dependencies of the AWS
services you will use in your project. The modules (dependencies) that are managed by the AWS
SDK for Java BOM are listed on Maven central repository (https://mvnrepository.com/artifact/
software.amazon.awssdk/bom/latest).
For more information about specifying SDK dependencies by using the BOM, see Use the SDK with
Apache Maven (p. 7).
11
AWS SDK for Java version 2 Developer Guide
Creating Service Clients
Topics
• Creating Service Clients (p. 12)
• Supplying and Retrieving AWS Credentials (p. 13)
• AWS Region Selection (p. 16)
• Client Configuration (p. 18)
• Asynchronous Programming (p. 20)
• Configure metrics (p. 26)
• Waiters (p. 30)
• HTTP/2 Programming (p. 32)
• Exception Handling (p. 32)
• Logging AWS SDK for Java Calls (p. 33)
• Setting the JVM TTL for DNS Name Lookups (p. 36)
• Configure IAM Roles for Amazon EC2 (Advanced) (p. 37)
Each AWS service has a service interface with methods for each action in the service API. For example,
the service interface for Amazon DynamoDB is named DynamoDbClient. Each service interface has a
static factory builder method you can use to construct an implementation of the service interface.
In the AWS SDK for Java 2.0, the setters are named without the with prefix.
Note
The fluent setter methods return the builder object, so that you can chain the method calls
for convenience and for more readable code. After you configure the properties you want, you
can call the build method to create the client. Once a client is created, it’s immutable. The only
way to create a client with different settings is to build a new client.
12
AWS SDK for Java version 2 Developer Guide
Using DefaultClient
Using DefaultClient
The client builders have another factory method named create. This method creates a service client
with the default configuration. It uses the default provider chain to load credentials and the AWS Region.
If credentials or the region can’t be determined from the environment that the application is running
in, the call to create fails. See Supplying and Retrieving AWS Credentials (p. 13) and AWS Region
Selection (p. 16) for more information about how credentials and region are determined.
Client Lifecycle
Service clients in the SDK are thread-safe. For best performance, treat them as long-lived objects. Each
client has its own connection pool resource that is released when the client is garbage collected. The
clients in the AWS SDK for Java 2.0 now extend the AutoClosable interface. For best practices, explicitly
close a client by calling the close method.
To close a client
DynamoDbClient client = DynamoDbClient.create();
client.close();
The following example creates a new service client that uses the default credential provider chain:
S3Client s3 = S3Client.builder()
.region(Region.US_WEST_2)
.build();
13
AWS SDK for Java version 2 Developer Guide
Use the Default Credential Provider Chain
1. Java system properties–aws.accessKeyId and aws.secretAccessKey. The AWS SDK for Java
uses the SystemPropertyCredentialsProvider to load these credentials.
2. Environment variables–AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY. The AWS SDK for
Java uses the EnvironmentVariableCredentialsProvider class to load these credentials.
3. The default credential profiles file– The specific location of this file can vary per platform, but is
typically located at ~/.aws/credentials. This file is shared by many of the AWS SDKs and by the
AWS CLI. The AWS SDK for Java uses the ProfileCredentialsProvider to load these credentials.
You can create a credentials file by using the aws configure command provided by the AWS CLI.
You can also create it by editing the file with a text editor. For information about the credentials file
format, see AWS Credentials File Format (p. 15).
4. Amazon ECS container credentials– This is loaded from Amazon ECS if the environment
variable AWS_CONTAINER_CREDENTIALS_RELATIVE_URI is set. The AWS SDK for Java uses the
ContainerCredentialsProvider to load these credentials.
5. Instance profile credentials– This is used on Amazon EC2 instances, and delivered through the
Amazon EC2 metadata service. The AWS SDK for Java uses the InstanceProfileCredentialsProvider to
load these credentials.
Setting Credentials
To use AWS credentials, supply them in at least one of the preceding locations. For information about
setting credentials, see the following topics:
• To supply credentials in the environment or in the default credential profiles file, see Set up AWS
credentials and region for development (p. 5).
• To set Java system properties, see the System Properties tutorial on the official Java Tutorials website.
• To set up and use instance profile credentials with your EC2 instances, see Configure IAM Roles for
Amazon EC2 (Advanced) (p. 37).
You can use the AWS_PROFILE environment variable to change the profile loaded by the SDK.
For example, in Linux, macOS, or Unix, you run the following command to change the profile to
myProfile.
export AWS_PROFILE="myProfile"
set AWS_PROFILE="myProfile"
14
AWS SDK for Java version 2 Developer Guide
Use a Specific Credential Provider or Provider Chain
Setting the AWS_PROFILE environment variable affects credential loading for all officially supported
AWS SDKs and tools, for example the AWS CLI and the AWS Tools for PowerShell. To change only the
profile for a Java application, use the system property aws.profile instead.
You can use this feature to temporarily change the location where the AWS SDK for Java looks for your
credentials file. For example, set this variable with the command line. You can also set the environment
variable in your user or system environment to change it for the user specifically or across the system.
export AWS_CREDENTIAL_PROFILES_FILE=path/to/credentials_file
set AWS_CREDENTIAL_PROFILES_FILE=path/to/credentials_file
[default]
aws_access_key_id={YOUR_ACCESS_KEY_ID}
aws_secret_access_key={YOUR_SECRET_ACCESS_KEY}
[profile2]
aws_access_key_id={YOUR_ACCESS_KEY_ID}
aws_secret_access_key={YOUR_SECRET_ACCESS_KEY}
The profile name is specified in square brackets (for example, [default]), followed by the configurable
fields in that profile as key-value pairs. You can have multiple profiles in your credentials file. You
can add or edit them using aws configure --profile PROFILE_NAME to select the profile to
configure. In addition to the access key and secret access keys, you can specify a session token using the
aws_session_token field.
You provide an instance of a credentials provider or provider chain to a client builder that takes an
AwsCredentialsProvider interface as input.
The following example creates a new service client that uses the environment credentials provided, called
EnvironmentVariableCredentialsProvider:
15
AWS SDK for Java version 2 Developer Guide
Supply Credentials Explicitly
S3Client s3 = S3Client.builder()
.credentialsProvider(EnvironmentVariableCredentialsProvider.create())
.build();
For the full list of AWS SDK for Java-supplied credential providers and provider chains, see All Known
Implementing Classes in AwsCredentialsProvider.
Note
You supply credential providers or provider chains that you create by using your own credential
provider that implements the AwsCredentialsProvider interface.
1. Instantiate a class that provides the AwsCredentials interface, such as AwsSessionCredentials. Supply
it with the AWS access key and secret key to use for the connection.
2. Create an StaticCredentialsProvider with the AwsCredentials object.
3. Configure the client builder with the StaticCredentialsProvider and build the client.
The following example creates a new service client that uses credentials that you supplied:
In AWS SDK for Java 2.0, all the different region related classes from version 1.x have been collapsed into
one Region class. You can use this class for all region-related actions such as retrieving metadata about a
region or checking whether a service is available in a region.
Choosing a Region
You can specify a region name and the SDK will automatically choose an appropriate endpoint for you.
16
AWS SDK for Java version 2 Developer Guide
Choosing a Specific Endpoint
To explicitly set a region, we recommend that you use the constants defined in the Region class. This is
an enumeration of all publicly available regions. To create a client with a region from the class, use the
following code.
If the region you are attempting to use isn’t one of the constants in the Region class, you can create a
new region using the of method. This feature allows you access to new Regions without upgrading the
SDK.
Note
After you build a client with the builder, it’s immutable and the region cannot be changed. If you
are working with multiple AWS Regions for the same service, you should create multiple clients
—one per region.
For example, to configure the Amazon EC2 client to use the Europe (Ireland) Region, use the following
code.
See Regions and Endpoints for the current list of regions and their corresponding endpoints for all AWS
services.
To use the default credential/region provider chain to determine the region from the environment, use
the client builder’s create method.
If you don’t explicitly set a region using the region method, the SDK consults the default region
provider chain to try and determine the region to use.
17
AWS SDK for Java version 2 Developer Guide
Checking for Service Availability in an AWS Region
1. Any explicit region set by using region on the builder itself takes precedence over anything else.
2. The AWS_REGION environment variable is checked. If it’s set, that region is used to configure the
client.
Note
This environment variable is set by the Lambda container.
3. The SDK checks the AWS shared configuration file (usually located at ~/.aws/config). If the region
property is present, the SDK uses it.
• The AWS_CONFIG_FILE environment variable can be used to customize the location of the shared
config file.
• The AWS_PROFILE environment variable or the aws.profile system property can be used to
customize the profile that the SDK loads.
4. The SDK attempts to use the Amazon EC2 instance metadata service to determine the region of the
currently running Amazon EC2 instance.
5. If the SDK still hasn’t found a region by this point, client creation fails with an exception.
When developing AWS applications, a common approach is to use the shared configuration file (described
in Use the Default Credential Provider Chain (p. 13)) to set the region for local development, and rely
on the default region provider chain to determine the region when running on AWS infrastructure. This
greatly simplifies client creation and keeps your application portable.
DynamoDbClient.serviceMetadata().regions().forEach(System.out::println);
See the Region class documentation for the regions you can specify, and use the endpoint prefix of the
service to query.
Client Configuration
The AWS SDK for Java enables you to change the default client configuration. This can be useful when
you want to specify settings like those for HTTP transport. This section provides information about
configuring those settings.
Topics
• HTTP transport configuration (p. 18)
• Optimize cold start performance for AWS Lambda (p. 20)
18
AWS SDK for Java version 2 Developer Guide
HTTP transport configuration
Note
For more information about Apache HTTPClient, see HttpClient Overview.
POM Entry
<dependency>
<artifactId>netty-nio-client</artifactId>
<groupId>software.amazon.awssdk</groupId>
<version>2.0.0</version>
</dependency>
Maximum connections
You can set the maximum allowed number of open HTTP connections by using the maxConcurrency
method. The maxPendingConnectionAcquires method enables you to set the maximum requests
allowed to queue up once max concurrency is reached.
Important
Set the maximum connections to the number of concurrent transactions to avoid connection
contentions and poor performance.
Use the HTTP client builder to have the SDK manage its lifecycle. The HTTP client will be closed for you
when the service client is shut down.
Imports
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient;
import software.amazon.awssdk.services.kinesis.KinesisAsyncClient;
Code
.maxPendingConnectionAcquires(10_000))
.build();
You can also pass the HTTP client directly to the service client if you want to manage the lifecycle
yourself.
Code
19
AWS SDK for Java version 2 Developer Guide
Optimize cold start performance for AWS Lambda
.build();
httpClient.close();
Version 2.x includes three primary changes that contribute to this improvement:
You can gain additional SDK startup time improvement by setting specific configuration values on
the client builder. They each save some time at startup by reducing the amount of information your
application needs to find for initialization.
In your client builder, specify a region, use Environment Variable credentials provider, and specify
UrlConnectionClient as the httpClient. See the code snippet below for an example.
• The region lookup process for the SDK takes time. By specifying a region, you can save up to 80ms of
initialization time.
Note
By specifying an AWS region, the code will not run in other regions without modification.
• The process the SDK uses to look for credentials can take up to 90ms. By using the
EnvironmentVariableCredentialsProvider
Note
Using this credentials provider enables the code to be used in Lambda functions, but may not
work on Amazon EC2 or other systems.
• Instantiation time for JDK’s URLConnection library is much lower than Apache HTTP Client or Netty.
You can save up to 1 second by using this HTTP client.
Asynchronous Programming
The AWS SDK for Java 2.0 features truly nonblocking asynchronous clients that implement high
concurrency across a few threads. The AWS SDK for Java 1.11.x has asynchronous clients that are
wrappers around a thread pool and blocking synchronous clients that don’t provide the full benefit of
nonblocking I/O.
Synchronous methods block your thread’s execution until the client receives a response from the service.
Asynchronous methods return immediately, giving control back to the calling thread without waiting for
a response.
20
AWS SDK for Java version 2 Developer Guide
Non-Streaming Operations
Because an asynchronous method returns before a response is available, you need a way to get
the response when it’s ready. The AWS SDK for Java 2.0 asynchronous client methods return
CompletableFuture objects that allow you to access the response when it’s ready.
Non-Streaming Operations
For non-streaming operations, asynchronous method calls are similar to synchronous methods. However,
the asynchronous methods in the AWS SDK for Java return a CompletableFuture object that contains the
results of the asynchronous operation in the future.
Call the CompletableFuture whenComplete() method with an action to complete when the result
is available. CompletableFuture implements the Future interface so you can also get the response
object by calling the get() method as well.
The following is an example of an asynchronous operation that calls a Amazon DynamoDB function to
get a list of tables, receiving a CompletableFuture that can hold a ListTablesResponse object. The
action defined in the call to whenComplete() is done only when the asynchronous call is complete.
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.model.ListTablesRequest;
import software.amazon.awssdk.services.dynamodb.model.ListTablesResponse;
import java.util.List;
import java.util.concurrent.CompletableFuture;
Code
listTables(client);
}
CompletableFuture<ListTablesResponse> response =
client.listTables(ListTablesRequest.builder()
.build());
// Map the response to another CompletableFuture containing just the table names
CompletableFuture<List<String>> tableNames =
response.thenApply(ListTablesResponse::tableNames);
21
AWS SDK for Java version 2 Developer Guide
Non-Streaming Operations
// Lets the application shut down. Only close the client when you are
completely done with it.
client.close();
}
});
tableNames.join();
}
}
The following code example shows you how to retrieve an Item from a table by using the Asynchronous
client. Invoke the getItem method of the DynamoDbAsyncClient and pass it a GetItemRequest object
with the table name and primary key value of the item you want. This is typically how you pass data that
the operation requires. In this example, notice that a String value is passed.
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
Code
keyToGet.put(key, AttributeValue.builder()
.s(keyVal).build());
try {
} catch (DynamoDbException e) {
System.err.println(e.getMessage());
System.exit(1);
}
22
AWS SDK for Java version 2 Developer Guide
Streaming Operations
Streaming Operations
For streaming operations, you must provide an AsyncRequestBody to provide the content incrementally,
or an AsyncResponseTransformer to receive and process the response.
The following example uploads a file to Amazon S3 asynchronously by using the PutObject operation.
Imports
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.PutObjectResponse;
import java.nio.file.Paths;
import java.util.concurrent.CompletableFuture;
Code
if (args.length < 3) {
System.out.println(USAGE);
System.exit(1);
}
23
AWS SDK for Java version 2 Developer Guide
Streaming Operations
// Handle error
err.printStackTrace();
}
} finally {
// Lets the application shut down. Only close the client when you are
completely done with it.
client.close();
}
});
future.join();
}
}
The following example gets a file from Amazon S3 asynchronously by using the GetObject operation.
Imports
import software.amazon.awssdk.core.async.AsyncResponseTransformer;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import java.nio.file.Paths;
import java.util.concurrent.CompletableFuture;
Code
if (args.length < 3) {
System.out.println(USAGE);
System.exit(1);
}
24
AWS SDK for Java version 2 Developer Guide
Advanced Operations
Advanced Operations
The AWS SDK for Java 2.0 uses Netty an asynchronous event-driven network application framework, to
handle I/O threads. The AWS SDK for Java 2.0 creates an ExecutorService behind Netty, to complete
the futures returned from the HTTP client request through to the Netty client. This abstraction reduces
the risk of an application breaking the async process if developers choose to stop or sleep threads. By
default, 50 Threads are generated for each asynchronous client, and managed in a queue within the
ExecutorService.
Advanced users can specify their thread pool size when creating an asynchronous client using the
following option when building.
Code
To optimize performance, you can manage your own thread pool executor, and include it when
configuring your client.
25
AWS SDK for Java version 2 Developer Guide
Configure metrics
.FUTURE_COMPLETION_EXECUTOR,
executor
)
)
.build();
If you prefer to not use a thread pool, at all, use Runnable::run instead of using a thread pool executor.
Configure metrics
With the AWS SDK for Java version 2 (v2), you can collect metrics about the service clients in your
application, analyze the output in Amazon CloudWatch, and then act on it.
By default, metrics collection is disabled in the SDK. This topic helps you to enable and configure it.
Prerequisites
Before you can enable and use metrics, you must complete the following steps:
For example:
<project>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>bom</artifactId>
<version>2.14.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>cloudwach-metric-publisher</artifactId>
<version>2.14.0</version>
</dependency>
</dependencies>
</project>
26
AWS SDK for Java version 2 Developer Guide
How to enable metrics collection
Note
To enhance the security of your application, you can use dedicated set of credentials for
publishing metrics to CloudWatch. Create a separate IAM user with cloudwatch:PutMetricData
permissions and then use that user’s access key as credentials in the MetricPublisher
configuration for your application.
For more information, see the Amazon CloudWatch Permissions Reference in the Amazon
CloudWatch User Guide and Adding and Removing IAM Identity Permissions inthe AWS IAM User
Guide.
The following snippet demonstrates how to use a custom configuration for the metrics publisher for
a specific service client. The customizations include loading a separate credentials profile, specifying
a different region than the service client, and customizing how often the publisher sends metrics to
CloudWatch.
.credentialsProvider(EnvironmentVariableCredentialsProvider.create("cloudwatch"))
.region(Region.US_WEST_2)
.publishFrequency(5, TimeUnit.MINUTES)
.build();
27
AWS SDK for Java version 2 Developer Guide
Service client metrics
Note
The metrics available vary by HTTP client.
For more information, see Using Amazon CloudWatch Metrics and Using Amazon CloudWatch Alarms in
the Amazon CloudWatch User Guide.
This topic contains the list and descriptions for the metrics that are collected.
For more information about enabling and configuring metrics for the SDK, see Configure
metrics (p. 26).
28
AWS SDK for Java version 2 Developer Guide
Service client metrics
29
AWS SDK for Java version 2 Developer Guide
Waiters
PendingConcurrencyAcquires
The number of requests Integer Yes
that are blocked,
waiting for another TCP
connection or a new
stream to be available
from the connection
pool
Waiters
The waiters utility of the AWS SDK for Java version 2 (v2) enables you to validate that AWS resources are
in a specified state before performing operations on those resources.
A waiter is an abstraction used to poll AWS resources, such as DynamoDB tables or Amazon S3 buckets,
until a desired state is reached (or until a determination is made that the resource won’t ever reach
the desired state). Instead of writing logic to continuously poll your AWS resources, which can be
cumbersome and error-prone, you can use waiters to poll a resource and have your code continue to run
after the resource is ready.
Prerequisites
Before you can use waiters in a project with the AWS SDK for Java, you must complete the following
steps:
For example:
<project>
<dependencyManagement>
<dependencies>
30
AWS SDK for Java version 2 Developer Guide
Using waiters
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>bom</artifactId>
<version>2.15.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
</project>
Using waiters
To instantiate a waiters object, first create a service client. Set the service client’s waiter() method as
the value of the waiter object. Once the waiter instance exists, set its response options to execute the
appropriate code.
Synchronous programming
The following code snippet shows how to wait for a DynamoDB table to exist and be in an ACTIVE state.
WaiterResponse<DescribeTableResponse> waiterResponse =
waiter.waitUntilTableExists(r -> r.tableName("myTable"));
Asynchronous programming
The following code snippet shows how to wait for a DynamoDB table to no longer exist.
CompletableFuture<WaiterResponse<DescribeTableResponse>> waiterResponse =
asyncWaiter.waitUntilTableNotExists(r -> r.tableName("myTable"));
waiterResponse.whenComplete((r, t) -> {
if (t == null) {
// print out the matched ResourceNotFoundException
r.matched().exception().ifPresent(System.out::println);
}
}).join();
Configuring waiters
You can customize the configuration for a waiter by using the overrideConfiguration() on its
builder. For some operations, you can apply a custom configuration when you make the request.
Configure a waiter
The following code snippet shows how to override the configuration on a waiter.
// sync
31
AWS SDK for Java version 2 Developer Guide
HTTP/2 Programming
DynamoDbWaiter waiter =
DynamoDbWaiter.builder()
.overrideConfiguration(b -> b.maxAttempts(10))
.client(dynamoDbClient)
.build();
// async
DynamoDbAsyncWaiter asyncWaiter =
DynamoDbAsyncWaiter.builder()
.client(dynamoDbAsyncClient)
.overrideConfiguration(o -> o.backoffStrategy(
FixedDelayBackoffStrategy.create(Duration.ofSeconds(2))))
.scheduledExecutorService(Executors.newScheduledThreadPool(3))
.build();
HTTP/2 Programming
HTTP/2 is a major revision of the HTTP protocol. This new version has several enhancements to improve
performance:
Developers upgrading to the latest SDKs will automatically use HTTP/2 when it’s supported by the
service they’re working with. New programming interfaces seamlessly take advantage of HTTP/2
features and provide new ways to build applications.
The AWS SDK for Java 2.0 features new APIs for event streaming that implement the HTTP/2 protocol.
For examples of how to use these new APIs, see Kinesis Examples Using the AWS SDK for Java (p. 103).
Exception Handling
Understanding how and when the AWS SDK for Java throws exceptions is important to building high-
quality applications using the SDK. The following sections describe the different cases of exceptions that
are thrown by the SDK and how to handle them appropriately.
32
AWS SDK for Java version 2 Developer Guide
SdkServiceException (and Subclasses)
• To allow developers fine-grained control over the errors they want to handle without forcing them to
handle exceptional cases they aren’t concerned about (and making their code overly verbose)
• To prevent scalability issues inherent with checked exceptions in large applications
In general, checked exceptions work well on small scales, but can become troublesome as applications
grow and become more complex.
When you encounter an SdkServiceException, you know that your request was successfully sent to
the AWS service but couldn’t be successfully processed. This can be because of errors in the request’s
parameters or because of issues on the service side.
SdkClientException
SdkClientException indicates that a problem occurred inside the Java client code, either while trying
to send a request to AWS or while trying to parse a response from AWS. An SdkClientException
is generally more severe than an SdkServiceException, and indicates a major problem that is
preventing the client from making service calls to AWS services. For example, the AWS SDK for Java
throws an SdkClientException if no network connection is available when you try to call an
operation on one of the clients.
Supported logging systems include the Java Logging Framework and Apache Log4j, among others. This
topic shows you how to use Log4j. You can use the SDK’s logging functionality without making any
changes to your application code.
33
AWS SDK for Java version 2 Developer Guide
Log4j Configuration file
Place your configuration file in a directory on your classpath. The Log4j JAR and the log4j2.xml file do
not have to be in the same directory.
The log4j2.xml configuration file specifies properties such as logging level, where logging output
is sent (for example, to a file or to the console), and the format of the output. The logging level is
the granularity of output that the logger generates. Log4j supports the concept of multiple logging
hierarchies. The logging level is set independently for each hierarchy. The following two logging
hierarchies are available in the AWS SDK for Java:
• software.amazon.awssdk
• org.apache.http.wire
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
</dependency>
If you’re using the Eclipse IDE, you can set the classpath by opening the menu and navigating to Project |
Properties | Java Build Path.
The following log4j2.xml file sets the rootLogger to WARN, which causes warning and error messages
from all loggers in the “software.amazon.awssdk” hierarchy to be included. Alternatively, you can
explicitly set the software.amazon.awssdk logger to WARN.
<Configuration status="WARN">
<Appenders>
<Console name="ConsoleAppender" target="SYSTEM_OUT">
<PatternLayout pattern="%d{YYYY-MM-dd HH:mm:ss} [%t] %-5p %c:%L - %m%n" />
</Console>
</Appenders>
34
AWS SDK for Java version 2 Developer Guide
Request/Response Summary Logging
<Loggers>
<Root level="WARN">
<AppenderRef ref="ConsoleAppender"/>
</Root>
<Logger name="software.amazon.awssdk" level="WARN" />
</Loggers>
</Configuration>
<Configuration status="WARN">
<Appenders>
<Console name="ConsoleAppender" target="SYSTEM_OUT">
<PatternLayout pattern="%d{YYYY-MM-dd HH:mm:ss} [%t] %-5p %c:%L - %m%n" />
</Console>
</Appenders>
<Loggers>
<Root level="WARN">
<AppenderRef ref="ConsoleAppender"/>
</Root>
<Logger name="software.amazon.awssdk" level="WARN" />
<Logger name="software.amazon.awssdk.request" level="DEBUG" />
</Loggers>
</Configuration>
The following log4j2.xml file turns on full wire logging in Apache HttpClient.
<Configuration status="WARN">
<Appenders>
<Console name="ConsoleAppender" target="SYSTEM_OUT">
<PatternLayout pattern="%d{YYYY-MM-dd HH:mm:ss} [%t] %-5p %c:%L - %m%n" />
35
AWS SDK for Java version 2 Developer Guide
Setting the JVM TTL for DNS Name Lookups
</Console>
</Appenders>
<Loggers>
<Root level="WARN">
<AppenderRef ref="ConsoleAppender"/>
</Root>
<Logger name="software.amazon.awssdk" level="WARN" />
<Logger name="software.amazon.awssdk.request" level="DEBUG" />
<Logger name="org.apache.http.wire" level="DEBUG" />
</Loggers>
</Configuration>
Additional Maven dependency on log4j-1.2-api is required for wire-logging with Apache as it uses 1.2
under the hood. Add the following to the pom.xml file if you enable wire logging.
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-1.2-api</artifactId>
</dependency>
Because AWS resources use DNS name entries that occasionally change, we recommend that you
configure your JVM with a TTL value of no more than 60 seconds. This ensures that when a resource’s
IP address changes, your application will be able to receive and use the resource’s new IP address by
requerying the DNS.
On some Java configurations, the JVM default TTL is set so that it will never refresh DNS entries until
the JVM is restarted. Thus, if the IP address for an AWS resource changes while your application is still
running, it won’t be able to use that resource until you manually restart the JVM and the cached IP
information is refreshed. In this case, it’s crucial to set the JVM’s TTL so that it will periodically refresh its
cached IP information.
Note
The default TTL can vary according to the version of your JVM and whether a security manager
is installed. Many JVMs provide a default TTL less than 60 seconds. If you’re using such a JVM
and not using a security manager, you can ignore the remainder of this topic.
• globally, for all applications that use the JVM. Set networkaddress.cache.ttl in the
$JAVA_HOME/jre/lib/security/java.security file:
networkaddress.cache.ttl=60
• for your application only, set networkaddress.cache.ttl in your application’s initialization code:
java.security.Security.setProperty("networkaddress.cache.ttl" , "60");
36
AWS SDK for Java version 2 Developer Guide
Configure IAM Roles for Amazon EC2 (Advanced)
This topic provides information about how to use IAM roles with AWS SDK for Java applications running
on Amazon EC2. For more information about IAM instances, see IAM Roles for Amazon EC2 in the
Amazon EC2 User Guide for Linux Instances.
The final step in the default provider chain is available only when running your application on an
Amazon EC2 instance. However, it provides the greatest ease of use and best security when working
with Amazon EC2 instances. You can also pass an InstanceProfileCredentialsProvider instance directly to
the client constructor to get instance profile credentials without proceeding through the entire default
provider chain.
For example:
S3Client s3 = S3Client.builder()
.credentialsProvider(InstanceProfileCredentialsProvider.builder().build())
.build();
When you use this approach, the SDK retrieves temporary AWS credentials that have the same
permissions as those associated with the IAM role that is associated with the Amazon EC2 instance
in its instance profile. Although these credentials are temporary and would eventually expire,
InstanceProfileCredentialsProvider periodically refreshes them for you so that the obtained
credentials continue to allow access to AWS.
37
AWS SDK for Java version 2 Developer Guide
Walkthrough: Using IAM roles for Amazon EC2 Instances
because you’ll need it when you launch your Amazon EC2 instance.
6. On the Review page, choose Create Role.
To launch an Amazon EC2 instance using the console, follow the directions in Getting Started with
Amazon EC2 Linux Instances in the Amazon EC2 User Guide for Linux Instances.
When you reach the Review Instance Launch page, select Edit instance details. In IAM role, choose the
IAM role that you created previously. Complete the procedure as directed.
Note
You need to create or use an existing security group and key pair to connect to the instance.
With this IAM and Amazon EC2 setup, you can deploy your application to the EC2 instance and it will
have read access to the Amazon S3 service.
38
AWS SDK for Java version 2 Developer Guide
Amazon CloudWatch Examples
Find the source code for these examples and others in the AWS documentation code examples repository
on GitHub.
To propose a new code example for the AWS documentation team to consider producing, create a new
request. The team is looking to produce code examples that cover broader scenarios and use cases,
versus simple code snippets that cover only individual API calls. For instructions, see the “Proposing new
code examples” section in the Readme on GitHub.
Topics
• CloudWatch examples using the AWS SDK for Java (p. 39)
• Amazon Cognito examples (p. 48)
• DynamoDB Examples Using the AWS SDK for Java (p. 53)
• Amazon EC2 Examples Using the AWS SDK for Java (p. 71)
• IAM Examples Using the AWS SDK for Java (p. 85)
• Kinesis Examples Using the AWS SDK for Java (p. 103)
• AWS Lambda examples for the AWS SDK for Java (p. 109)
• Amazon Pinpoint examples (p. 111)
• Amazon S3 Examples Using the AWS SDK for Java (p. 119)
• Working with Amazon S3 Presigned URLs (p. 128)
• Amazon Simple Notification Service examples (p. 131)
• Amazon SQS Examples Using the AWS SDK for Java (p. 135)
• Amazon Transcribe Examples Using the AWS SDK for Java (p. 141)
• Retrieving Paginated Results (p. 145)
Amazon CloudWatch monitors your Amazon Web Services (AWS) resources and the applications you run
on AWS in real time. You can use CloudWatch to collect and track metrics, which are variables you can
measure for your resources and applications. CloudWatch alarms send notifications or automatically
make changes to the resources you are monitoring based on rules that you define.
For more information about CloudWatch, see the Amazon CloudWatch User Guide.
The following examples include only the code needed to demonstrate each technique. The complete
example code is available on GitHub. From there, you can download a single source file or clone the
repository locally to get all the examples to build and run.
Topics
• Get metrics from CloudWatch (p. 40)
• Publish custom metric data (p. 41)
39
AWS SDK for Java version 2 Developer Guide
Get metrics from CloudWatch
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cloudwatch.CloudWatchClient;
import software.amazon.awssdk.services.cloudwatch.model.ListMetricsRequest;
import software.amazon.awssdk.services.cloudwatch.model.ListMetricsResponse;
import software.amazon.awssdk.services.cloudwatch.model.Metric;
Code
while(!done) {
ListMetricsResponse response;
if (nextToken == null) {
ListMetricsRequest request = ListMetricsRequest.builder()
.namespace(namespace)
.build();
response = cw.listMetrics(request);
} else {
ListMetricsRequest request = ListMetricsRequest.builder()
.namespace(namespace)
.nextToken(nextToken)
.build();
response = cw.listMetrics(request);
}
if(response.nextToken() == null) {
done = true;
} else {
nextToken = response.nextToken();
40
AWS SDK for Java version 2 Developer Guide
Publish custom metric data
}
}
The results may be paged. To retrieve the next batch of results, call nextToken on the response object
and use the token value to build a new request object. Then call the listMetrics method again with
the new request.
More information
• ListMetrics in the Amazon CloudWatch API Reference.
Imports
package com.example.cloudwatch;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cloudwatch.CloudWatchClient;
import software.amazon.awssdk.services.cloudwatch.model.Dimension;
import software.amazon.awssdk.services.cloudwatch.model.MetricDatum;
import software.amazon.awssdk.services.cloudwatch.model.StandardUnit;
import software.amazon.awssdk.services.cloudwatch.model.PutMetricDataRequest;
import software.amazon.awssdk.services.cloudwatch.model.PutMetricDataResponse;
import software.amazon.awssdk.services.cloudwatch.model.CloudWatchException;
Code
try {
Dimension dimension = Dimension.builder()
.name("UNIQUE_PAGES")
.value("URLS").build();
41
AWS SDK for Java version 2 Developer Guide
Work with CloudWatch alarms
.namespace("SITE/TRAFFIC")
.metricData(datum).build();
} catch (CloudWatchException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
System.out.printf("Successfully put data point %f", dataPoint);
More information
• Using Amazon CloudWatch Metrics in the Amazon CloudWatch User Guide.
• AWS Namespaces in the Amazon CloudWatch User Guide.
• PutMetricData in the Amazon CloudWatch API Reference.
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cloudwatch.CloudWatchClient;
import software.amazon.awssdk.services.cloudwatch.model.Dimension;
import software.amazon.awssdk.services.cloudwatch.model.PutMetricAlarmRequest;
import software.amazon.awssdk.services.cloudwatch.model.ComparisonOperator;
import software.amazon.awssdk.services.cloudwatch.model.Statistic;
import software.amazon.awssdk.services.cloudwatch.model.StandardUnit;
import software.amazon.awssdk.services.cloudwatch.model.PutMetricAlarmResponse;
import software.amazon.awssdk.services.cloudwatch.model.CloudWatchException;
Code
try {
Dimension dimension = Dimension.builder()
.name("InstanceId")
.value(instanceId).build();
42
AWS SDK for Java version 2 Developer Guide
Work with CloudWatch alarms
.actionsEnabled(false)
.alarmDescription(
"Alarm when server CPU utilization exceeds 70%")
.unit(StandardUnit.SECONDS)
.dimensions(dimension)
.build();
} catch (CloudWatchException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
System.out.printf(
"Successfully created alarm with name %s", alarmName);
List alarms
To list the CloudWatch alarms that you have created, call the CloudWatchClient’s describeAlarms
method with a DescribeAlarmsRequest that you can use to set options for the result.
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cloudwatch.CloudWatchClient;
import software.amazon.awssdk.services.cloudwatch.model.CloudWatchException;
import software.amazon.awssdk.services.cloudwatch.model.DescribeAlarmsRequest;
import software.amazon.awssdk.services.cloudwatch.model.DescribeAlarmsResponse;
import software.amazon.awssdk.services.cloudwatch.model.MetricAlarm;
Code
try {
while(!done) {
DescribeAlarmsResponse response;
if (newToken == null) {
DescribeAlarmsRequest request = DescribeAlarmsRequest.builder().build();
response = cw.describeAlarms(request);
} else {
DescribeAlarmsRequest request = DescribeAlarmsRequest.builder()
.nextToken(newToken)
.build();
response = cw.describeAlarms(request);
}
if(response.nextToken() == null) {
done = true;
} else {
43
AWS SDK for Java version 2 Developer Guide
Work with CloudWatch alarms
newToken = response.nextToken();
}
}
} catch (CloudWatchException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
System.out.printf("Done");
The list of alarms can be obtained by calling MetricAlarms on the DescribeAlarmsResponse that is
returned by describeAlarms.
The results may be paged. To retrieve the next batch of results, call nextToken on the response object
and use the token value to build a new request object. Then call the describeAlarms method again
with the new request.
Note
You can also retrieve alarms for a specific metric by using the CloudWatchClient’s
describeAlarmsForMetric method. Its use is similar to describeAlarms.
Delete alarms
To delete CloudWatch alarms, call the CloudWatchClient’s deleteAlarms method with a
DeleteAlarmsRequest containing one or more names of alarms that you want to delete.
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cloudwatch.CloudWatchClient;
import software.amazon.awssdk.services.cloudwatch.model.CloudWatchException;
import software.amazon.awssdk.services.cloudwatch.model.DeleteAlarmsRequest;
Code
try {
DeleteAlarmsRequest request = DeleteAlarmsRequest.builder()
.alarmNames(alarmName).build();
cw.deleteAlarms(request);
System.out.printf("Successfully deleted alarm %s", alarmName);
} catch (CloudWatchException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
More information
• Creating Amazon CloudWatch Alarms in the Amazon CloudWatch User Guide
• PutMetricAlarm in the Amazon CloudWatch API Reference
• DescribeAlarms in the Amazon CloudWatch API Reference
• DeleteAlarms in the Amazon CloudWatch API Reference
44
AWS SDK for Java version 2 Developer Guide
Use alarm actions in CloudWatch
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cloudwatch.CloudWatchClient;
import software.amazon.awssdk.services.cloudwatch.model.CloudWatchException;
import software.amazon.awssdk.services.cloudwatch.model.EnableAlarmActionsRequest;
import software.amazon.awssdk.services.cloudwatch.model.EnableAlarmActionsResponse;
Code
try {
EnableAlarmActionsRequest request = EnableAlarmActionsRequest.builder()
.alarmNames(alarm).build();
} catch (CloudWatchException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cloudwatch.CloudWatchClient;
import software.amazon.awssdk.services.cloudwatch.model.CloudWatchException;
import software.amazon.awssdk.services.cloudwatch.model.DisableAlarmActionsRequest;
import software.amazon.awssdk.services.cloudwatch.model.DisableAlarmActionsResponse;
Code
45
AWS SDK for Java version 2 Developer Guide
Send events to CloudWatch
try {
DisableAlarmActionsRequest request = DisableAlarmActionsRequest.builder()
.alarmNames(alarmName).build();
} catch (CloudWatchException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
System.out.printf(
"Successfully disabled actions on alarm %s", alarmName);
}
More information
• Create Alarms to Stop, Terminate, Reboot, or Recover an Instance in the Amazon CloudWatch User
Guide
• PutMetricAlarm in the Amazon CloudWatch API Reference
• EnableAlarmActions in the Amazon CloudWatch API Reference
• DisableAlarmActions in the Amazon CloudWatch API Reference
Add events
To add custom CloudWatch events, call the CloudWatchEventsClient’s putEvents method with a
PutEventsRequest object that contains one or more PutEventsRequestEntry objects that provide details
about each event. You can specify several parameters for the entry such as the source and type of the
event, resources associated with the event, and so on.
Note
You can specify a maximum of 10 events per call to putEvents.
Imports
import software.amazon.awssdk.services.cloudwatch.model.CloudWatchException;
import software.amazon.awssdk.services.cloudwatchevents.CloudWatchEventsClient;
import software.amazon.awssdk.services.cloudwatchevents.model.PutEventsRequest;
import software.amazon.awssdk.services.cloudwatchevents.model.PutEventsRequestEntry;
import software.amazon.awssdk.services.cloudwatchevents.model.PutEventsResponse;
Code
try {
46
AWS SDK for Java version 2 Developer Guide
Send events to CloudWatch
} catch (CloudWatchException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
Add rules
To create or update a rule, call the CloudWatchEventsClient’s putRule method with a PutRuleRequest
with the name of the rule and optional parameters such as the event pattern, IAM role to associate with
the rule, and a scheduling expression that describes how often the rule is run.
Imports
import software.amazon.awssdk.services.cloudwatch.model.CloudWatchException;
import software.amazon.awssdk.services.cloudwatchevents.CloudWatchEventsClient;
import software.amazon.awssdk.services.cloudwatchevents.model.PutRuleRequest;
import software.amazon.awssdk.services.cloudwatchevents.model.PutRuleResponse;
import software.amazon.awssdk.services.cloudwatchevents.model.RuleState;
Code
try {
PutRuleRequest request = PutRuleRequest.builder()
.name(ruleName)
.roleArn("arn:aws:iam::335446330391:role/testRole1")
.scheduleExpression("rate(5 minutes)")
.state(RuleState.ENABLED)
.build();
response = cwe.putRule(request);
} catch (
CloudWatchException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
System.out.printf(
"Successfully created CloudWatch events rule %s with ARN %s",
roleArn, response.ruleArn());
}
47
AWS SDK for Java version 2 Developer Guide
Amazon Cognito Examples
Add targets
Targets are the resources that are invoked when a rule is triggered. Example targets include Amazon EC2
instances, Lambda functions, Kinesis streams, Amazon ECS tasks, Step Functions state machines, and
built-in targets.
Imports
import software.amazon.awssdk.services.cloudwatchevents.CloudWatchEventsClient;
import software.amazon.awssdk.services.cloudwatchevents.model.PutTargetsRequest;
import software.amazon.awssdk.services.cloudwatchevents.model.PutTargetsResponse;
import software.amazon.awssdk.services.cloudwatchevents.model.Target;
Code
More information
• Adding Events with PutEvents in the Amazon CloudWatch Events User Guide
• Schedule Expressions for Rules in the Amazon CloudWatch Events User Guide
• Event Types for CloudWatch Events in the Amazon CloudWatch Events User Guide
• Events and Event Patterns in the Amazon CloudWatch Events User Guide
• PutEvents in the Amazon CloudWatch Events API Reference
• PutTargets in the Amazon CloudWatch Events API Reference
• PutRule in the Amazon CloudWatch Events API Reference
48
AWS SDK for Java version 2 Developer Guide
List users from a user pool
To create a user pool, start by building a CreateUserPoolRequest object, with the name of the user pool
as the value of its poolName(). Call the createUserPool() method of your CreateUserPoolRequest,
passing in the CreateUserPoolRequest object. You can capture the result of this request as a
CreateUserPoolResponse object, as demonstrated in the following code snippet.
Imports
import software.amazon.awssdk.regions.Region;
import
software.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient;
import
software.amazon.awssdk.services.cognitoidentityprovider.model.CognitoIdentityProviderException;
import software.amazon.awssdk.services.cognitoidentityprovider.model.CreateUserPoolRequest;
import
software.amazon.awssdk.services.cognitoidentityprovider.model.CreateUserPoolResponse;
Code
try {
CreateUserPoolResponse repsonse = cognitoclient.createUserPool(
CreateUserPoolRequest.builder()
.poolName(userPoolName)
.build()
);
return repsonse.userPool().id();
Imports
import software.amazon.awssdk.regions.Region;
import
software.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient;
import
software.amazon.awssdk.services.cognitoidentityprovider.model.CognitoIdentityProviderException;
import software.amazon.awssdk.services.cognitoidentityprovider.model.ListUserPoolsResponse;
import software.amazon.awssdk.services.cognitoidentityprovider.model.ListUserPoolsRequest;
import
software.amazon.awssdk.services.cognitoidentityprovider.model.UserPoolDescriptionType;
Code
49
AWS SDK for Java version 2 Developer Guide
Create an identity pool
try {
ListUserPoolsResponse response = cognitoclient
.listUserPools(
ListUserPoolsRequest.builder()
.maxResults(10)
.build()
);
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cognitoidentity.CognitoIdentityClient;
import software.amazon.awssdk.services.cognitoidentity.model.CreateIdentityPoolRequest;
import software.amazon.awssdk.services.cognitoidentity.model.CreateIdentityPoolResponse;
import
software.amazon.awssdk.services.cognitoidentityprovider.model.CognitoIdentityProviderException;
Code
try {
CreateIdentityPoolResponse response = cognitoclient.createIdentityPool(
CreateIdentityPoolRequest.builder()
.allowUnauthenticatedIdentities(false)
.identityPoolName(identityPoolName)
.build()
);
return response.identityPoolId();
50
AWS SDK for Java version 2 Developer Guide
Add an app client
Imports
import software.amazon.awssdk.regions.Region;
import
software.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient;
import
software.amazon.awssdk.services.cognitoidentityprovider.model.CognitoIdentityProviderException;
import
software.amazon.awssdk.services.cognitoidentityprovider.model.CreateUserPoolClientRequest;
import
software.amazon.awssdk.services.cognitoidentityprovider.model.CreateUserPoolClientResponse;
Code
try {
51
AWS SDK for Java version 2 Developer Guide
Get credentials for an ID
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cognitoidentity.CognitoIdentityClient;
import software.amazon.awssdk.services.cognitoidentity.model.CognitoIdentityProvider;
import software.amazon.awssdk.services.cognitoidentity.model.UpdateIdentityPoolRequest;
import software.amazon.awssdk.services.cognitoidentity.model.UpdateIdentityPoolResponse;
import
software.amazon.awssdk.services.cognitoidentityprovider.model.CognitoIdentityProviderException;
import java.util.ArrayList;
import java.util.List;
Code
try{
AdminCreateUserResponse response = cognitoclient.adminCreateUser(
AdminCreateUserRequest.builder()
.userPoolId(userPoolId)
.username(name)
.userAttributes(AttributeType.builder()
.name("email")
.value(email)
.build())
.messageAction("SUPPRESS")
.build()
);
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cognitoidentity.CognitoIdentityClient;
import
software.amazon.awssdk.services.cognitoidentity.model.GetCredentialsForIdentityRequest;
import
software.amazon.awssdk.services.cognitoidentity.model.GetCredentialsForIdentityResponse;
import
software.amazon.awssdk.services.cognitoidentityprovider.model.CognitoIdentityProviderException;
52
AWS SDK for Java version 2 Developer Guide
Amazon DynamoDB Examples
Code
try {
GetCredentialsForIdentityRequest getCredentialsForIdentityRequest =
GetCredentialsForIdentityRequest.builder()
.identityId(identityId)
.build();
GetCredentialsForIdentityResponse response =
cognitoclient.getCredentialsForIdentity(getCredentialsForIdentityRequest);
System.out.println("Identity ID " + response.identityId() + ", Access key ID "
+ response.credentials().accessKeyId());
} catch (CognitoIdentityProviderException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
The following examples include only the code needed to demonstrate each technique. The complete
example code is available on GitHub. From there, you can download a single source file or clone the
repository locally to get all the examples to build and run.
Topics
• Work with tables in DynamoDB (p. 53)
• Work with items in DynamoDB (p. 60)
• Map items in DynamoDB tables (p. 64)
A primary key can be simple, consisting of a single partition (HASH) key, or composite, consisting of a
partition and a sort (RANGE) key.
Each key value has an associated data type, enumerated by the ScalarAttributeType class. The key
value can be binary (B), numeric (N), or a string (S). For more information, see Naming Rules and Data
Types in the Amazon DynamoDB Developer Guide.
53
AWS SDK for Java version 2 Developer Guide
Work with tables in DynamoDB
• Provisioned throughput are values that define the number of reserved read/write capacity units for the
table.
Note
Amazon DynamoDB pricing is based on the provisioned throughput values that you set on
your tables, so reserve only as much capacity as you think you’ll need for your table.
Provisioned throughput for a table can be modified at any time, so you can adjust capacity as
your needs change.
Create a table
Use the DynamoDbClient’s createTable method to create a new DynamoDB table. You need to
construct table attributes and a table schema, both of which are used to identify the primary key of your
table. You must also supply initial provisioned throughput values and a table name.
Note
If a table with the name you chose already exists, an DynamoDbException is thrown.
Imports
import software.amazon.awssdk.core.waiters.WaiterResponse;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.model.CreateTableRequest;
import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition;
import software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType;
import software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType;
import software.amazon.awssdk.services.dynamodb.model.KeySchemaElement;
import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughput;
import software.amazon.awssdk.services.dynamodb.model.KeyType;
import software.amazon.awssdk.services.dynamodb.model.CreateTableResponse;
import software.amazon.awssdk.services.dynamodb.model.DescribeTableRequest;
import software.amazon.awssdk.services.dynamodb.model.DescribeTableResponse;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.waiters.DynamoDbWaiter;
Code
54
AWS SDK for Java version 2 Developer Guide
Work with tables in DynamoDB
.build())
.tableName(tableName)
.build();
newTable = response.tableDescription().tableName();
return newTable;
} catch (DynamoDbException e) {
System.err.println(e.getMessage());
System.exit(1);
}
return "";
}
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition;
import software.amazon.awssdk.services.dynamodb.model.CreateTableRequest;
import software.amazon.awssdk.services.dynamodb.model.CreateTableResponse;
import software.amazon.awssdk.services.dynamodb.model.KeySchemaElement;
import software.amazon.awssdk.services.dynamodb.model.KeyType;
import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughput;
import software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
Code
55
AWS SDK for Java version 2 Developer Guide
Work with tables in DynamoDB
KeySchemaElement.builder()
.attributeName("Language")
.keyType(KeyType.HASH)
.build(),
KeySchemaElement.builder()
.attributeName("Greeting")
.keyType(KeyType.RANGE)
.build())
.provisionedThroughput(
ProvisionedThroughput.builder()
.readCapacityUnits(new Long(10))
.writeCapacityUnits(new Long(10)).build())
.tableName(tableName)
.build();
try {
CreateTableResponse result = ddb.createTable(request);
tableId = result.tableDescription().tableId();
return tableId;
} catch (DynamoDbException e) {
System.err.println(e.getMessage());
System.exit(1);
}
List tables
You can list the tables in a particular region by calling the DynamoDbClient’s listTables method.
Note
If the named table doesn’t exist for your account and region, a ResourceNotFoundException is
thrown.
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.ListTablesResponse;
import software.amazon.awssdk.services.dynamodb.model.ListTablesRequest;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import java.util.List;
Code
while(moreTables) {
try {
ListTablesResponse response = null;
if (lastName == null) {
ListTablesRequest request = ListTablesRequest.builder().build();
response = ddb.listTables(request);
} else {
ListTablesRequest request = ListTablesRequest.builder()
.exclusiveStartTableName(lastName).build();
56
AWS SDK for Java version 2 Developer Guide
Work with tables in DynamoDB
response = ddb.listTables(request);
}
if (tableNames.size() > 0) {
for (String curName : tableNames) {
System.out.format("* %s\n", curName);
}
} else {
System.out.println("No tables found!");
System.exit(0);
}
lastName = response.lastEvaluatedTableName();
if (lastName == null) {
moreTables = false;
}
} catch (DynamoDbException e) {
System.err.println(e.getMessage());
System.exit(1);
}
}
By default, up to 100 tables are returned per call—use lastEvaluatedTableName on the returned
ListTablesResponse object to get the last table that was evaluated. You can use this value to start the
listing after the last returned value of the previous listing.
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition;
import software.amazon.awssdk.services.dynamodb.model.DescribeTableRequest;
import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughputDescription;
import software.amazon.awssdk.services.dynamodb.model.TableDescription;
import java.util.List;
Code
try {
TableDescription tableInfo =
ddb.describeTable(request).table();
57
AWS SDK for Java version 2 Developer Guide
Work with tables in DynamoDB
if (tableInfo != null) {
System.out.format("Table name : %s\n",
tableInfo.tableName());
System.out.format("Table ARN : %s\n",
tableInfo.tableArn());
System.out.format("Status : %s\n",
tableInfo.tableStatus());
System.out.format("Item count : %d\n",
tableInfo.itemCount().longValue());
System.out.format("Size (bytes): %d\n",
tableInfo.tableSizeBytes().longValue());
ProvisionedThroughputDescription throughputInfo =
tableInfo.provisionedThroughput();
System.out.println("Throughput");
System.out.format(" Read Capacity : %d\n",
throughputInfo.readCapacityUnits().longValue());
System.out.format(" Write Capacity: %d\n",
throughputInfo.writeCapacityUnits().longValue());
List<AttributeDefinition> attributes =
tableInfo.attributeDefinitions();
System.out.println("Attributes");
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughput;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.UpdateTableRequest;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
Code
System.out.format(
"Updating %s with new provisioned throughput values\n",
58
AWS SDK for Java version 2 Developer Guide
Work with tables in DynamoDB
tableName);
System.out.format("Read capacity : %d\n", readCapacity);
System.out.format("Write capacity : %d\n", writeCapacity);
try {
ddb.updateTable(request);
} catch (DynamoDbException e) {
System.err.println(e.getMessage());
System.exit(1);
}
Delete a table
Call the DynamoDbClient’s deleteTable method and pass it the table’s name.
Note
If the named table doesn’t exist for your account and region, a ResourceNotFoundException is
thrown.
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest;
Code
try {
ddb.deleteTable(request);
} catch (DynamoDbException e) {
System.err.println(e.getMessage());
System.exit(1);
}
More information
• Guidelines for Working with Tables in the Amazon DynamoDB Developer Guide
59
AWS SDK for Java version 2 Developer Guide
Work with items in DynamoDB
You can use the returned GetItemResponse object’s item() method to retrieve a Map of key (String)
and value (AttributeValue) pairs that are associated with the item.
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
Code
keyToGet.put(key, AttributeValue.builder()
.s(keyVal).build());
try {
Map<String,AttributeValue> returnedItem = ddb.getItem(request).item();
if (returnedItem != null) {
Set<String> keys = returnedItem.keySet();
System.out.println("Table Attributes: \n");
60
AWS SDK for Java version 2 Developer Guide
Work with items in DynamoDB
System.exit(1);
}
You can return a Collection instance with all of the attributes for that item (refer to the following
example).
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
Code
keyToGet.put(key, AttributeValue.builder()
.s(keyVal).build());
try {
} catch (DynamoDbException e) {
System.err.println(e.getMessage());
System.exit(1);
}
61
AWS SDK for Java version 2 Developer Guide
Work with items in DynamoDB
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;
import java.util.HashMap;
Code
try {
ddb.putItem(request);
System.out.println(tableName +" was successfully updated");
} catch (ResourceNotFoundException e) {
System.err.format("Error: The table \"%s\" can't be found.\n", tableName);
System.err.println("Be sure that it exists and that you've typed its name
correctly!");
System.exit(1);
} catch (DynamoDbException e) {
System.err.println(e.getMessage());
System.exit(1);
}
62
AWS SDK for Java version 2 Developer Guide
Work with items in DynamoDB
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.AttributeAction;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.AttributeValueUpdate;
import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import java.util.HashMap;
Code
itemKey.put(key, AttributeValue.builder().s(keyVal).build());
HashMap<String,AttributeValueUpdate> updatedValues =
new HashMap<String,AttributeValueUpdate>();
try {
ddb.updateItem(request);
} catch (ResourceNotFoundException e) {
System.err.println(e.getMessage());
System.exit(1);
} catch (DynamoDbException e) {
System.err.println(e.getMessage());
System.exit(1);
}
63
AWS SDK for Java version 2 Developer Guide
Map items in DynamoDB tables
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import java.util.HashMap;
Code
HashMap<String,AttributeValue> keyToGet =
new HashMap<String,AttributeValue>();
keyToGet.put(key, AttributeValue.builder()
.s(keyVal)
.build());
try {
ddb.deleteItem(deleteReq);
} catch (DynamoDbException e) {
System.err.println(e.getMessage());
System.exit(1);
}
More information
• Guidelines for Working with Items in the Amazon DynamoDB Developer Guide
• Working with Items in DynamoDB in the Amazon DynamoDB Developer Guide
64
AWS SDK for Java version 2 Developer Guide
Map items in DynamoDB tables
The AWS SDK for Java v2 includes a set of annotations that you can use with a Java bean to quickly
generate a TableSchema for mapping your classes to tables. Alternatively, if you declare each
TableSchema explicitly, you don’t need to include annotations in your classes.
To work with items in a DynamoDB table using the enhanced client, first create a
DynamoDbEnhancedClient from an existing DynamoDbClient object.
createDynamoDBTable(enhancedClient);
Once this data class has been defined, call TableSchema’s fromBean() with that data class to create the
table schema.
Imports
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbSortKey;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
Code
try {
// Create a DynamoDbTable object
DynamoDbTable<Customer> custTable = enhancedClient.table("Customer",
TableSchema.fromBean(Customer.class));
65
AWS SDK for Java version 2 Developer Guide
Map items in DynamoDB tables
} catch (DynamoDbException e) {
System.err.println(e.getMessage());
System.exit(1);
}
System.out.println("done");
}
@DynamoDbPartitionKey
public String getId() {
return this.id;
};
this.id = id;
}
@DynamoDbSortKey
public String getCustName() {
return this.name;
this.name = name;
}
this.email = email;
}
this.regDate = registrationDate;
}
66
AWS SDK for Java version 2 Developer Guide
Map items in DynamoDB tables
For example, the following code snippet demonstrates one way to use the enhanced client to get
information from an item in a DynamoDB table.
Imports
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable;
import software.amazon.awssdk.enhanced.dynamodb.Key;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbSortKey;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import java.time.Instant;
Code
} catch (DynamoDbException e) {
System.err.println(e.getMessage());
System.exit(1);
}
In the following code snippet, a DynamoDbTable object is created, two items are queued up to be
added to the table, and then the items are written to the table in a single call. Include multiple entries
of addDeleteItem() and addPutItem() (part of WriteBatch.Builder) in each batch, as needed. To
queue up changes to a different table, add another instance of WriteBatch.builder() and provide a
corresponding DynamoDbTable object in mappedTableResource().
67
AWS SDK for Java version 2 Developer Guide
Map items in DynamoDB tables
Imports
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbSortKey;
import software.amazon.awssdk.enhanced.dynamodb.model.BatchWriteItemEnhancedRequest;
import software.amazon.awssdk.enhanced.dynamodb.model.WriteBatch;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
Code
} catch (DynamoDbException e) {
System.err.println(e.getMessage());
System.exit(1);
}
68
AWS SDK for Java version 2 Developer Guide
Map items in DynamoDB tables
@DynamoDbPartitionKey
public String getId() {
return this.id;
};
this.id = id;
}
@DynamoDbSortKey
public String getCustName() {
return this.name;
}
this.regDate = registrationDate;
}
}
In the following code snippet, you build a filter by first defining the value or values you’re searching
for as an AttributeValue object. Then you put this into a HashMap and build an Expression from the
classname:HashMap. Build a QueryConditional object to specify the primary key to match against in the
query, and then execute the query on your DynamoDbTable object.
Note
The QueryConditional interface has several methods you can use to build your queries, including
common conditional statements like greater than, less than, and in between.
Imports
69
AWS SDK for Java version 2 Developer Guide
Map items in DynamoDB tables
import java.time.Instant;
import java.util.Map;
import java.util.Iterator;
import java.util.HashMap;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable;
import software.amazon.awssdk.enhanced.dynamodb.Expression;
import software.amazon.awssdk.enhanced.dynamodb.Key;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbSortKey;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.enhanced.dynamodb.model.QueryConditional;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
Code
try{
// Create a DynamoDbTable object
DynamoDbTable<EnhancedQueryRecords.Customer> mappedTable =
enhancedClient.table("Customer",
TableSchema.fromBean(EnhancedQueryRecords.Customer.class));
// Get items in the Customer table and write out the ID value
Iterator<EnhancedQueryRecords.Customer> results = mappedTable.query(r ->
r.queryConditional(queryConditional).filterExpression(expression)).items().iterator();
while (results.hasNext()) {
} catch (DynamoDbException e) {
System.err.println(e.getMessage());
System.exit(1);
}
System.out.println("Done");
70
AWS SDK for Java version 2 Developer Guide
Amazon EC2 Examples
Imports
import java.time.Instant;
import java.util.Iterator;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbSortKey;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
Code
try{
// Create a DynamoDbTable object
DynamoDbTable<Customer> custTable = enhancedClient.table("Customer",
TableSchema.fromBean(Customer.class));
// Get items in the Record table and write out the ID values
Iterator<Customer> results = custTable.scan().items().iterator();
while (results.hasNext()) {
} catch (DynamoDbException e) {
System.err.println(e.getMessage());
System.exit(1);
}
System.out.println("Done");
}
For more information, see Working with items in DynamoDB in the Amazon DynamoDB Developer Guide.
Topics
• Manage Amazon EC2 instances (p. 72)
71
AWS SDK for Java version 2 Developer Guide
Manage Amazon EC2 instances
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.InstanceType;
import software.amazon.awssdk.services.ec2.model.RunInstancesRequest;
import software.amazon.awssdk.services.ec2.model.RunInstancesResponse;
import software.amazon.awssdk.services.ec2.model.Tag;
import software.amazon.awssdk.services.ec2.model.CreateTagsRequest;
import software.amazon.awssdk.services.ec2.model.Ec2Exception;
Code
try {
ec2.createTags(tagRequest);
System.out.printf(
"Successfully started EC2 Instance %s based on AMI %s",
instanceId, amiId);
return instanceId;
} catch (Ec2Exception e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
72
AWS SDK for Java version 2 Developer Guide
Manage Amazon EC2 instances
Start an instance
To start an Amazon EC2 instance, call the Ec2Client’s startInstances method, providing it with a
StartInstancesRequest containing the ID of the instance to start.
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.StartInstancesRequest;
import software.amazon.awssdk.services.ec2.model.StopInstancesRequest;
Code
ec2.startInstances(request);
Stop an instance
To stop an Amazon EC2 instance, call the Ec2Client’s stopInstances method, providing it with a
StopInstancesRequest containing the ID of the instance to stop.
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.StartInstancesRequest;
import software.amazon.awssdk.services.ec2.model.StopInstancesRequest;
Code
ec2.stopInstances(request);
Reboot an instance
To reboot an Amazon EC2 instance, call the Ec2Client’s rebootInstances method, providing it with a
RebootInstancesRequest containing the ID of the instance to reboot.
Imports
73
AWS SDK for Java version 2 Developer Guide
Manage Amazon EC2 instances
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.Ec2Exception;
import software.amazon.awssdk.services.ec2.model.RebootInstancesRequest;
Code
try {
RebootInstancesRequest request = RebootInstancesRequest.builder()
.instanceIds(instanceId)
.build();
ec2.rebootInstances(request);
System.out.printf(
"Successfully rebooted instance %s", instanceId);
} catch (Ec2Exception e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
Describe instances
To list your instances, create a DescribeInstancesRequest and call the Ec2Client’s describeInstances
method. It will return a DescribeInstancesResponse object that you can use to list the Amazon EC2
instances for your account and region.
Instances are grouped by reservation. Each reservation corresponds to the call to startInstances that
launched the instance. To list your instances, you must first call the DescribeInstancesResponse
class’ reservations method, and then call instances on each returned Reservation object.
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.DescribeInstancesRequest;
import software.amazon.awssdk.services.ec2.model.DescribeInstancesResponse;
import software.amazon.awssdk.services.ec2.model.Instance;
import software.amazon.awssdk.services.ec2.model.Reservation;
import software.amazon.awssdk.services.ec2.model.Ec2Exception;
Code
try {
do {
DescribeInstancesRequest request =
DescribeInstancesRequest.builder().maxResults(6).nextToken(nextToken).build();
DescribeInstancesResponse response = ec2.describeInstances(request);
74
AWS SDK for Java version 2 Developer Guide
Manage Amazon EC2 instances
} catch (Ec2Exception e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
Results are paged; you can get further results by passing the value returned from the result object’s
nextToken method to a new request object’s nextToken method, then using the new request object in
your next call to describeInstances.
Monitor an instance
You can monitor various aspects of your Amazon EC2 instances, such as CPU and network utilization,
available memory, and disk space remaining. To learn more about instance monitoring, see Monitoring
Amazon EC2 in the Amazon EC2 User Guide for Linux Instances.
To start monitoring an instance, you must create a MonitorInstancesRequest with the ID of the instance
to monitor, and pass it to the Ec2Client’s monitorInstances method.
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.MonitorInstancesRequest;
import software.amazon.awssdk.services.ec2.model.UnmonitorInstancesRequest;
Code
ec2.monitorInstances(request);
75
AWS SDK for Java version 2 Developer Guide
Use elastic IP addresses in Amazon EC2
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.MonitorInstancesRequest;
import software.amazon.awssdk.services.ec2.model.UnmonitorInstancesRequest;
Code
ec2.unmonitorInstances(request);
More information
• RunInstances in the Amazon EC2 API Reference
• DescribeInstances in the Amazon EC2 API Reference
• StartInstances in the Amazon EC2 API Reference
• StopInstances in the Amazon EC2 API Reference
• RebootInstances in the Amazon EC2 API Reference
• DescribeInstances in the Amazon EC2 API Reference
• MonitorInstances in the Amazon EC2 API Reference
• UnmonitorInstances in the Amazon EC2 API Reference
The returned AllocateAddressResponse contains an allocation ID that you can use to associate the
address with an instance, by passing the allocation ID and instance ID in a AssociateAddressRequest to
the Ec2Client’s associateAddress method.
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.AllocateAddressRequest;
import software.amazon.awssdk.services.ec2.model.DomainType;
import software.amazon.awssdk.services.ec2.model.AllocateAddressResponse;
import software.amazon.awssdk.services.ec2.model.AssociateAddressRequest;
import software.amazon.awssdk.services.ec2.model.AssociateAddressResponse;
import software.amazon.awssdk.services.ec2.model.Ec2Exception;
Code
76
AWS SDK for Java version 2 Developer Guide
Use elastic IP addresses in Amazon EC2
try {
AllocateAddressRequest allocateRequest = AllocateAddressRequest.builder()
.domain(DomainType.VPC)
.build();
AllocateAddressResponse allocateResponse =
ec2.allocateAddress(allocateRequest);
AssociateAddressRequest associateRequest =
AssociateAddressRequest.builder()
.instanceId(instanceId)
.allocationId(allocationId)
.build();
AssociateAddressResponse associateResponse =
ec2.associateAddress(associateRequest);
return associateResponse.associationId();
} catch (Ec2Exception e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
return "";
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.Address;
import software.amazon.awssdk.services.ec2.model.DescribeAddressesResponse;
import software.amazon.awssdk.services.ec2.model.Ec2Exception;
Code
try {
DescribeAddressesResponse response = ec2.describeAddresses();
77
AWS SDK for Java version 2 Developer Guide
Use elastic IP addresses in Amazon EC2
}
} catch (Ec2Exception e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.Ec2Exception;
import software.amazon.awssdk.services.ec2.model.ReleaseAddressRequest;
import software.amazon.awssdk.services.ec2.model.ReleaseAddressResponse;
Code
try {
ReleaseAddressRequest request = ReleaseAddressRequest.builder()
.allocationId(allocId).build();
System.out.printf(
"Successfully released elastic IP address %s", allocId);
} catch (Ec2Exception e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
}
After you release an Elastic IP address, it is released to the AWS IP address pool and might be unavailable
to you afterward. Be sure to update your DNS records and any servers or devices that communicate with
the address.
If you are using EC2-Classic or a default VPC, then releasing an Elastic IP address automatically
disassociates it from any instance that it’s associated with. To disassociate an Elastic IP address without
releasing it, use the Ec2Client’s disassociateAddress method.
If you are using a non-default VPC, you must use disassociateAddress to disassociate the Elastic IP
address before you try to release it. Otherwise, Amazon EC2 returns an error (InvalidIPAddress.InUse).
More information
• Elastic IP Addresses in the Amazon EC2 User Guide for Linux Instances
• AllocateAddress in the Amazon EC2 API Reference
• DescribeAddresses in the Amazon EC2 API Reference
78
AWS SDK for Java version 2 Developer Guide
Use regions and availability zones
Imports
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.DescribeRegionsResponse;
import software.amazon.awssdk.services.ec2.model.Region;
import software.amazon.awssdk.services.ec2.model.AvailabilityZone;
import software.amazon.awssdk.services.ec2.model.Ec2Exception;
import software.amazon.awssdk.services.ec2.model.DescribeAvailabilityZonesResponse;
Code
try {
Imports
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.DescribeRegionsResponse;
import software.amazon.awssdk.services.ec2.model.Region;
import software.amazon.awssdk.services.ec2.model.AvailabilityZone;
import software.amazon.awssdk.services.ec2.model.Ec2Exception;
import software.amazon.awssdk.services.ec2.model.DescribeAvailabilityZonesResponse;
Code
79
AWS SDK for Java version 2 Developer Guide
Use regions and availability zones
DescribeAvailabilityZonesResponse zonesResponse =
ec2.describeAvailabilityZones();
Describe accounts
To describe your account, call the Ec2Client’s describeAccountAttributes method. This method
returns a DescribeAccountAttributesResponse object. Invoke this objects accountAttributes method
to get a list of AccountAttribute objects. You can iterate through the list to retrieve an AccountAttribute
object.
You can get your account’s attribute values by invoking the AccountAttribute object’s
attributeValues method. This method returns a list of AccountAttributeValue objects. You can iterate
through this second list to display the value of attributes (see the following code example).
Imports
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.DescribeRegionsResponse;
import software.amazon.awssdk.services.ec2.model.Region;
import software.amazon.awssdk.services.ec2.model.AvailabilityZone;
import software.amazon.awssdk.services.ec2.model.Ec2Exception;
import software.amazon.awssdk.services.ec2.model.DescribeAvailabilityZonesResponse;
Code
try {
More information
• Regions and Availability Zones in the Amazon EC2 User Guide for Linux Instances
• DescribeRegions in the Amazon EC2 API Reference
• DescribeAvailabilityZones in the Amazon EC2 API Reference
80
AWS SDK for Java version 2 Developer Guide
Work with Amazon EC2 key pairs
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.CreateKeyPairRequest;
import software.amazon.awssdk.services.ec2.model.CreateKeyPairResponse;
import software.amazon.awssdk.services.ec2.model.Ec2Exception;
Code
try {
CreateKeyPairRequest request = CreateKeyPairRequest.builder()
.keyName(keyName).build();
} catch (Ec2Exception e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.DescribeKeyPairsResponse;
import software.amazon.awssdk.services.ec2.model.KeyPairInfo;
import software.amazon.awssdk.services.ec2.model.Ec2Exception;
Code
try {
DescribeKeyPairsResponse response = ec2.describeKeyPairs();
81
AWS SDK for Java version 2 Developer Guide
Work with security groups in Amazon EC2
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.DeleteKeyPairRequest;
import software.amazon.awssdk.services.ec2.model.DeleteKeyPairResponse;
import software.amazon.awssdk.services.ec2.model.Ec2Exception;
Code
try {
More information
• Amazon EC2 Key Pairs in the Amazon EC2 User Guide for Linux Instances
• CreateKeyPair in the Amazon EC2 API Reference
• DescribeKeyPairs in the Amazon EC2 API Reference
• DeleteKeyPair in the Amazon EC2 API Reference
Imports
82
AWS SDK for Java version 2 Developer Guide
Work with security groups in Amazon EC2
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.CreateSecurityGroupRequest;
import software.amazon.awssdk.services.ec2.model.AuthorizeSecurityGroupIngressRequest;
import software.amazon.awssdk.services.ec2.model.AuthorizeSecurityGroupIngressResponse;
import software.amazon.awssdk.services.ec2.model.Ec2Exception;
import software.amazon.awssdk.services.ec2.model.IpPermission;
import software.amazon.awssdk.services.ec2.model.CreateSecurityGroupResponse;
import software.amazon.awssdk.services.ec2.model.IpRange;
Code
To add ingress rules to your security group, use the Ec2Client’s authorizeSecurityGroupIngress
method, providing the name of the security group and the access rules (IpPermission) you want to assign
to it within an AuthorizeSecurityGroupIngressRequest object. The following example shows how to add
IP permissions to a security group.
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.CreateSecurityGroupRequest;
import software.amazon.awssdk.services.ec2.model.AuthorizeSecurityGroupIngressRequest;
import software.amazon.awssdk.services.ec2.model.AuthorizeSecurityGroupIngressResponse;
import software.amazon.awssdk.services.ec2.model.Ec2Exception;
import software.amazon.awssdk.services.ec2.model.IpPermission;
import software.amazon.awssdk.services.ec2.model.CreateSecurityGroupResponse;
import software.amazon.awssdk.services.ec2.model.IpRange;
Code
83
AWS SDK for Java version 2 Developer Guide
Work with security groups in Amazon EC2
AuthorizeSecurityGroupIngressRequest authRequest =
AuthorizeSecurityGroupIngressRequest.builder()
.groupName(groupName)
.ipPermissions(ipPerm, ipPerm2)
.build();
AuthorizeSecurityGroupIngressResponse authResponse =
ec2.authorizeSecurityGroupIngress(authRequest);
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.DescribeSecurityGroupsRequest;
import software.amazon.awssdk.services.ec2.model.DescribeSecurityGroupsResponse;
import software.amazon.awssdk.services.ec2.model.SecurityGroup;
import software.amazon.awssdk.services.ec2.model.Ec2Exception;
Code
try {
DescribeSecurityGroupsRequest request =
DescribeSecurityGroupsRequest.builder()
.groupIds(groupId).build();
DescribeSecurityGroupsResponse response =
ec2.describeSecurityGroups(request);
84
AWS SDK for Java version 2 Developer Guide
AWS Identity and Access Management (IAM) Examples
group.vpcId(),
group.description());
}
} catch (Ec2Exception e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.DeleteSecurityGroupRequest;
import software.amazon.awssdk.services.ec2.model.DeleteSecurityGroupResponse;
import software.amazon.awssdk.services.ec2.model.Ec2Exception;
Code
try {
DeleteSecurityGroupRequest request = DeleteSecurityGroupRequest.builder()
.groupId(groupId)
.build();
ec2.deleteSecurityGroup(request);
System.out.printf(
"Successfully deleted Security Group with id %s", groupId);
} catch (Ec2Exception e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
More information
• Amazon EC2 Security Groups in the Amazon EC2 User Guide for Linux Instances
• Authorizing Inbound Traffic for Your Linux Instances in the Amazon EC2 User Guide for Linux Instances
• CreateSecurityGroup in the Amazon EC2 API Reference
• DescribeSecurityGroups in the Amazon EC2 API Reference
• DeleteSecurityGroup in the Amazon EC2 API Reference
• AuthorizeSecurityGroupIngress in the Amazon EC2 API Reference
85
AWS SDK for Java version 2 Developer Guide
Manage IAM access keys
AWS Identity and Access Management (IAM) enables you to securely control access to AWS services
and resources for your users. Using IAM, you can create and manage AWS users and groups, and use
permissions to allow and deny their access to AWS resources. For a complete guide to IAM, visit the IAM
User Guide.
The following examples include only the code needed to demonstrate each technique. The complete
example code is available on GitHub. From there, you can download a single source file or clone the
repository locally to get all the examples to build and run.
Topics
• Manage IAM access keys (p. 86)
• Managing IAM Users (p. 90)
• Use IAM account aliases (p. 93)
• Work with IAM policies (p. 95)
• Work with IAM server certificates (p. 100)
Imports
import software.amazon.awssdk.services.iam.model.CreateAccessKeyRequest;
import software.amazon.awssdk.services.iam.model.CreateAccessKeyResponse;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;
import software.amazon.awssdk.services.iam.model.IamException;
Code
try {
CreateAccessKeyRequest request = CreateAccessKeyRequest.builder()
.userName(user).build();
} catch (IamException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
return "";
}
86
AWS SDK for Java version 2 Developer Guide
Manage IAM access keys
Imports
import software.amazon.awssdk.services.iam.model.AccessKeyMetadata;
import software.amazon.awssdk.services.iam.model.IamException;
import software.amazon.awssdk.services.iam.model.ListAccessKeysRequest;
import software.amazon.awssdk.services.iam.model.ListAccessKeysResponse;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;
Code
try {
boolean done = false;
String newMarker = null;
while (!done) {
ListAccessKeysResponse response;
if(newMarker == null) {
ListAccessKeysRequest request = ListAccessKeysRequest.builder()
.userName(userName).build();
response = iam.listAccessKeys(request);
} else {
ListAccessKeysRequest request = ListAccessKeysRequest.builder()
.userName(userName)
.marker(newMarker).build();
response = iam.listAccessKeys(request);
}
if (!response.isTruncated()) {
done = true;
} else {
newMarker = response.marker();
}
}
} catch (IamException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
The results of listAccessKeys are paged (with a default maximum of 100 records per call). You can
call isTruncated on the returned ListAccessKeysResponse object to see if the query returned fewer
results then are available. If so, then call marker on the ListAccessKeysResponse and use it when
creating a new request. Use that new request in the next invocation of listAccessKeys.
87
AWS SDK for Java version 2 Developer Guide
Manage IAM access keys
You can then use the returned GetAccessKeyLastUsedResponse object to retrieve the key’s last used time.
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;
import software.amazon.awssdk.services.iam.model.GetAccessKeyLastUsedRequest;
import software.amazon.awssdk.services.iam.model.GetAccessKeyLastUsedResponse;
import software.amazon.awssdk.services.iam.model.IamException;
Code
try {
GetAccessKeyLastUsedRequest request = GetAccessKeyLastUsedRequest.builder()
.accessKeyId(accessId).build();
} catch (IamException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
System.out.println("Done");
Imports
import software.amazon.awssdk.services.iam.model.IamException;
import software.amazon.awssdk.services.iam.model.StatusType;
import software.amazon.awssdk.services.iam.model.UpdateAccessKeyRequest;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;
Code
public static void updateKey(IamClient iam, String username, String accessId, String
status ) {
88
AWS SDK for Java version 2 Developer Guide
Manage IAM access keys
try {
if (status.toLowerCase().equalsIgnoreCase("active")) {
statusType = StatusType.ACTIVE;
} else if (status.toLowerCase().equalsIgnoreCase("inactive")) {
statusType = StatusType.INACTIVE;
} else {
statusType = StatusType.UNKNOWN_TO_SDK_VERSION;
}
UpdateAccessKeyRequest request = UpdateAccessKeyRequest.builder()
.accessKeyId(accessId)
.userName(username)
.status(statusType)
.build();
iam.updateAccessKey(request);
System.out.printf(
"Successfully updated the status of access key %s to" +
"status %s for user %s", accessId, status, username);
} catch (IamException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;
import software.amazon.awssdk.services.iam.model.DeleteAccessKeyRequest;
import software.amazon.awssdk.services.iam.model.IamException;
Code
try {
DeleteAccessKeyRequest request = DeleteAccessKeyRequest.builder()
.accessKeyId(accessKey)
.userName(username)
.build();
iam.deleteAccessKey(request);
System.out.println("Successfully deleted access key " + accessKey +
" from user " + username);
} catch (IamException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
89
AWS SDK for Java version 2 Developer Guide
Managing IAM Users
More information
• CreateAccessKey in the IAM API Reference
• ListAccessKeys in the IAM API Reference
• GetAccessKeyLastUsed in the IAM API Reference
• UpdateAccessKey in the IAM API Reference
• DeleteAccessKey in the IAM API Reference
Imports
import software.amazon.awssdk.core.waiters.WaiterResponse;
import software.amazon.awssdk.services.iam.model.CreateUserRequest;
import software.amazon.awssdk.services.iam.model.CreateUserResponse;
import software.amazon.awssdk.services.iam.model.IamException;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;
import software.amazon.awssdk.services.iam.waiters.IamWaiter;
import software.amazon.awssdk.services.iam.model.GetUserRequest;
import software.amazon.awssdk.services.iam.model.GetUserResponse;
Code
try {
// Create an IamWaiter object
IamWaiter iamWaiter = iam.waiter();
WaiterResponse<GetUserResponse> waitUntilUserExists =
iamWaiter.waitUntilUserExists(userRequest);
waitUntilUserExists.matched().response().ifPresent(System.out::println);
return response.user().userName();
} catch (IamException e) {
90
AWS SDK for Java version 2 Developer Guide
Managing IAM Users
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
return "";
}
Listing Users
To list the IAM users for your account, create a new ListUsersRequest and pass it to the IamClient’s
listUsers method. You can retrieve the list of users by calling users on the returned
ListUsersResponse object.
The list of users returned by listUsers is paged. You can check to see there are more results to retrieve
by calling the response object’s isTruncated method. If it returns true, then call the response object’s
marker() method. Use the marker value to create a new request object. Then call the listUsers
method again with the new request.
Imports
import software.amazon.awssdk.services.iam.model.IamException;
import software.amazon.awssdk.services.iam.model.ListUsersRequest;
import software.amazon.awssdk.services.iam.model.ListUsersResponse;
import software.amazon.awssdk.services.iam.model.User;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;
Code
try {
while(!done) {
ListUsersResponse response;
if (newMarker == null) {
ListUsersRequest request = ListUsersRequest.builder().build();
response = iam.listUsers(request);
} else {
ListUsersRequest request = ListUsersRequest.builder()
.marker(newMarker).build();
response = iam.listUsers(request);
}
if(!response.isTruncated()) {
done = true;
} else {
newMarker = response.marker();
}
}
} catch (IamException e) {
System.err.println(e.awsErrorDetails().errorMessage());
91
AWS SDK for Java version 2 Developer Guide
Managing IAM Users
System.exit(1);
}
Updating a User
To update a user, call the IamClient object’s updateUser method, which takes a UpdateUserRequest
object that you can use to change the user’s name or path.
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;
import software.amazon.awssdk.services.iam.model.IamException;
import software.amazon.awssdk.services.iam.model.UpdateUserRequest;
Code
try {
UpdateUserRequest request = UpdateUserRequest.builder()
.userName(curName)
.newUserName(newName)
.build();
iam.updateUser(request);
System.out.printf("Successfully updated user to username %s",
newName);
} catch (IamException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
}
Deleting a User
To delete a user, call the IamClient’s deleteUser request with a UpdateUserRequest object set with the
user name to delete.
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;
import software.amazon.awssdk.services.iam.model.DeleteUserRequest;
import software.amazon.awssdk.services.iam.model.IamException;
Code
try {
DeleteUserRequest request = DeleteUserRequest.builder()
92
AWS SDK for Java version 2 Developer Guide
Use IAM account aliases
.userName(userName)
.build();
iam.deleteUser(request);
System.out.println("Successfully deleted IAM user " + userName);
} catch (IamException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
}
More Information
• IAM Users in the IAM User Guide
• Managing IAM Users in the IAM User Guide
• CreateUser in the IAM API Reference
• ListUsers in the IAM API Reference
• UpdateUser in the IAM API Reference
• DeleteUser in the IAM API Reference
Imports
import software.amazon.awssdk.services.iam.model.CreateAccountAliasRequest;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;
import software.amazon.awssdk.services.iam.model.IamException;
Code
try {
CreateAccountAliasRequest request = CreateAccountAliasRequest.builder()
.accountAlias(alias)
.build();
iam.createAccountAlias(request);
System.out.println("Successfully created account alias: " + alias);
} catch (IamException e) {
System.err.println(e.awsErrorDetails().errorMessage());
93
AWS SDK for Java version 2 Developer Guide
Use IAM account aliases
System.exit(1);
}
}
Imports
import software.amazon.awssdk.services.iam.model.IamException;
import software.amazon.awssdk.services.iam.model.ListAccountAliasesResponse;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;
Code
try {
ListAccountAliasesResponse response = iam.listAccountAliases();
} catch (IamException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
Imports
import software.amazon.awssdk.services.iam.model.DeleteAccountAliasRequest;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;
import software.amazon.awssdk.services.iam.model.IamException;
Code
94
AWS SDK for Java version 2 Developer Guide
Work with IAM policies
try {
DeleteAccountAliasRequest request = DeleteAccountAliasRequest.builder()
.accountAlias(alias)
.build();
iam.deleteAccountAlias(request);
System.out.println("Successfully deleted account alias " + alias);
} catch (IamException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
System.out.println("Done");
More information
• Your AWS Account ID and Its Alias in the IAM User Guide
• CreateAccountAlias in the IAM API Reference
• ListAccountAliases in the IAM API Reference
• DeleteAccountAlias in the IAM API Reference
Imports
import software.amazon.awssdk.core.waiters.WaiterResponse;
import software.amazon.awssdk.services.iam.model.CreatePolicyRequest;
import software.amazon.awssdk.services.iam.model.CreatePolicyResponse;
import software.amazon.awssdk.services.iam.model.GetPolicyRequest;
import software.amazon.awssdk.services.iam.model.GetPolicyResponse;
import software.amazon.awssdk.services.iam.model.IamException;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;
import software.amazon.awssdk.services.iam.waiters.IamWaiter;
Code
try {
// Create an IamWaiter object
IamWaiter iamWaiter = iam.waiter();
95
AWS SDK for Java version 2 Developer Guide
Work with IAM policies
WaiterResponse<GetPolicyResponse> waitUntilPolicyExists =
iamWaiter.waitUntilPolicyExists(polRequest);
waitUntilPolicyExists.matched().response().ifPresent(System.out::println);
return response.policy().arn();
} catch (IamException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
return "" ;
}
Get a policy
To retrieve an existing policy, call the IamClient’s getPolicy method, providing the policy’s ARN within
a GetPolicyRequest object.
Imports
import software.amazon.awssdk.services.iam.model.GetPolicyRequest;
import software.amazon.awssdk.services.iam.model.GetPolicyResponse;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;
import software.amazon.awssdk.services.iam.model.IamException;
Code
try {
} catch (IamException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
}
Imports
96
AWS SDK for Java version 2 Developer Guide
Work with IAM policies
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;
import software.amazon.awssdk.services.iam.model.IamException;
import software.amazon.awssdk.services.iam.model.AttachRolePolicyRequest;
import software.amazon.awssdk.services.iam.model.AttachedPolicy;
import software.amazon.awssdk.services.iam.model.ListAttachedRolePoliciesRequest;
import software.amazon.awssdk.services.iam.model.ListAttachedRolePoliciesResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
Code
try {
while(!done) {
ListAttachedRolePoliciesResponse response;
if (newMarker == null) {
ListAttachedRolePoliciesRequest request =
ListAttachedRolePoliciesRequest.builder()
.roleName(roleName).build();
response = iam.listAttachedRolePolicies(request);
} else {
ListAttachedRolePoliciesRequest request =
ListAttachedRolePoliciesRequest.builder()
.roleName(roleName)
.marker(newMarker).build();
response = iam.listAttachedRolePolicies(request);
}
matchingPolicies.addAll(
response.attachedPolicies()
.stream()
.filter(p -> p.policyName().equals(roleName))
.collect(Collectors.toList()));
if(!response.isTruncated()) {
done = true;
} else {
newMarker = response.marker();
}
}
if (matchingPolicies.size() > 0) {
System.out.println(roleName +
" policy is already attached to this role.");
return;
}
AttachRolePolicyRequest attachRequest =
AttachRolePolicyRequest.builder()
.roleName(roleName)
.policyArn(policyArn).build();
97
AWS SDK for Java version 2 Developer Guide
Work with IAM policies
iam.attachRolePolicy(attachRequest);
} catch (IamException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;
import software.amazon.awssdk.services.iam.model.IamException;
import software.amazon.awssdk.services.iam.model.AttachRolePolicyRequest;
import software.amazon.awssdk.services.iam.model.AttachedPolicy;
import software.amazon.awssdk.services.iam.model.ListAttachedRolePoliciesRequest;
import software.amazon.awssdk.services.iam.model.ListAttachedRolePoliciesResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
Code
try {
while(!done) {
ListAttachedRolePoliciesResponse response;
if (newMarker == null) {
ListAttachedRolePoliciesRequest request =
ListAttachedRolePoliciesRequest.builder()
.roleName(roleName).build();
response = iam.listAttachedRolePolicies(request);
} else {
ListAttachedRolePoliciesRequest request =
ListAttachedRolePoliciesRequest.builder()
.roleName(roleName)
.marker(newMarker).build();
response = iam.listAttachedRolePolicies(request);
98
AWS SDK for Java version 2 Developer Guide
Work with IAM policies
matchingPolicies.addAll(
response.attachedPolicies()
.stream()
.filter(p -> p.policyName().equals(roleName))
.collect(Collectors.toList()));
if(!response.isTruncated()) {
done = true;
} else {
newMarker = response.marker();
}
}
if (matchingPolicies.size() > 0) {
System.out.println(roleName +
" policy is already attached to this role.");
return;
}
AttachRolePolicyRequest attachRequest =
AttachRolePolicyRequest.builder()
.roleName(roleName)
.policyArn(policyArn).build();
iam.attachRolePolicy(attachRequest);
} catch (IamException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
Imports
import software.amazon.awssdk.services.iam.model.DetachRolePolicyRequest;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;
import software.amazon.awssdk.services.iam.model.IamException;
Code
try {
DetachRolePolicyRequest request = DetachRolePolicyRequest.builder()
.roleName(roleName)
.policyArn(policyArn)
.build();
iam.detachRolePolicy(request);
99
AWS SDK for Java version 2 Developer Guide
Work with IAM server certificates
} catch (IamException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
More information
• Overview of IAM Policies in the IAM User Guide.
• AWS IAM Policy Reference in the IAM User Guide.
• CreatePolicy in the IAM API Reference
• GetPolicy in the IAM API Reference
• AttachRolePolicy in the IAM API Reference
• ListAttachedRolePolicies in the IAM API Reference
• DetachRolePolicy in the IAM API Reference
We recommend that you use ACM to provision, manage, and deploy your server certificates. With ACM
you can request a certificate, deploy it to your AWS resources, and let ACM handle certificate renewals
for you. Certificates provided by ACM are free. For more information about ACM , see the ACM User
Guide.
Imports
import software.amazon.awssdk.services.iam.model.GetServerCertificateRequest;
import software.amazon.awssdk.services.iam.model.GetServerCertificateResponse;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;
import software.amazon.awssdk.services.iam.model.IamException;
Code
try {
GetServerCertificateRequest request = GetServerCertificateRequest.builder()
.serverCertificateName(certName)
.build();
100
AWS SDK for Java version 2 Developer Guide
Work with IAM server certificates
} catch (IamException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
}
Imports
import software.amazon.awssdk.services.iam.model.IamException;
import software.amazon.awssdk.services.iam.model.ListServerCertificatesRequest;
import software.amazon.awssdk.services.iam.model.ListServerCertificatesResponse;
import software.amazon.awssdk.services.iam.model.ServerCertificateMetadata;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;
Code
try {
boolean done = false;
String newMarker = null;
while(!done) {
ListServerCertificatesResponse response;
if (newMarker == null) {
ListServerCertificatesRequest request =
ListServerCertificatesRequest.builder().build();
response = iam.listServerCertificates(request);
} else {
ListServerCertificatesRequest request =
ListServerCertificatesRequest.builder()
.marker(newMarker).build();
response = iam.listServerCertificates(request);
}
for(ServerCertificateMetadata metadata :
response.serverCertificateMetadataList()) {
System.out.printf("Retrieved server certificate %s",
metadata.serverCertificateName());
}
if(!response.isTruncated()) {
done = true;
101
AWS SDK for Java version 2 Developer Guide
Work with IAM server certificates
} else {
newMarker = response.marker();
}
}
} catch (IamException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;
import software.amazon.awssdk.services.iam.model.IamException;
import software.amazon.awssdk.services.iam.model.UpdateServerCertificateRequest;
import software.amazon.awssdk.services.iam.model.UpdateServerCertificateResponse;
Code
try {
UpdateServerCertificateRequest request =
UpdateServerCertificateRequest.builder()
.serverCertificateName(curName)
.newServerCertificateName(newName)
.build();
UpdateServerCertificateResponse response =
iam.updateServerCertificate(request);
} catch (IamException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
}
Imports
import software.amazon.awssdk.services.iam.model.DeleteServerCertificateRequest;
102
AWS SDK for Java version 2 Developer Guide
Amazon Kinesis Examples
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;
import software.amazon.awssdk.services.iam.model.IamException;
Code
try {
DeleteServerCertificateRequest request =
DeleteServerCertificateRequest.builder()
.serverCertificateName(certName)
.build();
iam.deleteServerCertificate(request);
System.out.println("Successfully deleted server certificate " +
certName);
} catch (IamException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
}
More information
• Working with Server Certificates in the IAM User Guide
• GetServerCertificate in the IAM API Reference
• ListServerCertificates in the IAM API Reference
• UpdateServerCertificate in the IAM API Reference
• DeleteServerCertificate in the IAM API Reference
• ACM User Guide
For more information about Kinesis, see the Amazon Kinesis Developer Guide.
The following examples include only the code needed to demonstrate each technique. The complete
example code is available on GitHub. From there, you can download a single source file or clone the
repository locally to get all the examples to build and run.
Topics
• Subscribing to Amazon Kinesis Data Streams (p. 103)
103
AWS SDK for Java version 2 Developer Guide
Subscribing to Amazon Kinesis Data Streams
Set Up
First, create an asynchronous Kinesis client and a SubscribeToShardRequest object. These objects are
used in each of the following examples to subscribe to Kinesis events.
Imports
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicInteger;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import software.amazon.awssdk.core.async.SdkPublisher;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.kinesis.KinesisAsyncClient;
import software.amazon.awssdk.services.kinesis.model.ShardIteratorType;
import software.amazon.awssdk.services.kinesis.model.SubscribeToShardEvent;
import software.amazon.awssdk.services.kinesis.model.SubscribeToShardEventStream;
import software.amazon.awssdk.services.kinesis.model.SubscribeToShardRequest;
import software.amazon.awssdk.services.kinesis.model.SubscribeToShardResponse;
import software.amazon.awssdk.services.kinesis.model.SubscribeToShardResponseHandler;
Code
Using the builder, you can set each lifecycle callback with a method call instead of implementing the full
interface.
Code
For more control of the publisher, you can use the publisherTransformer method to customize the
publisher.
Code
104
AWS SDK for Java version 2 Developer Guide
Subscribing to Amazon Kinesis Data Streams
In this example, you implement the onEventStream method, which allows you full access to the
publisher. This demonstrates how to transform the publisher to event records for printing by the
subscriber.
Code
@Override
public void responseReceived(SubscribeToShardResponse response) {
System.out.println("Received initial response");
}
@Override
public void onEventStream(SdkPublisher<SubscribeToShardEventStream> publisher) {
publisher
// Filter to only SubscribeToShardEvents
.filter(SubscribeToShardEvent.class)
// Flat map into a publisher of just records
.flatMapIterable(SubscribeToShardEvent::records)
// Limit to 1000 total records
.limit(1000)
// Batch records into lists of 25
.buffer(25)
// Print out each record batch
.subscribe(batch -> System.out.println("Record Batch - " + batch));
}
@Override
public void complete() {
System.out.println("All records stream successfully");
}
@Override
public void exceptionOccurred(Throwable throwable) {
System.err.println("Error during stream - " + throwable.getMessage());
}
};
return client.subscribeToShard(request, responseHandler);
105
AWS SDK for Java version 2 Developer Guide
Subscribing to Amazon Kinesis Data Streams
Code
Code
@Override
public void onSubscribe(Subscription subscription) {
this.subscription = subscription;
this.subscription.request(1);
}
@Override
public void onNext(SubscribeToShardEventStream shardSubscriptionEventStream) {
System.out.println("Received event " + shardSubscriptionEventStream);
if (eventCount.incrementAndGet() >= 100) {
// Cancel the subscription at any time to stop receiving events
subscription.cancel();
}
subscription.request(1);
}
@Override
public void onError(Throwable throwable) {
System.err.println("Error occurred while stream - " + throwable.getMessage());
}
106
AWS SDK for Java version 2 Developer Guide
Subscribing to Amazon Kinesis Data Streams
@Override
public void onComplete() {
System.out.println("Finished streaming all events");
}
}
You can pass that custom subscriber to the subscribe method, similarly to preview examples. The
following code snippet shows this example.
Code
Imports
import java.net.URI;
import java.util.concurrent.CompletableFuture;
import io.reactivex.Flowable;
import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.core.async.SdkPublisher;
import software.amazon.awssdk.http.Protocol;
import software.amazon.awssdk.http.SdkHttpConfigurationOption;
import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.kinesis.KinesisAsyncClient;
import software.amazon.awssdk.services.kinesis.model.ShardIteratorType;
import software.amazon.awssdk.services.kinesis.model.StartingPosition;
import software.amazon.awssdk.services.kinesis.model.SubscribeToShardEvent;
import software.amazon.awssdk.services.kinesis.model.SubscribeToShardRequest;
import software.amazon.awssdk.services.kinesis.model.SubscribeToShardResponseHandler;
import software.amazon.awssdk.utils.AttributeMap;
In the following Java code example, notice that StockTrade object is used as the data to write to the
Kinesis data stream. Before running this example, ensure that you have created the data steam.
Code
107
AWS SDK for Java version 2 Developer Guide
Subscribing to Amazon Kinesis Data Streams
.builder()
.onError(t -> System.err.println("Error during stream - " + t.getMessage()))
.subscriber(MySubscriber::new)
.build();
return client.subscribeToShard(request, responseHandler);
}
To use the library, add it as a dependency. If you’re using Maven, the example shows the POM snippet to
use.
POM Entry
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
Imports
import java.net.URI;
import java.util.concurrent.CompletableFuture;
import io.reactivex.Flowable;
import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.core.async.SdkPublisher;
import software.amazon.awssdk.http.Protocol;
import software.amazon.awssdk.http.SdkHttpConfigurationOption;
import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.kinesis.KinesisAsyncClient;
import software.amazon.awssdk.services.kinesis.model.ShardIteratorType;
import software.amazon.awssdk.services.kinesis.model.StartingPosition;
import software.amazon.awssdk.services.kinesis.model.SubscribeToShardEvent;
import software.amazon.awssdk.services.kinesis.model.SubscribeToShardRequest;
import software.amazon.awssdk.services.kinesis.model.SubscribeToShardResponseHandler;
import software.amazon.awssdk.utils.AttributeMap;
This example uses RxJava in the onEventStream lifecycle method. This gives you full access to the
publisher, which can be used to create an Rx Flowable.
Code
108
AWS SDK for Java version 2 Developer Guide
Amazon Lambda Examples
.build();
You can also use the publisherTransformer method with the Flowable publisher. You must adapt
the Flowable publisher to an SdkPublisher, as shown in the following example.
Code
More Information
• SubscribeToShardEvent in the Amazon Kinesis API Reference
• SubscribeToShard in the Amazon Kinesis API Reference
The following examples include only the code needed to demonstrate each technique. The complete
example code is available on GitHub. From there, you can download a single source file or clone the
repository locally to get all the examples to build and run.
Topics
• Invoke, list, and delete AWS Lambda functions (p. 109)
Topics
• Invoke a Lambda function (p. 109)
• List Lambda functions (p. 110)
• Delete a Lambda function (p. 111)
To pass payload data to a function, create a SdkBytes object that contains information. For example, in
the following code example, notice the JSON data passed to the Lambda function.
Imports
109
AWS SDK for Java version 2 Developer Guide
Service operations
import software.amazon.awssdk.services.lambda.LambdaClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.lambda.model.InvokeRequest;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.services.lambda.model.InvokeResponse;
import software.amazon.awssdk.services.lambda.model.LambdaException;
Code
//Setup an InvokeRequest
InvokeRequest request = InvokeRequest.builder()
.functionName(functionName)
.payload(payload)
.build();
} catch(LambdaException e) {
System.err.println(e.getMessage());
System.exit(1);
}
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.lambda.LambdaClient;
import software.amazon.awssdk.services.lambda.model.LambdaException;
import software.amazon.awssdk.services.lambda.model.ListFunctionsResponse;
import software.amazon.awssdk.services.lambda.model.FunctionConfiguration;
import java.util.Iterator;
import java.util.List;
Code
The following Java code example demonstrates how to retrieve a list of function names.
110
AWS SDK for Java version 2 Developer Guide
Amazon Pinpoint Examples
try {
// Get a list of all functions
ListFunctionsResponse functionResult = awsLambda.listFunctions();
List<FunctionConfiguration> list = functionResult.functions();
} catch(LambdaException e) {
System.err.println(e.getMessage());
System.exit(1);
}
Imports
import software.amazon.awssdk.services.lambda.LambdaClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.lambda.model.DeleteFunctionRequest;
import software.amazon.awssdk.services.lambda.model.LambdaException;
Code
} catch(LambdaException e) {
System.err.println(e.getMessage());
System.exit(1);
}
111
AWS SDK for Java version 2 Developer Guide
Create a project
Create a project
A project (or application) in Amazon Pinpoint is a collection of settings, customer data, segments, and
campaigns.
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.pinpoint.PinpointClient;
import software.amazon.awssdk.services.pinpoint.model.CreateAppRequest;
import software.amazon.awssdk.services.pinpoint.model.CreateAppResponse;
import software.amazon.awssdk.services.pinpoint.model.CreateApplicationRequest;
import software.amazon.awssdk.services.pinpoint.model.PinpointException;
Code
try {
CreateApplicationRequest appRequest = CreateApplicationRequest.builder()
.name(appName)
.build();
return result.applicationResponse().id();
} catch (PinpointException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
return "";
To create a dynamic segment, first build all of the dimensions you want for this segment. For example,
the following code snippet is set to include customers who were active on the site in the last 30 days.
You can do this by first building a RecencyDimension object with the duration() and recencyType()
you want (that is, ACTIVE or INACTIVE), and then passing this object to a SegmentBehaviors builder
object as the value of recency().
When you have defined your segment attributes, build them into a SegmentDimensions object. Then
build a WriteSegmentRequest object, passing in the SegmentDimensions object as the value of its
112
AWS SDK for Java version 2 Developer Guide
Create a dynamic segment
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.pinpoint.PinpointClient;
import software.amazon.awssdk.services.pinpoint.model.AttributeDimension;
import software.amazon.awssdk.services.pinpoint.model.SegmentResponse;
import software.amazon.awssdk.services.pinpoint.model.AttributeType;
import software.amazon.awssdk.services.pinpoint.model.RecencyDimension;
import software.amazon.awssdk.services.pinpoint.model.SegmentBehaviors;
import software.amazon.awssdk.services.pinpoint.model.SegmentDemographics;
import software.amazon.awssdk.services.pinpoint.model.SegmentLocation;
import software.amazon.awssdk.services.pinpoint.model.SegmentDimensions;
import software.amazon.awssdk.services.pinpoint.model.WriteSegmentRequest;
import software.amazon.awssdk.services.pinpoint.model.CreateSegmentRequest;
import software.amazon.awssdk.services.pinpoint.model.CreateSegmentResponse;
import software.amazon.awssdk.services.pinpoint.model.PinpointException;
import java.util.HashMap;
import java.util.Map;
Code
try {
Map<String, AttributeDimension> segmentAttributes = new HashMap<>();
segmentAttributes.put("Team", AttributeDimension.builder()
.attributeType(AttributeType.INCLUSIVE)
.values("Lakers")
.build());
113
AWS SDK for Java version 2 Developer Guide
Import a static segment
.build();
CreateSegmentResponse createSegmentResult =
client.createSegment(createSegmentRequest);
System.out.println("Segment ID: " + createSegmentResult.segmentResponse().id());
System.out.println("Done");
return createSegmentResult.segmentResponse();
} catch (PinpointException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
return null;
}
Prerequisite
Before you can complete this example, you need to create an IAM role that grants Amazon Pinpoint
access to Amazon S3. For more information, see IAM role for importing endpoints or segments in the
Amazon Pinpoint Developer Guide.
To import a static segment, start by building an ImportJobRequest object. In the builder, specify the
s3Url(), roleArn(), and format().
Note
For more information about the properties of an ImportJobRequest, see the
ImportJobRequest section of Import Jobs in the Amazon Pinpoint API Reference.
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.pinpoint.PinpointClient;
import software.amazon.awssdk.services.pinpoint.model.CreateImportJobRequest;
import software.amazon.awssdk.services.pinpoint.model.ImportJobResponse;
import software.amazon.awssdk.services.pinpoint.model.ImportJobRequest;
import software.amazon.awssdk.services.pinpoint.model.Format;
import software.amazon.awssdk.services.pinpoint.model.CreateImportJobResponse;
import software.amazon.awssdk.services.pinpoint.model.PinpointException;
Code
114
AWS SDK for Java version 2 Developer Guide
List segments for your project
String appId,
String bucket,
String key,
String roleArn) {
try {
return jobResponse.importJobResponse();
} catch (PinpointException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
return null;
}
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.pinpoint.PinpointClient;
import software.amazon.awssdk.services.pinpoint.model.GetSegmentsRequest;
import software.amazon.awssdk.services.pinpoint.model.GetSegmentsResponse;
import software.amazon.awssdk.services.pinpoint.model.PinpointException;
import software.amazon.awssdk.services.pinpoint.model.SegmentResponse;
import java.util.List;
Code
try {
GetSegmentsRequest request = GetSegmentsRequest.builder()
.applicationId(appId)
.build();
115
AWS SDK for Java version 2 Developer Guide
Create a campaign
Create a campaign
A campaign is an initiative meant to engage a particular audience segment by sending messages to those
customers.
To create a campaign, first build all of the settings you want for this campaign. In the following code
snippet, for example, the campaign will start immediately because the startTime() of the Schedule is
set to IMMEDIATE. To set it to start at a specific time instead, specify a time in ISO 8601 format.
Note
For more information about the settings available for campaigns, see the Schedule section of
Campaigns in the Amazon Pinpoint API Reference.
After you define your campaign configuration, build it into a WriteCampaignRequest object. None
of the methods of the builder() of the WriteCampaignRequest are required. But you do
need to include any of the configuration settings (MessageConfiguration) that you set for the
campaign. We also recommend that you include a name and a description for your campaign so
you can easily distinguish it from other campaigns. Call the createCampaign() method of your
PinpointClient, passing in the WriteCampaignRequest object. Capture the result of this request as
a CreateCampaignResponse object.
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.pinpoint.PinpointClient;
import software.amazon.awssdk.services.pinpoint.model.CampaignResponse;
import software.amazon.awssdk.services.pinpoint.model.Message;
import software.amazon.awssdk.services.pinpoint.model.Schedule;
import software.amazon.awssdk.services.pinpoint.model.Action;
import software.amazon.awssdk.services.pinpoint.model.MessageConfiguration;
import software.amazon.awssdk.services.pinpoint.model.WriteCampaignRequest;
import software.amazon.awssdk.services.pinpoint.model.CreateCampaignResponse;
import software.amazon.awssdk.services.pinpoint.model.CreateCampaignRequest;
import software.amazon.awssdk.services.pinpoint.model.PinpointException;
Code
116
AWS SDK for Java version 2 Developer Guide
Send a message
try {
Schedule schedule = Schedule.builder()
.startTime("IMMEDIATE")
.build();
return result.campaignResponse();
} catch (PinpointException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
return null;
}
Send a message
To send an SMS text message through Amazon Pinpoint, first build an AddressConfiguration object to
specify the channelType(). (In the following example, it’s set to ChannelType.SMS to indicate the
message will be sent via SMS.) Initialize a HashMap to store the destination phone number and the
AddressConfiguration object. Next, build an SMSMessage object containing the relevant values.
These include the originationNumber, the type of message (messageType), and the body of the
message itself.
When you have created the message, build the SMSMessage object into a DirectMessageConfiguration
object. Build your Map object and DirectMessageConfiguration object into a MessageRequest
object. Build a SendMessagesRequest object, including your project ID (applicationId) and your
MessageRequest object. Call the sendMessages() method of your PinpointClient, passing in the
SendMessagesRequest object. Capture the result of this request as a SendMessagesResponse object.
117
AWS SDK for Java version 2 Developer Guide
Send a message
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.pinpoint.PinpointClient;
import software.amazon.awssdk.services.pinpoint.model.DirectMessageConfiguration;
import software.amazon.awssdk.services.pinpoint.model.SMSMessage;
import software.amazon.awssdk.services.pinpoint.model.AddressConfiguration;
import software.amazon.awssdk.services.pinpoint.model.ChannelType;
import software.amazon.awssdk.services.pinpoint.model.MessageRequest;
import software.amazon.awssdk.services.pinpoint.model.SendMessagesRequest;
import software.amazon.awssdk.services.pinpoint.model.SendMessagesResponse;
import software.amazon.awssdk.services.pinpoint.model.MessageResponse;
import software.amazon.awssdk.services.pinpoint.model.PinpointException;
import java.util.HashMap;
import java.util.Map;
Code
try {
addressMap.put(destinationNumber, addConfig);
} catch (PinpointException e) {
118
AWS SDK for Java version 2 Developer Guide
Amazon S3 Examples
e.getStackTrace();
}
The following examples include only the code needed to demonstrate each technique. The complete
example code is available on GitHub. From there, you can download a single source file or clone the
repository locally to get all the examples to build and run.
Topics
• Creating, Listing, and Deleting Amazon S3 Buckets (p. 119)
• Work with Amazon S3 objects (p. 122)
Topics
• Create a Bucket (p. 119)
• List the Buckets (p. 120)
• Delete a Bucket (p. 121)
Create a Bucket
Build a CreateBucketRequest and provide a bucket name. Pass it to the S3Client’s createBucket
method. Use the S3Client to do additional operations such as listing or deleting buckets as shown in later
examples.
Imports
119
AWS SDK for Java version 2 Developer Guide
Bucket Operations
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.CreateBucketConfiguration;
import software.amazon.awssdk.services.s3.model.CreateBucketRequest;
import software.amazon.awssdk.services.s3.model.DeleteBucketRequest;
import software.amazon.awssdk.services.s3.model.ListBucketsRequest;
import software.amazon.awssdk.services.s3.model.ListBucketsResponse;
Code
// Create bucket
CreateBucketRequest createBucketRequest = CreateBucketRequest
.builder()
.bucket(bucket)
.createBucketConfiguration(CreateBucketConfiguration.builder()
.locationConstraint(region.id())
.build())
.build();
s3.createBucket(createBucketRequest);
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.CreateBucketConfiguration;
import software.amazon.awssdk.services.s3.model.CreateBucketRequest;
import software.amazon.awssdk.services.s3.model.DeleteBucketRequest;
import software.amazon.awssdk.services.s3.model.ListBucketsRequest;
import software.amazon.awssdk.services.s3.model.ListBucketsResponse;
Code
120
AWS SDK for Java version 2 Developer Guide
Bucket Operations
// List buckets
ListBucketsRequest listBucketsRequest = ListBucketsRequest.builder().build();
ListBucketsResponse listBucketsResponse = s3.listBuckets(listBucketsRequest);
listBucketsResponse.buckets().stream().forEach(x -> System.out.println(x.name()));
Delete a Bucket
Before you can delete an Amazon S3 bucket, you must ensure that the bucket is empty or the service will
return an error. If you have a versioned bucket, you must also delete any versioned objects that are in the
bucket.
Topics
• Delete Objects in a Bucket (p. 121)
• Delete an Empty Bucket (p. 121)
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.CreateBucketConfiguration;
import software.amazon.awssdk.services.s3.model.CreateBucketRequest;
import software.amazon.awssdk.services.s3.model.DeleteBucketRequest;
import software.amazon.awssdk.services.s3.model.ListBucketsRequest;
import software.amazon.awssdk.services.s3.model.ListBucketsResponse;
Code
DeleteBucketRequest deleteBucketRequest =
DeleteBucketRequest.builder().bucket(bucket).build();
s3.deleteBucket(deleteBucketRequest);
Imports
import software.amazon.awssdk.regions.Region;
121
AWS SDK for Java version 2 Developer Guide
Object Operations
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.CreateBucketConfiguration;
import software.amazon.awssdk.services.s3.model.CreateBucketRequest;
import software.amazon.awssdk.services.s3.model.DeleteBucketRequest;
import software.amazon.awssdk.services.s3.model.ListBucketsRequest;
import software.amazon.awssdk.services.s3.model.ListBucketsResponse;
Code
DeleteBucketRequest deleteBucketRequest =
DeleteBucketRequest.builder().bucket(bucket).build();
s3.deleteBucket(deleteBucketRequest);
DeleteBucketRequest deleteBucketRequest =
DeleteBucketRequest.builder().bucket(bucket).build();
s3.deleteBucket(deleteBucketRequest);
Topics
• Upload an object (p. 122)
• Upload objects in multiple parts (p. 123)
• Download an object (p. 125)
• Delete an object (p. 126)
• Copy an object (p. 126)
• List objects (p. 127)
Upload an object
Build a PutObjectRequest and supply a bucket name and key name. Then use the S3Client’s putObject
method with a RequestBody that contains the object content and the PutObjectRequest object. The
bucket must exist, or the service will return an error.
122
AWS SDK for Java version 2 Developer Guide
Object Operations
Imports
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Random;
import software.amazon.awssdk.core.waiters.WaiterResponse;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.paginators.ListObjectsV2Iterable;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.s3.model.S3Exception;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.ListObjectsV2Request;
import software.amazon.awssdk.services.s3.model.ListObjectsV2Response;
import software.amazon.awssdk.services.s3.model.S3Object;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
import software.amazon.awssdk.services.s3.model.DeleteBucketRequest;
import software.amazon.awssdk.services.s3.model.CreateMultipartUploadRequest;
import software.amazon.awssdk.services.s3.model.CreateMultipartUploadResponse;
import software.amazon.awssdk.services.s3.model.CompletedMultipartUpload;
import software.amazon.awssdk.services.s3.model.CreateBucketRequest;
import software.amazon.awssdk.services.s3.model.CompletedPart;
import software.amazon.awssdk.services.s3.model.CreateBucketConfiguration;
import software.amazon.awssdk.services.s3.model.UploadPartRequest;
import software.amazon.awssdk.services.s3.model.CompleteMultipartUploadRequest;
import software.amazon.awssdk.services.s3.waiters.S3Waiter;
import software.amazon.awssdk.services.s3.model.HeadBucketRequest;
import software.amazon.awssdk.services.s3.model.HeadBucketResponse;
Code
s3.putObject(objectRequest, RequestBody.fromByteBuffer(getRandomByteBuffer(10_000)));
Imports
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Random;
import software.amazon.awssdk.core.waiters.WaiterResponse;
import software.amazon.awssdk.regions.Region;
123
AWS SDK for Java version 2 Developer Guide
Object Operations
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.paginators.ListObjectsV2Iterable;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.s3.model.S3Exception;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.ListObjectsV2Request;
import software.amazon.awssdk.services.s3.model.ListObjectsV2Response;
import software.amazon.awssdk.services.s3.model.S3Object;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
import software.amazon.awssdk.services.s3.model.DeleteBucketRequest;
import software.amazon.awssdk.services.s3.model.CreateMultipartUploadRequest;
import software.amazon.awssdk.services.s3.model.CreateMultipartUploadResponse;
import software.amazon.awssdk.services.s3.model.CompletedMultipartUpload;
import software.amazon.awssdk.services.s3.model.CreateBucketRequest;
import software.amazon.awssdk.services.s3.model.CompletedPart;
import software.amazon.awssdk.services.s3.model.CreateBucketConfiguration;
import software.amazon.awssdk.services.s3.model.UploadPartRequest;
import software.amazon.awssdk.services.s3.model.CompleteMultipartUploadRequest;
import software.amazon.awssdk.services.s3.waiters.S3Waiter;
import software.amazon.awssdk.services.s3.model.HeadBucketRequest;
import software.amazon.awssdk.services.s3.model.HeadBucketResponse;
Code
CreateMultipartUploadResponse response =
s3.createMultipartUpload(createMultipartUploadRequest);
String uploadId = response.uploadId();
System.out.println(uploadId);
UploadPartRequest uploadPartRequest2 =
UploadPartRequest.builder().bucket(bucketName).key(key)
.uploadId(uploadId)
.partNumber(2).build();
String etag2 = s3.uploadPart(uploadPartRequest2,
RequestBody.fromByteBuffer(getRandomByteBuffer(3 * mB))).eTag();
CompletedPart part2 = CompletedPart.builder().partNumber(2).eTag(etag2).build();
CompleteMultipartUploadRequest completeMultipartUploadRequest =
124
AWS SDK for Java version 2 Developer Guide
Object Operations
CompleteMultipartUploadRequest.builder()
.bucket(bucketName)
.key(key)
.uploadId(uploadId)
.multipartUpload(completedMultipartUpload)
.build();
s3.completeMultipartUpload(completeMultipartUploadRequest);
Download an object
Build a GetObjectRequest and supply a bucket name and key name. Use the S3Client’s getObject
method, passing it the GetObjectRequest object and a ResponseTransformer object. The
ResponseTransformer creates a response handler that writes the response content to the specified
file or stream.
The following example specifies a file name to write the object content to.
Imports
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Random;
import software.amazon.awssdk.core.waiters.WaiterResponse;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.paginators.ListObjectsV2Iterable;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.s3.model.S3Exception;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.ListObjectsV2Request;
import software.amazon.awssdk.services.s3.model.ListObjectsV2Response;
import software.amazon.awssdk.services.s3.model.S3Object;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
import software.amazon.awssdk.services.s3.model.DeleteBucketRequest;
import software.amazon.awssdk.services.s3.model.CreateMultipartUploadRequest;
import software.amazon.awssdk.services.s3.model.CreateMultipartUploadResponse;
import software.amazon.awssdk.services.s3.model.CompletedMultipartUpload;
import software.amazon.awssdk.services.s3.model.CreateBucketRequest;
import software.amazon.awssdk.services.s3.model.CompletedPart;
import software.amazon.awssdk.services.s3.model.CreateBucketConfiguration;
import software.amazon.awssdk.services.s3.model.UploadPartRequest;
import software.amazon.awssdk.services.s3.model.CompleteMultipartUploadRequest;
import software.amazon.awssdk.services.s3.waiters.S3Waiter;
import software.amazon.awssdk.services.s3.model.HeadBucketRequest;
import software.amazon.awssdk.services.s3.model.HeadBucketResponse;
Code
s3.getObject(getObjectRequest);
125
AWS SDK for Java version 2 Developer Guide
Object Operations
Delete an object
Build a DeleteObjectRequest and supply a bucket name and key name. Use the S3Client’s
deleteObject method, and pass it the name of a bucket and object to delete. The specified bucket and
object key must exist, or the service will return an error.
Imports
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Random;
import software.amazon.awssdk.core.waiters.WaiterResponse;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.paginators.ListObjectsV2Iterable;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.s3.model.S3Exception;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.ListObjectsV2Request;
import software.amazon.awssdk.services.s3.model.ListObjectsV2Response;
import software.amazon.awssdk.services.s3.model.S3Object;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
import software.amazon.awssdk.services.s3.model.DeleteBucketRequest;
import software.amazon.awssdk.services.s3.model.CreateMultipartUploadRequest;
import software.amazon.awssdk.services.s3.model.CreateMultipartUploadResponse;
import software.amazon.awssdk.services.s3.model.CompletedMultipartUpload;
import software.amazon.awssdk.services.s3.model.CreateBucketRequest;
import software.amazon.awssdk.services.s3.model.CompletedPart;
import software.amazon.awssdk.services.s3.model.CreateBucketConfiguration;
import software.amazon.awssdk.services.s3.model.UploadPartRequest;
import software.amazon.awssdk.services.s3.model.CompleteMultipartUploadRequest;
import software.amazon.awssdk.services.s3.waiters.S3Waiter;
import software.amazon.awssdk.services.s3.model.HeadBucketRequest;
import software.amazon.awssdk.services.s3.model.HeadBucketResponse;
Code
s3.deleteObject(deleteObjectRequest);
Copy an object
Build a CopyObjectRequest and supply a bucket name that the object is coped into, a URL encoded
string value (see the URLEncoder.encode method), and the key name of the object. Use the S3Client’s
copyObject method, and pass the CopyObjectRequest object. The specified bucket and object key must
exist, or the service will return an error.
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.CopyObjectRequest;
import software.amazon.awssdk.services.s3.model.CopyObjectResponse;
126
AWS SDK for Java version 2 Developer Guide
Object Operations
import software.amazon.awssdk.services.s3.model.S3Exception;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
Code
public static String copyBucketObject (S3Client s3, String fromBucket, String objectKey,
String toBucket) {
try {
CopyObjectResponse copyRes = s3.copyObject(copyReq);
return copyRes.copyObjectResult().toString();
} catch (S3Exception e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
List objects
Build a ListObjectsRequest and supply the bucket name. Then invoke the S3Client’s listObjects
method and pass the ListObjectsRequest object. This method returns a ListObjectsResponse that
contains all of the objects in the bucket. You can invoke this object’s contents method to get a list of
objects. You can iterate through this list to display the objects, as shown in the following code example.
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.ListObjectsRequest;
import software.amazon.awssdk.services.s3.model.ListObjectsResponse;
import software.amazon.awssdk.services.s3.model.S3Exception;
import software.amazon.awssdk.services.s3.model.S3Object;
import java.util.List;
import java.util.ListIterator;
Code
try {
ListObjectsRequest listObjects = ListObjectsRequest
.builder()
.bucket(bucketName)
.build();
127
AWS SDK for Java version 2 Developer Guide
Amazon S3 Presigned Examples
Topics
• Generate a Presigned URL and Upload an Object (p. 128)
• Get a Presigned Object (p. 130)
You can use the PresignedPutObjectRequest object to obtain the URL by invoking its url method.
Imports
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.Duration;
import software.amazon.awssdk.services.s3.model.ObjectCannedACL;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.S3Exception;
import software.amazon.awssdk.services.s3.presigner.model.PresignedPutObjectRequest;
import software.amazon.awssdk.services.s3.presigner.S3Presigner;
128
AWS SDK for Java version 2 Developer Guide
Generate a Presigned URL and Upload an Object
import software.amazon.awssdk.services.s3.presigner.model.PutObjectPresignRequest;
Code
try {
PresignedPutObjectRequest presignedRequest =
presigner.presignPutObject(presignRequest);
// Create the connection and use it to upload the new object by using the pre-
signed URL
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type","text/plain");
connection.setRequestMethod("PUT");
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write("This text uploaded as an object via presigned URL.");
out.close();
connection.getResponseCode();
System.out.println("HTTP response code: " + connection.getResponseCode());
/*
* It's recommended that you close the S3Presigner when it is done being used,
because some credential
* providers (e.g. if your AWS profile is configured to assume an STS role)
require system resources
* that need to be freed. If you are using one S3Presigner per application (as
recommended), this
* usually isn't needed
*/
presigner.close();
} catch (S3Exception e) {
e.getStackTrace();
} catch (IOException e) {
e.getStackTrace();
}
129
AWS SDK for Java version 2 Developer Guide
Get a Presigned Object
Invoke the presignGetObject method that belongs to the S3Presigner object to create a
PresignedPutObjectRequest object. You can invoke this object’s url method to obtain the URL to use.
Once you have the URL, you can use standard HTTP Java logic to read the contents of the bucket, as
shown in the following Java code example.
Imports
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.time.Duration;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.S3Exception;
import software.amazon.awssdk.services.s3.presigner.model.GetObjectPresignRequest;
import software.amazon.awssdk.services.s3.presigner.model.PresignedGetObjectRequest;
import software.amazon.awssdk.services.s3.presigner.S3Presigner;
import software.amazon.awssdk.utils.IoUtils;
Code
The following Java code example reads content from a presigned S3 bucket.
try {
130
AWS SDK for Java version 2 Developer Guide
Amazon SNS Examples
// Specify any headers that the service needs (not needed when
isBrowserExecutable is true)
presignedGetObjectRequest.httpRequest().headers().forEach((header, values) -> {
values.forEach(value -> {
connection.addRequestProperty(header, value);
});
});
// Send any request payload that the service needs (not needed when
isBrowserExecutable is true)
if (presignedGetObjectRequest.signedPayload().isPresent()) {
connection.setDoOutput(true);
try (InputStream signedPayload =
presignedGetObjectRequest.signedPayload().get().asInputStream();
OutputStream httpOutputStream = connection.getOutputStream()) {
IoUtils.copy(signedPayload, httpOutputStream);
}
}
/*
* It's recommended that you close the S3Presigner when it is done being used,
because some credential
* providers (e.g. if your AWS profile is configured to assume an STS role)
require system resources
* that need to be freed. If you are using one S3Presigner per application (as
recommended), this
* usually isn't needed
*/
presigner.close();
} catch (S3Exception e) {
e.getStackTrace();
} catch (IOException e) {
e.getStackTrace();
}
Create a topic
A topic is a logical grouping of communication channels that defines which systems to send a message
to, for example, fanning out a message to AWS Lambda and an HTTP webhook. You send messages to
Amazon SNS, then they’re distributed to the channels defined in the topic. This makes the messages
available to subscribers.
To create a topic, first build a CreateTopicRequest object, with the name of the topic set using
the name() method in the builder. Then, send the request object to Amazon SNS by using
131
AWS SDK for Java version 2 Developer Guide
List your SNS topics
the createTopic() method of the SnsClient. You can capture the result of this request as a
CreateTopicResponse object, as demonstrated in the following code snippet.
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.CreateTopicRequest;
import software.amazon.awssdk.services.sns.model.CreateTopicResponse;
import software.amazon.awssdk.services.sns.model.SnsException;
Code
result = snsClient.createTopic(request);
return result.topicArn();
} catch (SnsException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
return "";
The following code snippet prints out the HTTP status code of the request and a list of Amazon Resource
Names (ARNs) for your Amazon SNS topics.
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.ListTopicsRequest;
import software.amazon.awssdk.services.sns.model.ListTopicsResponse;
import software.amazon.awssdk.services.sns.model.SnsException;
Code
try {
ListTopicsRequest request = ListTopicsRequest.builder()
.build();
132
AWS SDK for Java version 2 Developer Guide
Subscribe an endpoint to a topic
} catch (SnsException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
To configure a communication channel as an endpoint for a topic, subscribe that endpoint to the topic.
To start, build a SubscribeRequest object. Specify the communication channel (for example, lambda
or email) as the protocol(). Set the endpoint() to the relevant output location (for example, the
ARN of a Lambda function or an email address), and then set the ARN of the topic to which you want to
subscribe as the topicArn(). Send the request object to SNS by using the subscribe() method of the
SnsClient. You can capture the result of this request as a SubscribeResponse object.
The following code snippet shows how to subscribe an email address to a topic.
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.SnsException;
import software.amazon.awssdk.services.sns.model.SubscribeRequest;
import software.amazon.awssdk.services.sns.model.SubscribeResponse;
Code
try {
SubscribeRequest request = SubscribeRequest.builder()
.protocol("email")
.endpoint(email)
.returnSubscriptionArn(true)
.topicArn(topicArn)
.build();
} catch (SnsException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
133
AWS SDK for Java version 2 Developer Guide
Unsubscribe an endpoint from a topic
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.PublishRequest;
import software.amazon.awssdk.services.sns.model.PublishResponse;
import software.amazon.awssdk.services.sns.model.SnsException;
Code
try {
PublishRequest request = PublishRequest.builder()
.message(message)
.topicArn(topicArn)
.build();
} catch (SnsException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
To remove a communication channel as an endpoint for a topic, unsubscribe that endpoint from the
topic. To start, build an UnsubscribeRequest object and set the ARN of the topic you want to unsubscribe
from as the subscriptionArn(). Then send the request object to SNS by using the unsubscribe()
method of the SnsClient. You can capture the result of this request as an UnsubscribeResponse object.
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.SnsException;
import software.amazon.awssdk.services.sns.model.UnsubscribeRequest;
import software.amazon.awssdk.services.sns.model.UnsubscribeResponse;
Code
try {
UnsubscribeRequest request = UnsubscribeRequest.builder()
.subscriptionArn(subscriptionToken)
.build();
134
AWS SDK for Java version 2 Developer Guide
Delete a topic
} catch (SnsException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
Delete a topic
To delete an Amazon SNS topic, first build a DeleteTopicRequest object with the ARN of the topic set
as the topicArn() method in the builder. Then send the request object to Amazon SNS by using
the deleteTopic() method of the SnsClient. You can capture the result of this request as a
DeleteTopicResponse object, as demonstrated in the following code snippet.
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.DeleteTopicRequest;
import software.amazon.awssdk.services.sns.model.DeleteTopicResponse;
import software.amazon.awssdk.services.sns.model.SnsException;
Code
try {
DeleteTopicRequest request = DeleteTopicRequest.builder()
.topicArn(topicArn)
.build();
} catch (SnsException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
The following examples include only the code needed to demonstrate each technique. The complete
example code is available on GitHub. From there, you can download a single source file or clone the
repository locally to get all the examples to build and run.
Topics
• Work with Amazon SQS message queues (p. 136)
• Sending, Receiving, and Deleting Amazon SQS Messages (p. 138)
135
AWS SDK for Java version 2 Developer Guide
Queue Operations
This topic describes how to create, list, delete, and get the URL of an Amazon SQS queue by using the
AWS SDK for Java.
Create a queue
Use the SqsClient’s createQueue method, and provide a CreateQueueRequest object that describes the
queue parameters.
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sqs.SqsClient;
import software.amazon.awssdk.services.sqs.model.ChangeMessageVisibilityRequest;
import software.amazon.awssdk.services.sqs.model.CreateQueueRequest;
import software.amazon.awssdk.services.sqs.model.DeleteMessageRequest;
import software.amazon.awssdk.services.sqs.model.GetQueueUrlRequest;
import software.amazon.awssdk.services.sqs.model.GetQueueUrlResponse;
import software.amazon.awssdk.services.sqs.model.ListQueuesRequest;
import software.amazon.awssdk.services.sqs.model.ListQueuesResponse;
import software.amazon.awssdk.services.sqs.model.Message;
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;
Code
sqsClient.createQueue(createQueueRequest);
List queues
To list the Amazon SQS queues for your account, call the SqsClient’s listQueues method with a
ListQueuesRequest object.
Using the listQueues overload without any parameters returns all queues, up to 1,000 queues. You can
supply a queue name prefix to the ListQueuesRequest object to limit the results to queues that match
that prefix.
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sqs.SqsClient;
import software.amazon.awssdk.services.sqs.model.ChangeMessageVisibilityRequest;
import software.amazon.awssdk.services.sqs.model.CreateQueueRequest;
import software.amazon.awssdk.services.sqs.model.DeleteMessageRequest;
import software.amazon.awssdk.services.sqs.model.GetQueueUrlRequest;
136
AWS SDK for Java version 2 Developer Guide
Queue Operations
import software.amazon.awssdk.services.sqs.model.GetQueueUrlResponse;
import software.amazon.awssdk.services.sqs.model.ListQueuesRequest;
import software.amazon.awssdk.services.sqs.model.ListQueuesResponse;
import software.amazon.awssdk.services.sqs.model.Message;
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;
Code
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sqs.SqsClient;
import software.amazon.awssdk.services.sqs.model.ChangeMessageVisibilityRequest;
import software.amazon.awssdk.services.sqs.model.CreateQueueRequest;
import software.amazon.awssdk.services.sqs.model.DeleteMessageRequest;
import software.amazon.awssdk.services.sqs.model.GetQueueUrlRequest;
import software.amazon.awssdk.services.sqs.model.GetQueueUrlResponse;
import software.amazon.awssdk.services.sqs.model.ListQueuesRequest;
import software.amazon.awssdk.services.sqs.model.ListQueuesResponse;
import software.amazon.awssdk.services.sqs.model.Message;
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;
Code
GetQueueUrlResponse getQueueUrlResponse =
sqsClient.getQueueUrl(GetQueueUrlRequest.builder().queueName(queueName).build());
String queueUrl = getQueueUrlResponse.queueUrl();
return queueUrl;
Delete a queue
Provide the queue’s URL (p. 137) to the DeleteMessageRequest object. Then call the SqsClient’s
deleteQueue method.
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sqs.SqsClient;
137
AWS SDK for Java version 2 Developer Guide
Message Operations
import software.amazon.awssdk.services.sqs.model.ChangeMessageVisibilityRequest;
import software.amazon.awssdk.services.sqs.model.CreateQueueRequest;
import software.amazon.awssdk.services.sqs.model.DeleteMessageRequest;
import software.amazon.awssdk.services.sqs.model.GetQueueUrlRequest;
import software.amazon.awssdk.services.sqs.model.GetQueueUrlResponse;
import software.amazon.awssdk.services.sqs.model.ListQueuesRequest;
import software.amazon.awssdk.services.sqs.model.ListQueuesResponse;
import software.amazon.awssdk.services.sqs.model.Message;
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;
Code
try {
sqsClient.deleteQueue(deleteQueueRequest);
} catch (QueueNameExistsException e) {
e.printStackTrace();
System.exit(1);
}
More information
• How Amazon SQS Queues Work in the Amazon SQS Developer Guide
• CreateQueue in the Amazon SQS API Reference
• GetQueueUrl in the Amazon SQS API Reference
• ListQueues in the Amazon SQS API Reference
• DeleteQueues in the Amazon SQS API Reference
Send a Message
Add a single message to an Amazon SQS queue by calling the SqsClient client sendMessage method.
Provide a SendMessageRequest object that contains the queue’s URL (p. 137), message body, and
optional delay value (in seconds).
138
AWS SDK for Java version 2 Developer Guide
Message Operations
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sqs.SqsClient;
import software.amazon.awssdk.services.sqs.model.ChangeMessageVisibilityRequest;
import software.amazon.awssdk.services.sqs.model.CreateQueueRequest;
import software.amazon.awssdk.services.sqs.model.DeleteMessageRequest;
import software.amazon.awssdk.services.sqs.model.GetQueueUrlRequest;
import software.amazon.awssdk.services.sqs.model.GetQueueUrlResponse;
import software.amazon.awssdk.services.sqs.model.ListQueuesRequest;
import software.amazon.awssdk.services.sqs.model.ListQueuesResponse;
import software.amazon.awssdk.services.sqs.model.Message;
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;
Code
sqsClient.sendMessage(SendMessageRequest.builder()
.queueUrl(queueUrl)
.messageBody("Hello world!")
.delaySeconds(10)
.build());
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sqs.SqsClient;
import software.amazon.awssdk.services.sqs.model.ChangeMessageVisibilityRequest;
import software.amazon.awssdk.services.sqs.model.CreateQueueRequest;
import software.amazon.awssdk.services.sqs.model.DeleteMessageRequest;
import software.amazon.awssdk.services.sqs.model.GetQueueUrlRequest;
import software.amazon.awssdk.services.sqs.model.GetQueueUrlResponse;
import software.amazon.awssdk.services.sqs.model.ListQueuesRequest;
import software.amazon.awssdk.services.sqs.model.ListQueuesResponse;
import software.amazon.awssdk.services.sqs.model.Message;
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;
Code
139
AWS SDK for Java version 2 Developer Guide
Message Operations
Retrieve Messages
Retrieve any messages that are currently in the queue by calling the SqsClientreceiveMessage method.
This method takes a ReceiveMessageRequest that contains the queue URL. You can also specify the
maximum number of messages to return. Messages are returned as a list of Message objects.
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sqs.SqsClient;
import software.amazon.awssdk.services.sqs.model.ChangeMessageVisibilityRequest;
import software.amazon.awssdk.services.sqs.model.CreateQueueRequest;
import software.amazon.awssdk.services.sqs.model.DeleteMessageRequest;
import software.amazon.awssdk.services.sqs.model.GetQueueUrlRequest;
import software.amazon.awssdk.services.sqs.model.GetQueueUrlResponse;
import software.amazon.awssdk.services.sqs.model.ListQueuesRequest;
import software.amazon.awssdk.services.sqs.model.ListQueuesResponse;
import software.amazon.awssdk.services.sqs.model.Message;
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;
Code
return messages;
Imports
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sqs.SqsClient;
import software.amazon.awssdk.services.sqs.model.ChangeMessageVisibilityRequest;
import software.amazon.awssdk.services.sqs.model.CreateQueueRequest;
import software.amazon.awssdk.services.sqs.model.DeleteMessageRequest;
import software.amazon.awssdk.services.sqs.model.GetQueueUrlRequest;
import software.amazon.awssdk.services.sqs.model.GetQueueUrlResponse;
import software.amazon.awssdk.services.sqs.model.ListQueuesRequest;
import software.amazon.awssdk.services.sqs.model.ListQueuesResponse;
import software.amazon.awssdk.services.sqs.model.Message;
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;
Code
140
AWS SDK for Java version 2 Developer Guide
Amazon Transcribe Examples
More Info
• How Amazon SQS Queues Work in the Amazon SQS Developer Guide
• SendMessage in the Amazon SQS API Reference
• SendMessageBatch in the Amazon SQS API Reference
• ReceiveMessage in the Amazon SQS API Reference
• DeleteMessage in the Amazon SQS API Reference
The following examples include only the code needed to demonstrate each technique. The complete
example code is available on GitHub. From there, you can download a single source file or clone the
repository locally to get all the examples to build and run.
Topics
• Working with Amazon Transcribe (p. 141)
See Streaming Transcription in the Amazon Transcribe Developer Guide to learn more about this feature.
See Getting Started in the Amazon Transcribe Developer Guide to get started using Amazon Transcribe.
Code
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.TargetDataLine;
141
AWS SDK for Java version 2 Developer Guide
Working with Amazon Transcribe
return dataLine;
}
}
Create a Publisher
This code implements a publisher that publishes audio data from the Amazon Transcribe audio stream.
Code
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.nio.ByteBuffer;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicLong;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.services.transcribestreaming.model.AudioEvent;
import software.amazon.awssdk.services.transcribestreaming.model.AudioStream;
@Override
public void subscribe(Subscriber<? super AudioStream> s) {
s.onSubscribe(new SubscriptionImpl(s, inputStream));
}
@Override
public void request(long n) {
142
AWS SDK for Java version 2 Developer Guide
Working with Amazon Transcribe
if (n <= 0) {
subscriber.onError(new IllegalArgumentException("Demand must be
positive"));
}
demand.getAndAdd(n);
executor.submit(() -> {
try {
do {
ByteBuffer audioBuffer = getNextEvent();
if (audioBuffer.remaining() > 0) {
AudioEvent audioEvent = audioEventFromBuffer(audioBuffer);
subscriber.onNext(audioEvent);
} else {
subscriber.onComplete();
break;
}
} while (demand.decrementAndGet() > 0);
} catch (Exception e) {
subscriber.onError(e);
}
});
}
@Override
public void cancel() {
int len = 0;
try {
len = inputStream.read(audioBytes);
if (len <= 0) {
audioBuffer = ByteBuffer.allocate(0);
} else {
audioBuffer = ByteBuffer.wrap(audioBytes, 0, len);
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return audioBuffer;
}
143
AWS SDK for Java version 2 Developer Guide
Working with Amazon Transcribe
You must also create a StartStreamTranscriptionResponseHandler to specify how to handle the response
from Amazon Transcribe.
Imports
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.TargetDataLine;
import javax.sound.sampled.AudioInputStream;
import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.services.transcribestreaming.TranscribeStreamingAsyncClient;
import software.amazon.awssdk.services.transcribestreaming.model.LanguageCode;
import software.amazon.awssdk.services.transcribestreaming.model.MediaEncoding;
import
software.amazon.awssdk.services.transcribestreaming.model.StartStreamTranscriptionRequest;
import
software.amazon.awssdk.services.transcribestreaming.model.StartStreamTranscriptionResponseHandler;
import software.amazon.awssdk.services.transcribestreaming.model.TranscriptEvent;
Code
.mediaEncoding(MediaEncoding.PCM)
.languageCode(LanguageCode.EN_US)
.mediaSampleRateHertz(16_000).build();
StartStreamTranscriptionResponseHandler response =
StartStreamTranscriptionResponseHandler.builder().subscriber(e -> {
TranscriptEvent event = (TranscriptEvent) e;
event.transcript().results().forEach(r -> r.alternatives().forEach(a ->
System.out.println(a.transcript())));
}).build();
More Info
• How It Works in the Amazon Transcribe Developer Guide.
• Getting Started With Streaming Audio in the Amazon Transcribe Developer Guide.
144
AWS SDK for Java version 2 Developer Guide
Pagination Examples
The following examples use Amazon S3 and Amazon DynamoDB operations to demonstrate the various
methods of retrieving your data from paginated responses.
Note
These code snippets assume that you understand the material in Using the AWS SDK for Java
2.0 (p. 12), and have configured default AWS credentials using the information in Set up AWS
credentials and region for development (p. 5).
Synchronous Pagination
These examples use the synchronous pagination methods for listing objects in an Amazon S3 bucket.
The first example demonstrates using the paginator object to iterate through all the response pages with
the stream method. You can directly stream over the response pages, convert the response stream to a
stream of S3Object content, and then process the content of the Amazon S3 object.
Imports
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Random;
import software.amazon.awssdk.core.waiters.WaiterResponse;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.paginators.ListObjectsV2Iterable;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.s3.model.S3Exception;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.ListObjectsV2Request;
import software.amazon.awssdk.services.s3.model.ListObjectsV2Response;
import software.amazon.awssdk.services.s3.model.S3Object;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
import software.amazon.awssdk.services.s3.model.DeleteBucketRequest;
import software.amazon.awssdk.services.s3.model.CreateMultipartUploadRequest;
import software.amazon.awssdk.services.s3.model.CreateMultipartUploadResponse;
import software.amazon.awssdk.services.s3.model.CompletedMultipartUpload;
import software.amazon.awssdk.services.s3.model.CreateBucketRequest;
import software.amazon.awssdk.services.s3.model.CompletedPart;
import software.amazon.awssdk.services.s3.model.CreateBucketConfiguration;
145
AWS SDK for Java version 2 Developer Guide
Synchronous Pagination
import software.amazon.awssdk.services.s3.model.UploadPartRequest;
import software.amazon.awssdk.services.s3.model.CompleteMultipartUploadRequest;
import software.amazon.awssdk.services.s3.waiters.S3Waiter;
import software.amazon.awssdk.services.s3.model.HeadBucketRequest;
import software.amazon.awssdk.services.s3.model.HeadBucketResponse;
Code
Use a Stream
Use the stream method on the response content to iterate over the paginated item collection.
Code
Code
Manual Pagination
If your use case requires it, manual pagination is still available. Use the next token in the response object
for the subsequent requests. Here’s an example using a while loop.
146
AWS SDK for Java version 2 Developer Guide
Asynchronous Pagination
Code
if (listObjResponse.nextContinuationToken() == null) {
done = true;
}
listObjectsReqManual = listObjectsReqManual.toBuilder()
.continuationToken(listObjResponse.nextContinuationToken())
.build();
}
Asynchronous Pagination
These examples use the asynchronous pagination methods for listing tables in DynamoDB. A manual
pagination example is available in the Asynchronous Programming (p. 20) topic.
Call the subscribe method on the ListTablesPublisher and pass a subscriber implementation. In this
example, the subscriber has an onNext method that requests one item at a time from the publisher. This
is the method that is called repeatedly until all pages are retrieved. The onSubscribe method calls the
Subscription.request method to initiate requests for data from the publisher. This method must be
called to start getting data from the publisher. The onError method is triggered if an error occurs while
retrieving data. Finally, the onComplete method is called when all pages have been requested.
Use a Subscriber
Imports
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import software.amazon.awssdk.core.async.SdkPublisher;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.model.ListTablesRequest;
import software.amazon.awssdk.services.dynamodb.model.ListTablesResponse;
import software.amazon.awssdk.services.dynamodb.paginators.ListTablesPublisher;
import io.reactivex.Flowable;
147
AWS SDK for Java version 2 Developer Guide
Asynchronous Pagination
import reactor.core.publisher.Flux;
Code
// Creates a default client with credentials and regions loaded from the environment
final DynamoDbAsyncClient asyncClient = DynamoDbAsyncClient.create();
@Override
public void onSubscribe(Subscription s) {
subscription = s;
// Request method should be called to demand data. Here we request a single page
subscription.request(1);
}
@Override
public void onNext(ListTablesResponse response) {
response.tableNames().forEach(System.out::println);
// Once you process the current page, call the request method to signal that you
are ready for next page
subscription.request(1);
}
@Override
public void onError(Throwable t) {
// Called when an error has occurred while processing the requests
}
@Override
public void onComplete() {
// This indicates all the results are delivered and there are no more pages left
}
Code
.forEach(System.out::println));
148
AWS SDK for Java version 2 Developer Guide
Asynchronous Pagination
Use a Subscriber
Code
// Creates a default client with credentials and regions loaded from the environment
final DynamoDbAsyncClient asyncClient = DynamoDbAsyncClient.create();
// Use subscriber
publisher.subscribe(new Subscriber<String>() {
private Subscription subscription;
@Override
public void onSubscribe(Subscription s) {
subscription = s;
subscription.request(1);
}
@Override
public void onNext(String tableName) {
System.out.println(tableName);
subscription.request(1);
}
@Override
public void onError(Throwable t) { }
@Override
public void onComplete() { }
Code
// Use forEach
CompletableFuture<Void> future = publisher.subscribe(System.out::println);
future.get();
149
AWS SDK for Java version 2 Developer Guide
Asynchronous Pagination
To use the library, add it as a dependency. If using Maven, the example shows the POM snippet to use.
POM Entry
<version>2.11.4-PREVIEW</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
Imports
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import software.amazon.awssdk.core.async.SdkPublisher;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.model.ListTablesRequest;
import software.amazon.awssdk.services.dynamodb.model.ListTablesResponse;
import software.amazon.awssdk.services.dynamodb.paginators.ListTablesPublisher;
import io.reactivex.Flowable;
import reactor.core.publisher.Flux;
Code
// The Flowable class has many helper methods that work with any reactive streams
compatible publisher implementation
List<String> tables = Flowable.fromPublisher(publisher)
.flatMapIterable(ListTablesResponse::tableNames)
.toList()
.blockingGet();
System.out.println(tables);
150
AWS SDK for Java version 2 Developer Guide
Data Protection
Security of the Cloud– AWS is responsible for protecting the infrastructure that runs all of the services
offered in the AWS Cloud and providing you with services that you can use securely. Our security
responsibility is the highest priority at AWS, and the effectiveness of our security is regularly tested and
verified by third-party auditors as part of the AWS Compliance Programs.
Security in the Cloud– Your responsibility is determined by the AWS service you are using, and other
factors including the sensitivity of your data, your organization’s requirements, and applicable laws and
regulations.
Topics
• Data Protection in this AWS Product or Service (p. 151)
• AWS SDK for Java support for TLS 1.2 (p. 152)
• Identity and Access Management for this AWS Product or Service (p. 153)
• Compliance Validation for this AWS Product or Service (p. 153)
• Resilience for this AWS Product or Service (p. 154)
• Infrastructure Security for this AWS Product or Service (p. 154)
For data protection purposes, we recommend that you protect AWS account credentials and set up
individual user accounts with AWS Identity and Access Management (IAM), so that each user is given only
the permissions necessary to fulfill their job duties. We also recommend that you secure your data in the
following ways:
151
AWS SDK for Java version 2 Developer Guide
Enforcing TLS 1.2
We strongly recommend that you never put sensitive identifying information, such as your customers’
account numbers, into free-form fields such as a Name field. This includes when you work with this
AWS product or service or other AWS services using the console, API, AWS CLI, or AWS SDKs. Any data
that you enter into this AWS product or service or other services might get picked up for inclusion in
diagnostic logs. When you provide a URL to an external server, don’t include credentials information in
the URL to validate your request to that server.
For more information about data protection, see the AWS Shared Responsibility Model and GDPR blog
post on the AWS Security Blog.
System*.out.println(*Arrays*.toString(*SSLContext*.getDefault().getSupportedSSLParameters().getProtocol
To see the SSL handshake in action and what version of TLS is used, you can use the system property
javax.net.debug.
• Apache HTTP client: The SDK always prefers TLS 1.2 (if it’s supported in the platform).
• ApacheHttpClient: The SDK always prefers TLS 1.2 (if it’s supported in the platform).
• UrlHttpConnectionClient: To enforce only TLS 1.2, you can use this Java command.
System.setProperty("jdk.tls.client.protocols", "TLSv1.2");
• NettyNioHttpClient: The SDK dependency for Netty is TLS 1.2 (if it’s supported in the platform).
152
AWS SDK for Java version 2 Developer Guide
Identity and Access Management
To use this AWS product or service to access AWS, you need an AWS account and AWS credentials. To
increase the security of your AWS account, we recommend that you use an IAM user to provide access
credentials instead of using your AWS account credentials.
For details about working with IAM, see AWS Identity and Access Management.
For an overview of IAM users and why they are important for the security of your account, see AWS
Security Credentials in the Amazon Web Services General Reference.
This AWS product or service follows the shared responsibility model through the specific Amazon Web
Services (AWS) services it supports. For AWS service security information, see the AWS service security
documentation page and AWS services that are in scope of AWS compliance efforts by compliance
program.
The security and compliance of AWS services is assessed by third-party auditors as part of multiple AWS
compliance programs. These include SOC, PCI, FedRAMP, HIPAA, and others. AWS provides a frequently
updated list of AWS services in scope of specific compliance programs at AWS Services in Scope by
Compliance Program.
Third-party audit reports are available for you to download using AWS Artifact. For more information,
see Downloading Reports in AWS Artifact.
For more information about AWS compliance programs, see AWS Compliance Programs.
Your compliance responsibility when using this AWS product or service to access an AWS service is
determined by the sensitivity of your data, your organization’s compliance objectives, and applicable
laws and regulations. If your use of an AWS service is subject to compliance with standards such as
HIPAA, PCI, or FedRAMP, AWS provides resources to help:
• Security and Compliance Quick Start Guides – Deployment guides that discuss architectural
considerations and provide steps for deploying security-focused and compliance-focused baseline
environments on AWS.
• Architecting for HIPAA Security and Compliance Whitepaper – A whitepaper that describes how
companies can use AWS to create HIPAA-compliant applications.
• AWS Compliance Resources – A collection of workbooks and guides that might apply to your industry
and location.
153
AWS SDK for Java version 2 Developer Guide
Resilience
• AWS Config – A service that assesses how well your resource configurations comply with internal
practices, industry guidelines, and regulations.
• AWS Security Hub – A comprehensive view of your security state within AWS that helps you check your
compliance with security industry standards and best practices.
AWS Regions provide multiple physically separated and isolated Availability Zones, which are connected
with low-latency, high-throughput, and highly redundant networking.
With Availability Zones, you can design and operate applications and databases that automatically fail
over between Availability Zones without interruption. Availability Zones are more highly available, fault
tolerant, and scalable than traditional single or multiple data center infrastructures.
For more information about AWS Regions and Availability Zones, see AWS Global Infrastructure.
This AWS product or service follows the shared responsibility model through the specific Amazon Web
Services (AWS) services it supports. For AWS service security information, see the AWS service security
documentation page and AWS services that are in scope of AWS compliance efforts by compliance
program.
154
AWS SDK for Java version 2 Developer Guide
Document history
This topic describes important changes to the AWS SDK for Java Developer Guide over the course of its
history.
30 September 2020
Added example topics for Amazon Pinpoint, Amazon Cognito, and Amazon SNS
29 May 2020
Added example topics for IAM, Amazon EC2, CloudWatch and DynamoDB
7 August 2017
155