Example usage for com.amazonaws.services.dynamodbv2.model ReturnValue ALL_NEW

List of usage examples for com.amazonaws.services.dynamodbv2.model ReturnValue ALL_NEW

Introduction

In this page you can find the example usage for com.amazonaws.services.dynamodbv2.model ReturnValue ALL_NEW.

Prototype

ReturnValue ALL_NEW

To view the source code for com.amazonaws.services.dynamodbv2.model ReturnValue ALL_NEW.

Click Source Link

Usage

From source file:com.amazon.janusgraph.diskstorage.dynamodb.DynamoDbSingleRowStore.java

License:Open Source License

@Override
public Collection<MutateWorker> createMutationWorkers(final Map<StaticBuffer, KCVMutation> mutationMap,
        final DynamoDbStoreTransaction txh) {

    final List<MutateWorker> workers = Lists.newLinkedList();

    for (Map.Entry<StaticBuffer, KCVMutation> entry : mutationMap.entrySet()) {
        final StaticBuffer hashKey = entry.getKey();
        final KCVMutation mutation = entry.getValue();

        final Map<String, AttributeValue> key = new ItemBuilder().hashKey(hashKey).build();

        // Using ExpectedAttributeValue map to handle large mutations in a single request
        // Large mutations would require multiple requests using expressions
        final Map<String, ExpectedAttributeValue> expected = new SingleExpectedAttributeValueBuilder(this, txh,
                hashKey).build(mutation);

        final Map<String, AttributeValueUpdate> attributeValueUpdates = new SingleUpdateBuilder()
                .deletions(mutation.getDeletions()).additions(mutation.getAdditions()).build();

        final UpdateItemRequest request = super.createUpdateItemRequest().withKey(key)
                .withReturnValues(ReturnValue.ALL_NEW).withAttributeUpdates(attributeValueUpdates)
                .withExpected(expected);

        final MutateWorker worker;
        if (mutation.hasDeletions() && !mutation.hasAdditions()) {
            worker = new SingleUpdateWithCleanupWorker(request, client.getDelegate());
        } else {/*from   w ww .  ja v a2  s .  c  o m*/
            worker = new UpdateItemWorker(request, client.getDelegate());
        }
        workers.add(worker);
    }
    return workers;
}

From source file:com.eho.dynamodb.DynamoDBConnection.java

public static UpdateItemOutcome update_resource(String resource) throws Exception {
    String id;//from  w  w w .ja  v a  2 s. c  om
    JSONObject json_resource = new JSONObject(resource);
    //does the resource have a primary key?
    if (json_resource.has(PRIMARY_KEY))//if it does not have a primary key, create one using uuid
        id = json_resource.getString(PRIMARY_KEY);
    else
        id = UUID.randomUUID().toString();

    DynamoDB dynamoDB = new DynamoDB(dynamoDBClient);
    Table table = dynamoDB.getTable(PATIENT_TABLE);

    //lets retreive based on the key. if key invalid (not assigned yet) nullis returned.
    Item retreived_item = table.getItem(PRIMARY_KEY, id);
    if (retreived_item == null)//if null instantiate it
    {
        retreived_item = new Item();
        retreived_item.withPrimaryKey(PRIMARY_KEY, id);
    }

    Integer new_version = retreived_item.getInt("version") + 1;
    retreived_item.withInt("version", new_version);
    String new_version_str = new_version.toString();

    UpdateItemSpec updateItemSpec = new UpdateItemSpec().withPrimaryKey(PRIMARY_KEY, id)
            .withUpdateExpression("SET " + new_version_str + "= :newval")
            .withValueMap(new ValueMap().withString(":newval", resource)).withReturnValues(ReturnValue.ALL_NEW);

    return table.updateItem(updateItemSpec);
}

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 v  a  2  s  . c o  m*/
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 w  w  .jav  a2 s  . c  om*/
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.rapid7.diskstorage.dynamodb.DynamoDBSingleRowStore.java

License:Open Source License

@Override
public Collection<MutateWorker> createMutationWorkers(Map<StaticBuffer, KCVMutation> mutationMap,
        DynamoDBStoreTransaction txh) {/*from ww  w . j a va  2  s . c o m*/

    List<MutateWorker> workers = Lists.newLinkedList();

    for (Map.Entry<StaticBuffer, KCVMutation> entry : mutationMap.entrySet()) {
        final StaticBuffer hashKey = entry.getKey();
        final KCVMutation mutation = entry.getValue();

        Map<String, AttributeValue> key = new ItemBuilder().hashKey(hashKey).build();

        // Using ExpectedAttributeValue map to handle large mutations in a single request
        // Large mutations would require multiple requests using expressions
        Map<String, ExpectedAttributeValue> expected = new SingleExpectedAttributeValueBuilder().key(hashKey)
                .transaction(txh).build(mutation);

        Map<String, AttributeValueUpdate> attributeValueUpdates = new SingleUpdateBuilder()
                .deletions(mutation.getDeletions()).additions(mutation.getAdditions()).build();

        UpdateItemRequest request = new UpdateItemRequest().withTableName(tableName).withKey(key)
                .withReturnValues(ReturnValue.ALL_NEW).withAttributeUpdates(attributeValueUpdates)
                .withExpected(expected).withReturnConsumedCapacity(ReturnConsumedCapacity.TOTAL);

        MutateWorker worker;
        if (mutation.hasDeletions() && !mutation.hasAdditions()) {
            worker = new SingleUpdateWithCleanupWorker(request, client.delegate());
        } else {
            worker = new UpdateItemWorker(request, client.delegate());
        }
        workers.add(worker);
    }
    return workers;
}

