Aws SDK Documentation

Download as pdf or txt
Download as pdf or txt
You are on page 1of 160
At a glance
Powered by AI
The document provides an overview of the AWS SDK for Java including its features, downloading and setup instructions, and examples of using services like S3, DynamoDB, and Lambda.

The AWS SDK for Java allows developers to build applications that integrate with AWS services like S3, EC2, DynamoDB, Lambda and more. It provides client libraries, examples, and documentation to make interacting with AWS services easier.

The AWS SDK for Java supports several methods for providing credentials for authentication including environment variables, Java system properties, credential profiles files, and AWS Identity and Access Management (IAM) roles for EC2 instances.

AWS SDK for Java version 2

Developer Guide

AWS SDK for Java version 2: Developer Guide


Copyright © 2020 Amazon Web Services, Inc. and/or its affiliates. All rights reserved.
AWS SDK for Java version 2 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

Import a static segment .................................................................................................. 114


List segments for your project .......................................................................................... 115
Create a campaign .......................................................................................................... 116
Send a message ............................................................................................................. 117
Amazon S3 Examples .............................................................................................................. 119
Bucket Operations .......................................................................................................... 119
Object Operations .......................................................................................................... 122
Amazon S3 Presigned Examples ............................................................................................... 128
Generate a Presigned URL and Upload an Object ................................................................ 128
Get a Presigned Object ................................................................................................... 130
Amazon SNS Examples ............................................................................................................ 131
Create a topic ................................................................................................................ 131
List your SNS topics ........................................................................................................ 132
Subscribe an endpoint to a topic ...................................................................................... 133
Publish a message to a topic ........................................................................................... 133
Unsubscribe an endpoint from a topic ............................................................................... 134
Delete a topic ................................................................................................................ 135
Amazon SQS Examples ............................................................................................................ 135
Queue Operations .......................................................................................................... 136
Message Operations ........................................................................................................ 138
Amazon Transcribe Examples ................................................................................................... 141
Working with Amazon Transcribe .................................................................................... 141
Pagination Examples ............................................................................................................... 145
Synchronous Pagination .................................................................................................. 145
Asynchronous Pagination ................................................................................................. 147
Security ......................................................................................................................................... 151
Data Protection ...................................................................................................................... 151
Enforcing TLS 1.2 ................................................................................................................... 152
TLS support in Java ........................................................................................................ 152
How to check the TLS version .......................................................................................... 152
How to set the TLS version .............................................................................................. 152
Identity and Access Management .............................................................................................. 153
Compliance Validation ............................................................................................................. 153
Resilience .............................................................................................................................. 154
Infrastructure Security ............................................................................................................. 154
Document history ........................................................................................................................... 155

v
AWS SDK for Java version 2 Developer Guide
What’s new in version 2

AWS SDK for Java 2.0 Developer


Guide
The AWS SDK for Java provides a Java API for Amazon Web Services. Using the SDK, you can easily
build Java applications that work with Amazon S3, Amazon EC2, DynamoDB, and more. We regularly
add support for new services to the AWS SDK for Java. For a list of changes and features in a particular
version, view the change log.

What’s new in version 2


The AWS SDK for Java 2.0 is a major rewrite of the version 1.x code base. It’s built on top of Java 8+ and
adds several frequently requested features. These include support for non-blocking I/O and the ability
to plug in a different HTTP implementation at run time. For more information see the AWS Blog. For
guidance on migrating your application from 1.11.x to 2.x, see the migration guide.

Features not yet in the AWS SDK for Java 2.0


See the following Github issues for details about additional features not yet in 2.x. Comments and
feedback are also welcome.

• 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:

• AWS SDK for Java 2.x Reference


• Java developer blog
• Java developer forums
• GitHub:
• Documentation source
• SDK source
• The AWS Code Sample Catalog
• @awsforjava (Twitter)

1
AWS SDK for Java version 2 Developer Guide
Contributing to the SDK

Contributing to the SDK


Developers can also contribute feedback through the following channels:

• Submit issues on GitHub:


• Submit documentation issues
• Submit SDK issues
• Join an informal chat about SDK on the AWS SDK for Java 2.x gitter channel
• Submit feedback anonymously to [email protected]. This email is monitored by
the AWS SDK for Java team.
• Submit pull requests in the documentation or SDK source GitHub repositories to contribute to the SDK
development.

Eclipse IDE support


The AWS Toolkit for Eclipse doesn’t currently support the AWS SDK for Java 2.0. To use the AWS Toolkit
for Eclipse with the AWS SDK for Java 2.0, you should use Maven tools in Eclipse to add a dependency on
the 2.x SDK.

Developing AWS applications for Android


If you’re an Android developer, Amazon Web Services publishes an SDK made specifically for Android
development: the AWS Mobile SDK for Android. See the AWS Mobile SDK for Android Developer Guide
for the complete documentation.

2
AWS SDK for Java version 2 Developer Guide
Sign up for AWS and Create an IAM User

Getting Started with AWS SDK for


Java 2.0
This section provides information about how to install, set up, and use the AWS SDK for Java.

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)

Sign up for AWS and Create an IAM User


