Java Code Examples for com.amazonaws.services.dynamodbv2.model.ReturnValue

The following examples show how to use com.amazonaws.services.dynamodbv2.model.ReturnValue. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
private static void updateAddNewAttribute() {
    try {
        HashMap<String, AttributeValue> key = new HashMap<String, AttributeValue>();
        key.put("Id", new AttributeValue().withN("121"));

        Map<String, AttributeValue> expressionAttributeValues = new HashMap<String, AttributeValue>();
        expressionAttributeValues.put(":val1", new AttributeValue().withS("Some value"));

        ReturnValue returnValues = ReturnValue.ALL_NEW;

        UpdateItemRequest updateItemRequest = new UpdateItemRequest().withTableName(tableName).withKey(key)
            .withUpdateExpression("set NewAttribute = :val1")
            .withExpressionAttributeValues(expressionAttributeValues).withReturnValues(returnValues);

        UpdateItemResult result = client.updateItem(updateItemRequest);

        // Check the response.
        System.out.println("Printing item after adding new attribute...");
        printItem(result.getAttributes());

    }
    catch (AmazonServiceException ase) {
        System.err.println("Failed to add new attribute in " + tableName);
        System.err.println(ase.getMessage());
    }
}
 
Example 2
private static void updateAddNewAttribute() {
    Table table = dynamoDB.getTable(tableName);

    try {

        UpdateItemSpec updateItemSpec = new UpdateItemSpec().withPrimaryKey("Id", 121)
            .withUpdateExpression("set #na = :val1").withNameMap(new NameMap().with("#na", "NewAttribute"))
            .withValueMap(new ValueMap().withString(":val1", "Some value")).withReturnValues(ReturnValue.ALL_NEW);

        UpdateItemOutcome outcome = table.updateItem(updateItemSpec);

        // Check the response.
        System.out.println("Printing item after adding new attribute...");
        System.out.println(outcome.getItem().toJSONPretty());

    }
    catch (Exception e) {
        System.err.println("Failed to add new attribute in " + tableName);
        System.err.println(e.getMessage());
    }
}
 
Example 3
private static void updateMultipleAttributes() {

        Table table = dynamoDB.getTable(tableName);

        try {

            UpdateItemSpec updateItemSpec = new UpdateItemSpec().withPrimaryKey("Id", 120)
                .withUpdateExpression("add #a :val1 set #na=:val2")
                .withNameMap(new NameMap().with("#a", "Authors").with("#na", "NewAttribute"))
                .withValueMap(
                    new ValueMap().withStringSet(":val1", "Author YY", "Author ZZ").withString(":val2", "someValue"))
                .withReturnValues(ReturnValue.ALL_NEW);

            UpdateItemOutcome outcome = table.updateItem(updateItemSpec);

            // Check the response.
            System.out.println("Printing item after multiple attribute update...");
            System.out.println(outcome.getItem().toJSONPretty());

        }
        catch (Exception e) {
            System.err.println("Failed to update multiple attributes in " + tableName);
            System.err.println(e.getMessage());

        }
    }
 
Example 4
private static void updateExistingAttributeConditionally() {

        Table table = dynamoDB.getTable(tableName);

        try {

            // Specify the desired price (25.00) and also the condition (price =
            // 20.00)

            UpdateItemSpec updateItemSpec = new UpdateItemSpec().withPrimaryKey("Id", 120)
                .withReturnValues(ReturnValue.ALL_NEW).withUpdateExpression("set #p = :val1")
                .withConditionExpression("#p = :val2").withNameMap(new NameMap().with("#p", "Price"))
                .withValueMap(new ValueMap().withNumber(":val1", 25).withNumber(":val2", 20));

            UpdateItemOutcome outcome = table.updateItem(updateItemSpec);

            // Check the response.
            System.out.println("Printing item after conditional update to new attribute...");
            System.out.println(outcome.getItem().toJSONPretty());

        }
        catch (Exception e) {
            System.err.println("Error updating item in " + tableName);
            System.err.println(e.getMessage());
        }
    }
 
