com.amazonaws.services.dynamodbv2.document.spec.UpdateItemSpec Java Examples

The following examples show how to use com.amazonaws.services.dynamodbv2.document.spec.UpdateItemSpec. 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
Source File: DocumentAPIItemCRUDExample.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
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 #2
Source File: DocumentAPIItemCRUDExample.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
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 #3
Source File: DocumentAPIItemCRUDExample.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
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 #4
Source File: DynamoDBSSHRecordStoreConnection.java    From athenz with Apache License 2.0 6 votes vote down vote up
@Override
public boolean updateSSHCertRecord(SSHCertRecord certRecord) {

    final String primaryKey = getPrimaryKey(certRecord.getInstanceId(), certRecord.getService());

    try {
        UpdateItemSpec updateItemSpec = new UpdateItemSpec()
                .withPrimaryKey(KEY_PRIMARY, primaryKey)
                .withAttributeUpdate(
                        new AttributeUpdate(KEY_INSTANCE_ID).put(certRecord.getInstanceId()),
                        new AttributeUpdate(KEY_SERVICE).put(certRecord.getService()),
                        new AttributeUpdate(KEY_CLIENT_IP).put(certRecord.getClientIP()),
                        new AttributeUpdate(KEY_PRINCIPALS).put(certRecord.getPrincipals()),
                        new AttributeUpdate(KEY_PRIVATE_IP).put(certRecord.getPrivateIP()),
                        new AttributeUpdate(KEY_TTL).put(System.currentTimeMillis() / 1000L + expiryTime)
                );
        table.updateItem(updateItemSpec);
        return true;
    } catch (Exception ex) {
        LOGGER.error("DynamoDB Update Error for {}: {}/{}", primaryKey, ex.getClass(), ex.getMessage());
        return false;
    }
}
 
Example #5
Source File: DynamoDBCertRecordStoreConnection.java    From athenz with 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 #6
Source File: DynamoDBCertRecordStoreConnectionTest.java    From athenz with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdateX509Record() {

    DynamoDBCertRecordStoreConnection dbConn = getDBConnection();

    Date now = new Date();
    X509CertRecord certRecord = getRecordNonNullableColumns(now);
    certRecord.setLastNotifiedTime(now);
    certRecord.setLastNotifiedServer("last-notified-server");
    certRecord.setExpiryTime(now);
    certRecord.setHostName("hostname");

    UpdateItemSpec item = new UpdateItemSpec()
            .withPrimaryKey("primaryKey", "athenz.provider:cn:1234")
            .withAttributeUpdate(
                    new AttributeUpdate("instanceId").put(certRecord.getInstanceId()),
                    new AttributeUpdate("provider").put(certRecord.getProvider()),
                    new AttributeUpdate("service").put(certRecord.getService()),
                    new AttributeUpdate("currentSerial").put(certRecord.getCurrentSerial()),
                    new AttributeUpdate("currentIP").put(certRecord.getCurrentIP()),
                    new AttributeUpdate("currentTime").put(certRecord.getCurrentTime().getTime()),
                    new AttributeUpdate("prevSerial").put(certRecord.getPrevSerial()),
                    new AttributeUpdate("prevIP").put(certRecord.getPrevIP()),
                    new AttributeUpdate("prevTime").put(certRecord.getPrevTime().getTime()),
                    new AttributeUpdate("clientCert").put(certRecord.getClientCert()),
                    new AttributeUpdate("ttl").put(certRecord.getCurrentTime().getTime() / 1000L + 3660 * 720),
                    new AttributeUpdate("lastNotifiedTime").put(certRecord.getLastNotifiedTime().getTime()),
                    new AttributeUpdate("lastNotifiedServer").put(certRecord.getLastNotifiedServer()),
                    new AttributeUpdate("expiryTime").put(certRecord.getExpiryTime().getTime()),
                    new AttributeUpdate("hostName").put(certRecord.getHostName()));

    Mockito.doReturn(updateOutcome).when(table).updateItem(item);
    boolean requestSuccess = dbConn.updateX509CertRecord(certRecord);
    assertTrue(requestSuccess);

    dbConn.close();
}
 
