Search in sources :

Example 6 with Expected

use of com.amazonaws.services.dynamodbv2.document.Expected in project thunder by RohanNagar.

the class UsersDao method insert.

/**
 * Insert a new PilotUser into the data store.
 *
 * @param user The object to insert.
 * @return The PilotUser object that was created.
 * @throws DatabaseException If the user already exists or if the database is down.
 */
public PilotUser insert(PilotUser user) {
    checkNotNull(user);
    long now = Instant.now().toEpochMilli();
    Item item = new Item().withPrimaryKey("email", user.getEmail().getAddress()).withString("id", UUID.randomUUID().toString()).withString("version", UUID.randomUUID().toString()).withLong("creation_time", now).withLong("update_time", now).withJSON("document", toJson(mapper, user));
    try {
        table.putItem(item, new Expected("email").notExist());
    } catch (ConditionalCheckFailedException e) {
        LOG.error("The user {} already exists in the database. Throwing DatabaseException.", user.getEmail());
        throw new DatabaseException("The user already exists.", DatabaseError.CONFLICT);
    } catch (AmazonServiceException e) {
        LOG.error("The database rejected the create request.", e);
        throw new DatabaseException("The database rejected the create request.", DatabaseError.REQUEST_REJECTED);
    } catch (AmazonClientException e) {
        LOG.error("The database is currently unresponsive.", e);
        throw new DatabaseException("The database is currently unavailable.", DatabaseError.DATABASE_DOWN);
    }
    return user;
}
Also used : Item(com.amazonaws.services.dynamodbv2.document.Item) Expected(com.amazonaws.services.dynamodbv2.document.Expected) AmazonClientException(com.amazonaws.AmazonClientException) AmazonServiceException(com.amazonaws.AmazonServiceException) ConditionalCheckFailedException(com.amazonaws.services.dynamodbv2.model.ConditionalCheckFailedException)

Example 7 with Expected

use of com.amazonaws.services.dynamodbv2.document.Expected in project camel by apache.

the class UpdateItemCommandTest method execute.

@Test
public void execute() {
    Map<String, AttributeValue> key = new HashMap<String, AttributeValue>();
    key.put("1", new AttributeValue("Key_1"));
    exchange.getIn().setHeader(DdbConstants.KEY, key);
    Map<String, AttributeValueUpdate> attributeMap = new HashMap<String, AttributeValueUpdate>();
    AttributeValueUpdate attributeValue = new AttributeValueUpdate(new AttributeValue("new value"), AttributeAction.ADD);
    attributeMap.put("name", attributeValue);
    exchange.getIn().setHeader(DdbConstants.UPDATE_VALUES, attributeMap);
    Map<String, ExpectedAttributeValue> expectedAttributeValueMap = new HashMap<String, ExpectedAttributeValue>();
    expectedAttributeValueMap.put("name", new ExpectedAttributeValue(new AttributeValue("expected value")));
    exchange.getIn().setHeader(DdbConstants.UPDATE_CONDITION, expectedAttributeValueMap);
    exchange.getIn().setHeader(DdbConstants.RETURN_VALUES, "ALL_OLD");
    command.execute();
    assertEquals("DOMAIN1", ddbClient.updateItemRequest.getTableName());
    assertEquals(attributeMap, ddbClient.updateItemRequest.getAttributeUpdates());
    assertEquals(key, ddbClient.updateItemRequest.getKey());
    assertEquals(expectedAttributeValueMap, ddbClient.updateItemRequest.getExpected());
    assertEquals("ALL_OLD", ddbClient.updateItemRequest.getReturnValues());
    assertEquals(new AttributeValue("attrValue"), exchange.getIn().getHeader(DdbConstants.ATTRIBUTES, Map.class).get("attrName"));
}
Also used : AttributeValue(com.amazonaws.services.dynamodbv2.model.AttributeValue) ExpectedAttributeValue(com.amazonaws.services.dynamodbv2.model.ExpectedAttributeValue) AttributeValueUpdate(com.amazonaws.services.dynamodbv2.model.AttributeValueUpdate) HashMap(java.util.HashMap) ExpectedAttributeValue(com.amazonaws.services.dynamodbv2.model.ExpectedAttributeValue) Test(org.junit.Test)