Example 5
private static void deleteItem() {

        Table table = dynamoDB.getTable(tableName);

        try {

            DeleteItemSpec deleteItemSpec = new DeleteItemSpec().withPrimaryKey("Id", 120)
                .withConditionExpression("#ip = :val").withNameMap(new NameMap().with("#ip", "InPublication"))
                .withValueMap(new ValueMap().withBoolean(":val", false)).withReturnValues(ReturnValue.ALL_OLD);

            DeleteItemOutcome outcome = table.deleteItem(deleteItemSpec);

            // Check the response.
            System.out.println("Printing item that was deleted...");
            System.out.println(outcome.getItem().toJSONPretty());

        }
        catch (Exception e) {
            System.err.println("Error deleting item in " + tableName);
            System.err.println(e.getMessage());
        }
    }
 
Example 6
Source Project: athenz   Source File: DynamoDBCertRecordStoreConnection.java    License: Apache License 2.0 6 votes vote down vote up
private List<X509CertRecord> updateLastNotified(String lastNotifiedServer, long lastNotifiedTime, List<Item> items) {
    long yesterday = lastNotifiedTime - TimeUnit.DAYS.toMillis(1);

    List<X509CertRecord> updatedRecords = new ArrayList<>();
    for (Item item : items) {
        // For each item, update lastNotifiedTime and lastNotifiedServer (unless they were already updated)
        UpdateItemSpec updateItemSpec = new UpdateItemSpec().withPrimaryKey(KEY_PRIMARY, item.getString(KEY_PRIMARY))
                .withReturnValues(ReturnValue.ALL_NEW)
                .withUpdateExpression("set lastNotifiedTime = :lastNotifiedTimeVal, lastNotifiedServer = :lastNotifiedServerVal")
                .withConditionExpression("attribute_not_exists(lastNotifiedTime) OR lastNotifiedTime < :v_yesterday")
                .withValueMap(new ValueMap()
                        .with(":lastNotifiedTimeVal", lastNotifiedTime)
                        .withNumber(":v_yesterday", yesterday)
                        .withString(":lastNotifiedServerVal", lastNotifiedServer));

        Item updatedItem = table.updateItem(updateItemSpec).getItem();

        if (isRecordUpdatedWithNotificationTimeAndServer(lastNotifiedServer, lastNotifiedTime, updatedItem)) {
            X509CertRecord x509CertRecord = itemToX509CertRecord(updatedItem);
            updatedRecords.add(x509CertRecord);
        }
    }

    return updatedRecords;
}
 
Example 7
private static void deleteItem() {

        Table table = dynamoDB.getTable(tableName);

        try {

            DeleteItemSpec deleteItemSpec = new DeleteItemSpec()
            .withPrimaryKey("Id", 120)
            .withConditionExpression("#ip = :val")
            .withNameMap(new NameMap()
                .with("#ip", "InPublication"))
            .withValueMap(new ValueMap()
            .withBoolean(":val", false))
            .withReturnValues(ReturnValue.ALL_OLD);

            DeleteItemOutcome outcome = table.deleteItem(deleteItemSpec);

            // Check the response.
            System.out.println("Printing item that was deleted...");
            System.out.println(outcome.getItem().toJSONPretty());

        } catch (Exception e) {
            System.err.println("Error deleting item in " + tableName);
            System.err.println(e.getMessage());
        }
    }
 