Example #7
Source File: DocumentAPIItemCRUDExample.java    From aws-dynamodb-examples with Apache License 2.0 5 votes vote down vote up
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 #8
Source File: DocumentAPIItemCRUDExample.java    From aws-dynamodb-examples with Apache License 2.0 5 votes vote down vote up
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 #9
Source File: DocumentAPIItemCRUDExample.java    From aws-dynamodb-examples with Apache License 2.0 5 votes vote down vote up
private static void updateAddNewAttribute() {
    Table table = dynamoDB.getTable(tableName);

    try {

        Map<String, String> expressionAttributeNames = new HashMap<String, String>();
        expressionAttributeNames.put("#na", "NewAttribute");

        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 #10
Source File: MoviesItemOps03.java    From aws-dynamodb-examples with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args)  {

        AmazonDynamoDBClient client = new AmazonDynamoDBClient();
        client.setEndpoint("http://localhost:8000");
        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")));

        System.out.println("Updating the item...");
        try {
            table.updateItem(updateItemSpec);
            System.out.println("UpdateItem succeeded: " + table.getItem("year", year, "title", title).toJSONPretty());
        } catch (Exception e) {
            System.out.println("UpdateItem failed");
            e.printStackTrace();
        }
                

    }
 
Example #11
Source File: MoviesItemOps04.java    From aws-dynamodb-examples with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args)  {

        AmazonDynamoDBClient client = new AmazonDynamoDBClient();
        client.setEndpoint("http://localhost:8000");
        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));

        System.out.println("Incrementing an atomic counter...");
        try {
            table.updateItem(updateItemSpec);
            System.out.println("UpdateItem succeeded: " + table.getItem("year", year, "title", title).toJSONPretty());
        } catch (Exception e) {
            System.out.println("UpdateItem failed");
            e.printStackTrace();
        }

    }
 
Example #12
Source File: MoviesItemOps05.java    From aws-dynamodb-examples with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args)  {

        AmazonDynamoDBClient client = new AmazonDynamoDBClient();
        client.setEndpoint("http://localhost:8000");
        DynamoDB dynamoDB = new DynamoDB(client);

        Table table = dynamoDB.getTable("Movies");
        
        int year = 2015;
        String title = "The Big New Movie";

        // Conditional update (will fail)

        UpdateItemSpec updateItemSpec = new UpdateItemSpec()
            .withPrimaryKey(new PrimaryKey("year", 2015, "title",  "The Big New Movie"))
            .withUpdateExpression("remove info.actors[0]")
            .withConditionExpression("size(info.actors) > :num")
            .withValueMap(new ValueMap().withNumber(":num", 3));

        System.out.println("Attempting a conditional update...");
        try {
            table.updateItem(updateItemSpec);
            System.out.println("UpdateItem succeeded: " + table.getItem("year", year, "title", title).toJSONPretty());
        } catch (ConditionalCheckFailedException e) {
            e.printStackTrace();
            System.out.println("UpdateItem failed");
        }

    }
 
Example #13
Source File: DynamoDBSSHRecordStoreConnectionTest.java    From athenz with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdateSSHRecordException() {

    SSHCertRecord certRecord = new SSHCertRecord();

    Mockito.doThrow(new AmazonDynamoDBException("invalid operation"))
            .when(table).updateItem(ArgumentMatchers.any(UpdateItemSpec.class));

    DynamoDBSSHRecordStoreConnection dbConn = new DynamoDBSSHRecordStoreConnection(dynamoDB, tableName);
    boolean requestSuccess = dbConn.updateSSHCertRecord(certRecord);
    assertFalse(requestSuccess);

    dbConn.close();
}
 
Example #14
Source File: DynamoDBSSHRecordStoreConnectionTest.java    From athenz with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdateSSHRecord() {

    DynamoDBSSHRecordStoreConnection dbConn = new DynamoDBSSHRecordStoreConnection(dynamoDB, tableName);

    SSHCertRecord certRecord = new SSHCertRecord();
    certRecord.setInstanceId("1234");
    certRecord.setService("cn");
    certRecord.setPrincipals("host1,host2");
    certRecord.setClientIP("10.10.10.11");
    certRecord.setPrivateIP("10.10.10.12");

    UpdateItemSpec item = new UpdateItemSpec()
            .withPrimaryKey("primaryKey", "cn:1234")
            .withAttributeUpdate(
                    new AttributeUpdate("instanceId").put(certRecord.getInstanceId()),
                    new AttributeUpdate("service").put(certRecord.getService()),
                    new AttributeUpdate("principals").put(certRecord.getPrincipals()),
                    new AttributeUpdate("clientIP").put(certRecord.getClientIP()),
                    new AttributeUpdate("privateIP").put(certRecord.getPrivateIP()));

    Mockito.doReturn(updateOutcome).when(table).updateItem(item);
    boolean requestSuccess = dbConn.updateSSHCertRecord(certRecord);
    assertTrue(requestSuccess);

    dbConn.close();
}
 
Example #15
Source File: DynamoDBCertRecordStoreConnectionTest.java    From athenz with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdateUnrefreshedCertificatesNotificationTimestampException() {
    Mockito.doThrow(new AmazonDynamoDBException("invalid operation"))
            .when(table).updateItem(any(UpdateItemSpec.class));

    DynamoDBCertRecordStoreConnection dbConn = getDBConnection();
    List<X509CertRecord> result = dbConn.updateUnrefreshedCertificatesNotificationTimestamp(
            "serverTest",
            1591706189000L,
            "providerTest");

    assertEquals(result.size(), 0);

    dbConn.close();
}
 
