com.amazonaws.services.dynamodbv2.document.utils.ValueMap Java Examples

The following examples show how to use com.amazonaws.services.dynamodbv2.document.utils.ValueMap. 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: SampleDataTryQuery.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
private static void findRepliesInLast15DaysWithConfig(String tableName, String forumName, String threadSubject) {

        String replyId = forumName + "#" + threadSubject;
        long twoWeeksAgoMilli = (new Date()).getTime() - (15L * 24L * 60L * 60L * 1000L);
        Date twoWeeksAgo = new Date();
        twoWeeksAgo.setTime(twoWeeksAgoMilli);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        String twoWeeksAgoStr = df.format(twoWeeksAgo);

        Table table = dynamoDB.getTable(tableName);

        QuerySpec querySpec = new QuerySpec().withKeyConditionExpression("Id = :v1 and ReplyDateTime > :v2")
            .withValueMap(new ValueMap().withString(":v1", replyId).withString(":v2", twoWeeksAgoStr))
            .withProjectionExpression("Message, ReplyDateTime, PostedBy");

        ItemCollection<QueryOutcome> items = table.query(querySpec);
        Iterator<Item> iterator = items.iterator();

        System.out.println("Query: printing results...");

        while (iterator.hasNext()) {
            System.out.println(iterator.next().toJSONPretty());
        }
    }
 
Example #2
Source File: MoviesItemOps06.java    From aws-dynamodb-examples with Apache License 2.0 6 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");
                
        // Conditional delete (will fail)
        
        DeleteItemSpec deleteItemSpec = new DeleteItemSpec()
            .withPrimaryKey(new PrimaryKey("year", 2015, "title", "The Big New Movie"))
            .withConditionExpression("info.rating <= :val")
            .withValueMap(new ValueMap()
                   .withNumber(":val", 5.0));
        
        System.out.println("Attempting a conditional delete...");
        try {
            table.deleteItem(deleteItemSpec);
            System.out.println("DeleteItem succeeded");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("DeleteItem failed");
        }

    }
 
Example #3
Source File: MoviesScan.java    From aws-dynamodb-examples with Apache License 2.0 6 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");
        
        ScanSpec scanSpec = new ScanSpec()
            .withProjectionExpression("#yr, title, info.rating")
            .withFilterExpression("#yr between :start_yr and :end_yr")
            .withNameMap(new NameMap().with("#yr",  "year"))
            .withValueMap(new ValueMap().withNumber(":start_yr", 1950).withNumber(":end_yr", 1959));
        
        ItemCollection<ScanOutcome> items = table.scan(scanSpec);
        
        Iterator<Item> iter = items.iterator();
        while (iter.hasNext()) {
            Item item = iter.next();
            System.out.println(item.toString());
        }
    }
 
Example #4
Source File: DynamoDBCertRecordStoreConnection.java    From athenz with Apache License 2.0 6 votes vote down vote up
private List<Item> getUnrefreshedCertRecordsByDate(String provider, Index index, long yesterday, String unrefreshedCertDate) {
    QuerySpec spec = new QuerySpec()
            .withKeyConditionExpression("currentDate = :v_current_date")
            .withFilterExpression("provider = :v_provider AND (attribute_not_exists(lastNotifiedTime) OR lastNotifiedTime < :v_last_notified)")
            .withValueMap(new ValueMap()
                    .withString(":v_current_date", unrefreshedCertDate)
                    .withNumber(":v_last_notified", yesterday)
                    .withString(":v_provider", provider));

    ItemCollection<QueryOutcome> outcome = index.query(spec);
    List<Item> items = new ArrayList<>();
    for (Item item : outcome) {
        items.add(item);
    }
    return items;
}
 
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: DocumentAPIQuery.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
private static void findRepliesUsingAFilterExpression(String forumName, String threadSubject) {

        Table table = dynamoDB.getTable(tableName);

        String replyId = forumName + "#" + threadSubject;

        QuerySpec spec = new QuerySpec().withProjectionExpression("Message, ReplyDateTime, PostedBy")
            .withKeyConditionExpression("Id = :v_id").withFilterExpression("PostedBy = :v_postedby")
            .withValueMap(new ValueMap().withString(":v_id", replyId).withString(":v_postedby", "User B"));

        ItemCollection<QueryOutcome> items = table.query(spec);

        System.out.println("\nfindRepliesUsingAFilterExpression results:");
        Iterator<Item> iterator = items.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next().toJSONPretty());
        }
    }
 
