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

The following examples show how to use software.amazon.awssdk.services.dynamodb.model.PutItemRequest. 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: ApplicationsService.java    From realworld-serverless-application with Apache License 2.0 6 votes vote down vote up
@Override
public Application createApplication(final CreateApplicationInput createApplicationInput) {
  log.info("Creating application with input {}", createApplicationInput);
  ApplicationRecord applicationRecord = modelMapper.map(createApplicationInput,
        ApplicationRecord.class);
  applicationRecord.setCreatedAt(Instant.now(clock));
  applicationRecord.setVersion(1L);
  applicationRecord.setUserId(securityContext.getUserPrincipal().getName());
  try {
    dynamodb.putItem(PutItemRequest.builder()
          .tableName(tableName)
          .item(applicationRecord.toAttributeMap())
          .conditionExpression(
                String.format("attribute_not_exists(%s) AND attribute_not_exists(%s)",
                      ApplicationRecord.USER_ID_ATTRIBUTE_NAME,
                      ApplicationRecord.APPLICATION_ID_ATTRIBUTE_NAME))
          .build());
  } catch (ConditionalCheckFailedException e) {
    throw new ConflictApiException(new ConflictException()
          .errorCode("ApplicationAlreadyExist")
          .message(String.format("Application %s already exists.",
                createApplicationInput.getApplicationId())));
  }
  return modelMapper.map(applicationRecord, Application.class);
}
 
Example #2
Source File: PutItemOperationTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void generateRequest_generatesCorrectRequest() {
    FakeItem fakeItem = createUniqueFakeItem();
    fakeItem.setSubclassAttribute("subclass-value");
    PutItemOperation<FakeItem> putItemOperation = PutItemOperation.create(PutItemEnhancedRequest.builder(FakeItem.class).item(fakeItem).build());

    PutItemRequest request = putItemOperation.generateRequest(FakeItem.getTableSchema(),
                                                              PRIMARY_CONTEXT,
                                                              null);

    Map<String, AttributeValue> expectedItemMap = new HashMap<>();
    expectedItemMap.put("id", AttributeValue.builder().s(fakeItem.getId()).build());
    expectedItemMap.put("subclass_attribute", AttributeValue.builder().s("subclass-value").build());
    PutItemRequest expectedRequest = PutItemRequest.builder()
        .tableName(TABLE_NAME)
        .item(expectedItemMap)
        .build();
    assertThat(request, is(expectedRequest));
}
 
Example #3
Source File: PutItemOperationTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void generateRequest_withMinimalConditionExpression() {
    FakeItem fakeItem = createUniqueFakeItem();
    PutItemOperation<FakeItem> putItemOperation =
        PutItemOperation.create(PutItemEnhancedRequest.builder(FakeItem.class)
                                                      .item(fakeItem)
                                                      .conditionExpression(MINIMAL_CONDITION_EXPRESSION)
                                                      .build());

    PutItemRequest request = putItemOperation.generateRequest(FakeItem.getTableSchema(),
                                                              PRIMARY_CONTEXT,
                                                              null);

    assertThat(request.conditionExpression(), is(MINIMAL_CONDITION_EXPRESSION.expression()));
    assertThat(request.expressionAttributeNames(), is(emptyMap()));
    assertThat(request.expressionAttributeValues(), is(emptyMap()));
}
 
Example #4
Source File: EmptyStringTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void putEmptyString() {
    TestBean testBean = new TestBean();
    testBean.setId("id123");
    testBean.setS("");

    dynamoDbTable.putItem(testBean);

    Map<String, AttributeValue> expectedItemMap = new HashMap<>();
    expectedItemMap.put("id", AttributeValue.builder().s("id123").build());
    expectedItemMap.put("s", EMPTY_STRING);

    PutItemRequest expectedRequest = PutItemRequest.builder()
                                                   .tableName(TABLE_NAME)
                                                   .item(expectedItemMap)
                                                   .build();

    verify(mockDynamoDbClient).putItem(expectedRequest);
}
 
