software.amazon.awssdk.services.dynamodb.model.ReturnValue Java Examples

The following examples show how to use software.amazon.awssdk.services.dynamodb.model.ReturnValue. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DynamoDBTest.java    From dynein with Apache License 2.0 6 votes vote down vote up
private UpdateItemRequest getUpdateItemReq(
    Schedule schedule, Schedule.JobStatus oldStatus, Schedule.JobStatus newStatus) {
  Map<String, AttributeValue> primaryKey = DynamoDBUtils.getPrimaryKey(schedule);
  Map<String, String> attributeNames = new HashMap<>();
  Map<String, AttributeValue> attributeValues = new HashMap<>();
  attributeNames.put("#jobStatus", DynamoDBUtils.Attribute.JOB_STATUS.columnName);
  attributeValues.put(":oldStatus", AttributeValue.builder().s(oldStatus.name()).build());
  attributeValues.put(":newStatus", AttributeValue.builder().s(newStatus.name()).build());

  String updated = "SET #jobStatus = :newStatus";

  return UpdateItemRequest.builder()
      .tableName(this.tableName)
      .key(primaryKey)
      .conditionExpression("#jobStatus = :oldStatus")
      .expressionAttributeNames(attributeNames)
      .expressionAttributeValues(attributeValues)
      .updateExpression(updated)
      .returnValues(ReturnValue.UPDATED_NEW)
      .build();
}
 
Example #2
Source File: DynamoDBLockProvider.java    From ShedLock with Apache License 2.0 6 votes vote down vote up
@Override
public void doUnlock() {
    // Set lockUntil to now or lockAtLeastUntil whichever is later
    String unlockTimeIso = toIsoString(lockConfiguration.getUnlockTime());

    Map<String, AttributeValue> key = singletonMap(ID, attr(lockConfiguration.getName()));

    Map<String, AttributeValue> attributeUpdates = singletonMap(":lockUntil", attr(unlockTimeIso));

    UpdateItemRequest request = UpdateItemRequest.builder()
            .tableName(tableName)
            .key(key)
            .updateExpression(RELEASE_LOCK_QUERY)
            .expressionAttributeValues(attributeUpdates)
            .returnValues(ReturnValue.UPDATED_NEW)
            .build();

    dynamoDbClient.updateItem(request);
}
 
Example #3
Source File: DeleteItemOperationTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void generateRequest_partitionAndSortKey() {
    FakeItemWithSort keyItem = createUniqueFakeItemWithSort();
    DeleteItemOperation<FakeItemWithSort> deleteItemOperation = DeleteItemOperation.create(
        DeleteItemEnhancedRequest.builder()
                                 .key(k -> k.partitionValue(keyItem.getId()).sortValue(keyItem.getSort()))
                                 .build());

    DeleteItemRequest request = deleteItemOperation.generateRequest(FakeItemWithSort.getTableSchema(),
                                                                   PRIMARY_CONTEXT,
                                                                    null);

    Map<String, AttributeValue> expectedKeyMap = new HashMap<>();
    expectedKeyMap.put("id", AttributeValue.builder().s(keyItem.getId()).build());
    expectedKeyMap.put("sort", AttributeValue.builder().s(keyItem.getSort()).build());
    DeleteItemRequest expectedRequest = DeleteItemRequest.builder()
                                                   .tableName(TABLE_NAME)
                                                   .key(expectedKeyMap)
                                                   .returnValues(ReturnValue.ALL_OLD)
                                                   .build();
    assertThat(request, is(expectedRequest));
}
 
Example #4
Source File: DeleteItemOperationTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void generateRequest_partitionKeyOnly() {
    FakeItem keyItem = createUniqueFakeItem();
    DeleteItemOperation<FakeItem> deleteItemOperation =
        DeleteItemOperation.create(DeleteItemEnhancedRequest.builder().key(k -> k.partitionValue(keyItem.getId())).build());

    DeleteItemRequest request = deleteItemOperation.generateRequest(FakeItem.getTableSchema(),
                                                                    PRIMARY_CONTEXT,
                                                                    null);

    Map<String, AttributeValue> expectedKeyMap = new HashMap<>();
    expectedKeyMap.put("id", AttributeValue.builder().s(keyItem.getId()).build());
    DeleteItemRequest expectedRequest = DeleteItemRequest.builder()
        .tableName(TABLE_NAME)
        .key(expectedKeyMap)
        .returnValues(ReturnValue.ALL_OLD)
        .build();
    assertThat(request, is(expectedRequest));
}
 
