com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder Java Examples

The following examples show how to use com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DBUtil.java    From chatbot with Apache License 2.0 8 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 File: AwsClientTracingTest.java    From zipkin-aws with 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 #3
Source File: DynamoDBUtil.java    From serverless with 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 #4
Source File: DBUtil.java    From alexa-skill-java with 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 #5
Source File: MostRecentEncryptedItem.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
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 #6
Source File: EncryptionContextOverridesWithDynamoDBMapper.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
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 #7
Source File: MoviesDeleteTable.java    From aws-doc-sdk-examples with 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 #8
Source File: DynamoDBLocalFixture.java    From aws-dynamodb-examples with Apache License 2.0 6 votes vote down vote up
/**
 * You can use mvn to run DynamoDBLocalFixture, e.g.
 * <p>
 * $ mvn clean package
 * <p>
 * $ mvn exec:java -Dexec.mainClass="com.amazonaws.services.dynamodbv2.DynamoDBLocalFixture" \
 * -Dexec.classpathScope="test" \
 * -Dsqlite4java.library.path=target/dependencies
 * <p>
 * It's recommended to run "aws configure" one time before you run DynamoDBLocalFixture
 *
 * @param args - no args
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    AmazonDynamoDB dynamodb = null;
    try {
        // Create an in-memory and in-process instance of DynamoDB Local that skips HTTP
        dynamodb = DynamoDBEmbedded.create().amazonDynamoDB();
        // use the DynamoDB API with DynamoDBEmbedded
        listTables(dynamodb.listTables(), "DynamoDB Embedded");
    } finally {
        // Shutdown the thread pools in DynamoDB Local / Embedded
        if(dynamodb != null) {
            dynamodb.shutdown();
        }
    }
    
    // Create an in-memory and in-process instance of DynamoDB Local that runs over HTTP
    final String[] localArgs = { "-inMemory" };
    DynamoDBProxyServer server = null;
    try {
        server = ServerRunner.createServerFromCommandLineArgs(localArgs);
        server.start();

        dynamodb = AmazonDynamoDBClientBuilder.standard().withEndpointConfiguration(
            // we can use any region here
            new AwsClientBuilder.EndpointConfiguration("http://localhost:8000", "us-west-2"))
            .build();

        // use the DynamoDB API over HTTP
        listTables(dynamodb.listTables(), "DynamoDB Local over HTTP");
    } finally {
        // Stop the DynamoDB Local endpoint
        if(server != null) {
            server.stop();
        }
    }
}
 
Example #9
Source File: DynaliteContainer.java    From testcontainers-java with MIT License 5 votes vote down vote up
/**
 * Gets a preconfigured {@link AmazonDynamoDB} client object for connecting to this
 * container.
 *
 * @return preconfigured client
 */
public AmazonDynamoDB getClient() {
    return AmazonDynamoDBClientBuilder.standard()
            .withEndpointConfiguration(getEndpointConfiguration())
            .withCredentials(getCredentials())
            .build();
}
 
Example #10
Source File: DeleteItem.java    From aws-doc-sdk-examples with 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 #11
Source File: DynamoDbDelegate.java    From dynamodb-janusgraph-storage-backend with Apache License 2.0 5 votes vote down vote up
public DynamoDbDelegate(final String endpoint, final String region, final AWSCredentialsProvider provider,
    final ClientConfiguration clientConfig, final Configuration titanConfig,
    final Map<String, RateLimiter> readRateLimit, final Map<String, RateLimiter> writeRateLimit,
    final long maxRetries, final long retryMillis, final String prefix, final String metricsPrefix,
    final RateLimiter controlPlaneRateLimiter) {
    if (prefix == null) {
        throw new IllegalArgumentException("prefix must be set");
    }
    if (metricsPrefix == null || metricsPrefix.isEmpty()) {
        throw new IllegalArgumentException("metrics-prefix may not be null or empty");
    }
    this.metricsPrefix = metricsPrefix;
    executorGaugeName = String.format("%s.%s_executor-queue-size", this.metricsPrefix, prefix);
    clientThreadPool = getPoolFromNs(titanConfig);
    if (!MetricManager.INSTANCE.getRegistry().getNames().contains(executorGaugeName)) {
        MetricManager.INSTANCE.getRegistry().register(executorGaugeName, (Gauge<Integer>) () -> clientThreadPool.getQueue().size());
    }

    client = AmazonDynamoDBClientBuilder.standard()
            .withCredentials(provider)
            .withClientConfiguration(clientConfig)
            .withEndpointConfiguration(getEndpointConfiguration(Optional.ofNullable(endpoint), region))
        .build();
    this.readRateLimit = readRateLimit;
    this.writeRateLimit = writeRateLimit;
    this.controlPlaneRateLimiter = controlPlaneRateLimiter;
    this.maxConcurrentUsers = titanConfig.get(Constants.DYNAMODB_CLIENT_EXECUTOR_MAX_CONCURRENT_OPERATIONS);
    this.maxRetries = maxRetries;
    this.retryMillis = retryMillis;
    if (maxConcurrentUsers < 1) {
        throw new IllegalArgumentException("need at least one user otherwise wont make progress on scan");
    }
    this.listTablesApiName = String.format("%s_ListTables", prefix);
}
 