Example #5
Source File: EmptyBinaryTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void putEmptyBytes() {
    TestBean testBean = new TestBean();
    testBean.setId("id123");
    testBean.setB(EMPTY_BYTES);

    dynamoDbTable.putItem(testBean);

    Map<String, AttributeValue> expectedItemMap = new HashMap<>();
    expectedItemMap.put("id", AttributeValue.builder().s("id123").build());
    expectedItemMap.put("b", EMPTY_BINARY);

    PutItemRequest expectedRequest = PutItemRequest.builder()
                                                   .tableName(TABLE_NAME)
                                                   .item(expectedItemMap)
                                                   .build();

    verify(mockDynamoDbClient).putItem(expectedRequest);
}
 
Example #6
Source File: PutItemOperation.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
private PutItemRequest.Builder addExpressionsIfExist(PutItemRequest.Builder requestBuilder,
                                                     WriteModification transformation) {
    Expression mergedConditionExpression;

    if (transformation != null && transformation.additionalConditionalExpression() != null) {
        mergedConditionExpression = Expression.join(this.request.conditionExpression(),
                                                    transformation.additionalConditionalExpression(), " AND ");
    } else {
        mergedConditionExpression = this.request.conditionExpression();
    }

    if (mergedConditionExpression != null) {
        requestBuilder = requestBuilder.conditionExpression(mergedConditionExpression.expression());

        // Avoiding adding empty collections that the low level SDK will propagate to DynamoDb where it causes error.
        if (mergedConditionExpression.expressionValues() != null && !mergedConditionExpression.expressionValues().isEmpty()) {
            requestBuilder = requestBuilder.expressionAttributeValues(mergedConditionExpression.expressionValues());

        }

        if (mergedConditionExpression.expressionNames() != null && !mergedConditionExpression.expressionNames().isEmpty()) {
            requestBuilder = requestBuilder.expressionAttributeNames(mergedConditionExpression.expressionNames());
        }
    }
    return requestBuilder;
}
 
Example #7
Source File: PutItemOperation.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Override
public TransactWriteItem generateTransactWriteItem(TableSchema<T> tableSchema,
                                                   OperationContext operationContext,
                                                   DynamoDbEnhancedClientExtension dynamoDbEnhancedClientExtension) {
    PutItemRequest putItemRequest = generateRequest(tableSchema, operationContext, dynamoDbEnhancedClientExtension);

    Put put = Put.builder()
                 .item(putItemRequest.item())
                 .tableName(putItemRequest.tableName())
                 .conditionExpression(putItemRequest.conditionExpression())
                 .expressionAttributeValues(putItemRequest.expressionAttributeValues())
                 .expressionAttributeNames(putItemRequest.expressionAttributeNames())
                 .build();

    return TransactWriteItem.builder()
                            .put(put)
                            .build();
}
 
Example #8
Source File: PutItemOperationTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void generateRequest_withConditionExpression_andExtensionWithSingleCondition() {
    FakeItem baseFakeItem = createUniqueFakeItem();
    when(mockDynamoDbEnhancedClientExtension.beforeWrite(any(DynamoDbExtensionContext.BeforeWrite.class)))
        .thenReturn(WriteModification.builder().additionalConditionalExpression(CONDITION_EXPRESSION_2).build());
    PutItemOperation<FakeItem> putItemOperation =
        PutItemOperation.create(PutItemEnhancedRequest.builder(FakeItem.class)
                                                      .conditionExpression(CONDITION_EXPRESSION)
                                                      .item(baseFakeItem)
                                                      .build());

    PutItemRequest request = putItemOperation.generateRequest(FakeItem.getTableSchema(),
                                                              PRIMARY_CONTEXT,
                                                              mockDynamoDbEnhancedClientExtension);

    Expression expectedCondition = Expression.join(CONDITION_EXPRESSION, CONDITION_EXPRESSION_2, " AND ");
    assertThat(request.conditionExpression(), is(expectedCondition.expression()));
    assertThat(request.expressionAttributeNames(), is(expectedCondition.expressionNames()));
    assertThat(request.expressionAttributeValues(), is(expectedCondition.expressionValues()));
}
 