Example 8 with Expected

use of com.amazonaws.services.dynamodbv2.document.Expected in project jcabi-dynamo by jcabi.

the class AwsItem method put.

@Override
public Map<String, AttributeValue> put(final Map<String, AttributeValueUpdate> attrs) throws IOException {
    final AmazonDynamoDB aws = this.credentials.aws();
    final Attributes expected = this.attributes.only(this.keys);
    try {
        final UpdateItemRequest request = new UpdateItemRequest().withTableName(this.name).withExpected(expected.asKeys()).withKey(expected).withAttributeUpdates(attrs).withReturnConsumedCapacity(ReturnConsumedCapacity.TOTAL).withReturnValues(ReturnValue.UPDATED_NEW);
        final long start = System.currentTimeMillis();
        final UpdateItemResult result = aws.updateItem(request);
        Logger.info(this, "#put('%s'): updated item to DynamoDB, %s, in %[ms]s", attrs, new PrintableConsumedCapacity(result.getConsumedCapacity()).print(), System.currentTimeMillis() - start);
        return result.getAttributes();
    } catch (final AmazonClientException ex) {
        throw new IOException(String.format("Failed to put %s into \"%s\" with %s", attrs, this.name, this.keys), ex);
    } finally {
        aws.shutdown();
    }
}
Also used : UpdateItemRequest(com.amazonaws.services.dynamodbv2.model.UpdateItemRequest) AmazonClientException(com.amazonaws.AmazonClientException) UpdateItemResult(com.amazonaws.services.dynamodbv2.model.UpdateItemResult) AmazonDynamoDB(com.amazonaws.services.dynamodbv2.AmazonDynamoDB) IOException(java.io.IOException)

Example 9 with Expected

use of com.amazonaws.services.dynamodbv2.document.Expected in project thunder by RohanNagar.

the class UsersDao method delete.

/**
 * Delete a PilotUser in the data store.
 *
 * @param email The email of the user to delete.
 * @return The PilotUser object that was deleted or {@code null} if the delete failed.
 * @throws DatabaseException If the user is not found or if the database is down.
 */
public PilotUser delete(String email) {
    checkNotNull(email);
    // Get the item that will be deleted to return it
    Item item;
    try {
        item = table.getItem("email", email);
    } catch (AmazonClientException e) {
        LOG.error("The database is currently unresponsive.", e);
        throw new DatabaseException("The database is currently unavailable.", DatabaseError.DATABASE_DOWN);
    }
    DeleteItemSpec deleteItemSpec = new DeleteItemSpec().withPrimaryKey("email", email).withExpected(new Expected("email").exists());
    try {
        table.deleteItem(deleteItemSpec);
    } catch (ConditionalCheckFailedException e) {
        LOG.warn("The email {} was not found in the database.", email, e);
        throw new DatabaseException("The user to delete was not found.", DatabaseError.USER_NOT_FOUND);
    } catch (AmazonClientException e) {
        LOG.error("The database is currently unresponsive.", e);
        throw new DatabaseException("The database is currently unavailable.", DatabaseError.DATABASE_DOWN);
    }
    return fromJson(mapper, item.getJSON("document"));
}
Also used : Item(com.amazonaws.services.dynamodbv2.document.Item) DeleteItemSpec(com.amazonaws.services.dynamodbv2.document.spec.DeleteItemSpec) Expected(com.amazonaws.services.dynamodbv2.document.Expected) AmazonClientException(com.amazonaws.AmazonClientException) ConditionalCheckFailedException(com.amazonaws.services.dynamodbv2.model.ConditionalCheckFailedException)

Example 10 with Expected

use of com.amazonaws.services.dynamodbv2.document.Expected in project thunder by RohanNagar.

the class UsersDao method update.

/**
 * Update a PilotUser in the data store.
 *
 * @param existingEmail The existing email of the user.
 *                     This must not be {@code null} if the email is to be changed.
 * @param user The user object to update. Must have the same email as the one to update.
 * @return The PilotUser object that was updated or {@code null} if the updated failed.
 * @throws DatabaseException If the user is not found, the database is down, or the update fails.
 */
