Java Code Examples for com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder

The following examples show how to use com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder. These examples are extracted from open source projects. 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 Project: chatbot   Source File: DBUtil.java    License: Apache License 2.0 7 votes vote down vote up
private static AmazonDynamoDB getClient() {
    if (null != dynamodbClient) {
        return dynamodbClient;
    }

    String region = System.getProperty("DYNAMODB_REGION");
    if (null == region) {
        System.err.println("Region not set, default \"" + Regions.US_EAST_1.name() + "\" is used");
        region = Regions.US_EAST_1.name();
    }
    System.out.println("DynamoDB region: " + region);

    dynamodbClient = AmazonDynamoDBClientBuilder.standard()
            .withRegion(region)
            .build();

    return dynamodbClient;
}
 
Example 2
Source Project: alexa-skill-java   Source File: DBUtil.java    License: Apache License 2.0 6 votes vote down vote up
private static AmazonDynamoDB getClient() {
    if (null != dynamodbClient) {
        return dynamodbClient;
    }

    String region = System.getProperty("DYNAMODB_REGION");
    if (null == region) {
        System.err.println("Region not set, default \"" + Regions.US_EAST_1.name() + "\" is used");
        region = Regions.US_EAST_1.name();
    }
    System.out.println("DynamoDB region: " + region);

    dynamodbClient = AmazonDynamoDBClientBuilder.standard()
            .withRegion(region)
            .build();

    return dynamodbClient;
}
 
Example 3
Source Project: zipkin-aws   Source File: AwsClientTracingTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setup() {
  String endpoint = "http://localhost:" + mockServer.getPort();
  HttpTracing httpTracing = HttpTracing.create(tracing);
  AmazonDynamoDBClientBuilder clientBuilder = AmazonDynamoDBClientBuilder.standard()
      .withCredentials(
          new AWSStaticCredentialsProvider(new BasicAWSCredentials("access", "secret")))
      .withEndpointConfiguration(
          new AwsClientBuilder.EndpointConfiguration(endpoint, "us-east-1"));

  dbClient = AwsClientTracing.create(httpTracing).build(clientBuilder);

  s3Client = AwsClientTracing.create(httpTracing).build(AmazonS3ClientBuilder.standard()
      .withCredentials(
          new AWSStaticCredentialsProvider(new BasicAWSCredentials("access", "secret")))
      .withEndpointConfiguration(
          new AwsClientBuilder.EndpointConfiguration(endpoint, "us-east-1"))
      .enableForceGlobalBucketAccess());
}
 
Example 4
Source Project: aws-doc-sdk-examples   Source File: MoviesDeleteTable.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {

        AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard()
            .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration("http://localhost:8000", "us-west-2"))
            .build();

        DynamoDB dynamoDB = new DynamoDB(client);

        Table table = dynamoDB.getTable("Movies");

        try {
            System.out.println("Attempting to delete table; please wait...");
            table.delete();
            table.waitForDelete();
            System.out.print("Success.");

        }
        catch (Exception e) {
            System.err.println("Unable to delete table: ");
            System.err.println(e.getMessage());
        }
    }
 
Example 5
Source Project: serverless   Source File: DynamoDBUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static final AmazonDynamoDB getClient() {
    if (null != dynamodbClient) {
        return dynamodbClient;
    }

    String region = System.getenv("DYNAMODB_REGION");
    if (null == region) {
        System.err.println("Region is null, using default \"" + Regions.US_WEST_1 + "\"");
        region = Regions.US_WEST_1.name();
    }
    System.out.println("DynamoDB region: " + region);

    dynamodbClient = AmazonDynamoDBClientBuilder.standard()
            .withRegion(region)
            .build();
    
    System.out.println("Got DynamoDB client...");

    return dynamodbClient;
}
 
Example 6
public static void main(String[] args) throws GeneralSecurityException {
  final String mode = args[0];
  final String region = args[1];
  final String tableName = args[2];
  final String keyTableName = args[3];
  final String cmkArn = args[4];
  final String materialName = args[5];
  
  if (mode.equalsIgnoreCase("--setup")) {
    AmazonDynamoDB ddb = AmazonDynamoDBClientBuilder.standard().withRegion(region).build();
    MetaStore.createTable(ddb, keyTableName, new ProvisionedThroughput(1L, 1L));
    return;
  }
  
  encryptRecord(tableName, keyTableName, region, cmkArn, materialName);
}
 