Example #9
Source File: PutItemOperationTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void generateRequest_withExtension_modifiesItemToPut() {
    FakeItem baseFakeItem = createUniqueFakeItem();
    FakeItem fakeItem = createUniqueFakeItem();
    Map<String, AttributeValue> baseMap = FakeItem.getTableSchema().itemToMap(baseFakeItem, true);
    Map<String, AttributeValue> fakeMap = FakeItem.getTableSchema().itemToMap(fakeItem, true);
    when(mockDynamoDbEnhancedClientExtension.beforeWrite(any(DynamoDbExtensionContext.BeforeWrite.class)))
        .thenReturn(WriteModification.builder().transformedItem(fakeMap).build());
    PutItemOperation<FakeItem> putItemOperation = PutItemOperation.create(PutItemEnhancedRequest.builder(FakeItem.class)
                                                                                                .item(baseFakeItem)
                                                                                                .build());

    PutItemRequest request = putItemOperation.generateRequest(FakeItem.getTableSchema(),
                                                              PRIMARY_CONTEXT,
                                                              mockDynamoDbEnhancedClientExtension);

    assertThat(request.item(), is(fakeMap));
    verify(mockDynamoDbEnhancedClientExtension).beforeWrite(
        DefaultDynamoDbExtensionContext.builder()
        .items(baseMap)
        .operationContext(PRIMARY_CONTEXT)
        .tableMetadata(FakeItem.getTableMetadata()).build());
}
 
Example #10
Source File: PutItemOperationTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void generateRequest_withExtension_singleCondition() {
    FakeItem baseFakeItem = createUniqueFakeItem();
    FakeItem fakeItem = createUniqueFakeItem();
    Map<String, AttributeValue> fakeMap = FakeItem.getTableSchema().itemToMap(fakeItem, true);
    Expression condition = Expression.builder().expression("condition").expressionValues(fakeMap).build();
    when(mockDynamoDbEnhancedClientExtension.beforeWrite(any(DynamoDbExtensionContext.BeforeWrite.class)))
        .thenReturn(WriteModification.builder().additionalConditionalExpression(condition).build());
    PutItemOperation<FakeItem> putItemOperation = PutItemOperation.create(PutItemEnhancedRequest.builder(FakeItem.class)
                                                                                                .item(baseFakeItem)
                                                                                                .build());

    PutItemRequest request = putItemOperation.generateRequest(FakeItem.getTableSchema(),
                                                              PRIMARY_CONTEXT,
                                                              mockDynamoDbEnhancedClientExtension);

    assertThat(request.conditionExpression(), is("condition"));
    assertThat(request.expressionAttributeValues(), is(fakeMap));
}
 
Example #11
Source File: ParallelScanIntegrationTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
private static void putTestData() {
    Map<String, AttributeValue> item = new HashMap<String, AttributeValue>();
    Random random = new Random();
    for (int hashKeyValue = 0; hashKeyValue < itemNumber; hashKeyValue++) {
        item.put(HASH_KEY_NAME, AttributeValue.builder().n(Integer.toString(hashKeyValue)).build());
        item.put(ATTRIBUTE_RANDOM, AttributeValue.builder().n(Integer.toString(random.nextInt(itemNumber))).build());
        if (hashKeyValue < itemNumber / 2) {
            item.put(ATTRIBUTE_FOO, AttributeValue.builder().n(Integer.toString(hashKeyValue)).build());
        } else {
            item.put(ATTRIBUTE_BAR, AttributeValue.builder().n(Integer.toString(hashKeyValue)).build());
        }

        dynamo.putItem(PutItemRequest.builder().tableName(tableName).item(item).build());
        item.clear();
    }
}
 