Example 8
@Before
public void setup() {
    Transaction t = manager.newTransaction();
    hashItem0 = new ExampleHashKeyItem();
    hashItem0.setId(UUID.randomUUID().toString());
    hashItem0.setSomething("val");
    hashItem0.setSomeSet(new HashSet<String>(Arrays.asList("one", "two")));
    t.save(hashItem0);
    key0 = newKey(INTEG_HASH_TABLE_NAME);
    item0 = new HashMap<String, AttributeValue>(key0);
    item0.put("s_someattr", new AttributeValue("val"));
    item0.put("ss_otherattr", new AttributeValue().withSS("one", "two"));
    Map<String, AttributeValue> putResult = t.putItem(new PutItemRequest()
        .withTableName(INTEG_HASH_TABLE_NAME)
        .withItem(item0)
        .withReturnValues(ReturnValue.ALL_OLD)).getAttributes();
    assertNull(putResult);
    t.commit();
    assertItemNotLocked(INTEG_HASH_TABLE_NAME, key0, item0, true);
    assertItemNotLocked(INTEG_HASH_TABLE_NAME, hashItem0.getKey(), hashItem0.getExpectedValues(), true);
}
 
Example 9
@Before
public void setup() {
    dynamodb.reset();
    Transaction t = manager.newTransaction();
    key0 = newKey(INTEG_HASH_TABLE_NAME);
    item0 = new HashMap<String, AttributeValue>(key0);
    item0.put("s_someattr", new AttributeValue("val"));
    item0.put("ss_otherattr", new AttributeValue().withSS("one", "two"));
    Map<String, AttributeValue> putResult = t.putItem(new PutItemRequest()
        .withTableName(INTEG_HASH_TABLE_NAME)
        .withItem(item0)
        .withReturnValues(ReturnValue.ALL_OLD)).getAttributes();
    assertNull(putResult);
    t.commit();
    assertItemNotLocked(INTEG_HASH_TABLE_NAME, key0, item0, true);
}
 
Example 10
@Test
public void getItemAfterPutItemInsert() {
    Transaction t1 = manager.newTransaction();
    Map<String, AttributeValue> key1 = newKey(INTEG_HASH_TABLE_NAME);
    Map<String, AttributeValue> item1 = new HashMap<String, AttributeValue>(key1);
    item1.put("asdf", new AttributeValue("wef"));
    
    Map<String, AttributeValue> getResult1 = t1.getItem(new GetItemRequest().withTableName(INTEG_HASH_TABLE_NAME).withKey(key1)).getItem();
    assertNull(getResult1);
    assertItemLocked(INTEG_HASH_TABLE_NAME, key1, t1.getId(), true, false);
    
    Map<String, AttributeValue> putResult1 = t1.putItem(new PutItemRequest()
        .withTableName(INTEG_HASH_TABLE_NAME)
        .withItem(item1)
        .withReturnValues(ReturnValue.ALL_OLD)).getAttributes();
    assertItemLocked(INTEG_HASH_TABLE_NAME, key1, item1, t1.getId(), true, true);
    assertNull(putResult1);
    
    Map<String, AttributeValue> getResult2 = t1.getItem(new GetItemRequest().withTableName(INTEG_HASH_TABLE_NAME).withKey(key1)).getItem();
    assertEquals(getResult2, item1);
    assertItemLocked(INTEG_HASH_TABLE_NAME, key1, item1, t1.getId(), true, true);
    
    t1.commit();
    
    assertItemNotLocked(INTEG_HASH_TABLE_NAME, key1, item1, true);
}
 