Example 7
public static void main(String[] args) throws GeneralSecurityException {
    final String cmkArn = args[0];
    final String region = args[1];
    final String encryptionContextTableName = args[2];

    AmazonDynamoDB ddb = null;
    AWSKMS kms = null;
    try {
        ddb = AmazonDynamoDBClientBuilder.standard().withRegion(region).build();
        kms = AWSKMSClientBuilder.standard().withRegion(region).build();
        encryptRecord(cmkArn, encryptionContextTableName, ddb, kms);
    } finally {
        if (ddb != null) {
            ddb.shutdown();
        }
        if (kms != null) {
            kms.shutdown();
        }
    }
}
 
Example 8
public DynamoDBMetadataHandler()
{
    // disable Glue if the env var is present and not explicitly set to "false"
    super((System.getenv(GLUE_ENV) != null && !"false".equalsIgnoreCase(System.getenv(GLUE_ENV))), SOURCE_TYPE);
    ddbClient = AmazonDynamoDBClientBuilder.standard().build();
    glueClient = getAwsGlue();
    tableResolver = new DynamoDBTableResolver(invoker, ddbClient);
}
 
Example 9
Source Project: dynamo-cassandra-proxy   Source File: DynamoManager.java    License: Apache License 2.0 5 votes vote down vote up
public synchronized AmazonDynamoDB get() {
    if (ddb == null) {
        AwsClientBuilder.EndpointConfiguration endpointConfiguration = new AwsClientBuilder.EndpointConfiguration(dynamodbEndpoint, signinRegion);
        ddb = AmazonDynamoDBClientBuilder.standard().withEndpointConfiguration(endpointConfiguration).build();
    }

    return ddb;
}
 
Example 10
Source Project: smartapp-sdk-java   Source File: AppConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public DefaultInstalledAppContextStore installedAppContextStore(
        TokenRefreshService tokenRefreshService) {
    AmazonDynamoDB client = AmazonDynamoDBClientBuilder.defaultClient();
    DynamoDB dynamoDB = new DynamoDB(client);
    return new DynamoDBInstalledAppContextStore(dynamoDB, tokenRefreshService);
}
 
Example 11
@Override
public AmazonDynamoDB amazonDynamoDB() {
    return decorateWithConfigsAndBuild(
        AmazonDynamoDBClientBuilder.standard(),
        LocalstackDocker::getEndpointDynamoDB
    );
}
 
Example 12
Source Project: java-specialagent   Source File: AwsTest.java    License: Apache License 2.0 5 votes vote down vote up
private static AmazonDynamoDB buildClient() {
  final EndpointConfiguration endpointConfiguration = new EndpointConfiguration("http://localhost:8000", "us-west-2");
  final BasicAWSCredentials awsCreds = new BasicAWSCredentials("access_key_id", "secret_key_id");
  return AmazonDynamoDBClientBuilder
    .standard()
    .withEndpointConfiguration(endpointConfiguration)
    .withCredentials(new AWSStaticCredentialsProvider(awsCreds))
    .withClientConfiguration(new ClientConfiguration().withConnectionTimeout(1))
    .build();
}
 
Example 13
Source Project: java-specialagent   Source File: Aws1ITest.java    License: Apache License 2.0 5 votes vote down vote up
private static AmazonDynamoDB buildClient() {
  final AwsClientBuilder.EndpointConfiguration endpointConfiguration = new AwsClientBuilder.EndpointConfiguration("http://localhost:8000", "us-west-2");
  final BasicAWSCredentials awsCreds = new BasicAWSCredentials("access_key_id", "secret_key_id");
  final AmazonDynamoDBClientBuilder builder = AmazonDynamoDBClientBuilder
    .standard()
    .withEndpointConfiguration(endpointConfiguration)
    .withCredentials(new AWSStaticCredentialsProvider(awsCreds))
    .withClientConfiguration(new ClientConfiguration().withConnectionTimeout(1));
  return builder.build();
}
 
Example 14
Source Project: pacbot   Source File: InventoryUtilTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Fetch dynamo DB tables test.
 *
 * @throws Exception the exception
 */