Example #12
Source File: MetaStore.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
/**
 * This API retrieves the intermediate keys from the source region and replicates it in the target region.
 *
 * @param materialName material name of the encryption material.
 * @param version version of the encryption material.
 * @param targetMetaStore target MetaStore where the encryption material to be stored.
 */
public void replicate(final String materialName, final long version, final MetaStore targetMetaStore) {
    try {
        final Map<String, AttributeValue> item = getMaterialItem(materialName, version);

        final Map<String, AttributeValue> plainText = getPlainText(item);
        final Map<String, AttributeValue> encryptedText = targetMetaStore.getEncryptedText(plainText);
        final PutItemRequest put = PutItemRequest.builder()
                                                 .tableName(targetMetaStore.tableName)
                                                 .item(encryptedText)
                                                 .expected(doesNotExist)
                                                 .build();
        targetMetaStore.ddb.putItem(put);
    } catch (ConditionalCheckFailedException e) {
        //Item already present.
    }
}
 
Example #13
Source File: DynamoDBTest.java    From dynein with Apache License 2.0 6 votes vote down vote up
@Test
public void testScheduleJob_Failure() throws Exception {
  DyneinJobSpec jobSpec = getTestJobSpec(validToken, "test2");
  Schedule schedule = jobSpecToSchedule(jobSpec);
  Map<String, AttributeValue> item = DynamoDBUtils.toAttributeMap(schedule);
  CompletableFuture<PutItemResponse> ret = new CompletableFuture<>();
  Exception putException = new Exception();
  ret.completeExceptionally(putException);

  PutItemRequest putItemRequest =
      PutItemRequest.builder().tableName(tableName).item(item).build();
  when(ddbClient.putItem(putItemRequest)).thenReturn(ret);

  CompletableFuture<Void> response = scheduleManager.addJob(schedule);

  assertSame(getException(response), putException);
  verify(ddbClient, times(1)).putItem(putItemRequest);
  verifyNoMoreInteractions(ddbClient);
}
 
Example #14
Source File: DynamoDBTest.java    From dynein with Apache License 2.0 6 votes vote down vote up
@Test
public void testScheduleJob() throws Exception {
  DyneinJobSpec jobSpec = getTestJobSpec(validToken, "test1");
  Schedule schedule = jobSpecToSchedule(jobSpec);
  Map<String, AttributeValue> item = DynamoDBUtils.toAttributeMap(schedule);

  PutItemRequest putItemRequest =
      PutItemRequest.builder().tableName(tableName).item(item).build();
  when(ddbClient.putItem(putItemRequest)).thenReturn(CompletableFuture.completedFuture(null));

  CompletableFuture<Void> response = scheduleManager.addJob(schedule);

  response.get(1000, TimeUnit.MILLISECONDS);
  verify(ddbClient, times(1)).putItem(putItemRequest);
  verifyNoMoreInteractions(ddbClient);
}
 
Example #15
Source File: PutItemOperationTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void generateTransactWriteItem_basicRequest() {
    FakeItem fakeItem = createUniqueFakeItem();
    Map<String, AttributeValue> fakeItemMap = FakeItem.getTableSchema().itemToMap(fakeItem, true);
    PutItemOperation<FakeItem> putItemOperation = spy(PutItemOperation.create(PutItemEnhancedRequest.builder(FakeItem.class)
                                                                                                    .item(fakeItem)
                                                                                                    .build()));
    OperationContext context = DefaultOperationContext.create(TABLE_NAME, TableMetadata.primaryIndexName());

    PutItemRequest putItemRequest = PutItemRequest.builder()
                                                  .tableName(TABLE_NAME)
                                                  .item(fakeItemMap)
                                                  .build();
    doReturn(putItemRequest).when(putItemOperation).generateRequest(any(), any(), any());

    TransactWriteItem actualResult = putItemOperation.generateTransactWriteItem(FakeItem.getTableSchema(),
                                                                                context,
                                                                                mockDynamoDbEnhancedClientExtension);

    TransactWriteItem expectedResult = TransactWriteItem.builder()
                                                        .put(Put.builder()
                                                                .item(fakeItemMap)
                                                                .tableName(TABLE_NAME)
                                                                .build())
                                                        .build();
    assertThat(actualResult, is(expectedResult));
    verify(putItemOperation).generateRequest(FakeItem.getTableSchema(), context, mockDynamoDbEnhancedClientExtension);
}
 
