Example usage for com.amazonaws.services.dynamodbv2.model PutItemRequest PutItemRequest

List of usage examples for com.amazonaws.services.dynamodbv2.model PutItemRequest PutItemRequest

Introduction

In this page you can find the example usage for com.amazonaws.services.dynamodbv2.model PutItemRequest PutItemRequest.

Prototype

public PutItemRequest() 

Source Link

Document

Default constructor for PutItemRequest object.

Usage

From source file:amazon.dynamodb.model.PutPointRequest.java

License:Open Source License

public PutPointRequest(GeoPunto 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:awslabs.lab22.SolutionCode.java

License:Open Source License

@Override
public void createAccountItem(AmazonDynamoDBClient ddbClient, String tableName, Account account) {
    // Create a HashMap<String, AttributeValue> object to hold the attributes of the item to add.
    Map<String, AttributeValue> itemAttributes = new HashMap<String, AttributeValue>();
    // Add the required items (Company and Email) from the account parameter to the attribute HashMap.
    itemAttributes.put("Company", new AttributeValue().withS(account.getCompany()));
    itemAttributes.put("Email", new AttributeValue().withS(account.getEmail()));

    // Check the account parameter and add all values that aren't empty strings ("") to the attribute HashMap.
    if (!account.getFirst().equals("")) {
        itemAttributes.put("First", new AttributeValue().withS(account.getFirst()));
    }/* w  w w  .  j  a  va2  s  .c  o  m*/
    if (!account.getLast().equals("")) {
        itemAttributes.put("Last", new AttributeValue().withS(account.getLast()));
    }
    if (!account.getAge().equals("")) {
        itemAttributes.put("Age", new AttributeValue().withN(account.getAge()));
    }

    // Construct a PutItemRequest object to put the attributes into the specified table.
    PutItemRequest putItemRequest = new PutItemRequest().withTableName(tableName).withItem(itemAttributes);

    // Submit the request using the putItem method of the ddbClient object.
    ddbClient.putItem(putItemRequest);
}

From source file:awslabs.lab22.StudentCode.java

License:Open Source License

/**
 * Create a DynamoDB item from the values specified in the account parameter. The names of the attributes in the
 * item should match the corresponding property names in the Account object. Don't add attributes for fields in the
 * Account object that are empty./*from w  w w  . j a  v a  2  s  .  c  om*/
 * 
 * Since the Company and Email attributes are part of the table key, those will always be provided in the Account
 * object when this method is called. This method will be called multiple times by the code controlling the lab.
 * 
 * Important: Even thought the Account.Age property is passed to you as a string, add it to the item as a numerical
 * value.
 * 
 * @param ddbClient The DynamoDB client object.
 * @param tableName The name of the table to add the item to.
 * @param account The Account object containing the data to add.
 */
@Override
public void createAccountItem(AmazonDynamoDBClient ddbClient, String tableName, Account account) {
    // TODO: Replace this call to the super class with your own implementation of the method.
    ddbClient.setRegion(Region.getRegion(Regions.US_EAST_1));
    Map<String, AttributeValue> items = new HashMap<String, AttributeValue>();
    items.put("Company", new AttributeValue().withS(account.getCompany()));
    items.put("Email", new AttributeValue().withS(account.getEmail()));

    if (account.getFirst() != null) {
        items.put("First", new AttributeValue().withS(account.getFirst()));
    }

    if (account.getLast() != null) {
        items.put("Last", new AttributeValue().withS(account.getLast()));
    }

    if (account.getAge() != null) {
        items.put("Age", new AttributeValue().withN(account.getAge()));
    }

    PutItemRequest request = new PutItemRequest().withTableName(tableName).withItem(items);
    ddbClient.putItem(request);
}

From source file:awslabs.lab51.SolutionCode.java

License:Open Source License

@Override
public void addImage(AmazonDynamoDBClient dynamoDbClient, String tableName, AmazonS3Client s3Client,
        String bucketName, String imageKey, String filePath) {

    try {/*from   w w  w. ja  va  2  s.com*/
        File file = new File(filePath);
        if (file.exists()) {
            s3Client.putObject(bucketName, imageKey, file);

            PutItemRequest putItemRequest = new PutItemRequest().withTableName(tableName);
            putItemRequest.addItemEntry("Key", new AttributeValue(imageKey));
            putItemRequest.addItemEntry("Bucket", new AttributeValue(bucketName));
            dynamoDbClient.putItem(putItemRequest);
            labController.logMessageToPage("Added imageKey: " + imageKey);
        } else {
            labController.logMessageToPage(
                    "Image doesn't exist on disk. Skipped: " + imageKey + "[" + filePath + "]");
        }
    } catch (Exception ex) {
        labController.logMessageToPage("addImage Error: " + ex.getMessage());
    }

}

From source file:cloudworker.DynamoDBService.java

License:Apache License

public static void addTask(String taskID, String task) {

    HashMap<String, AttributeValue> item = new HashMap<String, AttributeValue>();
    item.put("taskID", new AttributeValue().withS(taskID));
    item.put("Task", new AttributeValue(task));

    ExpectedAttributeValue notExpected = new ExpectedAttributeValue(false);
    Map<String, ExpectedAttributeValue> expected = new HashMap<String, ExpectedAttributeValue>();
    expected.put("taskID", notExpected);

    PutItemRequest putItemRequest = new PutItemRequest().withTableName(TABLE_NAME).withItem(item)
            .withExpected(expected); //put item only if no taskID exists!

    dynamoDB.putItem(putItemRequest);/*  ww  w  . j a  va  2s .  c  om*/

}

From source file:com.amediamanager.dao.DynamoDbUserDaoImpl.java

License:Apache License

@Override
public void save(User user) throws UserExistsException, DataSourceTableDoesNotExistException {
    try {/*from  w  w w  . ja v a  2s  .com*/
        // See if User item exists
        User existing = this.find(user.getEmail());

        // If the user exists, throw an exception
        if (existing != null) {
            throw new UserExistsException();
        }

        // Convert the User object to a Map. The DynamoDB PutItemRequest object
        // requires the Item to be in the Map<String, AttributeValue> structure
        Map<String, AttributeValue> userItem = getMapFromUser(user);

        // Create a request to save and return the user
        PutItemRequest putItemRequest = new PutItemRequest()
                .withTableName(config.getProperty(ConfigurationSettings.ConfigProps.DDB_USERS_TABLE))
                .withItem(userItem);

        // Save user
        dynamoClient.putItem(putItemRequest);
    } catch (ResourceNotFoundException rnfe) {
        throw new DataSourceTableDoesNotExistException(
                config.getProperty(ConfigurationSettings.ConfigProps.DDB_USERS_TABLE));
    } catch (AmazonServiceException ase) {
        throw ase;
    }
}

From source file:com.amediamanager.dao.DynamoDbUserDaoImpl.java

License:Apache License

@Override
public void update(User user) throws DataSourceTableDoesNotExistException {
    try {/*  w  ww.j a  va  2s  . co  m*/
        // If the object includes a profile pic file, upload it to S3
        if (user.getprofilePicData() != null && user.getprofilePicData().getSize() > 0) {
            try {
                String profilePicUrl = this.uploadFileToS3(user.getprofilePicData());
                user.setProfilePicKey(profilePicUrl);
            } catch (IOException e) {
                LOG.error("Error uploading profile pic to S3", e);
            }
        }

        // Convert the User object to a Map
        Map<String, AttributeValue> userItem = getMapFromUser(user);

        // Create a request to save and return the user
        PutItemRequest putItemRequest = new PutItemRequest().withItem(userItem)
                .withTableName(config.getProperty(ConfigurationSettings.ConfigProps.DDB_USERS_TABLE));

        // Save user
        dynamoClient.putItem(putItemRequest);
    } catch (ResourceNotFoundException rnfe) {
        throw new DataSourceTableDoesNotExistException(
                config.getProperty(ConfigurationSettings.ConfigProps.DDB_USERS_TABLE));
    } catch (AmazonServiceException ase) {
        throw ase;
    }

}

From source file:com.clicktravel.infrastructure.persistence.aws.dynamodb.AbstractDynamoDbTemplate.java

License:Apache License

protected final <T extends Item> Collection<PropertyDescriptor> createUniqueConstraintIndexes(final T item,
        final ItemConfiguration itemConfiguration,
        final Collection<PropertyDescriptor> constraintPropertyDescriptors) {
    final Set<PropertyDescriptor> createdConstraintPropertyDescriptors = new HashSet<>();
    ItemConstraintViolationException itemConstraintViolationException = null;
    for (final UniqueConstraint uniqueConstraint : itemConfiguration.uniqueConstraints()) {
        final String uniqueConstraintPropertyName = uniqueConstraint.propertyName();
        final PropertyDescriptor uniqueConstraintPropertyDescriptor = uniqueConstraint.propertyDescriptor();
        if (constraintPropertyDescriptors.contains(uniqueConstraintPropertyDescriptor)) {
            final AttributeValue uniqueConstraintAttributeValue = DynamoDbPropertyMarshaller.getValue(item,
                    uniqueConstraintPropertyDescriptor);
            if (uniqueConstraintAttributeValue == null) {
                continue;
            }//w ww  .  jav  a 2 s.  com
            if (uniqueConstraintAttributeValue.getS() != null) {
                uniqueConstraintAttributeValue.setS(uniqueConstraintAttributeValue.getS().toUpperCase());
            }
            final Map<String, AttributeValue> attributeMap = new HashMap<>();
            attributeMap.put("property", new AttributeValue(uniqueConstraintPropertyName));
            attributeMap.put("value", uniqueConstraintAttributeValue);
            final Map<String, ExpectedAttributeValue> expectedResults = new HashMap<>();
            expectedResults.put("value", new ExpectedAttributeValue(false));
            final String indexTableName = databaseSchemaHolder.schemaName() + "-indexes."
                    + itemConfiguration.tableName();
            final PutItemRequest itemRequest = new PutItemRequest().withTableName(indexTableName)
                    .withItem(attributeMap).withExpected(expectedResults);
            try {
                amazonDynamoDbClient.putItem(itemRequest);
                createdConstraintPropertyDescriptors.add(uniqueConstraintPropertyDescriptor);
            } catch (final ConditionalCheckFailedException e) {
                itemConstraintViolationException = new ItemConstraintViolationException(
                        uniqueConstraintPropertyName,
                        "Unique constraint violation on property '" + uniqueConstraintPropertyName + "' ('"
                                + uniqueConstraintAttributeValue + "') of item " + item.getClass());
                break;
            } catch (final AmazonServiceException e) {
                throw new PersistenceResourceFailureException(
                        "Failure while attempting DynamoDb put (creating unique constraint index entry)", e);
            }
        }
    }
    if (itemConstraintViolationException != null) {
        try {
            deleteUniqueConstraintIndexes(item, itemConfiguration, createdConstraintPropertyDescriptors);
        } catch (final Exception e) {
            logger.error(e.getMessage(), e);
        }
        throw itemConstraintViolationException;
    }
    return createdConstraintPropertyDescriptors;
}

From source file:com.clicktravel.infrastructure.persistence.aws.dynamodb.DynamoDbTemplate.java

License:Apache License

@Override
public <T extends Item> T create(final T item,
        final PersistenceExceptionHandler<?>... persistenceExceptionHandlers) {
    final ItemConfiguration itemConfiguration = getItemConfiguration(item.getClass());
    final Collection<PropertyDescriptor> createdConstraintPropertyDescriptors = createUniqueConstraintIndexes(
            item, itemConfiguration);/*from   w  ww  .ja  v a  2 s  . co  m*/
    final Map<String, ExpectedAttributeValue> expectedResults = new HashMap<>();
    expectedResults.put(itemConfiguration.primaryKeyDefinition().propertyName(),
            new ExpectedAttributeValue(false));
    final Map<String, AttributeValue> attributeMap = getAttributeMap(item, itemConfiguration, 1l);
    final String tableName = databaseSchemaHolder.schemaName() + "." + itemConfiguration.tableName();
    final PutItemRequest itemRequest = new PutItemRequest().withTableName(tableName).withItem(attributeMap)
            .withExpected(expectedResults);
    boolean itemRequestSucceeded = false;
    try {
        amazonDynamoDbClient.putItem(itemRequest);
        itemRequestSucceeded = true;
    } catch (final ConditionalCheckFailedException conditionalCheckFailedException) {
        throw new ItemConstraintViolationException(itemConfiguration.primaryKeyDefinition().propertyName(),
                "Failure to create item as store already contains item with matching primary key");
    } catch (final AmazonServiceException amazonServiceException) {
        throw new PersistenceResourceFailureException("Failure while attempting DynamoDb put (create)",
                amazonServiceException);
    } finally {
        if (!itemRequestSucceeded) {
            try {
                deleteUniqueConstraintIndexes(item, itemConfiguration, createdConstraintPropertyDescriptors);
            } catch (final Exception deleteUniqueConstraintIndexesException) {
                logger.error(deleteUniqueConstraintIndexesException.getMessage(),
                        deleteUniqueConstraintIndexesException);
            }
        }
    }
    item.setVersion(1l);
    return item;
}

From source file:com.clicktravel.infrastructure.persistence.aws.dynamodb.integration.DynamoDbDataGenerator.java

License:Apache License

StubVariantItem createStubVariantItem() {
    final StubVariantItem stubItem = new StubVariantItem();
    stubItem.setId(randomId());//from   w w  w  . j ava2  s .co  m
    stubItem.setStringProperty(randomString(10));
    stubItem.setStringProperty2(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.getStringProperty2() != null) {
        itemMap.put("stringProperty2", new AttributeValue(stubItem.getStringProperty2()));
    }
    itemMap.put("version", new AttributeValue().withN(String.valueOf(stubItem.getVersion())));
    itemMap.put("discriminator", new AttributeValue().withS("a"));
    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;
}