@SuppressWarnings("static-access")
@Test
public void fetchDynamoDBTablesTest() throws Exception {
    
    mockStatic(AmazonDynamoDBClientBuilder.class);
    AmazonDynamoDB awsClient = PowerMockito.mock(AmazonDynamoDB.class);
    AmazonDynamoDBClientBuilder amazonDynamoDBClientBuilder = PowerMockito.mock(AmazonDynamoDBClientBuilder.class);
    AWSStaticCredentialsProvider awsStaticCredentialsProvider = PowerMockito.mock(AWSStaticCredentialsProvider.class);
    PowerMockito.whenNew(AWSStaticCredentialsProvider.class).withAnyArguments().thenReturn(awsStaticCredentialsProvider);
    when(amazonDynamoDBClientBuilder.standard()).thenReturn(amazonDynamoDBClientBuilder);
    when(amazonDynamoDBClientBuilder.withCredentials(anyObject())).thenReturn(amazonDynamoDBClientBuilder);
    when(amazonDynamoDBClientBuilder.withRegion(anyString())).thenReturn(amazonDynamoDBClientBuilder);
    when(amazonDynamoDBClientBuilder.build()).thenReturn(awsClient);
    
    ListTablesResult listTableResult = new ListTablesResult();
    List<String> tables = new ArrayList<>();
    tables.add(new String());
    listTableResult.setTableNames(tables);
    when(awsClient.listTables()).thenReturn(listTableResult);
    
    DescribeTableResult describeTableResult = new DescribeTableResult();
    TableDescription table = new TableDescription();
    table.setTableArn("tableArn");
    describeTableResult.setTable(table);
    when(awsClient.describeTable(anyString())).thenReturn(describeTableResult);
    
    when(awsClient.listTagsOfResource(anyObject())).thenReturn(new ListTagsOfResourceResult());
    assertThat(inventoryUtil.fetchDynamoDBTables(new BasicSessionCredentials("awsAccessKey", "awsSecretKey", "sessionToken"), 
            "skipRegions", "account","accountName").size(), is(1));
    
}
 
Example 15
Source Project: syndesis   Source File: AWSDDBMetadataRetrieval.java    License: Apache License 2.0 5 votes vote down vote up
DescribeTableResult fetchTableDescription(Map<String, Object> properties) {
    AWSCredentials credentials = new BasicAWSCredentials(properties.get("accessKey").toString(),
        properties.get("secretKey").toString());
    AWSCredentialsProvider credentialsProvider = new AWSStaticCredentialsProvider(credentials);
    AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().withCredentials(credentialsProvider)
        .withRegion(Regions.valueOf(properties.get("region").toString())).build();

    return client.describeTable(properties.get("tableName").toString());
}
 
Example 16
Source Project: strongbox   Source File: DynamoDB.java    License: Apache License 2.0 5 votes vote down vote up
public static DynamoDB fromCredentials(AWSCredentialsProvider awsCredentials,
                                       ClientConfiguration clientConfiguration,
                                       SecretsGroupIdentifier groupIdentifier,
                                       ReadWriteLock readWriteLock) {
    AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard()
        .withCredentials(awsCredentials)
        .withClientConfiguration(verifyOrThrow(transformAndVerifyOrThrow(clientConfiguration)))
        .withRegion(groupIdentifier.region.getName())
        .build();
    return new DynamoDB(client, awsCredentials, clientConfiguration, groupIdentifier, readWriteLock);
}
 
Example 17
Source Project: strongbox   Source File: IntegrationTestHelper.java    License: Apache License 2.0 5 votes vote down vote up
private static void cleanUpDynamoDBTables(Regions testRegion, String testResourcePrefix, Date createdBeforeThreshold,
                                          AWSCredentialsProvider awsCredentials) {
    LOG.info("Cleaning DynamoDB...");
    AmazonDynamoDB dynamoDBClient = AmazonDynamoDBClientBuilder.standard()
            .withCredentials(awsCredentials)
            .withRegion(testRegion)
            .build();

    List<String> tableNames = dynamoDBClient.listTables().getTableNames();
    for (String tableName: tableNames) {
        if (!tableName.startsWith(testResourcePrefix)) {
            continue;
        }
        LOG.info(String.format("Checking if table %s needs cleaning...", tableName));

        try {
            TableDescription desc = dynamoDBClient.describeTable(tableName).getTable();
            if (!desc.getTableName().equals(TableStatus.DELETING.toString()) &&
                    desc.getCreationDateTime() != null &&
                    desc.getCreationDateTime().before(createdBeforeThreshold)) {
                LOG.info("Cleaning up table: " + tableName);
                dynamoDBClient.deleteTable(tableName);
            }
        } catch (ResourceNotFoundException e) {
            LOG.info("Looks like table was already cleaned up: " + tableName);
        }
    }
}
 