Example #16
Source File: PutItemOperationTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void generateRequest_withExtension_noModifications() {
    FakeItem baseFakeItem = createUniqueFakeItem();
    when(mockDynamoDbEnhancedClientExtension.beforeWrite(any(DynamoDbExtensionContext.BeforeWrite.class)))
        .thenReturn(WriteModification.builder().build());
    PutItemOperation<FakeItem> putItemOperation = PutItemOperation.create(PutItemEnhancedRequest.builder(FakeItem.class)
                                                                                                .item(baseFakeItem)
                                                                                                .build());

    PutItemRequest request = putItemOperation.generateRequest(FakeItem.getTableSchema(),
                                                              PRIMARY_CONTEXT,
                                                              mockDynamoDbEnhancedClientExtension);
    assertThat(request.conditionExpression(), is(nullValue()));
    assertThat(request.expressionAttributeValues().size(), is(0));
}
 
Example #17
Source File: PutItemOperationTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void generateTransactWriteItem_conditionalRequest() {
    FakeItem fakeItem = createUniqueFakeItem();
    Map<String, AttributeValue> fakeItemMap = FakeItem.getTableSchema().itemToMap(fakeItem, true);
    PutItemOperation<FakeItem> putItemOperation = spy(PutItemOperation.create(PutItemEnhancedRequest.builder(FakeItem.class)
                                                                                                    .item(fakeItem)
                                                                                                    .build()));
    OperationContext context = DefaultOperationContext.create(TABLE_NAME, TableMetadata.primaryIndexName());

    String conditionExpression = "condition-expression";
    Map<String, AttributeValue> attributeValues = Collections.singletonMap("key", stringValue("value1"));
    Map<String, String> attributeNames = Collections.singletonMap("key", "value2");

    PutItemRequest putItemRequest = PutItemRequest.builder()
                                                  .tableName(TABLE_NAME)
                                                  .item(fakeItemMap)
                                                  .conditionExpression(conditionExpression)
                                                  .expressionAttributeValues(attributeValues)
                                                  .expressionAttributeNames(attributeNames)
                                                  .build();
    doReturn(putItemRequest).when(putItemOperation).generateRequest(any(), any(), any());

    TransactWriteItem actualResult = putItemOperation.generateTransactWriteItem(FakeItem.getTableSchema(),
                                                                                context,
                                                                                mockDynamoDbEnhancedClientExtension);

    TransactWriteItem expectedResult = TransactWriteItem.builder()
                                                        .put(Put.builder()
                                                                .item(fakeItemMap)
                                                                .tableName(TABLE_NAME)
                                                                .conditionExpression(conditionExpression)
                                                                .expressionAttributeNames(attributeNames)
                                                                .expressionAttributeValues(attributeValues)
                                                                .build())
                                                        .build();
    assertThat(actualResult, is(expectedResult));
    verify(putItemOperation).generateRequest(FakeItem.getTableSchema(), context, mockDynamoDbEnhancedClientExtension);
}
 
Example #18
Source File: EnhancedClientGetOverheadBenchmark.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
private static String marshall(Map<String, AttributeValue> item) {
    return PUT_ITEM_REQUEST_MARSHALLER.marshall(PutItemRequest.builder().item(item).build())
            .contentStreamProvider().map(cs -> {
                try {
                    return IoUtils.toUtf8String(cs.newStream());
                } catch (IOException e) {
                    throw new UncheckedIOException(e);
                }
            }).orElse(null);
}
 