Example #5
Source File: UpdateItemOperationTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void generateRequest_keyOnlyItem() {
    FakeItemWithSort item = createUniqueFakeItemWithSort();
    UpdateItemOperation<FakeItemWithSort> updateItemOperation =
        UpdateItemOperation.create(UpdateItemEnhancedRequest.builder(FakeItemWithSort.class)
                                                            .item(item)
                                                            .ignoreNulls(true)
                                                            .build());
    Map<String, AttributeValue> expectedKey = new HashMap<>();
    expectedKey.put("id", AttributeValue.builder().s(item.getId()).build());
    expectedKey.put("sort", AttributeValue.builder().s(item.getSort()).build());
    UpdateItemRequest expectedRequest = UpdateItemRequest.builder()
                                                         .tableName(TABLE_NAME)
                                                         .key(expectedKey)
                                                         .returnValues(ReturnValue.ALL_NEW)
                                                         .build();


    UpdateItemRequest request = updateItemOperation.generateRequest(FakeItemWithSort.getTableSchema(),
                                                                    PRIMARY_CONTEXT,
                                                                    null);

    assertThat(request, is(expectedRequest));
}
 
Example #6
Source File: DeleteItemOperation.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Override
public DeleteItemRequest generateRequest(TableSchema<T> tableSchema,
                                         OperationContext operationContext,
                                         DynamoDbEnhancedClientExtension extension) {

    if (!TableMetadata.primaryIndexName().equals(operationContext.indexName())) {
        throw new IllegalArgumentException("DeleteItem cannot be executed against a secondary index.");
    }

    DeleteItemRequest.Builder requestBuilder =
        DeleteItemRequest.builder()
                         .tableName(operationContext.tableName())
                         .key(this.request.key().keyMap(tableSchema, operationContext.indexName()))
                         .returnValues(ReturnValue.ALL_OLD);

    requestBuilder = addExpressionsIfExist(requestBuilder);

    return requestBuilder.build();
}
 
Example #7
Source File: UpdateItemOperationTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void generateRequest_nullValuesNotIgnoredByDefault() {
    FakeItemWithSort item = createUniqueFakeItemWithSort();
    item.setOtherAttribute1("value-1");
    UpdateItemOperation<FakeItemWithSort> updateItemOperation = UpdateItemOperation.create(
        UpdateItemEnhancedRequest.builder(FakeItemWithSort.class).item(item).build());
    Map<String, AttributeValue> expectedKey = new HashMap<>();
    expectedKey.put("id", AttributeValue.builder().s(item.getId()).build());
    expectedKey.put("sort", AttributeValue.builder().s(item.getSort()).build());
    Map<String, AttributeValue> expectedValues = new HashMap<>();
    expectedValues.put(OTHER_ATTRIBUTE_1_VALUE, AttributeValue.builder().s("value-1").build());
    Map<String, String> expectedNames = new HashMap<>();
    expectedNames.put(OTHER_ATTRIBUTE_1_NAME, "other_attribute_1");
    expectedNames.put(OTHER_ATTRIBUTE_2_NAME, "other_attribute_2");
    UpdateItemRequest.Builder baseExpectedRequest = UpdateItemRequest.builder()
                                                                     .tableName(TABLE_NAME)
                                                                     .expressionAttributeValues(expectedValues)
                                                                     .expressionAttributeNames(expectedNames)
                                                                     .key(expectedKey)
                                                                     .returnValues(ReturnValue.ALL_NEW);
    UpdateItemRequest expectedRequest =
        baseExpectedRequest.updateExpression("SET " + OTHER_ATTRIBUTE_1_NAME + " = " + OTHER_ATTRIBUTE_1_VALUE +
                                             " REMOVE " + OTHER_ATTRIBUTE_2_NAME)
                           .build();

    UpdateItemRequest request = updateItemOperation.generateRequest(FakeItemWithSort.getTableSchema(),
                                                                    PRIMARY_CONTEXT,
                                                                    null);

    assertThat(request, is(expectedRequest));
}
 
