use of com.amazonaws.services.dynamodbv2.AmazonDynamoDB in project aws-doc-sdk-examples by awsdocs.
the class DynamoDBMapperBatchWriteExample method testBatchWrite.
private static void testBatchWrite(DynamoDBMapper mapper) {
// Create Forum item to save
Forum forumItem = new Forum();
forumItem.name = "Test BatchWrite Forum";
forumItem.threads = 0;
forumItem.category = "Amazon Web Services";
// Create Thread item to save
Thread threadItem = new Thread();
threadItem.forumName = "AmazonDynamoDB";
threadItem.subject = "My sample question";
threadItem.message = "BatchWrite message";
List<String> tags = new ArrayList<String>();
tags.add("batch operations");
tags.add("write");
threadItem.tags = new HashSet<String>(tags);
// Load ProductCatalog item to delete
Book book3 = mapper.load(Book.class, 903);
List<Object> objectsToWrite = Arrays.asList(forumItem, threadItem);
List<Book> objectsToDelete = Arrays.asList(book3);
DynamoDBMapperConfig config = DynamoDBMapperConfig.builder().withSaveBehavior(DynamoDBMapperConfig.SaveBehavior.CLOBBER).build();
mapper.batchWrite(objectsToWrite, objectsToDelete, config);
}
use of com.amazonaws.services.dynamodbv2.AmazonDynamoDB in project aws-doc-sdk-examples by awsdocs.
the class UpdateItem method main.
public static void main(String[] args) {
final String USAGE = "\n" + "Usage:\n" + " UpdateItem <table> <name> <greeting>\n\n" + "Where:\n" + " table - the table to put the item in.\n" + " name - a name to update in the table. The name must exist,\n" + " or an error will result.\n" + "Additional fields can be specified by appending them to the end of the\n" + "input.\n\n" + "Examples:\n" + " UpdateItem SiteColors text default=000000 bold=b22222\n" + " UpdateItem SiteColors background default=eeeeee code=d3d3d3\n\n";
if (args.length < 3) {
System.out.println(USAGE);
System.exit(1);
}
String table_name = args[0];
String name = args[1];
ArrayList<String[]> extra_fields = new ArrayList<String[]>();
// any additional args (fields to add or update)?
for (int x = 2; x < args.length; x++) {
String[] fields = args[x].split("=", 2);
if (fields.length == 2) {
extra_fields.add(fields);
} else {
System.out.format("Invalid argument: %s\n", args[x]);
System.out.println(USAGE);
System.exit(1);
}
}
System.out.format("Updating \"%s\" in %s\n", name, table_name);
if (extra_fields.size() > 0) {
System.out.println("Additional fields:");
for (String[] field : extra_fields) {
System.out.format(" %s: %s\n", field[0], field[1]);
}
}
HashMap<String, AttributeValue> item_key = new HashMap<String, AttributeValue>();
item_key.put("Name", new AttributeValue(name));
HashMap<String, AttributeValueUpdate> updated_values = new HashMap<String, AttributeValueUpdate>();
for (String[] field : extra_fields) {
updated_values.put(field[0], new AttributeValueUpdate(new AttributeValue(field[1]), AttributeAction.PUT));
}
final AmazonDynamoDB ddb = AmazonDynamoDBClientBuilder.defaultClient();
try {
ddb.updateItem(table_name, item_key, updated_values);
} catch (ResourceNotFoundException e) {
System.err.println(e.getMessage());
System.exit(1);
} catch (AmazonServiceException e) {
System.err.println(e.getMessage());
System.exit(1);
}
System.out.println("Done!");
}
use of com.amazonaws.services.dynamodbv2.AmazonDynamoDB in project aws-doc-sdk-examples by awsdocs.
the class StreamsLowLevelDemo method main.
public static void main(String[] args) throws InterruptedException {
AmazonDynamoDB dynamoDBClient = AmazonDynamoDBClientBuilder.standard().withRegion(Regions.US_EAST_2).withCredentials(new DefaultAWSCredentialsProviderChain()).build();
AmazonDynamoDBStreams streamsClient = AmazonDynamoDBStreamsClientBuilder.standard().withRegion(Regions.US_EAST_2).withCredentials(new DefaultAWSCredentialsProviderChain()).build();
// Create a table, with a stream enabled
String tableName = "TestTableForStreams";
ArrayList<AttributeDefinition> attributeDefinitions = new ArrayList<>(Arrays.asList(new AttributeDefinition().withAttributeName("Id").withAttributeType("N")));
ArrayList<KeySchemaElement> keySchema = new ArrayList<>(Arrays.asList(new KeySchemaElement().withAttributeName("Id").withKeyType(// Partition key
KeyType.HASH)));
StreamSpecification streamSpecification = new StreamSpecification().withStreamEnabled(true).withStreamViewType(StreamViewType.NEW_AND_OLD_IMAGES);
CreateTableRequest createTableRequest = new CreateTableRequest().withTableName(tableName).withKeySchema(keySchema).withAttributeDefinitions(attributeDefinitions).withProvisionedThroughput(new ProvisionedThroughput().withReadCapacityUnits(10L).withWriteCapacityUnits(10L)).withStreamSpecification(streamSpecification);
System.out.println("Issuing CreateTable request for " + tableName);
dynamoDBClient.createTable(createTableRequest);
System.out.println("Waiting for " + tableName + " to be created...");
try {
TableUtils.waitUntilActive(dynamoDBClient, tableName);
} catch (AmazonClientException e) {
e.printStackTrace();
}
// Print the stream settings for the table
DescribeTableResult describeTableResult = dynamoDBClient.describeTable(tableName);
String streamArn = describeTableResult.getTable().getLatestStreamArn();
System.out.println("Current stream ARN for " + tableName + ": " + describeTableResult.getTable().getLatestStreamArn());
StreamSpecification streamSpec = describeTableResult.getTable().getStreamSpecification();
System.out.println("Stream enabled: " + streamSpec.getStreamEnabled());
System.out.println("Update view type: " + streamSpec.getStreamViewType());
System.out.println();
// Generate write activity in the table
System.out.println("Performing write activities on " + tableName);
int maxItemCount = 100;
for (Integer i = 1; i <= maxItemCount; i++) {
System.out.println("Processing item " + i + " of " + maxItemCount);
// Write a new item
Map<String, AttributeValue> item = new HashMap<>();
item.put("Id", new AttributeValue().withN(i.toString()));
item.put("Message", new AttributeValue().withS("New item!"));
dynamoDBClient.putItem(tableName, item);
// Update the item
Map<String, AttributeValue> key = new HashMap<>();
key.put("Id", new AttributeValue().withN(i.toString()));
Map<String, AttributeValueUpdate> attributeUpdates = new HashMap<>();
attributeUpdates.put("Message", new AttributeValueUpdate().withAction(AttributeAction.PUT).withValue(new AttributeValue().withS("This item has changed")));
dynamoDBClient.updateItem(tableName, key, attributeUpdates);
// Delete the item
dynamoDBClient.deleteItem(tableName, key);
}
// Get all the shard IDs from the stream. Note that DescribeStream returns
// the shard IDs one page at a time.
String lastEvaluatedShardId = null;
do {
DescribeStreamResult describeStreamResult = streamsClient.describeStream(new DescribeStreamRequest().withStreamArn(streamArn).withExclusiveStartShardId(lastEvaluatedShardId));
List<Shard> shards = describeStreamResult.getStreamDescription().getShards();
for (Shard shard : shards) {
String shardId = shard.getShardId();
System.out.println("Shard: " + shard);
// Get an iterator for the current shard
GetShardIteratorRequest getShardIteratorRequest = new GetShardIteratorRequest().withStreamArn(streamArn).withShardId(shardId).withShardIteratorType(ShardIteratorType.TRIM_HORIZON);
GetShardIteratorResult getShardIteratorResult = streamsClient.getShardIterator(getShardIteratorRequest);
String currentShardIter = getShardIteratorResult.getShardIterator();
// Shard iterator is not null until the Shard is sealed (marked as READ_ONLY).
// To prevent running the loop until the Shard is sealed, which will be on average
// 4 hours, we process only the items that were written into DynamoDB and then exit.
int processedRecordCount = 0;
while (currentShardIter != null && processedRecordCount < maxItemCount) {
System.out.println(" Shard iterator: " + currentShardIter.substring(380));
// Use the shard iterator to read the stream records
GetRecordsResult getRecordsResult = streamsClient.getRecords(new GetRecordsRequest().withShardIterator(currentShardIter));
List<Record> records = getRecordsResult.getRecords();
for (Record record : records) {
System.out.println(" " + record.getDynamodb());
}
processedRecordCount += records.size();
currentShardIter = getRecordsResult.getNextShardIterator();
}
}
// If LastEvaluatedShardId is set, then there is
// at least one more page of shard IDs to retrieve
lastEvaluatedShardId = describeStreamResult.getStreamDescription().getLastEvaluatedShardId();
} while (lastEvaluatedShardId != null);
// Delete the table
System.out.println("Deleting the table...");
dynamoDBClient.deleteTable(tableName);
System.out.println("Demo complete");
}
use of com.amazonaws.services.dynamodbv2.AmazonDynamoDB in project aws-doc-sdk-examples by awsdocs.
the class MoviesItemOps05 method main.
public static void main(String[] args) throws Exception {
AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration("http://localhost:8000", "us-west-2")).build();
DynamoDB dynamoDB = new DynamoDB(client);
Table table = dynamoDB.getTable("Movies");
int year = 2015;
String title = "The Big New Movie";
UpdateItemSpec updateItemSpec = new UpdateItemSpec().withPrimaryKey(new PrimaryKey("year", year, "title", title)).withUpdateExpression("remove info.actors[0]").withConditionExpression("size(info.actors) > :num").withValueMap(new ValueMap().withNumber(":num", 3)).withReturnValues(ReturnValue.UPDATED_NEW);
// Conditional update (we expect this to fail)
try {
System.out.println("Attempting a conditional update...");
UpdateItemOutcome outcome = table.updateItem(updateItemSpec);
System.out.println("UpdateItem succeeded:\n" + outcome.getItem().toJSONPretty());
} catch (Exception e) {
System.err.println("Unable to update item: " + year + " " + title);
System.err.println(e.getMessage());
}
}
use of com.amazonaws.services.dynamodbv2.AmazonDynamoDB in project aws-doc-sdk-examples by awsdocs.
the class MoviesScan method main.
public static void main(String[] args) throws Exception {
AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration("http://localhost:8000", "us-west-2")).build();
DynamoDB dynamoDB = new DynamoDB(client);
Table table = dynamoDB.getTable("Movies");
ScanSpec scanSpec = new ScanSpec().withProjectionExpression("#yr, title, info.rating").withFilterExpression("#yr between :start_yr and :end_yr").withNameMap(new NameMap().with("#yr", "year")).withValueMap(new ValueMap().withNumber(":start_yr", 1950).withNumber(":end_yr", 1959));
try {
ItemCollection<ScanOutcome> items = table.scan(scanSpec);
Iterator<Item> iter = items.iterator();
while (iter.hasNext()) {
Item item = iter.next();
System.out.println(item.toString());
}
} catch (Exception e) {
System.err.println("Unable to scan the table:");
System.err.println(e.getMessage());
}
}
Aggregations