Example #19
Source File: V2DynamoDbAttributeValue.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
private static byte[] toUtf8ByteArray(Map<String, AttributeValue> item) {
    SdkHttpFullRequest marshalled = putItemRequestMarshaller().marshall(PutItemRequest.builder().item(item).build());
    InputStream content = marshalled.contentStreamProvider().get().newStream();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buff = new byte[8192];
    int read;
    try {
        while ((read = content.read(buff)) != -1) {
            baos.write(buff, 0, read);
        }
    } catch (IOException ioe) {
        throw new UncheckedIOException(ioe);
    }
    return baos.toByteArray();
}
 
Example #20
Source File: MetaStore.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
private Map<String, AttributeValue> conditionalPut(final Map<String, AttributeValue> item) {
    try {
        final PutItemRequest put = PutItemRequest.builder().tableName(tableName).item(item)
                .expected(doesNotExist).build();
        ddb.putItem(put);
        return item;
    } catch (final ConditionalCheckFailedException ex) {
        final Map<String, AttributeValue> ddbKey = new HashMap<>();
        ddbKey.put(DEFAULT_HASH_KEY, item.get(DEFAULT_HASH_KEY));
        ddbKey.put(DEFAULT_RANGE_KEY, item.get(DEFAULT_RANGE_KEY));
        return ddbGet(ddbKey);
    }
}
 
Example #21
Source File: MostRecentProviderTests.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
@Test
public void singleVersion() throws InterruptedException {
    final MostRecentProvider prov = new MostRecentProvider(store, MATERIAL_NAME, 500);
    verify(client, never()).putItem(any(PutItemRequest.class));
    final EncryptionMaterials eMat1 = prov.getEncryptionMaterials(ctx);
    // It's a new provider, so we see a single putItem
    verify(client).putItem(any(PutItemRequest.class));
    reset(client);
    // Ensure the cache is working
    final EncryptionMaterials eMat2 = prov.getEncryptionMaterials(ctx);
    verifyNoMoreInteractions(client);
    assertEquals(0, store.getVersionFromMaterialDescription(eMat1.getMaterialDescription()));
    assertEquals(0, store.getVersionFromMaterialDescription(eMat2.getMaterialDescription()));
    // Let the TTL be exceeded
    Thread.sleep(500);
    final EncryptionMaterials eMat3 = prov.getEncryptionMaterials(ctx);
    verify(client).query(any(QueryRequest.class));
    verifyNoMoreInteractions(client);
    assertEquals(0, store.getVersionFromMaterialDescription(eMat3.getMaterialDescription()));

    assertEquals(eMat1.getSigningKey(), eMat2.getSigningKey());
    assertEquals(eMat1.getSigningKey(), eMat3.getSigningKey());
    // Check algorithms. Right now we only support AES and HmacSHA256
    assertEquals("AES", eMat1.getEncryptionKey().getAlgorithm());
    assertEquals("HmacSHA256", eMat1.getSigningKey().getAlgorithm());

    // Ensure we can decrypt all of them without hitting ddb more than the minimum
    final MostRecentProvider prov2 = new MostRecentProvider(store, MATERIAL_NAME, 500);
    final DecryptionMaterials dMat1 = prov2.getDecryptionMaterials(ctx(eMat1));
    reset(client);
    assertEquals(eMat1.getEncryptionKey(), dMat1.getDecryptionKey());
    assertEquals(eMat1.getSigningKey(), dMat1.getVerificationKey());
    final DecryptionMaterials dMat2 = prov2.getDecryptionMaterials(ctx(eMat2));
    assertEquals(eMat2.getEncryptionKey(), dMat2.getDecryptionKey());
    assertEquals(eMat2.getSigningKey(), dMat2.getVerificationKey());
    final DecryptionMaterials dMat3 = prov2.getDecryptionMaterials(ctx(eMat3));
    assertEquals(eMat3.getEncryptionKey(), dMat3.getDecryptionKey());
    assertEquals(eMat3.getSigningKey(), dMat3.getVerificationKey());
    verifyNoMoreInteractions(client);
}
 
