Example usage for com.amazonaws.services.dynamodbv2.model ScalarAttributeType S

List of usage examples for com.amazonaws.services.dynamodbv2.model ScalarAttributeType S

Introduction

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

Prototype

ScalarAttributeType S

To view the source code for com.amazonaws.services.dynamodbv2.model ScalarAttributeType S.

Click Source Link

Usage

From source file:whgHelper.java

License:Open Source License

public static void setTable(AmazonDynamoDBClient dynamoDB, String tableName) {

    // Create table if it does not exist yet
    if (Tables.doesTableExist(dynamoDB, tableName)) {
        System.out.println("Table " + tableName + " is already ACTIVE");
    } else {/*from  w  w  w.j a  va 2  s .c  o m*/
        // Create a table with a primary hash key named 'name', which holds a string
        CreateTableRequest createTableRequest = new CreateTableRequest().withTableName(tableName)
                .withKeySchema(new KeySchemaElement().withAttributeName("alertId").withKeyType(KeyType.HASH))
                .withAttributeDefinitions(new AttributeDefinition().withAttributeName("alertId")
                        .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);
    }
    return;
}

From source file:DynamoDBUtils.java

License:Open Source License

/**
 * Creates the Amazon DynamoDB table if it does not already exist and have the correct schema. Then it
 * waits for the table to become active.
 *
 * @param client//from www  .  j a v a2  s.  c om
 *        The {@link AmazonDynamoDBClient} with Amazon DynamoDB read and write privileges
 * @param tableName
 *        The Amazon DynamoDB table to create
 * @param key
 *        The Amazon DynamoDB table hashkey
 * @param readCapacityUnits
 *        Number of read capacity units for the Amazon DynamoDB table
 * @param writeCapacityUnits
 *        Number of write capacity units for the Amazon DynamoDB table
 * @throws IllegalStateException
 *         Table already exists and schema does not match
 * @throws IllegalStateException
 *         Table is already getting created
 */
public static void createTable(AmazonDynamoDBClient client, String tableName, String key,
        long readCapacityUnits, long writeCapacityUnits) {
    if (tableExists(client, tableName)) {
        if (tableHasCorrectSchema(client, tableName, key)) {
            waitForActive(client, tableName);
            return;
        } else {
            throw new IllegalStateException("Table already exists and schema does not match");
        }

    }
    CreateTableRequest createTableRequest = new CreateTableRequest();
    createTableRequest.setTableName(tableName);
    createTableRequest.setKeySchema(Arrays.asList(new KeySchemaElement(key, KeyType.HASH)));
    createTableRequest
            .setProvisionedThroughput(new ProvisionedThroughput(readCapacityUnits, writeCapacityUnits));
    createTableRequest
            .setAttributeDefinitions(Arrays.asList(new AttributeDefinition(key, ScalarAttributeType.S)));
    try {
        client.createTable(createTableRequest);
    } catch (ResourceInUseException e) {
        throw new IllegalStateException("The table may already be getting created.", e);
    }
    LOG.info("Table " + tableName + " created");
    waitForActive(client, tableName);
}

From source file:DynamoDBUtils.java

License:Open Source License

/**
 * Verifies if the table has the expected schema.
 *
 * @param client//  w  w  w.j  av  a  2s .c o  m
 *        The {@link AmazonDynamoDBClient} with Amazon DynamoDB read privileges
 * @param tableName
 *        The Amazon DynamoDB table to check
 * @param key
 *        The expected hashkey for the Amazon DynamoDB table
 * @return true if the Amazon DynamoDB table exists and the expected hashkey matches the table schema,
 *         otherwise return false
 */
