Example usage for com.amazonaws.services.dynamodbv2.util TableUtils createTableIfNotExists

List of usage examples for com.amazonaws.services.dynamodbv2.util TableUtils createTableIfNotExists

Introduction

In this page you can find the example usage for com.amazonaws.services.dynamodbv2.util TableUtils createTableIfNotExists.

Prototype

public static final boolean createTableIfNotExists(final AmazonDynamoDB dynamo,
        final CreateTableRequest createTableRequest) 

Source Link

Document

Creates the table and ignores any errors if it already exists.

Usage

From source file:AmazonDynamoDBSample_PutThrottled.java

License:Open Source License

public static void main(String[] args) throws Exception {
    init();//www  .  j a  v a  2s  .  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:com.envirover.spl.stream.DynamoDBOutputStream.java

License:Open Source License

@Override
public void open() throws IOException {
    AmazonDynamoDB dynamoDBClient = AmazonDynamoDBClientBuilder.defaultClient();

    if (TableUtils.createTableIfNotExists(dynamoDBClient,
            new CreateTableRequest().withTableName(tableName)
                    .withKeySchema(new KeySchemaElement(ATTR_DEVICE_ID, KeyType.HASH),
                            new KeySchemaElement(ATTR_TIME, KeyType.RANGE))
                    .withAttributeDefinitions(new AttributeDefinition(ATTR_DEVICE_ID, ScalarAttributeType.S),
                            new AttributeDefinition(ATTR_TIME, ScalarAttributeType.N))
                    .withProvisionedThroughput(new ProvisionedThroughput().withReadCapacityUnits(READ_CAPACITY)
                            .withWriteCapacityUnits(WRITE_CAPACITY)))) {

        try {/*from  w w w  .  ja  va2 s . c o  m*/
            TableUtils.waitUntilActive(dynamoDBClient, tableName);
        } catch (TableNeverTransitionedToStateException e) {
            throw new IOException(e);
        } catch (InterruptedException e) {
            throw new IOException(e);
        }

        logger.info(MessageFormat.format("DynamoDB table ''{0}'' created.", tableName));
    }

    dynamoDB = new DynamoDB(dynamoDBClient);
}

From source file:com.hussi.aws.dynamoDB.AmazonDynamoDBSample.java

License:Open Source License

public static void main(String[] args) throws Exception {
    init();//from ww w.ja va2 s.co m

    try {
        String tableName = "hussi_first_dynamo_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);

        // 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.venu.springmvc.dao.AmazonDynamoDBDAO.java

License:Open Source License

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

    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:io.ignitr.dispatchr.manager.core.data.ClientRepository.java

License:Apache License

/**
 * Creates the DynamoDB tables that are used by this repository.
 *
 * @throws Exception/*from   w w  w.ja v a2 s . c om*/
 */
@PostConstruct
private void initialize() throws Exception {
    LOG.info("Initializing DynamoDB tables for TopicRepository...");

    CreateTableRequest clientRequest = new CreateTableRequest(
            Arrays.asList(new AttributeDefinition("clientId", ScalarAttributeType.S)), CLIENT_TABLE_NAME,
            Arrays.asList(new KeySchemaElement("clientId", KeyType.HASH)), new ProvisionedThroughput(4L, 1L));

    if (TableUtils.createTableIfNotExists(dynamoDBClient, clientRequest)) {
        LOG.info("Creating DynamoDB table '{}'...", CLIENT_TABLE_NAME);
    } else {
        LOG.debug("DynamoDB table '{}' already exists!  Skipping table creation.", CLIENT_TABLE_NAME);
    }

    LOG.info("Waiting for DynamoDB table '{}' to become active...", CLIENT_TABLE_NAME);
    TableUtils.waitUntilActive(dynamoDBClient, CLIENT_TABLE_NAME);
    LOG.info("DynamoDB table '{}' is active", CLIENT_TABLE_NAME);
}

From source file:io.ignitr.dispatchr.manager.core.data.SubscriptionRepository.java

License:Apache License

@PostConstruct
private void initialize() throws Exception {
    LOG.info("Initializing DynamoDB tables for SubscriptionRepository...");

    // Dispatchr_Subscription
    CreateTableRequest subscriptionRequest = new CreateTableRequest(
            Arrays.asList(new AttributeDefinition("id", ScalarAttributeType.S)), SUBSCRIPTION_TABLE_NAME,
            Arrays.asList(new KeySchemaElement("id", KeyType.HASH)), new ProvisionedThroughput(4L, 1L));

    // Dispatchr_TopicSubscriptions
    CreateTableRequest topicSubscriptionsRequest = new CreateTableRequest(
            Arrays.asList(new AttributeDefinition("topic", ScalarAttributeType.S),
                    new AttributeDefinition("subscriptionId", ScalarAttributeType.S)

            ), TOPIC_SUBSCRIPTIONS_TABLE_NAME, Arrays.asList(new KeySchemaElement("topic", KeyType.HASH),
                    new KeySchemaElement("subscriptionId", KeyType.RANGE)),
            new ProvisionedThroughput(4L, 1L));

    if (TableUtils.createTableIfNotExists(dynamoDBClient, subscriptionRequest)) {
        LOG.info("Creating DynamoDB table '{}'...", SUBSCRIPTION_TABLE_NAME);
    } else {//  w ww  .j  a v  a2s .  c  o  m
        LOG.debug("DynamoDB table '{}' already exists!  Skipping table creation.", SUBSCRIPTION_TABLE_NAME);
    }

    if (TableUtils.createTableIfNotExists(dynamoDBClient, topicSubscriptionsRequest)) {
        LOG.info("Creating DynamoDB table '{}'...", TOPIC_SUBSCRIPTIONS_TABLE_NAME);
    } else {
        LOG.debug("DynamoDB table '{}' already exists!  Skipping table creation.",
                TOPIC_SUBSCRIPTIONS_TABLE_NAME);
    }

    LOG.info("Waiting for DynamoDB table '{}' to become active...", SUBSCRIPTION_TABLE_NAME);
    TableUtils.waitUntilActive(dynamoDBClient, SUBSCRIPTION_TABLE_NAME);
    LOG.info("DynamoDB table '{}' is active", SUBSCRIPTION_TABLE_NAME);

    LOG.info("Waiting for DynamoDB table '{}' to become active...", TOPIC_SUBSCRIPTIONS_TABLE_NAME);
    TableUtils.waitUntilActive(dynamoDBClient, TOPIC_SUBSCRIPTIONS_TABLE_NAME);
    LOG.info("DynamoDB table '{}' is active", TOPIC_SUBSCRIPTIONS_TABLE_NAME);
}

From source file:io.ignitr.dispatchr.manager.core.data.TopicRepository.java

License:Apache License

@PostConstruct
private void initialize() throws Exception {
    LOG.info("Initializing DynamoDB tables for TopicRepository...");

    CreateTableRequest request = new CreateTableRequest(
            Arrays.asList(new AttributeDefinition("name", ScalarAttributeType.S)), TOPIC_TABLE_NAME,
            Arrays.asList(new KeySchemaElement("name", KeyType.HASH)), new ProvisionedThroughput(4L, 1L));

    if (TableUtils.createTableIfNotExists(dynamoDBClient, request)) {
        LOG.info("Creating DynamoDB table '{}'...", TOPIC_TABLE_NAME);
    } else {//www .ja  va2  s . co m
        LOG.debug("DynamoDB table '{}' already exists!  Skipping table creation.", TOPIC_TABLE_NAME);
    }

    LOG.info("Waiting for DynamoDB table '{}' to become active...", TOPIC_TABLE_NAME);
    TableUtils.waitUntilActive(dynamoDBClient, TOPIC_TABLE_NAME);
    LOG.info("DynamoDB table '{}' is active", TOPIC_TABLE_NAME);
}

From source file:io.klerch.alexa.state.handler.AWSDynamoStateHandler.java

License:Open Source License

private void ensureTableExists() throws InterruptedException {
    // given custom table is always assumed as existing so you can have this option to bypass existance checks
    // for reason of least privileges on used AWS credentials or better performance
    if (!tableExistenceApproved || !tableExists()) {
        final ArrayList<AttributeDefinition> attributeDefinitions = new ArrayList<>();
        // describe keys
        attributeDefinitions.add(new AttributeDefinition().withAttributeName(pkUser).withAttributeType("S"));
        attributeDefinitions.add(new AttributeDefinition().withAttributeName(pkModel).withAttributeType("S"));
        // define keys
        final ArrayList<KeySchemaElement> keySchema = new ArrayList<>();
        keySchema.add(new KeySchemaElement().withAttributeName(pkUser).withKeyType(KeyType.HASH));
        keySchema.add(new KeySchemaElement().withAttributeName(pkModel).withKeyType(KeyType.RANGE));
        // prepare table creation request
        final CreateTableRequest awsRequest = new CreateTableRequest().withTableName(tableName)
                .withKeySchema(keySchema).withAttributeDefinitions(attributeDefinitions)
                .withProvisionedThroughput(new ProvisionedThroughput().withReadCapacityUnits(readCapacityUnits)
                        .withWriteCapacityUnits(writeCapacityUnits));
        // create on not existing table
        if (TableUtils.createTableIfNotExists(awsClient, awsRequest)) {
            log.info(String.format(
                    "Table '%1$s' is created in DynamoDB. Now standing by for up to ten minutes for this table to be in active state.",
                    tableName));/*from  w w w.  j  a  v  a 2 s.  c  o  m*/
            // wait for table to be in ACTIVE state in order to proceed with read or write
            // this could take up to possible ten minutes so be sure to run this code once before publishing your skill ;)
            TableUtils.waitUntilActive(awsClient, awsRequest.getTableName());
        }
    }
}

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

License:Apache License

static void createTable() throws Exception {
    try {//from  ww  w .ja  v a2  s.  c om
        CreateTableRequest create_req = new CreateTableRequest().withTableName(DDBSampleLoader.TBL_NAME)
                .withKeySchema(new KeySchemaElement().withAttributeName("Id").withKeyType(KeyType.HASH))
                .withAttributeDefinitions(new AttributeDefinition().withAttributeName("Id")
                        .withAttributeType(ScalarAttributeType.S))
                .withProvisionedThroughput(
                        new ProvisionedThroughput().withReadCapacityUnits(DDBSampleLoader.RCU)
                                .withWriteCapacityUnits(DDBSampleLoader.WCU));

        DDBSampleLoader.log.info("Creating a new table ...");
        TableUtils.createTableIfNotExists(DDBSampleLoader.ddb_client, create_req);

        DDBSampleLoader.log.info("Waiting for the table status to be 'ACTIVE' ...");
        TableUtils.waitUntilActive(DDBSampleLoader.ddb_client, DDBSampleLoader.TBL_NAME);

    } catch (AmazonServiceException e) {
        DDBSampleLoader.log.error("Caught an AmazonServiceException ...");
        DDBSampleLoader.log.error("Error Message:    " + e.getMessage());
        DDBSampleLoader.log.error("HTTP Status Code: " + e.getStatusCode());
        DDBSampleLoader.log.error("AWS Error Code:   " + e.getErrorCode());
        DDBSampleLoader.log.error("Error Type:       " + e.getErrorType());
        DDBSampleLoader.log.error("Request ID:       " + e.getRequestId());

    } catch (AmazonClientException e) {
        DDBSampleLoader.log.error("Caught an AmazonClientException ...");
        DDBSampleLoader.log.error("Error Message:    " + e.getMessage());
    }
}

From source file:mx.iteso.desi.cloud.keyvalue.DynamoDBStorage.java

License:Apache License

public DynamoDBStorage(String dbName) {
    BasicAWSCredentials cred = new BasicAWSCredentials(Config.accessKeyID, Config.secretAccessKey);

    if (Config.DynamoDbClientType == Config.DYNAMODBCLIENTTYPE.Local) {
        client = new AmazonDynamoDBClient(cred);
        client.setRegion(Region.getRegion(Config.amazonRegion));
        client.setEndpoint("http://localhost:8000");
    } else {// www.j a v a 2s . c  om
        client = AmazonDynamoDBClientBuilder.standard().withRegion(Config.amazonRegion)
                .withCredentials(new AWSStaticCredentialsProvider(cred)).build();
    }
    docClient = new DynamoDB(client);

    this.dbName = dbName;
    // Create a table
    CreateTableRequest createTableRequest = new CreateTableRequest().withTableName(dbName)
            .withKeySchema(new KeySchemaElement().withAttributeName("keyword").withKeyType(KeyType.HASH),
                    new KeySchemaElement().withAttributeName("inx").withKeyType(KeyType.RANGE))
            .withAttributeDefinitions(
                    new AttributeDefinition().withAttributeName("keyword")
                            .withAttributeType(ScalarAttributeType.S),
                    new AttributeDefinition().withAttributeName("inx").withAttributeType(ScalarAttributeType.N))
            .withProvisionedThroughput(
                    new ProvisionedThroughput().withReadCapacityUnits(1L).withWriteCapacityUnits(1L));
    // Create table if it does not exist yet
    TableUtils.createTableIfNotExists(client, createTableRequest);
    // Wait for the table to move into Active state
    try {
        TableUtils.waitUntilActive(client, dbName);
    } catch (Exception e) {
        // Do nothing... yet
    }
    //requestItems.put(dbName, requestList);
}