Example 18
Source Project: zipkin-aws   Source File: ITTracingRequestHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override protected AmazonDynamoDB newClient(int i) {
  ClientConfiguration clientConfiguration = new ClientConfiguration();
  clientConfiguration.setMaxErrorRetry(0);
  clientConfiguration.setRequestTimeout(1000);

  return AmazonDynamoDBClientBuilder.standard()
      .withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials("x", "y")))
      .withEndpointConfiguration(
          new AwsClientBuilder.EndpointConfiguration("http://127.0.0.1:" + i, "us-east-1"))
      .withRequestHandlers(new TracingRequestHandler(httpTracing))
      .withClientConfiguration(clientConfiguration)
      .build();
}
 
Example 19
Source Project: aws-doc-sdk-examples   Source File: TryDaxHelper.java    License: Apache License 2.0 5 votes vote down vote up
DynamoDB getDynamoDBClient() {
   System.out.println("Creating a DynamoDB client");
   AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard()
           .withRegion(region)
           .build();
   return new DynamoDB(client);
}
 
Example 20
Source Project: aws-doc-sdk-examples   Source File: UpdateTable.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args)
{
    final String USAGE = "\n" +
        "Usage:\n" +
        "    UpdateTable <table> <read> <write>\n\n" +
        "Where:\n" +
        "    table - the table to put the item in.\n" +
        "    read  - the new read capacity of the table.\n" +
        "    write - the new write capacity of the table.\n\n" +
        "Example:\n" +
        "    UpdateTable HelloTable 16 10\n";

    if (args.length < 3) {
        System.out.println(USAGE);
        System.exit(1);
    }

    String table_name = args[0];
    Long read_capacity = Long.parseLong(args[1]);
    Long write_capacity = Long.parseLong(args[2]);

    System.out.format(
            "Updating %s with new provisioned throughput values\n",
            table_name);
    System.out.format("Read capacity : %d\n", read_capacity);
    System.out.format("Write capacity : %d\n", write_capacity);

    ProvisionedThroughput table_throughput = new ProvisionedThroughput(
          read_capacity, write_capacity);

    final AmazonDynamoDB ddb = AmazonDynamoDBClientBuilder.defaultClient();

    try {
        ddb.updateTable(table_name, table_throughput);
    } catch (AmazonServiceException e) {
        System.err.println(e.getErrorMessage());
        System.exit(1);
    }
    System.out.println("Done!");
}
 
Example 21
Source Project: aws-doc-sdk-examples   Source File: DeleteTable.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args)
{
    final String USAGE = "\n" +
        "Usage:\n" +
        "    DeleteTable <table>\n\n" +
        "Where:\n" +
        "    table - the table to delete.\n\n" +
        "Example:\n" +
        "    DeleteTable Greetings\n\n" +
        "**Warning** This program will actually delete the table\n" +
        "            that you specify!\n";

    if (args.length < 1) {
        System.out.println(USAGE);
        System.exit(1);
    }

    String table_name = args[0];

    System.out.format("Deleting table %s...\n", table_name);

    final AmazonDynamoDB ddb = AmazonDynamoDBClientBuilder.defaultClient();

    try {
        ddb.deleteTable(table_name);
    } catch (AmazonServiceException e) {
        System.err.println(e.getErrorMessage());
        System.exit(1);
    }
    System.out.println("Done!");
}
 