Example 11
@Test
public void getItemAfterPutItemOverwrite() {
    Transaction t1 = manager.newTransaction();
    Map<String, AttributeValue> item1 = new HashMap<String, AttributeValue>(item0);
    item1.put("asdf", new AttributeValue("wef"));
    
    Map<String, AttributeValue> getResult1 = t1.getItem(new GetItemRequest().withTableName(INTEG_HASH_TABLE_NAME).withKey(key0)).getItem();
    assertEquals(getResult1, item0);
    assertItemLocked(INTEG_HASH_TABLE_NAME, key0, item0, t1.getId(), false, false);
    
    Map<String, AttributeValue> putResult1 = t1.putItem(new PutItemRequest()
        .withTableName(INTEG_HASH_TABLE_NAME)
        .withItem(item1)
        .withReturnValues(ReturnValue.ALL_OLD)).getAttributes();
    assertItemLocked(INTEG_HASH_TABLE_NAME, key0, item1, t1.getId(), false, true);
    assertEquals(putResult1, item0);
    
    Map<String, AttributeValue> getResult2 = t1.getItem(new GetItemRequest().withTableName(INTEG_HASH_TABLE_NAME).withKey(key0)).getItem();
    assertEquals(getResult2, item1);
    assertItemLocked(INTEG_HASH_TABLE_NAME, key0, item1, t1.getId(), false, true);
    
    t1.commit();
    
    assertItemNotLocked(INTEG_HASH_TABLE_NAME, key0, item1, true);
}
 
Example 12
@Test
public void getThenUpdateNewItem() {
    Transaction t1 = manager.newTransaction();
    Map<String, AttributeValue> key1 = newKey(INTEG_HASH_TABLE_NAME);
    
    Map<String, AttributeValue> item1 = new HashMap<String, AttributeValue>(key1);
    item1.put("asdf", new AttributeValue("didn't exist"));
    
    Map<String, AttributeValueUpdate> updates1 = new HashMap<String, AttributeValueUpdate>();
    updates1.put("asdf", new AttributeValueUpdate(new AttributeValue("didn't exist"), AttributeAction.PUT));
    
    Map<String, AttributeValue> getResult = t1.getItem(new GetItemRequest().withTableName(INTEG_HASH_TABLE_NAME).withKey(key1)).getItem();
    assertItemLocked(INTEG_HASH_TABLE_NAME, key1, t1.getId(), true, false);
    assertNull(getResult);
    
    Map<String, AttributeValue> updateResult = t1.updateItem(new UpdateItemRequest().withTableName(INTEG_HASH_TABLE_NAME).withKey(key1)
            .withAttributeUpdates(updates1).withReturnValues(ReturnValue.ALL_NEW)).getAttributes();
    assertItemLocked(INTEG_HASH_TABLE_NAME, key1, item1, t1.getId(), true, true);
    assertEquals(item1, updateResult);
    
    t1.commit();
    
    assertItemNotLocked(INTEG_HASH_TABLE_NAME, key1, item1, true);
}
 
Example 13
@Test
public void getThenUpdateExistingItem() {
    Transaction t1 = manager.newTransaction();
    
    Map<String, AttributeValue> item0a = new HashMap<String, AttributeValue>(item0);
    item0a.put("wef", new AttributeValue("new attr"));
    
    Map<String, AttributeValueUpdate> updates1 = new HashMap<String, AttributeValueUpdate>();
    updates1.put("wef", new AttributeValueUpdate(new AttributeValue("new attr"), AttributeAction.PUT));
    
    Map<String, AttributeValue> getResult = t1.getItem(new GetItemRequest().withTableName(INTEG_HASH_TABLE_NAME).withKey(key0)).getItem();
    assertItemLocked(INTEG_HASH_TABLE_NAME, key0, item0, t1.getId(), false, false);
    assertEquals(item0, getResult);
    
    Map<String, AttributeValue> updateResult = t1.updateItem(new UpdateItemRequest().withTableName(INTEG_HASH_TABLE_NAME).withKey(key0)
            .withAttributeUpdates(updates1).withReturnValues(ReturnValue.ALL_NEW)).getAttributes();
    assertItemLocked(INTEG_HASH_TABLE_NAME, key0, item0a, t1.getId(), false, true);
    assertEquals(item0a, updateResult);
    
    t1.commit();
    
    assertItemNotLocked(INTEG_HASH_TABLE_NAME, key0, item0a, true);
}
 