To use the AWS SDK for Java to access Amazon Web Services (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.
Note
For an overview of IAM user and why they are important for the security of your account, see
AWS Security Credentials in the Amazon Web Services General Reference.

To sign up for AWS

1. Open https://aws.amazon.com/ and click Sign Up.


2. Follow the on-screen instructions. Part of the sign-up procedure involves receiving a phone call and
entering a PIN using your phone keypad.

Next, create an IAM user and download (or copy) its secret access key.

To create an IAM user

1. Go to the IAM console (you may need to sign in to AWS first).


2. Click Users in the sidebar to view your IAM users.
3. If you don’t have any IAM users set up, click Create New Users to create one.
4. Select the IAM user in the list that you’ll use to access AWS.
5. Open the Security Credentials tab, and click Create Access Key.
Note
You can have a maximum of two active access keys for any given IAM user. If your IAM user
has two access keys already, then you’ll need to delete one of them before creating a new
key.
6. On the resulting dialog box, click the Download Credentials button to download the credential file
to your computer, or click Show User Security Credentials to view the IAM user’s access key ID and
secret access key (which you can copy and paste).

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.

Download the AWS SDK for Java 2.0


This topic describes how to download the AWS SDK for Java into your project.

Prerequisites
To use the AWS SDK for Java, you must have:

• A suitable Java Development Environment (p. 5).


• An AWS account and access keys. For instructions, see Sign up for AWS and Create an IAM
User (p. 3).
• AWS credentials (access keys) set in your environment, or use the shared credentials file used by
the AWS CLI and other SDKs. For more information, see Set up AWS credentials and region for
development (p. 5).

Downloading the SDK into Your Project


Depending on your build system or IDE, use one of the following methods to download the SDK into
your project by using Apache Maven or Gradle:

• 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.

Compiling the SDK


You can build the AWS SDK for Java using Maven. Maven downloads all necessary dependencies, builds
the SDK, and installs the SDK in one step. See http://maven.apache.org/ for installation instructions and
more information.

To compile the SDK

1. Open AWS SDK for Java 2.x (GitHub).


Note
Version 1.0 of the SDK is also available in GitHub at AWS SDK for Java 1.x (GitHub).

4
AWS SDK for Java version 2 Developer Guide
Installing a Java Development Environment

2. Click the Clone or download button to choose your download option.


3. In a terminal window, navigate to the directory where you downloaded the SDK source.
4. Build and install the SDK by using the following command (Maven required).

mvn clean install

The resulting .jar file is built into the target directory.


5. (Optional) Build the API Reference documentation using the following command.

mvn javadoc:javadoc

The documentation is built into the target/site/apidocs/ directories of each service.

Installing a Java Development Environment


The AWS SDK for Java requires 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/.

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.

Set up AWS credentials and region for


development
To connect to any of the supported services with the AWS SDK for Java, you must provide AWS
credentials. The AWS SDKs and CLIs use provider chains to look for AWS credentials in several different
places, including system/user environment variables and local AWS configuration files.

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.

Set AWS credentials


You can set your credentials for use by the AWS SDK for Java in several ways. However, these are the
recommended approaches:

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

This file should contain lines in the following format:

[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.

To set these variables on Linux, macOS, or Unix, use export :

export AWS_ACCESS_KEY_ID=your_access_key_id
export AWS_SECRET_ACCESS_KEY=your_secret_access_key

To set these variables on Windows, use set :

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

Refresh IMDS credentials


The AWS SDK for Java supports opt-in refreshing IMDS credentials in the background every 1 minute,
regardless of the credential expiration time. This allows you to refresh credentials more frequently and
reduces the chance that not reaching IMDS impacts the perceived AWS availability.

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

Set the AWS region


You should set a default AWS Region to use for accessing AWS services with the AWS SDK for Java. For
the best network performance, choose a region that’s geographically close to you (or to your customers).
Note
If you don’t select a region, service calls that require a region will fail.

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

This file should contain lines in the following format:

[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.

On Linux, macOS, or Unix, use export :

export AWS_REGION=your_aws_region

On Windows, use set :

set AWS_REGION=your_aws_region

Where your_aws_region is the desired AWS Region name.

For information about selecting a region, see AWS Region Selection (p. 16).

Use the SDK with Apache Maven


You can use Apache Maven to configure and build AWS SDK for Java projects, or to build the SDK itself.

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

Create a Maven project


To create a Maven project from the command line, open a terminal or command prompt window, enter
or paste the following command, and then press Enter or Return.

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.

Configure the Java compiler for Maven


If you created your project using the AWS Lambda project archetype as described earlier, this is already
done for you.

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>

Declare the SDK as a dependency


To use the AWS SDK for Java in your project, you need to declare it as a dependency in your project’s
pom.xml file.

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.

Set dependencies for SDK modules


Now that you have configured the SDK, you can add dependencies for one or more of the AWS SDK for
Java modules to use in your project.

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

Build the entire SDK into your project


To optimize your application, we strongly recommend that you pull in only the components you need
instead of the entire SDK. However, to build the entire AWS SDK for Java into your project, declare it in
your pom.xml file, as follows.

<project>
<dependencies>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>aws-sdk-java</artifactId>
<version>2.X.X</version>
</dependency>
</dependencies>
</project>

Build your project


After you configure the pom.xml file, you can use Maven to build your 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.

Use the SDK with Gradle


You can use Gradle to configure and build AWS SDK for Java projects.

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

1. Add the BOM to the dependencies section of the file.

...
dependencies {
implementation platform('software.amazon.awssdk:bom:2.X.X')

// Declare individual SDK dependencies without version


...
}

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'

apply plugin: 'java'

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

Using the AWS SDK for Java 2.0


This section provides important general information about programming with the AWS SDK for Java that
applies to all services you might use with the SDK.

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)

Creating Service Clients


To make requests to Amazon Web Services, you first create a service client object. In version 2.x of the
SDK, you can create clients only by using service client builders.

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.

Obtaining a Client Builder


To obtain an instance of the client, use the static factory method builder. Then customize it by using
the setters in the builder, as shown in the following example.

In the AWS SDK for Java 2.0, the setters are named without the with prefix.

DynamoDbClient client = DynamoDbClient.builder()


.region(Region.US_WEST_2)
.credentialsProvider(ProfileCredentialsProvider.builder()
.profileName("myProfile")
.build())
.build();

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.

To create a default client


DynamoDbClient client = DynamoDbClient.create();

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();

Supplying and Retrieving AWS Credentials


To make requests to Amazon Web Services (AWS), you must supply AWS credentials to the AWS SDK for
Java. You can do this by using the following methods:

• Use the default credential provider chain (recommended).


• Use a specific credential provider or provider chain.
• Supply credentials explicitly.

Each of these methods is discussed in the following sections.

Use the Default Credential Provider Chain


When you initialize a new service client without supplying any arguments, the AWS SDK for Java
attempts to find AWS credentials. It uses the default credential provider chain implemented by the
DefaultCredentialsProvider class.

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();

Credential Retrieval Order


You can use a supported credential retrieval technique to retrieve credentials required to perform AWS
operations. For example, the following Java code shows how to create a DynamoDbClient object by
using an EnvironmentVariableCredentialsProvider object.

13
AWS SDK for Java version 2 Developer Guide
Use the Default Credential Provider Chain

Region region = Region.US_WEST_2;


DynamoDbClient ddb = DynamoDbClient.builder()
.region(region)
.credentialsProvider(EnvironmentVariableCredentialsProvider.create())
.build();

The following list shows the supported credential retrieval techniques:

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

Setting an Alternate Credentials Profile


The AWS SDK for Java uses the default profile, but there are ways to customize which profile is sourced
from the credentials file.

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"

In Windows, run the following command.

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.

Setting an Alternate Credentials File Location


The AWS SDK for Java loads AWS credentials automatically from the default credentials file location.
However, you can also specify the location by setting the AWS_CREDENTIAL_PROFILES_FILE
environment variable with the full path to the credentials file.

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.

To override the default credentials file location


• Set the AWS_CREDENTIAL_PROFILES_FILE environment variable to the location of your AWS
credentials file.
• On Linux, macOS, or Unix, use export :

export AWS_CREDENTIAL_PROFILES_FILE=path/to/credentials_file

• On Windows, use set :

set AWS_CREDENTIAL_PROFILES_FILE=path/to/credentials_file

AWS Credentials File Format


When you use the aws configure command to create an AWS credentials file, the command creates a
file with the following format.

[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.

Use a Specific Credential Provider or Provider Chain


You can use a credential provider that is different from the default credential provider chain by using the
client builder.

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.

Supply Credentials Explicitly


If the default credential chain or a specific or custom provider or provider chain doesn’t work for
your code, you can supply the credentials that you want. These can be AWS account credentials, IAM
credentials, or temporary credentials retrieved from AWS Security Token Service (AWS STS). If you’ve
retrieved temporary credentials using AWS STS, use this method to specify the credentials for AWS
access.
Important
For security, we strongly recommend that you use IAM account credentials instead of the AWS
account credentials for AWS access. For more information, see AWS Security Credentials in the
Amazon Web Services General Reference.

To explicitly supply credentials to an AWS client

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:

AwsSessionCredentials awsCreds = AwsSessionCredentials.create(


"your_access_key_id_here",
"your_secret_key_id_here",
"your_session_token_here");

S3Client s32 = S3Client.builder()


.credentialsProvider(StaticCredentialsProvider.create(awsCreds))
.build();

AWS Region Selection


Regions enable you to access AWS services that physically reside in a specific geographic area. This can
be useful both for redundancy and to keep your data and applications running close to where you and
your users will access them.

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.

Ec2Client ec2 = Ec2Client.builder()


.region(Region.US_WEST_2)
.build();

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.

Region newRegion = Region.of("us-east-42");


Ec2Client ec2 = Ec2Client.builder()
.region(newRegion)
.build();

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.

Choosing a Specific Endpoint


Each AWS client can be configured to use a specific endpoint within a region by calling the
endpointOverride method.

For example, to configure the Amazon EC2 client to use the Europe (Ireland) Region, use the following
code.

Ec2Client ec2 = Ec2Client.builder()


.region(Region.EU_WEST_1)
.endpointOverride(URI.create("https://ec2.eu-
west-1.amazonaws.com"))
.build();

See Regions and Endpoints for the current list of regions and their corresponding endpoints for all AWS
services.

Automatically Determine the AWS Region from the


Environment
When running on Amazon EC2 or AWS Lambda, you might want to configure clients to use the same
region that your code is running on. This decouples your code from the environment it’s running in and
makes it easier to deploy your application to multiple regions for lower latency or redundancy.

To use the default credential/region provider chain to determine the region from the environment, use
the client builder’s create method.

Ec2Client ec2 = Ec2Client.create();

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

Default Region Provider Chain


The following is the region lookup process:

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.

Checking for Service Availability in an AWS Region


To see if a particular AWS service is available in a region, use the serviceMetadata and region
method on the service that you’d like to check.

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)

HTTP transport configuration


You can use the NettyNioAsyncHttpClient for asynchronous clients or the ApacheHttpClient for
synchronous clients to set HTTP transport settings. For a full list of options you can set with these
clients, see the AWS SDK for Java API Reference version 2.x.

18
AWS SDK for Java version 2 Developer Guide
HTTP transport configuration

Note
For more information about Apache HTTPClient, see HttpClient Overview.

Add a dependency on the netty-nio-client in your POM to use the NettyNioAsyncHttpClient.

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.

• Default for maxConcurrency: 50


• Default for maxPendingConnectionAcquires: 10_000

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

KinesisAsyncClient client = KinesisAsyncClient.builder()


.httpClientBuilder(NettyNioAsyncHttpClient.builder()
.maxConcurrency(100)

.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

SdkAsyncHttpClient httpClient = NettyNioAsyncHttpClient.builder()


.maxConcurrency(100)
.maxPendingConnectionAcquires(10_000)
.build();

KinesisAsyncClient kinesisClient = KinesisAsyncClient.builder()


.httpClient(httpClient)

19
AWS SDK for Java version 2 Developer Guide
Optimize cold start performance for AWS Lambda

.build();

httpClient.close();

Optimize cold start performance for AWS Lambda


Among the improvements in the AWS SDK for Java 2.0 is the SDK cold startup time for Java functions in
Lambda. This is the time it takes for a Java Lambda function to start up and respond to its first request.

Version 2.x includes three primary changes that contribute to this improvement:

• Use of jackson-jr, which is a serialization library that improves initialization time.


• Use of the java.time libraries for date and time objects.
• Use of Slf4j for a logging facade.

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.

Example client configuration


S3Client client = S3Client.builder()
.region(Region.US_WEST_2)
.credentialsProvider(EnvironmentVariableCredentialsProvider.create())
.httpClient(UrlConnectionHttpClient.builder().build())
.build();

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

public class DynamoDBAsyncListTables {

public static void main(String[] args) throws InterruptedException {

// Create the DynamoDbAsyncClient object


Region region = Region.US_EAST_1;
DynamoDbAsyncClient client = DynamoDbAsyncClient.builder()
.region(region)
.build();

listTables(client);
}

public static void listTables(DynamoDbAsyncClient 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);

// When future is complete (either successfully or in error) handle the response


tableNames.whenComplete((tables, err) -> {
try {
if (tables != null) {
tables.forEach(System.out::println);
} else {
// Handle error
err.printStackTrace();
}
} finally {

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

ic static void getItem(DynamoDbAsyncClient client, String tableName, String key, String


keyVal) {

HashMap<String, AttributeValue> keyToGet =


new HashMap<String, AttributeValue>();

keyToGet.put(key, AttributeValue.builder()
.s(keyVal).build());

try {

// Create a GetItemRequest instance


GetItemRequest request = GetItemRequest.builder()
.key(keyToGet)
.tableName(tableName)
.build();

// Invoke the DynamoDbAsyncClient object's getItem


java.util.Collection<software.amazon.awssdk.services.dynamodb.model.AttributeValue>
returnedItem = client.getItem(request).join().item().values();

// Convert Set to Map


Map<String, AttributeValue> map =
returnedItem.stream().collect(Collectors.toMap(AttributeValue::s, s->s));
Set<String> keys = map.keySet();
for (String sinKey : keys) {
System.out.format("%s: %s\n", sinKey, map.get(sinKey).toString());
}

} catch (DynamoDbException e) {
System.err.println(e.getMessage());
System.exit(1);
}

See the complete example on GitHub.

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

public class S3AsyncOps {

public static void main(String[] args) {

final String USAGE = "\n" +


"Usage:\n" +
" S3AsyncOps <bucketname> <objectname> <path>\n\n" +
"Where:\n" +
" bucketname - the name of the bucket (i.e., bucket1)\n\n" +
" objectname - the name of the object (i.e., book.pdf)\n" +
" path - the local path to the file (i.e., C:\\AWS\\book.pdf)\n" +
"Example:\n" +
" bucket1 book.pdf C:\\AWS\\book.pdf\n";

if (args.length < 3) {
System.out.println(USAGE);
System.exit(1);
}

String bucketName = args[0];


String key = args[1];
String path = args[2];

Region region = Region.US_WEST_2;


S3AsyncClient client = S3AsyncClient.builder()
.region(region)
.build();

PutObjectRequest objectRequest = PutObjectRequest.builder()


.bucket(bucketName)
.key(key)
.build();

// Put the object into the bucket


CompletableFuture<PutObjectResponse> future = client.putObject(objectRequest,
AsyncRequestBody.fromFile(Paths.get(path))
);
future.whenComplete((resp, err) -> {
try {
if (resp != null) {
System.out.println("Object uploaded. Details: " + resp);
} else {

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

public class S3AsyncStreamOps {

public static void main(String[] args) {

final String USAGE = "\n" +


"Usage:\n" +
" S3AsyncOps <bucketname> <objectname> <path>\n\n" +
"Where:\n" +
" bucketname - the name of the bucket (i.e., bucket1)\n\n" +
" objectname - the name of the object (i.e., book.pdf)\n" +
" path - the local path where the file is written (i.e., C:\\AWS\
\book.pdf)\n" +
"Example:\n" +
" bucket1 book.pdf C:\\AWS\\book.pdf\n";

if (args.length < 3) {
System.out.println(USAGE);
System.exit(1);
}

String bucketName = args[0];


String objectKey = args[1];
String path = args[2];

Region region = Region.US_WEST_2;


S3AsyncClient client = S3AsyncClient.builder()
.region(region)
.build();

// Create a GetObjectRequest instance


GetObjectRequest objectRequest = GetObjectRequest.builder()
.bucket(bucketName)
.key(objectKey)
.build();

24
AWS SDK for Java version 2 Developer Guide
Advanced Operations

CompletableFuture<GetObjectResponse> futureGet = client.getObject(objectRequest,


AsyncResponseTransformer.toFile(Paths.get(path)));

futureGet.whenComplete((resp, err) -> {


try {
if (resp != null) {
System.out.println("Object downloaded. Details: " + resp);
} else {
// Handle error
err.printStackTrace();
}
} finally {
// Lets the application shut down. Only close the client when you are
completely done with it
client.close();
}
});
futureGet.join();
}
}

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

S3AsyncClient clientThread = S3AsyncClient.builder()


.asyncConfiguration(
b -> b.advancedOption(SdkAdvancedAsyncClientOption
.FUTURE_COMPLETION_EXECUTOR,
Executors.newFixedThreadPool(10)
)
)
.build();

To optimize performance, you can manage your own thread pool executor, and include it when
configuring your client.

ThreadPoolExecutor executor = new ThreadPoolExecutor(50, 50,


10, TimeUnit.SECONDS,
new LinkedBlockingQueue<>(10_000),
new ThreadFactoryBuilder()
.threadNamePrefix("sdk-async-response").build());

// Allow idle core threads to time out


executor.allowCoreThreadTimeOut(true);

S3AsyncClient clientThread = S3AsyncClient.builder()


.asyncConfiguration(
b -> b.advancedOption(SdkAdvancedAsyncClientOption

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.

S3AsyncClient clientThread = S3AsyncClient.builder()


.asyncConfiguration(
b -> b.advancedOption(SdkAdvancedAsyncClientOption
.FUTURE_COMPLETION_EXECUTOR,
Runnable::run
)
)
.build();

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:

• Sign up for AWS and create an IAM user


• Set up AWS credentials and region for development
• Configure your project dependencies (for example, in your pom.xml or build.gradle file) to use
version 2.14.0 or later of the AWS SDK for Java.

To enabling publishing of metrics to CloudWatch, also include the artifactId cloudwatch-metric-


publisher with the version number 2.14.0 or later in your project’s dependencies.

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.

How to enable metrics collection


You can enable metrics in your application for a service client or on individual requests.

Enable metrics for a specific request


The following code snippet shows how to enable the CloudWatch metrics publisher for a request to
Amazon DynamoDB. It uses the default metrics publisher configuration.

MetricPublisher metricsPub = CloudWatchMetricPublisher.create();


DynamoDbClient ddb = DynamoDbClient.create();
ddb.listTables(ListTablesRequest.builder()
.overrideConfiguration(c -> c.addMetricPublisher(metricsPub))
.build());

Enable metrics for a specific service client


The following code snippet shows how to enable the CloudWatch metrics publisher for a service client.

MetricPublisher metricsPub = CloudWatchMetricPublisher.create();

DynamoDbClient ddb = DynamoDbClient.builder()


.overrideConfiguration(c -> c.addMetricPublisher(metricsPub))
.build();

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.

MetricPublisher metricsPub = CloudWatchMetricPublisher.builder()

.credentialsProvider(EnvironmentVariableCredentialsProvider.create("cloudwatch"))
.region(Region.US_WEST_2)
.publishFrequency(5, TimeUnit.MINUTES)
.build();

Region region = Region.US_EAST_1;


DynamoDbClient ddb = DynamoDbClient.builder()
.region(region)
.overrideConfiguration(c -> c.addMetricPublisher(metricsPub))
.build();

What information is collected?


Metrics collection includes the following:

27
AWS SDK for Java version 2 Developer Guide
Service client metrics

• Number of API requests, including whether they succeed or fail


• Information about the AWS services you call in your API requests, including exceptions returned
• The duration for various operations such as Marshalling, Signing, and HTTP requests
• HTTP client metrics, such as the number of open connections, the number of pending requests, and
the name of the HTTP client used

Note
The metrics available vary by HTTP client.

For a complete list, see Service client metrics (p. 28).

How can I use this information?


You can use the metrics the SDK collects to monitor the service clients in your application. You can look
at overall usage trends, identify anomalies, review service client exceptions returned, or to dig in to
understand a particular issue. Using Amazon CloudWatch, you can also create alarms to notify you as
soon as your application reaches a condition that you define.

For more information, see Using Amazon CloudWatch Metrics and Using Amazon CloudWatch Alarms in
the Amazon CloudWatch User Guide.

Service client metrics


With the AWS SDK for Java version 2 (v2), you can collect metrics about the service clients in your
application and then publish (output) those metrics to CloudWatch.

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

Metrics collected with each request

Metric name Description Type Collected by default?

ServiceId Service ID of the AWS String Yes


service that the API
request is made against

OperationName The name of the AWS String Yes


API the request is made
to

ApiCallSuccessful True if the API call was Boolean Yes


successful; false if not

RetryCount Number of times the Integer Yes


SDK retried the API call

ApiCallDuration The total time taken Duration Yes


to finish a request
(inclusive of all retries)

MarshallingDuration The time taken to Duration Yes


marshall the request

28
AWS SDK for Java version 2 Developer Guide
Service client metrics

Metric name Description Type Collected by default?

CredentialsFetchDuration The time taken to fetch Duration Yes


signing credentials for
the request

Metrics collected for each request attempt


Each API call that your application makes may take multiple attempts before responded with a success or
failure. These metrics are collected for each attempt.

Metric name Description Type Collected by default?

BackoffDelayDuration The duration of time Duration Yes


the SDK waited before
this API call attempt

MarshallingDuration The time it takes Duration Yes


to marshall an SDK
request to an HTTP
request

SigningDuration The time it takes to sign Duration Yes


the HTTP request

ServiceCallDuration The time it takes to Duration Yes


connect to the service,
send the request, and
receive the HTTP status
code and header from
the response

UnmarshallingDuration The time it takes to Duration Yes


unmarshall an HTTP
response to an SDK
response

AwsRequestId The request ID of the String Yes


service request

AwsExtendedRequestId The extended request String Yes


ID of the service request

HttpClientName The name of the HTTP String Yes


being use for the
request

MaxConcurrency The max number of Integer Yes


concurrent requests
supported by the HTTP
client

AvailableConcurrency The number of Integer Yes


remaining concurrent
requests that can be
supported by the HTTP
client without needing

29
AWS SDK for Java version 2 Developer Guide
Waiters

Metric name Description Type Collected by default?


to establish another
connection

LeasedConcurrency The number of request Integer Yes


currently being
executed by the HTTP
client

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

HttpStatusCode The status code Integer Yes


returned with the HTTP
response

LocalStreamWindowSize The local HTTP/2 Integer Yes


window size in bytes
this request’s stream

RemoteStreamWindowSizeThe remote HTTP/2 Integer Yes


window size in bytes
this request’s stream

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:

• Sign up for AWS and Create an IAM User (p. 3)


• Set up AWS credentials and region for development (p. 5)
• Configure your project dependencies (for example, in your pom.xml or build.gradle file) to use
version 2.15.0 or later of the AWS SDK for Java.

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.

DynamoDbClient dynamo = DynamoDbClient.create();


DynamoDbWaiter waiter = dynamo.waiter();

WaiterResponse<DescribeTableResponse> waiterResponse =
waiter.waitUntilTableExists(r -> r.tableName("myTable"));

// print out the matched response with a tableStatus of ACTIVE


waiterResponse.matched().response().ifPresent(System.out::println);

Asynchronous programming
The following code snippet shows how to wait for a DynamoDB table to no longer exist.

DynamoDbAsyncClient asyncDynamo = DynamoDbAsyncClient.create();


DynamoDbAsyncWaiter asyncWaiter = asyncDynamo.waiter();

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();

Override configuration for a specific request


The following code snippet shows how to override the configuration for a waiter on a per-request basis.
Note that only some operations have customizable configurations.

waiter.waitUntilTableNotExists(b -> b.tableName("myTable"),


o -> o.maxAttempts(10));

asyncWaiter.waitUntilTableExists(b -> b.tableName("myTable"),


o -> o.waitTimeout(Duration.ofMinutes(1)));

HTTP/2 Programming
HTTP/2 is a major revision of the HTTP protocol. This new version has several enhancements to improve
performance:

• Binary data encoding provides more efficient data transfer.


• Header compression reduces the overhead bytes downloaded by the client, helping get the content to
the client sooner. This is especially useful for mobile clients that are already constrained on bandwidth.
• Bidirectional asynchronous communication (multiplexing) allows multiple requests and response
messages between the client and AWS to be in flight at the same time over a single connection,
instead of over multiple connections, which improves 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.

Why Unchecked Exceptions?


The AWS SDK for Java uses runtime (or unchecked) exceptions instead of checked exceptions for these
reasons:

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.

SdkServiceException (and Subclasses)


SdkServiceException is the most common exception that you’ll experience when using the AWS SDK
for Java. This exception represents an error response from an AWS service. For example, if you try to
terminate an Amazon EC2 instance that doesn’t exist, EC2 will return an error response and all the details
of that error response will be included in the SdkServiceException that’s thrown. For some cases, a
subclass of SdkServiceException is thrown to allow developers fine-grained control over handling
error cases through catch blocks.

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.

SdkServiceException provides you with information such as:

• Returned HTTP status code


• Returned AWS error code
• Detailed error message from the service
• AWS request ID for the failed request

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.

Logging AWS SDK for Java Calls


The AWS SDK for Java is instrumented with Slf4j, which is an abstraction layer that enables the use of
any one of several logging systems at runtime.

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.

To learn more about Log4j, see the Apache website.

Add the Log4J JAR


To use Log4j with the SDK, you need to download the Log4j JAR from the Log4j website or use Maven by
adding a dependency on Log4j in your pom.xml file. The SDK doesn’t include the JAR.

33
AWS SDK for Java version 2 Developer Guide
Log4j Configuration file

Log4j Configuration file


Log4j uses a configuration file, log4j2.xml. Example configuration files are shown below. To learn more
about the values used in the configuration file, see the manual for Log4j configuration.

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

Setting the Classpath


Both the Log4j JAR and the log4j2.xml file must be located on your classpath. To configure the log4j
binding for Sl4j in Maven you can add the following to your pom.xml:

<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.

Service-Specific Errors and Warnings


We recommend that you always leave the “software.amazon.awssdk” logger hierarchy set to “WARN” to
catch any important messages from the client libraries. For example, if the Amazon S3 client detects that
your application hasn’t properly closed an InputStream and could be leaking resources, the S3 client
reports it through a warning message to the logs. This also ensures that messages are logged if the client
has any problems handling requests or responses.

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>

Request/Response Summary Logging


Every request to an AWS service generates a unique AWS request ID that is useful if you run into an issue
with how an AWS service is handling a request. AWS request IDs are accessible programmatically through
Exception objects in the SDK for any failed service call, and can also be reported through the DEBUG log
level in the “software.amazon.awssdk.request” logger.

The following log4j2.xml file enables a summary of requests and responses.

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

Here is an example of the log output:

2018-01-28 19:31:56 [main] DEBUG software.amazon.awssdk.request:Logger.java:78 - Sending


Request: software.amazon.awssdk.http.DefaultSdkHttpFullRequest@3a80515c

Verbose Wire Logging


In some cases, it can be useful to see the exact requests and responses that the AWS SDK for Java sends
and receives. If you really need access to this information, you can temporarily enable it through the
Apache HttpClient logger. Enabling the DEBUG level on the apache.http.wire logger enables logging
for all request and response data.
Warning
We recommend you only use wire logging for debugging purposes. Disable it in your production
environments because it can log sensitive data. It logs the full request or response without
encryption, even for an HTTPS call. For large requests (e.g., to upload a file to Amazon S3) or
responses, verbose wire logging can also significantly impact your application’s performance.

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>

Setting the JVM TTL for DNS Name Lookups


The Java virtual machine (JVM) caches DNS name lookups. When the JVM resolves a hostname to an IP
address, it caches the IP address for a specified period of time, known as the time-to-live (TTL).

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.

How to Set the JVM TTL


To modify the JVM’s TTL, set the networkaddress.cache.ttl property value. Use one of the following
methods, depending on your needs:

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

Configure IAM Roles for Amazon EC2 (Advanced)


All requests to AWS services must be cryptographically signed using credentials issued by AWS. You can
use IAM roles to conveniently grant secure access to AWS resources from your Amazon EC2 instances.

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.

Default Provider Chain and Amazon EC2 Instance


Profiles
If your application creates an AWS client using the create method, the client searches for credentials
using the default credentials provider chain, in the following order:

1. In the Java system properties: aws.accessKeyId and aws.secretAccessKey.


2. In system environment variables: AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY.
3. In the default credentials file (the location of this file varies by platform).
4. In the Amazon ECS environment variable: AWS_CONTAINER_CREDENTIALS_RELATIVE_URI.
5. In the instance profile credentials, which exist within the instance metadata associated with the IAM
role for the EC2 instance.

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.

Walkthrough: Using IAM roles for Amazon EC2


Instances
This walkthrough shows you how to retrieve an object from Amazon S3 using an IAM role to manage
access.

Create an IAM Role


Create an IAM role that grants read-only access to Amazon S3.

To create the IAM role

1. Open the IAM console.

37
AWS SDK for Java version 2 Developer Guide
Walkthrough: Using IAM roles for Amazon EC2 Instances

2. In the navigation pane, choose Roles, then Create New Role.


3. On the Select Role Type page, under AWS Service Roles, choose Amazon EC2.
4. On the Attach Policy page, choose Amazon S3 Read Only Access from the policy list, then choose
Next Step.
5. Enter a name for the role, then select Next Step. Remember this name

because you’ll need it when you launch your Amazon EC2 instance.
6. On the Review page, choose Create Role.

Launch an EC2 Instance and Specify Your IAM Role


You can launch an Amazon EC2 instance with an IAM role using the Amazon EC2 console.

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

AWS SDK for Java 2.0 Code


Examples
This section provides programming examples using the AWS SDK for Java 2.0 that applies to specific use
cases.

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)

CloudWatch examples using the AWS SDK for Java


This section provides examples of programming CloudWatch by using the AWS SDK for Java 2.0.

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

• Work with CloudWatch alarms (p. 42)


• Use alarm actions in CloudWatch (p. 45)
• Send events to CloudWatch (p. 46)

Get metrics from CloudWatch


Listing metrics
To list CloudWatch metrics, create a ListMetricsRequest and call the CloudWatchClient’s listMetrics
method. You can use the ListMetricsRequest to filter the returned metrics by namespace, metric
name, or dimensions.
Note
A list of metrics and dimensions that are posted by AWS services can be found within the
Amazon CloudWatch Metrics and Dimensions Reference in the Amazon CloudWatch User Guide.

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

public static void listMets( CloudWatchClient cw, String namespace) {

boolean done = false;


String nextToken = null;

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);
}

for (Metric metric : response.metrics()) {


System.out.printf(
"Retrieved metric %s", metric.metricName());
System.out.println();
}

if(response.nextToken() == null) {
done = true;
} else {
nextToken = response.nextToken();

40
AWS SDK for Java version 2 Developer Guide
Publish custom metric data

}
}

The metrics are returned in a ListMetricsResponse by calling its getMetrics method.

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.

See the complete example on GitHub.

More information
• ListMetrics in the Amazon CloudWatch API Reference.

Publish custom metric data


A number of AWS services publish their own metrics in namespaces beginning with “AWS/” You can also
publish custom metric data using your own namespace (as long as it doesn’t begin with “AWS/”).

Publish custom metric data


To publish your own metric data, call the CloudWatchClient’s putMetricData method with a
PutMetricDataRequest. The PutMetricDataRequest must include the custom namespace to use for
the data, and information about the data point itself in a MetricDatum object.
Note
You cannot specify a namespace that begins with “AWS/”. Namespaces that begin with “AWS/”
are reserved for use by Amazon Web Services products.

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

public static void putMetData(CloudWatchClient cw, Double dataPoint ) {

try {
Dimension dimension = Dimension.builder()
.name("UNIQUE_PAGES")
.value("URLS").build();

MetricDatum datum = MetricDatum.builder()


.metricName("PAGES_VISITED")
.unit(StandardUnit.NONE)
.value(dataPoint)
.dimensions(dimension).build();

PutMetricDataRequest request = PutMetricDataRequest.builder()

41
AWS SDK for Java version 2 Developer Guide
Work with CloudWatch alarms

.namespace("SITE/TRAFFIC")
.metricData(datum).build();

PutMetricDataResponse response = cw.putMetricData(request);

} catch (CloudWatchException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
System.out.printf("Successfully put data point %f", dataPoint);

See the complete example on GitHub.

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.

Work with CloudWatch alarms


Create an alarm
To create an alarm based on a CloudWatch metric, call the CloudWatchClient’s putMetricAlarm
method with a PutMetricAlarmRequest filled with the alarm conditions.

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

public static void putMetricAlarm(CloudWatchClient cw, String alarmName, String instanceId)


{

try {
Dimension dimension = Dimension.builder()
.name("InstanceId")
.value(instanceId).build();

PutMetricAlarmRequest request = PutMetricAlarmRequest.builder()


.alarmName(alarmName)
.comparisonOperator(
ComparisonOperator.GREATER_THAN_THRESHOLD)
.evaluationPeriods(1)
.metricName("CPUUtilization")
.namespace("AWS/EC2")
.period(60)
.statistic(Statistic.AVERAGE)
.threshold(70.0)

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();

PutMetricAlarmResponse response = cw.putMetricAlarm(request);

} catch (CloudWatchException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}

System.out.printf(
"Successfully created alarm with name %s", alarmName);

See the complete example on GitHub.

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

public static void deleteCWAlarms( CloudWatchClient cw) {

try {

boolean done = false;


String newToken = null;

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);
}

for(MetricAlarm alarm : response.metricAlarms()) {


System.out.printf("\n Retrieved alarm %s", alarm.alarmName());
}

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.

See the complete example on GitHub.

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

public static void deleteCWAlarm(CloudWatchClient cw, String alarmName) {

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);
}

See the complete example on GitHub.

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

Use alarm actions in CloudWatch


Using CloudWatch alarm actions, you can create alarms that perform actions such as automatically
stopping, terminating, rebooting, or recovering Amazon EC2 instances.
Note
Alarm actions can be added to an alarm by using the PutMetricAlarmRequest’s alarmActions
method when creating an alarm (p. 42).

Enable alarm actions


To enable alarm actions for a CloudWatch alarm, call the CloudWatchClient’s enableAlarmActions
with a EnableAlarmActionsRequest containing one or more names of alarms whose actions you want to
enable.

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

public static void enableActions(CloudWatchClient cw, String alarm) {

try {
EnableAlarmActionsRequest request = EnableAlarmActionsRequest.builder()
.alarmNames(alarm).build();

EnableAlarmActionsResponse response = cw.enableAlarmActions(request);

} catch (CloudWatchException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}

See the complete example on GitHub.

Disable alarm actions


To disable alarm actions for a CloudWatch alarm, call the CloudWatchClient’s disableAlarmActions
with a DisableAlarmActionsRequest containing one or more names of alarms whose actions you want to
disable.

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

public static void disableActions(CloudWatchClient cw, String alarmName) {

45
AWS SDK for Java version 2 Developer Guide
Send events to CloudWatch

try {
DisableAlarmActionsRequest request = DisableAlarmActionsRequest.builder()
.alarmNames(alarmName).build();

DisableAlarmActionsResponse response = cw.disableAlarmActions(request);

} catch (CloudWatchException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}

System.out.printf(
"Successfully disabled actions on alarm %s", alarmName);
}

See the complete example on GitHub.

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

Send events to CloudWatch


CloudWatch Events delivers a near real-time stream of system events that describe changes in AWS
resources to Amazon EC2 instances, Lambda functions, Kinesis streams, Amazon ECS tasks, Step
Functions state machines, Amazon SNS topics, Amazon SQS queues, or built-in targets. You can match
events and route them to one or more target functions or streams by using simple rules.

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

public static void putCWEvents(CloudWatchEventsClient cwe, String resourceArn ) {

try {

46
AWS SDK for Java version 2 Developer Guide
Send events to CloudWatch

final String EVENT_DETAILS =


"{ \"key1\": \"value1\", \"key2\": \"value2\" }";

PutEventsRequestEntry requestEntry = PutEventsRequestEntry.builder()


.detail(EVENT_DETAILS)
.detailType("sampleSubmitted")
.resources(resourceArn)
.source("aws-sdk-java-cloudwatch-example").build();

PutEventsRequest request = PutEventsRequest.builder()


.entries(requestEntry).build();

PutEventsResponse response = cwe.putEvents(request);

} catch (CloudWatchException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}

See the complete example on GitHub.

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

public static void putCWRule(CloudWatchEventsClient cwe, String ruleName, String roleArn) {

PutRuleResponse response = null;

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());
}

See the complete example on GitHub.

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.

To add a target to a rule, call the CloudWatchEventsClient’s putTargets method with a


PutTargetsRequest containing the rule to update and a list of targets to add to the rule.

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

public static void putCWTargets(CloudWatchEventsClient cwe, String ruleName, String


functionArn, String targetId ) {

Target target = Target.builder()


.arn(functionArn)
.id(targetId)
.build();

PutTargetsRequest request = PutTargetsRequest.builder()


.targets(target)
.rule(ruleName)
.build();

PutTargetsResponse response = cwe.putTargets(request);

See the complete example on GitHub.

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

Amazon Cognito examples


With Amazon Cognito, you can quickly add user sign-up or sign-in capability to your web or mobile app.
The examples here demonstrate some of the basic functionality of Cognito.

Create a user pool


A user pool is a directory of users that you can configure for your web or mobile app.

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

public static String createPool(CognitoIdentityProviderClient cognitoclient,String


userPoolName ) {

try {
CreateUserPoolResponse repsonse = cognitoclient.createUserPool(
CreateUserPoolRequest.builder()
.poolName(userPoolName)
.build()
);
return repsonse.userPool().id();

} catch (CognitoIdentityProviderException e){


System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
return "";

See the complete example on GitHub.

List users from a user pool


To list users from your user pools, start by building a ListUserPoolsRequest object, with the number
of maximum results as the value of its maxResults(). Call the listUserPools() method of your
CognitoIdentityProviderClient, passing in the ListUserPoolsRequest object. You can capture
the result of this request as a ListUserPoolsResponse object, as demonstrated in the following code
snippet. Create a UserPoolDescriptionType object to easily iterate over the results and pull out the
attributes of each user.

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

public static void listAllUserPools(CognitoIdentityProviderClient cognitoclient ) {

try {
ListUserPoolsResponse response = cognitoclient
.listUserPools(
ListUserPoolsRequest.builder()
.maxResults(10)
.build()
);

for (UserPoolDescriptionType userpool : response.userPools()) {


System.out.println("User pool " + userpool.name() + ", User ID " + userpool.id()
+ ", Status " + userpool.status());
}
} catch (CognitoIdentityProviderException e){
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}

See the complete example on GitHub.

Create an identity pool


An identity pool is a container that organizes the IDs from your external identity provider,
keeping a unique identifier for each user. To create an identity pool, start by building a
CreateIdentityPoolRequest with the name of the user pool as the value of its identityPoolName().
Set allowUnauthenticatedIdentities() to true or false. Call the createIdentityPool()
method of your CognitoIdentityClient object, passing in the CreateIdentityPoolRequest
object. You can capture the result of this request as a CreateIdentityPoolResponse object, as
demonstrated in the following code snippet.

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

public static String createIdPool(CognitoIdentityClient cognitoclient, String


identityPoolName ) {

try {
CreateIdentityPoolResponse response = cognitoclient.createIdentityPool(
CreateIdentityPoolRequest.builder()
.allowUnauthenticatedIdentities(false)
.identityPoolName(identityPoolName)
.build()
);

return response.identityPoolId();

} catch (CognitoIdentityProviderException e){


System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
return "";

50
AWS SDK for Java version 2 Developer Guide
Add an app client

See the complete example on GitHub.

Add an app client


To enable the hosted web sign-up or sign-in UI for your app, create an app client. To create an app client,
start by building a CreateUserPoolClientRequest object, with the name of the client as the value of its
clientName(). Set userPoolId() to the ID of the user pool to which you want to attach this app
client. Call the createUserPoolClient() method of your CognitoIdentityProviderClient,
passing in the CreateUserPoolClientRequest object. You can capture the result of this request as a
CreateUserPoolClientResponse 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.CreateUserPoolClientRequest;
import
software.amazon.awssdk.services.cognitoidentityprovider.model.CreateUserPoolClientResponse;

Code

public static void createPoolClient ( CognitoIdentityProviderClient cognitoclient,


String clientName,
String userPoolId ) {

try {

CreateUserPoolClientResponse repsonse = cognitoclient.createUserPoolClient(


CreateUserPoolClientRequest.builder()
.clientName(clientName)
.userPoolId(userPoolId)
.build()
);

System.out.println("User pool " + repsonse.userPoolClient().clientName() + "


created. ID: " + repsonse.userPoolClient().clientId());

} catch (CognitoIdentityProviderException e){


System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}

See the complete example on GitHub.

Add a third-party identity provider


Adding an external identity provider (IdP) enables your users to log into your app using that
service’s login mechanism. To add a third-party IdP, start by building an UpdateIdentityPoolRequest
object, with the name of the identity pool as the value of its identityPoolName(). Set
allowUnauthenticatedIdentities() to true or false, specify the identityPoolId(),
and define which login providers will be supported with supportedLoginProviders().
Call the updateIdentityPool() method of your CognitoIdentityClient, passing in
the UpdateIdentityPoolRequest object. You can capture the result of this request as an
UpdateIdentityPoolResponse object, as demonstrated in the following code snippet.

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

public static void createAdmin(CognitoIdentityProviderClient cognitoclient,


String userPoolId,
String name,
String email){

try{
AdminCreateUserResponse response = cognitoclient.adminCreateUser(
AdminCreateUserRequest.builder()
.userPoolId(userPoolId)
.username(name)
.userAttributes(AttributeType.builder()
.name("email")
.value(email)
.build())
.messageAction("SUPPRESS")
.build()
);

System.out.println("User " + response.user().username() + "is created. Status: " +


response.user().userStatus());

} catch (CognitoIdentityProviderException e){


System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}

See the complete example on GitHub.

Get credentials for an ID


To get the credentials for an identity in an identity pool, first build a GetCredentialsForIdentityRequest
with the identity ID as the value of its identityId(). Call the getCredentialsForIdentity()
method of your CognitoIdentityClient, passing in the GetCredentialsForIdentityRequest.
You can capture the result of this request as a GetCredentialsForIdentityResponse object, as
demonstrated in the following code snippet.

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

public static void getCredsForIdentity(CognitoIdentityClient cognitoclient, String


identityId) {

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);
}

See the complete example on GitHub.

For more information, see the Amazon Cognito Developer Guide.

DynamoDB Examples Using the AWS SDK for Java


This section provides examples that show you how to program DynamoDB by using the AWS SDK for
Java 2.0.

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)

Work with tables in DynamoDB


Tables are the containers for all items in a DynamoDB database. Before you can add or remove data from
DynamoDB, you must create a table.

For each table, you must define:

• A table name that is unique for your account and region.


• A primary key for which every value must be unique; no two items in your table can have the same
primary key value.

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;

Create a table with a simple primary key


This code creates a table with a simple primary key (“Name”).

Code

public static String createTable(DynamoDbClient ddb, String tableName, String key) {

// Create a waiter object


DynamoDbWaiter dbWaiter = ddb.waiter();

// Create the CreateTableRequest object


CreateTableRequest request = CreateTableRequest.builder()
.attributeDefinitions(AttributeDefinition.builder()
.attributeName(key)
.attributeType(ScalarAttributeType.S)
.build())
.keySchema(KeySchemaElement.builder()
.attributeName(key)
.keyType(KeyType.HASH)
.build())
.provisionedThroughput(ProvisionedThroughput.builder()
.readCapacityUnits(new Long(10))
.writeCapacityUnits(new Long(10))

54
AWS SDK for Java version 2 Developer Guide
Work with tables in DynamoDB

.build())
.tableName(tableName)
.build();

String newTable ="";


try {
CreateTableResponse response = ddb.createTable(request);

// Create a DescribeTableRequest object required for waiter functionality


DescribeTableRequest tableRequest = DescribeTableRequest.builder()
.tableName(tableName)
.build();

// Wait until the table is created


WaiterResponse<DescribeTableResponse> waiterResponse =
dbWaiter.waitUntilTableExists(r -> r.tableName(tableName));

// print out the matched response with a tableStatus of ACTIVE


waiterResponse.matched().response().ifPresent(System.out::println);

newTable = response.tableDescription().tableName();
return newTable;
} catch (DynamoDbException e) {
System.err.println(e.getMessage());
System.exit(1);
}
return "";
}

See the complete example on GitHub.

Create a table with a composite primary key


Add another AttributeDefinition and KeySchemaElement to CreateTableRequest.

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

public static String createTableComKey(DynamoDbClient ddb, String tableName) {


CreateTableRequest request = CreateTableRequest.builder()
.attributeDefinitions(
AttributeDefinition.builder()
.attributeName("Language")
.attributeType(ScalarAttributeType.S)
.build(),
AttributeDefinition.builder()
.attributeName("Greeting")
.attributeType(ScalarAttributeType.S)
.build())
.keySchema(

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();

String tableId = "";

try {
CreateTableResponse result = ddb.createTable(request);
tableId = result.tableDescription().tableId();
return tableId;
} catch (DynamoDbException e) {
System.err.println(e.getMessage());
System.exit(1);
}

See the complete example on GitHub.

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

public static void listAllTables(DynamoDbClient ddb){

boolean moreTables = true;


String lastName = null;

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);
}

List<String> tableNames = response.tableNames();

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.

See the complete example on GitHub.

Describe (get information about) a table


Call the DynamoDbClient’s describeTable 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.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

public static void describeDymamoDBTable(DynamoDbClient ddb,String tableName ) {

DescribeTableRequest request = DescribeTableRequest.builder()


.tableName(tableName)
.build();

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");

for (AttributeDefinition a : attributes) {


System.out.format(" %s (%s)\n",
a.attributeName(), a.attributeType());
}
}
} catch (DynamoDbException e) {
System.err.println(e.getMessage());
System.exit(1);
}

See the complete example on GitHub.

Modify (update) a table


You can modify your table’s provisioned throughput values at any time by calling the DynamoDbClient’s
updateTable 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.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

public static void updateDynamoDBTable(DynamoDbClient ddb,


String tableName,
Long readCapacity,
Long writeCapacity) {

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

ProvisionedThroughput tableThroughput = ProvisionedThroughput.builder()


.readCapacityUnits(readCapacity)
.writeCapacityUnits(writeCapacity)
.build();

UpdateTableRequest request = UpdateTableRequest.builder()


.provisionedThroughput(tableThroughput)
.tableName(tableName)
.build();

try {
ddb.updateTable(request);
} catch (DynamoDbException e) {
System.err.println(e.getMessage());
System.exit(1);
}

See the complete example on GitHub.

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

public static void deleteDynamoDBTable(DynamoDbClient ddb, String tableName) {

DeleteTableRequest request = DeleteTableRequest.builder()


.tableName(tableName)
.build();

try {
ddb.deleteTable(request);

} catch (DynamoDbException e) {
System.err.println(e.getMessage());
System.exit(1);
}

See the complete example on GitHub.

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

• Working with Tables in DynamoDB in the Amazon DynamoDB Developer Guide

Work with items in DynamoDB


In DynamoDB, an item is a collection of attributes, each of which has a name and a value. An attribute
value can be a scalar, set, or document type. For more information, see Naming Rules and Data Types in
the Amazon DynamoDB Developer Guide.

Retrieve (get) an item from a table


Call the DynamoDbClient’s getItem method and pass it a GetItemRequest object with the table
name and primary key value of the item you want. It returns a GetItemResponse object with all of the
attributes for that item. You can specify one or more projection expressions in the GetItemRequest to
retrieve specific attributes.

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

public static void getDynamoDBItem(DynamoDbClient ddb,String tableName,String key,String


keyVal ) {

HashMap<String,AttributeValue> keyToGet = new HashMap<String,AttributeValue>();

keyToGet.put(key, AttributeValue.builder()
.s(keyVal).build());

// Create a GetItemRequest object


GetItemRequest request = GetItemRequest.builder()
.key(keyToGet)
.tableName(tableName)
.build();

try {
Map<String,AttributeValue> returnedItem = ddb.getItem(request).item();

if (returnedItem != null) {
Set<String> keys = returnedItem.keySet();
System.out.println("Table Attributes: \n");

for (String key1 : keys) {


System.out.format("%s: %s\n", key1, returnedItem.get(key1).toString());
}
} else {
System.out.format("No item found with the key %s!\n", key);
}
} catch (DynamoDbException e) {
System.err.println(e.getMessage());

60
AWS SDK for Java version 2 Developer Guide
Work with items in DynamoDB

System.exit(1);
}

See the complete example on GitHub.

Retrieve (get) an item from a table 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.

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

ic static void getItem(DynamoDbAsyncClient client, String tableName, String key, String


keyVal) {

HashMap<String, AttributeValue> keyToGet =


new HashMap<String, AttributeValue>();

keyToGet.put(key, AttributeValue.builder()
.s(keyVal).build());

try {

// Create a GetItemRequest instance


GetItemRequest request = GetItemRequest.builder()
.key(keyToGet)
.tableName(tableName)
.build();

// Invoke the DynamoDbAsyncClient object's getItem


java.util.Collection<software.amazon.awssdk.services.dynamodb.model.AttributeValue>
returnedItem = client.getItem(request).join().item().values();

// Convert Set to Map


Map<String, AttributeValue> map =
returnedItem.stream().collect(Collectors.toMap(AttributeValue::s, s->s));
Set<String> keys = map.keySet();
for (String sinKey : keys) {
System.out.format("%s: %s\n", sinKey, map.get(sinKey).toString());
}

} 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

See the complete example on GitHub.

Add a new item to a table


Create a Map of key-value pairs that represent the item’s attributes. These must include values for the
table’s primary key fields. If the item identified by the primary key already exists, its fields are updated by
the request.
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.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;
import java.util.HashMap;

Code

public static void putItemInTable(DynamoDbClient ddb,


String tableName,
String key,
String keyVal,
String albumTitle,
String albumTitleValue,
String awards,
String awardVal,
String songTitle,
String songTitleVal){

HashMap<String,AttributeValue> itemValues = new HashMap<String,AttributeValue>();

// Add all content to the table


itemValues.put(key, AttributeValue.builder().s(keyVal).build());
itemValues.put(songTitle, AttributeValue.builder().s(songTitleVal).build());
itemValues.put(albumTitle, AttributeValue.builder().s(albumTitleValue).build());
itemValues.put(awards, AttributeValue.builder().s(awardVal).build());

// Create a PutItemRequest object


PutItemRequest request = PutItemRequest.builder()
.tableName(tableName)
.item(itemValues)
.build();

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

See the complete example on GitHub.

Update an existing item in a table


You can update an attribute for an item that already exists in a table by using the DynamoDbClient’s
updateItem method, providing a table name, primary key value, and a map of fields to update.
Note
If the named table doesn’t exist for your account and region, or if the item identified by the
primary key you passed in doesn’t exist, 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.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

public static void updateTableItem(DynamoDbClient ddb,


String tableName,
String key,
String keyVal,
String name,
String updateVal){

HashMap<String,AttributeValue> itemKey = new HashMap<String,AttributeValue>();

itemKey.put(key, AttributeValue.builder().s(keyVal).build());

HashMap<String,AttributeValueUpdate> updatedValues =
new HashMap<String,AttributeValueUpdate>();

// Update the column specified by name with updatedVal


updatedValues.put(name, AttributeValueUpdate.builder()
.value(AttributeValue.builder().s(updateVal).build())
.action(AttributeAction.PUT)
.build());

UpdateItemRequest request = UpdateItemRequest.builder()


.tableName(tableName)
.key(itemKey)
.attributeUpdates(updatedValues)
.build();

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);
}

See the complete example on GitHub.

63
AWS SDK for Java version 2 Developer Guide
Map items in DynamoDB tables

Delete an existing item in a table


You can delete an item that exists in a table by using the DynamoDbClient’s deleteItem method and
providing a table name as well as the primary key value.
Note
If the named table doesn’t exist for your account and region, or if the item identified by the
primary key you passed in doesn’t exist, a ResourceNotFoundException is thrown.

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

public static void deleteDymamoDBItem(DynamoDbClient ddb, String tableName, String key,


String keyVal) {

HashMap<String,AttributeValue> keyToGet =
new HashMap<String,AttributeValue>();

keyToGet.put(key, AttributeValue.builder()
.s(keyVal)
.build());

DeleteItemRequest deleteReq = DeleteItemRequest.builder()


.tableName(tableName)
.key(keyToGet)
.build();

try {
ddb.deleteItem(deleteReq);
} catch (DynamoDbException e) {
System.err.println(e.getMessage());
System.exit(1);
}

See the complete example on GitHub.

More information
• Guidelines for Working with Items in the Amazon DynamoDB Developer Guide
• Working with Items in DynamoDB in the Amazon DynamoDB Developer Guide

Map items in DynamoDB tables


The Amazon DynamoDB enhanced client is a high-level library that is part of the AWS SDK for Java
version 2 (v2). It offers a straightforward way to map client-side classes to DynamoDB tables. You
define the relationships between tables and their corresponding model classes in your code. Then you
can intuitively perform various create, read, update, or delete (CRUD) operations on tables or items in
DynamoDB.

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.

Region region = Region.US_EAST_1;


DynamoDbClient ddb = DynamoDbClient.builder()
.region(region)
.build();

DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder()


.dynamoDbClient(ddb)
.build();

createDynamoDBTable(enhancedClient);

Create a table using the enhanced client


To easily create a TableSchema using the enhanced client, start by creating a Java data class that
includes a default public constructor and standardized names of getters and setters for each property in
the class. Include a class-level annotation to indicate it is a DynamoDbBean and, at a minimum, include a
DynamoDbPartitionKey annotation on the getter or setter for the primary key of the table record.

Once this data class has been defined, call TableSchema’s fromBean() with that data class to create the
table schema.

See the code snippet below for an example of how to do this.

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

// Put an item into a DynamoDB table


public static void putRecord(DynamoDbEnhancedClient enhancedClient) {

try {
// Create a DynamoDbTable object
DynamoDbTable<Customer> custTable = enhancedClient.table("Customer",
TableSchema.fromBean(Customer.class));

// Create an Instant object


LocalDate localDate = LocalDate.parse("2020-04-07");
LocalDateTime localDateTime = localDate.atStartOfDay();

65
AWS SDK for Java version 2 Developer Guide
Map items in DynamoDB tables

Instant instant = localDateTime.toInstant(ZoneOffset.UTC);

// Populate the table


Customer custRecord = new Customer();
custRecord.setCustName("Susan Blue");
custRecord.setId("id103");
custRecord.setEmail("[email protected]");
custRecord.setRegistrationDate(instant) ;

// Put the customer data into a DynamoDB table


custTable.putItem(custRecord);

} catch (DynamoDbException e) {
System.err.println(e.getMessage());
System.exit(1);
}
System.out.println("done");
}

// Create the Customer table


@DynamoDbBean
public static class Customer {

private String id;


private String name;
private String email;
private Instant regDate;

@DynamoDbPartitionKey
public String getId() {
return this.id;
};

public void setId(String id) {

this.id = id;
}

@DynamoDbSortKey
public String getCustName() {
return this.name;

public void setCustName(String name) {

this.name = name;
}

public String getEmail() {


return this.email;
}

public void setEmail(String email) {

this.email = email;
}

public Instant getRegistrationDate() {


return regDate;
}
public void setRegistrationDate(Instant registrationDate) {

this.regDate = registrationDate;
}

66
AWS SDK for Java version 2 Developer Guide
Map items in DynamoDB tables

See the complete example on GitHub.

Retrieve (get) an item from a table


To get an item from a DynamoDB table, create a DynamoDbTable object and call getItem() with a
GetItemEnhancedRequest object to get the actual item.

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

public static String getItem(DynamoDbEnhancedClient enhancedClient) {


try {
// Create a DynamoDbTable object
DynamoDbTable<Customer> mappedTable = enhancedClient.table("Customer",
TableSchema.fromBean(Customer.class));

// Create a KEY object


Key key = Key.builder()
.partitionValue("id110")
.build();

// Get the item by using the key


Customer result = mappedTable.getItem(r->r.key(key));
return "The record id is "+result.getId();

} catch (DynamoDbException e) {
System.err.println(e.getMessage());
System.exit(1);
}

See the complete example on GitHub.

Batch create (put) and delete items


You can batch a series of put requests (PutItemEnhancedRequest) and delete requests
(DeleteItemEnhancedRequest) to one or more tables, and then send all of the changes in a single
request.

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

public static void putBatchRecords(DynamoDbEnhancedClient enhancedClient) {


try {

// Create a DynamoDbTable object


DynamoDbTable<Customer> mappedTable = enhancedClient.table("Customer",
TableSchema.fromBean(Customer.class));

// Create an Instant object


LocalDate localDate = LocalDate.parse("2020-04-07");
LocalDateTime localDateTime = localDate.atStartOfDay();
Instant instant = localDateTime.toInstant(ZoneOffset.UTC);

// Populate the table


Customer record2 = new Customer();
record2.setCustName("Fred Pink");
record2.setId("id110");
record2.setEmail("[email protected]");
record2.setRegistrationDate(instant) ;

Customer record3 = new Customer();


record3.setCustName("Susan Pink");
record3.setId("id120");
record3.setEmail("[email protected]");
record3.setRegistrationDate(instant) ;

// Create a BatchWriteItemEnhancedRequest object


BatchWriteItemEnhancedRequest batchWriteItemEnhancedRequest =
BatchWriteItemEnhancedRequest.builder()
.writeBatches(
WriteBatch.builder(Customer.class)
.mappedTableResource(mappedTable)
.addPutItem(r -> r.item(record2))
.addPutItem(r -> r.item(record3))
.build())
.build();

// Add these two items to the table


enhancedClient.batchWriteItem(batchWriteItemEnhancedRequest);
System.out.println("done");

} 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

// Create the Customer table


@DynamoDbBean
public static class Customer {

private String id;


private String name;
private String email;
private Instant regDate;

@DynamoDbPartitionKey
public String getId() {
return this.id;
};

public void setId(String id) {

this.id = id;
}

@DynamoDbSortKey
public String getCustName() {
return this.name;
}

public void setCustName(String name) {


this.name = name;
}

public String getEmail() {


return this.email;
}

public void setEmail(String email) {


this.email = email;
}

public Instant getRegistrationDate() {


return regDate;
}
public void setRegistrationDate(Instant registrationDate) {

this.regDate = registrationDate;
}
}

See the complete example on GitHub.

Use a filtered query to get items from a table


You can get items from a table based on filterable queries, and then perform operations (for example,
return item values) on one or more of the items in the query results.

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

public static void queryTableFilter(DynamoDbEnhancedClient enhancedClient) {

try{
// Create a DynamoDbTable object
DynamoDbTable<EnhancedQueryRecords.Customer> mappedTable =
enhancedClient.table("Customer",
TableSchema.fromBean(EnhancedQueryRecords.Customer.class));

// Get the row where email is [email protected]


AttributeValue att = AttributeValue.builder()
.s("[email protected]")
.build();

Map<String, AttributeValue> expressionValues = new HashMap<>();


expressionValues.put(":value", att);

Expression expression = Expression.builder()


.expression("email = :value")
.expressionValues(expressionValues)
.build();

// Create a QueryConditional object that's used in the query operation


QueryConditional queryConditional = QueryConditional
.keyEqualTo(Key.builder().partitionValue("id103")
.build());

// 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()) {

EnhancedQueryRecords.Customer rec = results.next();


System.out.println("The record id is "+rec.getId());
}

} catch (DynamoDbException e) {
System.err.println(e.getMessage());
System.exit(1);
}
System.out.println("Done");

See the complete example on GitHub.

70
AWS SDK for Java version 2 Developer Guide
Amazon EC2 Examples

Retrieve (get) all items from a table


When you want to get all of the records in a given DynamoDB table, use the scan() method of your
DynamoDbTable object and the items() method to create a set of results against which you can
execute various item operations. For example, the following code snippet prints out the ID value of each
item in the Record table.

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

public static void scan( DynamoDbEnhancedClient enhancedClient) {

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()) {

Customer rec = results.next();


System.out.println("The record id is "+rec.getId());
}

} catch (DynamoDbException e) {
System.err.println(e.getMessage());
System.exit(1);
}
System.out.println("Done");
}

See the complete example on GitHub.

For more information, see Working with items in DynamoDB in the Amazon DynamoDB Developer Guide.

Amazon EC2 Examples Using the AWS SDK for


Java
This section provides examples of programming Amazon EC2 that use the AWS SDK for Java 2.0.

Topics
• Manage Amazon EC2 instances (p. 72)

71
AWS SDK for Java version 2 Developer Guide
Manage Amazon EC2 instances

• Use elastic IP addresses in Amazon EC2 (p. 76)


• Use regions and availability zones (p. 79)
• Work with Amazon EC2 key pairs (p. 81)
• Work with security groups in Amazon EC2 (p. 82)

Manage Amazon EC2 instances


Create an instance
Create a new Amazon EC2 instance by calling the Ec2Client’s runInstances method, providing it with a
RunInstancesRequest containing the Amazon Machine Image (AMI) to use and an instance type.

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

public static String createEC2Instance(Ec2Client ec2,String name, String amiId ) {

RunInstancesRequest runRequest = RunInstancesRequest.builder()


.imageId(amiId)
.instanceType(InstanceType.T1_MICRO)
.maxCount(1)
.minCount(1)
.build();

RunInstancesResponse response = ec2.runInstances(runRequest);


String instanceId = response.instances().get(0).instanceId();

Tag tag = Tag.builder()


.key("Name")
.value(name)
.build();

CreateTagsRequest tagRequest = CreateTagsRequest.builder()


.resources(instanceId)
.tags(tag)
.build();

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

See the complete example on GitHub.

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

public static void startInstance(Ec2Client ec2, String instanceId) {

StartInstancesRequest request = StartInstancesRequest.builder()


.instanceIds(instanceId)
.build();

ec2.startInstances(request);

See the complete example on GitHub.

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

public static void stopInstance(Ec2Client ec2, String instanceId) {

StopInstancesRequest request = StopInstancesRequest.builder()


.instanceIds(instanceId)
.build();

ec2.stopInstances(request);

See the complete example on GitHub.

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

public static void rebootEC2Instance(Ec2Client ec2, String instanceId) {

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);
}

See the complete example on GitHub.

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

public static void describeEC2Instances( Ec2Client ec2){

boolean done = false;


String nextToken = null;

try {

do {
DescribeInstancesRequest request =
DescribeInstancesRequest.builder().maxResults(6).nextToken(nextToken).build();
DescribeInstancesResponse response = ec2.describeInstances(request);

for (Reservation reservation : response.reservations()) {

74
AWS SDK for Java version 2 Developer Guide
Manage Amazon EC2 instances

for (Instance instance : reservation.instances()) {


System.out.printf(
"Found Reservation with id %s, " +
"AMI %s, " +
"type %s, " +
"state %s " +
"and monitoring state %s",
instance.instanceId(),
instance.imageId(),
instance.instanceType(),
instance.state().name(),
instance.monitoring().state());
System.out.println("");
}
}
nextToken = response.nextToken();
} while (nextToken != null);

} 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.

See the complete example on GitHub.

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

MonitorInstancesRequest request = MonitorInstancesRequest.builder()


.instanceIds(instanceId).build();

ec2.monitorInstances(request);

See the complete example on GitHub.

Stop instance monitoring


To stop monitoring an instance, create an UnmonitorInstancesRequest with the ID of the instance to stop
monitoring, and pass it to the Ec2Client’s unmonitorInstances method.

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

UnmonitorInstancesRequest request = UnmonitorInstancesRequest.builder()


.instanceIds(instanceId).build();

ec2.unmonitorInstances(request);

See the complete example on GitHub.

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

Use elastic IP addresses in Amazon EC2


Allocate an elastic IP address
To use an Elastic IP address, you first allocate one to your account, and then associate it with your
instance or a network interface.

To allocate an Elastic IP address, call the Ec2Client’s allocateAddress method with an


AllocateAddressRequest object containing the network type (classic EC2 or VPC).

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

public static String getAllocateAddress( Ec2Client ec2, String instanceId) {

try {
AllocateAddressRequest allocateRequest = AllocateAddressRequest.builder()
.domain(DomainType.VPC)
.build();

AllocateAddressResponse allocateResponse =
ec2.allocateAddress(allocateRequest);

String allocationId = allocateResponse.allocationId();

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 "";

See the complete example on GitHub.

Describe elastic IP addresses


To list the Elastic IP addresses assigned to your account, call the Ec2Client’s describeAddresses
method. It returns a DescribeAddressesResponse which you can use to get a list of Address objects that
represent the Elastic IP addresses on your account.

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

public static void describeEC2Address(Ec2Client ec2 ) {

try {
DescribeAddressesResponse response = ec2.describeAddresses();

for(Address address : response.addresses()) {


System.out.printf(
"Found address with public IP %s, " +
"domain %s, " +
"allocation id %s " +
"and NIC id %s",
address.publicIp(),
address.domain(),
address.allocationId(),
address.networkInterfaceId());

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);
}

See the complete example on GitHub.

Release an elastic IP address


To release an Elastic IP address, call the Ec2Client’s releaseAddress method, passing it a
ReleaseAddressRequest containing the allocation ID of the Elastic IP address you want to release.

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

public static void releaseEC2Address(Ec2Client ec2,String allocId) {

try {
ReleaseAddressRequest request = ReleaseAddressRequest.builder()
.allocationId(allocId).build();

ReleaseAddressResponse response = ec2.releaseAddress(request);

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

See the complete example on GitHub.

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

• ReleaseAddress in the Amazon EC2 API Reference

Use regions and availability zones


Describe regions
To list the Regions available to your account, call the Ec2Client’s describeRegions method. It returns a
DescribeRegionsResponse. Call the returned object’s regions method to get a list of Region objects that
represent each Region.

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 {

DescribeRegionsResponse regionsResponse = ec2.describeRegions();

for(Region region : regionsResponse.regions()) {


System.out.printf(
"Found Region %s " +
"with endpoint %s",
region.regionName(),
region.endpoint());
System.out.println();

See the complete example on GitHub.

Describe availability zones


To list each Availability Zone available to your account, call the Ec2Client’s
describeAvailabilityZones method. It returns a DescribeAvailabilityZonesResponse. Call its
availabilityZones method to get a list of AvailabilityZone objects that represent each Availability
Zone.

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

Create the Ec2Client.

Ec2Client ec2 = Ec2Client.create();

79
AWS SDK for Java version 2 Developer Guide
Use regions and availability zones

Then call describeAvailabilityZones() and retrieve results.

DescribeAvailabilityZonesResponse zonesResponse =
ec2.describeAvailabilityZones();

for(AvailabilityZone zone : zonesResponse.availabilityZones()) {


System.out.printf(
"Found Availability Zone %s " +
"with status %s " +
"in region %s",
zone.zoneName(),
zone.state(),
zone.regionName());
System.out.println();

See the complete example on GitHub.

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 {

DescribeRegionsResponse regionsResponse = ec2.describeRegions();

for(Region region : regionsResponse.regions()) {


System.out.printf(
"Found Region %s " +
"with endpoint %s",
region.regionName(),
region.endpoint());
System.out.println();

See the complete example on GitHub.

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

Work with Amazon EC2 key pairs


Create a key pair
To create a key pair, call the Ec2Client’s createKeyPair method with a CreateKeyPairRequest that
contains the key’s name.

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

public static void createEC2KeyPair(Ec2Client ec2,String keyName ) {

try {
CreateKeyPairRequest request = CreateKeyPairRequest.builder()
.keyName(keyName).build();

CreateKeyPairResponse response = ec2.createKeyPair(request);


System.out.printf(
"Successfully created key pair named %s",
keyName);

} catch (Ec2Exception e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}

See the complete example on GitHub.

Describe key pairs


To list your key pairs or to get information about them, call the Ec2Client’s describeKeyPairs method.
It returns a DescribeKeyPairsResponse that you can use to access the list of key pairs by calling its
keyPairs method, which returns a list of KeyPairInfo objects.

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

public static void describeEC2Keys( Ec2Client ec2){

try {
DescribeKeyPairsResponse response = ec2.describeKeyPairs();

for(KeyPairInfo keyPair : response.keyPairs()) {


System.out.printf(

81
AWS SDK for Java version 2 Developer Guide
Work with security groups in Amazon EC2

"Found key pair with name %s " +


"and fingerprint %s",
keyPair.keyName(),
keyPair.keyFingerprint());
}
} catch (Ec2Exception e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}

See the complete example on GitHub.

Delete a key pair


To delete a key pair, call the Ec2Client’s deleteKeyPair method, passing it a DeleteKeyPairRequest that
contains the name of the key pair to delete.

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

public static void deleteKeys(Ec2Client ec2, String keyPair) {

try {

DeleteKeyPairRequest request = DeleteKeyPairRequest.builder()


.keyName(keyPair)
.build();

DeleteKeyPairResponse response = ec2.deleteKeyPair(request);

See the complete example on GitHub.

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

Work with security groups in Amazon EC2


Create a security group
To create a security group, call the Ec2Client’s createSecurityGroup method with a
CreateSecurityGroupRequest that contains the key’s name.

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

CreateSecurityGroupRequest createRequest = CreateSecurityGroupRequest.builder()


.groupName(groupName)
.description(groupDesc)
.vpcId(vpcId)
.build();

CreateSecurityGroupResponse resp= ec2.createSecurityGroup(createRequest);

See the complete example on GitHub.

Configure a security group


A security group can control both inbound (ingress) and outbound (egress) traffic to your Amazon EC2
instances.

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

First, create an Ec2Client

Region region = Region.US_WEST_2;


Ec2Client ec2 = Ec2Client.builder()
.region(region)
.build();

Then use the Ec2Client’s authorizeSecurityGroupIngress method,

IpRange ipRange = IpRange.builder()


.cidrIp("0.0.0.0/0").build();

83
AWS SDK for Java version 2 Developer Guide
Work with security groups in Amazon EC2

IpPermission ipPerm = IpPermission.builder()


.ipProtocol("tcp")
.toPort(80)
.fromPort(80)
.ipRanges(ipRange)
.build();

IpPermission ipPerm2 = IpPermission.builder()


.ipProtocol("tcp")
.toPort(22)
.fromPort(22)
.ipRanges(ipRange)
.build();

AuthorizeSecurityGroupIngressRequest authRequest =
AuthorizeSecurityGroupIngressRequest.builder()
.groupName(groupName)
.ipPermissions(ipPerm, ipPerm2)
.build();

AuthorizeSecurityGroupIngressResponse authResponse =
ec2.authorizeSecurityGroupIngress(authRequest);

To add an egress rule to the security group, provide similar data in an


AuthorizeSecurityGroupEgressRequest to the Ec2Client’s authorizeSecurityGroupEgress method.

See the complete example on GitHub.

Describe security groups


To describe your security groups or get information about them, call the Ec2Client’s
describeSecurityGroups method. It returns a DescribeSecurityGroupsResponse that you can use
to access the list of security groups by calling its securityGroups method, which returns a list of
SecurityGroup objects.

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

public static void describeEC2SecurityGroups(Ec2Client ec2, String groupId) {

try {
DescribeSecurityGroupsRequest request =
DescribeSecurityGroupsRequest.builder()
.groupIds(groupId).build();

DescribeSecurityGroupsResponse response =
ec2.describeSecurityGroups(request);

for(SecurityGroup group : response.securityGroups()) {


System.out.printf(
"Found Security Group with id %s, " +
"vpc id %s " +
"and description %s",
group.groupId(),

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);
}

See the complete example on GitHub.

Delete a security group


To delete a security group, call the Ec2Client’s deleteSecurityGroup method, passing it a
DeleteSecurityGroupRequest that contains the ID of the security group to delete.

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

public static void deleteEC2SecGroup(Ec2Client ec2,String groupId) {

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);
}

See the complete example on GitHub.

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

IAM Examples Using the AWS SDK for Java


This section provides examples of programming IAM by using the AWS SDK for Java 2.0.

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)

Manage IAM access keys


Create an access key
To create an IAM access key, call the IamClient’s createAccessKey method with a
CreateAccessKeyRequest object.
Note
You must set the region to AWS_GLOBAL for IamClient calls to work because IAM is a global
service.

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

public static String createIAMAccessKey(IamClient iam,String user) {

try {
CreateAccessKeyRequest request = CreateAccessKeyRequest.builder()
.userName(user).build();

CreateAccessKeyResponse response = iam.createAccessKey(request);


String keyId = response.accessKey().accessKeyId();
return keyId;

} catch (IamException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
return "";
}

See the complete example on GitHub.

86
AWS SDK for Java version 2 Developer Guide
Manage IAM access keys

List access keys


To list the access keys for a given user, create a ListAccessKeysRequest object that contains the user name
to list keys for, and pass it to the IamClient’s listAccessKeys method.
Note
If you do not supply a user name to listAccessKeys, it will attempt to list access keys
associated with the AWS account that signed the request.

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

public static void listKeys( IamClient iam,String userName ){

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);
}

for (AccessKeyMetadata metadata :


response.accessKeyMetadata()) {
System.out.format("Retrieved access key %s",
metadata.accessKeyId());
}

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

See the complete example on GitHub.

Retrieve an access key’s last used time


To get the time an access key was last used, call the IamClient’s getAccessKeyLastUsed method with
the access key’s ID (which can be passed in using a GetAccessKeyLastUsedRequest object.

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

public static void getAccessKeyLastUsed(IamClient iam, String accessId ){

try {
GetAccessKeyLastUsedRequest request = GetAccessKeyLastUsedRequest.builder()
.accessKeyId(accessId).build();

GetAccessKeyLastUsedResponse response = iam.getAccessKeyLastUsed(request);

System.out.println("Access key was last used at: " +


response.accessKeyLastUsed().lastUsedDate());

} catch (IamException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
System.out.println("Done");

See the complete example on GitHub.

Activate or deactivate access keys


You can activate or deactivate an access key by creating an UpdateAccessKeyRequest object, providing
the access key ID, optionally the user name, and the desired status, then passing the request object to
the IamClient’s updateAccessKey method.

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);
}

See the complete example on GitHub.

Delete an access key


To permanently delete an access key, call the IamClient’s deleteKey method, providing it with a
DeleteAccessKeyRequest containing the access key’s ID and username.
Note
Once deleted, a key can no longer be retrieved or used. To temporarily deactivate a key so that it
can be activated again later, use updateAccessKey (p. 88) method instead.

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

public static void deleteKey(IamClient iam ,String username, String accessKey ) {

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

See the complete example on GitHub.

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

Managing IAM Users


Creating a User
Create a new IAM user by providing the user name to the IamClient’s createUser method using a
CreateUserRequest object containing the user name.

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

public static String createIAMUser(IamClient iam, String username ) {

try {
// Create an IamWaiter object
IamWaiter iamWaiter = iam.waiter();

CreateUserRequest request = CreateUserRequest.builder()


.userName(username)
.build();

CreateUserResponse response = iam.createUser(request);

// Wait until the user is created


GetUserRequest userRequest = GetUserRequest.builder()
.userName(response.user().userName())
.build();

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 "";
}

See the complete example on GitHub.

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

public static void listAllUsers(IamClient iam ) {

try {

boolean done = false;


String newMarker = null;

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);
}

for(User user : response.users()) {


System.out.format("\n Retrieved user %s", user.userName());
}

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);
}

See the complete example on GitHub.

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

public static void updateIAMUser(IamClient iam, String curName,String newName ) {

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);
}
}

See the complete example on GitHub.

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

public static void deleteIAMUser(IamClient iam, String userName) {

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);
}
}

See the complete example on GitHub.

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

Use IAM account aliases


If you want the URL for your sign-in page to contain your company name or other friendly identifier
instead of your AWS account ID, you can create an alias for your AWS account.
Note
AWS supports exactly one account alias per account.

Create an account alias


To create an account alias, call the IamClient’s createAccountAlias method with a
CreateAccountAliasRequest object that contains the alias name.

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

public static void createIAMAccountAlias(IamClient iam, String alias) {

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);
}
}

See the complete example on GitHub.

List account aliases


To list your account’s alias, if any, call the IamClient’s listAccountAliases method.
Note
The returned ListAccountAliasesResponse supports the same isTruncated and marker
methods as other AWS SDK for Javalist methods, but an AWS account can have only one account
alias.

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

public static void listAliases(IamClient iam) {

try {
ListAccountAliasesResponse response = iam.listAccountAliases();

for (String alias : response.accountAliases()) {


System.out.printf("Retrieved account alias %s", alias);
}

} catch (IamException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}

see the complete example on GitHub.

Delete an account alias


To delete your account’s alias, call the IamClient’s deleteAccountAlias method. When deleting an
account alias, you must supply its name using a DeleteAccountAliasRequest object.

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

public static void deleteIAMAccountAlias(IamClient iam, String alias ) {

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");

See the complete example on GitHub.

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

Work with IAM policies


Create a policy
To create a new policy, provide the policy’s name and a JSON-formatted policy document in a
CreatePolicyRequest to the IamClient’s createPolicy method.

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

public static String createIAMPolicy(IamClient iam, String policyName ) {

try {
// Create an IamWaiter object
IamWaiter iamWaiter = iam.waiter();

CreatePolicyRequest request = CreatePolicyRequest.builder()


.policyName(policyName)
.policyDocument(PolicyDocument).build();

CreatePolicyResponse response = iam.createPolicy(request);

95
AWS SDK for Java version 2 Developer Guide
Work with IAM policies

// Wait until the policy is created


GetPolicyRequest polRequest = GetPolicyRequest.builder()
.policyArn(response.policy().arn())
.build();

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 "" ;
}

See the complete example on GitHub.

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

public static void getIAMPolicy(IamClient iam, String policyArn) {

try {

GetPolicyRequest request = GetPolicyRequest.builder()


.policyArn(policyArn).build();

GetPolicyResponse response = iam.getPolicy(request);


System.out.format("Successfully retrieved policy %s",
response.policy().policyName());

} catch (IamException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
}

See the complete example on GitHub.

Attach a role policy


You can attach a policy to an IAMrole by calling the IamClient’s attachRolePolicy method, providing
it with the role name and policy ARN in an AttachRolePolicyRequest.

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

public static void attachIAMRolePolicy(IamClient iam,String roleName, String policyArn ) {

try {

List<AttachedPolicy> matchingPolicies = new ArrayList<>();

boolean done = false;


String newMarker = null;

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

System.out.println("Successfully attached policy " + policyArn +


" to role " + roleName);

} catch (IamException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}

See the complete example on GitHub.

List attached role policies


List attached policies on a role by calling the IamClient’s listAttachedRolePolicies method. It
takes a ListAttachedRolePoliciesRequest object that contains the role name to list the policies for.

Call getAttachedPolicies on the returned ListAttachedRolePoliciesResponse object to get the


list of attached policies. Results may be truncated; if the ListAttachedRolePoliciesResponse
object’s isTruncated method returns true, call the ListAttachedRolePoliciesResponse
object’s marker method. Use the marker returned to create a new request and use it to call
listAttachedRolePolicies again to get the next batch of results.

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

public static void attachIAMRolePolicy(IamClient iam,String roleName, String policyArn ) {

try {

List<AttachedPolicy> matchingPolicies = new ArrayList<>();

boolean done = false;


String newMarker = null;

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

System.out.println("Successfully attached policy " + policyArn +


" to role " + roleName);

} catch (IamException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}

See the complete example on GitHub.

Detach a role policy


To detach a policy from a role, call the IamClient’s detachRolePolicy method, providing it with the
role name and policy ARN in a DetachRolePolicyRequest.

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

public static void detachPolicy(IamClient iam, String roleName, String policyArn ) {

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

System.out.println("Successfully detached policy " + policyArn +


" from role " + roleName);

} catch (IamException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}

See the complete example on GitHub.

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

Work with IAM server certificates


To enable HTTPS connections to your website or application on AWS, you need an SSL/TLS server
certificate. You can use a server certificate provided by AWS Certificate Manager or one that you obtained
from an external provider.

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.

Get a server certificate


You can retrieve a server certificate by calling the IamClient’s getServerCertificate method, passing
it a GetServerCertificateRequest with the certificate’s name.

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

public static void getCertificate(IamClient iam,String certName ) {

try {
GetServerCertificateRequest request = GetServerCertificateRequest.builder()
.serverCertificateName(certName)
.build();

GetServerCertificateResponse response = iam.getServerCertificate(request);


System.out.format("Successfully retrieved certificate with body %s",
response.serverCertificate().certificateBody());

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);
}
}

See the complete example on GitHub.

List server certificates


To list your server certificates, call the IamClient’s listServerCertificates method with a
ListServerCertificatesRequest. It returns a ListServerCertificatesResponse.

Call the returned ListServerCertificateResponse object’s serverCertificateMetadataList


method to get a list of ServerCertificateMetadata objects that you can use to get information about each
certificate.

Results may be truncated; if the ListServerCertificateResponse object’s isTruncated method


returns true, call the ListServerCertificatesResponse object’s marker method and use the
marker to create a new request. Use the new request to call listServerCertificates again to get
the next batch of results.

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

public static void listCertificates(IamClient iam) {

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);
}

See the complete example on GitHub.

Update a server certificate


You can update a server certificate’s name or path by calling the IamClient’s
updateServerCertificate method. It takes a UpdateServerCertificateRequest object set with the
server certificate’s current name and either a new name or new path to use.

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

public static void updateCertificate(IamClient iam, String curName, String newName) {

try {
UpdateServerCertificateRequest request =
UpdateServerCertificateRequest.builder()
.serverCertificateName(curName)
.newServerCertificateName(newName)
.build();

UpdateServerCertificateResponse response =
iam.updateServerCertificate(request);

System.out.printf("Successfully updated server certificate to name %s",


newName);

} catch (IamException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
}

See the complete example on GitHub.

Delete a server certificate


To delete a server certificate, call the IamClient’s deleteServerCertificate method with a
DeleteServerCertificateRequest containing the certificate’s name.

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

public static void deleteCert(IamClient iam,String certName ) {

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);
}
}

See the complete example on GitHub.

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

Kinesis Examples Using the AWS SDK for Java


This section provides examples of programming Amazon Kinesis using the AWS SDK for Java 2.0.

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)

Subscribing to Amazon Kinesis Data Streams


The following examples show you how to retrieve and process data from Amazon Kinesis Data Streams
using the subscribeToShard method. Kinesis Data Streams now employs the enhanced fanout feature
and a low-latency HTTP/2 data retrieval API, making it easier for developers to run multiple low-latency,
high-performance applications on the same Kinesis Data Stream.

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

Region region = Region.US_EAST_1;


KinesisAsyncClient client = KinesisAsyncClient.builder()
.region(region)
.build();

SubscribeToShardRequest request = SubscribeToShardRequest.builder()


.consumerARN(CONSUMER_ARN)
.shardId("arn:aws:kinesis:us-east-1:814548047983:stream/StockTradeStream")
.startingPosition(s -> s.type(ShardIteratorType.LATEST)).build();

Use the Builder Interface


You can use the builder method to simplify the creation of the SubscribeToShardResponseHandler.

Using the builder, you can set each lifecycle callback with a method call instead of implementing the full
interface.

Code

private static CompletableFuture<Void> responseHandlerBuilder(KinesisAsyncClient client,


SubscribeToShardRequest request) {
SubscribeToShardResponseHandler responseHandler = SubscribeToShardResponseHandler
.builder()
.onError(t -> System.err.println("Error during stream - " + t.getMessage()))
.onComplete(() -> System.out.println("All records stream successfully"))
// Must supply some type of subscriber
.subscriber(e -> System.out.println("Received event - " + e))
.build();
return client.subscribeToShard(request, responseHandler);
}

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

private static CompletableFuture<Void>


responseHandlerBuilderPublisherTransformer(KinesisAsyncClient client,
SubscribeToShardRequest request) {
SubscribeToShardResponseHandler responseHandler = SubscribeToShardResponseHandler
.builder()
.onError(t -> System.err.println("Error during stream - " + t.getMessage()))
.publisherTransformer(p -> p.filter(e -> e instanceof
SubscribeToShardEvent).limit(100))
.subscriber(e -> System.out.println("Received event - " + e))
.build();
return client.subscribeToShard(request, responseHandler);
}

See the complete example on GitHub.

Use a Custom Response Handler


For full control of the subscriber and publisher, implement the SubscribeToShardResponseHandler
interface.

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

private static CompletableFuture<Void> responseHandlerBuilderClassic(KinesisAsyncClient


client, SubscribeToShardRequest request) {
SubscribeToShardResponseHandler responseHandler = new SubscribeToShardResponseHandler()
{

@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

See the complete example on GitHub.

Use the Visitor Interface


You can use a Visitor object to subscribe to specific events you’re interested in watching.

Code

private static CompletableFuture<Void>


responseHandlerBuilderVisitorBuilder(KinesisAsyncClient client, SubscribeToShardRequest
request) {
SubscribeToShardResponseHandler.Visitor visitor =
SubscribeToShardResponseHandler.Visitor
.builder()
.onSubscribeToShardEvent(e -> System.out.println("Received subscribe to shard
event " + e))
.build();
SubscribeToShardResponseHandler responseHandler = SubscribeToShardResponseHandler
.builder()
.onError(t -> System.err.println("Error during stream - " + t.getMessage()))
.subscriber(visitor)
.build();
return client.subscribeToShard(request, responseHandler);
}

See the complete example on GitHub.

Use a Custom Subscriber


You can also implement your own custom subscriber to subscribe to the stream.

This code snippet shows an example subscriber.

Code

private static class MySubscriber implements Subscriber<SubscribeToShardEventStream> {

private Subscription subscription;


private AtomicInteger eventCount = new AtomicInteger(0);

@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

private static CompletableFuture<Void> responseHandlerBuilderSubscriber(KinesisAsyncClient


client, SubscribeToShardRequest request) {
SubscribeToShardResponseHandler responseHandler = SubscribeToShardResponseHandler
.builder()
.onError(t -> System.err.println("Error during stream - " + t.getMessage()))
.subscriber(MySubscriber::new)
.build();
return client.subscribeToShard(request, responseHandler);
}

See the complete example on GitHub.

Write data records into a Kinesis data stream


You can use the KinesisClient object to write data records into a Kinesis data stream by using the
putRecords method. To successfully invoke this method, create a PutRecordsRequest object. You pass
the name of the data steam to the streamName method. Also you must pass the data by using the
putRecords method (as shown in the following code example).

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

private static CompletableFuture<Void> responseHandlerBuilderSubscriber(KinesisAsyncClient


client, SubscribeToShardRequest request) {
SubscribeToShardResponseHandler responseHandler = SubscribeToShardResponseHandler

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);
}

See the complete example on GitHub.

Use a Third-Party Library


You can use other third-party libraries instead of implementing a custom subscriber. This example
demonstrates using the RxJava implementation, but you can use any library that implements the
Reactive Streams interfaces. See the RxJava wiki page on Github for more information on that library.

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

SubscribeToShardResponseHandler responseHandler = SubscribeToShardResponseHandler


.builder()
.onError(t -> System.err.println("Error during stream - " + t.getMessage()))
.onEventStream(p -> Flowable.fromPublisher(p)
.ofType(SubscribeToShardEvent.class)
.flatMapIterable(SubscribeToShardEvent::records)
.limit(1000)
.buffer(25)
.subscribe(e -> System.out.println("Record batch = " + e)))

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

SubscribeToShardResponseHandler responseHandler = SubscribeToShardResponseHandler


.builder()
.onError(t -> System.err.println("Error during stream - " + t.getMessage()))
.publisherTransformer(p -> SdkPublisher.adapt(Flowable.fromPublisher(p).limit(100)))
.build();

See the complete example on GitHub.

More Information
• SubscribeToShardEvent in the Amazon Kinesis API Reference
• SubscribeToShard in the Amazon Kinesis API Reference

AWS Lambda examples for the AWS SDK for Java


This section provides examples of programming Lambda using the AWS SDK for Java 2.0.

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)

Invoke, list, and delete AWS Lambda functions


This section provides examples of programming with the Lambda service client by using the AWS SDK
for Java 2.0.

Topics
• Invoke a Lambda function (p. 109)
• List Lambda functions (p. 110)
• Delete a Lambda function (p. 111)

Invoke a Lambda function


You can invoke a Lambda function by creating a LambdaClient object and invoking its invoke
method. Create an InvokeRequest object to specify additional information such as the function name
and the payload to pass to the Lambda function. Function names appear as arn:aws:lambda:us-
west-2:555556330391:function:HelloFunction. You can retrieve the value by looking at the function in
the AWS Console.

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

The following code example demonstrates how to invoke a Lambda function.

public static void invokeFunction(LambdaClient awsLambda, String functionName) {

InvokeResponse res = null ;


try {
//Need a SdkBytes instance for the payload
SdkBytes payload = SdkBytes.fromUtf8String("{\n" +
" \"Hello \": \"Paris\",\n" +
" \"countryCode\": \"FR\"\n" +
"}" ) ;

//Setup an InvokeRequest
InvokeRequest request = InvokeRequest.builder()
.functionName(functionName)
.payload(payload)
.build();

//Invoke the Lambda function


res = awsLambda.invoke(request);
String value = res.payload().asUtf8String() ;
System.out.println(value);

} catch(LambdaException e) {
System.err.println(e.getMessage());
System.exit(1);
}

See the complete example on GitHub.

List Lambda functions


Build a LambdaClient object and invoke its listFunctions method. This method returns a
ListFunctionsResponse object. You can invoke this object’s functions method to return a list of
FunctionConfiguration objects. You can iterate through the list to retrieve information about the
functions. For example, the following Java code example shows how to get each function name.

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.

public static void listFunctions(LambdaClient awsLambda) {

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();

for (FunctionConfiguration config: list) {


System.out.println("The function name is "+config.functionName());
}

} catch(LambdaException e) {
System.err.println(e.getMessage());
System.exit(1);
}

See the complete example on GitHub.

Delete a Lambda function


Build a LambdaClient object and invoke its deleteFunction method. Create a DeleteFunctionRequest
object and pass it to the deleteFunction method. This object contains information
such as the name of the function to delete. Function names appear as arn:aws:lambda:us-
west-2:555556330391:function:HelloFunction. You can retrieve the value by looking at the function in
the AWS Console.

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

The following Java code demonstrates how to delete a Lambda function.

public static void deleteLambdaFunction(LambdaClient awsLambda, String functionName ) {


try {
//Setup an DeleteFunctionRequest
DeleteFunctionRequest request = DeleteFunctionRequest.builder()
.functionName(functionName)
.build();

//Invoke the Lambda deleteFunction method


awsLambda.deleteFunction(request);
System.out.println("The "+functionName +" function was deleted");

} catch(LambdaException e) {
System.err.println(e.getMessage());
System.exit(1);
}

See the complete example on GitHub.

Amazon Pinpoint examples


You can use Amazon Pinpoint to send relevant, personalized messages to your customers via multiple
communication channels, such as push notifications, SMS, and email.

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.

To create a project, start by building a CreateApplicationRequest object with the name of


the project as the value of its name(). Then build a CreateAppRequest object, passing in the
CreateApplicationRequest object as the value of its createApplicationRequest() method. Call
the createApp() method of your PinpointClient, passing in the CreateAppRequest object. Capture
the result of this request as a CreateAppResponse object, as demonstrated in the following code snippet.

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

public static String createApplication(PinpointClient pinpoint, String appName) {

try {
CreateApplicationRequest appRequest = CreateApplicationRequest.builder()
.name(appName)
.build();

CreateAppRequest request = CreateAppRequest.builder()


.createApplicationRequest(appRequest)
.build();

CreateAppResponse result = pinpoint.createApp(request);

return result.applicationResponse().id();

} catch (PinpointException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
return "";

See the complete example on GitHub.

Create a dynamic segment


A segment is a set of customers who share specific attributes, such as the city they live in or how
frequently they visit your website. A dynamic segment is one that’s based on attributes that you define,
and can change over time.

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

dimensions(). Next, build a CreateSegmentRequest object, passing in the WriteSegmentRequest


object as the value of its writeSegmentRequest(). Finally, call the createSegment() method of
your PinpointClient, passing in the CreateSegmentRequest object. Capture the result of this
request as a CreateSegmentResponse object.

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

public static SegmentResponse createSegment(PinpointClient client, String appId) {

try {
Map<String, AttributeDimension> segmentAttributes = new HashMap<>();
segmentAttributes.put("Team", AttributeDimension.builder()
.attributeType(AttributeType.INCLUSIVE)
.values("Lakers")
.build());

RecencyDimension recencyDimension = RecencyDimension.builder()


.duration("DAY_30")
.recencyType("ACTIVE")
.build();

SegmentBehaviors segmentBehaviors = SegmentBehaviors.builder()


.recency(recencyDimension)
.build();

SegmentDemographics segmentDemographics = SegmentDemographics


.builder()
.build();

SegmentLocation segmentLocation = SegmentLocation


.builder()
.build();

SegmentDimensions dimensions = SegmentDimensions


.builder()
.attributes(segmentAttributes)
.behavior(segmentBehaviors)
.demographic(segmentDemographics)
.location(segmentLocation)
.build();

WriteSegmentRequest writeSegmentRequest = WriteSegmentRequest.builder()


.name("MySegment")
.dimensions(dimensions)

113
AWS SDK for Java version 2 Developer Guide
Import a static segment

.build();

CreateSegmentRequest createSegmentRequest = CreateSegmentRequest.builder()


.applicationId(appId)
.writeSegmentRequest(writeSegmentRequest)
.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;
}

See the complete example on GitHub.

Import a static segment


A static segment is one you create and import from outside of Amazon Pinpoint. The following example
code shows how to create a static segment by importing it from Amazon S3.

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.

Then build a CreateImportJobRequest object, passing in the ImportJobRequest object as the


value of its importJobRequest(), and the ID of your project as the applicationId(). Call the
createImportJob() method of your PinpointClient, passing in the CreateImportJobRequest
object. Capture the result of this request as a CreateImportJobResponse object, as demonstrated in
the following code snippet.

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

public static ImportJobResponse createImportSegment(PinpointClient client,

114
AWS SDK for Java version 2 Developer Guide
List segments for your project

String appId,
String bucket,
String key,
String roleArn) {

try {

// Create the job


ImportJobRequest importRequest = ImportJobRequest.builder()
.defineSegment(true)
.registerEndpoints(true)
.roleArn(roleArn)
.format(Format.JSON)
.s3Url("s3://" + bucket + "/" + key)
.build();

CreateImportJobRequest jobRequest = CreateImportJobRequest.builder()


.importJobRequest(importRequest)
.applicationId(appId)
.build();

CreateImportJobResponse jobResponse = client.createImportJob(jobRequest);

return jobResponse.importJobResponse();

} catch (PinpointException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
return null;
}

See the complete example on GitHub.

List segments for your project


To list the segments associated with a particular project, start by building a GetSegmentsRequest
object, with the ID of the project as the value of its applicationId(). Next, call the getSegments()
method of your PinpointClient, passing in the GetSegmentsRequest object. Capture the result
of this request as a GetSegmentsResponse object. Finally, instantiate a List object upcasted to the
SegmentResponse class. Then call the segmentsResponse().item() of GetSegmentsResponse, as
demonstrated in the following code snippet. From there, you can iterate through the results.

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

public static void listSegs( PinpointClient pinpoint, String appId) {

try {
GetSegmentsRequest request = GetSegmentsRequest.builder()
.applicationId(appId)
.build();

115
AWS SDK for Java version 2 Developer Guide
Create a campaign

GetSegmentsResponse response = pinpoint.getSegments(request);


List<SegmentResponse> segments = response.segmentsResponse().item();

for(SegmentResponse segment: segments) {


System.out.println("Segment " + segment.id() + " " + segment.name() + " " +
segment.lastModifiedDate());
}
} catch ( PinpointException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}

See the complete example on GitHub.

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

public static void createPinCampaign(PinpointClient pinpoint, String appId, String


segmentId) {

CampaignResponse result = createCampaign(pinpoint, appId, segmentId);


System.out.println("Campaign " + result.name() + " created.");
System.out.println(result.description());

116
AWS SDK for Java version 2 Developer Guide
Send a message

public static CampaignResponse createCampaign(PinpointClient client, String appID, String


segmentID) {

try {
Schedule schedule = Schedule.builder()
.startTime("IMMEDIATE")
.build();

Message defaultMessage = Message.builder()


.action(Action.OPEN_APP)
.body("My message body.")
.title("My message title.")
.build();

MessageConfiguration messageConfiguration = MessageConfiguration.builder()


.defaultMessage(defaultMessage)
.build();

WriteCampaignRequest request = WriteCampaignRequest.builder()


.description("My description")
.schedule(schedule)
.name("MyCampaign")
.segmentId(segmentID)
.messageConfiguration(messageConfiguration)
.build();

CreateCampaignResponse result = client.createCampaign(


CreateCampaignRequest.builder()
.applicationId(appID)
.writeCampaignRequest(request).build()
);

System.out.println("Campaign ID: " + result.campaignResponse().id());

return result.campaignResponse();

} catch (PinpointException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}

return null;
}

See the complete example on GitHub.

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

public static void sendSMSMessage(PinpointClient pinpoint, String message) {

try {

Map<String, AddressConfiguration> addressMap =


new HashMap<String, AddressConfiguration>();

AddressConfiguration addConfig = AddressConfiguration.builder()


.channelType(ChannelType.SMS)
.build();

addressMap.put(destinationNumber, addConfig);

SMSMessage smsMessage = SMSMessage.builder()


.body(message)
.messageType(messageType)
.originationNumber(originationNumber)
.senderId(senderId)
.keyword(registeredKeyword)
.build();

// Create a DirectMessageConfiguration object


DirectMessageConfiguration direct = DirectMessageConfiguration.builder()
.smsMessage(smsMessage)
.build();

MessageRequest msgReq = MessageRequest.builder()


.addresses(addressMap)
.messageConfiguration(direct)
.build();

// create a SendMessagesRequest object


SendMessagesRequest request = SendMessagesRequest.builder()
.applicationId(appId)
.messageRequest(msgReq)
.build();

SendMessagesResponse response= pinpoint.sendMessages(request);

MessageResponse msg1 = response.messageResponse();


Map map1 = msg1.result();

//Write out the result of sendMessage


map1.forEach((k, v) -> System.out.println((k + ":" + v)));

} catch (PinpointException e) {

118
AWS SDK for Java version 2 Developer Guide
Amazon S3 Examples

e.getStackTrace();
}

See the complete example on GitHub.

For more information, see the Amazon Pinpoint Developer Guide.

Amazon S3 Examples Using the AWS SDK for Java


This section provides examples of programming Amazon S3 using the AWS SDK for Java 2.0.

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)

Creating, Listing, and Deleting Amazon S3 Buckets


Every object (file) in Amazon S3 must reside within a bucket. A bucket represents a collection (container)
of objects. Each bucket must have a unique key (name). For detailed information about buckets and their
configuration, see Working with Amazon S3 Buckets in the Amazon S3 Developer Guide.
Note
Best Practice
We recommend that you enable the AbortIncompleteMultipartUpload lifecycle rule on your
Amazon S3 buckets.
This rule directs Amazon S3 to abort multipart uploads that don’t complete within a specified
number of days after being initiated. When the set time limit is exceeded, Amazon S3 aborts the
upload and then deletes the incomplete upload data.
For more information, see Lifecycle Configuration for a Bucket with Versioning in the Amazon
S3 User Guide.
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).

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

First create an S3Client.

Region region = Region.US_WEST_2;


S3Client s3 = S3Client.builder().region(region).build();

Make a Create Bucket Request.

Region region = Region.US_WEST_2;


S3Client s3 = S3Client.builder().region(region).build();
String bucket = "bucket" + System.currentTimeMillis();
System.out.println(bucket);

// Create bucket
CreateBucketRequest createBucketRequest = CreateBucketRequest
.builder()
.bucket(bucket)
.createBucketConfiguration(CreateBucketConfiguration.builder()
.locationConstraint(region.id())
.build())
.build();
s3.createBucket(createBucketRequest);

See the complete example on GitHub.

List the Buckets


Build a ListBucketsRequest. Use the S3Client’s listBuckets method to retrieve the list of buckets. If
the request succeeds a ListBucketsResponse is returned. Use this response object to retrieve the list of
buckets.

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

First create an S3Client.

Region region = Region.US_WEST_2;


S3Client s3 = S3Client.builder().region(region).build();

120
AWS SDK for Java version 2 Developer Guide
Bucket Operations

Make a List Buckets Request.

// List buckets
ListBucketsRequest listBucketsRequest = ListBucketsRequest.builder().build();
ListBucketsResponse listBucketsResponse = s3.listBuckets(listBucketsRequest);
listBucketsResponse.buckets().stream().forEach(x -> System.out.println(x.name()));

See the complete example on GitHub.

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)

Delete Objects in a Bucket


Build a ListObjectsV2Request and use the S3Client’s listObjects method to retrieve the list of objects
in the bucket. Then use the deleteObject method on each object to delete it.

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

First create an S3Client.

Region region = Region.US_WEST_2;


S3Client s3 = S3Client.builder().region(region).build();

DeleteBucketRequest deleteBucketRequest =
DeleteBucketRequest.builder().bucket(bucket).build();
s3.deleteBucket(deleteBucketRequest);

See the complete example on GitHub.

Delete an Empty Bucket


Build a DeleteBucketRequest with a bucket name and pass it to the S3Client’s deleteBucket method.

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

First create an S3Client.

DeleteBucketRequest deleteBucketRequest =
DeleteBucketRequest.builder().bucket(bucket).build();
s3.deleteBucket(deleteBucketRequest);

Delete all objects in the bucket.

DeleteBucketRequest deleteBucketRequest =
DeleteBucketRequest.builder().bucket(bucket).build();
s3.deleteBucket(deleteBucketRequest);

See the complete example on GitHub.

Work with Amazon S3 objects


An Amazon S3 object represents a file or collection of data. Every object must be contained in a
bucket (p. 119).
Note
Best Practice
We recommend that you enable the AbortIncompleteMultipartUpload lifecycle rule on your
Amazon S3 buckets.
This rule directs Amazon S3 to abort multipart uploads that don’t complete within a specified
number of days after being initiated. When the set time limit is exceeded, Amazon S3 aborts the
upload and then deletes the incomplete upload data.
For more information, see Lifecycle Configuration for a Bucket with Versioning in the Amazon
S3 User Guide.
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).

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

Region region = Region.US_WEST_2;


s3 = S3Client.builder()
.region(region)
.build();

createBucket(s3, bucket, region);

PutObjectRequest objectRequest = PutObjectRequest.builder()


.bucket(bucket)
.key(key)
.build();

s3.putObject(objectRequest, RequestBody.fromByteBuffer(getRandomByteBuffer(10_000)));

See the complete example on GitHub.

Upload objects in multiple parts


Use the S3Client’s createMultipartUpload method to get an upload ID. Then use the uploadPart
method to upload each part. Finally, use the S3Client’s completeMultipartUpload method to tell
Amazon S3 to merge all the uploaded parts and finish the upload operation.

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

// First create a multipart upload and get the upload id


CreateMultipartUploadRequest createMultipartUploadRequest =
CreateMultipartUploadRequest.builder()
.bucket(bucketName)
.key(key)
.build();

CreateMultipartUploadResponse response =
s3.createMultipartUpload(createMultipartUploadRequest);
String uploadId = response.uploadId();
System.out.println(uploadId);

// Upload all the different parts of the object


UploadPartRequest uploadPartRequest1 = UploadPartRequest.builder()
.bucket(bucketName)
.key(key)
.uploadId(uploadId)
.partNumber(1).build();

String etag1 = s3.uploadPart(uploadPartRequest1,


RequestBody.fromByteBuffer(getRandomByteBuffer(5 * mB))).eTag();

CompletedPart part1 = CompletedPart.builder().partNumber(1).eTag(etag1).build();

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();

// Finally call completeMultipartUpload operation to tell S3 to merge all uploaded


// parts and finish the multipart operation.
CompletedMultipartUpload completedMultipartUpload = CompletedMultipartUpload.builder()
.parts(part1, part2)
.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);

See the complete example on GitHub.

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

GetObjectRequest getObjectRequest = GetObjectRequest.builder()


.bucket(bucket)
.key(key)
.build();

s3.getObject(getObjectRequest);

See the complete example on GitHub.

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

DeleteObjectRequest deleteObjectRequest = DeleteObjectRequest.builder()


.bucket(bucket)
.key(key)
.build();

s3.deleteObject(deleteObjectRequest);

See the complete example on GitHub.

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

String encodedUrl = null;


try {
encodedUrl = URLEncoder.encode(fromBucket + "/" + objectKey,
StandardCharsets.UTF_8.toString());
} catch (UnsupportedEncodingException e) {
System.out.println("URL could not be encoded: " + e.getMessage());
}
CopyObjectRequest copyReq = CopyObjectRequest.builder()
.copySource(encodedUrl)
.bucket(toBucket)
.key(objectKey)
.build();

try {
CopyObjectResponse copyRes = s3.copyObject(copyReq);
return copyRes.copyObjectResult().toString();
} catch (S3Exception e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}

See the complete example on GitHub.

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

public static void listBucketObjects(S3Client s3, String bucketName ) {

try {
ListObjectsRequest listObjects = ListObjectsRequest
.builder()
.bucket(bucketName)
.build();

127
AWS SDK for Java version 2 Developer Guide
Amazon S3 Presigned Examples

ListObjectsResponse res = s3.listObjects(listObjects);


List<S3Object> objects = res.contents();

for (ListIterator iterVals = objects.listIterator(); iterVals.hasNext(); ) {


S3Object myValue = (S3Object) iterVals.next();
System.out.print("\n The name of the key is " + myValue.key());
System.out.print("\n The object is " + calKb(myValue.size()) + " KBs");
System.out.print("\n The owner is " + myValue.owner());
}
} catch (S3Exception e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
}
//convert bytes to kbs
private static long calKb(Long val) {
return val/1024;
}

See the complete example on GitHub.

Working with Amazon S3 Presigned URLs


You can use a S3Presigner object to sign an Amazon S3SdkRequest so that it’s executed without
requiring authentication on the part of the caller. For example, assume Alice has access to an S3 object,
and she wants to temporarily share access to that object with Bob. Alice can generate a pre-signed
GetObjectRequest object to secure share with Bob so that he can download the object without requiring
access to Alice’s credentials.

Topics
• Generate a Presigned URL and Upload an Object (p. 128)
• Get a Presigned Object (p. 130)

Generate a Presigned URL and Upload an Object


Build a S3Presigner object that represents the client object. Next create a PresignedPutObjectRequest
object that can be executed at a later time without requiring additional signing or authentication. When
you create this object, you can specify the bucket name and the key name. In addition, you can also
specify the time in minutes that the bucket can be accessed without using credentials by invoking the
signatureDuration method (as shown in the following code example).

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

The following Java code example uploads content to a presigned S3 bucket.

public static void signBucket(S3Presigner presigner, String bucketName, String keyName)


{

try {

// Use a PutObjectRequest to set additional values


PutObjectRequest objectRequest = PutObjectRequest.builder()
.bucket(bucketName)
.key(keyName)
.contentType("text/plain")
.build();

PutObjectPresignRequest presignRequest = PutObjectPresignRequest.builder()


.signatureDuration(Duration.ofMinutes(10))
.putObjectRequest(objectRequest)
.build();

PresignedPutObjectRequest presignedRequest =
presigner.presignPutObject(presignRequest);

System.out.println("Pre-signed URL to upload a file to: " +


presignedRequest.url());
System.out.println("Which HTTP method needs to be used when uploading a file: "
+
presignedRequest.httpRequest().method());

// Upload content to the bucket by using this URL


URL url = presignedRequest.url();

// 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

See the complete example on GitHub.

Get a Presigned Object


Build a S3Presigner object that represents the client object. Next, create a GetObjectRequest object and
specify the bucket name and key name. In addition, create a GetObjectPresignRequest object that can
be executed at a later time without requiring additional signing or authentication. When you create this
object, you can specify the time in minutes that the bucket can be accessed without using credentials by
invoking the signatureDuration method (as shown in the following code example).

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.

public static void getPresignedUrl( S3Presigner presigner, String bucketName,String


keyName ) {

try {

// Create a GetObjectRequest to be pre-signed


GetObjectRequest getObjectRequest =
GetObjectRequest.builder()
.bucket(bucketName)
.key(keyName)
.build();

// Create a GetObjectPresignRequest to specify the signature duration


GetObjectPresignRequest getObjectPresignRequest =
GetObjectPresignRequest.builder()
.signatureDuration(Duration.ofMinutes(10))
.getObjectRequest(getObjectRequest)
.build();

// Generate the presigned request


PresignedGetObjectRequest presignedGetObjectRequest =
presigner.presignGetObject(getObjectPresignRequest);

// Log the presigned URL


System.out.println("Presigned URL: " + presignedGetObjectRequest.url());

// Create a JDK HttpURLConnection for communicating with S3


HttpURLConnection connection = (HttpURLConnection)
presignedGetObjectRequest.url().openConnection();

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);
}
}

// Download the result of executing the request


try (InputStream content = connection.getInputStream()) {
System.out.println("Service returned response: ");
IoUtils.copy(content, System.out);
}

/*
* 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();
}

See the complete example on GitHub.

Amazon Simple Notification Service examples


With Amazon Simple Notification Service, you can easily push real-time notification messages from your
applications to subscribers over multiple communication channels. This topic describes how to perform
some of the basic functions of SNS.

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

public static String createSNSTopic(SnsClient snsClient, String topicName ) {

CreateTopicResponse result = null;


try {
CreateTopicRequest request = CreateTopicRequest.builder()
.name(topicName)
.build();

result = snsClient.createTopic(request);
return result.topicArn();
} catch (SnsException e) {

System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
return "";

See the complete example on GitHub.

List your SNS topics


To retrieve a list of your existing Amazon SNS topics, build a ListTopicsRequest object. Then, send the
request object to Amazon SNS by using the listTopics() method of the SnsClient. You can capture
the result of this request as a ListTopicsResponse object.

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

public static void listSNSTopics(SnsClient snsClient) {

try {
ListTopicsRequest request = ListTopicsRequest.builder()
.build();

ListTopicsResponse result = snsClient.listTopics(request);


System.out.println("Status was " + result.sdkHttpResponse().statusCode() + "\n
\nTopics\n\n" + result.topics());

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);
}

See the complete example on GitHub.

Subscribe an endpoint to a topic


After you create a topic, you can configure which communication channels will be endpoints for that
topic. Messages are distributed to these endpoints after Amazon SNS receives them.

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

public static void subEmail(SnsClient snsClient, String topicArn, String email) {

try {
SubscribeRequest request = SubscribeRequest.builder()
.protocol("email")
.endpoint(email)
.returnSubscriptionArn(true)
.topicArn(topicArn)
.build();

SubscribeResponse result = snsClient.subscribe(request);


System.out.println("Subscription ARN: " + result.subscriptionArn() + "\n\n Status
was " + result.sdkHttpResponse().statusCode());

} catch (SnsException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}

See the complete example on GitHub.

Publish a message to a topic


After you have a topic and one or more endpoints configured for it, you can publish a message to it.
To start, build a PublishRequest object. Specify the message() to send, and the ARN of the topic
(topicArn()) to send it to. Then, send the request object to Amazon SNS by using the publish()
method of the SnsClient. You can capture the result of this request as a PublishResponse object.

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

public static void pubTopic(SnsClient snsClient, String message, String topicArn) {

try {
PublishRequest request = PublishRequest.builder()
.message(message)
.topicArn(topicArn)
.build();

PublishResponse result = snsClient.publish(request);


System.out.println(result.messageId() + " Message sent. Status was " +
result.sdkHttpResponse().statusCode());

} catch (SnsException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}

See the complete example on GitHub.

Unsubscribe an endpoint from a topic


You can remove the communication channels configured as endpoints for a topic. After doing that, the
topic itself continues to exist and distribute messages to any other endpoints configured for that topic.

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

public static void unSub(SnsClient snsClient, String subscriptionToken) {

try {
UnsubscribeRequest request = UnsubscribeRequest.builder()
.subscriptionArn(subscriptionToken)
.build();

UnsubscribeResponse result = snsClient.unsubscribe(request);

System.out.println("\n\nStatus was " + result.sdkHttpResponse().statusCode()


+ "\n\nSubscription was removed for " + request.subscriptionArn());

134
AWS SDK for Java version 2 Developer Guide
Delete a topic

} catch (SnsException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}

See the complete example on GitHub.

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

public static void deleteSNSTopic(SnsClient snsClient, String topicArn ) {

try {
DeleteTopicRequest request = DeleteTopicRequest.builder()
.topicArn(topicArn)
.build();

DeleteTopicResponse result = snsClient.deleteTopic(request);


System.out.println("\n\nStatus was " + result.sdkHttpResponse().statusCode());

} catch (SnsException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}

See the complete example on GitHub.

For more information, see the Amazon SNS Developer Guide.

Amazon SQS Examples Using the AWS SDK for


Java
This section provides examples of programming Amazon SQS using the AWS SDK for Java 2.0.

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

Work with Amazon SQS message queues


A message queue is the logical container used for sending messages reliably in Amazon SQS. There
are two types of queues: standard and first-in, first-out (FIFO). To learn more about queues and the
differences between these types, see the Amazon SQS Developer Guide.

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

CreateQueueRequest createQueueRequest = CreateQueueRequest.builder()


.queueName(queueName)
.build();

sqsClient.createQueue(createQueueRequest);

See the complete sample on GitHub.

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

String prefix = "que";


ListQueuesRequest listQueuesRequest =
ListQueuesRequest.builder().queueNamePrefix(prefix).build();
ListQueuesResponse listQueuesResponse = sqsClient.listQueues(listQueuesRequest);
for (String url : listQueuesResponse.queueUrls()) {
System.out.println(url);
}

See the complete sample on GitHub.

Get the URL for a queue


Call the SqsClient’s getQueueUrl method. with a GetQueueUrlRequest object.

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;

See the complete sample on GitHub.

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

public static void deleteSQSQueue(SqsClient sqsClient, String queueName) {

try {

GetQueueUrlRequest getQueueRequest = GetQueueUrlRequest.builder()


.queueName(queueName)
.build();

String queueUrl = sqsClient.getQueueUrl(getQueueRequest).queueUrl();

DeleteQueueRequest deleteQueueRequest = DeleteQueueRequest.builder()


.queueUrl(queueUrl)
.build();

sqsClient.deleteQueue(deleteQueueRequest);

} catch (QueueNameExistsException e) {
e.printStackTrace();
System.exit(1);
}

See the complete sample on GitHub.

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

Sending, Receiving, and Deleting Amazon SQS


Messages
A message is a piece of data that can be sent and received by distributed components. Messages are
always delivered using an SQS Queue (p. 136).

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());

Send Multiple Messages in a Request


Send more than one message in a single request by using the SqsClientsendMessageBatch method.
This method takes a SendMessageBatchRequest that contains the queue URL and a list of messages
to send. (Each message is a SendMessageBatchRequestEntry.) You can also delay sending a specific
message by setting a delay value on the message.

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

SendMessageBatchRequest sendMessageBatchRequest = SendMessageBatchRequest.builder()


.queueUrl(queueUrl)
.entries(SendMessageBatchRequestEntry.builder().id("id1").messageBody("Hello from
msg 1").build(),
SendMessageBatchRequestEntry.builder().id("id2").messageBody("msg
2").delaySeconds(10).build())
.build();
sqsClient.sendMessageBatch(sendMessageBatchRequest);

139
AWS SDK for Java version 2 Developer Guide
Message Operations

See the complete sample on GitHub.

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

ReceiveMessageRequest receiveMessageRequest = ReceiveMessageRequest.builder()


.queueUrl(queueUrl)
.maxNumberOfMessages(5)
.build();
List<Message> messages = sqsClient.receiveMessage(receiveMessageRequest).messages();

return messages;

Delete a Message After Receipt


After receiving a message and processing its contents, delete the message from the queue by sending
the message’s receipt handle and queue URL to the SqsClientdeleteMessage method.

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

for (Message message : messages) {

140
AWS SDK for Java version 2 Developer Guide
Amazon Transcribe Examples

DeleteMessageRequest deleteMessageRequest = DeleteMessageRequest.builder()


.queueUrl(queueUrl)
.receiptHandle(message.receiptHandle())
.build();
sqsClient.deleteMessage(deleteMessageRequest);
}

See the complete sample on GitHub.

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

Amazon Transcribe Examples Using the AWS SDK


for Java
This section provides examples of programming Amazon Transcribe using the AWS SDK for Java 2.0.

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)

Working with Amazon Transcribe


The following example shows how bidirectional streaming works using Amazon Transcribe. Bidirectional
streaming implies that there’s both a stream of data going to the service and being received back in real
time. The example uses Amazon Transcribe streaming transcription to send an audio stream and receive
a stream of transcribed text back in real time.

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.

Set up the Microphone


This code uses the javax.sound.sampled package to stream audio from an input device.

Code

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.TargetDataLine;

public class Microphone {

141
AWS SDK for Java version 2 Developer Guide
Working with Amazon Transcribe

public static TargetDataLine get() throws Exception {


AudioFormat format = new AudioFormat(16000, 16, 1, true, false);
DataLine.Info datalineInfo = new DataLine.Info(TargetDataLine.class, format);

TargetDataLine dataLine = (TargetDataLine) AudioSystem.getLine(datalineInfo);


dataLine.open(format);

return dataLine;
}
}

See the complete example on GitHub.

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;

public class AudioStreamPublisher implements Publisher<AudioStream> {


private final InputStream inputStream;

public AudioStreamPublisher(InputStream inputStream) {


this.inputStream = inputStream;
}

@Override
public void subscribe(Subscriber<? super AudioStream> s) {
s.onSubscribe(new SubscriptionImpl(s, inputStream));
}

private class SubscriptionImpl implements Subscription {


private static final int CHUNK_SIZE_IN_BYTES = 1024 * 1;
private ExecutorService executor = Executors.newFixedThreadPool(1);
private AtomicLong demand = new AtomicLong(0);

private final Subscriber<? super AudioStream> subscriber;


private final InputStream inputStream;

private SubscriptionImpl(Subscriber<? super AudioStream> s, InputStream


inputStream) {
this.subscriber = s;
this.inputStream = 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() {

private ByteBuffer getNextEvent() {


ByteBuffer audioBuffer;
byte[] audioBytes = new byte[CHUNK_SIZE_IN_BYTES];

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;
}

private AudioEvent audioEventFromBuffer(ByteBuffer bb) {


return AudioEvent.builder()
.audioChunk(SdkBytes.fromByteBuffer(bb))
.build();
}
}
}

See the complete example on GitHub.

Create the Client and Start the Stream


In the main method, create a request object, start the audio input stream and instantiate the publisher
with the audio input.

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.

Then, use the TranscribeStreamingAsyncClient’s startStreamTranscription method to start the


bidirectional streaming.

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

public static void main(String[] args) throws Exception {


TranscribeStreamingAsyncClient client =
TranscribeStreamingAsyncClient.builder().credentialsProvider(ProfileCredentialsProvider.create()).buil

StartStreamTranscriptionRequest request = StartStreamTranscriptionRequest.builder()

.mediaEncoding(MediaEncoding.PCM)

.languageCode(LanguageCode.EN_US)

.mediaSampleRateHertz(16_000).build();

TargetDataLine mic = Microphone.get();


mic.start();

AudioStreamPublisher publisher = new AudioStreamPublisher(new


AudioInputStream(mic));

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();

client.startStreamTranscription(request, publisher, response).join();


}

See the complete example on GitHub.

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

• Guidelines and Limits in the Amazon Transcribe Developer Guide.

Retrieving Paginated Results


Many AWS operations return paginated results when the response object is too large to return in a single
response. In the AWS SDK for Java 1.0, the response contained a token you had to use to retrieve the
next page of results. New in the AWS SDK for Java 2.0 are autopagination methods that make multiple
service calls to get the next page of results for you automatically. You only have to write code that
processes the results. Additionally both types of methods have synchronous and asynchronous versions.
See Asynchronous Programming (p. 20) for more detail about asynchronous clients.

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.

Iterate over Pages


Build a ListObjectsV2Request and provide a bucket name. Optionally you can provide the maximum
number of keys to retrieve at one time. Pass it to the S3Client’s listObjectsV2Paginator method.
This method returns a ListObjectsV2Iterable object, which is an Iterable of the ListObjectsV2Response
class.

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

ListObjectsV2Request listReq = ListObjectsV2Request.builder()


.bucket(bucket)
.maxKeys(1)
.build();

ListObjectsV2Iterable listRes = s3.listObjectsV2Paginator(listReq);


// Process response pages
listRes.stream()
.flatMap(r -> r.contents().stream())
.forEach(content -> System.out.println(" Key: " + content.key() + " size = " +
content.size()));

See the complete example on GitHub.

Iterate over Objects


The following examples show ways to iterate over the objects returned in the response instead of the
pages of the response.

Use a Stream
Use the stream method on the response content to iterate over the paginated item collection.

Code

// Helper method to work with paginated collection of items directly


listRes.contents().stream()
.forEach(content -> System.out.println(" Key: " + content.key() + " size = " +
content.size()));

See the complete example on GitHub.

Use a For Loop


Use a standard for loop to iterate through the contents of the response.

Code

for (S3Object content : listRes.contents()) {


System.out.println(" Key: " + content.key() + " size = " + content.size());
}

See the complete example on GitHub.

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

ListObjectsV2Request listObjectsReqManual = ListObjectsV2Request.builder()


.bucket(bucket)
.maxKeys(1)
.build();

boolean done = false;


while (!done) {
ListObjectsV2Response listObjResponse = s3.listObjectsV2(listObjectsReqManual);
for (S3Object content : listObjResponse.contents()) {
System.out.println(content.key());
}

if (listObjResponse.nextContinuationToken() == null) {
done = true;
}

listObjectsReqManual = listObjectsReqManual.toBuilder()
.continuationToken(listObjResponse.nextContinuationToken())
.build();
}

See the complete example on GitHub.

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.

Iterate over Pages of Table Names


First, create an asynchronous DynamoDB client. Then, call the listTablesPaginator method to get a
ListTablesPublisher. This is an implementation of the reactive streams Publisher interface. To learn more
about the reactive streams model, see the Reactive Streams Github repo.

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

First create a asyc client

// Creates a default client with credentials and regions loaded from the environment
final DynamoDbAsyncClient asyncClient = DynamoDbAsyncClient.create();

ListTablesRequest listTablesRequest = ListTablesRequest.builder().limit(3).build();

Then use Subscriber to get results.

// Or subscribe method should be called to create a new Subscription.


// A Subscription represents a one-to-one life-cycle of a Subscriber subscribing to a
Publisher.
publisher.subscribe(new Subscriber<ListTablesResponse>() {
// Maintain a reference to the subscription object, which is required to request data
from the publisher
private Subscription subscription;

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

See the complete example on GitHub.

Use a For Loop


Use a for loop to iterate through the pages for simple use cases when creating a new subscriber might
be too much overhead. The response publisher object has a forEach helper method for this purpose.

Code

ListTablesPublisher publisher = asyncClient.listTablesPaginator(listTablesRequest);

// Use a for-loop for simple use cases


CompletableFuture<Void> future = publisher.subscribe(response -> response.tableNames()

.forEach(System.out::println));

148
AWS SDK for Java version 2 Developer Guide
Asynchronous Pagination

See the complete example on GitHub.

Iterate over Table Names


The following examples show ways to iterate over the objects returned in the response instead of the
pages of the response. Similar to the synchronous result, the asynchronous result class has a method to
interact with the underlying item collection. The return type of the convenience method is a publisher
that can be used to request items across all pages.

Use a Subscriber
Code

First create a asyc client

System.out.println("running AutoPagination - iterating on item collection...\n");

// Creates a default client with credentials and regions loaded from the environment
final DynamoDbAsyncClient asyncClient = DynamoDbAsyncClient.create();

ListTablesRequest listTablesRequest = ListTablesRequest.builder().limit(3).build();

Then use Subscriber to get results.

// 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() { }

See the complete example on GitHub.

Use a For Loop


Use the forEach convenience method to iterate through the results.

Code

// Use forEach
CompletableFuture<Void> future = publisher.subscribe(System.out::println);
future.get();

See the complete example on GitHub.

149
AWS SDK for Java version 2 Developer Guide
Asynchronous Pagination

Use Third-party Library


You can use other third party libraries instead of implementing a custom subscriber. This example
demonstrates using the RxJava implementation but any library that implements the reactive stream
interfaces can be used. See the RxJava wiki page on Github for more information on that library.

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

System.out.println("running AutoPagination - using third party subscriber...\n");

DynamoDbAsyncClient asyncClient = DynamoDbAsyncClient.create();


ListTablesPublisher publisher = asyncClient.listTablesPaginator(ListTablesRequest.builder()
.build());

// 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 for this AWS Product or


Service
Cloud security at Amazon Web Services (AWS) is the highest priority. As an AWS customer, you benefit
from a data center and network architecture that is built to meet the requirements of the most
security-sensitive organizations. Security is a shared responsibility between AWS and you. The Shared
Responsibility Model describes this as Security of the Cloud and Security in the Cloud.

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)

Data Protection in this AWS Product or Service


This AWS product or service conforms to the shared responsibility model, which includes regulations
and guidelines for data protection. Amazon Web Services (AWS) is responsible for protecting the
global infrastructure that runs all the AWS services. AWS maintains control over data hosted on this
infrastructure, including the security configuration controls for handling customer content and personal
data. AWS customers and APN partners, acting either as data controllers or data processors, are
responsible for any personal data that they put in the AWS Cloud.

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:

• Use multi-factor authentication (MFA) with each account.


• Use SSL/TLS to communicate with AWS resources. To use a minimum TLS version of 1.2, see Enforcing
TLS 1.2.
• Set up API and user activity logging with AWS CloudTrail.
• Use AWS encryption solutions, along with all default security controls within AWS services.
• Use advanced managed security services such as Amazon Macie, which assists in discovering and
securing personal data that is stored in Amazon S3.

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.

AWS SDK for Java support for TLS 1.2


The following information applies only to Java SSL implementation (the default SSL implementation
in the AWS SDK for Java). If you’re using a different SSL implementation, see your specific SSL
implementation to learn how to enforce TLS versions.

TLS support in Java


TLS 1.2 is supported starting in Java 7.

How to check the TLS version


To check what TLS version is supported in your Java virtual machine (JVM), you can use the following
code.

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.

java app.jar -Djavax.net.debug=ssl

How to set the TLS version


AWS SDK for Java 1.x

• Apache HTTP client: The SDK always prefers TLS 1.2 (if it’s supported in the platform).

AWS SDK for Java 2.x

• 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.

java app.jar -Djdk.tls.client.protocols=TLSv1.2

Or use this code.

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

Identity and Access Management for this AWS


Product or Service
AWS Identity and Access Management (IAM) is an Amazon Web Services (AWS) service that helps
an administrator securely control access to AWS resources. IAM administrators control who can be
authenticated (signed in) and authorized (have permissions) to use resources in AWS services. IAM is an
AWS service that you can use with no additional charge.

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.

Compliance Validation for this AWS Product or


Service
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.

Resilience for this AWS Product or Service


The Amazon Web Services (AWS) global infrastructure is built around AWS Regions and Availability
Zones.

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.

Infrastructure Security for this AWS Product or


Service
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.

This documentation was last built on: Nov 09, 2020

30 September 2020

Added information about waiters


30 May 2020

Added example topics for Amazon Pinpoint, Amazon Cognito, and Amazon SNS
29 May 2020

Added AWS Lambda function performance topic


27 April 2020

Added JVM TTL DNS caching topic


21 April 2020

New Maven and Gradle set up topics


20 April 2020

Added DynamoDB enhanced client topic


19 March 2020

Added TLS 1.2 to security section


2 August 2018

Added Kinesis stream examples


5 April 2018

Added auto pagination topic


29 December 2017

Added example topics for IAM, Amazon EC2, CloudWatch and DynamoDB
7 August 2017

Added getobjects example for Amazon S3


4 August 2017

Added async topic


28 June 2017

AWS SDK for Java version 2 (v2) released

155

You might also like