public PilotUser update(@Nullable String existingEmail, PilotUser user) {
    checkNotNull(user);
    // Different emails means we need to delete and insert
    if (existingEmail != null && !existingEmail.equals(user.getEmail().getAddress())) {
        LOG.info("User to update has new email. The user will be deleted and then reinserted.");
        delete(existingEmail);
        return insert(user);
    }
    // Compute the new data
    long now = Instant.now().toEpochMilli();
    String newVersion = UUID.randomUUID().toString();
    String document = toJson(mapper, user);
    // Get the old version
    Item item;
    try {
        item = table.getItem("email", user.getEmail().getAddress());
    } catch (AmazonClientException e) {
        LOG.error("The database is currently unresponsive.", e);
        throw new DatabaseException("The database is currently unavailable.", DatabaseError.DATABASE_DOWN);
    }
    if (item == null) {
        LOG.warn("The user {} was not found in the database.", user.getEmail().getAddress());
        throw new DatabaseException("The user was not found.", DatabaseError.USER_NOT_FOUND);
    }
    String oldVersion = item.getString("version");
    Item newItem = item.withString("version", newVersion).withLong("update_time", now).withJSON("document", document);
    try {
        table.putItem(newItem, new Expected("version").eq(oldVersion));
    } catch (ConditionalCheckFailedException e) {
        LOG.error("The user was updated while this update was in progress." + " Aborting to avoid race condition.", e);
        throw new DatabaseException("The user to update is at an unexpected stage.", DatabaseError.CONFLICT);
    } catch (AmazonServiceException e) {
        LOG.error("The database rejected the update request.", e);
        throw new DatabaseException("The database rejected the update request.", DatabaseError.REQUEST_REJECTED);
    } catch (AmazonClientException e) {
        LOG.error("The database is currently unresponsive.", e);
        throw new DatabaseException("The database is currently unavailable.", DatabaseError.DATABASE_DOWN);
    }
    return user;
}
Also used : Item(com.amazonaws.services.dynamodbv2.document.Item) Expected(com.amazonaws.services.dynamodbv2.document.Expected) AmazonClientException(com.amazonaws.AmazonClientException) AmazonServiceException(com.amazonaws.AmazonServiceException) ConditionalCheckFailedException(com.amazonaws.services.dynamodbv2.model.ConditionalCheckFailedException)

Aggregations

Expected (com.amazonaws.services.dynamodbv2.document.Expected)5 ConditionalCheckFailedException (com.amazonaws.services.dynamodbv2.model.ConditionalCheckFailedException)5 AmazonClientException (com.amazonaws.AmazonClientException)4 AttributeValue (com.amazonaws.services.dynamodbv2.model.AttributeValue)4 Test (org.junit.Test)4 Item (com.amazonaws.services.dynamodbv2.document.Item)3 ExpectedAttributeValue (com.amazonaws.services.dynamodbv2.model.ExpectedAttributeValue)3 HashMap (java.util.HashMap)3 AmazonServiceException (com.amazonaws.AmazonServiceException)2 AttributeUpdate (com.amazonaws.services.dynamodbv2.document.AttributeUpdate)2 UpdateItemSpec (com.amazonaws.services.dynamodbv2.document.spec.UpdateItemSpec)2 DescribeAutoScalingGroupsRequest (com.amazonaws.services.autoscaling.model.DescribeAutoScalingGroupsRequest)1 DescribeAutoScalingGroupsResult (com.amazonaws.services.autoscaling.model.DescribeAutoScalingGroupsResult)1 ListMetricsRequest (com.amazonaws.services.cloudwatch.model.ListMetricsRequest)1 ListMetricsResult (com.amazonaws.services.cloudwatch.model.ListMetricsResult)1 PutMetricDataRequest (com.amazonaws.services.cloudwatch.model.PutMetricDataRequest)1 PutMetricDataResult (com.amazonaws.services.cloudwatch.model.PutMetricDataResult)1 AmazonDynamoDB (com.amazonaws.services.dynamodbv2.AmazonDynamoDB)1 DeleteItemSpec (com.amazonaws.services.dynamodbv2.document.spec.DeleteItemSpec)1 AttributeValueUpdate (com.amazonaws.services.dynamodbv2.model.AttributeValueUpdate)1