Example 14
@Test
public void putItemAllOldInsert() {
    Transaction t1 = manager.newTransaction();
    Map<String, AttributeValue> key1 = newKey(INTEG_HASH_TABLE_NAME);
    Map<String, AttributeValue> item1 = new HashMap<String, AttributeValue>(key1);
    item1.put("asdf", new AttributeValue("wef"));
    
    Map<String, AttributeValue> putResult1 = t1.putItem(new PutItemRequest()
        .withTableName(INTEG_HASH_TABLE_NAME)
        .withItem(item1)
        .withReturnValues(ReturnValue.ALL_OLD)).getAttributes();
    assertItemLocked(INTEG_HASH_TABLE_NAME, key1, item1, t1.getId(), true, true);
    assertNull(putResult1);
    
    t1.commit();
    
    assertItemNotLocked(INTEG_HASH_TABLE_NAME, key1, item1, true);
}
 
Example 15
@Test
public void putItemAllOldOverwrite() {
    Transaction t1 = manager.newTransaction();
    Map<String, AttributeValue> item1 = new HashMap<String, AttributeValue>(item0);
    item1.put("asdf", new AttributeValue("wef"));
    
    Map<String, AttributeValue> putResult1 = t1.putItem(new PutItemRequest()
        .withTableName(INTEG_HASH_TABLE_NAME)
        .withItem(item1)
        .withReturnValues(ReturnValue.ALL_OLD)).getAttributes();
    assertItemLocked(INTEG_HASH_TABLE_NAME, key0, item1, t1.getId(), false, true);
    assertEquals(putResult1, item0);
    
    t1.commit();
    
    assertItemNotLocked(INTEG_HASH_TABLE_NAME, key0, item1, true);
}
 
Example 16
@Test
public void updateItemAllOldInsert() {
    Transaction t1 = manager.newTransaction();
    Map<String, AttributeValue> key1 = newKey(INTEG_HASH_TABLE_NAME);
    Map<String, AttributeValue> item1 = new HashMap<String, AttributeValue>(key1);
    item1.put("asdf", new AttributeValue("wef"));
    Map<String, AttributeValueUpdate> updates = new HashMap<String, AttributeValueUpdate>();
    updates.put("asdf", new AttributeValueUpdate().withAction(AttributeAction.PUT).withValue(new AttributeValue("wef")));
    
    Map<String, AttributeValue> result1 = t1.updateItem(new UpdateItemRequest()
        .withTableName(INTEG_HASH_TABLE_NAME)
        .withKey(key1)
        .withAttributeUpdates(updates)
        .withReturnValues(ReturnValue.ALL_OLD)).getAttributes();
    assertItemLocked(INTEG_HASH_TABLE_NAME, key1, item1, t1.getId(), true, true);
    assertNull(result1);
    
    t1.commit();
    
    assertItemNotLocked(INTEG_HASH_TABLE_NAME, key1, item1, true);
}
 
Example 17
@Test
public void updateItemAllOldOverwrite() {
    Transaction t1 = manager.newTransaction();
    Map<String, AttributeValue> item1 = new HashMap<String, AttributeValue>(item0);
    item1.put("asdf", new AttributeValue("wef"));
    Map<String, AttributeValueUpdate> updates = new HashMap<String, AttributeValueUpdate>();
    updates.put("asdf", new AttributeValueUpdate().withAction(AttributeAction.PUT).withValue(new AttributeValue("wef")));
    
    Map<String, AttributeValue> result1 = t1.updateItem(new UpdateItemRequest()
        .withTableName(INTEG_HASH_TABLE_NAME)
        .withKey(key0)
        .withAttributeUpdates(updates)
        .withReturnValues(ReturnValue.ALL_OLD)).getAttributes();
    assertItemLocked(INTEG_HASH_TABLE_NAME, key0, item1, t1.getId(), false, true);
    assertEquals(result1, item0);
    
    t1.commit();
    
    assertItemNotLocked(INTEG_HASH_TABLE_NAME, key0, item1, true);
}
 
