Professional Documents
Culture Documents
Aws SDK Java DG PDF
Aws SDK Java DG PDF
Developer Guide
Version v1.0.0
AWS SDK for Java Developer Guide
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 Developer Guide
Table of Contents
What is the AWS SDK for Java? ....................................................................................................... 1
About the AWS SDK for Java ................................................................................................... 1
Browse the Source at GitHub .......................................................................................... 1
Developing AWS Applications for Android .......................................................................... 2
What's in this Guide? ............................................................................................................. 2
Viewing the Revision History for the SDK for Java ....................................................................... 2
About Amazon Web Services .................................................................................................. 3
Getting Started ............................................................................................................................. 4
Get an AWS Account and Your AWS Credentials ......................................................................... 4
Install a Java Development Environment .................................................................................... 5
Install the AWS SDK for Java ................................................................................................... 5
Set up your AWS Credentials for Use with the SDK for Java .......................................................... 6
Explore the SDK for Java Code Samples ................................................................................... 7
Where to Go from Here .......................................................................................................... 7
AWS SDK for Java Basics ............................................................................................................... 8
Providing Credentials ............................................................................................................. 8
Using the Default Credential Provider Chain ....................................................................... 9
Specifying a Credential Provider or Provider Chain ............................................................ 10
Explicitly Specifying Credentials ..................................................................................... 10
See Also .................................................................................................................... 11
AWS Region Selection .......................................................................................................... 11
Client Networking Configuration ............................................................................................. 12
Setting the JVM TTL for DNS Name Lookups ........................................................................... 13
Exception Handling .............................................................................................................. 13
Logging ............................................................................................................................. 15
Setting the Classpath ................................................................................................... 15
Service-Specific Errors and Warnings ............................................................................. 15
Request/Response Summary Logging ............................................................................ 16
Verbose Wire Logging .................................................................................................. 16
Access Control Policies ......................................................................................................... 17
Using AWS Services .................................................................................................................... 20
DynamoDB ......................................................................................................................... 20
Manage Tomcat Session State with DynamoDB ................................................................ 20
Amazon EC2 ...................................................................................................................... 23
Starting an Amazon EC2 Instance .................................................................................. 23
Using IAM Roles for EC2 Instances ................................................................................ 29
Tutorial: Amazon EC2 Spot Instances .............................................................................. 36
Tutorial: Advanced Amazon EC2 Spot Request Management .............................................. 45
Amazon SWF ...................................................................................................................... 63
Registering an Amazon SWF Domain ............................................................................. 63
Listing Amazon SWF Domains ....................................................................................... 63
Additional Resources ................................................................................................................... 65
Home Page for the AWS SDK for Java ..................................................................................... 65
SDK Reference Documentation .............................................................................................. 65
AWS Java Developer Blog ..................................................................................................... 65
AWS Forums ...................................................................................................................... 66
AWS Toolkit for Eclipse ......................................................................................................... 66
SDK for Java Source Code and Samples ................................................................................. 66
SDK for Java Code Samples .................................................................................................. 66
List of Code Samples ................................................................................................... 66
Building and Running the Samples using the Command Line .............................................. 67
Building and Running the Samples using the Eclipse IDE ................................................... 68
Document History ........................................................................................................................ 70
Version v1.0.0
iii
AWS SDK for Java Developer Guide
About the AWS SDK for Java
The AWS SDK for Java provides a Java API for AWS infrastructure services. Using the SDK for Java,
you can build applications that work with Amazon Simple Storage Service (Amazon S3), Amazon Elastic
Compute Cloud (Amazon EC2), Amazon SimpleDB, and more.
New AWS services are occasionally added to the AWS SDK for Java. For a complete list of the services
that are supported by the SDK for Java, see Supported Services on the AWS SDK for Java home page.
Topics
• About the AWS SDK for Java (p. 1)
• What's in this Guide? (p. 2)
• Viewing the Revision History for the SDK for Java (p. 2)
• About Amazon Web Services (p. 3)
Version v1.0.0
1
AWS SDK for Java Developer Guide
Developing AWS Applications for Android
Each release of the AWS SDK for Java is also published to GitHub. The comments in the commit history
provide information about what changed in each commit. To view the comments associated with a commit,
click the plus sign next to that commit.
Version v1.0.0
2
AWS SDK for Java Developer Guide
About Amazon Web Services
Version v1.0.0
3
AWS SDK for Java Developer Guide
Get an AWS Account and Your AWS Credentials
Getting Started
This section provides information about how to install, set up and use the SDK for Java. If you have never
used the SDK for Java before, you should start here.
Topics
• Get an AWS Account and Your AWS Credentials (p. 4)
• Install a Java Development Environment (p. 5)
• Install the AWS SDK for Java (p. 5)
• Set up your AWS Credentials for Use with the SDK for Java (p. 6)
• Explore the SDK for Java Code Samples (p. 7)
• Where to Go from Here (p. 7)
Part of the sign-up procedure involves receiving a phone call and entering a PIN using the phone
keypad.
AWS sends you a confirmation e-mail after the sign-up process is complete. At any time, you can view
your current account activity and manage your account by going to http://aws.amazon.com and clicking
My Account/Console.
Access keys consist of an access key ID and secret access key, which are used to sign programmatic
requests that you make to AWS. If you don't have access keys, you can create them by using the AWS
Management Console. We recommend that you use IAM access keys instead of AWS root account
access keys. IAM lets you securely control access to AWS services and resources in your AWS account.
Version v1.0.0
4
AWS SDK for Java Developer Guide
Install a Java Development Environment
Note
To create access keys, you must have permissions to perform the required IAM actions. For
more information, see Granting IAM User Permission to Manage Password Policy and Credentials
in Using IAM.
Your secret key will no longer be available through the AWS Management Console; you will have
the only copy. Keep it confidential in order to protect your account, and never email it. Do not share
it outside your organization, even if an inquiry appears to come from AWS or Amazon.com. No one
who legitimately represents Amazon will ever ask you for your secret key.
Related topics
If you use Eclipse, the AWS Toolkit for Eclipse provides support for the AWS SDK for Java as well as
additional management features. For more information on installing the AWS Toolkit for Eclipse, see
http://aws.amazon.com/eclipse/. For more information about using the Toolkit for AWS development, see
the AWS Toolkit for Eclipse Getting Started Guide.
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. Using the 32-bit version of the JVM with the -Server
option at run time should provide comparable performance to the 64-bit JVM.
Version v1.0.0
5
AWS SDK for Java Developer Guide
Set up your AWS Credentials for Use with the SDK for
Java
If you intend to use the SDK for Java with the Eclipse IDE, you should install the AWS Toolkit for Eclipse,
which automatically includes the AWS SDK for Java. For information about how to obtain, install and set
up the Toolkit for Eclipse, see Setting Up the AWS Toolkit for Eclipse in the AWS Toolkit for Eclipse
Getting Started Guide.
If you intend to build using Ant and the command-line, or will be using an IDE other than Eclipse, you can
set up the Java SDK as shown here.
1. Download the AWS SDK for Java from the SDK web page at http://aws.amazon.com/sdkforjava.
2. After downloading the SDK, extract the contents into a directory.
Setting your credentials for use by the SDK for Java can be done in a number of ways, but here are the
recommended approaches:
• To set credentials for your local user (login), use the AWS CLI to set credentials with the following
command:
The CLI will store credentials that are specified this way in a local file, typically ~/.aws/config.
• To set credentials for a particular terminal (command-line) session, set the AWS_ACCESS_KEY_ID
and AWS_SECRET_ACCESS_KEY environment variables.
export AWS_ACCESS_KEY_ID=your_access_key_id
export AWS_SECRET_ACCESS_KEY=your_secret_access_key
set AWS_ACCESS_KEY_ID=your_access_key_id
set AWS_SECRET_ACCESS_KEY=your_secret_access_key
• To set credentials for an EC2 instance, you should specify an IAM role and then give your EC2 instance
access to that role as shown in Using IAM Roles for EC2 Instances (p. 29).
Once you have set your AWS credentials using one of these methods, they can be loaded automatically
by the SDK for Java by using the default credential provider chain. For complete information about how
to load and use AWS credentials in your SDK for Java applications, see Providing Credentials (p. 8).
Version v1.0.0
6
AWS SDK for Java Developer Guide
Explore the SDK for Java Code Samples
Note
You can override the default location of the AWS credential file by setting the
AWS_CREDENTIAL_FILE environment variable. For more information, see Providing
Credentials (p. 8).
The Using AWS Services (p. 20) section provides instructions about how to use the SDK for Java to
perform common actions with various AWS services. Many of these are accompanied by code examples
that demonstrate the techniques that are discussed.
The Additional Resources (p. 65) section has pointers to other resources to assist you with programming
AWS using the SDK for Java.
Version v1.0.0
7
AWS SDK for Java Developer Guide
Providing Credentials
This section provides important general information about programming with the AWS SDK for Java.
Information in this section applies to all services that you might be using with the SDK for Java.
For information that is specific to a particular service (EC2, SWF, etc.), see the Using AWS Services (p. 20)
section.
Topics
• Providing AWS Credentials in the AWS SDK for Java (p. 8)
• AWS Region Selection (p. 11)
• Client Networking Configuration (p. 12)
• Setting the JVM TTL for DNS Name Lookups (p. 13)
• Exception Handling (p. 13)
• Logging AWS SDK for Java Calls (p. 15)
• Access Control Policies (p. 17)
This topic provides information about how to load credentials for AWS using the SDK for Java.
Topics
• Using the Default Credential Provider Chain (p. 9)
• Specifying a Credential Provider or Provider Chain (p. 10)
• Explicitly Specifying Credentials (p. 10)
• See Also (p. 11)
Version v1.0.0
8
AWS SDK for Java Developer Guide
Using the Default Credential Provider Chain
Setting Credentials
AWS credentials must be set in at least one of the preceding locations in order to be used. For information
about setting credentials, visit one of the following topics:
• For information about specifying credentials in the environment or in the default credential profiles file,
see Set up your AWS Credentials for Use with the SDK for Java (p. 6).
• For information about setting Java system properties, see the System Properties tutorial on the official
Java Tutorials website.
• For information about how to set up and use instance profile credentials for use with your EC2 instances,
see Using IAM Roles for EC2 Instances (p. 29).
This feature can be used to temporarily change the location where the SDK for Java looks for your
credentials file (by setting this variable with the command-line, for example), or you can set the environment
variable in your user or system environment to change it for the user or system-wide.
• Set the AWS_CREDENTIAL_FILE environment variable to the location of your AWS credentials file.
export AWS_CREDENTIAL_FILE=path/to/credentials_file
set AWS_CREDENTIAL_FILE=path/to/credentials_file
Version v1.0.0
9
AWS SDK for Java Developer Guide
Specifying a Credential Provider or Provider Chain
Loading Credentials
Once credentials have been set, you can load them using the SDK for Java default credential provider
chain.
• Instantiate an AWS Service client using the default constructor. For example:
• Provide an instance of a credentials provider or provider chain to a service client constructor that takes
an AWSCredentialsProvider interface as input. For example, to use environment credentials specifically:
For the full list of SDK for Java-supplied credential providers and provider chains, see the list of "All known
implementing classes" in the reference topic for AWSCredentialsProvider.
Tip
You can use this technique to supply credential providers or provider chains that you create, by
implementing your own credential provider that implements the AWSCredentialsProvider
interface, or by sub-classing the AWSCredentialsProviderChain class.
In most cases, it's better to create your own credential provider and to use that (as shown in Specifying
a Credential Provider or Provider Chain (p. 10)), but there may be some situations in which this isn't
feasible.
Version v1.0.0
10
AWS SDK for Java Developer Guide
See Also
Instantiate a class that provides the AWSCredentials interface, such as BasicAWSCredentials, supplying
it with the AWS access key and secret key you will use for the connection.
Provide the class instance to a service client constructor that takes an AWSCredentials interface as input.
For example:
See Also
• Get an AWS Account and Your AWS Credentials (p. 4)
• Set up your AWS Credentials for Use with the SDK for Java (p. 6)
• Using IAM Roles for EC2 Instances (p. 29)
Each AWS client can be configured to use a specific endpoint by calling the setEndpoint(String
endpointUrl) method.
For example, to configure the Amazon EC2 client to use the EU (Ireland) Region, use the following code:
Be aware that regions are logically isolated from each other, so for example, you won't be able to access
US East resources when communicating with the EU West endpoint. If your code accesses multiple AWS
regions, we recommend that you instantiate a specific client for each region, as the following example
shows.
Using a specific client for each endpoint also protects against the (unfortunate) scenario in which, in a
multithreaded environment, one thread sets the endpoint for a client and then later a different thread
changes the endpoint for that client.
Version v1.0.0
11
AWS SDK for Java Developer Guide
Client Networking Configuration
The AWS SDK for Java uses the US East (Northern Virginia) Region as the default region if you do not
specify a region in your code. However, the AWS Management Console uses US West (Oregon) Region
as its default.Therefore, when using the AWS Management Console in conjunction with your development,
be sure to specify the same region in both your code and the console.
Go to Regions and Endpoints for the current list of regions and corresponding endpoints for all AWS
services.
Proxy Configuration
If you're connecting to the Internet through a proxy server, you'll need to configure your proxy server
settings (proxy host, port and username/password) through the ClientConfiguration object.
Several HTTP transport options can be configured through the ClientConfiguration object. Default
values will suffice for the majority of users, but users who want more control can configure the following:
• Socket timeout
• Connection timeout
• Maximum retry attempts for retry-able errors
• Maximum open HTTP connections
Advanced users who want to tune low-level TCP parameters can additionally set TCP buffer size hints
through the ClientConfiguration object. The majority of users will never need to tweak these values,
but they are provided for advanced users.
Optimal TCP buffer sizes for an application are highly dependent on network and OS configuration and
capabilities. For example, most modern operating systems provide auto-tuning logic for TCP buffer sizes,
which can have a big impact on performance for TCP connections that are held open long enough for
the auto-tuning to optimize buffer sizes.
Large buffer sizes (e.g., 2 MB) allow the OS to buffer more data in memory without requiring the remote
server to acknowledge receipt of that information, so can be particularly useful when the network has
high latency.
This is only a hint, and the OS may choose not to honor it. When using this option, users should always
check the operating system's configured limits and defaults. Most OS's have a maximum TCP buffer size
limit configured, and won't let you go beyond that limit unless you explicitly raise the max TCP buffer size
limit.
Version v1.0.0
12
AWS SDK for Java Developer Guide
Setting the JVM TTL for DNS Name Lookups
Many resources available to help with configuring TCP buffer sizes and operating system specific TCP
settings, including:
The JVM caches DNS name lookups. That is, when the JVM resolves a DNS name to an IP address, it
caches the IP address for a period of time. During this time period, the JVM uses the cached IP address
rather than querying a DNS server. This time period is known as the time-to-live or TTL. The default TTL
varies with the version of the JVM and also depends on whether a security manager is installed.
In some cases, the JVM default TTL is set to never re-resolve DNS names to IP addresses. This means
that when the IP address for an AWS resource changes, the application will be unable to connect to that
resource until someone manually restarts the JVM so that the new IP addresses can be picked up. In
these cases, it is vital that the TTL be configured to a shorter time period.
A TTL of 60 seconds ensures that if there is a change in the IP address that corresponds to an AWS
resource, the JVM will refresh the cached IP value after a relatively brief period of time. If the TTL value
is too large, Java applications may fail to connect to AWS resources because the cached IP has become
invalid.
You can configure the TTL in the file java.security, which is located in the directory %JRE%\lib\security.
The configured value specifies the number of seconds that the JVM should cache a successful DNS
name lookup. Here is an example that shows how to configure the TTL to 60 seconds.
networkaddress.cache.ttl=60
You can also configure the TTL programmatically using the following code
java.security.Security.setProperty("networkaddress.cache.ttl" , "60");
Note that the JVM is a shared resource; multiple Java applications could be using the same JVM. The
TTL value affects all Java applications that use the JVM.
Exception Handling
Understanding how and when the AWS SDK for Java throws exceptions is important in order to build
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.
The AWS Java SDK uses runtime (or unchecked) exceptions instead of checked exceptions for a few
reasons:
Version v1.0.0
13
AWS SDK for Java Developer Guide
Exception Handling
• 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.
For more information about the use of checked and unchecked exceptions, see the following articles:
This is the main type of exception that you'll need to deal with when using the AWS SDK for Java. This
exception represents an error response from an AWS service. For example, if you request 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 thrown AmazonServiceException. For some cases, a subclass
of AmazonServiceException will be thrown to allow developers fine grained control over handling error
cases through catch blocks.
When you encounter an AmazonServiceException, you know that your request was successfully sent
to the AWS service, but could not be successfully processed either because of errors in the request's
parameters or because of issues on the service side.
AmazonServiceException also includes a field that describes whether the failed request was the
caller's fault (i.e., a request with illegal values) or the AWS service's fault (i.e., an internal service error).
AmazonClientException
This exception 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. AmazonClientException exceptions
are more severe than AmazonServiceException exceptions and indicate a major problem that is
preventing the client from being able to make service calls to AWS services. For example, the AWS Java
SDK will throw an AmazonClientException if no network connection is available when you try to call
an operation on one of the clients.
IllegalArgumentException
When calling operations, if you pass an illegal argument, the AWS SDK for Java will throw an
IllegalArgumentException. For example, if you call an operation and pass a null value in for one of
the required parameters, the SDK will throw an IllegalArgumentException describing the illegal
argument.
Version v1.0.0
14
AWS SDK for Java Developer Guide
Logging
In order to use Log4j with the SDK, you need to download the Log4j jar from the Apache website. The
jar is not included in the SDK. Copy the jar file to a location that is on your classpath.
Log4j uses a configuration file, log4j.properties. Example configuration files are shown below. Copy this
configuration file to a directory on your classpath. The Log4j jar and the log4j.properties file do not have
to be in the same directory.
The log4j.properties configuration file specifies properties such as logging level, where logging output is
sent (such as 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
SDK.
• log4j.logger.com.amazonaws
• log4j.logger.org.apache.http.wire
<path id="aws.java.sdk.classpath">
<fileset dir="../../third-party" includes="**/*.jar"/>
<fileset dir="../../lib" includes="**/*.jar"/>
<pathelement location="."/>
</path>
If you are using the Eclipse IDE, you can set the classpath by navigating to:
The following log4j.properties file sets the rootLogger to WARN, which will cause warning and error
messages from all loggers in the "com.amazonaws" hierarchy to be included. Alternatively, you can
explicitly set the com.amazonaws logger to WARN.
Version v1.0.0
15
AWS SDK for Java Developer Guide
Request/Response Summary Logging
log4j.rootLogger=WARN, A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%d [%t] %-5p %c - %m%n
# Or you can explicitly enable WARN and ERROR messages for the AWS Java clients
log4j.logger.com.amazonaws=WARN
The following log4j.properties file enables a summary of requests and responses, including AWS request
IDs.
log4j.rootLogger=WARN, A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%d [%t] %-5p %c - %m%n
# Turn on DEBUG logging in com.amazonaws.request to log
# a summary of requests/responses with AWS request IDs
log4j.logger.com.amazonaws.request=DEBUG
Version v1.0.0
16
AWS SDK for Java Developer Guide
Access Control Policies
4 logger. Enabling the DEBUG level on the apache.http.wire logger enables logging for all request
and response data.
The following log4j.properties file turns on full wire logging in Apache HttpClient 4 and should only be
turned on temporarily since it can have a significant performance impact on your application.
log4j.rootLogger=WARN, A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%d [%t] %-5p %c - %m%n
# Log all HTTP content (headers, parameters, content, etc) for
# all requests and responses. Use caution with this since it can
# be very expensive to log such verbose data!
log4j.logger.org.apache.http.wire=DEBUG
Access control policies are a collection of statements. Each statement takes the form: "A has permission
to do B to C where D applies".
A is the principal
The AWS account that is making a request to access or modify one of your AWS resources.
B is the action
The way in which your AWS resource is being accessed or modified, such as sending a message
to an Amazon SQS queue, or storing an object in an Amazon S3 bucket.
C is the resource
Your AWS entity that the principal wants to access, such as an Amazon SQS queue, or an object
stored in Amazon S3.
D is the set of conditions
The optional constraints that specify when to allow or deny access for the principal to access your
resource. Many expressive conditions are available, some specific to each service. For example,
you can use date conditions to allow access to your resources only after or before a specific time.
Amazon S3 Example
The following example demonstrates a policy that allows anyone access to read all the objects in a bucket,
but restricts access to uploading objects to that bucket to two specific AWS accounts (in addition to the
bucket owner's account).
Version v1.0.0
17
AWS SDK for Java Developer Guide
Access Control Policies
One common use of policies is to authorize an Amazon SQS queue to receive messages from an Amazon
SNS topic.
/*
* This policy allows an SNS topic to send messages to an SQS queue.
* You can find your SNS topic's ARN through the SNS getTopicAttributes opera
tion.
*/
Policy policy = new Policy().withStatements(
new Statement(Effect.Allow)
.withPrincipals(Principal.AllUsers)
.withActions(SQSActions.SendMessage)
.withConditions(ConditionFactory.newSourceArnCondition(myTopicArn)));
Some services offer additional conditions that can be used in policies. Amazon SNS provides conditions
for allowing or denying subscriptions to SNS topics based on the protocol (e.g., email, HTTP, HTTPS,
SQS) and endpoint (e.g., email address, URL, SQS ARN) of the request to subscribe to a topic.
/*
* This SNS condition allows you to restrict subscriptions to an Amazon SNS
topic
* based on the requested endpoint (email address, SQS queue ARN, etc.) used
when
* someone tries to subscribe to your SNS topic.
*/
Condition endpointCondition =
SNSConditionFactory.newEndpointCondition("*@mycompany.com");
Version v1.0.0
18
AWS SDK for Java Developer Guide
Access Control Policies
.withActions(SNSActions.Subscribe)
.withConditions(endpointCondition));
Version v1.0.0
19
AWS SDK for Java Developer Guide
DynamoDB
This section provides information about how to program various Amazon Web Services using the SDK
for Java.
Topics
• Programming DynamoDB with the AWS SDK for Java (p. 20)
• Programming Amazon EC2 with the AWS SDK for Java (p. 23)
• Programming Amazon SWF with the AWS SDK for Java (p. 63)
Topics
• Manage Tomcat Session State with DynamoDB (p. 20)
DynamoDB, a NoSQL database store from Amazon Web Services (AWS), avoids these drawbacks by
providing an effective solution for sharing session state across web servers.
Version v1.0.0
20
AWS SDK for Java Developer Guide
Manage Tomcat Session State with DynamoDB
1. The AwsAccessKey and AwsSecretKey attributes of the Manager element explicitly provide
credentials.
2. The AwsCredentialsFile attribute on the Manager element specifies a properties file from which
to load credentials.
Version v1.0.0
21
AWS SDK for Java Developer Guide
Manage Tomcat Session State with DynamoDB
• A config file that copies the jar into Tomcat's lib directory and applies the overridden context.xml
file.
You can find in more information on customizing the AWS Elastic Beanstalk environments in the developer
guide for that service.
If you deploy to AWS Elastic Beanstalk with the AWS Toolkit for Eclipse, then the session manager is
set up for you if you go through the New AWS Java Web Project wizard and select DynamoDB for
session management. The Toolkit for Eclipse configures all the needed files, and puts them in the
.ebextensions directory inside the WebContent directory of your project. If you have problems finding
this directory, make sure you aren't hiding files that begin with a period.
When your application starts, it looks for an DynamoDB table called, by default, Tomcat_SessionState.
The table should have a string hash key named "sessionId" (case-sensitive), no range key, and the desired
values for ReadCapacityUnits and WriteCapacityUnits.
We recommend that you create this table before first running your application. (For information on working
with DynamoDB tables and provisioned throughput, see the Amazon DynamoDB Developer Guide.) If
you don't create the table, however, the extension creates it during initialization. See the context.xml
options in the next section for a list of attributes that configure how the session-state table is created
when it doesn't exist.
Once the application is configured and the table is created, you can use sessions with any other session
provider.
Version v1.0.0
22
AWS SDK for Java Developer Guide
Amazon EC2
Troubleshooting
If you encounter issues with the session manager, the first place to look is in catalina.out. If you have
access to the Tomcat installation, you can go directly to this log file and look for any error messages from
the session manager. If you're using AWS Elastic Beanstalk, you can view the environment logs with the
AWS Management Console or the AWS Toolkit for Eclipse.
Limitations
The session manager does not support session locking.Therefore, applications that use many concurrent
AJAX calls to manipulate session data may not be appropriate for use with the session manager, due to
race conditions on session data writes and saves back to the data store.
Topics
• Starting an Amazon EC2 Instance (p. 23)
• Using IAM Roles for EC2 Instances with the AWS SDK for Java (p. 29)
• Tutorial: Amazon EC2 Spot Instances (p. 36)
• Tutorial: Advanced Amazon EC2 Spot Request Management (p. 45)
Topics
• Create an Amazon EC2 Client (p. 23)
• Create an Amazon EC2 Security Group (p. 24)
• Authorize Security Group Ingress (p. 25)
• Create a Key Pair (p. 26)
• Run an Amazon EC2 Instance (p. 27)
• Connect to Your Amazon EC2 Instance (p. 28)
• Related Resources (p. 29)
Version v1.0.0
23
AWS SDK for Java Developer Guide
Starting an Amazon EC2 Instance
secretKey=YOUR_SECRET_KEY
accessKey=YOUR_ACCESS_KEY
Specify your AWS credentials as values for the secretKey and accessKey entries. To learn more about
your AWS credentials, including where to find them, go to AWS Security Credentials.
After you create this file, you are ready to create and initialize your Amazon EC2 client.
AWSCredentials credentials =
new PropertiesCredentials(
AwsConsoleApp.class.getResourceAsStream("AwsCredentials.proper
ties"));
amazonEC2Client =
new AmazonEC2Client(credentials);
amazonEC2Client.setEndpoint("ec2.us-west-2.amazonaws.com");
The AWS SDK for Java uses US East (N. Virginia) as the default region if you do not specify a region
in your code. However, the AWS Management Console uses US West (Oregon) as its default.
Therefore, when using the AWS Management Console in conjunction with your development, be
sure to specify the same region in both your code and the console.
Go to Regions and Endpoints for the current list of regions and corresponding endpoints for all AWS
services.
Before running an Amazon EC2 instance, you will need to create an Amazon EC2 security group, authorize
security group ingress, and create a key pair to allow you to log into your instance.
For information about creating a security group, see Create an Amazon EC2 Security Group (p. 24).
For information about authorizing security group ingress, see Authorize Amazon EC2 Security Group
Ingress (p. 25).
For information about creating a key pair, see Create a Key Pair (p. 26).
For information about running your Amazon EC2 instance, see Run an Amazon EC2 Instance (p. 27).
Version v1.0.0
24
AWS SDK for Java Developer Guide
Starting an Amazon EC2 Instance
If you want to allow inbound traffic, create a security group and assign a rule to it that allows the ingress
that you want. Then associate the new security group with an Amazon EC2 instance. For more information,
see Authorize Security Group Ingress (p. 25).
CreateSecurityGroupRequest createSecurityGroupRequest =
new CreateSecurityGroupRequest();
createSecurityGroupRequest.withGroupName("JavaSecurityGroup")
.withDescription("My Java Security Group");
The security group name must be unique within the AWS region in which you initialize your Amazon
EC2 client. You must use US-ASCII characters for the security group name and description.
2. Pass the request object as a parameter to the createSecurityGroup method. The method returns a
CreateSecurityGroupResult object, as follows:
CreateSecurityGroupResult createSecurityGroupResult =
amazonEC2Client.createSecurityGroup(createSecurityGroupRequest);
If you attempt to create a security group with the same name as an existing security group,
createSecurityGroup throws an exception.
Before starting an Amazon EC2 instance, you next need to authorize security group ingress and create
a key pair to allow you to log into your instance.
For information about authorizing security group ingress, see Authorize Amazon EC2 Security Group
Ingress (p. 25).
For information about creating a key pair, see Create a Key Pair (p. 26).
For information about running your Amazon EC2 instance, see Run an Amazon EC2 Instance (p. 27).
1. Create and initialize an IpPermission instance. Use the withIpRanges method to set the range of
IP addresses to authorize ingress for, and use the withIpProtocol method to set the IP protocol. Use
the withFromPort and withToPort methods to specify range of ports to authorize ingress for, as
follows:
Version v1.0.0
25
AWS SDK for Java Developer Guide
Starting an Amazon EC2 Instance
IpPermission ipPermission =
new IpPermission();
ipPermission.withIpRanges("111.111.111.111/32", "150.150.150.150/32")
.withIpProtocol("tcp")
.withFromPort(22)
.withToPort(22);
All the conditions that you specify in the IpPermission object must be met in order for ingress to
be allowed.
Specify the IP address using CIDR notation. If you specify the protocol as TCP/UDP, you must
provide a source port and a destination port.You can authorize ports only if you specify TCP or UDP.
2. Create and initialize an AuthorizeSecurityGroupIngressRequest instance. Use the withGroupName
method to specify the security group name, and pass the IpPermission object you initialized earlier
to the withIpPermissions method, as follows:
AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest
=
new AuthorizeSecurityGroupIngressRequest();
authorizeSecurityGroupIngressRequest.withGroupName("JavaSecurityGroup")
.withIpPermissions(ipPermission);
amazonEC2Client.authorizeSecurityGroupIngress(authorizeSecurityGroupIngress
Request);
Before starting an Amazon EC2 instance, you need to create a key pair to allow you to log into your
instance. For information about creating a key pair, see Create a Key Pair (p. 26).
Version v1.0.0
26
AWS SDK for Java Developer Guide
Starting an Amazon EC2 Instance
1. Create and initialize a CreateKeyPairRequest instance. Use the withKeyName method to set the key
pair name, as follows:
CreateKeyPairRequest createKeyPairRequest =
new CreateKeyPairRequest();
createKeyPairRequest.withKeyName(keyName);
2. Pass the request object to the createKeyPair method. The method returns a CreateKeyPairResult
instance, as follows:
CreateKeyPairResult createKeyPairResult =
amazonEC2Client.createKeyPair(createKeyPairRequest);
Key pair names must be unique. If you attempt to create a key pair with the same key name as an
existing key pair, createKeyPair returns an exception.
3. Call the result object's getKeyPair method to obtain a KeyPair object. Call the KeyPair object's
getKeyMaterial method to obtain the unencrypted PEM-encoded private key, as follows:
keyPair = createKeyPairResult.getKeyPair();
Calling createKeyPair is the only way to obtain the private key programmatically.
Before logging onto an Amazon EC2 instance, you must create the instance and ensure that it is running.
For information on how to run an Amazon EC2 instance, see Run an Amazon EC2 Instance (p. 27).
For information on how to use your key pair to connect to your Amazon EC2 instance, see Connect to
Your Amazon EC2 Instance (p. 28).
1. Create and initialize a RunInstancesRequest instance. Specify the Amazon Machine Image (AMI)
(withImageId), the instance type (withInstanceType), the minimum (withMinCount) and maximum
(withMaxCount) number of instances to run, key pair name (withKeyName), and the name of one or
more security groups (withSecurityGroups), as follows:
RunInstancesRequest runInstancesRequest =
Version v1.0.0
27
AWS SDK for Java Developer Guide
Starting an Amazon EC2 Instance
new RunInstancesRequest();
runInstancesRequest.withImageId("ami-4b814f22")
.withInstanceType("m1.small")
.withMinCount(1)
.withMaxCount(1)
.withKeyName(“YourKeyName”)
.withSecurityGroups("YourSecurityGroupName");
You must specify a public or privately-provided AMI. A large selection of Amazon-provided public
AMIs is available for you to use. For a list of public AMIs provided by Amazon, go to Amazon Machine
Images. Ensure that the specified image ID exists in the region in which your client was created.
The instance type must match the AMI you want to run. For 64-bit architecture, you cannot specify
an instance type of m1.small. For more information on instance types, go to Instance Families and
Types.
You must specify a minimum number and a maximum number of instances to launch. If the specified
number of instances is greater than the number of instances you are authorized to launch, no instances
are launched. The specified number of maximum instances must be no greater than the maximum
number allowed for your account; by default, the maximum number of instances is 20. If there are
fewer instances available than the maximum number specified, the largest possible number of images
are launched.
Ensure that the specified key name and security group exists for the region in which your client was
created.
2. Pass the request object into the runInstances method. The method returns a RunInstancesResult
object, as follows:
RunInstancesResult runInstancesResult =
amazonEC2Client.runInstances(runInstancesRequest);
After you have created your Amazon EC2 instance, you can log onto the AWS Management Console to
check the status of the instance.
Once your Amazon EC2 instance is running, you can remotely connect to it using your key pair. For
information about connecting to your instance, see Connect to Your Amazon EC2 Instance (p. 28).
If you did not authorize ingress for the security group that your instance belongs to, you will not be able
to connect to your instance. By default, Amazon EC2 instances do not permit inbound traffic. For more
information on authorizing security group ingress, see Authorize Security Group Ingress (p. 25).
For information on how to connect to your Amazon EC2 instance, go to Connecting to Instances in the
Amazon Elastic Compute Cloud User Guide.
Version v1.0.0
28
AWS SDK for Java Developer Guide
Using IAM Roles for EC2 Instances
Related Resources
The following table lists related resources that you'll find useful when using Amazon EC2 with the AWS
SDK for Java.
Resource Description
Java Developer Center Provides sample code, documentation, tools, and additional
resources to help you build applications on Amazon Web
Services.
AWS SDK for Java Documentation Provides documentation for the AWS SDK for Java.
Amazon Elastic Compute Cloud Provides documentation for the Amazon EC2 service.
(Amazon EC2) Documentation
For software that runs on Amazon Elastic Compute Cloud (Amazon EC2) instances which are, by definition,
internet-accessible servers, you must manage AWS credentials in a way that keeps them secure but also
makes them accessible to your application so it can make AWS requests.
Using IAM roles for EC2 instances is a secure, effective way to provide AWS credentials to applications
that run on EC2 instances. This section will describe what IAM roles for EC2 instances are, how they're
used, and then show you how it works with a simple Java program.
Note
For complete information about using IAM Roles for EC2 instances, see Using Identity and
Access Management in the AWS Identity and Access Management User Guide.
Topics
• How Applications Obtain AWS Credentials Using IAM Roles for EC2 Instances (p. 29)
• Using IAM Roles with the SDK for Java (p. 30)
• Walkthrough: Using IAM Roles to Retrieve an Amazon S3 Object from an EC2 Instance (p. 30)
Version v1.0.0
29
AWS SDK for Java Developer Guide
Using IAM Roles for EC2 Instances
By default, if the AWS client constructor can't find credentials in the environment variables or in the Java
system properties, it will attempt to obtain temporary AWS credentials from the IMDS. These credentials
have the same permissions as the IAM role associated with the EC2 instance in its instance profile.
Note
The credentials provided by the IMDS are temporary and eventually expire, but the SDK for Java
client periodically refreshes them so that your application does not lose access to AWS. This
credential refesh is automatic and is transparent to your application; no actions need to be taken
by your application to refresh the credentials obtained through the IMDS.
You can tell the SDK for Java to use AWS credentials obtained from the IMDS first, before it attempts to
look for credentials in the environment or java system properties, by passing an
InstanceProfileCredentialsProvider object to the AWS client's constructor. For example, to create an S3
client using IMDS-supplied credentials:
If the client constructor can't find credentials in the IMDS or through any of the other methods in the
credentials provider chain, an AmazonClientException will be thrown.
Note
AWS CloudFormation does not support calling its API with an IAM role. You must call the AWS
CloudFormation API as a regular IAM user.
Topics
• Create the IAM Role (p. 30)
• Launch an EC2 Instance with an Instance Profile (p. 32)
• Create your Application (p. 33)
• Transfer the Compiled Program to Your EC2 Instance (p. 35)
• Run the Program (p. 35)
Version v1.0.0
30
AWS SDK for Java Developer Guide
Using IAM Roles for EC2 Instances
To create the IAM role to give S3 read-only access to your EC2 instance
4.
The IAM console provides ready-made policy templates for specific AWS services. When you create the
IAM role, specify the Amazon S3 Read Only Access policy template. The following screen shot from
the IAM role creation wizard shows this policy template.
Version v1.0.0
31
AWS SDK for Java Developer Guide
Using IAM Roles for EC2 Instances
Note
Policies can also be represented in JSON format. Here is a policy that provides read ("Get" and
"List") access to Amazon S3.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:Get*",
"s3:List*"
],
"Resource": "*"
}
]
}
This is the policy that provides a trust relationship with EC2, allowing your instance to assume
the IAM role:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow",
"Principal": {
"Service": "ec2.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
Remember the name of the IAM role that you create. You'll need to provide it when you create your EC2
instance in the next step.
When you create your EC2 instance, you also need to specify a key pair and a security group. Make sure
to use a key pair for which you have the private key (PEM file) stored on your local computer. Specify a
security group that enables you to connect to your EC2 instance using SSH (port 22).
Note
Information about key pairs and security groups is provided in Running an Instance in the Amazon
Elastic Compute Cloud User Guide.
After you create the EC2 instance, go to the EC2 Instances area of the AWS Management Console and
view your instance. Once the instance is Running, record the public DNS name for the instance. You
will use this DNS name to connect to the instance with SSH.
Version v1.0.0
32
AWS SDK for Java Developer Guide
Using IAM Roles for EC2 Instances
Next, copy the SDK for Java libraries into your newly-created tutorial directory. If you downloaded the
SDK for Java to your ~/Downloads directory, you can copy them with the following commands:
cp -r ~/Downloads/aws-java-sdk-1.7.5/lib .
cp -r ~/Downloads/aws-java-sdk-1.7.5/third-party .
Here is the program that we'll be transferring to your EC2 instance. Open a new file, call it
GetS3Ojbect.java, and type (or paste) the following code:
import java.io.*;
import com.amazonaws.auth.*;
import com.amazonaws.services.s3.*;
import com.amazonaws.services.s3.model.*;
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
try
Version v1.0.0
33
AWS SDK for Java Developer Guide
Using IAM Roles for EC2 Instances
{
System.out.println("Downloading an object");
S3Object s3object = s3Client.getObject(
new GetObjectRequest(bucketName, key));
displayTextInputStream(s3object.getObjectContent());
}
catch(AmazonServiceException ase)
{
System.out.println( "AmazonServiceException" );
}
catch(AmazonClientException ace)
{
System.out.println( "AmazonClientException" );
}
}
You'll also need an Ant build script to build and run your application. Open a new file in the same directory
as GetS3Object.java and call it build.xml. Add the following lines to the file:
<target name="build">
<javac debug="true"
includeantruntime="false"
srcdir="."
destdir="."
classpathref="aws.java.sdk.classpath"/>
</target>
Version v1.0.0
34
AWS SDK for Java Developer Guide
Using IAM Roles for EC2 Instances
Build and run the modified program. Since no credentials are stored in the program, unless you have
your AWS credentials specified in your environment, it's likely that you'll get an AmazonServiceException.
For example:
$ ant
Buildfile: /path/to/my/GetS3ObjectApp/build.xml
build:
[javac] Compiling 1 source file to /path/to/my/GetS3ObjectApp
run:
[java] Downloading an object
[java] AmazonServiceException
BUILD SUCCESSFUL
Note
If you launched an AMI other than the Amazon Linux AMI recommended earlier, you may need
to use "root" instead of "ec2-user" when connecting to the instance using SCP or SSH.
In the preceding commands, GetS3Object.class is your compiled program, build.xml is the ant file
used to build and run your program, and the lib and third-party directories are the corresponding
library folders from the SDK for Java.
The -r switch indicates that scp should do a recursive copy of all of the contents of the library and
third-party directories from the SDK for Java.
The -p switch indicates that scp should preserve the permissions of the source files when it copies them
to the destination. If you are copying the files from Windows, you may need to fix the permissions on your
instance by using the following command:
Version v1.0.0
35
AWS SDK for Java Developer Guide
Tutorial: Amazon EC2 Spot Instances
If ant is not installed on the AMI that you selected, you can install it using the yum installer.
ant getS3Object
The program should output the contents of your Amazon S3 object to your command window.
Spot Instances can significantly lower your Amazon EC2 costs for batch processing, scientific research,
image processing, video encoding, data and web crawling, financial analysis, and testing. Additionally,
Spot Instances give you access to large amounts of additional capacity in situations where the need for
that capacity is not urgent.
To use Spot Instances, place a Spot Instance request specifying the maximum price you are willing to
pay per instance hour; this is your bid. If your bid exceeds the current Spot Price, your request is fulfilled
and your instances will run until either you choose to terminate them or the Spot Price increases above
your bid (whichever is sooner).
• You will often pay less per hour than your bid. Amazon EC2 adjusts the Spot Price periodically as
requests come in and available supply changes. Everyone pays the same Spot Price for that period
regardless of whether their bid was higher. Therefore, you might pay less than your bid, but you will
never pay more than your bid.
• If you're running Spot Instances and your bid no longer meets or exceeds the current Spot Price, your
instances will be terminated. This means that you will want to make sure that your workloads and
applications are flexible enough to take advantage of this opportunistic capacity.
Spot Instances perform exactly like other Amazon EC2 instances while running, and like other Amazon
EC2 instances, Spot Instances can be terminated when you no longer need them. If you terminate your
instance, you pay for any partial hour used (as you would for On-Demand or Reserved Instances).
However, if the Spot Price goes above your bid and your instance is terminated by Amazon EC2, you
will not be charged for any partial hour of usage.
This tutorial provides a quick overview of how to use the Java programming language to do the following.
Version v1.0.0
36
AWS SDK for Java Developer Guide
Tutorial: Amazon EC2 Spot Instances
Prerequisites
To use this tutorial you need to be signed up for Amazon Web Services (AWS). If you have not yet signed
up for AWS, go to the Amazon Web Services website, and click Create an AWS Account in the upper
right corner of the page. In addition, you also need to install the AWS Java SDK.
If you are using the Eclipse development environment, we recommend that you install the AWS Toolkit
for Eclipse. Note that the AWS Toolkit for Eclipse includes the latest version of the AWS SDK for Java.
Copy and paste your access key ID and secret access key into the AwsCredentials.properties file.
Access keys consist of an access key ID and secret access key, which are used to sign programmatic
requests that you make to AWS. If you don't have access keys, you can create them by using the AWS
Management Console. We recommend that you use IAM access keys instead of AWS root account
access keys. IAM lets you securely control access to AWS services and resources in your AWS account.
Note
To create access keys, you must have permissions to perform the required IAM actions. For
more information, see Granting IAM User Permission to Manage Password Policy and Credentials
in Using IAM.
Your secret key will no longer be available through the AWS Management Console; you will have
the only copy. Keep it confidential in order to protect your account, and never email it. Do not share
it outside your organization, even if an inquiry appears to come from AWS or Amazon.com. No one
who legitimately represents Amazon will ever ask you for your secret key.
Related topics
Version v1.0.0
37
AWS SDK for Java Developer Guide
Tutorial: Amazon EC2 Spot Instances
Now that you have configured your settings, you can get started using the code in the example.
To enable access to the group, we create an ipPermission object with the IP address range set to the
CIDR representation of the subnet for the local computer; the "/10" suffix on the IP address indicates the
subnet for the specified IP address. We also configure the ipPermission object with the TCP protocol
and port 22 (SSH). The final step is to call ec2.authorizeSecurityGroupIngress with the name of
our security group and the ipPermission object.
1
// Retrieves the credentials from an AWSCredentials.properties file.
AWSCredentials credentials = null;
try {
5 credentials = new PropertiesCredentials(
GettingStartedApp.class.getResourceAsStream("AwsCredentials.proper
ties"));
} catch (IOException e1) {
System.out.println("Credentials were not properly entered into AwsCre
dentials.properties.");
System.out.println(e1.getMessage());
10 System.exit(-1);
}
// Get the IP of the current host, so that we can limit the Security
// Group by default to the ip range associated with your subnet.
try {
30 InetAddress addr = InetAddress.getLocalHost();
Version v1.0.0
38
AWS SDK for Java Developer Guide
Tutorial: Amazon EC2 Spot Instances
// Get IP Address
ipAddr = addr.getHostAddress()+"/10";
} catch (UnknownHostException e) {
35 }
You can view this entire code sample in the CreateSecurityGroupApp.java code sample. Note you
only need to run this application once to create a new security group.
You can also create the security group using the AWS Toolkit for Eclipse. Go to the toolkit documentation
for more information.
There are several instance types to choose from; go to Amazon EC2 Instance Types for a complete list.
For this tutorial, we will use t1.micro, the cheapest instance type available. Next, we will determine the
type of AMI we would like to use. We'll use ami-8c1fece5, the most up-to-date Amazon Linux AMI available
when we wrote this tutorial. The latest AMI may change over time, but you can always determine the
latest version AMI by following these steps:
1. Log into the AWS Management Console, click the EC2 tab, and, from the EC2 Console Dashboard,
attempt to launch an instance.
Version v1.0.0
39
AWS SDK for Java Developer Guide
Tutorial: Amazon EC2 Spot Instances
2. In the window that displays AMIs, just use the AMI ID as shown in the following screen shot.
Alternatively, you can use the DescribeImages API, but leveraging that command is outside the
scope of this tutorial.
There are many ways to approach bidding for Spot instances; to get a broad overview of the various
approaches you should view the Bidding for Spot Instances video. However, to get started, we'll describe
three common strategies: bid to ensure cost is less than on-demand pricing; bid based on the value of
the resulting computation; bid so as to acquire computing capacity as quickly as possible.
• Reduce Cost below On-Demand You have a batch processing job that will take a number of hours
or days to run. However, you are flexible with respect to when it starts and when it completes. You
want to see if you can complete it for less cost than with On-Demand Instances. You examine the Spot
Price history for instance types using either the AWS Management Console or the Amazon EC2 API.
For more information, go to Viewing Spot Price History. After you've analyzed the price history for your
desired instance type in a given Availability Zone, you have two alternative approaches for your bid:
• You could bid at the upper end of the range of Spot Prices (which are still below the On-Demand
price), anticipating that your one-time Spot request would most likely be fulfilled and run for enough
consecutive compute time to complete the job.
• Or, you could bid at the lower end of the price range, and plan to combine many instances launched
over time through a persistent request. The instances would run long enough--in aggregate--to
complete the job at an even lower total cost. (We will explain how to automate this task later in this
tutorial.)
• Pay No More than the Value of the Result You have a data processing job to run. You understand
the value of the job's results well enough to know how much they are worth in terms of computing costs.
After you've analyzed the Spot Price history for your instance type, you choose a bid price at which the
cost of the computing time is no more than the value of the job's results. You create a persistent bid
and allow it to run intermittently as the Spot Price fluctuates at or below your bid.
• Acquire Computing Capacity Quickly You have an unanticipated, short-term need for additional
capacity that is not available through On-Demand Instances. After you've analyzed the Spot Price
history for your instance type, you bid above the highest historical price to provide a high likelihood that
your request will be fulfilled quickly and continue computing until it completes.
After you choose your bid price, you are ready to request a Spot Instance. For the purposes of this tutorial,
we will bid the On-Demand price ($0.03) to maximize the chances that the bid will be fulfilled. You can
determine the types of available instances and the On-Demand prices for instances by going to Amazon
EC2 Pricing page. To request a Spot Instance, you simply need to build your request with the parameters
you chose earlier. We start by creating a RequestSpotInstanceRequest object. The request object
requires the number of instances you want to start and the bid price. Additionally, you need to set the
Version v1.0.0
40
AWS SDK for Java Developer Guide
Tutorial: Amazon EC2 Spot Instances
LaunchSpecification for the request, which includes the instance type, AMI ID, and security group
you want to use. Once the request is populated, you call the requestSpotInstances method on the
AmazonEC2Client object. The following example shows how to request a Spot Instance.
Running this code will launch a new Spot Instance Request. There are other options you can use to
configure your Spot Requests. To learn more, please visit the Java Developers: Advanced Spot Features
Tutorials or the RequestSpotInstances API in the SDK for Java.
Note
You will be charged for any Spot Instances that are actually launched, so make sure that you
cancel any requests and terminate any instances you launch to reduce any associated fees.
Version v1.0.0
41
AWS SDK for Java Developer Guide
Tutorial: Amazon EC2 Spot Instances
The request ID created in Step 2 is embedded in the response to our requestSpotInstances request.
The following example code shows how to gather request IDs from the requestSpotInstances response
and use them to populate an ArrayList.
// Add all of the request ids to the hashset, so we can determine when they
hit the
10 // active state.
for (SpotInstanceRequest requestResponse : requestResponses) {
System.out.println("Created Spot Request: "+requestResponse.getSpotIn
stanceRequestId());
spotInstanceRequestIds.add(requestResponse.getSpotInstanceRequestId());
}
To monitor your request ID, call the describeSpotInstanceRequests method to determine the state
of the request. Then loop until the request is not in the "open" state. Note that we monitor for a state of
not "open", rather a state of, say, "active", because the request can go straight to "closed" if there is a
problem with your request arguments. The following code example provides the details of how to
accomplish this task.
5 do {
// Create the describeRequest object with all of the request ids
// to monitor (e.g. that we started).
DescribeSpotInstanceRequestsRequest describeRequest = new DescribeSpot
InstanceRequestsRequest();
describeRequest.setSpotInstanceRequestIds(spotInstanceRequestIds);
10
// Initialize the anyOpen variable to false - which assumes there
// are no requests open unless we find one that is still open.
anyOpen=false;
15 try {
// Retrieve all of the requests we want to monitor.
DescribeSpotInstanceRequestsResult describeResult = ec2.describeS
potInstanceRequests(describeRequest);
List<SpotInstanceRequest> describeResponses = describeResult.get
SpotInstanceRequests();
Version v1.0.0
42
AWS SDK for Java Developer Guide
Tutorial: Amazon EC2 Spot Instances
try {
40 // Sleep for 60 seconds.
Thread.sleep(60*1000);
} catch (Exception e) {
// Do nothing because it woke up early.
}
45 } while (anyOpen);
After running this code, your Spot Instance Request will have completed or will have failed with an error
that will be output to the screen. In either case, we can proceed to the next step to clean up any active
requests and terminate any running instances.
1 try {
// Cancel requests.
CancelSpotInstanceRequestsRequest cancelRequest = new CancelSpotInstan
ceRequestsRequest(spotInstanceRequestIds);
ec2.cancelSpotInstanceRequests(cancelRequest);
5 } catch (AmazonServiceException e) {
// Write out any exceptions that may have occurred.
System.out.println("Error cancelling instances");
System.out.println("Caught Exception: " + e.getMessage());
System.out.println("Reponse Status Code: " + e.getStatusCode());
10 System.out.println("Error Code: " + e.getErrorCode());
System.out.println("Request ID: " + e.getRequestId());
}
Version v1.0.0
43
AWS SDK for Java Developer Guide
Tutorial: Amazon EC2 Spot Instances
To terminate any outstanding instances, you will need the instance ID associated with the request that
started them. The following code example takes our original code for monitoring the instances and adds
an ArrayList in which we store the instance ID associated with the describeInstance response.
1 // Create a variable that will track whether there are any requests
// still in the open state.
boolean anyOpen;
5 // Initialize variables.
ArrayList<String> instanceIds = new ArrayList<String>();
do {
// Create the describeRequest with all of the request ids to
10 // monitor (e.g. that we started).
DescribeSpotInstanceRequestsRequest describeRequest = new DescribeSpot
InstanceRequestsRequest();
describeRequest.setSpotInstanceRequestIds(spotInstanceRequestIds);
try {
// Retrieve all of the requests we want to monitor.
20 DescribeSpotInstanceRequestsResult describeResult = ec2.describeS
potInstanceRequests(describeRequest);
List<SpotInstanceRequest> describeResponses = describeResult.get
SpotInstanceRequests();
Version v1.0.0
44
AWS SDK for Java Developer Guide
Tutorial: Advanced Amazon EC2 Spot Request
Management
}
} while (anyOpen);
Using the instance IDs, stored in the ArrayList, terminate any running instances using the following
code snippet.
1 try {
// Terminate instances.
TerminateInstancesRequest terminateRequest = new TerminateInstances
Request(instanceIds);
ec2.terminateInstances(terminateRequest);
5 } catch (AmazonServiceException e) {
// Write out any exceptions that may have occurred.
System.out.println("Error terminating instances");
System.out.println("Caught Exception: " + e.getMessage());
System.out.println("Reponse Status Code: " + e.getStatusCode());
10 System.out.println("Error Code: " + e.getErrorCode());
System.out.println("Request ID: " + e.getRequestId());
}
We also create a GettingStartedApp class, which has a main method where we perform the high level
function calls. Specifically, we initialize the Requests object described previously. We submit the Spot
Instance request. Then we wait for the Spot request to reach the "Active" state. Finally, we clean up the
requests and instances.
Congratulations! You have just completed the getting started tutorial for developing Spot Instance software
with the AWS SDK for Java.
Next Steps
We recommend that you take the Java Developers: Tutorial: Advanced Amazon EC2 Spot Request
Management (p. 45).
Version v1.0.0
45
AWS SDK for Java Developer Guide
Tutorial: Advanced Amazon EC2 Spot Request
Management
Spot Instances can significantly lower your Amazon EC2 costs for batch processing, scientific research,
image processing, video encoding, data and web crawling, financial analysis, and testing. Additionally,
Spot Instances can provide access to large amounts of additional compute capacity when your need for
the capacity is not urgent.
This tutorial provides a quick overview of some advanced Spot Request features, such as detailed options
to create Spot requests, alternative methods for launching Spot Instances, and methods to manage your
instances. This tutorial is not meant to be a complete list of all advanced topics associated with Spot
Instances. Instead, it gives you a quick reference of code samples for some of the commonly used methods
for managing Spot Requests and Spot Instances.
Prerequisites
To use this tutorial you need to be signed up for Amazon Web Services (AWS). If you have not yet signed
up for AWS, go to the Amazon Web Services website, and click Create an AWS Account in the upper
right corner of the page. In addition, you also need to install the AWS SDK for Java.
If you are using the Eclipse development environment, we recommend that you install the AWS Toolkit
for Eclipse. The Toolkit for Eclipse includes the latest version of the AWS SDK for Java.
Copy and paste your access key ID and secret access key into the AwsCredentials.properties file.
Access keys consist of an access key ID and secret access key, which are used to sign programmatic
requests that you make to AWS. If you don't have access keys, you can create them by using the AWS
Management Console. We recommend that you use IAM access keys instead of AWS root account
access keys. IAM lets you securely control access to AWS services and resources in your AWS account.
Note
To create access keys, you must have permissions to perform the required IAM actions. For
more information, see Granting IAM User Permission to Manage Password Policy and Credentials
in Using IAM.
Your secret key will no longer be available through the AWS Management Console; you will have
the only copy. Keep it confidential in order to protect your account, and never email it. Do not share
it outside your organization, even if an inquiry appears to come from AWS or Amazon.com. No one
who legitimately represents Amazon will ever ask you for your secret key.
Version v1.0.0
46
AWS SDK for Java Developer Guide
Tutorial: Advanced Amazon EC2 Spot Request
Management
Related topics
To enable access to the group, we create an ipPermission object with the IP address range set to the
CIDR representation of the subnet for the local computer; the "/10" suffix on the IP address indicates the
subnet for the specified IP address. We also configure the ipPermission object with the TCP protocol
and port 22 (SSH). The final step is to call ec2.authorizeSecurityGroupIngress with the name of
our security group and the ipPermission object.
(The following code is the same as what we used in the first tutorial.)
1
// Retrieves the credentials from an AWSCredentials.properties file.
AWSCredentials credentials = null;
try {
5 credentials = new PropertiesCredentials(
GettingStartedApp.class.getResourceAsStream("AwsCredentials.proper
ties"));
} catch (IOException e1) {
System.out.println("Credentials were not properly entered into AwsCreden
tials.properties.");
System.out.println(e1.getMessage());
10 System.exit(-1);
}
Version v1.0.0
47
AWS SDK for Java Developer Guide
Tutorial: Advanced Amazon EC2 Spot Request
Management
// Get the IP of the current host, so that we can limit the Security Group
// by default to the ip range associated with your subnet.
30 try {
InetAddress addr = InetAddress.getLocalHost();
// Get IP Address
ipAddr = addr.getHostAddress()+"/10";
35 } catch (UnknownHostException e) {
}
try {
// Authorize the ports to the used.
AuthorizeSecurityGroupIngressRequest ingressRequest =
55 new AuthorizeSecurityGroupIngressRequest("GettingStartedGroup",ip
Permissions);
ec2.authorizeSecurityGroupIngress(ingressRequest);
} catch (AmazonServiceException ase) {
// Ignore because this likely means the zone has already
// been authorized.
60 System.out.println(ase.getMessage());
}
You can view this entire code sample in the advanced.CreateSecurityGroupApp.java code sample.
Note you only need to run this application once to create a new security group.
You can also create the security group using the AWS Toolkit for Eclipse. Go to the toolkit documentation
for more information.
Let's start by creating a RequestSpotInstanceRequest object. The request object requires the number
of instances you want and the bid price. Additionally, we need to set the LaunchSpecification for the
request, which includes the instance type, AMI ID, and security group you want to use. After the request
is populated, we call the requestSpotInstances method on the AmazonEC2Client object. An example
of how to request a Spot instance follows.
(The following code is the same as what we used in the first tutorial.)
Version v1.0.0
48
AWS SDK for Java Developer Guide
Tutorial: Advanced Amazon EC2 Spot Request
Management
1
// Retrieves the credentials from an AWSCredentials.properties file.
AWSCredentials credentials = null;
try {
5 credentials = new PropertiesCredentials(
GettingStartedApp.class.getResourceAsStream("AwsCredentials.proper
ties"));
} catch (IOException e1) {
System.out.println("Credentials were not properly entered into AwsCre
dentials.properties.");
System.out.println(e1.getMessage());
10 System.exit(-1);
}
Version v1.0.0
49
AWS SDK for Java Developer Guide
Tutorial: Advanced Amazon EC2 Spot Request
Management
1
// Retrieves the credentials from an
// AWSCredentials.properties file.
AWSCredentials credentials = null;
5 try {
credentials = new PropertiesCredentials(
GettingStartedApp.class.getResourceAsStream("AwsCredentials.proper
ties"));
} catch (IOException e1) {
System.out.println("Credentials were not properly entered into AwsCre
dentials.properties.");
10 System.out.println(e1.getMessage());
System.exit(-1);
}
Version v1.0.0
50
AWS SDK for Java Developer Guide
Tutorial: Advanced Amazon EC2 Spot Request
Management
1
// Retrieves the credentials from an AWSCredentials.properties file.
AWSCredentials credentials = null;
try {
5 credentials = new PropertiesCredentials(
GettingStartedApp.class.getResourceAsStream("AwsCredentials.proper
ties"));
} catch (IOException e1) {
System.out.println("Credentials were not properly entered into AwsCre
dentials.properties.");
System.out.println(e1.getMessage());
10 System.exit(-1);
}
// Set the valid end time to be two minutes and two hours from now.
cal.add(Calendar.HOUR, 2);
30 requestRequest.setValidUntil(cal.getTime());
Version v1.0.0
51
AWS SDK for Java Developer Guide
Tutorial: Advanced Amazon EC2 Spot Request
Management
If you want to ensure your Spot instances are all launched and terminated together, then you have the
option to leverage a launch group. A launch group is a label that groups a set of bids together. All instances
in a launch group are started and terminated together. Note, if instances in a launch group have already
been fulfilled, there is no guarantee that new instances launched with the same launch group will also be
fulfilled. An example of how to set a Launch Group is shown in the following code example.
1
// Retrieves the credentials from an AWSCredentials.properties file.
AWSCredentials credentials = null;
try {
5 credentials = new PropertiesCredentials(
GettingStartedApp.class.getResourceAsStream("AwsCredentials.proper
ties"));
} catch (IOException e1) {
System.out.println("Credentials were not properly entered into AwsCre
dentials.properties.");
System.out.println(e1.getMessage());
10 System.exit(-1);
}
Version v1.0.0
52
AWS SDK for Java Developer Guide
Tutorial: Advanced Amazon EC2 Spot Request
Management
questRequest);
If you want to ensure that all instances within a request are launched in the same Availability Zone, and
you don't care which one, you can leverage Availability Zone groups. An Availability Zone group is a label
that groups a set of instances together in the same Availability Zone. All instances that share an Availability
Zone group and are fulfilled at the same time will start in the same Availability Zone. An example of how
to set an Availability Zone group follows.
1
// Retrieves the credentials from an AWSCredentials.properties file.
AWSCredentials credentials = null;
try {
5 credentials = new PropertiesCredentials(
GettingStartedApp.class.getResourceAsStream("AwsCredentials.proper
ties"));
} catch (IOException e1) {
System.out.println("Credentials were not properly entered into AwsCre
dentials.properties.");
System.out.println(e1.getMessage());
10 System.exit(-1);
}
Version v1.0.0
53
AWS SDK for Java Developer Guide
Tutorial: Advanced Amazon EC2 Spot Request
Management
You can specify an Availability Zone that you want for your Spot Instances. The following code example
shows you how to set an Availability Zone.
1
// Retrieves the credentials from an AWSCredentials.properties file.
AWSCredentials credentials = null;
try {
5 credentials = new PropertiesCredentials(
GettingStartedApp.class.getResourceAsStream("AwsCredentials.proper
ties"));
} catch (IOException e1) {
System.out.println("Credentials were not properly entered into AwsCre
dentials.properties.");
System.out.println(e1.getMessage());
10 System.exit(-1);
}
Lastly, you can specify a placement group if you are using High Performance Computing (HPC) Spot
instances, such as cluster compute instances or cluster GPU instances. Placement groups provide you
Version v1.0.0
54
AWS SDK for Java Developer Guide
Tutorial: Advanced Amazon EC2 Spot Request
Management
with lower latency and high-bandwidth connectivity between the instances. An example of how to set a
placement group follows.
1
// Retrieves the credentials from an AWSCredentials.properties file.
AWSCredentials credentials = null;
try {
5 credentials = new PropertiesCredentials(
GettingStartedApp.class.getResourceAsStream("AwsCredentials.proper
ties"));
} catch (IOException e1) {
System.out.println("Credentials were not properly entered into AwsCre
dentials.properties.");
System.out.println(e1.getMessage());
10 System.exit(-1);
}
All of the parameters shown in this section are optional. It is also important to realize that most of these
parameters—with the exception of whether your bid is one-time or persistent—can reduce the likelihood
of bid fulfillment. So, it is important to leverage these options only if you need them. All of the preceding
Version v1.0.0
55
AWS SDK for Java Developer Guide
Tutorial: Advanced Amazon EC2 Spot Request
Management
code examples are combined into one long code sample, which can be found in the
com.amazonaws.codesamples.advanced.InlineGettingStartedCodeSampleApp.java class.
In the added code, we create a BlockDeviceMapping object and set its associated Elastic Block Storage
(EBS) to an EBS object that we've configured to not be deleted if the Spot Instance is terminated. We
then add this BlockDeviceMapping to the ArrayList of mappings that we include in the launch
specification.
1
// Retrieves the credentials from an AWSCredentials.properties file.
AWSCredentials credentials = null;
try {
5 credentials = new PropertiesCredentials(
GettingStartedApp.class.getResourceAsStream("AwsCredentials.proper
ties"));
} catch (IOException e1) {
System.out.println("Credentials were not properly entered into AwsCre
dentials.properties.");
System.out.println(e1.getMessage());
10 System.exit(-1);
}
Version v1.0.0
56
AWS SDK for Java Developer Guide
Tutorial: Advanced Amazon EC2 Spot Request
Management
Assuming you wanted to re-attach this volume to your instance on startup, you can also use the block
device mapping settings. Alternatively, if you attached a non-root partition, you can specify the Amazon
EBS volumes you want to attach to your Spot instance after it resumes. You do this simply by specifying
a snapshot ID in your EbsBlockDevice and alternative device name in your BlockDeviceMapping
objects. By leveraging block device mappings, it can be easier to bootstrap your instance.
Using the root partition to checkpoint your critical data is a great way to manage the potential for interruption
of your instances. For more methods on managing the potential of interruption, please visit the Managing
Interruption video.
To add tags to your resources, you need to tag them after they have been requested. Specifically, you
must add a tag after a Spot request has been submitted or after the RunInstances call has been
performed. The following code example illustrates adding tags.
1
/*
* Copyright 2010-2011 Amazon.com, Inc. or its affiliates. All Rights Re
served.
*
5 * Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
10 *
Version v1.0.0
57
AWS SDK for Java Developer Guide
Tutorial: Advanced Amazon EC2 Spot Request
Management
import java.io.IOException;
import java.util.ArrayList;
20 import java.util.List;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.PropertiesCredentials;
25 import com.amazonaws.codesamples.getting_started.GettingStartedApp;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.AmazonEC2Client;
import com.amazonaws.services.ec2.model.CancelSpotInstanceRequestsRequest;
import com.amazonaws.services.ec2.model.CreateTagsRequest;
30 import com.amazonaws.services.ec2.model.DescribeSpotInstanceRequestsRequest;
import com.amazonaws.services.ec2.model.DescribeSpotInstanceRequestsResult;
import com.amazonaws.services.ec2.model.LaunchSpecification;
import com.amazonaws.services.ec2.model.RequestSpotInstancesRequest;
import com.amazonaws.services.ec2.model.RequestSpotInstancesResult;
35 import com.amazonaws.services.ec2.model.SpotInstanceRequest;
import com.amazonaws.services.ec2.model.Tag;
import com.amazonaws.services.ec2.model.TerminateInstancesRequest;
/**
40 * Welcome to your new AWS Java SDK based project!
*
* This class is meant as a starting point for your console-based application
that
* makes one or more calls to the AWS services supported by the Java SDK,
such as EC2,
* SimpleDB, and S3.
45 *
* In order to use the services in this sample, you need:
*
* - A valid Amazon Web Services account. You can register for AWS at:
* https://aws-portal.amazon.com/gp/aws/developer/registration/in
dex.html
50 *
* - Your account's Access Key ID and Secret Access Key:
* http://aws.amazon.com/security-credentials
*
* - A subscription to Amazon EC2. You can sign up for EC2 at:
55 * http://aws.amazon.com/ec2/
*
*/
Version v1.0.0
58
AWS SDK for Java Developer Guide
Tutorial: Advanced Amazon EC2 Spot Request
Management
//============================================================//
//======== Getting the Request ID from the Request ===========//
//============================================================//
110
// Call the RequestSpotInstance API.
RequestSpotInstancesResult requestResult = ec2.requestSpotInstances(re
questRequest);
List<SpotInstanceRequest> requestResponses = requestResult.getSpotIn
stanceRequests();
Version v1.0.0
59
AWS SDK for Java Developer Guide
Tutorial: Advanced Amazon EC2 Spot Request
Management
155 // Create a variable that will track whether there are any
// requests still in the open state.
boolean anyOpen;
// Initialize variables.
160 ArrayList<String> instanceIds = new ArrayList<String>();
do {
// Create the describeRequest with tall of the request
// id to monitor (e.g. that we started).
165 DescribeSpotInstanceRequestsRequest describeRequest = new DescribeS
potInstanceRequestsRequest();
describeRequest.setSpotInstanceRequestIds(spotInstanceRequestIds);
try {
// Retrieve all of the requests we want to monitor.
Version v1.0.0
60
AWS SDK for Java Developer Guide
Tutorial: Advanced Amazon EC2 Spot Request
Management
200 try {
// Sleep for 60 seconds.
Thread.sleep(60*1000);
} catch (Exception e) {
// Do nothing because it woke up early.
205 }
} while (anyOpen);
//========================================================//
//============= Tag the Spot Instances ====================//
210 //========================================================//
Version v1.0.0
61
AWS SDK for Java Developer Guide
Tutorial: Advanced Amazon EC2 Spot Request
Management
//===========================================================//
//================== Canceling the Request ==================//
235 //===========================================================//
try {
// Cancel requests.
CancelSpotInstanceRequestsRequest cancelRequest = new CancelSpotIn
stanceRequestsRequest(spotInstanceRequestIds);
240 ec2.cancelSpotInstanceRequests(cancelRequest);
} catch (AmazonServiceException e) {
// Write out any exceptions that may have occurred.
System.out.println("Error canceling instances");
System.out.println("Caught Exception: " + e.getMessage());
245 System.out.println("Reponse Status Code: " + e.getStatusCode());
System.out.println("Error Code: " + e.getErrorCode());
System.out.println("Request ID: " + e.getRequestId());
}
250 //===========================================================//
//=============== Terminating any Instances =================//
//===========================================================//
try {
// Terminate instances.
255 TerminateInstancesRequest terminateRequest = new TerminateInstances
Request(instanceIds);
ec2.terminateInstances(terminateRequest);
} catch (AmazonServiceException e) {
// Write out any exceptions that may have occurred.
System.out.println("Error terminating instances");
260 System.out.println("Caught Exception: " + e.getMessage());
System.out.println("Reponse Status Code: " + e.getStatusCode());
System.out.println("Error Code: " + e.getErrorCode());
System.out.println("Request ID: " + e.getRequestId());
}
265 } // main
}
Tags are a simple first step toward making it easier to manage your own cluster of instances. To read
more about tagging Amazon EC2 resources, go to Using Tags in the Amazon Elastic Compute Cloud
User Guide.
Congratulations! You've completed the Advanced Request Features tutorial for developing Spot Instance
software with the AWS SDK for Java.
Version v1.0.0
62
AWS SDK for Java Developer Guide
Amazon SWF
Topics
• Registering an Amazon SWF Domain Using the AWS SDK for Java (p. 63)
• Listing Amazon SWF Domains Using the AWS SDK for Java (p. 63)
1. Create a new RegisterDomainRequest object, providing it with at least the domain name and workflow
execution retention period (these parameters are both required).
2. Call the AmazonSimpleWorkflowClient.registerDomain method with the RegisterDomainRequest
object.
3. Catch the DomainAlreadyExistsException if the domain you're requesting already exists (in which
case, no action is usually required).
request.setWorkflowExecutionRetentionPeriodInDays("10");
try
{
swf.registerDomain(request);
}
catch (DomainAlreadyExistsException e)
{
System.out.println("Domain already exists!");
}
}
Version v1.0.0
63
AWS SDK for Java Developer Guide
Listing Amazon SWF Domains
1. Create a ListDomainsRequest object, and specify the registration status of the domains that you're
interested in—this is required.
2. Call AmazonSimpleWorkflowClient.listDomains with the ListDomainRequest object. Results are
provided in a DomainInfos object.
3. Call getDomainInfos on the returned object to get a list of DomainInfo objects.
4. Call getName on each DomainInfo object to get its name.
Version v1.0.0
64
AWS SDK for Java Developer Guide
Home Page for the AWS SDK for Java
Additional Resources
This section lists sources of additional information about using Amazon Web Services and the AWS SDK
for Java.
Topics
• Home Page for the AWS SDK for Java (p. 65)
• SDK Reference Documentation (p. 65)
• AWS Java Developer Blog (p. 65)
• AWS Forums (p. 66)
• AWS Toolkit for Eclipse (p. 66)
• SDK for Java Source Code and Samples (p. 66)
• AWS SDK for Java Code Samples (p. 66)
Version v1.0.0
65
AWS SDK for Java Developer Guide
AWS Forums
AWS Forums
Visit the AWS forums to ask questions or provide feedback about AWS. There is a forum specifically for
AWS development in Java as well as forums for individual services such as Amazon S3. AWS engineers
monitor the forums and respond to questions, feedback, and issues. You can subscribe to RSS feeds for
any of the forums.
For information about setting up and using the Toolkit for Eclipse, see the AWS Toolkit for Eclipse Getting
Started Guide.
• http://github.com/aws/aws-sdk-java
Included with the SDK code is the code for all of the samples that are packaged with the SDK. For more
information about the samples, including instructions for running the samples using the command-line or
the Eclipse IDE, see SDK for Java Code Samples (p. 66).
Topics
• List of Code Samples (p. 66)
• Building and Running the Samples using the Command Line (p. 67)
• Building and Running the Samples using the Eclipse IDE (p. 68)
Version v1.0.0
66
AWS SDK for Java Developer Guide
Building and Running the Samples using the Command
Line
Prerequisites
Before running any of the AWS SDK for Java samples, you will need to set your AWS credentials in the
environment or with the AWS CLI as specified in Set up your AWS Credentials for Use with the SDK for
Java (p. 6). The samples use the default credential provider chain whenever possible, so by setting your
credentials this way, you can avoid the risky practice of inserting your AWS credentials in files within the
source code directory (where they may inadvertently be checked in and shared publicly).
1. Change to the directory containing the sample's code. For example, if you are in the root directory
of the AWS SDK download and want to run the AwsConsoleApp sample, you would type:
cd samples/AwsConsoleApp
2. Build and run the sample with Ant. The default build target performs both actions, so you can just
enter:
Version v1.0.0
67
AWS SDK for Java Developer Guide
Building and Running the Samples using the Eclipse
IDE
ant
<step>
</step>
===========================================
===========================================
You have access to 4 Availability Zones.
1. Open Eclipse.
2. Create a new AWS Java project. In Eclipse, on the File menu, point to New, and then click Project.
The New Project wizard opens.
3. Expand the AWS category, then select AWS Java Project.
4. Click Next. The project settings page is displayed.
5. Enter a name in the Project Name box. The AWS SDK for Java Samples group displays the samples
available in the SDK, as described previously.
6. Select the samples you want to include in your project by selecting each check box.
7. Enter your AWS credentials. If you've already configured the AWS Toolkit for Eclipse with your
credentials, this is automatically filled in.
8. Click Finish. The project is created and added to the Project Explorer.
Version v1.0.0
68
AWS SDK for Java Developer Guide
Building and Running the Samples using the Eclipse
IDE
1. Select the sample .java file you want to run. For example, for the Amazon S3 sample, select
S3Sample.java.
2. Select Run from the Run menu.
1. Right-click the project in Project Explorer, point to Build Path, and then click Add Libraries.
2. Select AWS Java SDK, and then click Next and follow the remaining on-screen instructions.
Version v1.0.0
69
AWS SDK for Java Developer Guide
Document History
The following table describes the important changes since the last release of the AWS SDK for Java
Developer Guide.
Updated topics The introduction (p. 1) and getting started (p. 4) material May 14, 2014
has been heavily revised to support the new guide
structure and now includes guidance about how to Set up
your AWS Credentials for Use with the SDK for
Java (p. 6).
Updated topics The overall structure of the SDK for Java documentation May 9, 2014
has been simplified, and the Getting Started (p. 4) and
Additional Resources (p. 65) topics have been updated.
New topic This topic tracks recent changes to the AWS SDK for Java September 9, 2013
Developer Guide. It is intended as a companion to the
release notes history.
Version v1.0.0
70