Example #16
Source File: DynamoDBCertRecordStoreConnectionTest.java    From athenz with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdateX509RecordException() {

    Date now = new Date();
    X509CertRecord certRecord = getRecordNonNullableColumns(now);

    Mockito.doThrow(new AmazonDynamoDBException("invalid operation"))
            .when(table).updateItem(any(UpdateItemSpec.class));

    DynamoDBCertRecordStoreConnection dbConn = getDBConnection();
    boolean requestSuccess = dbConn.updateX509CertRecord(certRecord);
    assertFalse(requestSuccess);

    dbConn.close();
}
 
Example #17
Source File: DynamoDBCertRecordStoreConnectionTest.java    From athenz with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdateX509RecordNullableColumns() {

    DynamoDBCertRecordStoreConnection dbConn = getDBConnection();

    Date now = new Date();
    X509CertRecord certRecord = getRecordNonNullableColumns(now);
    certRecord.setLastNotifiedTime(null);
    certRecord.setLastNotifiedServer(null);
    certRecord.setExpiryTime(null);
    certRecord.setHostName(null);

    UpdateItemSpec item = new UpdateItemSpec()
            .withPrimaryKey("primaryKey", "athenz.provider:cn:1234")
            .withAttributeUpdate(
                    new AttributeUpdate("instanceId").put(certRecord.getInstanceId()),
                    new AttributeUpdate("provider").put(certRecord.getProvider()),
                    new AttributeUpdate("service").put(certRecord.getService()),
                    new AttributeUpdate("currentSerial").put(certRecord.getCurrentSerial()),
                    new AttributeUpdate("currentIP").put(certRecord.getCurrentIP()),
                    new AttributeUpdate("currentTime").put(certRecord.getCurrentTime().getTime()),
                    new AttributeUpdate("prevSerial").put(certRecord.getPrevSerial()),
                    new AttributeUpdate("prevIP").put(certRecord.getPrevIP()),
                    new AttributeUpdate("prevTime").put(certRecord.getPrevTime().getTime()),
                    new AttributeUpdate("clientCert").put(certRecord.getClientCert()),
                    new AttributeUpdate("ttl").put(certRecord.getCurrentTime().getTime() / 1000L + 3660 * 720),
                    new AttributeUpdate("lastNotifiedTime").put(null),
                    new AttributeUpdate("lastNotifiedServer").put(null),
                    new AttributeUpdate("expiryTime").put(null),
                    new AttributeUpdate("hostName").put(null));

    Mockito.doReturn(updateOutcome).when(table).updateItem(item);
    boolean requestSuccess = dbConn.updateX509CertRecord(certRecord);
    assertTrue(requestSuccess);

    dbConn.close();
}
 
Example #18
Source File: DynamoDBAnnouncer.java    From hollow-reference-implementation with Apache License 2.0 5 votes vote down vote up
@Override
public void announce(long stateVersion) {
    Table table = dynamoDB.getTable(tableName);

    UpdateItemSpec updateItemSpec = new UpdateItemSpec()
            .withPrimaryKey("namespace", blobNamespace)
            .withUpdateExpression("set #version = :ver")
            .withNameMap(new NameMap().with("#version", "version"))
            .withValueMap(new ValueMap().withNumber(":ver", stateVersion));

    table.updateItem(updateItemSpec);
}
 
Example #19
Source File: DynamoDBCertRecordStoreConnection.java    From athenz with Apache License 2.0 5 votes vote down vote up
@Override
public boolean updateX509CertRecord(X509CertRecord certRecord) {

    final String primaryKey = getPrimaryKey(certRecord.getProvider(), certRecord.getInstanceId(),
            certRecord.getService());

    try {
        UpdateItemSpec updateItemSpec = new UpdateItemSpec()
                .withPrimaryKey(KEY_PRIMARY, primaryKey)
                .withAttributeUpdate(
                        new AttributeUpdate(KEY_INSTANCE_ID).put(certRecord.getInstanceId()),
                        new AttributeUpdate(KEY_PROVIDER).put(certRecord.getProvider()),
                        new AttributeUpdate(KEY_SERVICE).put(certRecord.getService()),
                        new AttributeUpdate(KEY_CURRENT_SERIAL).put(certRecord.getCurrentSerial()),
                        new AttributeUpdate(KEY_CURRENT_IP).put(certRecord.getCurrentIP()),
                        new AttributeUpdate(KEY_CURRENT_TIME).put(getLongFromDate(certRecord.getCurrentTime())),
                        new AttributeUpdate(KEY_CURRENT_DATE).put(DynamoDBUtils.getIso8601FromDate(certRecord.getCurrentTime())),
                        new AttributeUpdate(KEY_PREV_SERIAL).put(certRecord.getPrevSerial()),
                        new AttributeUpdate(KEY_PREV_IP).put(certRecord.getPrevIP()),
                        new AttributeUpdate(KEY_PREV_TIME).put(getLongFromDate(certRecord.getPrevTime())),
                        new AttributeUpdate(KEY_CLIENT_CERT).put(certRecord.getClientCert()),
                        new AttributeUpdate(KEY_TTL).put(certRecord.getCurrentTime().getTime() / 1000L + expiryTime),
                        new AttributeUpdate(KEY_EXPIRY_TIME).put(getLongFromDate(certRecord.getExpiryTime()))
                );
        table.updateItem(updateItemSpec);
        return true;
    } catch (Exception ex) {
        LOGGER.error("DynamoDB Update Error for {}: {}/{}", primaryKey, ex.getClass(), ex.getMessage());
        return false;
    }
}
 