Example #7
Source File: DocumentAPIQuery.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
private static void findRepliesPostedWithinTimePeriod(String forumName, String threadSubject) {

        Table table = dynamoDB.getTable(tableName);

        long startDateMilli = (new Date()).getTime() - (15L * 24L * 60L * 60L * 1000L);
        long endDateMilli = (new Date()).getTime() - (5L * 24L * 60L * 60L * 1000L);
        java.text.SimpleDateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        String startDate = df.format(startDateMilli);
        String endDate = df.format(endDateMilli);

        String replyId = forumName + "#" + threadSubject;

        QuerySpec spec = new QuerySpec().withProjectionExpression("Message, ReplyDateTime, PostedBy")
            .withKeyConditionExpression("Id = :v_id and ReplyDateTime between :v_start_dt and :v_end_dt")
            .withValueMap(new ValueMap().withString(":v_id", replyId).withString(":v_start_dt", startDate)
                .withString(":v_end_dt", endDate));

        ItemCollection<QueryOutcome> items = table.query(spec);

        System.out.println("\nfindRepliesPostedWithinTimePeriod results:");
        Iterator<Item> iterator = items.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next().toJSONPretty());
        }
    }
 
Example #8
Source File: DocumentAPIQuery.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
private static void findRepliesInLast15DaysWithConfig(String forumName, String threadSubject) {

        Table table = dynamoDB.getTable(tableName);

        long twoWeeksAgoMilli = (new Date()).getTime() - (15L * 24L * 60L * 60L * 1000L);
        Date twoWeeksAgo = new Date();
        twoWeeksAgo.setTime(twoWeeksAgoMilli);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        String twoWeeksAgoStr = df.format(twoWeeksAgo);

        String replyId = forumName + "#" + threadSubject;

        QuerySpec spec = new QuerySpec().withProjectionExpression("Message, ReplyDateTime, PostedBy")
            .withKeyConditionExpression("Id = :v_id and ReplyDateTime <= :v_reply_dt_tm")
            .withValueMap(new ValueMap().withString(":v_id", replyId).withString(":v_reply_dt_tm", twoWeeksAgoStr));

        ItemCollection<QueryOutcome> items = table.query(spec);

        System.out.println("\nfindRepliesInLast15DaysWithConfig results:");
        Iterator<Item> iterator = items.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next().toJSONPretty());
        }

    }
 
Example #9
Source File: DocumentAPIQuery.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
private static void findRepliesForAThreadSpecifyOptionalLimit(String forumName, String threadSubject) {

        Table table = dynamoDB.getTable(tableName);

        String replyId = forumName + "#" + threadSubject;

        QuerySpec spec = new QuerySpec().withKeyConditionExpression("Id = :v_id")
            .withValueMap(new ValueMap().withString(":v_id", replyId)).withMaxPageSize(1);

        ItemCollection<QueryOutcome> items = table.query(spec);

        System.out.println("\nfindRepliesForAThreadSpecifyOptionalLimit results:");

        // Process each page of results
        int pageNum = 0;
        for (Page<Item, QueryOutcome> page : items.pages()) {

            System.out.println("\nPage: " + ++pageNum);

            // Process each item on the current page
            Iterator<Item> item = page.iterator();
            while (item.hasNext()) {
                System.out.println(item.next().toJSONPretty());
            }
        }
    }
 