Example 18
@Test
public void updateItemAllNewInsert() {
    Transaction t1 = manager.newTransaction();
    Map<String, AttributeValue> key1 = newKey(INTEG_HASH_TABLE_NAME);
    Map<String, AttributeValue> item1 = new HashMap<String, AttributeValue>(key1);
    item1.put("asdf", new AttributeValue("wef"));
    Map<String, AttributeValueUpdate> updates = new HashMap<String, AttributeValueUpdate>();
    updates.put("asdf", new AttributeValueUpdate().withAction(AttributeAction.PUT).withValue(new AttributeValue("wef")));
    
    Map<String, AttributeValue> result1 = t1.updateItem(new UpdateItemRequest()
        .withTableName(INTEG_HASH_TABLE_NAME)
        .withKey(key1)
        .withAttributeUpdates(updates)
        .withReturnValues(ReturnValue.ALL_NEW)).getAttributes();
    assertItemLocked(INTEG_HASH_TABLE_NAME, key1, item1, t1.getId(), true, true);
    assertEquals(result1, item1);
    
    t1.commit();
    
    assertItemNotLocked(INTEG_HASH_TABLE_NAME, key1, item1, true);
}
 
Example 19
@Test
public void updateItemAllNewOverwrite() {
    Transaction t1 = manager.newTransaction();
    Map<String, AttributeValue> item1 = new HashMap<String, AttributeValue>(item0);
    item1.put("asdf", new AttributeValue("wef"));
    Map<String, AttributeValueUpdate> updates = new HashMap<String, AttributeValueUpdate>();
    updates.put("asdf", new AttributeValueUpdate().withAction(AttributeAction.PUT).withValue(new AttributeValue("wef")));
    
    Map<String, AttributeValue> result1 = t1.updateItem(new UpdateItemRequest()
        .withTableName(INTEG_HASH_TABLE_NAME)
        .withKey(key0)
        .withAttributeUpdates(updates)
        .withReturnValues(ReturnValue.ALL_NEW)).getAttributes();
    assertItemLocked(INTEG_HASH_TABLE_NAME, key0, item1, t1.getId(), false, true);
    assertEquals(result1, item1);
    
    t1.commit();
    
    assertItemNotLocked(INTEG_HASH_TABLE_NAME, key0, item1, true);
}
 
Example 20
@Test
public void deleteItemAllOldNotExists() {
    Transaction t1 = manager.newTransaction();
    Map<String, AttributeValue> key1 = newKey(INTEG_HASH_TABLE_NAME);
    
    Map<String, AttributeValue> result1 = t1.deleteItem(new DeleteItemRequest()
        .withTableName(INTEG_HASH_TABLE_NAME)
        .withKey(key1)
        .withReturnValues(ReturnValue.ALL_OLD)).getAttributes();
    assertItemLocked(INTEG_HASH_TABLE_NAME, key1, key1, t1.getId(), true, false);
    assertNull(result1);
    
    t1.commit();
    
    assertItemNotLocked(INTEG_HASH_TABLE_NAME, key1, false);
}
 
Example 21
@Override
public final Response putItem(final Request request) {

    if (request.isWaitForActive()) {
        try {
            TableUtils.waitUntilActive(this.dynamoDBClient, request.getTableName());
        } catch (InterruptedException e) {
            return new Response(null,
                    "Error while waiting for table to become active with API version V2: " + e.getMessage());
        }
    }

    Map<String, AttributeValue> attributeValueMap = new HashMap<>();

    attributeValueMap.put(request.getPartitionKey(), new AttributeValue(request.getPartitionKeyValue()));
    attributeValueMap.put(request.getSortKey(), new AttributeValue().withN(request.getSortKeyValue().toString()));

    if (request.getStringData() != null) {
        request.getStringData().forEach((k, v)
                -> attributeValueMap.put(k, new AttributeValue(v)));
    }

    if (request.getIntegerData() != null) {
        request.getIntegerData().forEach((k, v)
                -> attributeValueMap.put(k, new AttributeValue().withN(v.toString())));
    }

    final PutItemRequest putItemRequest = new PutItemRequest()
            .withTableName(request.getTableName())
            .withItem(attributeValueMap)
            .withReturnValues(ReturnValue.NONE);

    this.dynamoDBClient.putItem(putItemRequest);

    return new Response("Item added into " + request.getTableName() + " with API version V2.", null);
}
 
