You are on page 1of 4

/*

* Copyright 2012 Amazon.com, Inc. or its affiliates. All Rights Reserved.


*
* 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
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
import java.util.HashMap;
import java.util.Map;
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import

com.amazonaws.AmazonClientException;
com.amazonaws.AmazonServiceException;
com.amazonaws.auth.AWSCredentials;
com.amazonaws.auth.PropertiesCredentials;
com.amazonaws.services.dynamodb.AmazonDynamoDBClient;
com.amazonaws.services.dynamodb.model.AttributeValue;
com.amazonaws.services.dynamodb.model.ComparisonOperator;
com.amazonaws.services.dynamodb.model.Condition;
com.amazonaws.services.dynamodb.model.CreateTableRequest;
com.amazonaws.services.dynamodb.model.DescribeTableRequest;
com.amazonaws.services.dynamodb.model.KeySchema;
com.amazonaws.services.dynamodb.model.KeySchemaElement;
com.amazonaws.services.dynamodb.model.ProvisionedThroughput;
com.amazonaws.services.dynamodb.model.PutItemRequest;
com.amazonaws.services.dynamodb.model.PutItemResult;
com.amazonaws.services.dynamodb.model.ScanRequest;
com.amazonaws.services.dynamodb.model.ScanResult;
com.amazonaws.services.dynamodb.model.TableDescription;
com.amazonaws.services.dynamodb.model.TableStatus;

/**
* This sample demonstrates how to perform a few simple operations with the
* Amazon DynamoDB service.
*/
public class AmazonDynamoDBSample {
/*
* Important: Be sure to fill in your AWS access credentials in the
*
AwsCredentials.properties file before you try to run this
*
sample.
* http://aws.amazon.com/security-credentials
*/
static AmazonDynamoDBClient dynamoDB;
/**
* The only information needed to create a client are security credentials
* consisting of the AWS Access Key ID and Secret Access Key. All other
* configuration, such as the service endpoints, are performed
* automatically. Client parameters, such as proxies, can be specified in an
* optional ClientConfiguration object when constructing a client.
*
* @see com.amazonaws.auth.BasicAWSCredentials

* @see com.amazonaws.auth.PropertiesCredentials
* @see com.amazonaws.ClientConfiguration
*/
private static void init() throws Exception {
AWSCredentials credentials = new PropertiesCredentials(
AmazonDynamoDBSample.class.getResourceAsStream("AwsCredentials.p
roperties"));
dynamoDB = new AmazonDynamoDBClient(credentials);
}
public static void main(String[] args) throws Exception {
init();
try {
String tableName = "my-favorite-movies-table";
// Create a table with a primary key named 'name', which holds a str
ing
CreateTableRequest createTableRequest = new CreateTableRequest().wit
hTableName(tableName)
.withKeySchema(new KeySchema(new KeySchemaElement().withAttribut
eName("name").withAttributeType("S")))
.withProvisionedThroughput(new ProvisionedThroughput().withReadC
apacityUnits(10L).withWriteCapacityUnits(10L));
TableDescription createdTableDescription = dynamoDB.createTable(crea
teTableRequest).getTableDescription();
System.out.println("Created Table: " + createdTableDescription);
// Wait for it to become active
waitForTableToBecomeAvailable(tableName);
// Describe our new table
DescribeTableRequest describeTableRequest = new DescribeTableRequest
().withTableName(tableName);
TableDescription tableDescription = dynamoDB.describeTable(describeT
ableRequest).getTable();
System.out.println("Table Description: " + tableDescription);
// Add an item
Map<String, AttributeValue> item = newItem("Bill & Ted's Excellent A
dventure", 1989, "****", "James", "Sara");
PutItemRequest putItemRequest = new PutItemRequest(tableName, item);
PutItemResult putItemResult = dynamoDB.putItem(putItemRequest);
System.out.println("Result: " + putItemResult);
// Add another item
item = newItem("Airplane", 1980, "*****", "James", "Billy Bob");
putItemRequest = new PutItemRequest(tableName, item);
putItemResult = dynamoDB.putItem(putItemRequest);
System.out.println("Result: " + putItemResult);
// Scan items for movies with a year attribute greater than 1985
HashMap<String, Condition> scanFilter = new HashMap<String, Conditio
n>();
Condition condition = new Condition()
.withComparisonOperator(ComparisonOperator.GT.toString())
.withAttributeValueList(new AttributeValue().withN("1985"));
scanFilter.put("year", condition);

ScanRequest scanRequest = new ScanRequest(tableName).withScanFilter(


scanFilter);
ScanResult scanResult = dynamoDB.scan(scanRequest);
System.out.println("Result: " + scanResult);
} catch (AmazonServiceException ase) {
System.out.println("Caught an AmazonServiceException, which means yo
ur request made it "
+ "to AWS, but was rejected with an error response for some
reason.");
System.out.println("Error Message:
" + ase.getMessage());
System.out.println("HTTP Status Code: " + ase.getStatusCode());
System.out.println("AWS Error Code: " + ase.getErrorCode());
System.out.println("Error Type:
" + ase.getErrorType());
System.out.println("Request ID:
" + ase.getRequestId());
} catch (AmazonClientException ace) {
System.out.println("Caught an AmazonClientException, which means the
client encountered "
+ "a serious internal problem while trying to communicate wi
th AWS, "
+ "such as not being able to access the network.");
System.out.println("Error Message: " + ace.getMessage());
}
}
private static Map<String, AttributeValue> newItem(String name, int year, St
ring rating, String... fans) {
Map<String, AttributeValue> item = new HashMap<String, AttributeValue>()
;
item.put("name", new AttributeValue(name));
item.put("year", new AttributeValue().withN(Integer.toString(year)));
item.put("rating", new AttributeValue(rating));
item.put("fans", new AttributeValue().withSS(fans));
return item;
}
private static void waitForTableToBecomeAvailable(String tableName) {
System.out.println("Waiting for " + tableName + " to become ACTIVE...");
long startTime = System.currentTimeMillis();
long endTime = startTime + (10 * 60 * 1000);
while (System.currentTimeMillis() < endTime) {
try {Thread.sleep(1000 * 20);} catch (Exception e) {}
try {
DescribeTableRequest request = new DescribeTableRequest().withTa
bleName(tableName);
TableDescription tableDescription = dynamoDB.describeTable(reque
st).getTable();
String tableStatus = tableDescription.getTableStatus();
System.out.println(" - current state: " + tableStatus);
if (tableStatus.equals(TableStatus.ACTIVE.toString())) return;
} catch (AmazonServiceException ase) {
if (ase.getErrorCode().equalsIgnoreCase("ResourceNotFoundExcepti
on") == false) throw ase;
}
}
throw new RuntimeException("Table " + tableName + " never went active");
}

You might also like