From 42c45dbe7b2357c5c9779c2de85443a3b2979f20 Mon Sep 17 00:00:00 2001 From: scmacdon Date: Wed, 20 Nov 2024 11:52:49 -0500 Subject: [PATCH] rolled in review comments --- .../dynamodb/{ => scenario}/Scenario.java | 799 +++++++-------- .../{ => scenario}/ScenarioPartiQ.java | 688 ++++++------- .../{ => scenario}/ScenarioPartiQLBatch.java | 914 +++++++++--------- .../dynamodb/src/test/java/DynamoDBTest.java | 4 +- 4 files changed, 1203 insertions(+), 1202 deletions(-) rename javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/{ => scenario}/Scenario.java (97%) rename javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/{ => scenario}/ScenarioPartiQ.java (93%) rename javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/{ => scenario}/ScenarioPartiQLBatch.java (93%) diff --git a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/Scenario.java b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/scenario/Scenario.java similarity index 97% rename from javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/Scenario.java rename to javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/scenario/Scenario.java index 5b9ee49bc11..943b3b3da06 100644 --- a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/Scenario.java +++ b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/scenario/Scenario.java @@ -1,399 +1,400 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.dynamodb; - -// snippet-start:[dynamodb.java2.scenario.import] -import com.fasterxml.jackson.databind.JsonNode; -import software.amazon.awssdk.core.waiters.WaiterResponse; -import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; -import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; -import software.amazon.awssdk.enhanced.dynamodb.TableSchema; -import software.amazon.awssdk.enhanced.dynamodb.Key; -import software.amazon.awssdk.enhanced.dynamodb.model.QueryConditional; -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.dynamodb.DynamoDbClient; -import software.amazon.awssdk.services.dynamodb.model.DynamoDbException; -import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition; -import software.amazon.awssdk.services.dynamodb.model.KeySchemaElement; -import software.amazon.awssdk.services.dynamodb.model.CreateTableRequest; -import software.amazon.awssdk.services.dynamodb.model.KeyType; -import software.amazon.awssdk.services.dynamodb.model.CreateTableResponse; -import software.amazon.awssdk.services.dynamodb.model.AttributeValue; -import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughput; -import software.amazon.awssdk.services.dynamodb.model.AttributeValueUpdate; -import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException; -import software.amazon.awssdk.services.dynamodb.model.DescribeTableRequest; -import software.amazon.awssdk.services.dynamodb.model.DescribeTableResponse; -import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest; -import software.amazon.awssdk.services.dynamodb.model.AttributeAction; -import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; -import software.amazon.awssdk.services.dynamodb.model.GetItemRequest; -import software.amazon.awssdk.services.dynamodb.waiters.DynamoDbWaiter; -import com.fasterxml.jackson.core.JsonFactory; -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.ObjectNode; -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; -// snippet-end:[dynamodb.java2.scenario.import] - -// snippet-start:[dynamodb.java2.scenario.main] -/** - * Before running this Java V2 code example, set up your development - * environment, including your credentials. - * - * For more information, see the following documentation topic: - * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html - * - * This Java example performs these tasks: - * - * 1. Creates the Amazon DynamoDB Movie table with partition and sort key. - * 2. Puts data into the Amazon DynamoDB table from a JSON document using the - * Enhanced client. - * 3. Gets data from the Movie table. - * 4. Adds a new item. - * 5. Updates an item. - * 6. Uses a Scan to query items using the Enhanced client. - * 7. Queries all items where the year is 2013 using the Enhanced Client. - * 8. Deletes the table. - */ - -public class Scenario { - public static final String DASHES = new String(new char[80]).replace("\0", "-"); - - public static void main(String[] args) throws IOException { - final String usage = """ - - Usage: - - - Where: - fileName - The path to the moviedata.json file that you can download from the Amazon DynamoDB Developer Guide. - """; - - if (args.length != 1) { - System.out.println(usage); - System.exit(1); - } - - String tableName = "Movies"; - String fileName = args[0]; - Region region = Region.US_EAST_1; - DynamoDbClient ddb = DynamoDbClient.builder() - .region(region) - .build(); - - System.out.println(DASHES); - System.out.println("Welcome to the Amazon DynamoDB example scenario."); - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println( - "1. Creating an Amazon DynamoDB table named Movies with a key named year and a sort key named title."); - createTable(ddb, tableName); - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println("2. Loading data into the Amazon DynamoDB table."); - loadData(ddb, tableName, fileName); - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println("3. Getting data from the Movie table."); - getItem(ddb); - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println("4. Putting a record into the Amazon DynamoDB table."); - putRecord(ddb); - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println("5. Updating a record."); - updateTableItem(ddb, tableName); - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println("6. Scanning the Amazon DynamoDB table."); - scanMovies(ddb, tableName); - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println("7. Querying the Movies released in 2013."); - queryTable(ddb); - System.out.println(DASHES); - - System.out.println(DASHES); - System.out.println("8. Deleting the Amazon DynamoDB table."); - deleteDynamoDBTable(ddb, tableName); - System.out.println(DASHES); - - ddb.close(); - } - - // snippet-start:[dynamodb.java2.scenario.create_table.main] - // Create a table with a Sort key. - public static void createTable(DynamoDbClient ddb, String tableName) { - DynamoDbWaiter dbWaiter = ddb.waiter(); - ArrayList attributeDefinitions = new ArrayList<>(); - - // Define attributes. - attributeDefinitions.add(AttributeDefinition.builder() - .attributeName("year") - .attributeType("N") - .build()); - - attributeDefinitions.add(AttributeDefinition.builder() - .attributeName("title") - .attributeType("S") - .build()); - - ArrayList tableKey = new ArrayList<>(); - KeySchemaElement key = KeySchemaElement.builder() - .attributeName("year") - .keyType(KeyType.HASH) - .build(); - - KeySchemaElement key2 = KeySchemaElement.builder() - .attributeName("title") - .keyType(KeyType.RANGE) - .build(); - - // Add KeySchemaElement objects to the list. - tableKey.add(key); - tableKey.add(key2); - - CreateTableRequest request = CreateTableRequest.builder() - .keySchema(tableKey) - .provisionedThroughput(ProvisionedThroughput.builder() - .readCapacityUnits(10L) - .writeCapacityUnits(10L) - .build()) - .attributeDefinitions(attributeDefinitions) - .tableName(tableName) - .build(); - - try { - CreateTableResponse response = ddb.createTable(request); - DescribeTableRequest tableRequest = DescribeTableRequest.builder() - .tableName(tableName) - .build(); - - // Wait until the Amazon DynamoDB table is created. - WaiterResponse waiterResponse = dbWaiter.waitUntilTableExists(tableRequest); - waiterResponse.matched().response().ifPresent(System.out::println); - String newTable = response.tableDescription().tableName(); - System.out.println("The " + newTable + " was successfully created."); - - } catch (DynamoDbException e) { - System.err.println(e.getMessage()); - System.exit(1); - } - } - // snippet-end:[dynamodb.java2.scenario.create_table.main] - - // snippet-start:[dynamodb.java2.scenario.query.main] - // Query the table. - public static void queryTable(DynamoDbClient ddb) { - try { - DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() - .dynamoDbClient(ddb) - .build(); - - DynamoDbTable custTable = enhancedClient.table("Movies", TableSchema.fromBean(Movies.class)); - QueryConditional queryConditional = QueryConditional - .keyEqualTo(Key.builder() - .partitionValue(2013) - .build()); - - // Get items in the table and write out the ID value. - Iterator results = custTable.query(queryConditional).items().iterator(); - String result = ""; - - while (results.hasNext()) { - Movies rec = results.next(); - System.out.println("The title of the movie is " + rec.getTitle()); - System.out.println("The movie information is " + rec.getInfo()); - } - - } catch (DynamoDbException e) { - System.err.println(e.getMessage()); - System.exit(1); - } - } - // snippet-end:[dynamodb.java2.scenario.query.main] - - // snippet-start:[dynamodb.java2.scenario.scan.main] - // Scan the table. - public static void scanMovies(DynamoDbClient ddb, String tableName) { - System.out.println("******* Scanning all movies.\n"); - try { - DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() - .dynamoDbClient(ddb) - .build(); - - DynamoDbTable custTable = enhancedClient.table("Movies", TableSchema.fromBean(Movies.class)); - Iterator results = custTable.scan().items().iterator(); - while (results.hasNext()) { - Movies rec = results.next(); - System.out.println("The movie title is " + rec.getTitle()); - System.out.println("The movie year is " + rec.getYear()); - } - - } catch (DynamoDbException e) { - System.err.println(e.getMessage()); - System.exit(1); - } - } - // snippet-end:[dynamodb.java2.scenario.scan.main] - - // snippet-start:[dynamodb.java2.scenario.populate_table.main] - // Load data into the table. - public static void loadData(DynamoDbClient ddb, String tableName, String fileName) throws IOException { - DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() - .dynamoDbClient(ddb) - .build(); - - DynamoDbTable mappedTable = enhancedClient.table("Movies", TableSchema.fromBean(Movies.class)); - JsonParser parser = new JsonFactory().createParser(new File(fileName)); - com.fasterxml.jackson.databind.JsonNode rootNode = new ObjectMapper().readTree(parser); - Iterator iter = rootNode.iterator(); - ObjectNode currentNode; - int t = 0; - while (iter.hasNext()) { - // Only add 200 Movies to the table. - if (t == 200) - break; - currentNode = (ObjectNode) iter.next(); - - int year = currentNode.path("year").asInt(); - String title = currentNode.path("title").asText(); - String info = currentNode.path("info").toString(); - - Movies movies = new Movies(); - movies.setYear(year); - movies.setTitle(title); - movies.setInfo(info); - - // Put the data into the Amazon DynamoDB Movie table. - mappedTable.putItem(movies); - t++; - } - } - // snippet-end:[dynamodb.java2.scenario.populate_table.main] - - // Update the record to include show only directors. - public static void updateTableItem(DynamoDbClient ddb, String tableName) { - HashMap itemKey = new HashMap<>(); - itemKey.put("year", AttributeValue.builder().n("1933").build()); - itemKey.put("title", AttributeValue.builder().s("King Kong").build()); - - HashMap updatedValues = new HashMap<>(); - updatedValues.put("info", AttributeValueUpdate.builder() - .value(AttributeValue.builder().s("{\"directors\":[\"Merian C. Cooper\",\"Ernest B. Schoedsack\"]") - .build()) - .action(AttributeAction.PUT) - .build()); - - UpdateItemRequest request = UpdateItemRequest.builder() - .tableName(tableName) - .key(itemKey) - .attributeUpdates(updatedValues) - .build(); - - try { - ddb.updateItem(request); - } catch (ResourceNotFoundException e) { - System.err.println(e.getMessage()); - System.exit(1); - } catch (DynamoDbException e) { - System.err.println(e.getMessage()); - System.exit(1); - } - - System.out.println("Item was updated!"); - } - - public static void deleteDynamoDBTable(DynamoDbClient ddb, String tableName) { - DeleteTableRequest request = DeleteTableRequest.builder() - .tableName(tableName) - .build(); - - try { - ddb.deleteTable(request); - - } catch (DynamoDbException e) { - System.err.println(e.getMessage()); - System.exit(1); - } - System.out.println(tableName + " was successfully deleted!"); - } - - public static void putRecord(DynamoDbClient ddb) { - try { - DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() - .dynamoDbClient(ddb) - .build(); - - DynamoDbTable table = enhancedClient.table("Movies", TableSchema.fromBean(Movies.class)); - - // Populate the Table. - Movies record = new Movies(); - record.setYear(2020); - record.setTitle("My Movie2"); - record.setInfo("no info"); - table.putItem(record); - - } catch (DynamoDbException e) { - System.err.println(e.getMessage()); - System.exit(1); - } - System.out.println("Added a new movie to the table."); - } - - // snippet-start:[dynamodb.java2.scenario.get_item.main] - public static void getItem(DynamoDbClient ddb) { - - HashMap keyToGet = new HashMap<>(); - keyToGet.put("year", AttributeValue.builder() - .n("1933") - .build()); - - keyToGet.put("title", AttributeValue.builder() - .s("King Kong") - .build()); - - GetItemRequest request = GetItemRequest.builder() - .key(keyToGet) - .tableName("Movies") - .build(); - - try { - Map returnedItem = ddb.getItem(request).item(); - - if (returnedItem != null) { - Set keys = returnedItem.keySet(); - System.out.println("Amazon DynamoDB table attributes: \n"); - - for (String key1 : keys) { - System.out.format("%s: %s\n", key1, returnedItem.get(key1).toString()); - } - } else { - System.out.format("No item found with the key %s!\n", "year"); - } - - } catch (DynamoDbException e) { - System.err.println(e.getMessage()); - System.exit(1); - } - } - // snippet-end:[dynamodb.java2.scenario.get_item.main] -} -// snippet-end:[dynamodb.java2.scenario.main] +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.dynamodb.scenario; + +// snippet-start:[dynamodb.java2.scenario.import] +import com.example.dynamodb.Movies; +import com.fasterxml.jackson.databind.JsonNode; +import software.amazon.awssdk.core.waiters.WaiterResponse; +import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; +import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; +import software.amazon.awssdk.enhanced.dynamodb.TableSchema; +import software.amazon.awssdk.enhanced.dynamodb.Key; +import software.amazon.awssdk.enhanced.dynamodb.model.QueryConditional; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.dynamodb.DynamoDbClient; +import software.amazon.awssdk.services.dynamodb.model.DynamoDbException; +import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition; +import software.amazon.awssdk.services.dynamodb.model.KeySchemaElement; +import software.amazon.awssdk.services.dynamodb.model.CreateTableRequest; +import software.amazon.awssdk.services.dynamodb.model.KeyType; +import software.amazon.awssdk.services.dynamodb.model.CreateTableResponse; +import software.amazon.awssdk.services.dynamodb.model.AttributeValue; +import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughput; +import software.amazon.awssdk.services.dynamodb.model.AttributeValueUpdate; +import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException; +import software.amazon.awssdk.services.dynamodb.model.DescribeTableRequest; +import software.amazon.awssdk.services.dynamodb.model.DescribeTableResponse; +import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest; +import software.amazon.awssdk.services.dynamodb.model.AttributeAction; +import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; +import software.amazon.awssdk.services.dynamodb.model.GetItemRequest; +import software.amazon.awssdk.services.dynamodb.waiters.DynamoDbWaiter; +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; +// snippet-end:[dynamodb.java2.scenario.import] + +// snippet-start:[dynamodb.java2.scenario.main] +/** + * Before running this Java V2 code example, set up your development + * environment, including your credentials. + * + * For more information, see the following documentation topic: + * + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + * + * This Java example performs these tasks: + * + * 1. Creates the Amazon DynamoDB Movie table with partition and sort key. + * 2. Puts data into the Amazon DynamoDB table from a JSON document using the + * Enhanced client. + * 3. Gets data from the Movie table. + * 4. Adds a new item. + * 5. Updates an item. + * 6. Uses a Scan to query items using the Enhanced client. + * 7. Queries all items where the year is 2013 using the Enhanced Client. + * 8. Deletes the table. + */ + +public class Scenario { + public static final String DASHES = new String(new char[80]).replace("\0", "-"); + + public static void main(String[] args) throws IOException { + final String usage = """ + + Usage: + + + Where: + fileName - The path to the moviedata.json file that you can download from the Amazon DynamoDB Developer Guide. + """; + + if (args.length != 1) { + System.out.println(usage); + System.exit(1); + } + + String tableName = "Movies"; + String fileName = args[0]; + Region region = Region.US_EAST_1; + DynamoDbClient ddb = DynamoDbClient.builder() + .region(region) + .build(); + + System.out.println(DASHES); + System.out.println("Welcome to the Amazon DynamoDB example scenario."); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println( + "1. Creating an Amazon DynamoDB table named Movies with a key named year and a sort key named title."); + createTable(ddb, tableName); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("2. Loading data into the Amazon DynamoDB table."); + loadData(ddb, tableName, fileName); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("3. Getting data from the Movie table."); + getItem(ddb); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("4. Putting a record into the Amazon DynamoDB table."); + putRecord(ddb); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("5. Updating a record."); + updateTableItem(ddb, tableName); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("6. Scanning the Amazon DynamoDB table."); + scanMovies(ddb, tableName); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("7. Querying the Movies released in 2013."); + queryTable(ddb); + System.out.println(DASHES); + + System.out.println(DASHES); + System.out.println("8. Deleting the Amazon DynamoDB table."); + deleteDynamoDBTable(ddb, tableName); + System.out.println(DASHES); + + ddb.close(); + } + + // snippet-start:[dynamodb.java2.scenario.create_table.main] + // Create a table with a Sort key. + public static void createTable(DynamoDbClient ddb, String tableName) { + DynamoDbWaiter dbWaiter = ddb.waiter(); + ArrayList attributeDefinitions = new ArrayList<>(); + + // Define attributes. + attributeDefinitions.add(AttributeDefinition.builder() + .attributeName("year") + .attributeType("N") + .build()); + + attributeDefinitions.add(AttributeDefinition.builder() + .attributeName("title") + .attributeType("S") + .build()); + + ArrayList tableKey = new ArrayList<>(); + KeySchemaElement key = KeySchemaElement.builder() + .attributeName("year") + .keyType(KeyType.HASH) + .build(); + + KeySchemaElement key2 = KeySchemaElement.builder() + .attributeName("title") + .keyType(KeyType.RANGE) + .build(); + + // Add KeySchemaElement objects to the list. + tableKey.add(key); + tableKey.add(key2); + + CreateTableRequest request = CreateTableRequest.builder() + .keySchema(tableKey) + .provisionedThroughput(ProvisionedThroughput.builder() + .readCapacityUnits(10L) + .writeCapacityUnits(10L) + .build()) + .attributeDefinitions(attributeDefinitions) + .tableName(tableName) + .build(); + + try { + CreateTableResponse response = ddb.createTable(request); + DescribeTableRequest tableRequest = DescribeTableRequest.builder() + .tableName(tableName) + .build(); + + // Wait until the Amazon DynamoDB table is created. + WaiterResponse waiterResponse = dbWaiter.waitUntilTableExists(tableRequest); + waiterResponse.matched().response().ifPresent(System.out::println); + String newTable = response.tableDescription().tableName(); + System.out.println("The " + newTable + " was successfully created."); + + } catch (DynamoDbException e) { + System.err.println(e.getMessage()); + System.exit(1); + } + } + // snippet-end:[dynamodb.java2.scenario.create_table.main] + + // snippet-start:[dynamodb.java2.scenario.query.main] + // Query the table. + public static void queryTable(DynamoDbClient ddb) { + try { + DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() + .dynamoDbClient(ddb) + .build(); + + DynamoDbTable custTable = enhancedClient.table("Movies", TableSchema.fromBean(Movies.class)); + QueryConditional queryConditional = QueryConditional + .keyEqualTo(Key.builder() + .partitionValue(2013) + .build()); + + // Get items in the table and write out the ID value. + Iterator results = custTable.query(queryConditional).items().iterator(); + String result = ""; + + while (results.hasNext()) { + Movies rec = results.next(); + System.out.println("The title of the movie is " + rec.getTitle()); + System.out.println("The movie information is " + rec.getInfo()); + } + + } catch (DynamoDbException e) { + System.err.println(e.getMessage()); + System.exit(1); + } + } + // snippet-end:[dynamodb.java2.scenario.query.main] + + // snippet-start:[dynamodb.java2.scenario.scan.main] + // Scan the table. + public static void scanMovies(DynamoDbClient ddb, String tableName) { + System.out.println("******* Scanning all movies.\n"); + try { + DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() + .dynamoDbClient(ddb) + .build(); + + DynamoDbTable custTable = enhancedClient.table("Movies", TableSchema.fromBean(Movies.class)); + Iterator results = custTable.scan().items().iterator(); + while (results.hasNext()) { + Movies rec = results.next(); + System.out.println("The movie title is " + rec.getTitle()); + System.out.println("The movie year is " + rec.getYear()); + } + + } catch (DynamoDbException e) { + System.err.println(e.getMessage()); + System.exit(1); + } + } + // snippet-end:[dynamodb.java2.scenario.scan.main] + + // snippet-start:[dynamodb.java2.scenario.populate_table.main] + // Load data into the table. + public static void loadData(DynamoDbClient ddb, String tableName, String fileName) throws IOException { + DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() + .dynamoDbClient(ddb) + .build(); + + DynamoDbTable mappedTable = enhancedClient.table("Movies", TableSchema.fromBean(Movies.class)); + JsonParser parser = new JsonFactory().createParser(new File(fileName)); + com.fasterxml.jackson.databind.JsonNode rootNode = new ObjectMapper().readTree(parser); + Iterator iter = rootNode.iterator(); + ObjectNode currentNode; + int t = 0; + while (iter.hasNext()) { + // Only add 200 Movies to the table. + if (t == 200) + break; + currentNode = (ObjectNode) iter.next(); + + int year = currentNode.path("year").asInt(); + String title = currentNode.path("title").asText(); + String info = currentNode.path("info").toString(); + + Movies movies = new Movies(); + movies.setYear(year); + movies.setTitle(title); + movies.setInfo(info); + + // Put the data into the Amazon DynamoDB Movie table. + mappedTable.putItem(movies); + t++; + } + } + // snippet-end:[dynamodb.java2.scenario.populate_table.main] + + // Update the record to include show only directors. + public static void updateTableItem(DynamoDbClient ddb, String tableName) { + HashMap itemKey = new HashMap<>(); + itemKey.put("year", AttributeValue.builder().n("1933").build()); + itemKey.put("title", AttributeValue.builder().s("King Kong").build()); + + HashMap updatedValues = new HashMap<>(); + updatedValues.put("info", AttributeValueUpdate.builder() + .value(AttributeValue.builder().s("{\"directors\":[\"Merian C. Cooper\",\"Ernest B. Schoedsack\"]") + .build()) + .action(AttributeAction.PUT) + .build()); + + UpdateItemRequest request = UpdateItemRequest.builder() + .tableName(tableName) + .key(itemKey) + .attributeUpdates(updatedValues) + .build(); + + try { + ddb.updateItem(request); + } catch (ResourceNotFoundException e) { + System.err.println(e.getMessage()); + System.exit(1); + } catch (DynamoDbException e) { + System.err.println(e.getMessage()); + System.exit(1); + } + + System.out.println("Item was updated!"); + } + + public static void deleteDynamoDBTable(DynamoDbClient ddb, String tableName) { + DeleteTableRequest request = DeleteTableRequest.builder() + .tableName(tableName) + .build(); + + try { + ddb.deleteTable(request); + + } catch (DynamoDbException e) { + System.err.println(e.getMessage()); + System.exit(1); + } + System.out.println(tableName + " was successfully deleted!"); + } + + public static void putRecord(DynamoDbClient ddb) { + try { + DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() + .dynamoDbClient(ddb) + .build(); + + DynamoDbTable table = enhancedClient.table("Movies", TableSchema.fromBean(Movies.class)); + + // Populate the Table. + Movies record = new Movies(); + record.setYear(2020); + record.setTitle("My Movie2"); + record.setInfo("no info"); + table.putItem(record); + + } catch (DynamoDbException e) { + System.err.println(e.getMessage()); + System.exit(1); + } + System.out.println("Added a new movie to the table."); + } + + // snippet-start:[dynamodb.java2.scenario.get_item.main] + public static void getItem(DynamoDbClient ddb) { + + HashMap keyToGet = new HashMap<>(); + keyToGet.put("year", AttributeValue.builder() + .n("1933") + .build()); + + keyToGet.put("title", AttributeValue.builder() + .s("King Kong") + .build()); + + GetItemRequest request = GetItemRequest.builder() + .key(keyToGet) + .tableName("Movies") + .build(); + + try { + Map returnedItem = ddb.getItem(request).item(); + + if (returnedItem != null) { + Set keys = returnedItem.keySet(); + System.out.println("Amazon DynamoDB table attributes: \n"); + + for (String key1 : keys) { + System.out.format("%s: %s\n", key1, returnedItem.get(key1).toString()); + } + } else { + System.out.format("No item found with the key %s!\n", "year"); + } + + } catch (DynamoDbException e) { + System.err.println(e.getMessage()); + System.exit(1); + } + } + // snippet-end:[dynamodb.java2.scenario.get_item.main] +} +// snippet-end:[dynamodb.java2.scenario.main] diff --git a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/ScenarioPartiQ.java b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/scenario/ScenarioPartiQ.java similarity index 93% rename from javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/ScenarioPartiQ.java rename to javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/scenario/ScenarioPartiQ.java index a28a9894cee..21e9645b1d9 100644 --- a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/ScenarioPartiQ.java +++ b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/scenario/ScenarioPartiQ.java @@ -1,345 +1,345 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.dynamodb; - -// snippet-start:[dynamodb.java2.scenario.partiql.import] -import com.fasterxml.jackson.databind.JsonNode; -import software.amazon.awssdk.core.waiters.WaiterResponse; -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.dynamodb.DynamoDbClient; -import software.amazon.awssdk.services.dynamodb.model.KeySchemaElement; -import software.amazon.awssdk.services.dynamodb.model.DynamoDbException; -import software.amazon.awssdk.services.dynamodb.model.CreateTableRequest; -import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughput; -import software.amazon.awssdk.services.dynamodb.model.DescribeTableRequest; -import software.amazon.awssdk.services.dynamodb.model.DescribeTableResponse; -import software.amazon.awssdk.services.dynamodb.model.AttributeValue; -import software.amazon.awssdk.services.dynamodb.model.CreateTableResponse; -import software.amazon.awssdk.services.dynamodb.model.KeyType; -import software.amazon.awssdk.services.dynamodb.model.ExecuteStatementResponse; -import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition; -import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; -import software.amazon.awssdk.services.dynamodb.model.ExecuteStatementRequest; -import software.amazon.awssdk.services.dynamodb.waiters.DynamoDbWaiter; -import com.fasterxml.jackson.core.JsonFactory; -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.ObjectNode; -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Iterator; -// snippet-end:[dynamodb.java2.scenario.partiql.import] - -/** - * Before running this Java V2 code example, set up your development - * environment, including your credentials. - * - * For more information, see the following documentation topic: - * - * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html - * - * This Java example performs the following tasks: - * - * 1. Creates the Amazon DynamoDB movie table with a partition and sort key. - * 2. Puts data into the Amazon DynamoDB table from a JSON document. - * 3. Adds a new item. - * 4. Gets an item by the composite key (the Partition key and Sort key). - * 5. Updates an item. - * 6. Uses a Scan to query items using the Enhanced client. - * 7. Queries all items where the year is 2013 using the Enhanced Client. - * 8. Deletes the table. - * - * To see another code example with more options using PartiQL and Batch - * commands, see the ScenarioPartiQBatch code example. - */ - -// snippet-start:[dynamodb.java2.scenario.partiql.main] -public class ScenarioPartiQ { - public static void main(String[] args) throws IOException { - final String usage = """ - - Usage: - - - Where: - fileName - The path to the moviedata.json file that you can download from the Amazon DynamoDB Developer Guide. - """; - - if (args.length != 1) { - System.out.println(usage); - System.exit(1); - } - - String fileName = args[0]; - String tableName = "MoviesPartiQ"; - Region region = Region.US_EAST_1; - DynamoDbClient ddb = DynamoDbClient.builder() - .region(region) - .build(); - - System.out.println( - "******* Creating an Amazon DynamoDB table named MoviesPartiQ with a key named year and a sort key named title."); - createTable(ddb, tableName); - - System.out.println("******* Loading data into the MoviesPartiQ table."); - loadData(ddb, fileName); - - System.out.println("******* Getting data from the MoviesPartiQ table."); - getItem(ddb); - - System.out.println("******* Putting a record into the MoviesPartiQ table."); - putRecord(ddb); - - System.out.println("******* Updating a record."); - updateTableItem(ddb); - - System.out.println("******* Querying the movies released in 2013."); - queryTable(ddb); - - System.out.println("******* Deleting the Amazon DynamoDB table."); - deleteDynamoDBTable(ddb, tableName); - ddb.close(); - } - - public static void createTable(DynamoDbClient ddb, String tableName) { - DynamoDbWaiter dbWaiter = ddb.waiter(); - ArrayList attributeDefinitions = new ArrayList<>(); - - // Define attributes. - attributeDefinitions.add(AttributeDefinition.builder() - .attributeName("year") - .attributeType("N") - .build()); - - attributeDefinitions.add(AttributeDefinition.builder() - .attributeName("title") - .attributeType("S") - .build()); - - ArrayList tableKey = new ArrayList<>(); - KeySchemaElement key = KeySchemaElement.builder() - .attributeName("year") - .keyType(KeyType.HASH) - .build(); - - KeySchemaElement key2 = KeySchemaElement.builder() - .attributeName("title") - .keyType(KeyType.RANGE) // Sort - .build(); - - // Add KeySchemaElement objects to the list. - tableKey.add(key); - tableKey.add(key2); - - CreateTableRequest request = CreateTableRequest.builder() - .keySchema(tableKey) - .provisionedThroughput(ProvisionedThroughput.builder() - .readCapacityUnits(new Long(10)) - .writeCapacityUnits(new Long(10)) - .build()) - .attributeDefinitions(attributeDefinitions) - .tableName(tableName) - .build(); - - try { - CreateTableResponse response = ddb.createTable(request); - DescribeTableRequest tableRequest = DescribeTableRequest.builder() - .tableName(tableName) - .build(); - - // Wait until the Amazon DynamoDB table is created. - WaiterResponse waiterResponse = dbWaiter.waitUntilTableExists(tableRequest); - waiterResponse.matched().response().ifPresent(System.out::println); - String newTable = response.tableDescription().tableName(); - System.out.println("The " + newTable + " was successfully created."); - - } catch (DynamoDbException e) { - System.err.println(e.getMessage()); - System.exit(1); - } - } - - // Load data into the table. - public static void loadData(DynamoDbClient ddb, String fileName) throws IOException { - - String sqlStatement = "INSERT INTO MoviesPartiQ VALUE {'year':?, 'title' : ?, 'info' : ?}"; - JsonParser parser = new JsonFactory().createParser(new File(fileName)); - com.fasterxml.jackson.databind.JsonNode rootNode = new ObjectMapper().readTree(parser); - Iterator iter = rootNode.iterator(); - ObjectNode currentNode; - int t = 0; - List parameters = new ArrayList<>(); - while (iter.hasNext()) { - - // Add 200 movies to the table. - if (t == 200) - break; - currentNode = (ObjectNode) iter.next(); - - int year = currentNode.path("year").asInt(); - String title = currentNode.path("title").asText(); - String info = currentNode.path("info").toString(); - - AttributeValue att1 = AttributeValue.builder() - .n(String.valueOf(year)) - .build(); - - AttributeValue att2 = AttributeValue.builder() - .s(title) - .build(); - - AttributeValue att3 = AttributeValue.builder() - .s(info) - .build(); - - parameters.add(att1); - parameters.add(att2); - parameters.add(att3); - - // Insert the movie into the Amazon DynamoDB table. - executeStatementRequest(ddb, sqlStatement, parameters); - System.out.println("Added Movie " + title); - - parameters.remove(att1); - parameters.remove(att2); - parameters.remove(att3); - t++; - } - } - - public static void getItem(DynamoDbClient ddb) { - - String sqlStatement = "SELECT * FROM MoviesPartiQ where year=? and title=?"; - List parameters = new ArrayList<>(); - AttributeValue att1 = AttributeValue.builder() - .n("2012") - .build(); - - AttributeValue att2 = AttributeValue.builder() - .s("The Perks of Being a Wallflower") - .build(); - - parameters.add(att1); - parameters.add(att2); - - try { - ExecuteStatementResponse response = executeStatementRequest(ddb, sqlStatement, parameters); - System.out.println("ExecuteStatement successful: " + response.toString()); - - } catch (DynamoDbException e) { - System.err.println(e.getMessage()); - System.exit(1); - } - } - - public static void putRecord(DynamoDbClient ddb) { - - String sqlStatement = "INSERT INTO MoviesPartiQ VALUE {'year':?, 'title' : ?, 'info' : ?}"; - try { - List parameters = new ArrayList<>(); - - AttributeValue att1 = AttributeValue.builder() - .n(String.valueOf("2020")) - .build(); - - AttributeValue att2 = AttributeValue.builder() - .s("My Movie") - .build(); - - AttributeValue att3 = AttributeValue.builder() - .s("No Information") - .build(); - - parameters.add(att1); - parameters.add(att2); - parameters.add(att3); - - executeStatementRequest(ddb, sqlStatement, parameters); - System.out.println("Added new movie."); - - } catch (DynamoDbException e) { - System.err.println(e.getMessage()); - System.exit(1); - } - } - - public static void updateTableItem(DynamoDbClient ddb) { - - String sqlStatement = "UPDATE MoviesPartiQ SET info = 'directors\":[\"Merian C. Cooper\",\"Ernest B. Schoedsack' where year=? and title=?"; - List parameters = new ArrayList<>(); - AttributeValue att1 = AttributeValue.builder() - .n(String.valueOf("2013")) - .build(); - - AttributeValue att2 = AttributeValue.builder() - .s("The East") - .build(); - - parameters.add(att1); - parameters.add(att2); - - try { - executeStatementRequest(ddb, sqlStatement, parameters); - - } catch (DynamoDbException e) { - System.err.println(e.getMessage()); - System.exit(1); - } - System.out.println("Item was updated!"); - } - - // Query the table where the year is 2013. - public static void queryTable(DynamoDbClient ddb) { - String sqlStatement = "SELECT * FROM MoviesPartiQ where year = ? ORDER BY year"; - try { - - List parameters = new ArrayList<>(); - AttributeValue att1 = AttributeValue.builder() - .n(String.valueOf("2013")) - .build(); - parameters.add(att1); - - // Get items in the table and write out the ID value. - ExecuteStatementResponse response = executeStatementRequest(ddb, sqlStatement, parameters); - System.out.println("ExecuteStatement successful: " + response.toString()); - - } catch (DynamoDbException e) { - System.err.println(e.getMessage()); - System.exit(1); - } - } - - public static void deleteDynamoDBTable(DynamoDbClient ddb, String tableName) { - - DeleteTableRequest request = DeleteTableRequest.builder() - .tableName(tableName) - .build(); - - try { - ddb.deleteTable(request); - - } catch (DynamoDbException e) { - System.err.println(e.getMessage()); - System.exit(1); - } - System.out.println(tableName + " was successfully deleted!"); - } - - private static ExecuteStatementResponse executeStatementRequest(DynamoDbClient ddb, String statement, - List parameters) { - ExecuteStatementRequest request = ExecuteStatementRequest.builder() - .statement(statement) - .parameters(parameters) - .build(); - - return ddb.executeStatement(request); - } - - private static void processResults(ExecuteStatementResponse executeStatementResult) { - System.out.println("ExecuteStatement successful: " + executeStatementResult.toString()); - } -} +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.dynamodb.scenario; + +// snippet-start:[dynamodb.java2.scenario.partiql.import] +import com.fasterxml.jackson.databind.JsonNode; +import software.amazon.awssdk.core.waiters.WaiterResponse; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.dynamodb.DynamoDbClient; +import software.amazon.awssdk.services.dynamodb.model.KeySchemaElement; +import software.amazon.awssdk.services.dynamodb.model.DynamoDbException; +import software.amazon.awssdk.services.dynamodb.model.CreateTableRequest; +import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughput; +import software.amazon.awssdk.services.dynamodb.model.DescribeTableRequest; +import software.amazon.awssdk.services.dynamodb.model.DescribeTableResponse; +import software.amazon.awssdk.services.dynamodb.model.AttributeValue; +import software.amazon.awssdk.services.dynamodb.model.CreateTableResponse; +import software.amazon.awssdk.services.dynamodb.model.KeyType; +import software.amazon.awssdk.services.dynamodb.model.ExecuteStatementResponse; +import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition; +import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; +import software.amazon.awssdk.services.dynamodb.model.ExecuteStatementRequest; +import software.amazon.awssdk.services.dynamodb.waiters.DynamoDbWaiter; +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Iterator; +// snippet-end:[dynamodb.java2.scenario.partiql.import] + +/** + * Before running this Java V2 code example, set up your development + * environment, including your credentials. + * + * For more information, see the following documentation topic: + * + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + * + * This Java example performs the following tasks: + * + * 1. Creates the Amazon DynamoDB movie table with a partition and sort key. + * 2. Puts data into the Amazon DynamoDB table from a JSON document. + * 3. Adds a new item. + * 4. Gets an item by the composite key (the Partition key and Sort key). + * 5. Updates an item. + * 6. Uses a Scan to query items using the Enhanced client. + * 7. Queries all items where the year is 2013 using the Enhanced Client. + * 8. Deletes the table. + * + * To see another code example with more options using PartiQL and Batch + * commands, see the ScenarioPartiQBatch code example. + */ + +// snippet-start:[dynamodb.java2.scenario.partiql.main] +public class ScenarioPartiQ { + public static void main(String[] args) throws IOException { + final String usage = """ + + Usage: + + + Where: + fileName - The path to the moviedata.json file that you can download from the Amazon DynamoDB Developer Guide. + """; + + if (args.length != 1) { + System.out.println(usage); + System.exit(1); + } + + String fileName = args[0]; + String tableName = "MoviesPartiQ"; + Region region = Region.US_EAST_1; + DynamoDbClient ddb = DynamoDbClient.builder() + .region(region) + .build(); + + System.out.println( + "******* Creating an Amazon DynamoDB table named MoviesPartiQ with a key named year and a sort key named title."); + createTable(ddb, tableName); + + System.out.println("Loading data into the MoviesPartiQ table."); + loadData(ddb, fileName); + + System.out.println("Getting data from the MoviesPartiQ table."); + getItem(ddb); + + System.out.println("Putting a record into the MoviesPartiQ table."); + putRecord(ddb); + + System.out.println("Updating a record."); + updateTableItem(ddb); + + System.out.println("Querying the movies released in 2013."); + queryTable(ddb); + + System.out.println("Deleting the Amazon DynamoDB table."); + deleteDynamoDBTable(ddb, tableName); + ddb.close(); + } + + public static void createTable(DynamoDbClient ddb, String tableName) { + DynamoDbWaiter dbWaiter = ddb.waiter(); + ArrayList attributeDefinitions = new ArrayList<>(); + + // Define attributes. + attributeDefinitions.add(AttributeDefinition.builder() + .attributeName("year") + .attributeType("N") + .build()); + + attributeDefinitions.add(AttributeDefinition.builder() + .attributeName("title") + .attributeType("S") + .build()); + + ArrayList tableKey = new ArrayList<>(); + KeySchemaElement key = KeySchemaElement.builder() + .attributeName("year") + .keyType(KeyType.HASH) + .build(); + + KeySchemaElement key2 = KeySchemaElement.builder() + .attributeName("title") + .keyType(KeyType.RANGE) // Sort + .build(); + + // Add KeySchemaElement objects to the list. + tableKey.add(key); + tableKey.add(key2); + + CreateTableRequest request = CreateTableRequest.builder() + .keySchema(tableKey) + .provisionedThroughput(ProvisionedThroughput.builder() + .readCapacityUnits(new Long(10)) + .writeCapacityUnits(new Long(10)) + .build()) + .attributeDefinitions(attributeDefinitions) + .tableName(tableName) + .build(); + + try { + CreateTableResponse response = ddb.createTable(request); + DescribeTableRequest tableRequest = DescribeTableRequest.builder() + .tableName(tableName) + .build(); + + // Wait until the Amazon DynamoDB table is created. + WaiterResponse waiterResponse = dbWaiter.waitUntilTableExists(tableRequest); + waiterResponse.matched().response().ifPresent(System.out::println); + String newTable = response.tableDescription().tableName(); + System.out.println("The " + newTable + " was successfully created."); + + } catch (DynamoDbException e) { + System.err.println(e.getMessage()); + System.exit(1); + } + } + + // Load data into the table. + public static void loadData(DynamoDbClient ddb, String fileName) throws IOException { + + String sqlStatement = "INSERT INTO MoviesPartiQ VALUE {'year':?, 'title' : ?, 'info' : ?}"; + JsonParser parser = new JsonFactory().createParser(new File(fileName)); + com.fasterxml.jackson.databind.JsonNode rootNode = new ObjectMapper().readTree(parser); + Iterator iter = rootNode.iterator(); + ObjectNode currentNode; + int t = 0; + List parameters = new ArrayList<>(); + while (iter.hasNext()) { + + // Add 200 movies to the table. + if (t == 200) + break; + currentNode = (ObjectNode) iter.next(); + + int year = currentNode.path("year").asInt(); + String title = currentNode.path("title").asText(); + String info = currentNode.path("info").toString(); + + AttributeValue att1 = AttributeValue.builder() + .n(String.valueOf(year)) + .build(); + + AttributeValue att2 = AttributeValue.builder() + .s(title) + .build(); + + AttributeValue att3 = AttributeValue.builder() + .s(info) + .build(); + + parameters.add(att1); + parameters.add(att2); + parameters.add(att3); + + // Insert the movie into the Amazon DynamoDB table. + executeStatementRequest(ddb, sqlStatement, parameters); + System.out.println("Added Movie " + title); + + parameters.remove(att1); + parameters.remove(att2); + parameters.remove(att3); + t++; + } + } + + public static void getItem(DynamoDbClient ddb) { + + String sqlStatement = "SELECT * FROM MoviesPartiQ where year=? and title=?"; + List parameters = new ArrayList<>(); + AttributeValue att1 = AttributeValue.builder() + .n("2012") + .build(); + + AttributeValue att2 = AttributeValue.builder() + .s("The Perks of Being a Wallflower") + .build(); + + parameters.add(att1); + parameters.add(att2); + + try { + ExecuteStatementResponse response = executeStatementRequest(ddb, sqlStatement, parameters); + System.out.println("ExecuteStatement successful: " + response.toString()); + + } catch (DynamoDbException e) { + System.err.println(e.getMessage()); + System.exit(1); + } + } + + public static void putRecord(DynamoDbClient ddb) { + + String sqlStatement = "INSERT INTO MoviesPartiQ VALUE {'year':?, 'title' : ?, 'info' : ?}"; + try { + List parameters = new ArrayList<>(); + + AttributeValue att1 = AttributeValue.builder() + .n(String.valueOf("2020")) + .build(); + + AttributeValue att2 = AttributeValue.builder() + .s("My Movie") + .build(); + + AttributeValue att3 = AttributeValue.builder() + .s("No Information") + .build(); + + parameters.add(att1); + parameters.add(att2); + parameters.add(att3); + + executeStatementRequest(ddb, sqlStatement, parameters); + System.out.println("Added new movie."); + + } catch (DynamoDbException e) { + System.err.println(e.getMessage()); + System.exit(1); + } + } + + public static void updateTableItem(DynamoDbClient ddb) { + + String sqlStatement = "UPDATE MoviesPartiQ SET info = 'directors\":[\"Merian C. Cooper\",\"Ernest B. Schoedsack' where year=? and title=?"; + List parameters = new ArrayList<>(); + AttributeValue att1 = AttributeValue.builder() + .n(String.valueOf("2013")) + .build(); + + AttributeValue att2 = AttributeValue.builder() + .s("The East") + .build(); + + parameters.add(att1); + parameters.add(att2); + + try { + executeStatementRequest(ddb, sqlStatement, parameters); + + } catch (DynamoDbException e) { + System.err.println(e.getMessage()); + System.exit(1); + } + System.out.println("Item was updated!"); + } + + // Query the table where the year is 2013. + public static void queryTable(DynamoDbClient ddb) { + String sqlStatement = "SELECT * FROM MoviesPartiQ where year = ? ORDER BY year"; + try { + + List parameters = new ArrayList<>(); + AttributeValue att1 = AttributeValue.builder() + .n(String.valueOf("2013")) + .build(); + parameters.add(att1); + + // Get items in the table and write out the ID value. + ExecuteStatementResponse response = executeStatementRequest(ddb, sqlStatement, parameters); + System.out.println("ExecuteStatement successful: " + response.toString()); + + } catch (DynamoDbException e) { + System.err.println(e.getMessage()); + System.exit(1); + } + } + + public static void deleteDynamoDBTable(DynamoDbClient ddb, String tableName) { + + DeleteTableRequest request = DeleteTableRequest.builder() + .tableName(tableName) + .build(); + + try { + ddb.deleteTable(request); + + } catch (DynamoDbException e) { + System.err.println(e.getMessage()); + System.exit(1); + } + System.out.println(tableName + " was successfully deleted!"); + } + + private static ExecuteStatementResponse executeStatementRequest(DynamoDbClient ddb, String statement, + List parameters) { + ExecuteStatementRequest request = ExecuteStatementRequest.builder() + .statement(statement) + .parameters(parameters) + .build(); + + return ddb.executeStatement(request); + } + + private static void processResults(ExecuteStatementResponse executeStatementResult) { + System.out.println("ExecuteStatement successful: " + executeStatementResult.toString()); + } +} // snippet-end:[dynamodb.java2.scenario.partiql.main] \ No newline at end of file diff --git a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/ScenarioPartiQLBatch.java b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/scenario/ScenarioPartiQLBatch.java similarity index 93% rename from javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/ScenarioPartiQLBatch.java rename to javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/scenario/ScenarioPartiQLBatch.java index be5aede9212..9f16f5c337b 100644 --- a/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/ScenarioPartiQLBatch.java +++ b/javav2/example_code/dynamodb/src/main/java/com/example/dynamodb/scenario/ScenarioPartiQLBatch.java @@ -1,458 +1,458 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package com.example.dynamodb; - -// snippet-start:[dynamodb.java2.scenario.partiql.batch.import] - -import software.amazon.awssdk.core.waiters.WaiterResponse; -import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.services.dynamodb.DynamoDbClient; -import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition; -import software.amazon.awssdk.services.dynamodb.model.AttributeValue; -import software.amazon.awssdk.services.dynamodb.model.BatchExecuteStatementRequest; -import software.amazon.awssdk.services.dynamodb.model.BatchExecuteStatementResponse; -import software.amazon.awssdk.services.dynamodb.model.BatchStatementRequest; -import software.amazon.awssdk.services.dynamodb.model.CreateTableRequest; -import software.amazon.awssdk.services.dynamodb.model.CreateTableResponse; -import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; -import software.amazon.awssdk.services.dynamodb.model.DescribeTableRequest; -import software.amazon.awssdk.services.dynamodb.model.DescribeTableResponse; -import software.amazon.awssdk.services.dynamodb.model.DynamoDbException; -import software.amazon.awssdk.services.dynamodb.model.ExecuteStatementRequest; -import software.amazon.awssdk.services.dynamodb.model.ExecuteStatementResponse; -import software.amazon.awssdk.services.dynamodb.model.KeySchemaElement; -import software.amazon.awssdk.services.dynamodb.model.KeyType; -import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughput; -import software.amazon.awssdk.services.dynamodb.waiters.DynamoDbWaiter; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -// snippet-end:[dynamodb.java2.scenario.partiql.batch.import] - -/** - * Before running this Java V2 code example, set up your development - * environment, including your credentials. - *