Example 22
private static void updateMultipleAttributes() {
    try {

        HashMap<String, AttributeValue> key = new HashMap<String, AttributeValue>();
        key.put("Id", new AttributeValue().withN("120"));

        Map<String, AttributeValue> expressionAttributeValues = new HashMap<String, AttributeValue>();
        expressionAttributeValues.put(":val1", new AttributeValue().withSS("Author YY", "Author ZZ"));
        expressionAttributeValues.put(":val2", new AttributeValue().withS("someValue"));

        ReturnValue returnValues = ReturnValue.ALL_NEW;

        UpdateItemRequest updateItemRequest = new UpdateItemRequest().withTableName(tableName).withKey(key)
            .withUpdateExpression("add Authors :val1 set NewAttribute=:val2")
            .withExpressionAttributeValues(expressionAttributeValues).withReturnValues(returnValues);

        UpdateItemResult result = client.updateItem(updateItemRequest);

        // Check the response.
        System.out.println("Printing item after multiple attribute update...");
        printItem(result.getAttributes());

    }
    catch (AmazonServiceException ase) {
        System.err.println("Failed to update multiple attributes in " + tableName);
        System.out.println(ase.getMessage()); // DELETEME
        System.err.println("Failed to update multiple attributes in " + tableName); // DELETEME
    }
}
 
Example 23
private static void updateExistingAttributeConditionally() {
    try {

        HashMap<String, AttributeValue> key = new HashMap<String, AttributeValue>();
        key.put("Id", new AttributeValue().withN("120"));

        // Specify the desired price (25.00) and also the condition (price =
        // 20.00)

        Map<String, AttributeValue> expressionAttributeValues = new HashMap<String, AttributeValue>();
        expressionAttributeValues.put(":val1", new AttributeValue().withN("25.00"));
        expressionAttributeValues.put(":val2", new AttributeValue().withN("20.00"));

        ReturnValue returnValues = ReturnValue.ALL_NEW;

        UpdateItemRequest updateItemRequest = new UpdateItemRequest().withTableName(tableName).withKey(key)
            .withUpdateExpression("set Price = :val1").withConditionExpression("Price = :val2")
            .withExpressionAttributeValues(expressionAttributeValues).withReturnValues(returnValues);

        UpdateItemResult result = client.updateItem(updateItemRequest);

        // Check the response.
        System.out.println("Printing item after conditional update to new attribute...");
        printItem(result.getAttributes());
    }
    catch (ConditionalCheckFailedException cse) {
        // Reload object and retry code.
        System.err.println("Conditional check failed in " + tableName);
    }
    catch (AmazonServiceException ase) {
        System.err.println("Error updating item in " + tableName);
    }
}
 
Example 24
private static void deleteItem() {
    try {

        HashMap<String, AttributeValue> key = new HashMap<String, AttributeValue>();
        key.put("Id", new AttributeValue().withN("120"));

        Map<String, AttributeValue> expressionAttributeValues = new HashMap<String, AttributeValue>();
        expressionAttributeValues.put(":val", new AttributeValue().withBOOL(false));

        ReturnValue returnValues = ReturnValue.ALL_OLD;

        DeleteItemRequest deleteItemRequest = new DeleteItemRequest().withTableName(tableName).withKey(key)
            .withConditionExpression("InPublication = :val")
            .withExpressionAttributeValues(expressionAttributeValues).withReturnValues(returnValues);

        DeleteItemResult result = client.deleteItem(deleteItemRequest);

        // Check the response.
        System.out.println("Printing item that was deleted...");
        printItem(result.getAttributes());

    }
    catch (AmazonServiceException ase) {
        System.err.println("Failed to get item after deletion " + tableName);
    }

}
 