Example #8
Source File: UpdateItemOperationTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void generateRequest_withConditionExpression() {
    FakeItemWithSort item = createUniqueFakeItemWithSort();
    item.setOtherAttribute1("value-1");
    UpdateItemOperation<FakeItemWithSort> updateItemOperation =
        UpdateItemOperation.create(UpdateItemEnhancedRequest.builder(FakeItemWithSort.class)
                                                            .item(item)
                                                            .conditionExpression(CONDITION_EXPRESSION)
                                                            .build());
    Map<String, AttributeValue> expectedKey = new HashMap<>();
    expectedKey.put("id", AttributeValue.builder().s(item.getId()).build());
    expectedKey.put("sort", AttributeValue.builder().s(item.getSort()).build());
    Map<String, AttributeValue> expectedValues = new HashMap<>(CONDITION_EXPRESSION.expressionValues());
    expectedValues.put(OTHER_ATTRIBUTE_1_VALUE, AttributeValue.builder().s("value-1").build());
    Map<String, String> expectedNames = new HashMap<>(CONDITION_EXPRESSION.expressionNames());
    expectedNames.put(OTHER_ATTRIBUTE_1_NAME, "other_attribute_1");
    expectedNames.put(OTHER_ATTRIBUTE_2_NAME, "other_attribute_2");
    UpdateItemRequest.Builder baseExpectedRequest =
        UpdateItemRequest.builder()
                         .tableName(TABLE_NAME)
                         .expressionAttributeValues(expectedValues)
                         .expressionAttributeNames(expectedNames)
                         .conditionExpression(CONDITION_EXPRESSION.expression())
                         .key(expectedKey)
                         .returnValues(ReturnValue.ALL_NEW);
    UpdateItemRequest expectedRequest =
        baseExpectedRequest.updateExpression("SET " + OTHER_ATTRIBUTE_1_NAME + " = " + OTHER_ATTRIBUTE_1_VALUE +
                                             " REMOVE " + OTHER_ATTRIBUTE_2_NAME)
                           .build();

    UpdateItemRequest request = updateItemOperation.generateRequest(FakeItemWithSort.getTableSchema(),
                                                                    PRIMARY_CONTEXT,
                                                                    null);

    assertThat(request, is(expectedRequest));
}
 
Example #9
Source File: UpdateItemOperationTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void generateRequest_explicitlyUnsetIgnoreNulls() {
    FakeItemWithSort item = createUniqueFakeItemWithSort();
    item.setOtherAttribute1("value-1");
    UpdateItemOperation<FakeItemWithSort> updateItemOperation =
        UpdateItemOperation.create(UpdateItemEnhancedRequest.builder(FakeItemWithSort.class)
                                                            .item(item)
                                                            .ignoreNulls(false)
                                                            .build());
    Map<String, AttributeValue> expectedKey = new HashMap<>();
    expectedKey.put("id", AttributeValue.builder().s(item.getId()).build());
    expectedKey.put("sort", AttributeValue.builder().s(item.getSort()).build());
    Map<String, AttributeValue> expectedValues = new HashMap<>();
    expectedValues.put(OTHER_ATTRIBUTE_1_VALUE, AttributeValue.builder().s("value-1").build());
    Map<String, String> expectedNames = new HashMap<>();
    expectedNames.put(OTHER_ATTRIBUTE_1_NAME, "other_attribute_1");
    expectedNames.put(OTHER_ATTRIBUTE_2_NAME, "other_attribute_2");
    UpdateItemRequest.Builder baseExpectedRequest = UpdateItemRequest.builder()
                                                                     .tableName(TABLE_NAME)
                                                                     .expressionAttributeValues(expectedValues)
                                                                     .expressionAttributeNames(expectedNames)
                                                                     .key(expectedKey)
                                                                     .returnValues(ReturnValue.ALL_NEW);
    UpdateItemRequest expectedRequest =
        baseExpectedRequest.updateExpression("SET " + OTHER_ATTRIBUTE_1_NAME + " = " + OTHER_ATTRIBUTE_1_VALUE +
                                             " REMOVE " + OTHER_ATTRIBUTE_2_NAME)
                           .build();

    UpdateItemRequest request = updateItemOperation.generateRequest(FakeItemWithSort.getTableSchema(),
                                                                    PRIMARY_CONTEXT,
                                                                    null);

    assertThat(request, is(expectedRequest));
}
 