Example #12
Source File: DynaliteContainerTest.java    From testcontainers-java with MIT License 5 votes vote down vote up
@Test
public void simpleTestWithManualClientCreation() {
    final AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard()
            .withEndpointConfiguration(dynamoDB.getEndpointConfiguration())
            .withCredentials(dynamoDB.getCredentials())
            .build();

    runTest(client);
}
 
Example #13
Source File: AwsKmsEncryptedObject.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
public static void encryptRecord(final String cmkArn, final String region) {
  // Sample object to be encrypted
  DataPoJo record = new DataPoJo();
  record.setPartitionAttribute("is this");
  record.setSortAttribute(55);
  record.setExample("data");
  record.setSomeNumbers(99);
  record.setSomeBinary(new byte[]{0x00, 0x01, 0x02});
  record.setLeaveMe("alone");

  // Set up our configuration and clients
  final AmazonDynamoDB ddb = AmazonDynamoDBClientBuilder.standard().withRegion(region).build();
  final AWSKMS kms = AWSKMSClientBuilder.standard().withRegion(region).build();
  final DirectKmsMaterialProvider cmp = new DirectKmsMaterialProvider(kms, cmkArn);
  // Encryptor creation
  final DynamoDBEncryptor encryptor = DynamoDBEncryptor.getInstance(cmp);
  // Mapper Creation
  // Please note the use of SaveBehavior.PUT (SaveBehavior.CLOBBER works as well).
  // Omitting this can result in data-corruption.
  DynamoDBMapperConfig mapperConfig = DynamoDBMapperConfig.builder().withSaveBehavior(SaveBehavior.PUT).build();
  DynamoDBMapper mapper = new DynamoDBMapper(ddb, mapperConfig, new AttributeEncryptor(encryptor));

  System.out.println("Plaintext Record: " + record);
  // Save the item to the DynamoDB table
  mapper.save(record);

  // Retrieve the encrypted item (directly without decrypting) from Dynamo so we can see it in our example
  final Map<String, AttributeValue> itemKey = new HashMap<>();
  itemKey.put("partition_attribute", new AttributeValue().withS("is this"));
  itemKey.put("sort_attribute", new AttributeValue().withN("55"));
  System.out.println("Encrypted Record: " + ddb.getItem("ExampleTable", itemKey).getItem());
  
  // Retrieve (and decrypt) it from DynamoDB
  DataPoJo decrypted_record = mapper.load(DataPoJo.class, "is this", 55);
  System.out.println("Decrypted Record: " + decrypted_record);
}
 
Example #14
Source File: DynamoDBClientFetcherImpl.java    From athenz with Apache License 2.0 5 votes vote down vote up
private DynamoDBClientAndCredentials getAuthenticatedDynamoDBClient(DynamoDBClientSettings dynamoDBClientSettings,
                                                      ZTSClientNotificationSender ztsClientNotificationSender) {
    AWSCredentialsProviderImpl credentialsProvider = getCredentials(dynamoDBClientSettings, ztsClientNotificationSender);
    AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard()
            .withCredentials(credentialsProvider)
            .withRegion(dynamoDBClientSettings.getRegion())
            .build();
    return new DynamoDBClientAndCredentials(client, credentialsProvider);
}
 
Example #15
Source File: DynamoDBSourceConfig.java    From pulsar with Apache License 2.0 5 votes vote down vote up
public AmazonDynamoDB buildDynamoDBClient(AwsCredentialProviderPlugin credPlugin) {
    AmazonDynamoDBClientBuilder builder = AmazonDynamoDBClientBuilder.standard();

    if (!this.getAwsEndpoint().isEmpty()) {
        builder.setEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(this.getDynamoEndpoint(), this.getAwsRegion()));
    }
    if (!this.getAwsRegion().isEmpty()) {
        builder.setRegion(this.getAwsRegion());
    }
    builder.setCredentials(credPlugin.getCredentialProvider());
    return builder.build();
}
 
