com.amazonaws.services.dynamodbv2.document.Table Java Examples

The following examples show how to use com.amazonaws.services.dynamodbv2.document.Table. 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: DocumentAPIItemBinaryExample.java    From aws-dynamodb-examples with Apache License 2.0 6 votes vote down vote up
public static void retrieveItem(String threadId, String replyDateTime) throws IOException {
    
    Table table = dynamoDB.getTable(tableName);
    
    GetItemSpec spec = new GetItemSpec()
        .withPrimaryKey("Id", threadId, "ReplyDateTime", replyDateTime)
        .withConsistentRead(true);

    Item item = table.getItem(spec);
    
    
 // Uncompress the reply message and print
    String uncompressed = uncompressString(ByteBuffer.wrap(item.getBinary("ExtendedMessage")));
    
    System.out.println("Reply message:\n"
        + " Id: " + item.getString("Id") + "\n" 
        + " ReplyDateTime: " + item.getString("ReplyDateTime") + "\n" 
        + " PostedBy: " + item.getString("PostedBy") + "\n"
        + " Message: " + item.getString("Message") + "\n"
        + " ExtendedMessage (uncompressed): " + uncompressed + "\n");
}
 
Example #2
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 #3
Source File: DocumentAPIParallelScan.java    From aws-dynamodb-examples with Apache License 2.0 6 votes vote down vote up
private static void uploadProduct(String tableName, int productIndex) {

        Table table = dynamoDB.getTable(tableName);

        try {
            System.out.println("Processing record #" + productIndex);

            Item item = new Item()
                .withPrimaryKey("Id", productIndex)
                .withString("Title", "Book " + productIndex + " Title")
                .withString("ISBN", "111-1111111111")
                .withStringSet(
                    "Authors",
                    new HashSet<String>(Arrays.asList("Author1")))
                .withNumber("Price", 2)
                .withString("Dimensions", "8.5 x 11.0 x 0.5")
                .withNumber("PageCount", 500)
                .withBoolean("InPublication", true)
                .withString("ProductCategory", "Book");
            table.putItem(item);

        }   catch (Exception e) {
            System.err.println("Failed to create item " + productIndex + " in " + tableName);
            System.err.println(e.getMessage());
        }
    }
 
Example #4
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 #5
Source File: DocumentAPITableExample.java    From aws-dynamodb-examples with Apache License 2.0 6 votes vote down vote up
static void deleteExampleTable() {

        Table table = dynamoDB.getTable(tableName);
        try {
            System.out.println("Issuing DeleteTable request for " + tableName);
            table.delete();

            System.out.println("Waiting for " + tableName
                + " to be deleted...this may take a while...");

            table.waitForDelete();
        } catch (Exception e) {
            System.err.println("DeleteTable request failed for " + tableName);
            System.err.println(e.getMessage());
        }
    }
 