Example #10
Source File: UpdateItemOperationTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void generateRequest_multipleSetters() {
    FakeItemWithSort item = createUniqueFakeItemWithSort();
    item.setOtherAttribute1("value-1");
    item.setOtherAttribute2("value-2");
    UpdateItemOperation<FakeItemWithSort> updateItemOperation =
        UpdateItemOperation.create(UpdateItemEnhancedRequest.builder(FakeItemWithSort.class)
                                                            .item(item)
                                                            .ignoreNulls(false)
                                                            .build());
    Map<String, AttributeValue> expectedKey = new HashMap<>();
    expectedKey.put("id", AttributeValue.builder().s(item.getId()).build());
    expectedKey.put("sort", AttributeValue.builder().s(item.getSort()).build());
    Map<String, AttributeValue> expectedValues = new HashMap<>();
    expectedValues.put(OTHER_ATTRIBUTE_1_VALUE, AttributeValue.builder().s("value-1").build());
    expectedValues.put(OTHER_ATTRIBUTE_2_VALUE, AttributeValue.builder().s("value-2").build());
    Map<String, String> expectedNames = new HashMap<>();
    expectedNames.put(OTHER_ATTRIBUTE_1_NAME, "other_attribute_1");
    expectedNames.put(OTHER_ATTRIBUTE_2_NAME, "other_attribute_2");
    UpdateItemRequest.Builder baseExpectedRequest = UpdateItemRequest.builder()
                                                                     .tableName(TABLE_NAME)
                                                                     .expressionAttributeValues(expectedValues)
                                                                     .expressionAttributeNames(expectedNames)
                                                                     .key(expectedKey)
                                                                     .returnValues(ReturnValue.ALL_NEW);
    UpdateItemRequest expectedRequest1 =
        baseExpectedRequest.updateExpression("SET " + OTHER_ATTRIBUTE_1_NAME + " = " + OTHER_ATTRIBUTE_1_VALUE +
                                             ", " + OTHER_ATTRIBUTE_2_NAME + " = " + OTHER_ATTRIBUTE_2_VALUE)
                           .build();
    UpdateItemRequest expectedRequest2 =
        baseExpectedRequest.updateExpression("SET " + OTHER_ATTRIBUTE_2_NAME + " = " + OTHER_ATTRIBUTE_2_VALUE +
                                             ", " + OTHER_ATTRIBUTE_1_NAME + " = " + OTHER_ATTRIBUTE_1_VALUE)
                           .build();

    UpdateItemRequest request = updateItemOperation.generateRequest(FakeItemWithSort.getTableSchema(),
                                                                    PRIMARY_CONTEXT,
                                                                    null);

    assertThat(request, either(is(expectedRequest1)).or(is(expectedRequest2)));
}
 
Example #11
Source File: UpdateItemOperationTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void generateRequest_multipleDeletes() {
    FakeItemWithSort item = createUniqueFakeItemWithSort();
    UpdateItemOperation<FakeItemWithSort> updateItemOperation =
        UpdateItemOperation.create(UpdateItemEnhancedRequest.builder(FakeItemWithSort.class)
                                                            .item(item)
                                                            .ignoreNulls(false)
                                                            .build());
    Map<String, AttributeValue> expectedKey = new HashMap<>();
    expectedKey.put("id", AttributeValue.builder().s(item.getId()).build());
    expectedKey.put("sort", AttributeValue.builder().s(item.getSort()).build());
    Map<String, String> expectedNames = new HashMap<>();
    expectedNames.put(OTHER_ATTRIBUTE_1_NAME, "other_attribute_1");
    expectedNames.put(OTHER_ATTRIBUTE_2_NAME, "other_attribute_2");
    UpdateItemRequest.Builder baseExpectedRequest = UpdateItemRequest.builder()
                                                                     .tableName(TABLE_NAME)
                                                                     .expressionAttributeNames(expectedNames)
                                                                     .key(expectedKey)
                                                                     .returnValues(ReturnValue.ALL_NEW);
    UpdateItemRequest expectedRequest1 =
        baseExpectedRequest.updateExpression("REMOVE " + OTHER_ATTRIBUTE_1_NAME + ", " + OTHER_ATTRIBUTE_2_NAME)
                           .build();
    UpdateItemRequest expectedRequest2 =
        baseExpectedRequest.updateExpression("REMOVE " + OTHER_ATTRIBUTE_2_NAME + ", " + OTHER_ATTRIBUTE_1_NAME)
                           .build();

    UpdateItemRequest request = updateItemOperation.generateRequest(FakeItemWithSort.getTableSchema(),
                                                                    PRIMARY_CONTEXT,
                                                                    null);

    assertThat(request,either(is(expectedRequest1)).or(is(expectedRequest2)));
}
 