Example #22
Source File: DynamoDBLeaseRefresherTest.java    From amazon-kinesis-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateLeaseIfNotExistsTimesOut() throws Exception {
    TimeoutException te = setRuleForDependencyTimeout();

    when(dynamoDbClient.putItem(any(PutItemRequest.class))).thenReturn(mockPutItemFuture);
    when(mockPutItemFuture.get(anyLong(), any())).thenThrow(te);

    when(leaseSerializer.toDynamoRecord(any())).thenReturn(serializedLease);
    when(leaseSerializer.getDynamoNonexistantExpectation()).thenReturn(Collections.emptyMap());

    verifyCancel(mockPutItemFuture, () -> leaseRefresher.createLeaseIfNotExists(lease));
}
 
Example #23
Source File: ProvisionedThroughputThrottlingIntegrationTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Tests that throttling errors and delayed retries are automatically
 * handled for users.
 *
 * We trigger ProvisionedThroughputExceededExceptions here because of the
 * low throughput on our test table, but users shouldn't see any problems
 * because of the backoff and retry strategy.
 */
@Test
public void testProvisionedThroughputExceededRetryHandling() throws Exception {
    for (int i = 0; i < 20; i++) {
        Map<String, AttributeValue> item = Collections
                .singletonMap(HASH_KEY_NAME, AttributeValue.builder().s(UUID.randomUUID().toString()).build());
        dynamo.putItem(PutItemRequest.builder().tableName(tableName).item(item).build());
    }
}
 
Example #24
Source File: ApplicationsServiceTest.java    From realworld-serverless-application with Apache License 2.0 5 votes vote down vote up
@Test
public void createApplication_alreadyExist() {
  String userId = UUID.randomUUID().toString();
  String applicationId = UUID.randomUUID().toString();
  CreateApplicationInput input = new CreateApplicationInput()
        .applicationId(applicationId);
  when(principal.getName()).thenReturn(userId);
  doThrow(ConditionalCheckFailedException.class).when(dynamodb).putItem(any(PutItemRequest.class));

  assertThatThrownBy(() -> service.createApplication(input))
        .isInstanceOf(ConflictApiException.class);
}
 
Example #25
Source File: ApplicationsServiceTest.java    From realworld-serverless-application with Apache License 2.0 5 votes vote down vote up
@Test
public void createApplication() {
  String userId = UUID.randomUUID().toString();
  String applicationId = UUID.randomUUID().toString();
  Instant createdAt = Instant.now();
  CreateApplicationInput input = new CreateApplicationInput()
        .applicationId(applicationId);
  Map<String, AttributeValue> recordMap = keyMap(userId, applicationId);
  recordMap.put("version", AttributeValue.builder().n("1").build());
  recordMap.put("createdAt", AttributeValue.builder().s(createdAt.toString()).build());

  when(principal.getName()).thenReturn(userId);
  when(clock.instant()).thenReturn(createdAt);

  PutItemRequest expectedPutItemRequest = PutItemRequest.builder()
        .tableName(TABLE_NAME)
        .item(recordMap)
        .conditionExpression("attribute_not_exists(userId) AND attribute_not_exists(applicationId)")
        .build();

  Application application = service.createApplication(input);

  ArgumentCaptor<PutItemRequest> putItemRequestArgumentCaptor = ArgumentCaptor.forClass(PutItemRequest.class);
  verify(dynamodb).putItem(putItemRequestArgumentCaptor.capture());

  assertThat(application.getApplicationId()).isEqualTo(applicationId);
  assertThat(putItemRequestArgumentCaptor.getValue()).isEqualTo(expectedPutItemRequest);
}
 