Example #20
Source File: DynamoDBLockProvider.java    From ShedLock with 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 #21
Source File: DynamoDBLockProvider.java    From ShedLock with 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 #22
Source File: MoviesItemOps03.java    From aws-doc-sdk-examples with 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 #23
Source File: MoviesItemOps04.java    From aws-doc-sdk-examples with 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 #24
Source File: MoviesItemOps05.java    From aws-doc-sdk-examples with 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 #25
Source File: DynamoDBCertRecordStoreConnectionTest.java    From athenz with Apache License 2.0 4 votes vote down vote up
@Test
public void testUpdateUnrefreshedCertificatesNotificationTimestamp() {
    DynamoDBCertRecordStoreConnection dbConn = getDBConnection();
    ItemCollection<QueryOutcome> itemCollection = Mockito.mock(ItemCollection.class);
    Date now = new Date(1591706189000L);
    long nowL = now.getTime();
    long fiveDaysAgo = nowL - 5 * 24 * 60 * 60 * 1000;

    Map<String, AttributeValue> unNotified = generateAttributeValues(
            "home.test.service2",
            "testInstance2",
            null,
            null,
            null,
            null,
            "testHost1");

    Map<String, AttributeValue> reNotified = generateAttributeValues(
            "home.test.service3",
            "testInstance3",
            Long.toString(fiveDaysAgo),
            Long.toString(fiveDaysAgo),
            "testServer",
            null,
            "testHost1");

    Item item1 = ItemUtils.toItem(unNotified);
    Item item2 = ItemUtils.toItem(reNotified);

    IteratorSupport<Item, QueryOutcome> iteratorSupport = Mockito.mock(IteratorSupport.class);
    when(itemCollection.iterator()).thenReturn(iteratorSupport);
    when(iteratorSupport.hasNext()).thenReturn(true, true, false);
    when(iteratorSupport.next()).thenReturn(item1).thenReturn(item2);

    Mockito.doReturn(itemCollection).when(index).query(any(QuerySpec.class));

    AttributeValue lastNotifiedTimeAttrValue = new AttributeValue();
    lastNotifiedTimeAttrValue.setN(Long.toString(nowL));
    AttributeValue lastNotifiedServerAttrValue = new AttributeValue();
    lastNotifiedServerAttrValue.setS("localhost");
    unNotified.put("lastNotifiedTime", lastNotifiedTimeAttrValue);
    unNotified.put("lastNotifiedServer", lastNotifiedServerAttrValue);

    reNotified.put("lastNotifiedTime", lastNotifiedTimeAttrValue);
    reNotified.put("lastNotifiedServer", lastNotifiedServerAttrValue);

    Item updatedItem1 = ItemUtils.toItem(unNotified);
    Item updatedItem2 = ItemUtils.toItem(reNotified);

    UpdateItemOutcome updateItemOutcome1 = Mockito.mock(UpdateItemOutcome.class);
    when(updateItemOutcome1.getItem()).thenReturn(updatedItem1);

    UpdateItemOutcome updateItemOutcome2 = Mockito.mock(UpdateItemOutcome.class);
    when(updateItemOutcome2.getItem()).thenReturn(updatedItem2);

    when(table.updateItem(any(UpdateItemSpec.class))).thenReturn(updateItemOutcome1).thenReturn(updateItemOutcome2);
    List<X509CertRecord> records = dbConn.updateUnrefreshedCertificatesNotificationTimestamp(
            "localhost",
            nowL,
            "provider");

    assertEquals(records.size(), 2);
    assertNull(records.get(0).getCurrentTime());
    assertEquals(records.get(0).getService(), "home.test.service2");
    assertEquals(records.get(0).getLastNotifiedTime(), now);
    assertEquals(records.get(1).getCurrentTime().getTime(), fiveDaysAgo);
    assertEquals(records.get(1).getService(), "home.test.service3");
    assertEquals(records.get(1).getLastNotifiedTime(), now);
}