Example #12
Source File: UpdateItemOperationTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void generateRequest_canIgnoreNullValues() {
    FakeItemWithSort item = createUniqueFakeItemWithSort();
    item.setOtherAttribute1("value-1");
    UpdateItemOperation<FakeItemWithSort> updateItemOperation =
        UpdateItemOperation.create(UpdateItemEnhancedRequest.builder(FakeItemWithSort.class)
                                                            .item(item)
                                                            .ignoreNulls(true)
                                                            .build());
    Map<String, AttributeValue> expectedKey = new HashMap<>();
    expectedKey.put("id", AttributeValue.builder().s(item.getId()).build());
    expectedKey.put("sort", AttributeValue.builder().s(item.getSort()).build());
    Map<String, AttributeValue> expectedValues =
        singletonMap(OTHER_ATTRIBUTE_1_VALUE, AttributeValue.builder().s("value-1").build());
    Map<String, String> expectedNames = singletonMap(OTHER_ATTRIBUTE_1_NAME, "other_attribute_1");
    UpdateItemRequest expectedRequest = UpdateItemRequest.builder()
        .tableName(TABLE_NAME)
        .updateExpression("SET " + OTHER_ATTRIBUTE_1_NAME + " = " + OTHER_ATTRIBUTE_1_VALUE)
        .expressionAttributeValues(expectedValues)
        .expressionAttributeNames(expectedNames)
        .key(expectedKey)
        .returnValues(ReturnValue.ALL_NEW)
        .build();


    UpdateItemRequest request = updateItemOperation.generateRequest(FakeItemWithSort.getTableSchema(),
                                                                    PRIMARY_CONTEXT,
                                                                    null);

    assertThat(request, is(expectedRequest));
}
 
Example #13
Source File: DynamoDBLockProvider.java    From ShedLock with Apache License 2.0 5 votes vote down vote up
@Override
@NonNull
public Optional<SimpleLock> lock(@NonNull LockConfiguration lockConfiguration) {
    String nowIso = toIsoString(now());
    String lockUntilIso = toIsoString(lockConfiguration.getLockAtMostUntil());

    Map<String, AttributeValue> key = singletonMap(ID, attr(lockConfiguration.getName()));

    Map<String, AttributeValue> attributeUpdates = new HashMap<>(3);
    attributeUpdates.put(":lockUntil", attr(lockUntilIso));
    attributeUpdates.put(":lockedAt", attr(nowIso));
    attributeUpdates.put(":lockedBy", attr(hostname));

    UpdateItemRequest request = UpdateItemRequest.builder()
            .tableName(tableName)
            .key(key)
            .updateExpression(OBTAIN_LOCK_QUERY)
            .conditionExpression(OBTAIN_LOCK_CONDITION)
            .expressionAttributeValues(attributeUpdates)
            .returnValues(ReturnValue.UPDATED_NEW)
            .build();

    try {
        // There are three possible situations:
        // 1. The lock document does not exist yet - it is inserted - we have the lock
        // 2. The lock document exists and lockUtil <= now - it is updated - we have the lock
        // 3. The lock document exists and lockUtil > now - ConditionalCheckFailedException is thrown
        dynamoDbClient.updateItem(request);
        return Optional.of(new DynamoDBLock(dynamoDbClient, tableName, lockConfiguration));
    } catch (ConditionalCheckFailedException e) {
        // Condition failed. This means there was a lock with lockUntil > now.
        return Optional.empty();
    }
}
 