Example #26
Source File: AbstractService.java    From quarkus-quickstarts with Apache License 2.0 5 votes vote down vote up
protected PutItemRequest putRequest(Fruit fruit) {
    Map<String, AttributeValue> item = new HashMap<>();
    item.put(FRUIT_NAME_COL, AttributeValue.builder().s(fruit.getName()).build());
    item.put(FRUIT_DESC_COL, AttributeValue.builder().s(fruit.getDescription()).build());

    return PutItemRequest.builder()
            .tableName(getTableName())
            .item(item)
            .build();
}
 
Example #27
Source File: DynamoDBUtils.java    From quarkus with Apache License 2.0 5 votes vote down vote up
public static PutItemRequest createPutRequest(String table, String keyValue, String rangeValue, String payLoad) {
    Map<String, AttributeValue> item = new HashMap<>();
    item.put(KEY_NAME, AttributeValue.builder().s(keyValue).build());
    item.put(RANGE_NAME, AttributeValue.builder().s(rangeValue).build());
    item.put(PAYLOAD_NAME, AttributeValue.builder().s(payLoad).build());

    return PutItemRequest.builder()
            .tableName(table)
            .item(item)
            .build();
}
 
Example #28
Source File: PutItemOperationTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void generateRequest_withConditionExpression_generatesCorrectRequest() {
    FakeItem fakeItem = createUniqueFakeItem();
    fakeItem.setSubclassAttribute("subclass-value");

    PutItemOperation<FakeItem> putItemOperation =
        PutItemOperation.create(PutItemEnhancedRequest.builder(FakeItem.class)
                                                      .conditionExpression(CONDITION_EXPRESSION)
                                                      .item(fakeItem)
                                                      .build());

    PutItemRequest request = putItemOperation.generateRequest(FakeItem.getTableSchema(),
                                                              PRIMARY_CONTEXT,
                                                              null);

    Map<String, AttributeValue> expectedItemMap = new HashMap<>();
    expectedItemMap.put("id", AttributeValue.builder().s(fakeItem.getId()).build());
    expectedItemMap.put("subclass_attribute", AttributeValue.builder().s("subclass-value").build());
    PutItemRequest expectedRequest =
        PutItemRequest.builder()
                      .tableName(TABLE_NAME)
                      .item(expectedItemMap)
                      .conditionExpression(CONDITION_EXPRESSION.expression())
                      .expressionAttributeNames(CONDITION_EXPRESSION.expressionNames())
                      .expressionAttributeValues(CONDITION_EXPRESSION.expressionValues())
                      .build();
    assertThat(request, is(expectedRequest));
}
 
Example #29
Source File: PaginatorIntegrationTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
private static void putTestData() {
    Map<String, AttributeValue> item = new HashMap();
    Random random = new Random();

    for (int hashKeyValue = 0; hashKeyValue < ITEM_COUNT; hashKeyValue++) {
        item.put(HASH_KEY_NAME, AttributeValue.builder().n(Integer.toString(hashKeyValue)).build());
        item.put(ATTRIBUTE_FOO, AttributeValue.builder().n(Integer.toString(random.nextInt(ITEM_COUNT))).build());

        dynamo.putItem(PutItemRequest.builder().tableName(TABLE_NAME).item(item).build());
        item.clear();
    }
}
 
Example #30
Source File: PutItemOperation.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Override
public WriteRequest generateWriteRequest(TableSchema<T> tableSchema,
                                         OperationContext operationContext,
                                         DynamoDbEnhancedClientExtension extension) {

    PutItemRequest putItemRequest = generateRequest(tableSchema, operationContext, extension);

    if (putItemRequest.conditionExpression() != null) {
        throw new IllegalArgumentException("A mapper extension inserted a conditionExpression in a PutItem "
                                           + "request as part of a BatchWriteItemRequest. This is not supported by "
                                           + "DynamoDb. An extension known to do this is the "
                                           + "VersionedRecordExtension which is loaded by default unless overridden. "
                                           + "To fix this use a table schema that does not "
                                           + "have a versioned attribute in it or do not load the offending extension.");
    }

    return WriteRequest.builder().putRequest(PutRequest.builder().item(putItemRequest.item()).build()).build();
}