Example 25
Source Project: aws-doc-sdk-examples   Source File: MoviesItemOps05.java    License: Apache License 2.0 5 votes vote down vote up
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());
        }
    }
 
Example 26
Source Project: aws-doc-sdk-examples   Source File: MoviesItemOps04.java    License: Apache License 2.0 5 votes vote down vote up
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("year", year, "title", title)
            .withUpdateExpression("set info.rating = info.rating + :val")
            .withValueMap(new ValueMap().withNumber(":val", 1)).withReturnValues(ReturnValue.UPDATED_NEW);

        try {
            System.out.println("Incrementing an atomic counter...");
            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());
        }
    }
 
Example 27
Source Project: aws-doc-sdk-examples   Source File: MoviesItemOps03.java    License: Apache License 2.0 5 votes vote down vote up
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("year", year, "title", title)
            .withUpdateExpression("set info.rating = :r, info.plot=:p, info.actors=:a")
            .withValueMap(new ValueMap().withNumber(":r", 5.5).withString(":p", "Everything happens all at once.")
                .withList(":a", Arrays.asList("Larry", "Moe", "Curly")))
            .withReturnValues(ReturnValue.UPDATED_NEW);

        try {
            System.out.println("Updating the item...");
            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());
        }
    }
 
Example 28
Source Project: ShedLock   Source File: DynamoDBLockProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
@NonNull
public Optional<SimpleLock> lock(@NonNull LockConfiguration lockConfiguration) {
    String nowIso = toIsoString(now());
    String lockUntilIso = toIsoString(lockConfiguration.getLockAtMostUntil());

    UpdateItemSpec request = new UpdateItemSpec()
            .withPrimaryKey(ID, lockConfiguration.getName())
            .withUpdateExpression(OBTAIN_LOCK_QUERY)
            .withConditionExpression(OBTAIN_LOCK_CONDITION)
            .withValueMap(new ValueMap()
                    .withString(":lockUntil", lockUntilIso)
                    .withString(":lockedAt", nowIso)
                    .withString(":lockedBy", hostname)
            )
            .withReturnValues(ReturnValue.UPDATED_NEW);

    try {
        // There are three possible situations:
        // 1. The lock document does not exist yet - it is inserted - we have the lock
        // 2. The lock document exists and lockUtil <= now - it is updated - we have the lock
        // 3. The lock document exists and lockUtil > now - ConditionalCheckFailedException is thrown
        table.updateItem(request);
        return Optional.of(new DynamoDBLock(table, lockConfiguration));
    } catch (ConditionalCheckFailedException e) {
        // Condition failed. This means there was a lock with lockUntil > now.
        return Optional.empty();
    }
}
 
Example 29
Source Project: ShedLock   Source File: DynamoDBLockProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void doUnlock() {
    // Set lockUntil to now or lockAtLeastUntil whichever is later
    String unlockTimeIso = toIsoString(lockConfiguration.getUnlockTime());
    UpdateItemSpec request = new UpdateItemSpec()
            .withPrimaryKey(ID, lockConfiguration.getName())
            .withUpdateExpression(RELEASE_LOCK_QUERY)
            .withValueMap(new ValueMap()
                    .withString(":lockUntil", unlockTimeIso)
            )
            .withReturnValues(ReturnValue.UPDATED_NEW);
    table.updateItem(request);
}
 
Example 30
@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 {
            worker = new UpdateItemWorker(request, client.getDelegate());
        }
        workers.add(worker);
    }
    return workers;
}