Example #6
Source File: DynamoDBServiceImpl1.java    From Serverless-Programming-Cookbook with MIT License 6 votes vote down vote up
@Override
public final Response createTable(final Request request) {

    if (tableExist(request.getTableName())) {
        return new Response(null, request.getTableName() + " already exist. Checked with version V1.");
    }

    Table table = dynamoDB.createTable(request.getTableName(),
            Arrays.asList(
                    new KeySchemaElement(request.getPartitionKey(), KeyType.HASH),  //Partition key
                    new KeySchemaElement(request.getSortKey(), KeyType.RANGE)), //Sort key
            Arrays.asList(
                    new AttributeDefinition(request.getPartitionKey(), ScalarAttributeType.S),
                    new AttributeDefinition(request.getSortKey(), ScalarAttributeType.N)),
            new ProvisionedThroughput(request.getReadCapacityUnits(), request.getWriteCapacityUnits()));

    if (request.isWaitForActive()) {
        try {
            table.waitForActive();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    return new Response(request.getTableName() + " created with API version V1.", null);
}
 
Example #7
Source File: MoviesItemOps01.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");
        
        int year = 2015;
        String title = "The Big New Movie";

        try {
            table.putItem(new Item()
                .withPrimaryKey("year", year, "title", title)
                .withJSON("info", "{\"plot\" : \"Something happens.\"}"));
            System.out.println("PutItem succeeded: " + 
                table.getItem("year", year, "title", title).toJSONPretty());

        } catch (Exception e) {
            System.out.println("PutItem failed");
            e.printStackTrace();
        }       
    }
 
Example #8
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 #9
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 #10
Source File: TryDaxHelper.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
void createTable(String tableName, DynamoDB client) {
    Table table = client.getTable(tableName);
    try {
        System.out.println("Attempting to create table; please wait...");

        table = client.createTable(tableName,
                Arrays.asList(
                        new KeySchemaElement("pk", KeyType.HASH),   // Partition key
                        new KeySchemaElement("sk", KeyType.RANGE)), // Sort key
                Arrays.asList(
                        new AttributeDefinition("pk", ScalarAttributeType.N),
                        new AttributeDefinition("sk", ScalarAttributeType.N)),
                new ProvisionedThroughput(10L, 10L));
        table.waitForActive();
        System.out.println("Successfully created table.  Table status: " +
                table.getDescription().getTableStatus());

    } catch (Exception e) {
        System.err.println("Unable to create table: ");
        e.printStackTrace();
    }
}
 
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 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 #12
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 #13
Source File: TryDaxTests.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
void scanTest(String tableName, DynamoDB client, int iterations) {
    long startTime, endTime;
    System.out.println("Scan test - all items in the table");
    Table table = client.getTable(tableName);

    for (int i = 0; i < iterations; i++) {
        startTime = System.nanoTime();
        ItemCollection<ScanOutcome> items = table.scan();
        try {

            Iterator<Item> iter = items.iterator();
            while (iter.hasNext()) {
                iter.next();
            }
        } catch (Exception e) {
            System.err.println("Unable to scan table:");
            e.printStackTrace();
        }
        endTime = System.nanoTime();
        printTime(startTime, endTime, iterations);
    }
}
 
Example #14
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 #15
Source File: DocumentAPIScan.java    From aws-dynamodb-examples with Apache License 2.0 6 votes vote down vote up
private static void findProductsForPriceLessThanZero() {
    
    Table table = dynamoDB.getTable(tableName);
       
    Map<String, Object> expressionAttributeValues = new HashMap<String, Object>();
    expressionAttributeValues.put(":pr", 100);
    
    ItemCollection<ScanOutcome> items = table.scan(
        "Price < :pr", //FilterExpression
        "Id, Title, ProductCategory, Price", //ProjectionExpression
        null, //ExpressionAttributeNames - not used in this example 
        expressionAttributeValues);
    
    System.out.println("Scan of " + tableName + " for items with a price less than 100.");
    Iterator<Item> iterator = items.iterator();
    while (iterator.hasNext()) {
        System.out.println(iterator.next().toJSONPretty());
    }    
}
 
Example #16
Source File: DocumentAPIItemCRUDExample.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
private static void createItems() {

        Table table = dynamoDB.getTable(tableName);
        try {

            Item item = new Item().withPrimaryKey("Id", 120).withString("Title", "Book 120 Title")
                .withString("ISBN", "120-1111111111")
                .withStringSet("Authors", new HashSet<String>(Arrays.asList("Author12", "Author22")))
                .withNumber("Price", 20).withString("Dimensions", "8.5x11.0x.75").withNumber("PageCount", 500)
                .withBoolean("InPublication", false).withString("ProductCategory", "Book");
            table.putItem(item);

            item = new Item().withPrimaryKey("Id", 121).withString("Title", "Book 121 Title")
                .withString("ISBN", "121-1111111111")
                .withStringSet("Authors", new HashSet<String>(Arrays.asList("Author21", "Author 22")))
                .withNumber("Price", 20).withString("Dimensions", "8.5x11.0x.75").withNumber("PageCount", 500)
                .withBoolean("InPublication", true).withString("ProductCategory", "Book");
            table.putItem(item);

        }
        catch (Exception e) {
            System.err.println("Create items failed.");
            System.err.println(e.getMessage());

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

        AmazonDynamoDBClient client = new AmazonDynamoDBClient();
        
        client.setEndpoint("http://localhost:8000");
        DynamoDB dynamoDB = new DynamoDB(client);
        
        String tableName = "Movies";
        Table table = dynamoDB.createTable(tableName,
                Arrays.asList(
                        new KeySchemaElement("year", KeyType.HASH),
                        new KeySchemaElement("title", KeyType.RANGE)), 
                Arrays.asList(
                        new AttributeDefinition("year", ScalarAttributeType.N),
                        new AttributeDefinition("title", ScalarAttributeType.S)), 
                new ProvisionedThroughput(10L, 10L));

        try {
            TableUtils.waitUntilActive(client, tableName);
            System.out.println("Table status: " + table.getDescription().getTableStatus());
        } catch (AmazonClientException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }
 
Example #18
Source File: GettingStartedLoadData.java    From aws-dynamodb-examples with Apache License 2.0 6 votes vote down vote up
private static void loadSampleForums(String tableName) {

        Table table = dynamoDB.getTable(tableName);

        try {

            System.out.println("Adding data to " + tableName);

            Item item = new Item().withPrimaryKey("Name", "Amazon DynamoDB")
                .withString("Category", "Amazon Web Services")
                .withNumber("Threads", 2)
                .withNumber("Messages", 4)
                .withNumber("Views", 1000);
            table.putItem(item);

            item = new Item().withPrimaryKey("Name", "Amazon S3")
                .withString("Category", "Amazon Web Services")
                .withNumber("Threads", 0);
            table.putItem(item);

        } catch (Exception e) {
            System.err.println("Failed to create item in " + tableName);
            System.err.println(e.getMessage());
        }
    }
 
Example #19
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 #20
Source File: DocumentAPIItemCRUDExample.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
private static void retrieveItem() {
    Table table = dynamoDB.getTable(tableName);

    try {

        Item item = table.getItem("Id", 120, "Id, ISBN, Title, Authors", null);

        System.out.println("Printing item after retrieving it....");
        System.out.println(item.toJSONPretty());

    }
    catch (Exception e) {
        System.err.println("GetItem failed.");
        System.err.println(e.getMessage());
    }

}
 
Example #21
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 #22
Source File: DocumentAPIGlobalSecondaryIndexExample.java    From aws-dynamodb-examples with Apache License 2.0 6 votes vote down vote up
public static void putItem(

        String issueId, String title, String description, String createDate,
        String lastUpdateDate, String dueDate, Integer priority,
            String status) {

        Table table = dynamoDB.getTable(tableName);

        Item item = new Item()
            .withPrimaryKey("IssueId", issueId)
            .withString("Title", title)
            .withString("Description", description)
            .withString("CreateDate", createDate)
            .withString("LastUpdateDate", lastUpdateDate)
            .withString("DueDate", dueDate)
            .withNumber("Priority", priority)
            .withString("Status", status);

        table.putItem(item);
    }
 
Example #23
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 #24
Source File: DocumentAPITableExample.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
static void updateExampleTable() {

        Table table = dynamoDB.getTable(tableName);
        System.out.println("Modifying provisioned throughput for " + tableName);

        try {
            table.updateTable(new ProvisionedThroughput().withReadCapacityUnits(6L).withWriteCapacityUnits(7L));

            table.waitForActive();
        }
        catch (Exception e) {
            System.err.println("UpdateTable request failed for " + tableName);
            System.err.println(e.getMessage());
        }
    }
 
Example #25
Source File: DynamoDBUtils.java    From ShedLock with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a locking table with the given name.
 * <p>
 * This method does not check if a table with the given name exists already.
 *
 * @param dynamodb   DynamoDB to be used
 * @param tableName  table to be used
 * @param throughput AWS {@link ProvisionedThroughput throughput requirements} for the given lock setup
 * @return           a {@link Table reference to the newly created table}
 *
 * @throws ResourceInUseException
 *         The operation conflicts with the resource's availability. You attempted to recreate an
 *         existing table.
 */
public static Table createLockTable(
        AmazonDynamoDB dynamodb,
        String tableName,
        ProvisionedThroughput throughput
) {

    CreateTableRequest request = new CreateTableRequest()
            .withTableName(tableName)
            .withKeySchema(new KeySchemaElement(ID, KeyType.HASH))
            .withAttributeDefinitions(new AttributeDefinition(ID, ScalarAttributeType.S))
            .withProvisionedThroughput(throughput);
    dynamodb.createTable(request).getTableDescription();
    return new DynamoDB(dynamodb).getTable(tableName);
}
 
Example #26
Source File: DocumentAPIParallelScan.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    System.out.println("Scanning " + tableName + " segment " + segment + " out of " + totalSegments
        + " segments " + itemLimit + " items at a time...");
    int totalScannedItemCount = 0;

    Table table = dynamoDB.getTable(tableName);

    try {
        ScanSpec spec = new ScanSpec().withMaxResultSize(itemLimit).withTotalSegments(totalSegments)
            .withSegment(segment);

        ItemCollection<ScanOutcome> items = table.scan(spec);
        Iterator<Item> iterator = items.iterator();

        Item currentItem = null;
        while (iterator.hasNext()) {
            totalScannedItemCount++;
            currentItem = iterator.next();
            System.out.println(currentItem.toString());
        }

    }
    catch (Exception e) {
        System.err.println(e.getMessage());
    }
    finally {
        System.out.println("Scanned " + totalScannedItemCount + " items from segment " + segment + " out of "
            + totalSegments + " of " + tableName);
    }
}
 
Example #27
Source File: MoviesDeleteTable.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");
        table.delete();
        System.out.println("Table is being deleted");
        
    }
 
Example #28
Source File: DocumentAPITableExample.java    From aws-dynamodb-examples with Apache License 2.0 5 votes vote down vote up
static void createExampleTable() {

        try {

            ArrayList<AttributeDefinition> attributeDefinitions = new ArrayList<AttributeDefinition>();
            attributeDefinitions.add(new AttributeDefinition()
                .withAttributeName("Id")
                .withAttributeType("N"));

            ArrayList<KeySchemaElement> keySchema = new ArrayList<KeySchemaElement>();
            keySchema.add(new KeySchemaElement()
                .withAttributeName("Id")
                .withKeyType(KeyType.HASH));

            CreateTableRequest request = new CreateTableRequest()
                .withTableName(tableName)
                .withKeySchema(keySchema)
                .withAttributeDefinitions(attributeDefinitions)
                .withProvisionedThroughput(new ProvisionedThroughput()
                    .withReadCapacityUnits(5L)
                    .withWriteCapacityUnits(6L));

            System.out.println("Issuing CreateTable request for " + tableName);
            Table table = dynamoDB.createTable(request);

            System.out.println("Waiting for " + tableName
                + " to be created...this may take a while...");
            table.waitForActive();

            getTableInformation();

        } catch (Exception e) {
            System.err.println("CreateTable request failed for " + tableName);
            System.err.println(e.getMessage());
        }

    }
 
Example #29
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 #30
Source File: DocumentAPILocalSecondaryIndexExample.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
public static void deleteTable(String tableName) {

        Table table = dynamoDB.getTable(tableName);
        System.out.println("Deleting table " + tableName + "...");
        table.delete();

        // Wait for table to be deleted
        System.out.println("Waiting for " + tableName + " to be deleted...");
        try {
            table.waitForDelete();
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
    }