Example #16
Source File: APIDemoHandler.java    From tutorials with MIT License 5 votes vote down vote up
@Override
public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context) throws IOException {

    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
    JSONObject responseJson = new JSONObject();

    AmazonDynamoDB client = AmazonDynamoDBClientBuilder.defaultClient();
    DynamoDB dynamoDb = new DynamoDB(client);

    try {
        JSONObject event = (JSONObject) parser.parse(reader);

        if (event.get("body") != null) {

            Person person = new Person((String) event.get("body"));

            dynamoDb.getTable(DYNAMODB_TABLE_NAME)
                .putItem(new PutItemSpec().withItem(new Item().withNumber("id", person.getId())
                    .withString("name", person.getName())));
        }

        JSONObject responseBody = new JSONObject();
        responseBody.put("message", "New item created");

        JSONObject headerJson = new JSONObject();
        headerJson.put("x-custom-header", "my custom header value");

        responseJson.put("statusCode", 200);
        responseJson.put("headers", headerJson);
        responseJson.put("body", responseBody.toString());

    } catch (ParseException pex) {
        responseJson.put("statusCode", 400);
        responseJson.put("exception", pex);
    }

    OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8");
    writer.write(responseJson.toString());
    writer.close();
}
 
Example #17
Source File: AwsClient.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
public AmazonDynamoDB createDynamoDbClient(AwsCredentialView awsCredential, String region) {
    return AmazonDynamoDBClientBuilder.standard()
            .withClientConfiguration(getDynamoDbClientConfiguration())
            .withCredentials(getCredentialProvider(awsCredential))
            .withRegion(region)
            .build();
}
 
Example #18
Source File: DynamoDBIOTestHelper.java    From beam with Apache License 2.0 5 votes vote down vote up
static AmazonDynamoDB getDynamoDBClient() {
  // Note: each test case got to have their own dynamo client obj, can't be shared
  // Otherwise will run into connection pool issue
  return AmazonDynamoDBClientBuilder.standard()
      .withEndpointConfiguration(
          localStackContainer.getEndpointConfiguration(LocalStackContainer.Service.DYNAMODB))
      .withCredentials(localStackContainer.getDefaultCredentialsProvider())
      .build();
}
 
Example #19
Source File: DeleteTable.java    From aws-doc-sdk-examples with 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 #20
Source File: MoviesCreateTable.java    From aws-doc-sdk-examples with 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);

        String tableName = "Movies";

        try {
            System.out.println("Attempting to create table; please wait...");
            Table table = dynamoDB.createTable(tableName,
                Arrays.asList(new KeySchemaElement("year", KeyType.HASH), // Partition
                                                                          // key
                    new KeySchemaElement("title", KeyType.RANGE)), // Sort key
                Arrays.asList(new AttributeDefinition("year", ScalarAttributeType.N),
                    new AttributeDefinition("title", ScalarAttributeType.S)),
                new ProvisionedThroughput(10L, 10L));
            table.waitForActive();
            System.out.println("Success.  Table status: " + table.getDescription().getTableStatus());

        }
        catch (Exception e) {
            System.err.println("Unable to create table: ");
            System.err.println(e.getMessage());
        }

    }
 
Example #21
Source File: DynamoDBIOTestHelper.java    From beam with Apache License 2.0 5 votes vote down vote up
static void startServerClient() {
  localStackContainer.start();

  if (dynamoDBClient == null) {
    dynamoDBClient =
        AmazonDynamoDBClientBuilder.standard()
            .withEndpointConfiguration(
                localStackContainer.getEndpointConfiguration(
                    LocalStackContainer.Service.DYNAMODB))
            .withCredentials(localStackContainer.getDefaultCredentialsProvider())
            .build();
  }
}
 
Example #22
Source File: BasicDynamoDBProvider.java    From beam with Apache License 2.0 5 votes vote down vote up
@Override
public AmazonDynamoDB createDynamoDB() {
  return AmazonDynamoDBClientBuilder.standard()
      .withCredentials(getCredentialsProvider())
      .withRegion(region)
      .build();
}
 
Example #23
Source File: DynamoDBMapperExample.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
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 File: MoviesItemOps02.java    From aws-doc-sdk-examples with 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 File: MoviesItemOps05.java    From aws-doc-sdk-examples with 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 File: MoviesItemOps04.java    From aws-doc-sdk-examples with 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 File: MoviesItemOps03.java    From aws-doc-sdk-examples with 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 File: MoviesItemOps06.java    From aws-doc-sdk-examples with 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 File: MoviesScan.java    From aws-doc-sdk-examples with 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 File: MoviesItemOps01.java    From aws-doc-sdk-examples with 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());
        }

    }