Example #10
Source File: DocumentAPIItemCRUDExample.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
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 #11
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 #12
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 #13
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 #14
Source File: DocumentAPIItemCRUDExample.java    From aws-dynamodb-examples with Apache License 2.0 6 votes vote down vote up
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 #15
Source File: DocumentAPIQuery.java    From aws-dynamodb-examples with Apache License 2.0 6 votes vote down vote up
private static void findRepliesUsingAFilterExpression(String forumName, String threadSubject) {

        Table table = dynamoDB.getTable(tableName);
        
        String replyId = forumName + "#" + threadSubject;

        QuerySpec spec = new QuerySpec()
            .withProjectionExpression("Message, ReplyDateTime, PostedBy")
            .withKeyConditionExpression("Id = :v_id")
            .withFilterExpression("PostedBy = :v_postedby")
            .withValueMap(new ValueMap()
                .withString(":v_id", replyId)
                .withString(":v_postedby", "User B"));
        
        ItemCollection<QueryOutcome> items = table.query(spec);

        System.out.println("\nfindRepliesUsingAFilterExpression results:");
        Iterator<Item> iterator = items.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next().toJSONPretty());
        }    
     }
 
Example #16
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 #17
Source File: DocumentAPIQuery.java    From aws-dynamodb-examples with Apache License 2.0 5 votes vote down vote up
private static void findRepliesForAThreadSpecifyOptionalLimit(String forumName, String threadSubject) {

        Table table = dynamoDB.getTable(tableName);
        
        String replyId = forumName + "#" + threadSubject;   
               
        QuerySpec spec = new QuerySpec()
            .withKeyConditionExpression("Id = :v_id")
            .withValueMap(new ValueMap()
                .withString(":v_id", replyId))
            .withMaxPageSize(1);

        ItemCollection<QueryOutcome> items = table.query(spec);
        
        System.out.println("\nfindRepliesForAThreadSpecifyOptionalLimit results:");

        // Process each page of results
        int pageNum = 0;
        for (Page<Item, QueryOutcome> page : items.pages()) {
            
            System.out.println("\nPage: " + ++pageNum);

            // Process each item on the current page
            Iterator<Item> item = page.iterator();
            while (item.hasNext()) {
                System.out.println(item.next().toJSONPretty());
            }
        }
    }
 
Example #18
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 #19
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 #20
Source File: GettingStartedTryQuery.java    From aws-dynamodb-examples with Apache License 2.0 5 votes vote down vote up
private static void findRepliesInLast15DaysWithConfig(
    String tableName, String forumName, String threadSubject) {

    String replyId = forumName + "#" + threadSubject;
    long twoWeeksAgoMilli = (new Date()).getTime()
        - (15L * 24L * 60L * 60L * 1000L);
    Date twoWeeksAgo = new Date();
    twoWeeksAgo.setTime(twoWeeksAgoMilli);
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    String twoWeeksAgoStr = df.format(twoWeeksAgo);

    Table table = dynamoDB.getTable(tableName);

    QuerySpec querySpec = new QuerySpec()
        .withKeyConditionExpression("Id = :v1 and ReplyDateTime > :v2")
        .withValueMap(new ValueMap()
            .withString(":v1", replyId)
            .withString(":v2", twoWeeksAgoStr))
        .withProjectionExpression("Message, ReplyDateTime, PostedBy");

    ItemCollection<QueryOutcome> items = table.query(querySpec);
    Iterator<Item> iterator = items.iterator();

    System.out.println("Query: printing results...");

    while (iterator.hasNext()) {
        System.out.println(iterator.next().toJSONPretty());
    }
}
 
