List of usage examples for com.amazonaws.services.dynamodbv2.model UpdateItemRequest UpdateItemRequest
public UpdateItemRequest()
From source file:amazon.dynamodb.model.UpdatePointRequest.java
License:Open Source License
public UpdatePointRequest(GeoPunto geoPoint, AttributeValue rangeKeyValue) { updateItemRequest = new UpdateItemRequest(); updateItemRequest.setKey(new HashMap<String, AttributeValue>()); updateItemRequest.setAttributeUpdates(new HashMap<String, AttributeValueUpdate>()); this.geoPoint = geoPoint; this.rangeKeyValue = rangeKeyValue; }
From source file:awslabs.lab22.SolutionCode.java
License:Open Source License
@Override public void updateIfMatch(AmazonDynamoDBClient ddbClient, String tableName, String email, String company, String firstNameTarget, String firstNameMatch) { // Construct an UpdateItemRequest object for the specified table. UpdateItemRequest updateItemRequest = new UpdateItemRequest().withTableName(tableName); // Add KeyEntry elements to the request containing AttributeValue objects for the company name and email // address provided. updateItemRequest.addKeyEntry("Company", new AttributeValue().withS(company)); updateItemRequest.addKeyEntry("Email", new AttributeValue().withS(email)); // Add an ExpectedEntry element to the request containing an ExpectedAttributeValue object that contains // the value in the firstNameMatch parameter. updateItemRequest.addExpectedEntry("First", new ExpectedAttributeValue().withValue(new AttributeValue().withS(firstNameMatch))); // Add an AttributeUpdatesEntry element to the request containing an AttributeValueUpdate object that // contains the value in the firstNameTarget parameter updateItemRequest.addAttributeUpdatesEntry("First", new AttributeValueUpdate().withAction("PUT") .withValue(new AttributeValue().withS(firstNameTarget))); // Submit the request using the updateItem method of the ddbClient object. ddbClient.updateItem(updateItemRequest); }
From source file:com.amazon.janusgraph.diskstorage.dynamodb.AbstractDynamoDbStore.java
License:Open Source License
protected UpdateItemRequest createUpdateItemRequest() { return new UpdateItemRequest().withTableName(tableName) .withReturnConsumedCapacity(ReturnConsumedCapacity.TOTAL); }
From source file:com.clicktravel.infrastructure.persistence.aws.dynamodb.AbstractDynamoDbTemplate.java
License:Apache License
@Override public GeneratedKeyHolder generateKeys(final SequenceKeyGenerator sequenceKeyGenerator) { final String sequenceName = sequenceKeyGenerator.sequenceName(); if (!sequenceConfigurations.contains(sequenceName)) { throw new IllegalStateException("Unsupported sequence: " + sequenceName); }//from w w w.jav a 2 s. c om final Map<String, AttributeValue> key = new HashMap<>(); key.put(SEQUENCE_NAME_ATTRIBUTE, new AttributeValue(sequenceName)); final AttributeValueUpdate attributeValueUpdate = new AttributeValueUpdate().withAction("ADD") .withValue(new AttributeValue().withN(String.valueOf(sequenceKeyGenerator.keyCount()))); final Map<String, AttributeValueUpdate> attributeUpdates = new HashMap<>(); attributeUpdates.put(SEQUENCE_CURRENT_VALUE_ATTRIBUTE, attributeValueUpdate); final String tableName = databaseSchemaHolder.schemaName() + "-" + SEQUENCE_TABLE_NAME; final UpdateItemRequest updateItemRequest = new UpdateItemRequest().withTableName(tableName).withKey(key) .withAttributeUpdates(attributeUpdates).withReturnValues("UPDATED_NEW"); final UpdateItemResult updateItemResult; try { updateItemResult = amazonDynamoDbClient.updateItem(updateItemRequest); } catch (final AmazonServiceException e) { throw new PersistenceResourceFailureException( "Failure while attempting DynamoDb Update (generate keys)", e); } final Map<String, AttributeValue> attributes = updateItemResult.getAttributes(); final AttributeValue currentAttributeValue = attributes.get(SEQUENCE_CURRENT_VALUE_ATTRIBUTE); final Long currentValue = Long.valueOf(currentAttributeValue.getN()); final Collection<Long> keys = new ArrayList<>(); for (long i = currentValue - sequenceKeyGenerator.keyCount(); i < currentValue; i++) { keys.add(i + 1); } return new GeneratedKeyHolder(keys); }
From source file:com.clicktravel.infrastructure.persistence.aws.dynamodb.DynamoDbTemplate.java
License:Apache License
@Override public <T extends Item> T update(final T item, final PersistenceExceptionHandler<?>... persistenceExceptionHandlers) { final ItemConfiguration itemConfiguration = getItemConfiguration(item.getClass()); if (item.getVersion() == null) { return create(item); }//w w w . ja v a2 s. c om final Collection<PropertyDescriptor> updatedUniqueConstraintPropertyDescriptors = new HashSet<>(); T previousItem = null; if (!itemConfiguration.uniqueConstraints().isEmpty()) { final ItemId itemId = itemConfiguration.getItemId(item); previousItem = readWithOnlyUniqueConstraintProperties(itemId, itemConfiguration); final Collection<UniqueConstraint> updatedUniqueConstraints = getUpdatedUniqueConstraints(item, previousItem, itemConfiguration); for (final UniqueConstraint uniqueConstraint : updatedUniqueConstraints) { updatedUniqueConstraintPropertyDescriptors.add(uniqueConstraint.propertyDescriptor()); } createUniqueConstraintIndexes(item, itemConfiguration, updatedUniqueConstraintPropertyDescriptors); } final long newVersion = item.getVersion() + 1; final Map<String, AttributeValueUpdate> attributeMap = getAttributeUpdateMap(item, itemConfiguration, newVersion); final Map<String, ExpectedAttributeValue> expectedResults = new HashMap<>(); expectedResults.put(VERSION_ATTRIBUTE, new ExpectedAttributeValue(new AttributeValue().withN(String.valueOf(item.getVersion())))); final String tableName = databaseSchemaHolder.schemaName() + "." + itemConfiguration.tableName(); final Map<String, AttributeValue> key = generateKey(itemConfiguration.getItemId(item), itemConfiguration); for (final Entry<String, AttributeValue> entry : key.entrySet()) { attributeMap.remove(entry.getKey()); } final UpdateItemRequest itemRequest = new UpdateItemRequest().withTableName(tableName).withKey(key) .withAttributeUpdates(attributeMap).withExpected(expectedResults); boolean itemRequestSucceeded = false; try { amazonDynamoDbClient.updateItem(itemRequest); itemRequestSucceeded = true; } catch (final ConditionalCheckFailedException conditionalCheckFailedException) { throw new OptimisticLockException("Conflicting write detected while updating item"); } catch (final AmazonServiceException amazonServiceException) { throw new PersistenceResourceFailureException("Failure while attempting DynamoDb Put (update item)", amazonServiceException); } finally { if (!itemRequestSucceeded) { try { deleteUniqueConstraintIndexes(item, itemConfiguration, updatedUniqueConstraintPropertyDescriptors); } catch (final Exception deleteUniqueConstraintIndexesException) { logger.error(deleteUniqueConstraintIndexesException.getMessage(), deleteUniqueConstraintIndexesException); } } } deleteUniqueConstraintIndexes(previousItem, itemConfiguration, updatedUniqueConstraintPropertyDescriptors); item.setVersion(newVersion); return item; }
From source file:com.grublr.geo.model.UpdatePointRequest.java
License:Open Source License
public UpdatePointRequest(GeoPoint geoPoint, AttributeValue rangeKeyValue) { updateItemRequest = new UpdateItemRequest(); updateItemRequest.setKey(new HashMap<String, AttributeValue>()); updateItemRequest.setAttributeUpdates(new HashMap<String, AttributeValueUpdate>()); this.geoPoint = geoPoint; this.rangeKeyValue = rangeKeyValue; }
From source file:com.lvl6.mobsters.dynamo.setup.TransactionExamples.java
License:Open Source License
/** * This example shows an example of how to handle errors *///from w ww . j ava2s . c o m public void badRequest() throws RuntimeException { print("\n*** badRequest() ***\n"); // Create a "success" flag and set it to false. We'll roll back the transaction in a finally {} if this wasn't set to true by then. boolean success = false; Transaction t1 = txManager.newTransaction(); try { // Construct a request that we know DynamoDB will reject. Map<String, AttributeValue> key = new HashMap<String, AttributeValue>(); key.put(EXAMPLE_TABLE_HASH_KEY, new AttributeValue("Item1")); // You cannot "add" a String type attribute. This request will be rejected by DynamoDB. Map<String, AttributeValueUpdate> updates = new HashMap<String, AttributeValueUpdate>(); updates.put("Will this work?", new AttributeValueUpdate().withAction(AttributeAction.ADD) .withValue(new AttributeValue("Nope."))); // The transaction library will make the request here, so we actually see print("Making invalid request"); t1.updateItem(new UpdateItemRequest().withTableName(EXAMPLE_TABLE_NAME).withKey(key) .withAttributeUpdates(updates)); t1.commit(); success = true; throw new RuntimeException("This should NOT have happened (actually should have failed before commit)"); } catch (AmazonServiceException e) { print("Caught a ValidationException. This is what we expected. The transaction will be rolled back: " + e.getMessage()); // in a real application, you'll probably want to throw an exception to your caller } finally { if (!success) { print("The transaction didn't work, as expected. Rolling back."); // It can be a good idea to use a "success" flag in this way, to ensure that you roll back if you get any exceptions // from the transaction library, or from DynamoDB, or any from the DynamoDB client library. These 3 exception base classes are: // TransactionException, AmazonServiceException, or AmazonClientExeption. // If you forget to roll back, no problem - another transaction will come along and roll yours back eventually. try { t1.rollback(); } catch (TransactionException te) { } // ignore, but should probably log } try { t1.delete(); } catch (TransactionException te) { } // ignore, but should probably log } }
From source file:com.lvl6.mobsters.dynamo.setup.TransactionExamples.java
License:Open Source License
/** * This example shows that reads can be performed in a transaction, and read locks can be upgraded to write locks. *///ww w.j a va2 s . c om public void readThenWrite() { print("\n*** readThenWrite() ***\n"); Transaction t1 = txManager.newTransaction(); // Perform a GetItem request on the transaction print("Reading Item1"); Map<String, AttributeValue> key1 = new HashMap<String, AttributeValue>(); key1.put(EXAMPLE_TABLE_HASH_KEY, new AttributeValue("Item1")); Map<String, AttributeValue> item1 = t1 .getItem(new GetItemRequest().withKey(key1).withTableName(EXAMPLE_TABLE_NAME)).getItem(); print("Item1: " + item1); // Now call UpdateItem to add a new attribute. // Notice that the library supports ReturnValues in writes print("Updating Item1"); Map<String, AttributeValueUpdate> updates = new HashMap<String, AttributeValueUpdate>(); updates.put("Color", new AttributeValueUpdate().withAction(AttributeAction.PUT).withValue(new AttributeValue("Green"))); item1 = t1.updateItem(new UpdateItemRequest().withKey(key1).withTableName(EXAMPLE_TABLE_NAME) .withAttributeUpdates(updates).withReturnValues(ReturnValue.ALL_NEW)).getAttributes(); print("Item1 is now: " + item1); t1.commit(); t1.delete(); }
From source file:com.lvl6.mobsters.dynamo.setup.TransactionExamples.java
License:Open Source License
/** * Demonstrates the 3 levels of supported read isolation: Uncommitted, Committed, Locked *//* w ww. j a v a 2 s . co m*/ public void reading() { print("\n*** reading() ***\n"); // First, create a new transaction and update Item1, but don't commit yet. print("Starting a transaction to modify Item1"); Transaction t1 = txManager.newTransaction(); Map<String, AttributeValue> key1 = new HashMap<String, AttributeValue>(); key1.put(EXAMPLE_TABLE_HASH_KEY, new AttributeValue("Item1")); // Show the current value before any changes print("Getting the current value of Item1 within the transaction. This is the strongest form of read isolation."); print(" However, you can't trust the value you get back until your transaction commits!"); Map<String, AttributeValue> item1 = t1 .getItem(new GetItemRequest().withKey(key1).withTableName(EXAMPLE_TABLE_NAME)).getItem(); print("Before any changes, Item1 is: " + item1); // Show the current value before any changes print("Changing the Color of Item1, but not committing yet"); Map<String, AttributeValueUpdate> updates = new HashMap<String, AttributeValueUpdate>(); updates.put("Color", new AttributeValueUpdate().withAction(AttributeAction.PUT).withValue(new AttributeValue("Purple"))); item1 = t1.updateItem(new UpdateItemRequest().withKey(key1).withTableName(EXAMPLE_TABLE_NAME) .withAttributeUpdates(updates).withReturnValues(ReturnValue.ALL_NEW)).getAttributes(); print("Item1 is not yet committed, but if committed, will be: " + item1); // Perform an Uncommitted read print("The weakest (but cheapest) form of read is Uncommitted, where you can get back changes that aren't yet committed"); print(" And might be rolled back!"); item1 = txManager.getItem(new GetItemRequest() // Uncommitted reads happen on the transaction manager, not on a transaction. .withKey(key1).withTableName(EXAMPLE_TABLE_NAME), IsolationLevel.UNCOMMITTED).getItem(); // Note the isloationLevel print("The read, which could return changes that will be rolled back, returned: " + item1); // Perform a Committed read print("A strong read is Committed. This means that you are guaranteed to read only committed changes,"); print(" but not necessarily the *latest* committed change!"); item1 = txManager.getItem(new GetItemRequest() // Uncommitted reads happen on the transaction manager, not on a transaction. .withKey(key1).withTableName(EXAMPLE_TABLE_NAME), IsolationLevel.COMMITTED).getItem(); // Note the isloationLevel print("The read, which should return the same value of the original read, returned: " + item1); // Now start a new transaction and do a read, write, and read in it Transaction t2 = txManager.newTransaction(); print("Getting Item1, but this time under a new transaction t2"); item1 = t2.getItem(new GetItemRequest().withKey(key1).withTableName(EXAMPLE_TABLE_NAME)).getItem(); print("Before any changes, in t2, Item1 is: " + item1); print(" This just rolled back transaction t1! Notice that this is the same value as *before* t1!"); updates = new HashMap<String, AttributeValueUpdate>(); updates.put("Color", new AttributeValueUpdate().withAction(AttributeAction.PUT) .withValue(new AttributeValue("Magenta"))); print("Updating item1 again, but now under t2"); item1 = t2.updateItem(new UpdateItemRequest().withKey(key1).withTableName(EXAMPLE_TABLE_NAME) .withAttributeUpdates(updates).withReturnValues(ReturnValue.ALL_NEW)).getAttributes(); print("Item1 is not yet committed, but if committed, will now be: " + item1); print("Getting Item1, again, under lock in t2. Notice that the transaction library makes your write during this transaction visible to future reads."); item1 = t2.getItem(new GetItemRequest().withKey(key1).withTableName(EXAMPLE_TABLE_NAME)).getItem(); print("Under transaction t2, Item1 is going to be: " + item1); print("Committing t2"); t2.commit(); try { print("Committing t1 (this will fail because it was rolled back)"); t1.commit(); throw new RuntimeException("Should have been rolled back"); } catch (TransactionRolledBackException e) { print("t1 was rolled back as expected. I hope you didn't act on the GetItem you did under the lock in t1!"); } }
From source file:com.nandanu.halomama.controller.DynamoDBRouter.java
License:Open Source License
public void incrementSeen(String userNameTwitter, String createdDate) { UpdateItemRequest upd = new UpdateItemRequest(); upd.setTableName(Constants.TABLE_NAME); AttributeValue unt = new AttributeValue(); unt.setS(userNameTwitter);/* ww w.ja v a2 s . co m*/ AttributeValue cd = new AttributeValue(); cd.setS(createdDate); upd.addKeyEntry(Constants.TAG_USERNAME, unt); upd.addKeyEntry(Constants.TAG_CREATED_DATE, cd); AttributeValue s = new AttributeValue(); s.setN("1"); AttributeValueUpdate seen = new AttributeValueUpdate(s, AttributeAction.ADD); upd.addAttributeUpdatesEntry(Constants.TAG_SEEN, seen); dDBClient.updateItem(upd); }