- * For more information, see the following documentation topic: - *

- * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html - *

- * This Java example performs the following tasks: - *

- * 1. Creates the Amazon DynamoDB movie table with a partition and sort key. - * 2. Puts new records into the table using a BatchExecuteStatement - * 3. Updates items using a BatchExecuteStatement. - * 4. Deletes items by using a BatchExecuteStatement. - * 5. Deletes the table. - *

- * To see another code example with more options using PartiQL, see the - * ScenarioPartiQ code example. - */ - -// snippet-start:[dynamodb.java2.scenario.partiql.batch.main] -public class ScenarioPartiQLBatch { - public static void main(String[] args) throws IOException { - String tableName = "MoviesPartiQBatch"; - Region region = Region.US_EAST_1; - DynamoDbClient ddb = DynamoDbClient.builder() - .region(region) - .build(); - - System.out.println("******* Creating an Amazon DynamoDB table named " + tableName - + " with a key named year and a sort key named title."); - createTable(ddb, tableName); - - System.out.println("******* Adding multiple records into the " + tableName - + " table using a batch command."); - putRecordBatch(ddb); - - // Update multiple movies by using the BatchExecute statement. - String title1 = "Star Wars"; - int year1 = 1977; - String title2 = "Wizard of Oz"; - int year2 = 1939; - - System.out.println("Updating two movies with producer information: " + title1 + " and " + title2 + "."); - getBatch(ddb, tableName, title1, title2, year1, year2); - - System.out.println("******* Updating multiple records using a batch command."); - updateTableItemBatch(ddb); - - System.out.println("******* Deleting multiple records using a batch command."); - deleteItemBatch(ddb); - - System.out.println("******* Deleting the Amazon DynamoDB table."); - deleteDynamoDBTable(ddb, tableName); - ddb.close(); - } - - public static boolean getBatch(DynamoDbClient ddb, String tableName, String title1, String title2, int year1, int year2) { - String getBatch = "SELECT * FROM " + tableName + " WHERE title = ? AND year = ?"; - - List statements = new ArrayList<>(); - statements.add(BatchStatementRequest.builder() - .statement(getBatch) - .parameters(AttributeValue.builder().s(title1).build(), - AttributeValue.builder().n(String.valueOf(year1)).build()) - .build()); - statements.add(BatchStatementRequest.builder() - .statement(getBatch) - .parameters(AttributeValue.builder().s(title2).build(), - AttributeValue.builder().n(String.valueOf(year2)).build()) - .build()); - - BatchExecuteStatementRequest batchExecuteStatementRequest = BatchExecuteStatementRequest.builder() - .statements(statements) - .build(); - - try { - BatchExecuteStatementResponse response = ddb.batchExecuteStatement(batchExecuteStatementRequest); - if (!response.responses().isEmpty()) { - response.responses().forEach(r -> { - System.out.println(r.item().get("title") + "\\t" + r.item().get("year")); - }); - return true; - } else { - System.out.println("Couldn't find either " + title1 + " or " + title2 + "."); - return false; - } - } catch (DynamoDbException e) { - System.err.println(e.getMessage()); - return false; - } - } - - public static void createTable(DynamoDbClient ddb, String tableName) { - DynamoDbWaiter dbWaiter = ddb.waiter(); - ArrayList attributeDefinitions = new ArrayList<>(); - - // Define attributes. - attributeDefinitions.add(AttributeDefinition.builder() - .attributeName("year") - .attributeType("N") - .build()); - - attributeDefinitions.add(AttributeDefinition.builder() - .attributeName("title") - .attributeType("S") - .build()); - - ArrayList tableKey = new ArrayList<>(); - KeySchemaElement key = KeySchemaElement.builder() - .attributeName("year") - .keyType(KeyType.HASH) - .build(); - - KeySchemaElement key2 = KeySchemaElement.builder() - .attributeName("title") - .keyType(KeyType.RANGE) // Sort - .build(); - - // Add KeySchemaElement objects to the list. - tableKey.add(key); - tableKey.add(key2); - - CreateTableRequest request = CreateTableRequest.builder() - .keySchema(tableKey) - .provisionedThroughput(ProvisionedThroughput.builder() - .readCapacityUnits(10L) - .writeCapacityUnits(10L) - .build()) - .attributeDefinitions(attributeDefinitions) - .tableName(tableName) - .build(); - - try { - CreateTableResponse response = ddb.createTable(request); - DescribeTableRequest tableRequest = DescribeTableRequest.builder() - .tableName(tableName) - .build(); - - // Wait until the Amazon DynamoDB table is created. - WaiterResponse waiterResponse = dbWaiter - .waitUntilTableExists(tableRequest); - waiterResponse.matched().response().ifPresent(System.out::println); - String newTable = response.tableDescription().tableName(); - System.out.println("The " + newTable + " was successfully created."); - - } catch (DynamoDbException e) { - System.err.println(e.getMessage()); - System.exit(1); - } - } - - public static void putRecordBatch(DynamoDbClient ddb) { - String sqlStatement = "INSERT INTO MoviesPartiQBatch VALUE {'year':?, 'title' : ?, 'info' : ?}"; - try { - // Create three movies to add to the Amazon DynamoDB table. - // Set data for Movie 1. - List parameters = new ArrayList<>(); - - AttributeValue att1 = AttributeValue.builder() - .n(String.valueOf("1977")) - .build(); - - AttributeValue att2 = AttributeValue.builder() - .s("Star Wars") - .build(); - - AttributeValue att3 = AttributeValue.builder() - .s("No Information") - .build(); - - parameters.add(att1); - parameters.add(att2); - parameters.add(att3); - - BatchStatementRequest statementRequestMovie1 = BatchStatementRequest.builder() - .statement(sqlStatement) - .parameters(parameters) - .build(); - - // Set data for Movie 2. - List parametersMovie2 = new ArrayList<>(); - AttributeValue attMovie2 = AttributeValue.builder() - .n(String.valueOf("1939")) - .build(); - - AttributeValue attMovie2A = AttributeValue.builder() - .s("Wizard of Oz") - .build(); - - AttributeValue attMovie2B = AttributeValue.builder() - .s("No Information") - .build(); - - parametersMovie2.add(attMovie2); - parametersMovie2.add(attMovie2A); - parametersMovie2.add(attMovie2B); - - BatchStatementRequest statementRequestMovie2 = BatchStatementRequest.builder() - .statement(sqlStatement) - .parameters(parametersMovie2) - .build(); - - // Set data for Movie 3. - List parametersMovie3 = new ArrayList<>(); - AttributeValue attMovie3 = AttributeValue.builder() - .n(String.valueOf("2022")) - .build(); - - AttributeValue attMovie3A = AttributeValue.builder() - .s("My Movie 3") - .build(); - - AttributeValue attMovie3B = AttributeValue.builder() - .s("No Information") - .build(); - - parametersMovie3.add(attMovie3); - parametersMovie3.add(attMovie3A); - parametersMovie3.add(attMovie3B); - - BatchStatementRequest statementRequestMovie3 = BatchStatementRequest.builder() - .statement(sqlStatement) - .parameters(parametersMovie3) - .build(); - - // Add all three movies to the list. - List myBatchStatementList = new ArrayList<>(); - myBatchStatementList.add(statementRequestMovie1); - myBatchStatementList.add(statementRequestMovie2); - myBatchStatementList.add(statementRequestMovie3); - - BatchExecuteStatementRequest batchRequest = BatchExecuteStatementRequest.builder() - .statements(myBatchStatementList) - .build(); - - BatchExecuteStatementResponse response = ddb.batchExecuteStatement(batchRequest); - System.out.println("ExecuteStatement successful: " + response.toString()); - System.out.println("Added new movies using a batch command."); - - } catch (DynamoDbException e) { - System.err.println(e.getMessage()); - System.exit(1); - } - } - - public static void updateTableItemBatch(DynamoDbClient ddb) { - String sqlStatement = "UPDATE MoviesPartiQBatch SET info = 'directors\":[\"Merian C. Cooper\",\"Ernest B. Schoedsack' where year=? and title=?"; - List parametersRec1 = new ArrayList<>(); - - // Update three records. - AttributeValue att1 = AttributeValue.builder() - .n(String.valueOf("2022")) - .build(); - - AttributeValue att2 = AttributeValue.builder() - .s("My Movie 1") - .build(); - - parametersRec1.add(att1); - parametersRec1.add(att2); - - BatchStatementRequest statementRequestRec1 = BatchStatementRequest.builder() - .statement(sqlStatement) - .parameters(parametersRec1) - .build(); - - // Update record 2. - List parametersRec2 = new ArrayList<>(); - AttributeValue attRec2 = AttributeValue.builder() - .n(String.valueOf("2022")) - .build(); - - AttributeValue attRec2a = AttributeValue.builder() - .s("My Movie 2") - .build(); - - parametersRec2.add(attRec2); - parametersRec2.add(attRec2a); - BatchStatementRequest statementRequestRec2 = BatchStatementRequest.builder() - .statement(sqlStatement) - .parameters(parametersRec2) - .build(); - - // Update record 3. - List parametersRec3 = new ArrayList<>(); - AttributeValue attRec3 = AttributeValue.builder() - .n(String.valueOf("2022")) - .build(); - - AttributeValue attRec3a = AttributeValue.builder() - .s("My Movie 3") - .build(); - - parametersRec3.add(attRec3); - parametersRec3.add(attRec3a); - BatchStatementRequest statementRequestRec3 = BatchStatementRequest.builder() - .statement(sqlStatement) - .parameters(parametersRec3) - .build(); - - // Add all three movies to the list. - List myBatchStatementList = new ArrayList<>(); - myBatchStatementList.add(statementRequestRec1); - myBatchStatementList.add(statementRequestRec2); - myBatchStatementList.add(statementRequestRec3); - - BatchExecuteStatementRequest batchRequest = BatchExecuteStatementRequest.builder() - .statements(myBatchStatementList) - .build(); - - try { - BatchExecuteStatementResponse response = ddb.batchExecuteStatement(batchRequest); - System.out.println("ExecuteStatement successful: " + response.toString()); - System.out.println("Updated three movies using a batch command."); - - } catch (DynamoDbException e) { - System.err.println(e.getMessage()); - System.exit(1); - } - System.out.println("Item was updated!"); - } - - public static void deleteItemBatch(DynamoDbClient ddb) { - String sqlStatement = "DELETE FROM MoviesPartiQBatch WHERE year = ? and title=?"; - List parametersRec1 = new ArrayList<>(); - - // Specify three records to delete. - AttributeValue att1 = AttributeValue.builder() - .n(String.valueOf("2022")) - .build(); - - AttributeValue att2 = AttributeValue.builder() - .s("My Movie 1") - .build(); - - parametersRec1.add(att1); - parametersRec1.add(att2); - - BatchStatementRequest statementRequestRec1 = BatchStatementRequest.builder() - .statement(sqlStatement) - .parameters(parametersRec1) - .build(); - - // Specify record 2. - List parametersRec2 = new ArrayList<>(); - AttributeValue attRec2 = AttributeValue.builder() - .n(String.valueOf("2022")) - .build(); - - AttributeValue attRec2a = AttributeValue.builder() - .s("My Movie 2") - .build(); - - parametersRec2.add(attRec2); - parametersRec2.add(attRec2a); - BatchStatementRequest statementRequestRec2 = BatchStatementRequest.builder() - .statement(sqlStatement) - .parameters(parametersRec2) - .build(); - - // Specify record 3. - List parametersRec3 = new ArrayList<>(); - AttributeValue attRec3 = AttributeValue.builder() - .n(String.valueOf("2022")) - .build(); - - AttributeValue attRec3a = AttributeValue.builder() - .s("My Movie 3") - .build(); - - parametersRec3.add(attRec3); - parametersRec3.add(attRec3a); - - BatchStatementRequest statementRequestRec3 = BatchStatementRequest.builder() - .statement(sqlStatement) - .parameters(parametersRec3) - .build(); - - // Add all three movies to the list. - List myBatchStatementList = new ArrayList<>(); - myBatchStatementList.add(statementRequestRec1); - myBatchStatementList.add(statementRequestRec2); - myBatchStatementList.add(statementRequestRec3); - - BatchExecuteStatementRequest batchRequest = BatchExecuteStatementRequest.builder() - .statements(myBatchStatementList) - .build(); - - try { - ddb.batchExecuteStatement(batchRequest); - System.out.println("Deleted three movies using a batch command."); - - } catch (DynamoDbException e) { - System.err.println(e.getMessage()); - System.exit(1); - } - } - - public static void deleteDynamoDBTable(DynamoDbClient ddb, String tableName) { - DeleteTableRequest request = DeleteTableRequest.builder() - .tableName(tableName) - .build(); - - try { - ddb.deleteTable(request); - - } catch (DynamoDbException e) { - System.err.println(e.getMessage()); - System.exit(1); - } - System.out.println(tableName + " was successfully deleted!"); - } - - private static ExecuteStatementResponse executeStatementRequest(DynamoDbClient ddb, String statement, - List parameters) { - ExecuteStatementRequest request = ExecuteStatementRequest.builder() - .statement(statement) - .parameters(parameters) - .build(); - - return ddb.executeStatement(request); - } -} +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.dynamodb.scenario; + +// snippet-start:[dynamodb.java2.scenario.partiql.batch.import] + +import software.amazon.awssdk.core.waiters.WaiterResponse; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.dynamodb.DynamoDbClient; +import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition; +import software.amazon.awssdk.services.dynamodb.model.AttributeValue; +import software.amazon.awssdk.services.dynamodb.model.BatchExecuteStatementRequest; +import software.amazon.awssdk.services.dynamodb.model.BatchExecuteStatementResponse; +import software.amazon.awssdk.services.dynamodb.model.BatchStatementRequest; +import software.amazon.awssdk.services.dynamodb.model.CreateTableRequest; +import software.amazon.awssdk.services.dynamodb.model.CreateTableResponse; +import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; +import software.amazon.awssdk.services.dynamodb.model.DescribeTableRequest; +import software.amazon.awssdk.services.dynamodb.model.DescribeTableResponse; +import software.amazon.awssdk.services.dynamodb.model.DynamoDbException; +import software.amazon.awssdk.services.dynamodb.model.ExecuteStatementRequest; +import software.amazon.awssdk.services.dynamodb.model.ExecuteStatementResponse; +import software.amazon.awssdk.services.dynamodb.model.KeySchemaElement; +import software.amazon.awssdk.services.dynamodb.model.KeyType; +import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughput; +import software.amazon.awssdk.services.dynamodb.waiters.DynamoDbWaiter; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +// snippet-end:[dynamodb.java2.scenario.partiql.batch.import] + +/** + * Before running this Java V2 code example, set up your development + * environment, including your credentials. + * + * For more information, see the following documentation topic: + * + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + * + * This Java example performs the following tasks: + * + * 1. Creates the Amazon DynamoDB movie table with a partition and sort key. + * 2. Puts new records into the table using a BatchExecuteStatement + * 3. Updates items using a BatchExecuteStatement. + * 4. Deletes items by using a BatchExecuteStatement. + * 5. Deletes the table. + * + * To see another code example with more options using PartiQL, see the + * ScenarioPartiQ code example. + */ + +// snippet-start:[dynamodb.java2.scenario.partiql.batch.main] +public class ScenarioPartiQLBatch { + public static void main(String[] args) throws IOException { + String tableName = "MoviesPartiQBatch"; + Region region = Region.US_EAST_1; + DynamoDbClient ddb = DynamoDbClient.builder() + .region(region) + .build(); + + System.out.println("Creating an Amazon DynamoDB table named " + tableName + + " with a key named year and a sort key named title."); + createTable(ddb, tableName); + + System.out.println("Adding multiple records into the " + tableName + + " table using a batch command."); + putRecordBatch(ddb); + + // Update multiple movies by using the BatchExecute statement. + String title1 = "Star Wars"; + int year1 = 1977; + String title2 = "Wizard of Oz"; + int year2 = 1939; + + System.out.println("Query two movies."); + getBatch(ddb, tableName, title1, title2, year1, year2); + + System.out.println("Updating multiple records using a batch command."); + updateTableItemBatch(ddb); + + System.out.println("Deleting multiple records using a batch command."); + deleteItemBatch(ddb); + + System.out.println("Deleting the Amazon DynamoDB table."); + deleteDynamoDBTable(ddb, tableName); + ddb.close(); + } + + public static boolean getBatch(DynamoDbClient ddb, String tableName, String title1, String title2, int year1, int year2) { + String getBatch = "SELECT * FROM " + tableName + " WHERE title = ? AND year = ?"; + + List statements = new ArrayList<>(); + statements.add(BatchStatementRequest.builder() + .statement(getBatch) + .parameters(AttributeValue.builder().s(title1).build(), + AttributeValue.builder().n(String.valueOf(year1)).build()) + .build()); + statements.add(BatchStatementRequest.builder() + .statement(getBatch) + .parameters(AttributeValue.builder().s(title2).build(), + AttributeValue.builder().n(String.valueOf(year2)).build()) + .build()); + + BatchExecuteStatementRequest batchExecuteStatementRequest = BatchExecuteStatementRequest.builder() + .statements(statements) + .build(); + + try { + BatchExecuteStatementResponse response = ddb.batchExecuteStatement(batchExecuteStatementRequest); + if (!response.responses().isEmpty()) { + response.responses().forEach(r -> { + System.out.println(r.item().get("title") + "\\t" + r.item().get("year")); + }); + return true; + } else { + System.out.println("Couldn't find either " + title1 + " or " + title2 + "."); + return false; + } + } catch (DynamoDbException e) { + System.err.println(e.getMessage()); + return false; + } + } + + public static void createTable(DynamoDbClient ddb, String tableName) { + DynamoDbWaiter dbWaiter = ddb.waiter(); + ArrayList attributeDefinitions = new ArrayList<>(); + + // Define attributes. + attributeDefinitions.add(AttributeDefinition.builder() + .attributeName("year") + .attributeType("N") + .build()); + + attributeDefinitions.add(AttributeDefinition.builder() + .attributeName("title") + .attributeType("S") + .build()); + + ArrayList tableKey = new ArrayList<>(); + KeySchemaElement key = KeySchemaElement.builder() + .attributeName("year") + .keyType(KeyType.HASH) + .build(); + + KeySchemaElement key2 = KeySchemaElement.builder() + .attributeName("title") + .keyType(KeyType.RANGE) // Sort + .build(); + + // Add KeySchemaElement objects to the list. + tableKey.add(key); + tableKey.add(key2); + + CreateTableRequest request = CreateTableRequest.builder() + .keySchema(tableKey) + .provisionedThroughput(ProvisionedThroughput.builder() + .readCapacityUnits(10L) + .writeCapacityUnits(10L) + .build()) + .attributeDefinitions(attributeDefinitions) + .tableName(tableName) + .build(); + + try { + CreateTableResponse response = ddb.createTable(request); + DescribeTableRequest tableRequest = DescribeTableRequest.builder() + .tableName(tableName) + .build(); + + // Wait until the Amazon DynamoDB table is created. + WaiterResponse waiterResponse = dbWaiter + .waitUntilTableExists(tableRequest); + waiterResponse.matched().response().ifPresent(System.out::println); + String newTable = response.tableDescription().tableName(); + System.out.println("The " + newTable + " was successfully created."); + + } catch (DynamoDbException e) { + System.err.println(e.getMessage()); + System.exit(1); + } + } + + public static void putRecordBatch(DynamoDbClient ddb) { + String sqlStatement = "INSERT INTO MoviesPartiQBatch VALUE {'year':?, 'title' : ?, 'info' : ?}"; + try { + // Create three movies to add to the Amazon DynamoDB table. + // Set data for Movie 1. + List parameters = new ArrayList<>(); + + AttributeValue att1 = AttributeValue.builder() + .n("1977") + .build(); + + AttributeValue att2 = AttributeValue.builder() + .s("Star Wars") + .build(); + + AttributeValue att3 = AttributeValue.builder() + .s("No Information") + .build(); + + parameters.add(att1); + parameters.add(att2); + parameters.add(att3); + + BatchStatementRequest statementRequestMovie1 = BatchStatementRequest.builder() + .statement(sqlStatement) + .parameters(parameters) + .build(); + + // Set data for Movie 2. + List parametersMovie2 = new ArrayList<>(); + AttributeValue attMovie2 = AttributeValue.builder() + .n("1939") + .build(); + + AttributeValue attMovie2A = AttributeValue.builder() + .s("Wizard of Oz") + .build(); + + AttributeValue attMovie2B = AttributeValue.builder() + .s("No Information") + .build(); + + parametersMovie2.add(attMovie2); + parametersMovie2.add(attMovie2A); + parametersMovie2.add(attMovie2B); + + BatchStatementRequest statementRequestMovie2 = BatchStatementRequest.builder() + .statement(sqlStatement) + .parameters(parametersMovie2) + .build(); + + // Set data for Movie 3. + List parametersMovie3 = new ArrayList<>(); + AttributeValue attMovie3 = AttributeValue.builder() + .n(String.valueOf("2022")) + .build(); + + AttributeValue attMovie3A = AttributeValue.builder() + .s("My Movie 3") + .build(); + + AttributeValue attMovie3B = AttributeValue.builder() + .s("No Information") + .build(); + + parametersMovie3.add(attMovie3); + parametersMovie3.add(attMovie3A); + parametersMovie3.add(attMovie3B); + + BatchStatementRequest statementRequestMovie3 = BatchStatementRequest.builder() + .statement(sqlStatement) + .parameters(parametersMovie3) + .build(); + + // Add all three movies to the list. + List myBatchStatementList = new ArrayList<>(); + myBatchStatementList.add(statementRequestMovie1); + myBatchStatementList.add(statementRequestMovie2); + myBatchStatementList.add(statementRequestMovie3); + + BatchExecuteStatementRequest batchRequest = BatchExecuteStatementRequest.builder() + .statements(myBatchStatementList) + .build(); + + BatchExecuteStatementResponse response = ddb.batchExecuteStatement(batchRequest); + System.out.println("ExecuteStatement successful: " + response.toString()); + System.out.println("Added new movies using a batch command."); + + } catch (DynamoDbException e) { + System.err.println(e.getMessage()); + System.exit(1); + } + } + + public static void updateTableItemBatch(DynamoDbClient ddb) { + String sqlStatement = "UPDATE MoviesPartiQBatch SET info = 'directors\":[\"Merian C. Cooper\",\"Ernest B. Schoedsack' where year=? and title=?"; + List parametersRec1 = new ArrayList<>(); + + // Update three records. + AttributeValue att1 = AttributeValue.builder() + .n(String.valueOf("2022")) + .build(); + + AttributeValue att2 = AttributeValue.builder() + .s("My Movie 1") + .build(); + + parametersRec1.add(att1); + parametersRec1.add(att2); + + BatchStatementRequest statementRequestRec1 = BatchStatementRequest.builder() + .statement(sqlStatement) + .parameters(parametersRec1) + .build(); + + // Update record 2. + List parametersRec2 = new ArrayList<>(); + AttributeValue attRec2 = AttributeValue.builder() + .n(String.valueOf("2022")) + .build(); + + AttributeValue attRec2a = AttributeValue.builder() + .s("My Movie 2") + .build(); + + parametersRec2.add(attRec2); + parametersRec2.add(attRec2a); + BatchStatementRequest statementRequestRec2 = BatchStatementRequest.builder() + .statement(sqlStatement) + .parameters(parametersRec2) + .build(); + + // Update record 3. + List parametersRec3 = new ArrayList<>(); + AttributeValue attRec3 = AttributeValue.builder() + .n(String.valueOf("2022")) + .build(); + + AttributeValue attRec3a = AttributeValue.builder() + .s("My Movie 3") + .build(); + + parametersRec3.add(attRec3); + parametersRec3.add(attRec3a); + BatchStatementRequest statementRequestRec3 = BatchStatementRequest.builder() + .statement(sqlStatement) + .parameters(parametersRec3) + .build(); + + // Add all three movies to the list. + List myBatchStatementList = new ArrayList<>(); + myBatchStatementList.add(statementRequestRec1); + myBatchStatementList.add(statementRequestRec2); + myBatchStatementList.add(statementRequestRec3); + + BatchExecuteStatementRequest batchRequest = BatchExecuteStatementRequest.builder() + .statements(myBatchStatementList) + .build(); + + try { + BatchExecuteStatementResponse response = ddb.batchExecuteStatement(batchRequest); + System.out.println("ExecuteStatement successful: " + response.toString()); + System.out.println("Updated three movies using a batch command."); + + } catch (DynamoDbException e) { + System.err.println(e.getMessage()); + System.exit(1); + } + System.out.println("Item was updated!"); + } + + public static void deleteItemBatch(DynamoDbClient ddb) { + String sqlStatement = "DELETE FROM MoviesPartiQBatch WHERE year = ? and title=?"; + List parametersRec1 = new ArrayList<>(); + + // Specify three records to delete. + AttributeValue att1 = AttributeValue.builder() + .n(String.valueOf("2022")) + .build(); + + AttributeValue att2 = AttributeValue.builder() + .s("My Movie 1") + .build(); + + parametersRec1.add(att1); + parametersRec1.add(att2); + + BatchStatementRequest statementRequestRec1 = BatchStatementRequest.builder() + .statement(sqlStatement) + .parameters(parametersRec1) + .build(); + + // Specify record 2. + List parametersRec2 = new ArrayList<>(); + AttributeValue attRec2 = AttributeValue.builder() + .n(String.valueOf("2022")) + .build(); + + AttributeValue attRec2a = AttributeValue.builder() + .s("My Movie 2") + .build(); + + parametersRec2.add(attRec2); + parametersRec2.add(attRec2a); + BatchStatementRequest statementRequestRec2 = BatchStatementRequest.builder() + .statement(sqlStatement) + .parameters(parametersRec2) + .build(); + + // Specify record 3. + List parametersRec3 = new ArrayList<>(); + AttributeValue attRec3 = AttributeValue.builder() + .n(String.valueOf("2022")) + .build(); + + AttributeValue attRec3a = AttributeValue.builder() + .s("My Movie 3") + .build(); + + parametersRec3.add(attRec3); + parametersRec3.add(attRec3a); + + BatchStatementRequest statementRequestRec3 = BatchStatementRequest.builder() + .statement(sqlStatement) + .parameters(parametersRec3) + .build(); + + // Add all three movies to the list. + List myBatchStatementList = new ArrayList<>(); + myBatchStatementList.add(statementRequestRec1); + myBatchStatementList.add(statementRequestRec2); + myBatchStatementList.add(statementRequestRec3); + + BatchExecuteStatementRequest batchRequest = BatchExecuteStatementRequest.builder() + .statements(myBatchStatementList) + .build(); + + try { + ddb.batchExecuteStatement(batchRequest); + System.out.println("Deleted three movies using a batch command."); + + } catch (DynamoDbException e) { + System.err.println(e.getMessage()); + System.exit(1); + } + } + + public static void deleteDynamoDBTable(DynamoDbClient ddb, String tableName) { + DeleteTableRequest request = DeleteTableRequest.builder() + .tableName(tableName) + .build(); + + try { + ddb.deleteTable(request); + + } catch (DynamoDbException e) { + System.err.println(e.getMessage()); + System.exit(1); + } + System.out.println(tableName + " was successfully deleted!"); + } + + private static ExecuteStatementResponse executeStatementRequest(DynamoDbClient ddb, String statement, + List parameters) { + ExecuteStatementRequest request = ExecuteStatementRequest.builder() + .statement(statement) + .parameters(parameters) + .build(); + + return ddb.executeStatement(request); + } +} // snippet-end:[dynamodb.java2.scenario.partiql.batch.main] \ No newline at end of file diff --git a/javav2/example_code/dynamodb/src/test/java/DynamoDBTest.java b/javav2/example_code/dynamodb/src/test/java/DynamoDBTest.java index 0d29afdcc53..5e31ecffbe4 100644 --- a/javav2/example_code/dynamodb/src/test/java/DynamoDBTest.java +++ b/javav2/example_code/dynamodb/src/test/java/DynamoDBTest.java @@ -10,8 +10,8 @@ import com.example.dynamodb.ListTables; import com.example.dynamodb.PutItem; import com.example.dynamodb.Query; -import com.example.dynamodb.Scenario; -import com.example.dynamodb.ScenarioPartiQ; +import com.example.dynamodb.scenario.Scenario; +import com.example.dynamodb.scenario.ScenarioPartiQ; import com.example.dynamodb.SyncPagination; import com.example.dynamodb.UpdateItem; import com.example.dynamodb.UpdateTable;