From source file:jp.classmethod.aws.dynamodb.DynamoDbRepository.java

License:Open Source License

@Override
public E update(K key, JsonPatch patch, boolean increment, long version) {
    final PrimaryKey pk = createKeys(key);
    Preconditions.checkNotNull(patch, "patch must not be null");
    Preconditions.checkArgument(version >= -1);

    ExpressionSpecBuilder builder = patch.get();

    //add a condition on item existence
    builder.withCondition(ExpressionSpecBuilder.attribute_exists(hashKeyName));
    //add update expression for incrementing the version
    if (increment && versionProperty != null) {
        builder.addUpdate(ExpressionSpecBuilder.N(versionProperty)
                .set(ExpressionSpecBuilder.N(versionProperty).plus(1L)));
    }/*from   w ww .j  av a  2  s . co  m*/
    //add version condition
    if (version >= 0) {
        Preconditions.checkState(versionProperty != null);
        builder.withCondition(ExpressionSpecBuilder.N(versionProperty).eq(version));
    }

    UpdateItemExpressionSpec spec = builder.buildForUpdate();
    Preconditions.checkArgument(false == Strings.isNullOrEmpty(spec.getUpdateExpression()),
            "patch may not be empty"); // TODO add mechanism to JSON patch to allow iterating over list of ops
    try {
        UpdateItemOutcome updateItemOutcome = table.updateItem(new UpdateItemSpec().withExpressionSpec(spec)
                .withPrimaryKey(pk).withReturnValues(ReturnValue.ALL_NEW));
        return convertItemToDomain(updateItemOutcome.getItem());
    } catch (AmazonClientException e) {
        throw processUpdateItemException(key, e);
    }
}

From source file:org.iternine.jeppetto.dao.dynamodb.DynamoDBQueryModelDAO.java

License:Apache License

private T updateItem(Map<String, AttributeValue> key, UpdateExpressionBuilder updateExpressionBuilder,
        ConditionExpressionBuilder conditionExpressionBuilder, ResultFromUpdate resultFromUpdate) {
    try {/*from w w  w .ja v  a  2s.co m*/
        UpdateItemRequest updateItemRequest = new UpdateItemRequest().withTableName(tableName).withKey(key)
                .withUpdateExpression(updateExpressionBuilder.getExpression());

        Map<String, AttributeValue> expressionAttributeValues;
        Map<String, String> expressionAttributeNames;

        if (conditionExpressionBuilder == null) {
            expressionAttributeValues = updateExpressionBuilder.getExpressionAttributeValues();
            expressionAttributeNames = updateExpressionBuilder.getExpressionAttributeNames();
        } else {
            expressionAttributeValues = new LinkedHashMap<String, AttributeValue>();
            expressionAttributeNames = new LinkedHashMap<String, String>();

            expressionAttributeValues.putAll(updateExpressionBuilder.getExpressionAttributeValues());
            expressionAttributeNames.putAll(updateExpressionBuilder.getExpressionAttributeNames());

            expressionAttributeValues.putAll(conditionExpressionBuilder.getExpressionAttributeValues());
            expressionAttributeNames.putAll(conditionExpressionBuilder.getExpressionAttributeNames());

            updateItemRequest.setConditionExpression(conditionExpressionBuilder.getExpression());
        }

        if (!expressionAttributeValues.isEmpty()) {
            updateItemRequest.setExpressionAttributeValues(expressionAttributeValues);
        }

        if (!expressionAttributeNames.isEmpty()) {
            updateItemRequest.setExpressionAttributeNames(expressionAttributeNames);
        }

        if (resultFromUpdate != ResultFromUpdate.ReturnNone) {
            updateItemRequest
                    .setReturnValues(resultFromUpdate == ResultFromUpdate.ReturnPreUpdate ? ReturnValue.ALL_OLD
                            : ReturnValue.ALL_NEW);

            UpdateItemResult result = dynamoDB.updateItem(updateItemRequest);

            T t = ConversionUtil.getObjectFromItem(result.getAttributes(), entityClass);

            ((DynamoDBPersistable) t).__markPersisted(dynamoDB.toString());

            return t;
        } else {
            dynamoDB.updateItem(updateItemRequest);

            return null;
        }
    } catch (Exception e) {
        throw new JeppettoException(e);
    }
}