Example usage for com.amazonaws.services.dynamodbv2.model PutItemRequest PutItemRequest

List of usage examples for com.amazonaws.services.dynamodbv2.model PutItemRequest PutItemRequest

Introduction

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

Prototype

public PutItemRequest(String tableName, java.util.Map<String, AttributeValue> item) 

Source Link

Document

Constructs a new PutItemRequest object.

Usage

From source file:com.venu.springmvc.dao.AmazonDynamoDBDAO.java

License:Open Source License

public static void main(String[] args) throws Exception {
    init();/*  w  w w  . j av a2s  .com*/

    try {
        String tableName = "my-favorite-movies-table";

        // Create a table with a primary hash key named 'name', which holds a string
        CreateTableRequest createTableRequest = new CreateTableRequest().withTableName(tableName)
                .withKeySchema(new KeySchemaElement().withAttributeName("name").withKeyType(KeyType.HASH))
                .withAttributeDefinitions(new AttributeDefinition().withAttributeName("name")
                        .withAttributeType(ScalarAttributeType.S))
                .withProvisionedThroughput(
                        new ProvisionedThroughput().withReadCapacityUnits(1L).withWriteCapacityUnits(1L));

        // Create table if it does not exist yet
        TableUtils.createTableIfNotExists(dynamoDB, createTableRequest);
        // wait for the table to move into ACTIVE state
        TableUtils.waitUntilActive(dynamoDB, tableName);

        // Describe our new table
        DescribeTableRequest describeTableRequest = new DescribeTableRequest().withTableName(tableName);
        TableDescription tableDescription = dynamoDB.describeTable(describeTableRequest).getTable();
        System.out.println("Table Description: " + tableDescription);

        // Add an item
        Map<String, AttributeValue> item = newItem("Gundamma katha", 1989, "****", "James", "Sara", "Venu");
        PutItemRequest putItemRequest = new PutItemRequest(tableName, item);
        PutItemResult putItemResult = dynamoDB.putItem(putItemRequest);
        System.out.println("Result: " + putItemResult);

        // Add another item
        item = newItem("Manadesam", 1980, "*****", "James", "Billy Bob", "Abburi");
        putItemRequest = new PutItemRequest(tableName, item);
        putItemResult = dynamoDB.putItem(putItemRequest);
        System.out.println("Result: " + putItemResult);

        // Scan items for movies with a year attribute greater than 1985
        HashMap<String, Condition> scanFilter = new HashMap<String, Condition>();
        Condition condition = new Condition().withComparisonOperator(ComparisonOperator.GT.toString())
                .withAttributeValueList(new AttributeValue().withN("1985"));
        scanFilter.put("year", condition);
        ScanRequest scanRequest = new ScanRequest(tableName).withScanFilter(scanFilter);
        ScanResult scanResult = dynamoDB.scan(scanRequest);
        System.out.println("Result: " + scanResult);

    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, which means your request made it "
                + "to AWS, but was rejected with an error response for some reason.");
        System.out.println("Error Message:    " + ase.getMessage());
        System.out.println("HTTP Status Code: " + ase.getStatusCode());
        System.out.println("AWS Error Code:   " + ase.getErrorCode());
        System.out.println("Error Type:       " + ase.getErrorType());
        System.out.println("Request ID:       " + ase.getRequestId());
    } catch (AmazonClientException ace) {
        System.out.println("Caught an AmazonClientException, which means the client encountered "
                + "a serious internal problem while trying to communicate with AWS, "
                + "such as not being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }
}

From source file:com.zhang.aws.dynamodb.AmazonDynamoDBSample.java

License:Open Source License

public static void main(String[] args) throws Exception {
    init();//from  w  w w . j  ava 2  s.  c  o  m

    try {
        String tableName = "my-favorite-movies-table";

        // Create table if it does not exist yet
        if (Tables.doesTableExist(dynamoDB, tableName)) {
            System.out.println("Table " + tableName + " is already ACTIVE");
        } else {
            // Create a table with a primary hash key named 'name', which holds a string
            CreateTableRequest createTableRequest = new CreateTableRequest().withTableName(tableName)
                    .withKeySchema(new KeySchemaElement().withAttributeName("name").withKeyType(KeyType.HASH))
                    .withAttributeDefinitions(new AttributeDefinition().withAttributeName("name")
                            .withAttributeType(ScalarAttributeType.S))
                    .withProvisionedThroughput(
                            new ProvisionedThroughput().withReadCapacityUnits(1L).withWriteCapacityUnits(1L));
            TableDescription createdTableDescription = dynamoDB.createTable(createTableRequest)
                    .getTableDescription();
            System.out.println("Created Table: " + createdTableDescription);

            // Wait for it to become active
            System.out.println("Waiting for " + tableName + " to become ACTIVE...");
            Tables.waitForTableToBecomeActive(dynamoDB, tableName);
        }

        // Describe our new table
        DescribeTableRequest describeTableRequest = new DescribeTableRequest().withTableName(tableName);
        TableDescription tableDescription = dynamoDB.describeTable(describeTableRequest).getTable();
        System.out.println("Table Description: " + tableDescription);

        // Add an item
        Map<String, AttributeValue> item = newItem("Bill & Ted's Excellent Adventure", 1989, "****", "James",
                "Sara");
        PutItemRequest putItemRequest = new PutItemRequest(tableName, item);
        PutItemResult putItemResult = dynamoDB.putItem(putItemRequest);
        System.out.println("Result: " + putItemResult);

        // Add another item
        item = newItem("Airplane", 1980, "*****", "James", "Billy Bob");
        putItemRequest = new PutItemRequest(tableName, item);
        putItemResult = dynamoDB.putItem(putItemRequest);
        System.out.println("Result: " + putItemResult);

        // Scan items for movies with a year attribute greater than 1985
        HashMap<String, Condition> scanFilter = new HashMap<String, Condition>();
        Condition condition = new Condition().withComparisonOperator(ComparisonOperator.GT.toString())
                .withAttributeValueList(new AttributeValue().withN("1985"));
        scanFilter.put("year", condition);
        ScanRequest scanRequest = new ScanRequest(tableName).withScanFilter(scanFilter);
        ScanResult scanResult = dynamoDB.scan(scanRequest);
        System.out.println("Result: " + scanResult);

    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, which means your request made it "
                + "to AWS, but was rejected with an error response for some reason.");
        System.out.println("Error Message:    " + ase.getMessage());
        System.out.println("HTTP Status Code: " + ase.getStatusCode());
        System.out.println("AWS Error Code:   " + ase.getErrorCode());
        System.out.println("Error Type:       " + ase.getErrorType());
        System.out.println("Request ID:       " + ase.getRequestId());
    } catch (AmazonClientException ace) {
        System.out.println("Caught an AmazonClientException, which means the client encountered "
                + "a serious internal problem while trying to communicate with AWS, "
                + "such as not being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }
}

From source file:Database.CustomerData.java

License:Open Source License

public static void main(String[] args) throws Exception {
    init();// w w  w  .jav a 2  s  . co m

    try {

        // Create table if it does not exist yet
        if (Tables.doesTableExist(dynamoDB, tableName)) {
            System.out.println("Table " + tableName + " is already ACTIVE");

        } else {
            // Create a table with a primary hash key Idd 'Id', which holds a string
            CreateTableRequest createTableRequest = new CreateTableRequest().withTableName(tableName)
                    .withKeySchema(new KeySchemaElement().withAttributeName("Id").withKeyType(KeyType.HASH))
                    .withAttributeDefinitions(new AttributeDefinition().withAttributeName("Id")
                            .withAttributeType(ScalarAttributeType.S))
                    .withProvisionedThroughput(
                            new ProvisionedThroughput().withReadCapacityUnits(1L).withWriteCapacityUnits(1L));
            TableDescription createdTableDescription = dynamoDB.createTable(createTableRequest)
                    .getTableDescription();
            System.out.println("Created Table: " + createdTableDescription);

            // Wait for it to become active
            System.out.println("Waiting for " + tableName + " to become ACTIVE...");
            Tables.waitForTableToBecomeActive(dynamoDB, tableName);

            // Describe our new table
            DescribeTableRequest describeTableRequest = new DescribeTableRequest().withTableName(tableName);
            TableDescription tableDescription = dynamoDB.describeTable(describeTableRequest).getTable();
            System.out.println("Table Description: " + tableDescription);

            // Add an item
            Map<String, AttributeValue> item = newItem("Nine Creatives on Creativity", "SQ_NS001", 2014,
                    "Squashouse", "Video");
            PutItemRequest putItemRequest = new PutItemRequest(tableName, item);
            PutItemResult putItemResult = dynamoDB.putItem(putItemRequest);

        }

    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, which means your request made it "
                + "to AWS, but was rejected with an error response for some reason.");
        System.out.println("Error Message:    " + ase.getMessage());
        System.out.println("HTTP Status Code: " + ase.getStatusCode());
        System.out.println("AWS Error Code:   " + ase.getErrorCode());
        System.out.println("Error Type:       " + ase.getErrorType());
        System.out.println("Request ID:       " + ase.getRequestId());
    } catch (AmazonClientException ace) {
        System.out.println("Caught an AmazonClientException, which means the client encountered "
                + "a serious internal problem while trying to communicate with AWS, "
                + "such as not being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }
}

From source file:Database.ProductData.java

License:Open Source License

public static void main(String[] args) throws Exception {
    init();/* w  w  w  . j  a  v  a  2 s .  c  o m*/

    try {
        String tableName = "CustomerData";

        // Create table if it does not exist yet
        if (Tables.doesTableExist(dynamoDB, tableName)) {
            System.out.println("Table " + tableName + " is already ACTIVE");
        } else {
            // Create a table with a primary hash key named 'name', which holds a string
            CreateTableRequest createTableRequest = new CreateTableRequest().withTableName(tableName)
                    .withKeySchema(new KeySchemaElement().withAttributeName("name").withKeyType(KeyType.HASH))
                    .withAttributeDefinitions(new AttributeDefinition().withAttributeName("name")
                            .withAttributeType(ScalarAttributeType.S))
                    .withProvisionedThroughput(
                            new ProvisionedThroughput().withReadCapacityUnits(1L).withWriteCapacityUnits(1L));
            TableDescription createdTableDescription = dynamoDB.createTable(createTableRequest)
                    .getTableDescription();
            System.out.println("Created Table: " + createdTableDescription);

            // Wait for it to become active
            System.out.println("Waiting for " + tableName + " to become ACTIVE...");
            Tables.waitForTableToBecomeActive(dynamoDB, tableName);
        }

        // Describe our new table
        DescribeTableRequest describeTableRequest = new DescribeTableRequest().withTableName(tableName);
        TableDescription tableDescription = dynamoDB.describeTable(describeTableRequest).getTable();
        System.out.println("Table Description: " + tableDescription);

        // Add an item
        Map<String, AttributeValue> item = newItem("Nine Creatives on Creativity", "SQ_NS001", 2014,
                "Squashouse", "Video");
        PutItemRequest putItemRequest = new PutItemRequest(tableName, item);
        PutItemResult putItemResult = dynamoDB.putItem(putItemRequest);
        //            System.out.println("Result: " + putItemResult);

        uploadSampleProducts(tableName);

        //            System.out.println("Result: " +         aQueryResult.withItems(item));

        // Scan items for movies with a year attribute greater than 1985
        HashMap<String, Condition> scanFilter = new HashMap<String, Condition>();
        Condition condition = new Condition().withComparisonOperator(ComparisonOperator.GT.toString())
                .withAttributeValueList(new AttributeValue().withN("1985"));
        scanFilter.put("year", condition);
        ScanRequest scanRequest = new ScanRequest(tableName).withScanFilter(scanFilter);
        ScanResult scanResult = dynamoDB.scan(scanRequest);
        System.out.println("Result: " + scanResult);

    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, which means your request made it "
                + "to AWS, but was rejected with an error response for some reason.");
        System.out.println("Error Message:    " + ase.getMessage());
        System.out.println("HTTP Status Code: " + ase.getStatusCode());
        System.out.println("AWS Error Code:   " + ase.getErrorCode());
        System.out.println("Error Type:       " + ase.getErrorType());
        System.out.println("Request ID:       " + ase.getRequestId());
    } catch (AmazonClientException ace) {
        System.out.println("Caught an AmazonClientException, which means the client encountered "
                + "a serious internal problem while trying to communicate with AWS, "
                + "such as not being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }
}

From source file:io.milton.s3.db.DynamoDBServiceImpl.java

License:Open Source License

/**
 * Put given item into the table. If the item exists, it replaces the entire
 * item. Instead of replacing the entire item, if you want to update only
 * specific attributes, you can use the updateItem method.
 * /*from   w  ww.j a  v  a2s  .  c om*/
 * @param item
 */
@Override
public PutItemResult putItem(String tableName, Map<String, AttributeValue> item) {
    if (item == null || item.isEmpty()) {
        LOG.warn("Does not support store null or empty entity in table " + tableName);
        return null;
    }

    LOG.info("Successfully putted item " + item.toString() + " into " + tableName);

    try {
        PutItemRequest putItemRequest = new PutItemRequest(tableName, item);
        PutItemResult putItemResult = dynamoDBClient.putItem(putItemRequest);
        LOG.info("Putted status: " + putItemResult);
        return putItemResult;
    } catch (AmazonServiceException ase) {
        LOG.error("Failed to put given item into the " + tableName, ase);
    } catch (AmazonClientException ace) {
        LOG.error("Failed to put given item into the " + tableName, ace);
    }
    return null;
}

From source file:main.java.ddb.loader.DDBLoaderUtils.java

License:Apache License

static void putTableItem() {
    Map<String, AttributeValue> item = getNewItem();
    PutItemRequest putItemRequest = new PutItemRequest(DDBSampleLoader.TBL_NAME, item);
    DDBSampleLoader.ddb_client.putItem(putItemRequest);
}

From source file:nyu.twitter.lg.FentchTwitter.java

License:Open Source License

private static void insertDB(String id, int count, String name, double longtitude, double latitude,
        String place, String message, String date) {
    // Add an item
    Map<String, AttributeValue> item = newItem(id, count, name, longtitude, latitude, place, message, date);
    //      System.out.println(item);
    PutItemRequest putItemRequest = new PutItemRequest(tableName, item);
    PutItemResult putItemResult = dynamoDB.putItem(putItemRequest);
    //      System.out.println("Result: " + putItemResult);
}

From source file:org.eluder.logback.ext.dynamodb.appender.DynamoDbAppender.java

License:Open Source License

@Override
protected void handle(final ILoggingEvent event, final String encoded) throws Exception {
    Item item = Item.fromJSON(encoded).withPrimaryKey(createEventId(event));
    Map<String, AttributeValue> attributes = InternalUtils.toAttributeValues(item);
    PutItemRequest request = new PutItemRequest(table, attributes);
    String errorMessage = format("Appender '%s' failed to send logging event '%s' to DynamoDB table '%s'",
            getName(), event, table);//from   w  ww  . j  a  va2  s. co m
    CountDownLatch latch = new CountDownLatch(isAsyncParent() ? 0 : 1);
    dynamoDb.putItemAsync(request,
            new LoggingEventHandler<PutItemRequest, PutItemResult>(this, latch, errorMessage));
    AppenderExecutors.awaitLatch(this, latch, getMaxFlushTime());
}

From source file:org.selman.tweetamo.PersistentStore.java

License:Apache License

public void add(Status status) throws Exception {
    try {/*from   w w  w  .jav  a  2 s  .  co  m*/
        Map<String, AttributeValue> item = newItem(status);
        PutItemRequest putItemRequest = new PutItemRequest(TABLE_NAME, item);
        dynamoDB.putItem(putItemRequest);
        LOG.info("Stored status in Dynamo: " + status.getId());
    } catch (Exception e) {
        handleException(e);
    }
}

From source file:pa3.RemoteWorkerSQS.java

License:Open Source License

public static void main(String[] args) throws Exception {

    initSQSandDynamoDB();/*from   w ww  .j a  v  a2s.com*/
    try {

        String tableName = "PA3" + args[2];
        // Create table if it does not exist yet
        if (Tables.doesTableExist(dynamoDB, tableName)) {
            System.out.println("Table " + tableName + " is already ACTIVE");
        } else {
            // Create a table with a primary hash key named 'name', which
            // holds a string
            CreateTableRequest createTableRequest = new CreateTableRequest().withTableName(tableName)
                    .withKeySchema(new KeySchemaElement().withAttributeName("taskID").withKeyType(KeyType.HASH))
                    .withAttributeDefinitions(new AttributeDefinition().withAttributeName("taskID")
                            .withAttributeType(ScalarAttributeType.S))
                    .withProvisionedThroughput(
                            new ProvisionedThroughput().withReadCapacityUnits(1L).withWriteCapacityUnits(1L));
            TableDescription createdTableDescription = dynamoDB.createTable(createTableRequest)
                    .getTableDescription();
            System.out.println("Created Table: " + createdTableDescription);

            // Wait for it to become active
            System.out.println("Waiting for " + tableName + " to become ACTIVE...");
            Tables.awaitTableToBecomeActive(dynamoDB, tableName);
        }

        String noOfWorkers = args[4];
        String requestQueueName = "TaskQueue" + args[2];
        String responseQueueName = "TaskResponseQueue" + args[2];
        String clientOrWorker = args[0];

        // Create a queue
        //System.out.println("Accessing SQS queue: "+requestQueueName);
        String myRequestQueueUrl = sqs.createQueue(requestQueueName).getQueueUrl();

        //System.out.println("Creating a new SQS queue called MyResponseQueue.\n");
        String myResponseQueueUrl = sqs.createQueue(responseQueueName).getQueueUrl();

        // Receive the messages
        try {
            ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(myRequestQueueUrl);
            receiveMessageRequest.setVisibilityTimeout(900);
            receiveMessageRequest.setWaitTimeSeconds(20);
            while (true) {
                List<Message> messages = sqs.receiveMessage(receiveMessageRequest).getMessages();
                // Throw exception when queue gets empty
                if (messages.isEmpty()) {
                    break;
                }
                for (Message message : messages) {
                    try {
                        String[] splitTask = message.getBody().split(" ");
                        //DynamoDB
                        Map<String, AttributeValue> item = newItem(splitTask[0]);
                        PutItemRequest putItemRequest = new PutItemRequest(tableName, item)
                                .withConditionExpression("attribute_not_exists(taskID)");
                        dynamoDB.putItem(putItemRequest);

                        //System.out.println(splitTask[0]+" : "+splitTask[2]);
                        // Execute Task
                        Thread.sleep(Long.parseLong(splitTask[2]));
                        sqs.sendMessage(new SendMessageRequest(myResponseQueueUrl, splitTask[0]));
                        // Delete the message
                        String messageReceiptHandle = message.getReceiptHandle();
                        sqs.deleteMessage(new DeleteMessageRequest(myRequestQueueUrl, messageReceiptHandle));

                    } catch (ConditionalCheckFailedException e) {
                        //e.printStackTrace();
                    }
                }
            }
        } catch (Exception ex) {
            //ex.printStackTrace();
        }

    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, which means your request made it "
                + "to AWS, but was rejected with an error response for some reason.");
        System.out.println("Error Message:    " + ase.getMessage());
        System.out.println("HTTP Status Code: " + ase.getStatusCode());
        System.out.println("AWS Error Code:   " + ase.getErrorCode());
        System.out.println("Error Type:       " + ase.getErrorType());
        System.out.println("Request ID:       " + ase.getRequestId());
    } catch (AmazonClientException ace) {
        System.out.println("Caught an AmazonClientException, which means the client encountered "
                + "a serious internal problem while trying to communicate with AWS, "
                + "such as not being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }

}