private static boolean tableHasCorrectSchema(AmazonDynamoDBClient client, String tableName, String key) {
    DescribeTableRequest describeTableRequest = new DescribeTableRequest();
    describeTableRequest.setTableName(tableName);
    DescribeTableResult describeTableResult = client.describeTable(describeTableRequest);
    TableDescription tableDescription = describeTableResult.getTable();
    if (tableDescription.getAttributeDefinitions().size() != 1) {
        LOG.error("The number of attribute definitions does not match the existing table.");
        return false;
    }
    AttributeDefinition attributeDefinition = tableDescription.getAttributeDefinitions().get(0);
    if (!attributeDefinition.getAttributeName().equals(key)
            || !attributeDefinition.getAttributeType().equals(ScalarAttributeType.S.toString())) {
        LOG.error("Attribute name or type does not match existing table.");
        return false;
    }
    List<KeySchemaElement> KSEs = tableDescription.getKeySchema();
    if (KSEs.size() != 1) {
        LOG.error("The number of key schema elements does not match the existing table.");
        return false;
    }
    KeySchemaElement kse = KSEs.get(0);
    if (!kse.getAttributeName().equals(key) || !kse.getKeyType().equals(KeyType.HASH.toString())) {
        LOG.error("The hash key does not match the existing table.");
        return false;
    }
    return true;

}

From source file:AmazonDynamoDBSample_PutThrottled.java

License:Open Source License