Example #14
Source File: EmptyStringTest.java    From aws-sdk-java-v2 with Apache License 2.0 4 votes vote down vote up
@Test
public void updateEmptyStringWithCondition() {
    Map<String, AttributeValue> expectedItemMap = new HashMap<>();
    expectedItemMap.put("id", AttributeValue.builder().s("id123").build());
    expectedItemMap.put("s", EMPTY_STRING);
    TestBean testBean = new TestBean();
    testBean.setId("id123");
    testBean.setS("");

    UpdateItemResponse response = UpdateItemResponse.builder()
                                                    .attributes(expectedItemMap)
                                                    .build();
    when(mockDynamoDbClient.updateItem(any(UpdateItemRequest.class))).thenReturn(response);

    Expression conditionExpression = Expression.builder()
                                                 .expression("#attr = :val")
                                                 .expressionNames(singletonMap("#attr", "s"))
                                                 .expressionValues(singletonMap(":val", EMPTY_STRING))
                                                 .build();

    TestBean result = dynamoDbTable.updateItem(r -> r.item(testBean).conditionExpression(conditionExpression));

    Map<String, String> expectedExpressionAttributeNames = new HashMap<>();
    expectedExpressionAttributeNames.put("#AMZN_MAPPED_s", "s");
    expectedExpressionAttributeNames.put("#attr", "s");
    Map<String, AttributeValue> expectedExpressionAttributeValues = new HashMap<>();
    expectedExpressionAttributeValues.put(":AMZN_MAPPED_s", EMPTY_STRING);
    expectedExpressionAttributeValues.put(":val", EMPTY_STRING);
    Map<String, AttributeValue> expectedKeyMap = new HashMap<>();
    expectedKeyMap.put("id", AttributeValue.builder().s("id123").build());

    UpdateItemRequest expectedRequest =
        UpdateItemRequest.builder()
                         .tableName(TABLE_NAME)
                         .key(expectedKeyMap)
                         .returnValues(ReturnValue.ALL_NEW)
                         .updateExpression("SET #AMZN_MAPPED_s = :AMZN_MAPPED_s")
                         .conditionExpression("#attr = :val")
                         .expressionAttributeNames(expectedExpressionAttributeNames)
                         .expressionAttributeValues(expectedExpressionAttributeValues)
                         .build();

    verify(mockDynamoDbClient).updateItem(expectedRequest);
    assertThat(result.getId()).isEqualTo("id123");
    assertThat(result.getS()).isEmpty();
}
 
Example #15
Source File: EmptyBinaryTest.java    From aws-sdk-java-v2 with Apache License 2.0 4 votes vote down vote up
@Test
public void updateEmptyBytesWithCondition() {
    Map<String, AttributeValue> expectedItemMap = new HashMap<>();
    expectedItemMap.put("id", AttributeValue.builder().s("id123").build());
    expectedItemMap.put("b", EMPTY_BINARY);
    TestBean testBean = new TestBean();
    testBean.setId("id123");
    testBean.setB(EMPTY_BYTES);

    UpdateItemResponse response = UpdateItemResponse.builder()
                                                    .attributes(expectedItemMap)
                                                    .build();
    when(mockDynamoDbClient.updateItem(any(UpdateItemRequest.class))).thenReturn(response);

    Expression conditionExpression = Expression.builder()
                                                 .expression("#attr = :val")
                                                 .expressionNames(singletonMap("#attr", "b"))
                                                 .expressionValues(singletonMap(":val", EMPTY_BINARY))
                                                 .build();

    TestBean result = dynamoDbTable.updateItem(r -> r.item(testBean).conditionExpression(conditionExpression));

    Map<String, String> expectedExpressionAttributeNames = new HashMap<>();
    expectedExpressionAttributeNames.put("#AMZN_MAPPED_b", "b");
    expectedExpressionAttributeNames.put("#attr", "b");
    Map<String, AttributeValue> expectedExpressionAttributeValues = new HashMap<>();
    expectedExpressionAttributeValues.put(":AMZN_MAPPED_b", EMPTY_BINARY);
    expectedExpressionAttributeValues.put(":val", EMPTY_BINARY);
    Map<String, AttributeValue> expectedKeyMap = new HashMap<>();
    expectedKeyMap.put("id", AttributeValue.builder().s("id123").build());

    UpdateItemRequest expectedRequest =
        UpdateItemRequest.builder()
                         .tableName(TABLE_NAME)
                         .key(expectedKeyMap)
                         .returnValues(ReturnValue.ALL_NEW)
                         .updateExpression("SET #AMZN_MAPPED_b = :AMZN_MAPPED_b")
                         .conditionExpression("#attr = :val")
                         .expressionAttributeNames(expectedExpressionAttributeNames)
                         .expressionAttributeValues(expectedExpressionAttributeValues)
                         .build();

    verify(mockDynamoDbClient).updateItem(expectedRequest);
    assertThat(result.getId()).isEqualTo("id123");
    assertThat(result.getB()).isEqualTo(EMPTY_BYTES);
}
 
