List of usage examples for com.amazonaws.services.dynamodbv2.model PutItemRequest PutItemRequest
public PutItemRequest()
From source file:com.clicktravel.infrastructure.persistence.aws.dynamodb.integration.DynamoDbDataGenerator.java
License:Apache License
StubVariantTwoItem createStubVariantTwoItem() { final StubVariantTwoItem stubItem = new StubVariantTwoItem(); stubItem.setId(randomId());//from w w w .jav a2s . c o m stubItem.setStringProperty(randomString(10)); stubItem.setStringPropertyTwo(randomString(10)); stubItem.setVersion((long) randomInt(100)); final Map<String, AttributeValue> itemMap = new HashMap<>(); itemMap.put("id", new AttributeValue(stubItem.getId())); if (stubItem.getStringProperty() != null) { itemMap.put("stringProperty", new AttributeValue(stubItem.getStringProperty())); } if (stubItem.getStringPropertyTwo() != null) { itemMap.put("stringPropertyTwo", new AttributeValue(stubItem.getStringPropertyTwo())); } itemMap.put("version", new AttributeValue().withN(String.valueOf(stubItem.getVersion()))); itemMap.put("discriminator", new AttributeValue().withS("b")); final PutItemRequest putItemRequest = new PutItemRequest() .withTableName(unitTestSchemaName + "." + stubItemTableName).withItem(itemMap); amazonDynamoDbClient.putItem(putItemRequest); logger.debug("Created stub item with id: " + stubItem.getId()); createdItemIds.add(stubItem.getId()); return stubItem; }
From source file:com.clicktravel.infrastructure.persistence.aws.dynamodb.integration.DynamoDbDataGenerator.java
License:Apache License
StubWithRangeItem createStubWithRangeItem() { final StubWithRangeItem stubItem = new StubWithRangeItem(); stubItem.setId(randomId());//from w ww. java 2s . c o m stubItem.setSupportingId(randomId()); stubItem.setStringProperty(randomString(10)); stubItem.setBooleanProperty(randomBoolean()); stubItem.setStringSetProperty( new HashSet<>(Sets.newSet(randomString(10), randomString(10), randomString(10)))); stubItem.setVersion((long) randomInt(100)); final Map<String, AttributeValue> itemMap = new HashMap<>(); itemMap.put("id", new AttributeValue(stubItem.getId())); itemMap.put("supportingId", new AttributeValue(stubItem.getSupportingId())); if (stubItem.getStringProperty() != null) { itemMap.put("stringProperty", new AttributeValue(stubItem.getStringProperty())); } itemMap.put("booleanProperty", new AttributeValue().withN(stubItem.isBooleanProperty() ? "1" : "0")); if (!stubItem.getStringSetProperty().isEmpty()) { itemMap.put("stringSetProperty", new AttributeValue().withSS(stubItem.getStringSetProperty())); } itemMap.put("version", new AttributeValue().withN(String.valueOf(stubItem.getVersion()))); final PutItemRequest putItemRequest = new PutItemRequest() .withTableName(unitTestSchemaName + "." + stubItemWithRangeTableName).withItem(itemMap); amazonDynamoDbClient.putItem(putItemRequest); logger.debug("Created stub item with id: " + stubItem.getId()); createdItemIds.add(stubItem.getId()); return stubItem; }
From source file:com.clicktravel.infrastructure.persistence.aws.dynamodb.integration.DynamoDbDataGenerator.java
License:Apache License
StubItem createStubItemWithExtraValues() { final StubItem stubItem = randomStubItem(); final Map<String, AttributeValue> itemMap = new HashMap<>(); itemMap.put("id", new AttributeValue(stubItem.getId())); if (stubItem.getStringProperty() != null) { itemMap.put("stringProperty", new AttributeValue(stubItem.getStringProperty())); }/*from ww w .j a v a 2s . c om*/ if (stubItem.getStringProperty2() != null) { itemMap.put("stringProperty2", new AttributeValue(stubItem.getStringProperty2())); } itemMap.put("booleanProperty", new AttributeValue().withN(stubItem.isBooleanProperty() ? "1" : "0")); if (!stubItem.getStringSetProperty().isEmpty()) { itemMap.put("stringSetProperty", new AttributeValue().withSS(stubItem.getStringSetProperty())); } // Add random properties for (int i = 0; i < randomInt(10); i++) { itemMap.put(randomString(10), new AttributeValue(randomString())); } itemMap.put("version", new AttributeValue().withN(String.valueOf(stubItem.getVersion()))); final PutItemRequest putItemRequest = new PutItemRequest() .withTableName(unitTestSchemaName + "." + stubItemTableName).withItem(itemMap); amazonDynamoDbClient.putItem(putItemRequest); logger.debug("Created stub item with id: " + stubItem.getId()); createdItemIds.add(stubItem.getId()); return stubItem; }
From source file:com.clicktravel.infrastructure.persistence.aws.dynamodb.integration.DynamoDbDataGenerator.java
License:Apache License
private void dynamoCreateItem(final StubItem stubItem) { final Map<String, AttributeValue> itemMap = new HashMap<>(); itemMap.put("id", new AttributeValue(stubItem.getId())); if (stubItem.getStringProperty() != null) { itemMap.put("stringProperty", new AttributeValue(stubItem.getStringProperty())); }//from w w w. j a v a 2 s . c om if (stubItem.getStringProperty2() != null) { itemMap.put("stringProperty2", new AttributeValue(stubItem.getStringProperty2())); } itemMap.put("booleanProperty", new AttributeValue().withN(stubItem.isBooleanProperty() ? "1" : "0")); if (!stubItem.getStringSetProperty().isEmpty()) { itemMap.put("stringSetProperty", new AttributeValue().withSS(stubItem.getStringSetProperty())); } itemMap.put("version", new AttributeValue().withN(String.valueOf(stubItem.getVersion()))); final PutItemRequest putItemRequest = new PutItemRequest() .withTableName(unitTestSchemaName + "." + stubItemTableName).withItem(itemMap); amazonDynamoDbClient.putItem(putItemRequest); logger.debug("Created stub item with id: " + stubItem.getId()); createdItemIds.add(stubItem.getId()); }
From source file:com.clicktravel.infrastructure.persistence.aws.dynamodb.manager.DynamoDbTemplateInfrastructureManager.java
License:Apache License
public void init() { for (final AbstractDynamoDbTemplate dynamoDbTemplate : dynamoDbTemplates) { final Collection<String> tablesPendingCreation = new ArrayList<>(); final DatabaseSchemaHolder databaseSchemaHolder = dynamoDbTemplate.databaseSchemaHolder(); for (final ItemConfiguration itemConfiguration : databaseSchemaHolder.itemConfigurations()) { if (VariantItemConfiguration.class.isAssignableFrom(itemConfiguration.getClass())) { continue; }//w w w . j a v a 2 s .c o m final String tableName = databaseSchemaHolder.schemaName() + "." + itemConfiguration.tableName(); if (!tablesPendingCreation.contains(tableName) && !isTableCreated(tableName)) { final List<AttributeDefinition> attributeDefinitions = new ArrayList<>(); final PrimaryKeyDefinition primaryKeyDefinition = itemConfiguration.primaryKeyDefinition(); final String hashKey = primaryKeyDefinition.propertyName(); final ScalarAttributeType hashKeyType = getAttributeType(primaryKeyDefinition.propertyType()); attributeDefinitions.add( new AttributeDefinition().withAttributeName(hashKey).withAttributeType(hashKeyType)); final List<KeySchemaElement> keySchema = new ArrayList<>(); keySchema.add(new KeySchemaElement().withAttributeName(hashKey).withKeyType(KeyType.HASH)); if (CompoundPrimaryKeyDefinition.class.isAssignableFrom(primaryKeyDefinition.getClass())) { final CompoundPrimaryKeyDefinition compoundPrimaryKeyDefinition = (CompoundPrimaryKeyDefinition) primaryKeyDefinition; final String rangeKey = compoundPrimaryKeyDefinition.supportingPropertyName(); final ScalarAttributeType rangeKeyType = getAttributeType( compoundPrimaryKeyDefinition.supportingPropertyType()); attributeDefinitions.add(new AttributeDefinition().withAttributeName(rangeKey) .withAttributeType(rangeKeyType)); keySchema .add(new KeySchemaElement().withAttributeName(rangeKey).withKeyType(KeyType.RANGE)); } final Collection<GlobalSecondaryIndex> globalSecondaryIndexes = new ArrayList<>(); for (final IndexDefinition indexDefinition : itemConfiguration.indexDefinitions()) { final ScalarAttributeType attributeType = getAttributeType( primaryKeyDefinition.propertyType()); // if there are any indexes, we need to add attributes for them attributeDefinitions .add(new AttributeDefinition().withAttributeName(indexDefinition.propertyName()) .withAttributeType(attributeType)); final ProvisionedThroughput indexProvisionedThroughput = new ProvisionedThroughput() .withReadCapacityUnits((long) readThroughput) .withWriteCapacityUnits((long) writeThroughput); final GlobalSecondaryIndex globalSecondaryIndex = new GlobalSecondaryIndex() .withIndexName(indexDefinition.propertyName() + "_idx") .withProvisionedThroughput(indexProvisionedThroughput) .withProjection(new Projection().withProjectionType("ALL")); final ArrayList<KeySchemaElement> indexKeySchema = new ArrayList<KeySchemaElement>(); indexKeySchema.add(new KeySchemaElement().withAttributeName(indexDefinition.propertyName()) .withKeyType(KeyType.HASH)); globalSecondaryIndex.setKeySchema(indexKeySchema); globalSecondaryIndexes.add(globalSecondaryIndex); } final ProvisionedThroughput tableProvisionedThroughput = new ProvisionedThroughput() .withReadCapacityUnits((long) readThroughput) .withWriteCapacityUnits((long) writeThroughput); CreateTableRequest request = new CreateTableRequest().withTableName(tableName) .withAttributeDefinitions(attributeDefinitions).withKeySchema(keySchema) .withProvisionedThroughput(tableProvisionedThroughput); if (!globalSecondaryIndexes.isEmpty()) { request = request.withGlobalSecondaryIndexes(globalSecondaryIndexes); } logger.debug("Creating table " + tableName); createTable(request, globalSecondaryIndexes.isEmpty()); tablesPendingCreation.add(tableName); } // Create tables for unique constraints if (!itemConfiguration.uniqueConstraints().isEmpty()) { final String uniqueConstraintTableName = databaseSchemaHolder.schemaName() + "-indexes." + itemConfiguration.tableName(); if (!isTableCreated(uniqueConstraintTableName)) { final List<KeySchemaElement> keySchema = new ArrayList<>(); keySchema.add(new KeySchemaElement("property", KeyType.HASH)); keySchema.add(new KeySchemaElement("value", KeyType.RANGE)); final List<AttributeDefinition> attributeDefinitions = new ArrayList<>(); attributeDefinitions.add(new AttributeDefinition("property", ScalarAttributeType.S)); attributeDefinitions.add(new AttributeDefinition("value", ScalarAttributeType.S)); final ProvisionedThroughput tableProvisionedThroughput = new ProvisionedThroughput() .withReadCapacityUnits((long) readThroughput) .withWriteCapacityUnits((long) writeThroughput); final CreateTableRequest createTableRequest = new CreateTableRequest() .withTableName(uniqueConstraintTableName) .withAttributeDefinitions(attributeDefinitions).withKeySchema(keySchema) .withProvisionedThroughput(tableProvisionedThroughput); createTable(createTableRequest, true); tablesPendingCreation.add(uniqueConstraintTableName); } } } // Create table for sequences if (!databaseSchemaHolder.sequenceConfigurations().isEmpty()) { final String sequenceTableName = databaseSchemaHolder.schemaName() + "-sequences"; if (!isTableCreated(sequenceTableName)) { final ProvisionedThroughput sequenceProvisionedThroughput = new ProvisionedThroughput() .withReadCapacityUnits((long) readThroughput) .withWriteCapacityUnits((long) writeThroughput); final List<KeySchemaElement> keySchema = new ArrayList<>(); keySchema.add(new KeySchemaElement().withAttributeName("name").withKeyType(KeyType.HASH)); final List<AttributeDefinition> attributeDefinitions = new ArrayList<>(); attributeDefinitions .add(new AttributeDefinition().withAttributeName("name").withAttributeType("S")); final CreateTableRequest request = new CreateTableRequest().withTableName(sequenceTableName) .withAttributeDefinitions(attributeDefinitions).withKeySchema(keySchema) .withProvisionedThroughput(sequenceProvisionedThroughput); logger.debug("Creating sequence table " + sequenceTableName); amazonDynamoDbClient.createTable(request); tablesPendingCreation.add(sequenceTableName); } } logger.debug("Waiting for table creation: " + tablesPendingCreation); final Collection<String> tableNames = new ArrayList<>(tablesPendingCreation); final long startTime = System.currentTimeMillis(); while (System.currentTimeMillis() - startTime < TABLE_CREATION_TIMEOUT_MS) { for (final String tableName : tableNames) { if (isTableCreated(tableName)) { logger.debug("Table " + tableName + " successfully created"); tablesPendingCreation.remove(tableName); } try { Thread.sleep(1000); } catch (final InterruptedException e) { throw new IllegalStateException(e); } } if (tablesPendingCreation.size() == 0) { break; } tableNames.clear(); tableNames.addAll(tablesPendingCreation); } if (tablesPendingCreation.size() != 0) { throw new IllegalStateException( "Unable to create tables for DynamoDb template: " + tablesPendingCreation); } // Seed the sequences with their starting values if (!databaseSchemaHolder.sequenceConfigurations().isEmpty()) { final ScanRequest scanRequest = new ScanRequest(databaseSchemaHolder.schemaName() + "-sequences"); final ScanResult scanResult = amazonDynamoDbClient.scan(scanRequest); Map<String, AttributeValue> lastEvaluatedKey = null; final Map<String, Map<String, AttributeValue>> sequenceItems = new HashMap<>(); do { for (final Map<String, AttributeValue> item : scanResult.getItems()) { sequenceItems.put(item.get("name").getS(), item); } lastEvaluatedKey = scanResult.getLastEvaluatedKey(); } while (lastEvaluatedKey != null); for (final SequenceConfiguration sequenceConfiguration : databaseSchemaHolder .sequenceConfigurations()) { final Map<String, AttributeValue> sequenceItem = sequenceItems .get(sequenceConfiguration.sequenceName()); if (sequenceItem == null) { final Map<String, ExpectedAttributeValue> expectedResults = new HashMap<>(); expectedResults.put("name", new ExpectedAttributeValue(false)); final Map<String, AttributeValue> attributeMap = new HashMap<>(); attributeMap.put("name", new AttributeValue().withS(sequenceConfiguration.sequenceName())); attributeMap.put("currentValue", new AttributeValue() .withN(String.valueOf(sequenceConfiguration.startingValue() - 1))); final String tableName = databaseSchemaHolder.schemaName() + "-sequences"; final PutItemRequest itemRequest = new PutItemRequest().withTableName(tableName) .withItem(attributeMap).withExpected(expectedResults); amazonDynamoDbClient.putItem(itemRequest); } } } dynamoDbTemplate.initialize(amazonDynamoDbClient); } }
From source file:com.grublr.geo.model.PutPointRequest.java
License:Open Source License
public PutPointRequest(GeoPoint geoPoint, AttributeValue rangeKeyValue) { putItemRequest = new PutItemRequest(); putItemRequest.setItem(new HashMap<String, AttributeValue>()); putRequest = new PutRequest(); putRequest.setItem(new HashMap<String, AttributeValue>()); this.geoPoint = geoPoint; this.rangeKeyValue = rangeKeyValue; }
From source file:com.lvl6.mobsters.dynamo.setup.TransactionExamples.java
License:Open Source License
/** * This example writes two items.//from w ww. j av a2 s .c o m */ public void twoItemTransaction() { print("\n*** twoItemTransaction() ***\n"); // Create a new transaction from the transaction manager Transaction t1 = txManager.newTransaction(); // Add a new PutItem request to the transaction object (instead of on the AmazonDynamoDB client) Map<String, AttributeValue> item1 = new HashMap<String, AttributeValue>(); item1.put(EXAMPLE_TABLE_HASH_KEY, new AttributeValue("Item1")); print("Put item: " + item1); t1.putItem(new PutItemRequest().withTableName(EXAMPLE_TABLE_NAME).withItem(item1)); print("At this point Item1 is in the table, but is not yet committed"); // Add second PutItem request for a different item to the transaction object Map<String, AttributeValue> item2 = new HashMap<String, AttributeValue>(); item2.put(EXAMPLE_TABLE_HASH_KEY, new AttributeValue("Item2")); print("Put item: " + item2); t1.putItem(new PutItemRequest().withTableName(EXAMPLE_TABLE_NAME).withItem(item2)); print("At this point Item2 is in the table, but is not yet committed"); // Commit the transaction. t1.commit(); print("Committed transaction. Item1 and Item2 are now both committed."); t1.delete(); print("Deleted the transaction item."); }
From source file:com.lvl6.mobsters.dynamo.setup.TransactionExamples.java
License:Open Source License
/** * This example demonstrates two transactions attempting to write to the same item. * Only one transaction will go through. *//* w w w . j a v a2 s. co m*/ public void conflictingTransactions() { print("\n*** conflictingTransactions() ***\n"); // Start transaction t1 Transaction t1 = txManager.newTransaction(); // Construct a primary key of an item that will overlap between two transactions. Map<String, AttributeValue> item1Key = new HashMap<String, AttributeValue>(); item1Key.put(EXAMPLE_TABLE_HASH_KEY, new AttributeValue("conflictingTransactions_Item1")); item1Key = Collections.unmodifiableMap(item1Key); // Add a new PutItem request to the transaction object (instead of on the AmazonDynamoDB client) // This will eventually get rolled back when t2 tries to work on the same item Map<String, AttributeValue> item1T1 = new HashMap<String, AttributeValue>(item1Key); item1T1.put("WhichTransaction?", new AttributeValue("t1")); print("T1 - Put item: " + item1T1); t1.putItem(new PutItemRequest().withTableName(EXAMPLE_TABLE_NAME).withItem(item1T1)); print("T1 - At this point Item1 is in the table, but is not yet committed"); Map<String, AttributeValue> item2T1 = new HashMap<String, AttributeValue>(); item2T1.put(EXAMPLE_TABLE_HASH_KEY, new AttributeValue("conflictingTransactions_Item2")); print("T1 - Put a second, non-overlapping item: " + item2T1); t1.putItem(new PutItemRequest().withTableName(EXAMPLE_TABLE_NAME).withItem(item2T1)); print("T1 - At this point Item2 is also in the table, but is not yet committed"); // Start a new transaction t2 Transaction t2 = txManager.newTransaction(); Map<String, AttributeValue> item1T2 = new HashMap<String, AttributeValue>(item1Key); item1T1.put("WhichTransaction?", new AttributeValue("t2 - I win!")); print("T2 - Put item: " + item1T2); t2.putItem(new PutItemRequest().withTableName(EXAMPLE_TABLE_NAME).withItem(item1T2)); print("T2 - At this point Item1 from t2 is in the table, but is not yet committed. t1 was rolled back."); // To prove that t1 will have been rolled back by this point, attempt to commit it. try { print("Attempting to commit t1 (this will fail)"); t1.commit(); throw new RuntimeException("T1 should have been rolled back. This is a bug."); } catch (TransactionRolledBackException e) { print("Transaction t1 was rolled back, as expected"); t1.delete(); // Delete it, no longer needed } // Now put a second item as a part of t2 Map<String, AttributeValue> item3T2 = new HashMap<String, AttributeValue>(); item3T2.put(EXAMPLE_TABLE_HASH_KEY, new AttributeValue("conflictingTransactions_Item3")); print("T2 - Put item: " + item3T2); t2.putItem(new PutItemRequest().withTableName(EXAMPLE_TABLE_NAME).withItem(item3T2)); print("T2 - At this point Item3 is in the table, but is not yet committed"); print("Committing and deleting t2"); t2.commit(); t2.delete(); // Now to verify, get the items Item1, Item2, and Item3. // More on read operations later. GetItemResult result = txManager.getItem( new GetItemRequest().withTableName(EXAMPLE_TABLE_NAME).withKey(item1Key), IsolationLevel.UNCOMMITTED); print("Notice that t2's write to Item1 won: " + result.getItem()); result = txManager.getItem(new GetItemRequest().withTableName(EXAMPLE_TABLE_NAME).withKey(item3T2), IsolationLevel.UNCOMMITTED); print("Notice that t2's write to Item3 also went through: " + result.getItem()); result = txManager.getItem(new GetItemRequest().withTableName(EXAMPLE_TABLE_NAME).withKey(item2T1), IsolationLevel.UNCOMMITTED); print("However, t1's write to Item2 did not go through (since Item2 is null): " + result.getItem()); }
From source file:com.lvl6.mobsters.dynamo.setup.TransactionExamples.java
License:Open Source License
/** * This example shows the kinds of exceptions that you might need to handle *//*from ww w . j a va2 s .co m*/ public void errorHandling() { print("\n*** errorHandling() ***\n"); // Create a new transaction from the transaction manager Transaction t1 = txManager.newTransaction(); boolean success = false; try { // Add a new PutItem request to the transaction object (instead of on the AmazonDynamoDB client) Map<String, AttributeValue> item1 = new HashMap<String, AttributeValue>(); item1.put(EXAMPLE_TABLE_HASH_KEY, new AttributeValue("Item1")); print("Put item: " + item1); t1.putItem(new PutItemRequest().withTableName(EXAMPLE_TABLE_NAME).withItem(item1)); // Commit the transaction. t1.commit(); success = true; print("Committed transaction. We aren't actually expecting failures in this example."); } catch (TransactionRolledBackException e) { // This gets thrown if the transaction was rolled back by another transaction throw e; } catch (ItemNotLockedException e) { // This gets thrown if there is too much contention with other transactions for the item you're trying to lock throw e; } catch (DuplicateRequestException e) { // This happens if you try to do two write operations on the same item in the same transaction throw e; } catch (InvalidRequestException e) { // This happens if you do something like forget the TableName or key attributes in the request throw e; } catch (TransactionException e) { // All exceptions thrown directly by this library derive from this. It is a catch-all throw e; } catch (AmazonServiceException e) { // However, your own requests can still fail if they're invalid. For example, you can get a // ValidationException if you try to add a "number" to a "string" in UpdateItem. So you have to handle // errors from DynamoDB in the same way you did before. Except now you should roll back the transaction if it fails. throw e; } finally { if (!success) { // It can be a good idea to use a "success" flag in this way, to ensure that you roll back if you get any exceptions // from the transaction library, or from DynamoDB, or any from the DynamoDB client library. These 3 exception base classes are: // TransactionException, AmazonServiceException, or AmazonClientExeption. // If you forget to roll back, no problem - another transaction will come along and roll yours back eventually. try { t1.rollback(); } catch (TransactionException te) { } // ignore, but should probably log } try { t1.delete(); } catch (TransactionException te) { } // ignore, but should probably log } }
From source file:com.makariev.dynamodb.data.populators.ForumPopulator.java
License:Apache License
private PutItemRequest request(String name, String category, Integer threads, Integer messages, Integer views) { final Map<String, AttributeValue> item = new HashMap<>(); if (null != name) { item.put("Name", new AttributeValue().withS(name)); }/*from w w w. j av a2 s. c om*/ if (null != category) { item.put("Category", new AttributeValue().withS(category)); } if (null != threads) { item.put("Threads", new AttributeValue().withN(threads.toString())); } if (null != messages) { item.put("Messages", new AttributeValue().withN(messages.toString())); } if (null != views) { item.put("Views", new AttributeValue().withN(views.toString())); } final PutItemRequest request = new PutItemRequest().withTableName(getTableName()).withItem(item); return request; }