Example 22
Source Project: aws-doc-sdk-examples   Source File: DeleteItem.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args)
{
    final String USAGE = "\n" +
        "Usage:\n" +
        "    DeleteItem <table> <name>\n\n" +
        "Where:\n" +
        "    table - the table to delete the item from.\n" +
        "    name  - the item to delete from the table,\n" +
        "            using the primary key \"Name\"\n\n" +
        "Example:\n" +
        "    DeleteItem HelloTable World\n\n" +
        "**Warning** This program will actually delete the item\n" +
        "            that you specify!\n";

    if (args.length < 2) {
        System.out.println(USAGE);
        System.exit(1);
    }

    String table_name = args[0];
    String name = args[1];

    System.out.format("Deleting item \"%s\" from %s\n", name, table_name);

    HashMap<String,AttributeValue> key_to_get =
        new HashMap<String,AttributeValue>();

    key_to_get.put("Name", new AttributeValue(name));

    final AmazonDynamoDB ddb = AmazonDynamoDBClientBuilder.defaultClient();

    try {
        ddb.deleteItem(table_name, key_to_get);
    } catch (AmazonServiceException e) {
        System.err.println(e.getErrorMessage());
        System.exit(1);
    }

    System.out.println("Done!");
}
 
Example 23
public static void main(String[] args) throws IOException {

        // Set the AWS region you want to access.
        Regions usWest2 = Regions.US_WEST_2;
        client = AmazonDynamoDBClientBuilder.standard().withRegion(usWest2).build();

        DimensionType dimType = new DimensionType();
        dimType.setHeight("8.00");
        dimType.setLength("11.0");
        dimType.setThickness("1.0");

        Book book = new Book();
        book.setId(502);
        book.setTitle("Book 502");
        book.setISBN("555-5555555555");
        book.setBookAuthors(new HashSet<String>(Arrays.asList("Author1", "Author2")));
        book.setDimensions(dimType);

        DynamoDBMapper mapper = new DynamoDBMapper(client);
        mapper.save(book);

        Book bookRetrieved = mapper.load(Book.class, 502);
        System.out.println("Book info: " + "\n" + bookRetrieved);

        bookRetrieved.getDimensions().setHeight("9.0");
        bookRetrieved.getDimensions().setLength("12.0");
        bookRetrieved.getDimensions().setThickness("2.0");

        mapper.save(bookRetrieved);

        bookRetrieved = mapper.load(Book.class, 502);
        System.out.println("Updated book info: " + "\n" + bookRetrieved);
    }
 
Example 24
Source Project: aws-doc-sdk-examples   Source File: MoviesItemOps02.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard()
            .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration("http://localhost:8000", "us-west-2"))
            .build();

        DynamoDB dynamoDB = new DynamoDB(client);

        Table table = dynamoDB.getTable("Movies");

        int year = 2015;
        String title = "The Big New Movie";

        GetItemSpec spec = new GetItemSpec().withPrimaryKey("year", year, "title", title);

        try {
            System.out.println("Attempting to read the item...");
            Item outcome = table.getItem(spec);
            System.out.println("GetItem succeeded: " + outcome);

        }
        catch (Exception e) {
            System.err.println("Unable to read item: " + year + " " + title);
            System.err.println(e.getMessage());
        }

    }
 
Example 25
Source Project: aws-doc-sdk-examples   Source File: MoviesItemOps05.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard()
            .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration("http://localhost:8000", "us-west-2"))
            .build();

        DynamoDB dynamoDB = new DynamoDB(client);

        Table table = dynamoDB.getTable("Movies");

        int year = 2015;
        String title = "The Big New Movie";

        UpdateItemSpec updateItemSpec = new UpdateItemSpec()
            .withPrimaryKey(new PrimaryKey("year", year, "title", title)).withUpdateExpression("remove info.actors[0]")
            .withConditionExpression("size(info.actors) > :num").withValueMap(new ValueMap().withNumber(":num", 3))
            .withReturnValues(ReturnValue.UPDATED_NEW);

        // Conditional update (we expect this to fail)
        try {
            System.out.println("Attempting a conditional update...");
            UpdateItemOutcome outcome = table.updateItem(updateItemSpec);
            System.out.println("UpdateItem succeeded:\n" + outcome.getItem().toJSONPretty());

        }
        catch (Exception e) {
            System.err.println("Unable to update item: " + year + " " + title);
            System.err.println(e.getMessage());
        }
    }
 