Example #16
Source File: UpdateItemOperation.java    From aws-sdk-java-v2 with Apache License 2.0 4 votes vote down vote up
@Override
public UpdateItemRequest generateRequest(TableSchema<T> tableSchema,
                                         OperationContext operationContext,
                                         DynamoDbEnhancedClientExtension extension) {
    if (!TableMetadata.primaryIndexName().equals(operationContext.indexName())) {
        throw new IllegalArgumentException("UpdateItem cannot be executed against a secondary index.");
    }

    Map<String, AttributeValue> itemMap = tableSchema.itemToMap(this.request.item(),
                                                                Boolean.TRUE.equals(this.request.ignoreNulls()));
    TableMetadata tableMetadata = tableSchema.tableMetadata();

    WriteModification transformation =
        extension != null ? extension.beforeWrite(DefaultDynamoDbExtensionContext.builder()
                                                                                 .items(itemMap)
                                                                                 .operationContext(operationContext)
                                                                                 .tableMetadata(tableMetadata)
                                                                                 .build()) : null;

    if (transformation != null && transformation.transformedItem() != null) {
        itemMap = transformation.transformedItem();
    }

    Collection<String> primaryKeys = tableSchema.tableMetadata().primaryKeys();

    Map<String, AttributeValue> keyAttributeValues = itemMap.entrySet().stream()
        .filter(entry -> primaryKeys.contains(entry.getKey()))
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

    UpdateItemRequest.Builder requestBuilder = UpdateItemRequest.builder()
        .tableName(operationContext.tableName())
        .key(keyAttributeValues)
        .returnValues(ReturnValue.ALL_NEW);

    Map<String, AttributeValue> filteredAttributeValues = itemMap.entrySet().stream()
        .filter(entry -> !primaryKeys.contains(entry.getKey()))
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

    requestBuilder = addExpressionsIfExist(transformation, filteredAttributeValues, requestBuilder);

    return requestBuilder.build();
}
 
Example #17
Source File: DynamoDBScheduleManager.java    From dynein with Apache License 2.0 4 votes vote down vote up
@Override
public CompletableFuture<Schedule> updateStatus(
    Schedule schedule, JobStatus oldStatus, JobStatus newStatus) {
  Map<String, AttributeValue> primaryKey = DynamoDBUtils.getPrimaryKey(schedule);
  Map<String, AttributeValue> attributeValues =
      DynamoDBUtils.attributeValuesMap(
          ImmutableMap.of(
              Value.OLD_STATUS, oldStatus.toString(),
              Value.NEW_STATUS, newStatus.toString()));

  String updated = "SET " + Condition.of(Attribute.JOB_STATUS, "=", Value.NEW_STATUS);

  UpdateItemRequest updateItemRequest =
      UpdateItemRequest.builder()
          .tableName(ddbConfig.getSchedulesTableName())
          .key(primaryKey)
          .conditionExpression(
              Condition.of(Attribute.JOB_STATUS, "=", Value.OLD_STATUS).toString())
          .expressionAttributeNames(DynamoDBUtils.getJobStatusAttributeMap())
          .expressionAttributeValues(attributeValues)
          .updateExpression(updated)
          .returnValues(ReturnValue.UPDATED_NEW)
          .build();

  return ddbClient
      .updateItem(updateItemRequest)
      .whenComplete(
          (response, exception) -> {
            DyneinJobSpec jobSpec = jobSpecTransformer.deserializeJobSpec(schedule.getJobSpec());
            if (exception != null) {
              log.error(
                  "Failed to set job {} to {}",
                  jobSpec.getJobToken(),
                  newStatus.toString(),
                  exception);
              metrics.updateJobStatusError(exception, oldStatus.toString(), newStatus.toString());
            } else {
              log.info("Set job {} to {}", jobSpec.getJobToken(), newStatus.toString());
              metrics.updateJobStatus(oldStatus.toString(), newStatus.toString());
            }
          })
      .thenApply(
          response -> {
            JobStatus updatedStatus =
                Optional.ofNullable(response.attributes().get(Attribute.JOB_STATUS.columnName))
                    .map(attr -> JobStatus.valueOf(attr.s()))
                    .orElseThrow(
                        () ->
                            new IllegalStateException(
                                "Status update successful but status isn't returned."));
            return schedule.withStatus(updatedStatus);
          });
}