public static void main(String[] args) throws Exception {
    init();//  w w  w .  ja  v a  2 s.  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("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);

        Thread[] thrds = new Thread[16];
        for (int i = 0; i < thrds.length; i++) {
            thrds[i] = newItemCreationThread(tableName, i);
            thrds[i].start();
        }
        for (Thread thrd : thrds) {
            thrd.join();
        }

        // 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:TableCreator.java

License:Open Source License

public static void main(String[] args) throws Exception {
    init();/*w ww. ja va  2s.  co  m*/
    long readCapacity = Long.valueOf(args[0]);
    long writeCapacity = Long.valueOf(args[1]);
    try {
        String tableName = "messages";

        //          DeleteTableRequest deleteTableRequest = new DeleteTableRequest(tableName);
        //          dynamoDB.deleteTable(deleteTableRequest);
        //          
        //          waitForTableToBecomeAvailable(tableName);

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

        // Wait for it to become active
        waitForTableToBecomeAvailable(tableName);

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

    } 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:DynamoDB.java

License:Open Source License

public void createTable() throws InterruptedException {
    // Create table if it does not exist yet
    if (Tables.doesTableExist(dynamoDB, tableName)) {
        System.out.println("Table " + tableName + " is already ACTIVE");
    } else {//w  w  w. j av  a2  s.  co  m
        // Create a table with a primary hash key named 'name', 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.awaitTableToBecomeActive(dynamoDB, tableName);
    }

}

From source file:amazon.dynamodb.util.GeoTableUtil.java

License:Open Source License

/**
 * <p>//from  w  ww  . j  ava2 s  .co  m
 * Construct a create table request object based on GeoDataManagerConfiguration. The users can update any aspect of
 * the request and call it.
 * </p>
 * Example:
 * 
 * <pre>
 * AmazonDynamoDBClient ddb = new AmazonDynamoDBClient(new ClasspathPropertiesFileCredentialsProvider());
 * Region usWest2 = Region.getRegion(Regions.US_WEST_2);
 * ddb.setRegion(usWest2);
 * 
 * CreateTableRequest createTableRequest = GeoTableUtil.getCreateTableRequest(config);
 * CreateTableResult createTableResult = ddb.createTable(createTableRequest);
 * </pre>
 * 
 * @return Generated create table request.
 */
public static CreateTableRequest getCreateTableRequest(GeoDataManagerConfiguration config) {
    CreateTableRequest createTableRequest = new CreateTableRequest().withTableName(config.getTableName())
            .withProvisionedThroughput(
                    new ProvisionedThroughput().withReadCapacityUnits(10L).withWriteCapacityUnits(5L))
            .withKeySchema(
                    new KeySchemaElement().withKeyType(KeyType.HASH)
                            .withAttributeName(config.getHashKeyAttributeName()),
                    new KeySchemaElement().withKeyType(KeyType.RANGE)
                            .withAttributeName(config.getRangeKeyAttributeName()))
            .withAttributeDefinitions(
                    new AttributeDefinition().withAttributeType(ScalarAttributeType.N)
                            .withAttributeName(config.getHashKeyAttributeName()),
                    new AttributeDefinition().withAttributeType(ScalarAttributeType.S)
                            .withAttributeName(config.getRangeKeyAttributeName()),
                    new AttributeDefinition().withAttributeType(ScalarAttributeType.N)
                            .withAttributeName(config.getGeohashAttributeName()))
            .withLocalSecondaryIndexes(new LocalSecondaryIndex().withIndexName(config.getGeohashIndexName())
                    .withKeySchema(
                            new KeySchemaElement().withKeyType(KeyType.HASH)
                                    .withAttributeName(config.getHashKeyAttributeName()),
                            new KeySchemaElement().withKeyType(KeyType.RANGE)
                                    .withAttributeName(config.getGeohashAttributeName()))
                    .withProjection(new Projection().withProjectionType(ProjectionType.ALL)));

    return createTableRequest;
}

From source file:aws.example.dynamodb.CreateTable.java

License:Open Source License

public static void main(String[] args) {
    final String USAGE = "\n" + "Usage:\n" + "    CreateTable <table>\n\n" + "Where:\n"
            + "    table - the table to create.\n\n" + "Example:\n" + "    CreateTable HelloTable\n";

    if (args.length < 1) {
        System.out.println(USAGE);
        System.exit(1);/*ww w.j  av a 2s.  c om*/
    }

    /* Read the name from command args */
    String table_name = args[0];

    System.out.format("Creating table \"%s\" with a simple primary key: \"Name\".\n", table_name);

    CreateTableRequest request = new CreateTableRequest()
            .withAttributeDefinitions(new AttributeDefinition("Name", ScalarAttributeType.S))
            .withKeySchema(new KeySchemaElement("Name", KeyType.HASH))
            .withProvisionedThroughput(new ProvisionedThroughput(new Long(10), new Long(10)))
            .withTableName(table_name);

    final AmazonDynamoDBClient ddb = new AmazonDynamoDBClient();

    try {
        CreateTableResult result = ddb.createTable(request);
    } catch (AmazonServiceException e) {
        System.err.println(e.getErrorMessage());
        System.exit(1);
    }
    System.out.println("Done!");
}

From source file:aws.example.dynamodb.CreateTableCompositeKey.java

License:Open Source License

public static void main(String[] args) {
    final String USAGE = "\n" + "Usage:\n" + "    CreateTable <table>\n\n" + "Where:\n"
            + "    table - the table to create.\n\n" + "Example:\n" + "    CreateTable GreetingsTable\n";

    if (args.length < 1) {
        System.out.println(USAGE);
        System.exit(1);//from  w ww . java  2  s  . c o m
    }

    /* Read the name from command args */
    String table_name = args[0];

    System.out.format("Creating table %s\n with a composite primary key:\n");
    System.out.format("* Language - partition key\n");
    System.out.format("* Greeting - sort key\n");

    CreateTableRequest request = new CreateTableRequest()
            .withAttributeDefinitions(new AttributeDefinition("Language", ScalarAttributeType.S),
                    new AttributeDefinition("Greeting", ScalarAttributeType.S))
            .withKeySchema(new KeySchemaElement("Language", KeyType.HASH),
                    new KeySchemaElement("Greeting", KeyType.RANGE))
            .withProvisionedThroughput(new ProvisionedThroughput(new Long(10), new Long(10)))
            .withTableName(table_name);

    final AmazonDynamoDBClient ddb = new AmazonDynamoDBClient();

    try {
        CreateTableResult result = ddb.createTable(request);
    } catch (AmazonServiceException e) {
        System.err.println(e.getErrorMessage());
        System.exit(1);
    }
    System.out.println("Done!");
}

From source file:br.com.faccilitacorretor.middleware.dynamo.AmazonDynamoDBSample.java

License:Open Source License

public static void main(String[] args) throws Exception {
    init();//from   w  w  w.  j  av a 2 s.  com

    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.awaitTableToBecomeActive(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());
    }
}