Example #21
Source File: DocumentAPIQuery.java    From aws-dynamodb-examples with Apache License 2.0 5 votes vote down vote up
private static void findRepliesInLast15DaysWithConfig(String forumName, String threadSubject) {

        Table table = dynamoDB.getTable(tableName);

        long twoWeeksAgoMilli = (new Date()).getTime() - (15L*24L*60L*60L*1000L);
        Date twoWeeksAgo = new Date();
        twoWeeksAgo.setTime(twoWeeksAgoMilli);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        String twoWeeksAgoStr = df.format(twoWeeksAgo);
        
        String replyId = forumName + "#" + threadSubject;

        QuerySpec spec = new QuerySpec()
            .withProjectionExpression("Message, ReplyDateTime, PostedBy")
            .withKeyConditionExpression("Id = :v_id and ReplyDateTime <= :v_reply_dt_tm")
            .withValueMap(new ValueMap()
                .withString(":v_id", replyId)
                .withString(":v_reply_dt_tm", twoWeeksAgoStr));
        
        ItemCollection<QueryOutcome> items = table.query(spec);

        System.out.println("\nfindRepliesInLast15DaysWithConfig results:");
        Iterator<Item> iterator = items.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next().toJSONPretty());
        }

    }
 
Example #22
Source File: DocumentAPIQuery.java    From aws-dynamodb-examples with Apache License 2.0 5 votes vote down vote up
private static void findRepliesPostedWithinTimePeriod(String forumName, String threadSubject) {

        Table table = dynamoDB.getTable(tableName);

        long startDateMilli = (new Date()).getTime() - (15L*24L*60L*60L*1000L); 
        long endDateMilli = (new Date()).getTime() - (5L*24L*60L*60L*1000L);    
        java.text.SimpleDateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        String startDate = df.format(startDateMilli);
        String endDate = df.format(endDateMilli);

        String replyId = forumName + "#" + threadSubject;

        QuerySpec spec = new QuerySpec()
            .withProjectionExpression("Message, ReplyDateTime, PostedBy")
            .withKeyConditionExpression("Id = :v_id and ReplyDateTime between :v_start_dt and :v_end_dt")
            .withValueMap(new ValueMap()
                .withString(":v_id", replyId)
                .withString(":v_start_dt", startDate)
                .withString(":v_end_dt", endDate));
        
        ItemCollection<QueryOutcome> items = table.query(spec);

        System.out.println("\nfindRepliesPostedWithinTimePeriod results:");
        Iterator<Item> iterator = items.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next().toJSONPretty());
        }    
    }
 
Example #23
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 #24
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 #25
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 #26
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 #27
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 #28
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 #29
Source File: MoviesScan.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");

        ScanSpec scanSpec = new ScanSpec().withProjectionExpression("#yr, title, info.rating")
            .withFilterExpression("#yr between :start_yr and :end_yr").withNameMap(new NameMap().with("#yr", "year"))
            .withValueMap(new ValueMap().withNumber(":start_yr", 1950).withNumber(":end_yr", 1959));

        try {
            ItemCollection<ScanOutcome> items = table.scan(scanSpec);

            Iterator<Item> iter = items.iterator();
            while (iter.hasNext()) {
                Item item = iter.next();
                System.out.println(item.toString());
            }

        }
        catch (Exception e) {
            System.err.println("Unable to scan the table:");
            System.err.println(e.getMessage());
        }
    }
 
Example #30
Source File: MoviesItemOps06.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";

        DeleteItemSpec deleteItemSpec = new DeleteItemSpec()
            .withPrimaryKey(new PrimaryKey("year", year, "title", title)).withConditionExpression("info.rating <= :val")
            .withValueMap(new ValueMap().withNumber(":val", 5.0));

        // Conditional delete (we expect this to fail)

        try {
            System.out.println("Attempting a conditional delete...");
            table.deleteItem(deleteItemSpec);
            System.out.println("DeleteItem succeeded");
        }
        catch (Exception e) {
            System.err.println("Unable to delete item: " + year + " " + title);
            System.err.println(e.getMessage());
        }
    }