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

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

Introduction

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

Prototype

public ExpectedAttributeValue(Boolean exists) 

Source Link

Document

Constructs a new ExpectedAttributeValue object.

Usage

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);//from ww w  .  ja v  a 2s.  co m

}

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.  j a va 2s  . 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  w w  .  ja va 2 s  .c o  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.DynamoDbTemplate.java

License:Apache License

@Override
public <T extends Item> T update(final T item,
        final PersistenceExceptionHandler<?>... persistenceExceptionHandlers) {
    final ItemConfiguration itemConfiguration = getItemConfiguration(item.getClass());
    if (item.getVersion() == null) {
        return create(item);
    }//  w w w  . j  a  v a  2s. com
    final Collection<PropertyDescriptor> updatedUniqueConstraintPropertyDescriptors = new HashSet<>();
    T previousItem = null;
    if (!itemConfiguration.uniqueConstraints().isEmpty()) {
        final ItemId itemId = itemConfiguration.getItemId(item);
        previousItem = readWithOnlyUniqueConstraintProperties(itemId, itemConfiguration);
        final Collection<UniqueConstraint> updatedUniqueConstraints = getUpdatedUniqueConstraints(item,
                previousItem, itemConfiguration);
        for (final UniqueConstraint uniqueConstraint : updatedUniqueConstraints) {
            updatedUniqueConstraintPropertyDescriptors.add(uniqueConstraint.propertyDescriptor());
        }
        createUniqueConstraintIndexes(item, itemConfiguration, updatedUniqueConstraintPropertyDescriptors);
    }
    final long newVersion = item.getVersion() + 1;
    final Map<String, AttributeValueUpdate> attributeMap = getAttributeUpdateMap(item, itemConfiguration,
            newVersion);
    final Map<String, ExpectedAttributeValue> expectedResults = new HashMap<>();
    expectedResults.put(VERSION_ATTRIBUTE,
            new ExpectedAttributeValue(new AttributeValue().withN(String.valueOf(item.getVersion()))));
    final String tableName = databaseSchemaHolder.schemaName() + "." + itemConfiguration.tableName();
    final Map<String, AttributeValue> key = generateKey(itemConfiguration.getItemId(item), itemConfiguration);
    for (final Entry<String, AttributeValue> entry : key.entrySet()) {
        attributeMap.remove(entry.getKey());
    }
    final UpdateItemRequest itemRequest = new UpdateItemRequest().withTableName(tableName).withKey(key)
            .withAttributeUpdates(attributeMap).withExpected(expectedResults);
    boolean itemRequestSucceeded = false;
    try {
        amazonDynamoDbClient.updateItem(itemRequest);
        itemRequestSucceeded = true;
    } catch (final ConditionalCheckFailedException conditionalCheckFailedException) {
        throw new OptimisticLockException("Conflicting write detected while updating item");
    } catch (final AmazonServiceException amazonServiceException) {
        throw new PersistenceResourceFailureException("Failure while attempting DynamoDb Put (update item)",
                amazonServiceException);
    } finally {
        if (!itemRequestSucceeded) {
            try {
                deleteUniqueConstraintIndexes(item, itemConfiguration,
                        updatedUniqueConstraintPropertyDescriptors);
            } catch (final Exception deleteUniqueConstraintIndexesException) {
                logger.error(deleteUniqueConstraintIndexesException.getMessage(),
                        deleteUniqueConstraintIndexesException);
            }
        }
    }
    deleteUniqueConstraintIndexes(previousItem, itemConfiguration, updatedUniqueConstraintPropertyDescriptors);
    item.setVersion(newVersion);
    return item;
}

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

License:Apache License

@Override
public void delete(final Item item, final PersistenceExceptionHandler<?>... persistenceExceptionHandlers) {
    final ItemConfiguration itemConfiguration = getItemConfiguration(item.getClass());
    final ItemId itemId = itemConfiguration.getItemId(item);
    final Map<String, AttributeValue> key = new HashMap<>();
    final PrimaryKeyDefinition primaryKeyDefinition = itemConfiguration.primaryKeyDefinition();
    key.put(primaryKeyDefinition.propertyName(), new AttributeValue(itemId.value()));
    if (CompoundPrimaryKeyDefinition.class.isAssignableFrom(primaryKeyDefinition.getClass())) {
        final CompoundPrimaryKeyDefinition compoundPrimaryKeyDefinition = (CompoundPrimaryKeyDefinition) primaryKeyDefinition;
        key.put(compoundPrimaryKeyDefinition.supportingPropertyName(),
                new AttributeValue(itemId.supportingValue()));
    }/*ww w. j av a 2s . c o m*/
    final Map<String, ExpectedAttributeValue> expectedResults = new HashMap<>();
    expectedResults.put(VERSION_ATTRIBUTE,
            new ExpectedAttributeValue(new AttributeValue().withN(String.valueOf(item.getVersion()))));
    final String tableName = databaseSchemaHolder.schemaName() + "." + itemConfiguration.tableName();
    final DeleteItemRequest deleteItemRequest = new DeleteItemRequest().withTableName(tableName).withKey(key)
            .withExpected(expectedResults);
    try {
        amazonDynamoDbClient.deleteItem(deleteItemRequest);
    } catch (final AmazonServiceException e) {
        throw new PersistenceResourceFailureException("Failure while attempting DynamoDb Delete", e);
    }

    deleteUniqueConstraintIndexes(item, itemConfiguration);
}

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;
            }//from w ww .  jav a  2s . co 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);
    }
}