Example 26
Source Project: aws-doc-sdk-examples   Source File: MoviesItemOps04.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard()
            .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration("http://localhost:8000", "us-west-2"))
            .build();

        DynamoDB dynamoDB = new DynamoDB(client);

        Table table = dynamoDB.getTable("Movies");

        int year = 2015;
        String title = "The Big New Movie";

        UpdateItemSpec updateItemSpec = new UpdateItemSpec().withPrimaryKey("year", year, "title", title)
            .withUpdateExpression("set info.rating = info.rating + :val")
            .withValueMap(new ValueMap().withNumber(":val", 1)).withReturnValues(ReturnValue.UPDATED_NEW);

        try {
            System.out.println("Incrementing an atomic counter...");
            UpdateItemOutcome outcome = table.updateItem(updateItemSpec);
            System.out.println("UpdateItem succeeded:\n" + outcome.getItem().toJSONPretty());

        }
        catch (Exception e) {
            System.err.println("Unable to update item: " + year + " " + title);
            System.err.println(e.getMessage());
        }
    }
 
Example 27
Source Project: aws-doc-sdk-examples   Source File: MoviesItemOps03.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard()
            .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration("http://localhost:8000", "us-west-2"))
            .build();

        DynamoDB dynamoDB = new DynamoDB(client);

        Table table = dynamoDB.getTable("Movies");

        int year = 2015;
        String title = "The Big New Movie";

        UpdateItemSpec updateItemSpec = new UpdateItemSpec().withPrimaryKey("year", year, "title", title)
            .withUpdateExpression("set info.rating = :r, info.plot=:p, info.actors=:a")
            .withValueMap(new ValueMap().withNumber(":r", 5.5).withString(":p", "Everything happens all at once.")
                .withList(":a", Arrays.asList("Larry", "Moe", "Curly")))
            .withReturnValues(ReturnValue.UPDATED_NEW);

        try {
            System.out.println("Updating the item...");
            UpdateItemOutcome outcome = table.updateItem(updateItemSpec);
            System.out.println("UpdateItem succeeded:\n" + outcome.getItem().toJSONPretty());

        }
        catch (Exception e) {
            System.err.println("Unable to update item: " + year + " " + title);
            System.err.println(e.getMessage());
        }
    }
 
Example 28
Source Project: aws-doc-sdk-examples   Source File: MoviesItemOps06.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard()
            .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration("http://localhost:8000", "us-west-2"))
            .build();

        DynamoDB dynamoDB = new DynamoDB(client);

        Table table = dynamoDB.getTable("Movies");

        int year = 2015;
        String title = "The Big New Movie";

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

        // Conditional delete (we expect this to fail)

        try {
            System.out.println("Attempting a conditional delete...");
            table.deleteItem(deleteItemSpec);
            System.out.println("DeleteItem succeeded");
        }
        catch (Exception e) {
            System.err.println("Unable to delete item: " + year + " " + title);
            System.err.println(e.getMessage());
        }
    }
 
Example 29
Source Project: aws-doc-sdk-examples   Source File: MoviesScan.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard()
            .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration("http://localhost:8000", "us-west-2"))
            .build();

        DynamoDB dynamoDB = new DynamoDB(client);

        Table table = dynamoDB.getTable("Movies");

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

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

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

        }
        catch (Exception e) {
            System.err.println("Unable to scan the table:");
            System.err.println(e.getMessage());
        }
    }
 
Example 30
Source Project: aws-doc-sdk-examples   Source File: MoviesItemOps01.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard()
            .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration("http://localhost:8000", "us-west-2"))
            .build();

        DynamoDB dynamoDB = new DynamoDB(client);

        Table table = dynamoDB.getTable("Movies");

        int year = 2015;
        String title = "The Big New Movie";

        final Map<String, Object> infoMap = new HashMap<String, Object>();
        infoMap.put("plot", "Nothing happens at all.");
        infoMap.put("rating", 0);

        try {
            System.out.println("Adding a new item...");
            PutItemOutcome outcome = table
                .putItem(new Item().withPrimaryKey("year", year, "title", title).withMap("info", infoMap));

            System.out.println("PutItem succeeded:\n" + outcome.getPutItemResult());

        }
        catch (Exception e) {
            System.err.println("Unable to add item: " + year + " " + title);
            System.err.println(e.getMessage());
        }

    }