index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
0
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/FileUpload.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.transfer.s3.model; import java.util.concurrent.CompletableFuture; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.services.s3.S3AsyncClient; import software.amazon.awssdk.transfer.s3.S3TransferManager; /** * An upload transfer of a single object to S3. */ @SdkPublicApi public interface FileUpload extends ObjectTransfer { /** * Pauses the current upload operation and return the information that can * be used to resume the upload at a later time. * <p> * The information object is serializable for persistent storage until it should be resumed. * See {@link ResumableFileUpload} for supported formats. * * <p> * Currently, it's only supported if the underlying {@link S3AsyncClient} is CRT-based (created via * {@link S3AsyncClient#crtBuilder()} or {@link S3AsyncClient#crtCreate()}). * It will throw {@link UnsupportedOperationException} if the {@link S3TransferManager} is created * with a non CRT-based S3 client (created via {@link S3AsyncClient#builder()}). * * @return A {@link ResumableFileUpload} that can be used to resume the upload. */ ResumableFileUpload pause(); @Override CompletableFuture<CompletedFileUpload> completionFuture(); }
4,100
0
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/CompletedDirectoryUpload.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.transfer.s3.model; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Objects; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.transfer.s3.S3TransferManager; import software.amazon.awssdk.utils.ToString; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * Represents a completed upload directory transfer to Amazon S3. It can be used to track * failed single file uploads. * * @see S3TransferManager#uploadDirectory(UploadDirectoryRequest) */ @SdkPublicApi public final class CompletedDirectoryUpload implements CompletedDirectoryTransfer, ToCopyableBuilder<CompletedDirectoryUpload.Builder, CompletedDirectoryUpload> { private final List<FailedFileUpload> failedTransfers; private CompletedDirectoryUpload(DefaultBuilder builder) { this.failedTransfers = Collections.unmodifiableList( new ArrayList<>(Validate.paramNotNull(builder.failedTransfers, "failedTransfers"))); } @Override public List<FailedFileUpload> failedTransfers() { return failedTransfers; } /** * Creates a default builder for {@link CompletedDirectoryUpload}. */ public static Builder builder() { return new DefaultBuilder(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CompletedDirectoryUpload that = (CompletedDirectoryUpload) o; return Objects.equals(failedTransfers, that.failedTransfers); } @Override public int hashCode() { return failedTransfers != null ? failedTransfers.hashCode() : 0; } @Override public String toString() { return ToString.builder("CompletedDirectoryUpload") .add("failedTransfers", failedTransfers) .build(); } public static Class<? extends Builder> serializableBuilderClass() { return DefaultBuilder.class; } @Override public Builder toBuilder() { return new DefaultBuilder(this); } public interface Builder extends CopyableBuilder<CompletedDirectoryUpload.Builder, CompletedDirectoryUpload> { /** * Sets a collection of {@link FailedFileUpload}s * * @param failedTransfers failed uploads * @return This builder for method chaining. */ Builder failedTransfers(Collection<FailedFileUpload> failedTransfers); /** * Adds a {@link FailedFileUpload} * * @param failedTransfer failed upload * @return This builder for method chaining. */ Builder addFailedTransfer(FailedFileUpload failedTransfer); /** * Builds a {@link CompletedDirectoryUpload} based on the properties supplied to this builder * @return An initialized {@link CompletedDirectoryUpload} */ CompletedDirectoryUpload build(); } private static final class DefaultBuilder implements Builder { private Collection<FailedFileUpload> failedTransfers = new ArrayList<>(); private DefaultBuilder() { } private DefaultBuilder(CompletedDirectoryUpload completedDirectoryUpload) { this.failedTransfers = new ArrayList<>(completedDirectoryUpload.failedTransfers); } @Override public Builder failedTransfers(Collection<FailedFileUpload> failedTransfers) { this.failedTransfers = new ArrayList<>(failedTransfers); return this; } @Override public Builder addFailedTransfer(FailedFileUpload failedTransfer) { failedTransfers.add(failedTransfer); return this; } public Collection<FailedFileUpload> getFailedTransfers() { return Collections.unmodifiableCollection(failedTransfers); } public void setFailedTransfers(Collection<FailedFileUpload> failedTransfers) { failedTransfers(failedTransfers); } @Override public CompletedDirectoryUpload build() { return new CompletedDirectoryUpload(this); } } }
4,101
0
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3
Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/FileDownload.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.transfer.s3.model; import java.util.concurrent.CompletableFuture; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; /** * A download transfer of a single object from S3. */ @SdkPublicApi @ThreadSafe public interface FileDownload extends ObjectTransfer { /** * Pause the current download operation and returns the information that can * be used to resume the download at a later time. * <p> * The information object is serializable for persistent storage until it should be resumed. * See {@link ResumableFileDownload} for supported formats. * * @return A {@link ResumableFileDownload} that can be used to resume the download. */ ResumableFileDownload pause(); @Override CompletableFuture<CompletedFileDownload> completionFuture(); }
4,102
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/NestedAttributeNameTest.java
package software.amazon.awssdk.enhanced.dynamodb; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.Collections; import org.junit.jupiter.api.Test; public class NestedAttributeNameTest { private static final String ATTRIBUTE_NAME = "attributeName"; @Test public void testNullAttributeNames_fails() { assertThatThrownBy(() -> NestedAttributeName.builder().build()) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("nestedAttributeNames must not be null"); assertThatThrownBy(() -> NestedAttributeName.builder().addElement(null).build()) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("nestedAttributeNames must not contain null values"); assertThatThrownBy(() -> NestedAttributeName.builder().elements(ATTRIBUTE_NAME).addElement(null).build()) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("nestedAttributeNames must not contain null values"); assertThatThrownBy(() -> NestedAttributeName.create()) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("nestedAttributeNames must not be empty"); } @Test public void testEmptyAttributeNameList_fails() { assertThatThrownBy(() -> NestedAttributeName.builder().elements(Collections.emptyList()).build()) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> NestedAttributeName.create(Collections.emptyList())) .isInstanceOf(IllegalArgumentException.class); } @Test public void testEmptyAttributeNames_allowed() { NestedAttributeName.builder().elements(Collections.singletonList("")).build(); NestedAttributeName.create(Collections.singletonList("")); } @Test public void testEmptyAttributeNames_toString() { NestedAttributeName nestedAttribute = NestedAttributeName.create("Attribute1", "Attribute*2", "Attribute-3"); assertThat(nestedAttribute.toString()).isEqualTo("Attribute1.Attribute*2.Attribute-3"); } @Test public void toBuilder() { NestedAttributeName builtObject = NestedAttributeName.builder().addElement(ATTRIBUTE_NAME).build(); NestedAttributeName copiedObject = builtObject.toBuilder().build(); assertThat(copiedObject).isEqualTo(builtObject); } }
4,103
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/KeyTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import java.util.Optional; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItemWithIndices; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; public class KeyTest { private final Key key = Key.builder().partitionValue("id123").sortValue("id456").build(); private final Key partitionOnlyKey = Key.builder().partitionValue("id123").build(); @Test public void getKeyMap() { Map<String, AttributeValue> expectedResult = new HashMap<>(); expectedResult.put("gsi_id", AttributeValue.builder().s("id123").build()); expectedResult.put("gsi_sort", AttributeValue.builder().s("id456").build()); assertThat(key.keyMap(FakeItemWithIndices.getTableSchema(), "gsi_1"), is(expectedResult)); } @Test public void getPrimaryKeyMap() { Map<String, AttributeValue> expectedResult = new HashMap<>(); expectedResult.put("id", AttributeValue.builder().s("id123").build()); expectedResult.put("sort", AttributeValue.builder().s("id456").build()); assertThat(key.primaryKeyMap(FakeItemWithIndices.getTableSchema()), is(expectedResult)); } @Test public void getPartitionKeyValue() { assertThat(key.partitionKeyValue(), is(AttributeValue.builder().s("id123").build())); } @Test public void getSortKeyValue() { assertThat(key.sortKeyValue(), is(Optional.of(AttributeValue.builder().s("id456").build()))); } @Test public void getKeyMap_partitionOnly() { Map<String, AttributeValue> expectedResult = new HashMap<>(); expectedResult.put("gsi_id", AttributeValue.builder().s("id123").build()); assertThat(partitionOnlyKey.keyMap(FakeItemWithIndices.getTableSchema(), "gsi_1"), is(expectedResult)); } @Test public void getPrimaryKeyMap_partitionOnly() { Map<String, AttributeValue> expectedResult = new HashMap<>(); expectedResult.put("id", AttributeValue.builder().s("id123").build()); assertThat(partitionOnlyKey.primaryKeyMap(FakeItemWithIndices.getTableSchema()), is(expectedResult)); } @Test public void getPartitionKeyValue_partitionOnly() { assertThat(partitionOnlyKey.partitionKeyValue(), is(AttributeValue.builder().s("id123").build())); } @Test public void getSortKeyValue_partitionOnly() { assertThat(partitionOnlyKey.sortKeyValue(), is(Optional.empty())); } @Test public void numericKeys_convertsToCorrectAttributeValue() { Key key = Key.builder().partitionValue(123).sortValue(45.6).build(); assertThat(key.partitionKeyValue(), is(AttributeValue.builder().n("123").build())); assertThat(key.sortKeyValue(), is(Optional.of(AttributeValue.builder().n("45.6").build()))); } @Test public void stringKeys_convertsToCorrectAttributeValue() { Key key = Key.builder().partitionValue("one").sortValue("two").build(); assertThat(key.partitionKeyValue(), is(AttributeValue.builder().s("one").build())); assertThat(key.sortKeyValue(), is(Optional.of(AttributeValue.builder().s("two").build()))); } @Test public void binaryKeys_convertsToCorrectAttributeValue() { SdkBytes partition = SdkBytes.fromString("one", StandardCharsets.UTF_8); SdkBytes sort = SdkBytes.fromString("two", StandardCharsets.UTF_8); Key key = Key.builder().partitionValue(partition).sortValue(sort).build(); assertThat(key.partitionKeyValue(), is(AttributeValue.builder().b(partition).build())); assertThat(key.sortKeyValue(), is(Optional.of(AttributeValue.builder().b(sort).build()))); } @Test public void toBuilder() { Key keyClone = key.toBuilder().build(); assertThat(key, is(equalTo(keyClone))); } @Test public void nullPartitionKey_shouldThrowException() { AttributeValue attributeValue = null; assertThatThrownBy(() -> Key.builder().partitionValue(attributeValue).build()) .isInstanceOf(IllegalArgumentException.class).hasMessageContaining("partitionValue should not be null"); assertThatThrownBy(() -> Key.builder().partitionValue(AttributeValue.builder().nul(true).build()).build()) .isInstanceOf(IllegalArgumentException.class).hasMessageContaining("partitionValue should not be null"); } }
4,104
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/ProjectionExpressionTest.java
package software.amazon.awssdk.enhanced.dynamodb; import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import org.junit.jupiter.api.Test; import software.amazon.awssdk.enhanced.dynamodb.internal.ProjectionExpression; public class ProjectionExpressionTest { private static final String NESTING_SEPARATOR = "."; private static final String PROJ_EXP_SEPARATOR = ","; private static final Map<String, String> EXPECTED_ATTRIBUTE_NAMES = new HashMap<>(); static { EXPECTED_ATTRIBUTE_NAMES.put("#AMZN_MAPPED_attribute", "attribute"); EXPECTED_ATTRIBUTE_NAMES.put("#AMZN_MAPPED_Attribute", "Attribute"); EXPECTED_ATTRIBUTE_NAMES.put("#AMZN_MAPPED_firstiteminlist[0]", "firstiteminlist[0]"); EXPECTED_ATTRIBUTE_NAMES.put("#AMZN_MAPPED_March_2021", "March-2021"); EXPECTED_ATTRIBUTE_NAMES.put("#AMZN_MAPPED_Why_Make_This_An_Attribute_Name", "Why.Make-This*An:Attribute:Name"); } @Test public void nullInputSetsStateCorrectly() { ProjectionExpression projectionExpression = ProjectionExpression.create(null); assertThat(projectionExpression.expressionAttributeNames()).isEmpty(); assertThat(projectionExpression.projectionExpressionAsString()).isEmpty(); } @Test public void emptyInputSetsStateCorrectly() { ProjectionExpression projectionExpression = ProjectionExpression.create(new ArrayList<>()); assertThat(projectionExpression.expressionAttributeNames()).isEmpty(); assertThat(projectionExpression.projectionExpressionAsString()).isEmpty(); } @Test public void severalTopLevelAttributes_handledCorrectly() { List<NestedAttributeName> attributeNames = EXPECTED_ATTRIBUTE_NAMES.values() .stream() .map(NestedAttributeName::create) .collect(Collectors.toList()); String expectedProjectionExpression = EXPECTED_ATTRIBUTE_NAMES.keySet() .stream() .collect(Collectors.joining(PROJ_EXP_SEPARATOR)); assertProjectionExpression(attributeNames, EXPECTED_ATTRIBUTE_NAMES, expectedProjectionExpression); } @Test public void severalNestedAttributes_handledCorrectly() { List<NestedAttributeName> attributeNames = Arrays.asList(NestedAttributeName.create( EXPECTED_ATTRIBUTE_NAMES.values() .stream() .collect(Collectors.toList()))); String expectedProjectionExpression = EXPECTED_ATTRIBUTE_NAMES.keySet() .stream() .collect(Collectors.joining(NESTING_SEPARATOR)); assertProjectionExpression(attributeNames, EXPECTED_ATTRIBUTE_NAMES, expectedProjectionExpression); } @Test public void nonUniqueAttributeNames_AreCollapsed() { Map<String, String> expectedAttributeNames = new HashMap<>(); expectedAttributeNames.put("#AMZN_MAPPED_attribute", "attribute"); List<NestedAttributeName> attributeNames = Arrays.asList( NestedAttributeName.create("attribute", "attribute"), NestedAttributeName.create("attribute") ); String expectedProjectionExpression = "#AMZN_MAPPED_attribute.#AMZN_MAPPED_attribute,#AMZN_MAPPED_attribute"; assertProjectionExpression(attributeNames, expectedAttributeNames, expectedProjectionExpression); } @Test public void nonUniquePlaceholders_AreDisambiguated() { Map<String, String> expectedAttributeNames = new HashMap<>(); expectedAttributeNames.put("#AMZN_MAPPED_0_attribute_03", "attribute-03"); expectedAttributeNames.put("#AMZN_MAPPED_1_attribute_03", "attribute.03"); expectedAttributeNames.put("#AMZN_MAPPED_2_attribute_03", "attribute:03"); List<NestedAttributeName> attributeNames = Arrays.asList( NestedAttributeName.create("attribute-03", "attribute.03"), NestedAttributeName.create("attribute:03") ); String expectedProjectionExpression = "#AMZN_MAPPED_0_attribute_03.#AMZN_MAPPED_1_attribute_03," + "#AMZN_MAPPED_2_attribute_03"; assertProjectionExpression(attributeNames, expectedAttributeNames, expectedProjectionExpression); } private void assertProjectionExpression(List<NestedAttributeName> attributeNames, Map<String, String> expectedAttributeNames, String expectedProjectionExpression) { ProjectionExpression projectionExpression = ProjectionExpression.create(attributeNames); Map<String, String> expressionAttributeNames = projectionExpression.expressionAttributeNames(); Optional<String> projectionExpressionString = projectionExpression.projectionExpressionAsString(); assertThat(projectionExpressionString.get()).isEqualTo(expectedProjectionExpression); assertThat(expressionAttributeNames).isEqualTo(expectedAttributeNames); } }
4,105
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/ExpressionTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasEntry; import static org.hamcrest.Matchers.is; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.EnhancedAttributeValue; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; public class ExpressionTest { @Rule public ExpectedException exception = ExpectedException.none(); @Test public void join_correctlyWrapsExpressions() { Expression expression1 = Expression.builder().expression("one").build(); Expression expression2 = Expression.builder().expression("two").build(); Expression expression3 = Expression.builder().expression("three").build(); Expression coalescedExpression = Expression.join(Expression.join(expression1, expression2, " AND "), expression3, " AND "); String expectedExpression = "((one) AND (two)) AND (three)"; assertThat(coalescedExpression.expression(), is(expectedExpression)); } @Test public void joinExpressions_correctlyJoins() { String result = Expression.joinExpressions("one", "two", " AND "); assertThat(result, is("(one) AND (two)")); } @Test public void joinNames_correctlyJoins() { Map<String, String> names1 = new HashMap<>(); names1.put("one", "1"); names1.put("two", "2"); Map<String, String> names2 = new HashMap<>(); names2.put("three", "3"); names2.put("four", "4"); Map<String, String> result = Expression.joinNames(names1, names2); assertThat(result.size(), is(4)); assertThat(result, hasEntry("one", "1")); assertThat(result, hasEntry("two", "2")); assertThat(result, hasEntry("three", "3")); assertThat(result, hasEntry("four", "4")); } @Test public void joinNames_correctlyJoinsEmpty() { Map<String, String> names1 = new HashMap<>(); names1.put("one", "1"); names1.put("two", "2"); Map<String, String> names2 = new HashMap<>(); names2.put("three", "3"); names2.put("four", "4"); Map<String, String> result = Expression.joinNames(names1, null); assertThat(result.size(), is(2)); assertThat(result, hasEntry("one", "1")); assertThat(result, hasEntry("two", "2")); result = Expression.joinNames(null, names2); assertThat(result.size(), is(2)); assertThat(result, hasEntry("three", "3")); assertThat(result, hasEntry("four", "4")); result = Expression.joinNames(names1, Collections.emptyMap()); assertThat(result.size(), is(2)); assertThat(result, hasEntry("one", "1")); assertThat(result, hasEntry("two", "2")); result = Expression.joinNames(Collections.emptyMap(), names2); assertThat(result.size(), is(2)); assertThat(result, hasEntry("three", "3")); assertThat(result, hasEntry("four", "4")); } @Test public void joinNames_conflictingKey() { Map<String, String> names1 = new HashMap<>(); names1.put("one", "1"); names1.put("two", "2"); Map<String, String> names2 = new HashMap<>(); names2.put("three", "3"); names2.put("two", "4"); exception.expect(IllegalArgumentException.class); exception.expectMessage("two"); Expression.joinNames(names1, names2); } @Test public void joinValues_correctlyJoins() { Map<String, AttributeValue> values1 = new HashMap<>(); values1.put("one", EnhancedAttributeValue.fromString("1").toAttributeValue()); values1.put("two", EnhancedAttributeValue.fromString("2").toAttributeValue()); Map<String, AttributeValue> values2 = new HashMap<>(); values2.put("three", EnhancedAttributeValue.fromString("3").toAttributeValue()); values2.put("four", EnhancedAttributeValue.fromString("4").toAttributeValue()); Map<String, AttributeValue> result = Expression.joinValues(values1, values2); assertThat(result.size(), is(4)); assertThat(result, hasEntry("one", EnhancedAttributeValue.fromString("1").toAttributeValue())); assertThat(result, hasEntry("two", EnhancedAttributeValue.fromString("2").toAttributeValue())); assertThat(result, hasEntry("three", EnhancedAttributeValue.fromString("3").toAttributeValue())); assertThat(result, hasEntry("four", EnhancedAttributeValue.fromString("4").toAttributeValue())); } @Test public void joinValues_conflictingKey() { Map<String, AttributeValue> values1 = new HashMap<>(); values1.put("one", EnhancedAttributeValue.fromString("1").toAttributeValue()); values1.put("two", EnhancedAttributeValue.fromString("2").toAttributeValue()); Map<String, AttributeValue> values2 = new HashMap<>(); values2.put("three", EnhancedAttributeValue.fromString("3").toAttributeValue()); values2.put("two", EnhancedAttributeValue.fromString("4").toAttributeValue()); exception.expect(IllegalArgumentException.class); exception.expectMessage("two"); Expression.joinValues(values1, values2); } }
4,106
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/EnhancedTypeDocumentationConfigurationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; public class EnhancedTypeDocumentationConfigurationTest { @Test public void defaultBuilder_defaultToFalse() { EnhancedTypeDocumentConfiguration configuration = EnhancedTypeDocumentConfiguration.builder().build(); assertThat(configuration.ignoreNulls()).isFalse(); assertThat(configuration.preserveEmptyObject()).isFalse(); } @Test public void equalsHashCode() { EnhancedTypeDocumentConfiguration configuration = EnhancedTypeDocumentConfiguration.builder() .preserveEmptyObject(true) .ignoreNulls(false) .build(); EnhancedTypeDocumentConfiguration another = EnhancedTypeDocumentConfiguration.builder() .preserveEmptyObject(true) .ignoreNulls(false) .build(); EnhancedTypeDocumentConfiguration different = EnhancedTypeDocumentConfiguration.builder() .preserveEmptyObject(false) .ignoreNulls(true) .build(); assertThat(configuration).isEqualTo(another); assertThat(configuration.hashCode()).isEqualTo(another.hashCode()); assertThat(configuration).isNotEqualTo(different); assertThat(configuration.hashCode()).isNotEqualTo(different.hashCode()); } }
4,107
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/TableSchemaTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItem; import software.amazon.awssdk.enhanced.dynamodb.mapper.BeanTableSchema; import software.amazon.awssdk.enhanced.dynamodb.mapper.ImmutableTableSchema; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticImmutableTableSchema; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema; import software.amazon.awssdk.enhanced.dynamodb.mapper.testbeans.InvalidBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.testbeans.SimpleBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.testbeans.SimpleImmutable; public class TableSchemaTest { @Rule public ExpectedException exception = ExpectedException.none(); @Test public void builder_constructsStaticTableSchemaBuilder_fromClass() { StaticTableSchema.Builder<FakeItem> builder = TableSchema.builder(FakeItem.class); assertThat(builder).isNotNull(); } @Test public void builder_constructsStaticTableSchemaBuilder_fromEnhancedType() { StaticTableSchema.Builder<FakeItem> builder = TableSchema.builder(EnhancedType.of(FakeItem.class)); assertThat(builder).isNotNull(); } @Test public void builder_constructsStaticImmutableTableSchemaBuilder_fromClass() { StaticImmutableTableSchema.Builder<SimpleImmutable, SimpleImmutable.Builder> builder = TableSchema.builder(SimpleImmutable.class, SimpleImmutable.Builder.class); assertThat(builder).isNotNull(); } @Test public void builder_constructsStaticImmutableTableSchemaBuilder_fromEnhancedType() { StaticImmutableTableSchema.Builder<SimpleImmutable, SimpleImmutable.Builder> builder = TableSchema.builder(EnhancedType.of(SimpleImmutable.class), EnhancedType.of(SimpleImmutable.Builder.class)); assertThat(builder).isNotNull(); } @Test public void fromBean_constructsBeanTableSchema() { BeanTableSchema<SimpleBean> beanBeanTableSchema = TableSchema.fromBean(SimpleBean.class); assertThat(beanBeanTableSchema).isNotNull(); } @Test public void fromImmutable_constructsImmutableTableSchema() { ImmutableTableSchema<SimpleImmutable> immutableTableSchema = TableSchema.fromImmutableClass(SimpleImmutable.class); assertThat(immutableTableSchema).isNotNull(); } @Test public void fromClass_constructsBeanTableSchema() { TableSchema<SimpleBean> tableSchema = TableSchema.fromClass(SimpleBean.class); assertThat(tableSchema).isInstanceOf(BeanTableSchema.class); } @Test public void fromClass_constructsImmutableTableSchema() { TableSchema<SimpleImmutable> tableSchema = TableSchema.fromClass(SimpleImmutable.class); assertThat(tableSchema).isInstanceOf(ImmutableTableSchema.class); } @Test public void fromClass_invalidClassThrowsException() { exception.expect(IllegalArgumentException.class); exception.expectMessage("InvalidBean"); TableSchema.fromClass(InvalidBean.class); } }
4,108
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/EnhancedTypeTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.Collection; import java.util.Deque; import java.util.List; import java.util.Map; import java.util.NavigableMap; import java.util.NavigableSet; import java.util.SortedMap; import java.util.SortedSet; import java.util.concurrent.ConcurrentMap; import org.junit.jupiter.api.Test; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema; public class EnhancedTypeTest { @Test public void anonymousCreationCapturesComplexTypeArguments() { EnhancedType<Map<String, List<List<String>>>> enhancedType = new EnhancedType<Map<String, List<List<String>>>>(){}; assertThat(enhancedType.rawClass()).isEqualTo(Map.class); assertThat(enhancedType.rawClassParameters().get(0).rawClass()).isEqualTo(String.class); assertThat(enhancedType.rawClassParameters().get(1).rawClass()).isEqualTo(List.class); assertThat(enhancedType.rawClassParameters().get(1).rawClassParameters().get(0).rawClass()).isEqualTo(List.class); assertThat(enhancedType.rawClassParameters().get(1).rawClassParameters().get(0).rawClassParameters().get(0).rawClass()) .isEqualTo(String.class); } @Test public void customTypesWork() { EnhancedType<EnhancedTypeTest> enhancedType = new EnhancedType<EnhancedTypeTest>(){}; assertThat(enhancedType.rawClass()).isEqualTo(EnhancedTypeTest.class); } @Test public void nonStaticInnerTypesWork() { EnhancedType<InnerType> enhancedType = new EnhancedType<InnerType>(){}; assertThat(enhancedType.rawClass()).isEqualTo(InnerType.class); } @Test public void staticInnerTypesWork() { EnhancedType<InnerStaticType> enhancedType = new EnhancedType<InnerStaticType>(){}; assertThat(enhancedType.rawClass()).isEqualTo(InnerStaticType.class); } @Test public <T> void genericParameterTypesDontWork() { assertThatThrownBy(() -> new EnhancedType<List<T>>(){}).isInstanceOf(IllegalStateException.class); } @Test public void helperCreationMethodsWork() { assertThat(EnhancedType.of(String.class).rawClass()).isEqualTo(String.class); assertThat(EnhancedType.listOf(String.class)).satisfies(v -> { assertThat(v.rawClass()).isEqualTo(List.class); assertThat(v.rawClassParameters()).hasSize(1); assertThat(v.rawClassParameters().get(0).rawClass()).isEqualTo(String.class); }); assertThat(EnhancedType.mapOf(String.class, Integer.class)).satisfies(v -> { assertThat(v.rawClass()).isEqualTo(Map.class); assertThat(v.rawClassParameters()).hasSize(2); assertThat(v.rawClassParameters().get(0).rawClass()).isEqualTo(String.class); assertThat(v.rawClassParameters().get(1).rawClass()).isEqualTo(Integer.class); }); } @Test public void equalityIsBasedOnInnerEquality() { verifyEquals(EnhancedType.of(String.class), EnhancedType.of(String.class)); verifyNotEquals(EnhancedType.of(String.class), EnhancedType.of(Integer.class)); verifyEquals(new EnhancedType<Map<String, List<String>>>(){}, new EnhancedType<Map<String, List<String>>>(){}); verifyNotEquals(new EnhancedType<Map<String, List<String>>>(){}, new EnhancedType<Map<String, List<Integer>>>(){}); TableSchema<String> tableSchema = StaticTableSchema.builder(String.class).build(); verifyNotEquals(EnhancedType.documentOf(String.class, tableSchema, b -> b.ignoreNulls(false)), EnhancedType.documentOf(String.class, tableSchema, b -> b.ignoreNulls(true))); verifyEquals(EnhancedType.documentOf(String.class, tableSchema, b -> b.ignoreNulls(false).preserveEmptyObject(true)), EnhancedType.documentOf(String.class, tableSchema, b -> b.ignoreNulls(false).preserveEmptyObject(true))); } @Test public void dequeOf_ReturnsRawClassOfDeque_WhenSpecifyingClass() { EnhancedType<Deque<String>> type = EnhancedType.dequeOf(String.class); assertThat(type.rawClass()).isEqualTo(Deque.class); assertThat(type.rawClassParameters()).containsExactly(EnhancedType.of(String.class)); } @Test public void dequeOf_ReturnsRawClassOfDeque_WhenSpecifyingEnhancedType() { EnhancedType<Deque<String>> type = EnhancedType.dequeOf(EnhancedType.of(String.class)); assertThat(type.rawClass()).isEqualTo(Deque.class); assertThat(type.rawClassParameters()).containsExactly(EnhancedType.of(String.class)); } @Test public void sortedSetOf_ReturnsRawClassOfDeque_WhenSpecifyingClass() { EnhancedType<SortedSet<String>> type = EnhancedType.sortedSetOf(String.class); assertThat(type.rawClass()).isEqualTo(SortedSet.class); assertThat(type.rawClassParameters()).containsExactly(EnhancedType.of(String.class)); } @Test public void sortedSetOf_ReturnsRawClassOfDeque_WhenSpecifyingEnhancedType() { EnhancedType<SortedSet<String>> type = EnhancedType.sortedSetOf(EnhancedType.of(String.class)); assertThat(type.rawClass()).isEqualTo(SortedSet.class); assertThat(type.rawClassParameters()).containsExactly(EnhancedType.of(String.class)); } @Test public void navigableSetOf_ReturnsRawClassOfNavigableSet_WhenSpecifyingClass() { EnhancedType<NavigableSet<String>> type = EnhancedType.navigableSetOf(String.class); assertThat(type.rawClass()).isEqualTo(NavigableSet.class); assertThat(type.rawClassParameters()).containsExactly(EnhancedType.of(String.class)); } @Test public void navigableSetOf_ReturnsRawClassOfNavigableSet_WhenSpecifyingEnhancedType() { EnhancedType<NavigableSet<String>> type = EnhancedType.navigableSetOf(EnhancedType.of(String.class)); assertThat(type.rawClass()).isEqualTo(NavigableSet.class); assertThat(type.rawClassParameters()).containsExactly(EnhancedType.of(String.class)); } @Test public void collectionOf_ReturnsRawClassOfCollection_WhenSpecifyingClass() { EnhancedType<Collection<String>> type = EnhancedType.collectionOf(String.class); assertThat(type.rawClass()).isEqualTo(Collection.class); assertThat(type.rawClassParameters()).containsExactly(EnhancedType.of(String.class)); } @Test public void collectionOf_ReturnsRawClassOfCollection_WhenSpecifyingEnhancedType() { EnhancedType<Collection<String>> type = EnhancedType.collectionOf(EnhancedType.of(String.class)); assertThat(type.rawClass()).isEqualTo(Collection.class); assertThat(type.rawClassParameters()).containsExactly(EnhancedType.of(String.class)); } @Test public void sortedMapOf_ReturnsRawClassOfSortedMap_WhenSpecifyingClass() { EnhancedType<SortedMap<String, Integer>> type = EnhancedType.sortedMapOf(String.class, Integer.class); assertThat(type.rawClass()).isEqualTo(SortedMap.class); assertThat(type.rawClassParameters()).containsExactly(EnhancedType.of(String.class), EnhancedType.of(Integer.class)); } @Test public void sortedMapOf_ReturnsRawClassOfSortedMap_WhenSpecifyingEnhancedType() { EnhancedType<SortedMap<String, Integer>> type = EnhancedType.sortedMapOf(EnhancedType.of(String.class), EnhancedType.of(Integer.class)); assertThat(type.rawClass()).isEqualTo(SortedMap.class); assertThat(type.rawClassParameters()).containsExactly(EnhancedType.of(String.class), EnhancedType.of(Integer.class)); } @Test public void concurrentMapOf_ReturnsRawClassOfConcurrentMap_WhenSpecifyingClass() { EnhancedType<ConcurrentMap<String, Integer>> type = EnhancedType.concurrentMapOf(String.class, Integer.class); assertThat(type.rawClass()).isEqualTo(ConcurrentMap.class); assertThat(type.rawClassParameters()).containsExactly(EnhancedType.of(String.class), EnhancedType.of(Integer.class)); } @Test public void concurrentMapOf_ReturnsRawClassOfConcurrentMap_WhenSpecifyingEnhancedType() { EnhancedType<ConcurrentMap<String, Integer>> type = EnhancedType.concurrentMapOf(EnhancedType.of(String.class), EnhancedType.of(Integer.class)); assertThat(type.rawClass()).isEqualTo(ConcurrentMap.class); assertThat(type.rawClassParameters()).containsExactly(EnhancedType.of(String.class), EnhancedType.of(Integer.class)); } @Test public void navigableMapOf_ReturnsRawClassOfNavigableMap_WhenSpecifyingClass() { EnhancedType<NavigableMap<String, Integer>> type = EnhancedType.navigableMapOf(String.class, Integer.class); assertThat(type.rawClass()).isEqualTo(NavigableMap.class); assertThat(type.rawClassParameters()).containsExactly(EnhancedType.of(String.class), EnhancedType.of(Integer.class)); } @Test public void navigableMapOf_ReturnsRawClassOfNavigableMap_WhenSpecifyingEnhancedType() { EnhancedType<NavigableMap<String, Integer>> type = EnhancedType.navigableMapOf(EnhancedType.of(String.class), EnhancedType.of(Integer.class)); assertThat(type.rawClass()).isEqualTo(NavigableMap.class); assertThat(type.rawClassParameters()).containsExactly(EnhancedType.of(String.class), EnhancedType.of(Integer.class)); } @Test public void documentOf_toString_doesNotRaiseNPE() { TableSchema<String> tableSchema = StaticTableSchema.builder(String.class).build(); EnhancedType<String> type = EnhancedType.documentOf(String.class, tableSchema); assertThatCode(() -> type.toString()).doesNotThrowAnyException(); } @Test public void documentOf_withEnhancedTypeConfiguration() { TableSchema<String> tableSchema = StaticTableSchema.builder(String.class).build(); EnhancedType<String> type = EnhancedType.documentOf(String.class, tableSchema, b -> b.preserveEmptyObject(true)); assertThat(type.documentConfiguration()).isPresent(); assertThat(type.documentConfiguration().get().preserveEmptyObject()).isTrue(); } public class InnerType { } public static class InnerStaticType { } private void verifyEquals(Object obj1, Object obj2) { assertThat(obj1).isEqualTo(obj2); assertThat(obj1.hashCode()).isEqualTo(obj2.hashCode()); } private void verifyNotEquals(Object obj1, Object obj2) { assertThat(obj1).isNotEqualTo(obj2); assertThat(obj1.hashCode()).isNotEqualTo(obj2.hashCode()); } }
4,109
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/update/DeleteActionTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.update; import static org.assertj.core.api.Assertions.assertThat; import java.util.Collections; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; class DeleteActionTest { private static final String PATH = "path string"; private static final String VALUE = "value string"; private static final String VALUE_TOKEN = ":valueToken"; private static final String ATTRIBUTE_TOKEN = "#attributeToken"; private static final String ATTRIBUTE_NAME = "attribute1"; private static final AttributeValue NUMERIC_VALUE = AttributeValue.builder().n("5").build(); @Test void equalsHashcode() { EqualsVerifier.forClass(DeleteAction.class) .usingGetClass() .withPrefabValues(AttributeValue.class, AttributeValue.builder().s("1").build(), AttributeValue.builder().s("2").build()) .verify(); } @Test void build_minimal() { DeleteAction action = DeleteAction.builder() .path(PATH) .value(VALUE) .putExpressionValue(VALUE_TOKEN, NUMERIC_VALUE) .build(); assertThat(action.path()).isEqualTo(PATH); assertThat(action.value()).isEqualTo(VALUE); assertThat(action.expressionValues()).containsEntry(VALUE_TOKEN, NUMERIC_VALUE); assertThat(action.expressionNames()).isEmpty(); } @Test void build_maximal() { DeleteAction action = DeleteAction.builder() .path(PATH) .value(VALUE) .expressionValues(Collections.singletonMap(VALUE_TOKEN, NUMERIC_VALUE)) .expressionNames(Collections.singletonMap(ATTRIBUTE_TOKEN, ATTRIBUTE_NAME)) .build(); assertThat(action.path()).isEqualTo(PATH); assertThat(action.value()).isEqualTo(VALUE); assertThat(action.expressionValues()).containsEntry(VALUE_TOKEN, NUMERIC_VALUE); assertThat(action.expressionNames()).containsEntry(ATTRIBUTE_TOKEN, ATTRIBUTE_NAME); } @Test void copy() { DeleteAction action = DeleteAction.builder() .path(PATH) .value(VALUE) .expressionValues(Collections.singletonMap(VALUE_TOKEN, NUMERIC_VALUE)) .expressionNames(Collections.singletonMap(ATTRIBUTE_TOKEN, ATTRIBUTE_NAME)) .build(); DeleteAction copy = action.toBuilder().build(); assertThat(action).isEqualTo(copy); } }
4,110
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/update/UpdateExpressionTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.update; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.Arrays; import java.util.List; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; class UpdateExpressionTest { private static final AttributeValue VAL = AttributeValue.builder().n("5").build(); private static final RemoveAction removeAction = RemoveAction.builder().path("").build(); private static final SetAction setAction = SetAction.builder() .path("") .value("") .putExpressionValue("", VAL) .build(); private static final DeleteAction deleteAction = DeleteAction.builder() .path("") .value("") .putExpressionValue("", VAL) .build(); private static final AddAction addAction = AddAction.builder() .path("") .value("") .putExpressionValue("", VAL) .build(); @Test void equalsHashcode() { EqualsVerifier.forClass(UpdateExpression.class) .withPrefabValues(AttributeValue.class, AttributeValue.builder().s("1").build(), AttributeValue.builder().s("2").build()) .verify(); } @Test void build_minimal() { UpdateExpression updateExpression = UpdateExpression.builder().build(); assertThat(updateExpression.removeActions()).isEmpty(); assertThat(updateExpression.setActions()).isEmpty(); assertThat(updateExpression.deleteActions()).isEmpty(); assertThat(updateExpression.addActions()).isEmpty(); } @Test void build_maximal_single() { UpdateExpression updateExpression = UpdateExpression.builder() .addAction(removeAction) .addAction(setAction) .addAction(deleteAction) .addAction(addAction) .build(); assertThat(updateExpression.removeActions()).containsExactly(removeAction); assertThat(updateExpression.setActions()).containsExactly(setAction); assertThat(updateExpression.deleteActions()).containsExactly(deleteAction); assertThat(updateExpression.addActions()).containsExactly(addAction); } @Test void build_maximal_plural() { UpdateExpression updateExpression = UpdateExpression.builder() .actions(removeAction, setAction, deleteAction, addAction) .build(); assertThat(updateExpression.removeActions()).containsExactly(removeAction); assertThat(updateExpression.setActions()).containsExactly(setAction); assertThat(updateExpression.deleteActions()).containsExactly(deleteAction); assertThat(updateExpression.addActions()).containsExactly(addAction); } @Test void build_plural_is_not_additive() { List<RemoveAction> removeActions = Arrays.asList(removeAction, removeAction); UpdateExpression updateExpression = UpdateExpression.builder() .actions(removeActions) .actions(setAction, deleteAction, addAction) .build(); assertThat(updateExpression.removeActions()).isEmpty(); assertThat(updateExpression.setActions()).containsExactly(setAction); assertThat(updateExpression.deleteActions()).containsExactly(deleteAction); assertThat(updateExpression.addActions()).containsExactly(addAction); } @Test void unknown_action_generates_error() { assertThatThrownBy(() -> UpdateExpression.builder().actions(new UnknownUpdateAction()).build()) .hasMessageContaining("Do not recognize UpdateAction") .hasMessageContaining("UnknownUpdateAction"); } @Test void merge_null_expression() { UpdateExpression updateExpression = UpdateExpression.builder() .actions(removeAction, setAction, deleteAction, addAction) .build(); UpdateExpression result = UpdateExpression.mergeExpressions(updateExpression, null); assertThat(result.removeActions()).containsExactly(removeAction); assertThat(result.setActions()).containsExactly(setAction); assertThat(result.deleteActions()).containsExactly(deleteAction); assertThat(result.addActions()).containsExactly(addAction); } @Test void merge_empty_expression() { UpdateExpression updateExpression = UpdateExpression.builder() .actions(removeAction, setAction, deleteAction, addAction) .build(); UpdateExpression result = UpdateExpression.mergeExpressions(updateExpression, UpdateExpression.builder().build()); assertThat(result.removeActions()).containsExactly(removeAction); assertThat(result.setActions()).containsExactly(setAction); assertThat(result.deleteActions()).containsExactly(deleteAction); assertThat(result.addActions()).containsExactly(addAction); } @Test void merge_expression_with_one_action_type() { UpdateExpression updateExpression = UpdateExpression.builder() .actions(removeAction, setAction, deleteAction, addAction) .build(); RemoveAction extraRemoveAction = RemoveAction.builder().path("a").build(); UpdateExpression additionalExpression = UpdateExpression.builder() .addAction(extraRemoveAction) .build(); UpdateExpression result = UpdateExpression.mergeExpressions(updateExpression, additionalExpression); assertThat(result.removeActions()).containsExactly(removeAction, extraRemoveAction); assertThat(result.setActions()).containsExactly(setAction); assertThat(result.deleteActions()).containsExactly(deleteAction); assertThat(result.addActions()).containsExactly(addAction); } @Test void merge_expression_with_all_action_types() { UpdateExpression updateExpression = UpdateExpression.builder() .actions(removeAction, setAction, deleteAction, addAction) .build(); RemoveAction extraRemoveAction = RemoveAction.builder().path("a").build(); SetAction extraSetAction = SetAction.builder().path("").value("").putExpressionValue("", VAL).build(); DeleteAction extraDeleteAction = DeleteAction.builder().path("").value("").putExpressionValue("", VAL).build(); AddAction extraAddAction = AddAction.builder().path("").value("").putExpressionValue("", VAL).build(); UpdateExpression additionalExpression = UpdateExpression.builder() .actions(extraRemoveAction, extraSetAction, extraDeleteAction, extraAddAction) .build(); UpdateExpression result = UpdateExpression.mergeExpressions(updateExpression, additionalExpression); assertThat(result.removeActions()).containsExactly(removeAction, extraRemoveAction); assertThat(result.setActions()).containsExactly(setAction, extraSetAction); assertThat(result.deleteActions()).containsExactly(deleteAction, extraDeleteAction); assertThat(result.addActions()).containsExactly(addAction, extraAddAction); } private static final class UnknownUpdateAction implements UpdateAction { } }
4,111
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/update/AddActionTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.update; import static org.assertj.core.api.Assertions.assertThat; import java.util.Collections; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; class AddActionTest { private static final String PATH = "path string"; private static final String VALUE = "value string"; private static final String VALUE_TOKEN = ":valueToken"; private static final String ATTRIBUTE_TOKEN = "#attributeToken"; private static final String ATTRIBUTE_NAME = "attribute1"; private static final AttributeValue NUMERIC_VALUE = AttributeValue.builder().n("5").build(); @Test void equalsHashcode() { EqualsVerifier.forClass(AddAction.class) .usingGetClass() .withPrefabValues(AttributeValue.class, AttributeValue.builder().s("1").build(), AttributeValue.builder().s("2").build()) .verify(); } @Test void build_minimal() { AddAction action = AddAction.builder() .path(PATH) .value(VALUE) .putExpressionValue(VALUE_TOKEN, NUMERIC_VALUE) .build(); assertThat(action.path()).isEqualTo(PATH); assertThat(action.value()).isEqualTo(VALUE); assertThat(action.expressionValues()).containsEntry(VALUE_TOKEN, NUMERIC_VALUE); assertThat(action.expressionNames()).isEmpty(); } @Test void build_maximal() { AddAction action = AddAction.builder() .path(PATH) .value(VALUE) .expressionValues(Collections.singletonMap(VALUE_TOKEN, NUMERIC_VALUE)) .expressionNames(Collections.singletonMap(ATTRIBUTE_TOKEN, ATTRIBUTE_NAME)) .build(); assertThat(action.path()).isEqualTo(PATH); assertThat(action.value()).isEqualTo(VALUE); assertThat(action.expressionValues()).containsEntry(VALUE_TOKEN, NUMERIC_VALUE); assertThat(action.expressionNames()).containsEntry(ATTRIBUTE_TOKEN, ATTRIBUTE_NAME); } @Test void copy() { AddAction action = AddAction.builder() .path(PATH) .value(VALUE) .expressionValues(Collections.singletonMap(VALUE_TOKEN, NUMERIC_VALUE)) .expressionNames(Collections.singletonMap(ATTRIBUTE_TOKEN, ATTRIBUTE_NAME)) .build(); AddAction copy = action.toBuilder().build(); assertThat(action).isEqualTo(copy); } }
4,112
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/update/SetActionTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.update; import static org.assertj.core.api.Assertions.assertThat; import java.util.Collections; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; class SetActionTest { private static final String PATH = "path string"; private static final String VALUE = "value string"; private static final String VALUE_TOKEN = ":valueToken"; private static final String ATTRIBUTE_TOKEN = "#attributeToken"; private static final String ATTRIBUTE_NAME = "attribute1"; private static final AttributeValue NUMERIC_VALUE = AttributeValue.builder().n("5").build(); @Test void equalsHashcode() { EqualsVerifier.forClass(SetAction.class) .usingGetClass() .withPrefabValues(AttributeValue.class, AttributeValue.builder().s("1").build(), AttributeValue.builder().s("2").build()) .verify(); } @Test void build_minimal() { SetAction action = SetAction.builder() .path(PATH) .value(VALUE) .putExpressionValue(VALUE_TOKEN, NUMERIC_VALUE) .build(); assertThat(action.path()).isEqualTo(PATH); assertThat(action.value()).isEqualTo(VALUE); assertThat(action.expressionValues()).containsEntry(VALUE_TOKEN, NUMERIC_VALUE); assertThat(action.expressionNames()).isEmpty(); } @Test void build_maximal() { SetAction action = SetAction.builder() .path(PATH) .value(VALUE) .expressionValues(Collections.singletonMap(VALUE_TOKEN, NUMERIC_VALUE)) .expressionNames(Collections.singletonMap(ATTRIBUTE_TOKEN, ATTRIBUTE_NAME)) .build(); assertThat(action.path()).isEqualTo(PATH); assertThat(action.value()).isEqualTo(VALUE); assertThat(action.expressionValues()).containsEntry(VALUE_TOKEN, NUMERIC_VALUE); assertThat(action.expressionNames()).containsEntry(ATTRIBUTE_TOKEN, ATTRIBUTE_NAME); } @Test void copy() { SetAction action = SetAction.builder() .path(PATH) .value(VALUE) .expressionValues(Collections.singletonMap(VALUE_TOKEN, NUMERIC_VALUE)) .expressionNames(Collections.singletonMap(ATTRIBUTE_TOKEN, ATTRIBUTE_NAME)) .build(); SetAction copy = action.toBuilder().build(); assertThat(action).isEqualTo(copy); } }
4,113
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/update/RemoveActionTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.update; import static org.assertj.core.api.Assertions.assertThat; import java.util.Collections; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; class RemoveActionTest { private static final String PATH = "path string"; private static final String ATTRIBUTE_TOKEN = "#attributeToken"; private static final String ATTRIBUTE_NAME = "attribute1"; @Test void equalsHashcode() { EqualsVerifier.forClass(RemoveAction.class) .usingGetClass() .verify(); } @Test void build_minimal() { RemoveAction action = RemoveAction.builder() .path(PATH) .build(); assertThat(action.path()).isEqualTo(PATH); assertThat(action.expressionNames()).isEmpty(); } @Test void build_maximal() { RemoveAction action = RemoveAction.builder() .path(PATH) .expressionNames(Collections.singletonMap(ATTRIBUTE_TOKEN, ATTRIBUTE_NAME)) .build(); assertThat(action.path()).isEqualTo(PATH); assertThat(action.expressionNames()).containsEntry(ATTRIBUTE_TOKEN, ATTRIBUTE_NAME); } @Test void copy() { RemoveAction action = RemoveAction.builder() .path(PATH) .expressionNames(Collections.singletonMap(ATTRIBUTE_TOKEN, ATTRIBUTE_NAME)) .build(); RemoveAction copy = action.toBuilder().build(); assertThat(action).isEqualTo(copy); } }
4,114
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/AsyncUpdateItemWithResponseTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests; import static org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey; import java.util.Objects; import org.junit.After; import org.junit.Before; import org.junit.Test; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbAsyncTable; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedAsyncClient; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema; import software.amazon.awssdk.enhanced.dynamodb.model.UpdateItemEnhancedResponse; import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; import software.amazon.awssdk.services.dynamodb.model.ReturnConsumedCapacity; public class AsyncUpdateItemWithResponseTest extends LocalDynamoDbAsyncTestBase { private static class Record { private Integer id; private String stringAttr1; private Integer getId() { return id; } private Record setId(Integer id) { this.id = id; return this; } private String getStringAttr1() { return stringAttr1; } private Record setStringAttr1(String stringAttr1) { this.stringAttr1 = stringAttr1; return this; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Record record = (Record) o; return Objects.equals(id, record.id) && Objects.equals(stringAttr1, record.stringAttr1); } @Override public int hashCode() { return Objects.hash(id, stringAttr1); } } private static final TableSchema<Record> TABLE_SCHEMA = StaticTableSchema.builder(Record.class) .newItemSupplier(Record::new) .addAttribute(Integer.class, a -> a.name("id_1") .getter(Record::getId) .setter(Record::setId) .tags(primaryPartitionKey())) .addAttribute(String.class, a -> a.name("stringAttr1") .getter(Record::getStringAttr1) .setter(Record::setStringAttr1)) .build(); private DynamoDbEnhancedAsyncClient enhancedClient; private DynamoDbAsyncTable<Record> mappedTable1; @Before public void createTable() { enhancedClient = DynamoDbEnhancedAsyncClient.builder() .dynamoDbClient(getDynamoDbAsyncClient()) .build(); mappedTable1 = enhancedClient.table(getConcreteTableName("table-name-1"), TABLE_SCHEMA); mappedTable1.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput())).join(); } @After public void deleteTable() { getDynamoDbAsyncClient().deleteTable(DeleteTableRequest.builder() .tableName(getConcreteTableName("table-name-1")) .build()) .join(); } @Test public void newValuesMapped() { Record original = new Record().setId(1).setStringAttr1("attr"); mappedTable1.putItem(original).join(); Record updated = new Record().setId(1).setStringAttr1("attr2"); UpdateItemEnhancedResponse<Record> response = mappedTable1.updateItemWithResponse(r -> r.item(updated)).join(); assertThat(response.attributes()).isEqualTo(updated); } @Test public void returnConsumedCapacity_unset_consumedCapacityNull() { Record original = new Record().setId(1).setStringAttr1("attr"); mappedTable1.putItem(original).join(); Record updated = new Record().setId(1).setStringAttr1("attr2"); UpdateItemEnhancedResponse<Record> response = mappedTable1.updateItemWithResponse(r -> r.item(updated)).join(); assertThat(response.consumedCapacity()).isNull(); } @Test public void returnConsumedCapacity_set_consumedCapacityNotNull() { Record original = new Record().setId(1).setStringAttr1("attr"); mappedTable1.putItem(original).join(); Record updated = new Record().setId(1).setStringAttr1("attr2"); UpdateItemEnhancedResponse<Record> response = mappedTable1.updateItemWithResponse(r -> r.item(updated) .returnConsumedCapacity(ReturnConsumedCapacity.TOTAL)) .join(); assertThat(response.consumedCapacity()).isNotNull(); } @Test public void returnItemCollectionMetrics_unset_itemCollectionMetricsNull() { Record original = new Record().setId(1).setStringAttr1("attr"); mappedTable1.putItem(original).join(); Record updated = new Record().setId(1).setStringAttr1("attr2"); UpdateItemEnhancedResponse<Record> response = mappedTable1.updateItemWithResponse(r -> r.item(updated)).join(); assertThat(response.itemCollectionMetrics()).isNull(); } }
4,115
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/AsyncBasicQueryTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.numberValue; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.stringValue; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primarySortKey; import static software.amazon.awssdk.enhanced.dynamodb.model.QueryConditional.keyEqualTo; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.junit.After; import org.junit.Before; import org.junit.Test; import software.amazon.awssdk.core.async.SdkPublisher; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbAsyncTable; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedAsyncClient; import software.amazon.awssdk.enhanced.dynamodb.Expression; import software.amazon.awssdk.enhanced.dynamodb.Key; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.internal.client.DefaultDynamoDbEnhancedAsyncClient; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema; import software.amazon.awssdk.enhanced.dynamodb.model.Page; import software.amazon.awssdk.enhanced.dynamodb.model.QueryConditional; import software.amazon.awssdk.enhanced.dynamodb.model.QueryEnhancedRequest; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; public class AsyncBasicQueryTest extends LocalDynamoDbAsyncTestBase { private static class Record { private String id; private Integer sort; private Integer value; public String getId() { return id; } public Record setId(String id) { this.id = id; return this; } public Integer getSort() { return sort; } public Record setSort(Integer sort) { this.sort = sort; return this; } public Integer getValue() { return value; } public Record setValue(Integer value) { this.value = value; return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Record record = (Record) o; return Objects.equals(id, record.id) && Objects.equals(sort, record.sort) && Objects.equals(value, record.value); } @Override public int hashCode() { return Objects.hash(id, sort, value); } } private static final TableSchema<Record> TABLE_SCHEMA = StaticTableSchema.builder(Record.class) .newItemSupplier(Record::new) .addAttribute(String.class, a -> a.name("id") .getter(Record::getId) .setter(Record::setId) .tags(primaryPartitionKey())) .addAttribute(Integer.class, a -> a.name("sort") .getter(Record::getSort) .setter(Record::setSort) .tags(primarySortKey())) .addAttribute(Integer.class, a -> a.name("value") .getter(Record::getValue) .setter(Record::setValue)) .build(); private static final List<Record> RECORDS = IntStream.range(0, 10) .mapToObj(i -> new Record().setId("id-value").setSort(i).setValue(i)) .collect(Collectors.toList()); private DynamoDbEnhancedAsyncClient enhancedAsyncClient = DefaultDynamoDbEnhancedAsyncClient.builder() .dynamoDbClient(getDynamoDbAsyncClient()) .build(); private DynamoDbAsyncTable<Record> mappedTable = enhancedAsyncClient.table(getConcreteTableName("table-name"), TABLE_SCHEMA); private void insertRecords() { RECORDS.forEach(record -> mappedTable.putItem(r -> r.item(record)).join()); } @Before public void createTable() { mappedTable.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput())).join(); } @After public void deleteTable() { getDynamoDbAsyncClient().deleteTable(DeleteTableRequest.builder() .tableName(getConcreteTableName("table-name")) .build()) .join(); } @Test public void queryAllRecordsDefaultSettings_usingShortcutForm() { insertRecords(); SdkPublisher<Page<Record>> publisher = mappedTable.query(keyEqualTo(k -> k.partitionValue("id-value"))); List<Page<Record>> results = drainPublisher(publisher, 1); Page<Record> page = results.get(0); assertThat(page.items(), is(RECORDS)); assertThat(page.lastEvaluatedKey(), is(nullValue())); } @Test public void queryAllRecordsWithFilter() { insertRecords(); Map<String, AttributeValue> expressionValues = new HashMap<>(); expressionValues.put(":min_value", numberValue(3)); expressionValues.put(":max_value", numberValue(5)); Expression expression = Expression.builder() .expression("#value >= :min_value AND #value <= :max_value") .expressionValues(expressionValues) .expressionNames(Collections.singletonMap("#value", "value")) .build(); SdkPublisher<Page<Record>> publisher = mappedTable.query(QueryEnhancedRequest.builder() .queryConditional(keyEqualTo(k -> k.partitionValue("id-value"))) .filterExpression(expression) .build()); List<Page<Record>> results = drainPublisher(publisher, 1); Page<Record> page = results.get(0); assertThat(page.items(), is(RECORDS.stream().filter(r -> r.sort >= 3 && r.sort <= 5).collect(Collectors.toList()))); assertThat(page.lastEvaluatedKey(), is(nullValue())); } @Test public void queryAllRecordsWithFilter_viaItems() { insertRecords(); Map<String, AttributeValue> expressionValues = new HashMap<>(); expressionValues.put(":min_value", numberValue(3)); expressionValues.put(":max_value", numberValue(5)); Expression expression = Expression.builder() .expression("#value >= :min_value AND #value <= :max_value") .expressionValues(expressionValues) .expressionNames(Collections.singletonMap("#value", "value")) .build(); SdkPublisher<Record> publisher = mappedTable.query(QueryEnhancedRequest.builder() .queryConditional(keyEqualTo(k -> k.partitionValue("id-value"))) .filterExpression(expression) .build()).items(); List<Record> results = drainPublisher(publisher, 3); assertThat(results, is(RECORDS.stream().filter(r -> r.sort >= 3 && r.sort <= 5).collect(Collectors.toList()))); } @Test public void queryBetween() { insertRecords(); Key fromKey = Key.builder().partitionValue("id-value").sortValue(3).build(); Key toKey = Key.builder().partitionValue("id-value").sortValue(5).build(); SdkPublisher<Page<Record>> publisher = mappedTable.query(r -> r.queryConditional(QueryConditional.sortBetween(fromKey, toKey))); List<Page<Record>> results = drainPublisher(publisher, 1); Page<Record> page = results.get(0); assertThat(page.items(), is(RECORDS.stream().filter(r -> r.sort >= 3 && r.sort <= 5).collect(Collectors.toList()))); assertThat(page.lastEvaluatedKey(), is(nullValue())); } @Test public void queryBetween_viaItems() { insertRecords(); Key fromKey = Key.builder().partitionValue("id-value").sortValue(3).build(); Key toKey = Key.builder().partitionValue("id-value").sortValue(5).build(); SdkPublisher<Record> publisher = mappedTable.query(r -> r.queryConditional(QueryConditional.sortBetween(fromKey, toKey))).items(); List<Record> results = drainPublisher(publisher, 3); assertThat(results, is(RECORDS.stream().filter(r -> r.sort >= 3 && r.sort <= 5).collect(Collectors.toList()))); } @Test public void queryLimit() { insertRecords(); SdkPublisher<Page<Record>> publisher = mappedTable.query(QueryEnhancedRequest.builder() .queryConditional(keyEqualTo(k -> k.partitionValue("id-value"))) .limit(5) .build()); List<Page<Record>> results = drainPublisher(publisher, 3); Page<Record> page1 = results.get(0); Page<Record> page2 = results.get(1); Page<Record> page3 = results.get(2); Map<String, AttributeValue> expectedLastEvaluatedKey1 = new HashMap<>(); expectedLastEvaluatedKey1.put("id", stringValue("id-value")); expectedLastEvaluatedKey1.put("sort", numberValue(4)); Map<String, AttributeValue> expectedLastEvaluatedKey2 = new HashMap<>(); expectedLastEvaluatedKey2.put("id", stringValue("id-value")); expectedLastEvaluatedKey2.put("sort", numberValue(9)); assertThat(page1.items(), is(RECORDS.subList(0, 5))); assertThat(page1.lastEvaluatedKey(), is(expectedLastEvaluatedKey1)); assertThat(page2.items(), is(RECORDS.subList(5, 10))); assertThat(page2.lastEvaluatedKey(), is(expectedLastEvaluatedKey2)); assertThat(page3.items(), is(empty())); assertThat(page3.lastEvaluatedKey(), is(nullValue())); } @Test public void queryLimit_viaItems() { insertRecords(); SdkPublisher<Record> publisher = mappedTable.query(QueryEnhancedRequest.builder() .queryConditional(keyEqualTo(k -> k.partitionValue("id-value"))) .limit(5) .build()) .items(); List<Record> results = drainPublisher(publisher, 10); assertThat(results, is(RECORDS)); } @Test public void queryEmpty() { SdkPublisher<Page<Record>> publisher = mappedTable.query(r -> r.queryConditional(keyEqualTo(k -> k.partitionValue("id-value")))); List<Page<Record>> results = drainPublisher(publisher, 1); Page<Record> page = results.get(0); assertThat(page.items(), is(empty())); assertThat(page.lastEvaluatedKey(), is(nullValue())); } @Test public void queryEmpty_viaItems() { SdkPublisher<Record> publisher = mappedTable.query(r -> r.queryConditional(keyEqualTo(k -> k.partitionValue("id-value")))).items(); List<Record> results = drainPublisher(publisher, 0); assertThat(results, is(empty())); } @Test public void queryExclusiveStartKey() { Map<String, AttributeValue> exclusiveStartKey = new HashMap<>(); exclusiveStartKey.put("id", stringValue("id-value")); exclusiveStartKey.put("sort", numberValue(7)); insertRecords(); SdkPublisher<Page<Record>> publisher = mappedTable.query(QueryEnhancedRequest.builder() .queryConditional(keyEqualTo(k -> k.partitionValue("id-value"))) .exclusiveStartKey(exclusiveStartKey) .build()); List<Page<Record>> results = drainPublisher(publisher, 1); Page<Record> page = results.get(0); assertThat(page.items(), is(RECORDS.subList(8, 10))); assertThat(page.lastEvaluatedKey(), is(nullValue())); } }
4,116
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/EmptyBinaryTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests; import static java.util.Collections.singletonMap; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.HashMap; import java.util.Map; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.Expression; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.GetItemRequest; import software.amazon.awssdk.services.dynamodb.model.GetItemResponse; import software.amazon.awssdk.services.dynamodb.model.PutItemRequest; import software.amazon.awssdk.services.dynamodb.model.PutItemResponse; import software.amazon.awssdk.services.dynamodb.model.ReturnValue; import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest; import software.amazon.awssdk.services.dynamodb.model.UpdateItemResponse; @RunWith(MockitoJUnitRunner.class) public class EmptyBinaryTest { private static final String TABLE_NAME = "TEST_TABLE"; private static final SdkBytes EMPTY_BYTES = SdkBytes.fromUtf8String(""); private static final AttributeValue EMPTY_BINARY = AttributeValue.builder().b(EMPTY_BYTES).build(); @Mock private DynamoDbClient mockDynamoDbClient; private DynamoDbTable<TestBean> dynamoDbTable; @DynamoDbBean public static class TestBean { private String id; private SdkBytes b; @DynamoDbPartitionKey public String getId() { return id; } public void setId(String id) { this.id = id; } public SdkBytes getB() { return b; } public void setB(SdkBytes b) { this.b = b; } } private static final TableSchema<TestBean> TABLE_SCHEMA = TableSchema.fromClass(TestBean.class); @Before public void initializeTable() { DynamoDbEnhancedClient dynamoDbEnhancedClient = DynamoDbEnhancedClient.builder() .dynamoDbClient(mockDynamoDbClient) .build(); this.dynamoDbTable = dynamoDbEnhancedClient.table(TABLE_NAME, TABLE_SCHEMA); } @Test public void putEmptyBytes() { TestBean testBean = new TestBean(); testBean.setId("id123"); testBean.setB(EMPTY_BYTES); PutItemResponse response = PutItemResponse.builder().build(); when(mockDynamoDbClient.putItem(any(PutItemRequest.class))).thenReturn(response); 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); } @Test public void getEmptyBytes() { Map<String, AttributeValue> itemMap = new HashMap<>(); itemMap.put("id", AttributeValue.builder().s("id123").build()); itemMap.put("b", EMPTY_BINARY); GetItemResponse response = GetItemResponse.builder() .item(itemMap) .build(); when(mockDynamoDbClient.getItem(any(GetItemRequest.class))).thenReturn(response); TestBean result = dynamoDbTable.getItem(r -> r.key(k -> k.partitionValue("id123"))); assertThat(result.getId()).isEqualTo("id123"); assertThat(result.getB()).isEqualTo(EMPTY_BYTES); } @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); } }
4,117
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/IndexScanTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.numberValue; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.stringValue; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primarySortKey; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.secondaryPartitionKey; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.secondarySortKey; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.junit.After; import org.junit.Before; import org.junit.Test; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbIndex; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.Expression; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema; import software.amazon.awssdk.enhanced.dynamodb.model.EnhancedGlobalSecondaryIndex; import software.amazon.awssdk.enhanced.dynamodb.model.Page; import software.amazon.awssdk.enhanced.dynamodb.model.ScanEnhancedRequest; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; import software.amazon.awssdk.services.dynamodb.model.ProjectionType; import software.amazon.awssdk.services.dynamodb.model.ReturnConsumedCapacity; public class IndexScanTest extends LocalDynamoDbSyncTestBase { private static class Record { private String id; private Integer sort; private Integer value; private String gsiId; private Integer gsiSort; private String getId() { return id; } private Record setId(String id) { this.id = id; return this; } private Integer getSort() { return sort; } private Record setSort(Integer sort) { this.sort = sort; return this; } private Integer getValue() { return value; } private Record setValue(Integer value) { this.value = value; return this; } private String getGsiId() { return gsiId; } private Record setGsiId(String gsiId) { this.gsiId = gsiId; return this; } private Integer getGsiSort() { return gsiSort; } private Record setGsiSort(Integer gsiSort) { this.gsiSort = gsiSort; return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Record record = (Record) o; return Objects.equals(id, record.id) && Objects.equals(sort, record.sort) && Objects.equals(value, record.value) && Objects.equals(gsiId, record.gsiId) && Objects.equals(gsiSort, record.gsiSort); } @Override public int hashCode() { return Objects.hash(id, sort, value, gsiId, gsiSort); } } private static final TableSchema<Record> TABLE_SCHEMA = StaticTableSchema.builder(Record.class) .newItemSupplier(Record::new) .addAttribute(String.class, a -> a.name("id") .getter(Record::getId) .setter(Record::setId) .tags(primaryPartitionKey())) .addAttribute(Integer.class, a -> a.name("sort") .getter(Record::getSort) .setter(Record::setSort) .tags(primarySortKey())) .addAttribute(Integer.class, a -> a.name("value") .getter(Record::getValue) .setter(Record::setValue)) .addAttribute(String.class, a -> a.name("gsi_id") .getter(Record::getGsiId) .setter(Record::setGsiId) .tags(secondaryPartitionKey("gsi_keys_only"))) .addAttribute(Integer.class, a -> a.name("gsi_sort") .getter(Record::getGsiSort) .setter(Record::setGsiSort) .tags(secondarySortKey("gsi_keys_only"))) .build(); private static final List<Record> RECORDS = IntStream.range(0, 10) .mapToObj(i -> new Record() .setId("id-value") .setSort(i) .setValue(i) .setGsiId("gsi-id-value") .setGsiSort(i)) .collect(Collectors.toList()); private static final List<Record> KEYS_ONLY_RECORDS = RECORDS.stream() .map(record -> new Record() .setId(record.id) .setSort(record.sort) .setGsiId(record.gsiId) .setGsiSort(record.gsiSort)) .collect(Collectors.toList()); private DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() .dynamoDbClient(getDynamoDbClient()) .build(); private DynamoDbTable<Record> mappedTable = enhancedClient.table(getConcreteTableName("table-name"), TABLE_SCHEMA); private DynamoDbIndex<Record> keysOnlyMappedIndex = mappedTable.index("gsi_keys_only"); private void insertRecords() { RECORDS.forEach(record -> mappedTable.putItem(r -> r.item(record))); } @Before public void createTable() { mappedTable.createTable( r -> r.provisionedThroughput(getDefaultProvisionedThroughput()) .globalSecondaryIndices( EnhancedGlobalSecondaryIndex.builder() .indexName("gsi_keys_only") .projection(p -> p.projectionType(ProjectionType.KEYS_ONLY)) .provisionedThroughput(getDefaultProvisionedThroughput()) .build())); } @After public void deleteTable() { getDynamoDbClient().deleteTable(DeleteTableRequest.builder() .tableName(getConcreteTableName("table-name")) .build()); } @Test public void scanAllRecordsDefaultSettings() { insertRecords(); Iterator<Page<Record>> results = keysOnlyMappedIndex.scan(r -> r.returnConsumedCapacity(ReturnConsumedCapacity.INDEXES)) .iterator(); assertThat(results.hasNext(), is(true)); Page<Record> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items(), is(KEYS_ONLY_RECORDS)); assertThat(page.lastEvaluatedKey(), is(nullValue())); assertThat(page.consumedCapacity(), is(notNullValue())); assertThat(page.consumedCapacity().capacityUnits(), is(notNullValue())); assertThat(page.consumedCapacity().globalSecondaryIndexes(), is(notNullValue())); assertThat(page.count(), equalTo(10)); assertThat(page.scannedCount(), equalTo(10)); } @Test public void scanAllRecordsWithFilter() { insertRecords(); Map<String, AttributeValue> expressionValues = new HashMap<>(); expressionValues.put(":min_value", numberValue(3)); expressionValues.put(":max_value", numberValue(5)); Expression expression = Expression.builder() .expression("sort >= :min_value AND sort <= :max_value") .expressionValues(expressionValues) .build(); Iterator<Page<Record>> results = keysOnlyMappedIndex.scan(ScanEnhancedRequest.builder().filterExpression(expression) .returnConsumedCapacity(ReturnConsumedCapacity.INDEXES).build()) .iterator(); assertThat(results.hasNext(), is(true)); Page<Record> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items(), is(KEYS_ONLY_RECORDS.stream().filter(r -> r.sort >= 3 && r.sort <= 5).collect(Collectors.toList()))); assertThat(page.lastEvaluatedKey(), is(nullValue())); assertThat(page.consumedCapacity(), is(notNullValue())); assertThat(page.consumedCapacity().capacityUnits(), is(notNullValue())); assertThat(page.consumedCapacity().globalSecondaryIndexes(), is(notNullValue())); assertThat(page.count(), equalTo(3)); assertThat(page.scannedCount(), equalTo(10)); } @Test public void scanLimit() { insertRecords(); Iterator<Page<Record>> results = keysOnlyMappedIndex.scan(r -> r.limit(5)).iterator(); assertThat(results.hasNext(), is(true)); Page<Record> page1 = results.next(); assertThat(results.hasNext(), is(true)); Page<Record> page2 = results.next(); assertThat(results.hasNext(), is(true)); Page<Record> page3 = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page1.items(), is(KEYS_ONLY_RECORDS.subList(0, 5))); assertThat(page1.consumedCapacity(), is(nullValue())); assertThat(page1.lastEvaluatedKey(), is(getKeyMap(4))); assertThat(page1.count(), equalTo(5)); assertThat(page1.scannedCount(), equalTo(5)); assertThat(page2.items(), is(KEYS_ONLY_RECORDS.subList(5, 10))); assertThat(page2.lastEvaluatedKey(), is(getKeyMap(9))); assertThat(page2.count(), equalTo(5)); assertThat(page2.scannedCount(), equalTo(5)); assertThat(page3.items(), is(empty())); assertThat(page3.lastEvaluatedKey(), is(nullValue())); assertThat(page3.count(), equalTo(0)); assertThat(page3.scannedCount(), equalTo(0)); } @Test public void scanEmpty() { Iterator<Page<Record>> results = keysOnlyMappedIndex.scan().iterator(); assertThat(results.hasNext(), is(true)); Page<Record> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items(), is(empty())); assertThat(page.lastEvaluatedKey(), is(nullValue())); assertThat(page.count(), equalTo(0)); assertThat(page.scannedCount(), equalTo(0)); } @Test public void scanExclusiveStartKey() { insertRecords(); Iterator<Page<Record>> results = keysOnlyMappedIndex.scan(r -> r.exclusiveStartKey(getKeyMap(7))).iterator(); assertThat(results.hasNext(), is(true)); Page<Record> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items(), is(KEYS_ONLY_RECORDS.subList(8, 10))); assertThat(page.lastEvaluatedKey(), is(nullValue())); assertThat(page.count(), equalTo(2)); assertThat(page.scannedCount(), equalTo(2)); } private Map<String, AttributeValue> getKeyMap(int sort) { Map<String, AttributeValue> result = new HashMap<>(); result.put("id", stringValue(KEYS_ONLY_RECORDS.get(sort).getId())); result.put("sort", numberValue(KEYS_ONLY_RECORDS.get(sort).getSort())); result.put("gsi_id", stringValue(KEYS_ONLY_RECORDS.get(sort).getGsiId())); result.put("gsi_sort", numberValue(KEYS_ONLY_RECORDS.get(sort).getGsiSort())); return Collections.unmodifiableMap(result); } }
4,118
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/AsyncBasicCrudTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.stringValue; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primarySortKey; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.secondaryPartitionKey; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.secondarySortKey; import java.util.Objects; import java.util.concurrent.CompletionException; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbAsyncTable; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedAsyncClient; import software.amazon.awssdk.enhanced.dynamodb.Expression; import software.amazon.awssdk.enhanced.dynamodb.Key; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.internal.client.DefaultDynamoDbEnhancedAsyncClient; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema; import software.amazon.awssdk.enhanced.dynamodb.model.DeleteItemEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.EnhancedGlobalSecondaryIndex; import software.amazon.awssdk.enhanced.dynamodb.model.PutItemEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.UpdateItemEnhancedRequest; import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException; import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; import software.amazon.awssdk.services.dynamodb.model.ProjectionType; public class AsyncBasicCrudTest extends LocalDynamoDbAsyncTestBase { private static class Record { private String id; private String sort; private String attribute; private String attribute2; private String attribute3; private String getId() { return id; } private Record setId(String id) { this.id = id; return this; } private String getSort() { return sort; } private Record setSort(String sort) { this.sort = sort; return this; } private String getAttribute() { return attribute; } private Record setAttribute(String attribute) { this.attribute = attribute; return this; } private String getAttribute2() { return attribute2; } private Record setAttribute2(String attribute2) { this.attribute2 = attribute2; return this; } private String getAttribute3() { return attribute3; } private Record setAttribute3(String attribute3) { this.attribute3 = attribute3; return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Record record = (Record) o; return Objects.equals(id, record.id) && Objects.equals(sort, record.sort) && Objects.equals(attribute, record.attribute) && Objects.equals(attribute2, record.attribute2) && Objects.equals(attribute3, record.attribute3); } @Override public int hashCode() { return Objects.hash(id, sort, attribute, attribute2, attribute3); } } private static class ShortRecord { private String id; private String sort; private String attribute; private String getId() { return id; } private ShortRecord setId(String id) { this.id = id; return this; } private String getSort() { return sort; } private ShortRecord setSort(String sort) { this.sort = sort; return this; } private String getAttribute() { return attribute; } private ShortRecord setAttribute(String attribute) { this.attribute = attribute; return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ShortRecord that = (ShortRecord) o; return Objects.equals(id, that.id) && Objects.equals(sort, that.sort) && Objects.equals(attribute, that.attribute); } @Override public int hashCode() { return Objects.hash(id, sort, attribute); } } private static final TableSchema<Record> TABLE_SCHEMA = StaticTableSchema.builder(Record.class) .newItemSupplier(Record::new) .addAttribute(String.class, a -> a.name("id") .getter(Record::getId) .setter(Record::setId) .tags(primaryPartitionKey())) .addAttribute(String.class, a -> a.name("sort") .getter(Record::getSort) .setter(Record::setSort) .tags(primarySortKey())) .addAttribute(String.class, a -> a.name("attribute") .getter(Record::getAttribute) .setter(Record::setAttribute)) .addAttribute(String.class, a -> a.name("attribute2*") .getter(Record::getAttribute2) .setter(Record::setAttribute2) .tags(secondaryPartitionKey("gsi_1"))) .addAttribute(String.class, a -> a.name("attribute3") .getter(Record::getAttribute3) .setter(Record::setAttribute3) .tags(secondarySortKey("gsi_1"))) .build(); private static final TableSchema<ShortRecord> SHORT_TABLE_SCHEMA = StaticTableSchema.builder(ShortRecord.class) .newItemSupplier(ShortRecord::new) .addAttribute(String.class, a -> a.name("id") .getter(ShortRecord::getId) .setter(ShortRecord::setId) .tags(primaryPartitionKey())) .addAttribute(String.class, a -> a.name("sort") .getter(ShortRecord::getSort) .setter(ShortRecord::setSort) .tags(primarySortKey())) .addAttribute(String.class, a -> a.name("attribute") .getter(ShortRecord::getAttribute) .setter(ShortRecord::setAttribute)) .build(); private DynamoDbEnhancedAsyncClient enhancedAsyncClient = DefaultDynamoDbEnhancedAsyncClient.builder() .dynamoDbClient(getDynamoDbAsyncClient()) .build(); private DynamoDbAsyncTable<Record> mappedTable = enhancedAsyncClient.table(getConcreteTableName("table-name"), TABLE_SCHEMA); private DynamoDbAsyncTable<ShortRecord> mappedShortTable = enhancedAsyncClient.table(getConcreteTableName("table-name"), SHORT_TABLE_SCHEMA); @Rule public ExpectedException exception = ExpectedException.none(); @Before public void createTable() { mappedTable.createTable( r -> r.provisionedThroughput(getDefaultProvisionedThroughput()) .globalSecondaryIndices( EnhancedGlobalSecondaryIndex.builder() .indexName("gsi_1") .projection(p -> p.projectionType(ProjectionType.ALL)) .provisionedThroughput(getDefaultProvisionedThroughput()) .build())) .join(); } @After public void deleteTable() { getDynamoDbAsyncClient().deleteTable(DeleteTableRequest.builder() .tableName(getConcreteTableName("table-name")) .build()) .join(); } @Test public void putThenGetItemUsingKey() { Record record = new Record() .setId("id-value") .setSort("sort-value") .setAttribute("one") .setAttribute2("two") .setAttribute3("three"); mappedTable.putItem(r -> r.item(record)).join(); Record result = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id-value").sortValue("sort-value"))).join(); assertThat(result, is(record)); } @Test public void putThenGetItemUsingKeyItem() { Record record = new Record() .setId("id-value") .setSort("sort-value") .setAttribute("one") .setAttribute2("two") .setAttribute3("three"); mappedTable.putItem(r -> r.item(record)).join(); Record keyItem = new Record(); keyItem.setId("id-value"); keyItem.setSort("sort-value"); Record result = mappedTable.getItem(keyItem).join(); assertThat(result, is(record)); } @Test public void getNonExistentItem() { Record result = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id-value").sortValue("sort-value"))).join(); assertThat(result, is(nullValue())); } @Test public void putTwiceThenGetItem() { Record record = new Record() .setId("id-value") .setSort("sort-value") .setAttribute("one") .setAttribute2("two") .setAttribute3("three"); mappedTable.putItem(r -> r.item(record)).join(); Record record2 = new Record() .setId("id-value") .setSort("sort-value") .setAttribute("four") .setAttribute2("five") .setAttribute3("six"); mappedTable.putItem(r -> r.item(record2)).join(); Record result = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id-value").sortValue("sort-value"))).join(); assertThat(result, is(record2)); } @Test public void putThenDeleteItem_usingShortcutForm() { Record record = new Record() .setId("id-value") .setSort("sort-value") .setAttribute("one") .setAttribute2("two") .setAttribute3("three"); mappedTable.putItem(record).join(); Record beforeDeleteResult = mappedTable.deleteItem(Key.builder().partitionValue("id-value").sortValue("sort-value").build()).join(); Record afterDeleteResult = mappedTable.getItem(Key.builder().partitionValue("id-value").sortValue("sort-value").build()).join(); assertThat(beforeDeleteResult, is(record)); assertThat(afterDeleteResult, is(nullValue())); } @Test public void putThenDeleteItem_usingKeyItemForm() { Record record = new Record() .setId("id-value") .setSort("sort-value") .setAttribute("one") .setAttribute2("two") .setAttribute3("three"); mappedTable.putItem(record).join(); Record beforeDeleteResult = mappedTable.deleteItem(record).join(); Record afterDeleteResult = mappedTable.getItem(Key.builder().partitionValue("id-value").sortValue("sort-value").build()).join(); assertThat(beforeDeleteResult, is(record)); assertThat(afterDeleteResult, is(nullValue())); } @Test public void putWithConditionThatSucceeds() { Record record = new Record() .setId("id-value") .setSort("sort-value") .setAttribute("one") .setAttribute2("two") .setAttribute3("three"); mappedTable.putItem(r -> r.item(record)).join(); record.setAttribute("four"); Expression conditionExpression = Expression.builder() .expression("#key = :value OR #key1 = :value1") .putExpressionName("#key", "attribute") .putExpressionName("#key1", "attribute3") .putExpressionValue(":value", stringValue("wrong")) .putExpressionValue(":value1", stringValue("three")) .build(); mappedTable.putItem(PutItemEnhancedRequest.builder(Record.class) .item(record) .conditionExpression(conditionExpression) .build()).join(); Record result = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id-value").sortValue("sort-value"))).join(); assertThat(result, is(record)); } @Test public void putWithConditionThatFails() { Record record = new Record() .setId("id-value") .setSort("sort-value") .setAttribute("one") .setAttribute2("two") .setAttribute3("three"); mappedTable.putItem(r -> r.item(record)).join(); record.setAttribute("four"); Expression conditionExpression = Expression.builder() .expression("#key = :value OR #key1 = :value1") .putExpressionName("#key", "attribute") .putExpressionName("#key1", "attribute3") .putExpressionValue(":value", stringValue("wrong")) .putExpressionValue(":value1", stringValue("wrong")) .build(); exception.expect(CompletionException.class); exception.expectCause(instanceOf(ConditionalCheckFailedException.class)); mappedTable.putItem(PutItemEnhancedRequest.builder(Record.class) .item(record) .conditionExpression(conditionExpression) .build()) .join(); } @Test public void deleteNonExistentItem() { Record result = mappedTable.deleteItem(r -> r.key(k -> k.partitionValue("id-value").sortValue("sort-value"))).join(); assertThat(result, is(nullValue())); } @Test public void deleteWithConditionThatSucceeds() { Record record = new Record() .setId("id-value") .setSort("sort-value") .setAttribute("one") .setAttribute2("two") .setAttribute3("three"); mappedTable.putItem(r -> r.item(record)).join(); Expression conditionExpression = Expression.builder() .expression("#key = :value OR #key1 = :value1") .putExpressionName("#key", "attribute") .putExpressionName("#key1", "attribute3") .putExpressionValue(":value", stringValue("wrong")) .putExpressionValue(":value1", stringValue("three")) .build(); Key key = mappedTable.keyFrom(record); mappedTable.deleteItem(DeleteItemEnhancedRequest.builder() .key(key) .conditionExpression(conditionExpression) .build()) .join(); Record result = mappedTable.getItem(r -> r.key(key)).join(); assertThat(result, is(nullValue())); } @Test public void deleteWithConditionThatFails() { Record record = new Record() .setId("id-value") .setSort("sort-value") .setAttribute("one") .setAttribute2("two") .setAttribute3("three"); mappedTable.putItem(r -> r.item(record)).join(); Expression conditionExpression = Expression.builder() .expression("#key = :value OR #key1 = :value1") .putExpressionName("#key", "attribute") .putExpressionName("#key1", "attribute3") .putExpressionValue(":value", stringValue("wrong")) .putExpressionValue(":value1", stringValue("wrong")) .build(); exception.expect(CompletionException.class); exception.expectCause(instanceOf(ConditionalCheckFailedException.class)); mappedTable.deleteItem(DeleteItemEnhancedRequest.builder().key(mappedTable.keyFrom(record)) .conditionExpression(conditionExpression) .build()).join(); } @Test public void updateOverwriteCompleteRecord_usingShortcutForm() { Record record = new Record() .setId("id-value") .setSort("sort-value") .setAttribute("one") .setAttribute2("two") .setAttribute3("three"); mappedTable.putItem(record).join(); Record record2 = new Record() .setId("id-value") .setSort("sort-value") .setAttribute("four") .setAttribute2("five") .setAttribute3("six"); Record result = mappedTable.updateItem(record2).join(); assertThat(result, is(record2)); } @Test public void updateCreatePartialRecord() { Record record = new Record() .setId("id-value") .setSort("sort-value") .setAttribute("one"); Record result = mappedTable.updateItem(r -> r.item(record)).join(); assertThat(result, is(record)); } @Test public void updateCreateKeyOnlyRecord() { Record record = new Record() .setId("id-value") .setSort("sort-value"); Record result = mappedTable.updateItem(r -> r.item(record)).join(); assertThat(result, is(record)); } @Test public void updateOverwriteModelledNulls() { Record record = new Record() .setId("id-value") .setSort("sort-value") .setAttribute("one") .setAttribute2("two") .setAttribute3("three"); mappedTable.putItem(r -> r.item(record)).join(); Record record2 = new Record() .setId("id-value") .setSort("sort-value") .setAttribute("four"); Record result = mappedTable.updateItem(r -> r.item(record2)).join(); assertThat(result, is(record2)); } @Test public void updateCanIgnoreNullsAndDoPartialUpdate() { Record record = new Record() .setId("id-value") .setSort("sort-value") .setAttribute("one") .setAttribute2("two") .setAttribute3("three"); mappedTable.putItem(r -> r.item(record)).join(); Record record2 = new Record() .setId("id-value") .setSort("sort-value") .setAttribute("four"); Record result = mappedTable.updateItem(UpdateItemEnhancedRequest.builder(Record.class) .item(record2) .ignoreNulls(true) .build()) .join(); Record expectedResult = new Record() .setId("id-value") .setSort("sort-value") .setAttribute("four") .setAttribute2("two") .setAttribute3("three"); assertThat(result, is(expectedResult)); } @Test public void updateShortRecordDoesPartialUpdate() { Record record = new Record() .setId("id-value") .setSort("sort-value") .setAttribute("one") .setAttribute2("two") .setAttribute3("three"); mappedTable.putItem(r -> r.item(record)).join(); ShortRecord record2 = new ShortRecord() .setId("id-value") .setSort("sort-value") .setAttribute("four"); ShortRecord shortResult = mappedShortTable.updateItem(r -> r.item(record2)).join(); Record result = mappedTable.getItem(r -> r.key(k -> k.partitionValue(record.getId()) .sortValue(record.getSort()))).join(); Record expectedResult = new Record() .setId("id-value") .setSort("sort-value") .setAttribute("four") .setAttribute2("two") .setAttribute3("three"); assertThat(result, is(expectedResult)); assertThat(shortResult, is(record2)); } @Test public void updateKeyOnlyExistingRecordDoesNothing() { Record record = new Record() .setId("id-value") .setSort("sort-value") .setAttribute("one") .setAttribute2("two") .setAttribute3("three"); mappedTable.putItem(r -> r.item(record)).join(); Record updateRecord = new Record().setId("id-value").setSort("sort-value"); Record result = mappedTable.updateItem(UpdateItemEnhancedRequest.builder(Record.class) .item(updateRecord) .ignoreNulls(true) .build()) .join(); assertThat(result, is(record)); } @Test public void updateWithConditionThatSucceeds() { Record record = new Record() .setId("id-value") .setSort("sort-value") .setAttribute("one") .setAttribute2("two") .setAttribute3("three"); mappedTable.putItem(r -> r.item(record)).join(); record.setAttribute("four"); Expression conditionExpression = Expression.builder() .expression("#key = :value OR #key1 = :value1") .putExpressionName("#key", "attribute") .putExpressionName("#key1", "attribute3") .putExpressionValue(":value", stringValue("wrong")) .putExpressionValue(":value1", stringValue("three")) .build(); mappedTable.updateItem(UpdateItemEnhancedRequest.builder(Record.class) .item(record) .conditionExpression(conditionExpression) .build()) .join(); Record result = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id-value").sortValue("sort-value"))).join(); assertThat(result, is(record)); } @Test public void updateWithConditionThatFails() { Record record = new Record() .setId("id-value") .setSort("sort-value") .setAttribute("one") .setAttribute2("two") .setAttribute3("three"); mappedTable.putItem(r -> r.item(record)).join(); record.setAttribute("four"); Expression conditionExpression = Expression.builder() .expression("#key = :value OR #key1 = :value1") .putExpressionName("#key", "attribute") .putExpressionName("#key1", "attribute3") .putExpressionValue(":value", stringValue("wrong")) .putExpressionValue(":value1", stringValue("wrong")) .build(); exception.expect(CompletionException.class); exception.expectCause(instanceOf(ConditionalCheckFailedException.class)); mappedTable.updateItem(UpdateItemEnhancedRequest.builder(Record.class) .item(record) .conditionExpression(conditionExpression) .build()) .join(); } @Test public void getAShortRecordWithNewModelledFields() { ShortRecord shortRecord = new ShortRecord() .setId("id-value") .setSort("sort-value") .setAttribute("one"); mappedShortTable.putItem(r -> r.item(shortRecord)).join(); Record expectedRecord = new Record() .setId("id-value") .setSort("sort-value") .setAttribute("one"); Record result = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id-value").sortValue("sort-value"))).join(); assertThat(result, is(expectedRecord)); } }
4,119
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/BatchWriteItemTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.junit.After; import org.junit.Before; import org.junit.Test; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema; import software.amazon.awssdk.enhanced.dynamodb.model.BatchWriteItemEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.WriteBatch; import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; public class BatchWriteItemTest extends LocalDynamoDbSyncTestBase { private static class Record1 { private Integer id; private String attribute; private Integer getId() { return id; } private Record1 setId(Integer id) { this.id = id; return this; } private String getAttribute() { return attribute; } private Record1 setAttribute(String attribute) { this.attribute = attribute; return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Record1 record1 = (Record1) o; return Objects.equals(id, record1.id) && Objects.equals(attribute, record1.attribute); } @Override public int hashCode() { return Objects.hash(id, attribute); } } private static class Record2 { private Integer id; private String attribute; private Integer getId() { return id; } private Record2 setId(Integer id) { this.id = id; return this; } private String getAttribute() { return attribute; } private Record2 setAttribute(String attribute) { this.attribute = attribute; return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Record2 record2 = (Record2) o; return Objects.equals(id, record2.id) && Objects.equals(attribute, record2.attribute); } @Override public int hashCode() { return Objects.hash(id, attribute); } } private static final TableSchema<Record1> TABLE_SCHEMA_1 = StaticTableSchema.builder(Record1.class) .newItemSupplier(Record1::new) .addAttribute(Integer.class, a -> a.name("id_1") .getter(Record1::getId) .setter(Record1::setId) .tags(primaryPartitionKey())) .addAttribute(String.class, a -> a.name("attribute") .getter(Record1::getAttribute) .setter(Record1::setAttribute)) .build(); private static final TableSchema<Record2> TABLE_SCHEMA_2 = StaticTableSchema.builder(Record2.class) .newItemSupplier(Record2::new) .addAttribute(Integer.class, a -> a.name("id_2") .getter(Record2::getId) .setter(Record2::setId) .tags(primaryPartitionKey())) .addAttribute(String.class, a -> a.name("attribute") .getter(Record2::getAttribute) .setter(Record2::setAttribute)) .build(); private DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() .dynamoDbClient(getDynamoDbClient()) .build(); private DynamoDbTable<Record1> mappedTable1 = enhancedClient.table(getConcreteTableName("table-name-1"), TABLE_SCHEMA_1); private DynamoDbTable<Record2> mappedTable2 = enhancedClient.table(getConcreteTableName("table-name-2"), TABLE_SCHEMA_2); private static final List<Record1> RECORDS_1 = IntStream.range(0, 2) .mapToObj(i -> new Record1().setId(i).setAttribute(Integer.toString(i))) .collect(Collectors.toList()); private static final List<Record2> RECORDS_2 = IntStream.range(0, 2) .mapToObj(i -> new Record2().setId(i).setAttribute(Integer.toString(i))) .collect(Collectors.toList()); @Before public void createTable() { mappedTable1.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput())); mappedTable2.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput())); } @After public void deleteTable() { getDynamoDbClient().deleteTable(DeleteTableRequest.builder() .tableName(getConcreteTableName("table-name-1")) .build()); getDynamoDbClient().deleteTable(DeleteTableRequest.builder() .tableName(getConcreteTableName("table-name-2")) .build()); } @Test public void singlePut() { BatchWriteItemEnhancedRequest batchWriteItemEnhancedRequest = BatchWriteItemEnhancedRequest.builder() .addWriteBatch( WriteBatch.builder(Record1.class) .mappedTableResource(mappedTable1) .addPutItem(r -> r.item(RECORDS_1.get(0))) .build()) .build(); enhancedClient.batchWriteItem(batchWriteItemEnhancedRequest); Record1 record = mappedTable1.getItem(r -> r.key(k -> k.partitionValue(0))); assertThat(record, is(RECORDS_1.get(0))); } @Test public void multiplePut() { BatchWriteItemEnhancedRequest batchWriteItemEnhancedRequest = BatchWriteItemEnhancedRequest.builder() .writeBatches( WriteBatch.builder(Record1.class) .mappedTableResource(mappedTable1) .addPutItem(r -> r.item(RECORDS_1.get(0))) .build(), WriteBatch.builder(Record2.class) .mappedTableResource(mappedTable2) .addPutItem(r -> r.item(RECORDS_2.get(0))) .build()) .build(); enhancedClient.batchWriteItem(batchWriteItemEnhancedRequest); Record1 record1 = mappedTable1.getItem(r -> r.key(k -> k.partitionValue(0))); Record2 record2 = mappedTable2.getItem(r -> r.key(k -> k.partitionValue(0))); assertThat(record1, is(RECORDS_1.get(0))); assertThat(record2, is(RECORDS_2.get(0))); } @Test public void singleDelete() { mappedTable1.putItem(r -> r.item(RECORDS_1.get(0))); WriteBatch singleDeleteBatch = WriteBatch.builder(Record1.class) .mappedTableResource(mappedTable1) .addDeleteItem(r -> r.key(k -> k.partitionValue(0))) .build(); BatchWriteItemEnhancedRequest batchWriteItemEnhancedRequest = BatchWriteItemEnhancedRequest.builder() .addWriteBatch(singleDeleteBatch) .build(); enhancedClient.batchWriteItem(batchWriteItemEnhancedRequest); Record1 record = mappedTable1.getItem(r -> r.key(k -> k.partitionValue(0))); assertThat(record, is(nullValue())); } @Test public void multipleDelete() { mappedTable1.putItem(r -> r.item(RECORDS_1.get(0))); mappedTable2.putItem(r -> r.item(RECORDS_2.get(0))); BatchWriteItemEnhancedRequest batchWriteItemEnhancedRequest = BatchWriteItemEnhancedRequest.builder() .writeBatches( WriteBatch.builder(Record1.class) .mappedTableResource(mappedTable1) .addDeleteItem(r -> r.key(k -> k.partitionValue(0))) .build(), WriteBatch.builder(Record2.class) .mappedTableResource(mappedTable2) .addDeleteItem(r -> r.key(k -> k.partitionValue(0))) .build()) .build(); enhancedClient.batchWriteItem(batchWriteItemEnhancedRequest); Record1 record1 = mappedTable1.getItem(r -> r.key(k -> k.partitionValue(0))); Record2 record2 = mappedTable2.getItem(r -> r.key(k -> k.partitionValue(0))); assertThat(record1, is(nullValue())); assertThat(record2, is(nullValue())); } @Test public void mixedCommands() { mappedTable1.putItem(r -> r.item(RECORDS_1.get(0))); mappedTable2.putItem(r -> r.item(RECORDS_2.get(0))); enhancedClient.batchWriteItem(r -> r.writeBatches( WriteBatch.builder(Record1.class) .mappedTableResource(mappedTable1) .addPutItem(i -> i.item(RECORDS_1.get(1))) .build(), WriteBatch.builder(Record2.class) .mappedTableResource(mappedTable2) .addDeleteItem(i -> i.key(k -> k.partitionValue(0))) .build())); assertThat(mappedTable1.getItem(r -> r.key(k -> k.partitionValue(0))), is(RECORDS_1.get(0))); assertThat(mappedTable1.getItem(r -> r.key(k -> k.partitionValue(1))), is(RECORDS_1.get(1))); assertThat(mappedTable2.getItem(r -> r.key(k -> k.partitionValue(0))), is(nullValue())); } }
4,120
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/AsyncDeleteItemWithResponseTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests; import static org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey; import java.util.Objects; import org.junit.After; import org.junit.Before; import org.junit.Test; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbAsyncTable; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedAsyncClient; import software.amazon.awssdk.enhanced.dynamodb.Key; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema; import software.amazon.awssdk.enhanced.dynamodb.model.DeleteItemEnhancedResponse; import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; import software.amazon.awssdk.services.dynamodb.model.ReturnConsumedCapacity; public class AsyncDeleteItemWithResponseTest extends LocalDynamoDbAsyncTestBase { private static class Record { private Integer id; private String stringAttr1; private Integer getId() { return id; } private Record setId(Integer id) { this.id = id; return this; } private String getStringAttr1() { return stringAttr1; } private Record setStringAttr1(String stringAttr1) { this.stringAttr1 = stringAttr1; return this; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Record record = (Record) o; return Objects.equals(id, record.id) && Objects.equals(stringAttr1, record.stringAttr1); } @Override public int hashCode() { return Objects.hash(id, stringAttr1); } } private static final TableSchema<Record> TABLE_SCHEMA = StaticTableSchema.builder(Record.class) .newItemSupplier(Record::new) .addAttribute(Integer.class, a -> a.name("id_1") .getter(Record::getId) .setter(Record::setId) .tags(primaryPartitionKey())) .addAttribute(String.class, a -> a.name("stringAttr1") .getter(Record::getStringAttr1) .setter(Record::setStringAttr1)) .build(); private DynamoDbEnhancedAsyncClient enhancedClient; private DynamoDbAsyncTable<Record> mappedTable1; @Before public void createTable() { enhancedClient = DynamoDbEnhancedAsyncClient.builder() .dynamoDbClient(getDynamoDbAsyncClient()) .build(); mappedTable1 = enhancedClient.table(getConcreteTableName("table-name-1"), TABLE_SCHEMA); mappedTable1.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput())).join(); } @After public void deleteTable() { getDynamoDbAsyncClient().deleteTable(DeleteTableRequest.builder() .tableName(getConcreteTableName("table-name-1")) .build()); } // Note: DynamoDB local seems to always return the consumed capacity even if not specified on the request. See // AsyncDeleteItemWithResponseIntegrationTest for additional testing of this field against the actual service. @Test public void returnConsumedCapacity_set_consumedCapacityNotNull() { Key key = Key.builder().partitionValue(1).build(); DeleteItemEnhancedResponse<Record> response = mappedTable1.deleteItemWithResponse(r -> r.key(key) .returnConsumedCapacity(ReturnConsumedCapacity.TOTAL)).join(); assertThat(response.consumedCapacity()).isNotNull(); } }
4,121
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/AtomicCounterTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.stream.IntStream; import org.junit.After; import org.junit.Before; import org.junit.Test; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.AtomicCounterRecord; import software.amazon.awssdk.enhanced.dynamodb.model.WriteBatch; import software.amazon.awssdk.services.dynamodb.model.DynamoDbException; public class AtomicCounterTest extends LocalDynamoDbSyncTestBase { private static final String STRING_VALUE = "string value"; private static final String RECORD_ID = "id123"; private static final TableSchema<AtomicCounterRecord> TABLE_SCHEMA = TableSchema.fromClass(AtomicCounterRecord.class); private final DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() .dynamoDbClient(getDynamoDbClient()) .build(); private final DynamoDbTable<AtomicCounterRecord> mappedTable = enhancedClient.table(getConcreteTableName("table-name"), TABLE_SCHEMA); @Before public void createTable() { mappedTable.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput())); } @After public void deleteTable() { getDynamoDbClient().deleteTable(r -> r.tableName(getConcreteTableName("table-name"))); } @Test public void createViaUpdate_incrementsCorrectly() { AtomicCounterRecord record = new AtomicCounterRecord(); record.setId(RECORD_ID); record.setAttribute1(STRING_VALUE); mappedTable.updateItem(record); AtomicCounterRecord persistedRecord = mappedTable.getItem(record); assertThat(persistedRecord.getAttribute1()).isEqualTo(STRING_VALUE); assertThat(persistedRecord.getDefaultCounter()).isEqualTo(0L); assertThat(persistedRecord.getCustomCounter()).isEqualTo(10L); assertThat(persistedRecord.getDecreasingCounter()).isEqualTo(-20L); mappedTable.updateItem(record); persistedRecord = mappedTable.getItem(record); assertThat(persistedRecord.getAttribute1()).isEqualTo(STRING_VALUE); assertThat(persistedRecord.getDefaultCounter()).isEqualTo(1L); assertThat(persistedRecord.getCustomCounter()).isEqualTo(15L); assertThat(persistedRecord.getDecreasingCounter()).isEqualTo(-21L); } @Test public void createViaUpdate_multipleUpdates_incrementsCorrectly() { AtomicCounterRecord record = new AtomicCounterRecord(); record.setId(RECORD_ID); record.setAttribute1(STRING_VALUE); mappedTable.updateItem(record); int numUpdates = 50; IntStream.range(0, numUpdates).forEach(i -> mappedTable.updateItem(record)); AtomicCounterRecord persistedRecord = mappedTable.getItem(record); assertThat(persistedRecord.getDefaultCounter()).isEqualTo(numUpdates); assertThat(persistedRecord.getCustomCounter()).isEqualTo(10 + numUpdates * 5); assertThat(persistedRecord.getDecreasingCounter()).isEqualTo(-20 + numUpdates * -1); } @Test public void createViaPut_incrementsCorrectly() { AtomicCounterRecord record = new AtomicCounterRecord(); record.setId(RECORD_ID); record.setAttribute1(STRING_VALUE); mappedTable.putItem(record); AtomicCounterRecord persistedRecord = mappedTable.getItem(record); assertThat(persistedRecord.getAttribute1()).isEqualTo(STRING_VALUE); assertThat(persistedRecord.getDefaultCounter()).isEqualTo(0L); assertThat(persistedRecord.getCustomCounter()).isEqualTo(10L); assertThat(persistedRecord.getDecreasingCounter()).isEqualTo(-20L); mappedTable.updateItem(record); persistedRecord = mappedTable.getItem(record); assertThat(persistedRecord.getAttribute1()).isEqualTo("string value"); assertThat(persistedRecord.getDefaultCounter()).isEqualTo(1L); assertThat(persistedRecord.getCustomCounter()).isEqualTo(15L); assertThat(persistedRecord.getDecreasingCounter()).isEqualTo(-21L); } @Test public void createViaUpdate_settingCounterInPojo_hasNoEffect() { AtomicCounterRecord record = new AtomicCounterRecord(); record.setId(RECORD_ID); record.setDefaultCounter(10L); record.setAttribute1(STRING_VALUE); mappedTable.updateItem(record); AtomicCounterRecord persistedRecord = mappedTable.getItem(record); assertThat(persistedRecord.getAttribute1()).isEqualTo(STRING_VALUE); assertThat(persistedRecord.getDefaultCounter()).isEqualTo(0L); assertThat(persistedRecord.getCustomCounter()).isEqualTo(10L); assertThat(persistedRecord.getDecreasingCounter()).isEqualTo(-20L); } @Test public void updateItem_retrievedFromDb_shouldNotThrowException() { AtomicCounterRecord record = new AtomicCounterRecord(); record.setId(RECORD_ID); record.setAttribute1(STRING_VALUE); mappedTable.updateItem(record); AtomicCounterRecord retrievedRecord = mappedTable.getItem(record); retrievedRecord.setAttribute1("ChangingThisAttribute"); retrievedRecord = mappedTable.updateItem(retrievedRecord); assertThat(retrievedRecord).isNotNull(); assertThat(retrievedRecord.getDefaultCounter()).isEqualTo(1L); assertThat(retrievedRecord.getCustomCounter()).isEqualTo(15L); assertThat(retrievedRecord.getDecreasingCounter()).isEqualTo(-21L); } @Test public void createViaPut_settingCounterInPojoHasNoEffect() { AtomicCounterRecord record = new AtomicCounterRecord(); record.setId(RECORD_ID); record.setDefaultCounter(10L); record.setAttribute1(STRING_VALUE); mappedTable.putItem(record); AtomicCounterRecord persistedRecord = mappedTable.getItem(record); assertThat(persistedRecord.getAttribute1()).isEqualTo(STRING_VALUE); assertThat(persistedRecord.getDefaultCounter()).isEqualTo(0L); } @Test public void transactUpdate_incrementsCorrectly() { AtomicCounterRecord record = new AtomicCounterRecord(); record.setId(RECORD_ID); record.setAttribute1(STRING_VALUE); enhancedClient.transactWriteItems(r -> r.addPutItem(mappedTable, record)); AtomicCounterRecord persistedRecord = mappedTable.getItem(record); assertThat(persistedRecord.getAttribute1()).isEqualTo(STRING_VALUE); assertThat(persistedRecord.getDefaultCounter()).isEqualTo(0L); enhancedClient.transactWriteItems(r -> r.addUpdateItem(mappedTable, record)); persistedRecord = mappedTable.getItem(record); assertThat(persistedRecord.getAttribute1()).isEqualTo(STRING_VALUE); assertThat(persistedRecord.getDefaultCounter()).isEqualTo(1L); } @Test public void batchPut_initializesCorrectly() { AtomicCounterRecord record = new AtomicCounterRecord(); record.setId(RECORD_ID); record.setAttribute1(STRING_VALUE); enhancedClient.batchWriteItem(r -> r.addWriteBatch(WriteBatch.builder(AtomicCounterRecord.class) .mappedTableResource(mappedTable) .addPutItem(record) .build())); AtomicCounterRecord persistedRecord = mappedTable.getItem(record); assertThat(persistedRecord.getAttribute1()).isEqualTo(STRING_VALUE); assertThat(persistedRecord.getDefaultCounter()).isEqualTo(0L); enhancedClient.transactWriteItems(r -> r.addUpdateItem(mappedTable, record)); persistedRecord = mappedTable.getItem(record); assertThat(persistedRecord.getAttribute1()).isEqualTo(STRING_VALUE); assertThat(persistedRecord.getDefaultCounter()).isEqualTo(1L); } }
4,122
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/IndexQueryTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.numberValue; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.stringValue; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primarySortKey; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.secondaryPartitionKey; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.secondarySortKey; import static software.amazon.awssdk.enhanced.dynamodb.model.QueryConditional.keyEqualTo; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.junit.After; import org.junit.Before; import org.junit.Test; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbIndex; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.Key; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema; import software.amazon.awssdk.enhanced.dynamodb.model.CreateTableEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.EnhancedGlobalSecondaryIndex; import software.amazon.awssdk.enhanced.dynamodb.model.Page; import software.amazon.awssdk.enhanced.dynamodb.model.QueryConditional; import software.amazon.awssdk.enhanced.dynamodb.model.QueryEnhancedRequest; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; import software.amazon.awssdk.services.dynamodb.model.ProjectionType; import software.amazon.awssdk.services.dynamodb.model.ReturnConsumedCapacity; public class IndexQueryTest extends LocalDynamoDbSyncTestBase { private static class Record { private String id; private Integer sort; private Integer value; private String gsiId; private Integer gsiSort; private String getId() { return id; } private Record setId(String id) { this.id = id; return this; } private Integer getSort() { return sort; } private Record setSort(Integer sort) { this.sort = sort; return this; } private Integer getValue() { return value; } private Record setValue(Integer value) { this.value = value; return this; } private String getGsiId() { return gsiId; } private Record setGsiId(String gsiId) { this.gsiId = gsiId; return this; } private Integer getGsiSort() { return gsiSort; } private Record setGsiSort(Integer gsiSort) { this.gsiSort = gsiSort; return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Record record = (Record) o; return Objects.equals(id, record.id) && Objects.equals(sort, record.sort) && Objects.equals(value, record.value) && Objects.equals(gsiId, record.gsiId) && Objects.equals(gsiSort, record.gsiSort); } @Override public int hashCode() { return Objects.hash(id, sort, value, gsiId, gsiSort); } } private static final TableSchema<Record> TABLE_SCHEMA = StaticTableSchema.builder(Record.class) .newItemSupplier(Record::new) .addAttribute(String.class, a -> a.name("id") .getter(Record::getId) .setter(Record::setId) .tags(primaryPartitionKey())) .addAttribute(Integer.class, a -> a.name("sort") .getter(Record::getSort) .setter(Record::setSort) .tags(primarySortKey())) .addAttribute(Integer.class, a -> a.name("value") .getter(Record::getValue) .setter(Record::setValue)) .addAttribute(String.class, a -> a.name("gsi_id") .getter(Record::getGsiId) .setter(Record::setGsiId) .tags(secondaryPartitionKey("gsi_keys_only"))) .addAttribute(Integer.class, a -> a.name("gsi_sort") .getter(Record::getGsiSort) .setter(Record::setGsiSort) .tags(secondarySortKey("gsi_keys_only"))) .build(); private static final List<Record> RECORDS = IntStream.range(0, 10) .mapToObj(i -> new Record() .setId("id-value") .setSort(i) .setValue(i) .setGsiId("gsi-id-value") .setGsiSort(i)) .collect(Collectors.toList()); private static final List<Record> KEYS_ONLY_RECORDS = RECORDS.stream() .map(record -> new Record() .setId(record.id) .setSort(record.sort) .setGsiId(record.gsiId) .setGsiSort(record.gsiSort)) .collect(Collectors.toList()); private DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() .dynamoDbClient(getDynamoDbClient()) .build(); private DynamoDbTable<Record> mappedTable = enhancedClient.table(getConcreteTableName("table-name"), TABLE_SCHEMA); private DynamoDbIndex<Record> keysOnlyMappedIndex = mappedTable.index("gsi_keys_only"); private void insertRecords() { RECORDS.forEach(record -> mappedTable.putItem(r -> r.item(record))); } @Before public void createTable() { mappedTable.createTable( CreateTableEnhancedRequest.builder() .provisionedThroughput(getDefaultProvisionedThroughput()) .globalSecondaryIndices( EnhancedGlobalSecondaryIndex.builder() .indexName("gsi_keys_only") .projection(p -> p.projectionType(ProjectionType.KEYS_ONLY)) .provisionedThroughput(getDefaultProvisionedThroughput()) .build()) .build()); } @After public void deleteTable() { getDynamoDbClient().deleteTable(DeleteTableRequest.builder() .tableName(getConcreteTableName("table-name")) .build()); } @Test public void queryAllRecordsDefaultSettings_usingShortcutForm() { insertRecords(); Iterator<Page<Record>> results = keysOnlyMappedIndex.query(keyEqualTo(k -> k.partitionValue("gsi-id-value"))).iterator(); assertThat(results.hasNext(), is(true)); Page<Record> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items(), is(KEYS_ONLY_RECORDS)); assertThat(page.lastEvaluatedKey(), is(nullValue())); assertThat(page.consumedCapacity(), is(nullValue())); } @Test public void queryBetween() { insertRecords(); Key fromKey = Key.builder().partitionValue("gsi-id-value").sortValue(3).build(); Key toKey = Key.builder().partitionValue("gsi-id-value").sortValue(5).build(); Iterator<Page<Record>> results = keysOnlyMappedIndex.query(r -> r.queryConditional(QueryConditional.sortBetween(fromKey, toKey)) .returnConsumedCapacity(ReturnConsumedCapacity.INDEXES)) .iterator(); assertThat(results.hasNext(), is(true)); Page<Record> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items(), is(KEYS_ONLY_RECORDS.stream().filter(r -> r.sort >= 3 && r.sort <= 5).collect(Collectors.toList()))); assertThat(page.lastEvaluatedKey(), is(nullValue())); assertThat(page.consumedCapacity(), is(notNullValue())); assertThat(page.consumedCapacity().capacityUnits(), is(notNullValue())); assertThat(page.consumedCapacity().globalSecondaryIndexes(), is(notNullValue())); assertThat(page.count(), equalTo(3)); assertThat(page.scannedCount(), equalTo(3)); } @Test public void queryLimit() { insertRecords(); Iterator<Page<Record>> results = keysOnlyMappedIndex.query(QueryEnhancedRequest.builder() .queryConditional(keyEqualTo(k -> k.partitionValue("gsi-id-value"))) .limit(5) .build()) .iterator(); assertThat(results.hasNext(), is(true)); Page<Record> page1 = results.next(); assertThat(results.hasNext(), is(true)); Page<Record> page2 = results.next(); assertThat(results.hasNext(), is(true)); Page<Record> page3 = results.next(); assertThat(results.hasNext(), is(false)); Map<String, AttributeValue> expectedLastEvaluatedKey1 = new HashMap<>(); expectedLastEvaluatedKey1.put("id", stringValue(KEYS_ONLY_RECORDS.get(4).getId())); expectedLastEvaluatedKey1.put("sort", numberValue(KEYS_ONLY_RECORDS.get(4).getSort())); expectedLastEvaluatedKey1.put("gsi_id", stringValue(KEYS_ONLY_RECORDS.get(4).getGsiId())); expectedLastEvaluatedKey1.put("gsi_sort", numberValue(KEYS_ONLY_RECORDS.get(4).getGsiSort())); Map<String, AttributeValue> expectedLastEvaluatedKey2 = new HashMap<>(); expectedLastEvaluatedKey2.put("id", stringValue(KEYS_ONLY_RECORDS.get(9).getId())); expectedLastEvaluatedKey2.put("sort", numberValue(KEYS_ONLY_RECORDS.get(9).getSort())); expectedLastEvaluatedKey2.put("gsi_id", stringValue(KEYS_ONLY_RECORDS.get(9).getGsiId())); expectedLastEvaluatedKey2.put("gsi_sort", numberValue(KEYS_ONLY_RECORDS.get(9).getGsiSort())); assertThat(page1.items(), is(KEYS_ONLY_RECORDS.subList(0, 5))); assertThat(page1.lastEvaluatedKey(), is(expectedLastEvaluatedKey1)); assertThat(page1.count(), equalTo(5)); assertThat(page1.scannedCount(), equalTo(5)); assertThat(page2.items(), is(KEYS_ONLY_RECORDS.subList(5, 10))); assertThat(page2.lastEvaluatedKey(), is(expectedLastEvaluatedKey2)); assertThat(page2.count(), equalTo(5)); assertThat(page2.scannedCount(), equalTo(5)); assertThat(page3.items(), is(empty())); assertThat(page3.lastEvaluatedKey(), is(nullValue())); assertThat(page3.count(), equalTo(0)); assertThat(page3.scannedCount(), equalTo(0)); } @Test public void queryEmpty() { Iterator<Page<Record>> results = keysOnlyMappedIndex.query(r -> r.queryConditional(keyEqualTo(k -> k.partitionValue("gsi-id-value")))).iterator(); assertThat(results.hasNext(), is(true)); Page<Record> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items(), is(empty())); assertThat(page.lastEvaluatedKey(), is(nullValue())); assertThat(page.count(), equalTo(0)); assertThat(page.scannedCount(), equalTo(0)); } @Test public void queryExclusiveStartKey() { insertRecords(); Map<String, AttributeValue> expectedLastEvaluatedKey = new HashMap<>(); expectedLastEvaluatedKey.put("id", stringValue(KEYS_ONLY_RECORDS.get(7).getId())); expectedLastEvaluatedKey.put("sort", numberValue(KEYS_ONLY_RECORDS.get(7).getSort())); expectedLastEvaluatedKey.put("gsi_id", stringValue(KEYS_ONLY_RECORDS.get(7).getGsiId())); expectedLastEvaluatedKey.put("gsi_sort", numberValue(KEYS_ONLY_RECORDS.get(7).getGsiSort())); Iterator<Page<Record>> results = keysOnlyMappedIndex.query(QueryEnhancedRequest.builder() .queryConditional(keyEqualTo(k -> k.partitionValue("gsi-id-value"))) .exclusiveStartKey(expectedLastEvaluatedKey).build()) .iterator(); assertThat(results.hasNext(), is(true)); Page<Record> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items(), is(KEYS_ONLY_RECORDS.subList(8, 10))); assertThat(page.lastEvaluatedKey(), is(nullValue())); assertThat(page.count(), equalTo(2)); assertThat(page.scannedCount(), equalTo(2)); } }
4,123
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/AsyncBatchWriteItemTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.junit.After; import org.junit.Before; import org.junit.Test; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbAsyncTable; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedAsyncClient; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.internal.client.DefaultDynamoDbEnhancedAsyncClient; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema; import software.amazon.awssdk.enhanced.dynamodb.model.BatchWriteItemEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.DeleteItemEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.WriteBatch; import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; public class AsyncBatchWriteItemTest extends LocalDynamoDbAsyncTestBase { private static class Record1 { private Integer id; private String attribute; private Integer getId() { return id; } private Record1 setId(Integer id) { this.id = id; return this; } private String getAttribute() { return attribute; } private Record1 setAttribute(String attribute) { this.attribute = attribute; return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Record1 record1 = (Record1) o; return Objects.equals(id, record1.id) && Objects.equals(attribute, record1.attribute); } @Override public int hashCode() { return Objects.hash(id, attribute); } } private static class Record2 { private Integer id; private String attribute; private Integer getId() { return id; } private Record2 setId(Integer id) { this.id = id; return this; } private String getAttribute() { return attribute; } private Record2 setAttribute(String attribute) { this.attribute = attribute; return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Record2 record2 = (Record2) o; return Objects.equals(id, record2.id) && Objects.equals(attribute, record2.attribute); } @Override public int hashCode() { return Objects.hash(id, attribute); } } private static final TableSchema<Record1> TABLE_SCHEMA_1 = StaticTableSchema.builder(Record1.class) .newItemSupplier(Record1::new) .addAttribute(Integer.class, a -> a.name("id_1") .getter(Record1::getId) .setter(Record1::setId) .tags(primaryPartitionKey())) .addAttribute(String.class, a -> a.name("attribute") .getter(Record1::getAttribute) .setter(Record1::setAttribute)) .build(); private static final TableSchema<Record2> TABLE_SCHEMA_2 = StaticTableSchema.builder(Record2.class) .newItemSupplier(Record2::new) .addAttribute(Integer.class, a -> a.name("id_2") .getter(Record2::getId) .setter(Record2::setId) .tags(primaryPartitionKey())) .addAttribute(String.class, a -> a.name("attribute") .getter(Record2::getAttribute) .setter(Record2::setAttribute)) .build(); private DynamoDbEnhancedAsyncClient enhancedAsyncClient = DefaultDynamoDbEnhancedAsyncClient.builder() .dynamoDbClient(getDynamoDbAsyncClient()) .build(); private DynamoDbAsyncTable<Record1> mappedTable1 = enhancedAsyncClient.table(getConcreteTableName("table-name-1"), TABLE_SCHEMA_1); private DynamoDbAsyncTable<Record2> mappedTable2 = enhancedAsyncClient.table(getConcreteTableName("table-name-2"), TABLE_SCHEMA_2); private static final List<Record1> RECORDS_1 = IntStream.range(0, 2) .mapToObj(i -> new Record1().setId(i).setAttribute(Integer.toString(i))) .collect(Collectors.toList()); private static final List<Record2> RECORDS_2 = IntStream.range(0, 2) .mapToObj(i -> new Record2().setId(i).setAttribute(Integer.toString(i))) .collect(Collectors.toList()); @Before public void createTable() { mappedTable1.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput())).join(); mappedTable2.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput())).join(); } @After public void deleteTable() { getDynamoDbAsyncClient().deleteTable(DeleteTableRequest.builder() .tableName(getConcreteTableName("table-name-1")) .build()).join(); getDynamoDbAsyncClient().deleteTable(DeleteTableRequest.builder() .tableName(getConcreteTableName("table-name-2")) .build()).join(); } @Test public void singlePut() { List<WriteBatch> writeBatches = singletonList(WriteBatch.builder(Record1.class) .mappedTableResource(mappedTable1) .addPutItem(r -> r.item(RECORDS_1.get(0))) .build()); enhancedAsyncClient.batchWriteItem(BatchWriteItemEnhancedRequest.builder().writeBatches(writeBatches).build()).join(); Record1 record = mappedTable1.getItem(r -> r.key(k -> k.partitionValue(0))).join(); assertThat(record, is(RECORDS_1.get(0))); } @Test public void multiplePut() { List<WriteBatch> writeBatches = asList(WriteBatch.builder(Record1.class) .mappedTableResource(mappedTable1) .addPutItem(r -> r.item(RECORDS_1.get(0))) .build(), WriteBatch.builder(Record2.class) .mappedTableResource(mappedTable2) .addPutItem(r -> r.item(RECORDS_2.get(0))) .build()); enhancedAsyncClient.batchWriteItem(BatchWriteItemEnhancedRequest.builder().writeBatches(writeBatches).build()).join(); Record1 record1 = mappedTable1.getItem(r -> r.key(k -> k.partitionValue(0))).join(); Record2 record2 = mappedTable2.getItem(r -> r.key(k -> k.partitionValue(0))).join(); assertThat(record1, is(RECORDS_1.get(0))); assertThat(record2, is(RECORDS_2.get(0))); } @Test public void singleDelete() { mappedTable1.putItem(r -> r.item(RECORDS_1.get(0))).join(); List<WriteBatch> writeBatches = singletonList(WriteBatch.builder(Record1.class) .mappedTableResource(mappedTable1) .addDeleteItem(r -> r.key(k -> k.partitionValue(0))) .build()); enhancedAsyncClient.batchWriteItem(BatchWriteItemEnhancedRequest.builder().writeBatches(writeBatches).build()).join(); Record1 record = mappedTable1.getItem(r -> r.key(k -> k.partitionValue(0))).join(); assertThat(record, is(nullValue())); } @Test public void multipleDelete() { mappedTable1.putItem(r -> r.item(RECORDS_1.get(0))).join(); mappedTable2.putItem(r -> r.item(RECORDS_2.get(0))).join(); List<WriteBatch> writeBatches = asList(WriteBatch.builder(Record1.class) .mappedTableResource(mappedTable1) .addDeleteItem(DeleteItemEnhancedRequest.builder().key(k -> k.partitionValue(0)).build()) .build(), WriteBatch.builder(Record2.class) .mappedTableResource(mappedTable2) .addDeleteItem(DeleteItemEnhancedRequest.builder().key(k -> k.partitionValue(0)).build()) .build()); enhancedAsyncClient.batchWriteItem(BatchWriteItemEnhancedRequest.builder().writeBatches(writeBatches).build()).join(); Record1 record1 = mappedTable1.getItem(r -> r.key(k -> k.partitionValue(0))).join(); Record2 record2 = mappedTable2.getItem(r -> r.key(k -> k.partitionValue(0))).join(); assertThat(record1, is(nullValue())); assertThat(record2, is(nullValue())); } @Test public void mixedCommands() { mappedTable1.putItem(r -> r.item(RECORDS_1.get(0))).join(); mappedTable2.putItem(r -> r.item(RECORDS_2.get(0))).join(); enhancedAsyncClient.batchWriteItem(r -> r.writeBatches( WriteBatch.builder(Record1.class) .mappedTableResource(mappedTable1) .addPutItem(i -> i.item(RECORDS_1.get(1))) .build(), WriteBatch.builder(Record2.class) .mappedTableResource(mappedTable2) .addDeleteItem(i -> i.key(k -> k.partitionValue(0))) .build())).join(); assertThat(mappedTable1.getItem(r -> r.key(k -> k.partitionValue(0))).join(), is(RECORDS_1.get(0))); assertThat(mappedTable1.getItem(r -> r.key(k -> k.partitionValue(1))).join(), is(RECORDS_1.get(1))); assertThat(mappedTable2.getItem(r -> r.key(k -> k.partitionValue(0))).join(), is(nullValue())); } }
4,124
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/EmptyStringTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests; import static java.util.Collections.singletonMap; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.HashMap; import java.util.Map; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.Expression; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.GetItemRequest; import software.amazon.awssdk.services.dynamodb.model.GetItemResponse; import software.amazon.awssdk.services.dynamodb.model.PutItemRequest; import software.amazon.awssdk.services.dynamodb.model.PutItemResponse; import software.amazon.awssdk.services.dynamodb.model.ReturnValue; import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest; import software.amazon.awssdk.services.dynamodb.model.UpdateItemResponse; @RunWith(MockitoJUnitRunner.class) public class EmptyStringTest { private static final String TABLE_NAME = "TEST_TABLE"; private static final AttributeValue EMPTY_STRING = AttributeValue.builder().s("").build(); @Mock private DynamoDbClient mockDynamoDbClient; private DynamoDbTable<TestBean> dynamoDbTable; @DynamoDbBean public static class TestBean { private String id; private String s; @DynamoDbPartitionKey public String getId() { return id; } public void setId(String id) { this.id = id; } public String getS() { return s; } public void setS(String s) { this.s = s; } } private static final TableSchema<TestBean> TABLE_SCHEMA = TableSchema.fromClass(TestBean.class); @Before public void initializeTable() { DynamoDbEnhancedClient dynamoDbEnhancedClient = DynamoDbEnhancedClient.builder() .dynamoDbClient(mockDynamoDbClient) .build(); this.dynamoDbTable = dynamoDbEnhancedClient.table(TABLE_NAME, TABLE_SCHEMA); } @Test public void putEmptyString() { TestBean testBean = new TestBean(); testBean.setId("id123"); testBean.setS(""); PutItemResponse response = PutItemResponse.builder().build(); when(mockDynamoDbClient.putItem(any(PutItemRequest.class))).thenReturn(response); 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); } @Test public void getEmptyString() { Map<String, AttributeValue> itemMap = new HashMap<>(); itemMap.put("id", AttributeValue.builder().s("id123").build()); itemMap.put("s", EMPTY_STRING); GetItemResponse response = GetItemResponse.builder() .item(itemMap) .build(); when(mockDynamoDbClient.getItem(any(GetItemRequest.class))).thenReturn(response); TestBean result = dynamoDbTable.getItem(r -> r.key(k -> k.partitionValue("id123"))); assertThat(result.getId()).isEqualTo("id123"); assertThat(result.getS()).isEmpty(); } @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(); } }
4,125
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/BasicQueryTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.numberValue; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.stringValue; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primarySortKey; import static software.amazon.awssdk.enhanced.dynamodb.model.QueryConditional.keyEqualTo; import static software.amazon.awssdk.enhanced.dynamodb.model.QueryConditional.sortBetween; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.junit.After; import org.junit.Before; import org.junit.Test; import software.amazon.awssdk.core.pagination.sync.SdkIterable; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.Expression; import software.amazon.awssdk.enhanced.dynamodb.Key; import software.amazon.awssdk.enhanced.dynamodb.NestedAttributeName; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.InnerAttributeRecord; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.NestedTestRecord; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema; import software.amazon.awssdk.enhanced.dynamodb.model.Page; import software.amazon.awssdk.enhanced.dynamodb.model.PageIterable; import software.amazon.awssdk.enhanced.dynamodb.model.QueryEnhancedRequest; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; public class BasicQueryTest extends LocalDynamoDbSyncTestBase { private static class Record { private String id; private Integer sort; private Integer value; public String getId() { return id; } public Record setId(String id) { this.id = id; return this; } public Integer getSort() { return sort; } public Record setSort(Integer sort) { this.sort = sort; return this; } public Integer getValue() { return value; } public Record setValue(Integer value) { this.value = value; return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Record record = (Record) o; return Objects.equals(id, record.id) && Objects.equals(sort, record.sort) && Objects.equals(value, record.value); } @Override public int hashCode() { return Objects.hash(id, sort, value); } } private static final TableSchema<Record> TABLE_SCHEMA = StaticTableSchema.builder(Record.class) .newItemSupplier(Record::new) .addAttribute(String.class, a -> a.name("id") .getter(Record::getId) .setter(Record::setId) .tags(primaryPartitionKey())) .addAttribute(Integer.class, a -> a.name("sort") .getter(Record::getSort) .setter(Record::setSort) .tags(primarySortKey())) .addAttribute(Integer.class, a -> a.name("value") .getter(Record::getValue) .setter(Record::setValue)) .build(); private static final List<Record> RECORDS = IntStream.range(0, 10) .mapToObj(i -> new Record().setId("id-value").setSort(i).setValue(i)) .collect(Collectors.toList()); private static final List<NestedTestRecord> NESTED_TEST_RECORDS = IntStream.range(0, 10) .mapToObj(i -> { final NestedTestRecord nestedTestRecord = new NestedTestRecord(); nestedTestRecord.setOuterAttribOne("id-value-" + i); nestedTestRecord.setSort(i); final InnerAttributeRecord innerAttributeRecord = new InnerAttributeRecord(); innerAttributeRecord.setAttribOne("attribOne-"+i); innerAttributeRecord.setAttribTwo(i); nestedTestRecord.setInnerAttributeRecord(innerAttributeRecord); nestedTestRecord.setDotVariable("v"+i); return nestedTestRecord; }) .collect(Collectors.toList()); private DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() .dynamoDbClient(getDynamoDbClient()) .build(); private DynamoDbTable<Record> mappedTable = enhancedClient.table(getConcreteTableName("table-name"), TABLE_SCHEMA); private DynamoDbTable<NestedTestRecord> mappedNestedTable = enhancedClient.table(getConcreteTableName("nested-table-name"), TableSchema.fromClass(NestedTestRecord.class)); private void insertRecords() { RECORDS.forEach(record -> mappedTable.putItem(r -> r.item(record))); NESTED_TEST_RECORDS.forEach(nestedTestRecord -> mappedNestedTable.putItem(r -> r.item(nestedTestRecord))); } private void insertNestedRecords() { NESTED_TEST_RECORDS.forEach(nestedTestRecord -> mappedNestedTable.putItem(r -> r.item(nestedTestRecord))); } @Before public void createTable() { mappedTable.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput())); mappedNestedTable.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput())); } @After public void deleteTable() { getDynamoDbClient().deleteTable(DeleteTableRequest.builder() .tableName(getConcreteTableName("table-name")) .build()); getDynamoDbClient().deleteTable(DeleteTableRequest.builder() .tableName(getConcreteTableName("nested-table-name")) .build()); } @Test public void queryAllRecordsDefaultSettings_shortcutForm() { insertRecords(); Iterator<Page<Record>> results = mappedTable.query(keyEqualTo(k -> k.partitionValue("id-value"))).iterator(); assertThat(results.hasNext(), is(true)); Page<Record> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items(), is(RECORDS)); assertThat(page.lastEvaluatedKey(), is(nullValue())); } @Test public void queryAllRecordsDefaultSettings_withProjection() { insertRecords(); Iterator<Page<Record>> results = mappedTable.query(b -> b .queryConditional(keyEqualTo(k -> k.partitionValue("id-value"))) .attributesToProject("value") ).iterator(); assertThat(results.hasNext(), is(true)); Page<Record> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items().size(), is(RECORDS.size())); Record firstRecord = page.items().get(0); assertThat(firstRecord.id, is(nullValue())); assertThat(firstRecord.sort, is(nullValue())); assertThat(firstRecord.value, is(0)); } @Test public void queryAllRecordsDefaultSettings_shortcutForm_viaItems() { insertRecords(); PageIterable<Record> query = mappedTable.query(keyEqualTo(k -> k.partitionValue("id-value"))); SdkIterable<Record> results = query.items(); assertThat(results.stream().collect(Collectors.toList()), is(RECORDS)); } @Test public void queryAllRecordsWithFilter() { insertRecords(); Map<String, AttributeValue> expressionValues = new HashMap<>(); expressionValues.put(":min_value", numberValue(3)); expressionValues.put(":max_value", numberValue(5)); Expression expression = Expression.builder() .expression("#value >= :min_value AND #value <= :max_value") .expressionValues(expressionValues) .expressionNames(Collections.singletonMap("#value", "value")) .build(); Iterator<Page<Record>> results = mappedTable.query(QueryEnhancedRequest.builder() .queryConditional(keyEqualTo(k -> k.partitionValue("id-value"))) .filterExpression(expression) .build()) .iterator(); assertThat(results.hasNext(), is(true)); Page<Record> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items(), is(RECORDS.stream().filter(r -> r.sort >= 3 && r.sort <= 5).collect(Collectors.toList()))); assertThat(page.lastEvaluatedKey(), is(nullValue())); } @Test public void queryAllRecordsWithFilterAndProjection() { insertRecords(); Map<String, AttributeValue> expressionValues = new HashMap<>(); expressionValues.put(":min_value", numberValue(3)); expressionValues.put(":max_value", numberValue(5)); Expression expression = Expression.builder() .expression("#value >= :min_value AND #value <= :max_value") .expressionValues(expressionValues) .expressionNames(Collections.singletonMap("#value", "value")) .build(); Iterator<Page<Record>> results = mappedTable.query(QueryEnhancedRequest.builder() .queryConditional(keyEqualTo(k -> k.partitionValue("id-value"))) .filterExpression(expression) .attributesToProject("value") .build()) .iterator(); assertThat(results.hasNext(), is(true)); Page<Record> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items(), hasSize(3)); assertThat(page.lastEvaluatedKey(), is(nullValue())); Record record = page.items().get(0); assertThat(record.id, nullValue()); assertThat(record.sort, nullValue()); assertThat(record.value, is(3)); } @Test public void queryBetween() { insertRecords(); Key fromKey = Key.builder().partitionValue("id-value").sortValue(3).build(); Key toKey = Key.builder().partitionValue("id-value").sortValue(5).build(); Iterator<Page<Record>> results = mappedTable.query(r -> r.queryConditional(sortBetween(fromKey, toKey))).iterator(); assertThat(results.hasNext(), is(true)); Page<Record> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items(), is(RECORDS.stream().filter(r -> r.sort >= 3 && r.sort <= 5).collect(Collectors.toList()))); assertThat(page.lastEvaluatedKey(), is(nullValue())); } @Test public void queryLimit() { insertRecords(); Iterator<Page<Record>> results = mappedTable.query(QueryEnhancedRequest.builder() .queryConditional(keyEqualTo(k -> k.partitionValue("id-value"))) .limit(5) .build()) .iterator(); assertThat(results.hasNext(), is(true)); Page<Record> page1 = results.next(); assertThat(results.hasNext(), is(true)); Page<Record> page2 = results.next(); assertThat(results.hasNext(), is(true)); Page<Record> page3 = results.next(); assertThat(results.hasNext(), is(false)); Map<String, AttributeValue> expectedLastEvaluatedKey1 = new HashMap<>(); expectedLastEvaluatedKey1.put("id", stringValue("id-value")); expectedLastEvaluatedKey1.put("sort", numberValue(4)); Map<String, AttributeValue> expectedLastEvaluatedKey2 = new HashMap<>(); expectedLastEvaluatedKey2.put("id", stringValue("id-value")); expectedLastEvaluatedKey2.put("sort", numberValue(9)); assertThat(page1.items(), is(RECORDS.subList(0, 5))); assertThat(page1.lastEvaluatedKey(), is(expectedLastEvaluatedKey1)); assertThat(page2.items(), is(RECORDS.subList(5, 10))); assertThat(page2.lastEvaluatedKey(), is(expectedLastEvaluatedKey2)); assertThat(page3.items(), is(empty())); assertThat(page3.lastEvaluatedKey(), is(nullValue())); } @Test public void queryEmpty() { Iterator<Page<Record>> results = mappedTable.query(r -> r.queryConditional(keyEqualTo(k -> k.partitionValue("id-value")))).iterator(); assertThat(results.hasNext(), is(true)); Page<Record> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items(), is(empty())); assertThat(page.lastEvaluatedKey(), is(nullValue())); } @Test public void queryEmpty_viaItems() { PageIterable<Record> query = mappedTable.query(keyEqualTo(k -> k.partitionValue("id-value"))); SdkIterable<Record> results = query.items(); assertThat(results.stream().collect(Collectors.toList()), is(empty())); } @Test public void queryExclusiveStartKey() { Map<String, AttributeValue> exclusiveStartKey = new HashMap<>(); exclusiveStartKey.put("id", stringValue("id-value")); exclusiveStartKey.put("sort", numberValue(7)); insertRecords(); Iterator<Page<Record>> results = mappedTable.query(QueryEnhancedRequest.builder() .queryConditional(keyEqualTo(k -> k.partitionValue("id-value"))) .exclusiveStartKey(exclusiveStartKey) .build()) .iterator(); assertThat(results.hasNext(), is(true)); Page<Record> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items(), is(RECORDS.subList(8, 10))); assertThat(page.lastEvaluatedKey(), is(nullValue())); } @Test public void queryExclusiveStartKey_viaItems() { Map<String, AttributeValue> exclusiveStartKey = new HashMap<>(); exclusiveStartKey.put("id", stringValue("id-value")); exclusiveStartKey.put("sort", numberValue(7)); insertRecords(); SdkIterable<Record> results = mappedTable.query(QueryEnhancedRequest.builder() .queryConditional(keyEqualTo(k -> k.partitionValue("id-value"))) .exclusiveStartKey(exclusiveStartKey) .build()) .items(); assertThat(results.stream().collect(Collectors.toList()), is(RECORDS.subList(8, 10))); } @Test public void queryNestedRecord_SingleAttributeName() { insertNestedRecords(); Iterator<Page<NestedTestRecord>> results = mappedNestedTable.query(b -> b .queryConditional(keyEqualTo(k -> k.partitionValue("id-value-1"))) .addNestedAttributeToProject(NestedAttributeName.builder().addElement("innerAttributeRecord") .addElement("attribOne").build())).iterator(); assertThat(results.hasNext(), is(true)); Page<NestedTestRecord> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items().size(), is(1)); NestedTestRecord firstRecord = page.items().get(0); assertThat(firstRecord.getOuterAttribOne(), is(nullValue())); assertThat(firstRecord.getSort(), is(nullValue())); assertThat(firstRecord.getInnerAttributeRecord().getAttribOne(), is("attribOne-1")); assertThat(firstRecord.getInnerAttributeRecord().getAttribTwo(), is(nullValue())); results = mappedNestedTable.query(b -> b .queryConditional(keyEqualTo(k -> k.partitionValue("id-value-1"))) .addAttributeToProject("sort")).iterator(); assertThat(results.hasNext(), is(true)); page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items().size(), is(1)); firstRecord = page.items().get(0); assertThat(firstRecord.getOuterAttribOne(), is(nullValue())); assertThat(firstRecord.getSort(), is(1)); assertThat(firstRecord.getInnerAttributeRecord(), is(nullValue())); } @Test public void queryNestedRecord_withAttributeNameList() { insertNestedRecords(); Iterator<Page<NestedTestRecord>> results = mappedNestedTable.query(b -> b .queryConditional(keyEqualTo(k -> k.partitionValue("id-value-1"))) .addNestedAttributesToProject(Arrays.asList( NestedAttributeName.builder().elements("innerAttributeRecord", "attribOne").build(), NestedAttributeName.builder().addElement("outerAttribOne").build())) .addNestedAttributesToProject(NestedAttributeName.builder() .addElements(Arrays.asList("innerAttributeRecord", "attribTwo")).build())).iterator(); assertThat(results.hasNext(), is(true)); Page<NestedTestRecord> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items().size(), is(1)); NestedTestRecord firstRecord = page.items().get(0); assertThat(firstRecord.getOuterAttribOne(), is("id-value-1")); assertThat(firstRecord.getSort(), is(nullValue())); assertThat(firstRecord.getInnerAttributeRecord().getAttribOne(), is("attribOne-1")); assertThat(firstRecord.getInnerAttributeRecord().getAttribTwo(), is(1)); } @Test public void queryNestedRecord_withAttributeNameListAndStringAttributeToProjectAppended() { insertNestedRecords(); Iterator<Page<NestedTestRecord>> results = mappedNestedTable.query(b -> b .queryConditional(keyEqualTo(k -> k.partitionValue("id-value-1"))) .addNestedAttributesToProject(Arrays.asList( NestedAttributeName.builder().elements("innerAttributeRecord","attribOne").build())) .addNestedAttributesToProject(NestedAttributeName.create("innerAttributeRecord","attribTwo")) .addAttributeToProject("sort")).iterator(); assertThat(results.hasNext(), is(true)); Page<NestedTestRecord> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items().size(), is(1)); NestedTestRecord firstRecord = page.items().get(0); assertThat(firstRecord.getOuterAttribOne(), is(is(nullValue()))); assertThat(firstRecord.getSort(), is(1)); assertThat(firstRecord.getInnerAttributeRecord().getAttribOne(), is("attribOne-1")); assertThat(firstRecord.getInnerAttributeRecord().getAttribTwo(), is(1)); } @Test public void queryAllRecordsDefaultSettings_withNestedProjectionNamesNotInNameMap() { insertNestedRecords(); Iterator<Page<NestedTestRecord>> results = mappedNestedTable.query(b -> b .queryConditional(keyEqualTo(k -> k.partitionValue("id-value-1"))) .addNestedAttributeToProject( NestedAttributeName.builder().addElement("nonExistentSlot").build())).iterator(); assertThat(results.hasNext(), is(true)); Page<NestedTestRecord> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items().size(), is(1)); NestedTestRecord firstRecord = page.items().get(0); assertThat(firstRecord, is(nullValue())); } @Test public void queryRecordDefaultSettings_withDotInTheName() { insertNestedRecords(); Iterator<Page<NestedTestRecord>> results = mappedNestedTable.query(b -> b .queryConditional(keyEqualTo(k -> k.partitionValue("id-value-7"))) .addNestedAttributeToProject( NestedAttributeName.create("test.com"))).iterator(); assertThat(results.hasNext(), is(true)); Page<NestedTestRecord> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items().size(), is(1)); NestedTestRecord firstRecord = page.items().get(0); assertThat(firstRecord.getOuterAttribOne(), is(is(nullValue()))); assertThat(firstRecord.getSort(), is(is(nullValue()))); assertThat(firstRecord.getInnerAttributeRecord() , is(nullValue())); assertThat(firstRecord.getDotVariable(), is("v7")); Iterator<Page<NestedTestRecord>> resultWithAttributeToProject = mappedNestedTable.query(b -> b .queryConditional(keyEqualTo(k -> k.partitionValue("id-value-7"))) .attributesToProject( "test.com").build()).iterator(); assertThat(resultWithAttributeToProject.hasNext(), is(true)); Page<NestedTestRecord> pageResult = resultWithAttributeToProject.next(); assertThat(resultWithAttributeToProject.hasNext(), is(false)); assertThat(pageResult.items().size(), is(1)); NestedTestRecord record = pageResult.items().get(0); assertThat(record.getOuterAttribOne(), is(is(nullValue()))); assertThat(record.getSort(), is(is(nullValue()))); assertThat(firstRecord.getInnerAttributeRecord() , is(nullValue())); assertThat(record.getDotVariable(), is("v7")); } @Test public void queryRecordDefaultSettings_withEmptyAttributeList() { insertNestedRecords(); Iterator<Page<NestedTestRecord>> results = mappedNestedTable.query(b -> b .queryConditional(keyEqualTo(k -> k.partitionValue("id-value-7"))) .attributesToProject(new ArrayList<>()).build()).iterator(); assertThat(results.hasNext(), is(true)); Page<NestedTestRecord> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items().size(), is(1)); NestedTestRecord firstRecord = page.items().get(0); assertThat(firstRecord.getOuterAttribOne(), is("id-value-7")); assertThat(firstRecord.getSort(), is(7)); assertThat(firstRecord.getInnerAttributeRecord().getAttribTwo(), is(7)); assertThat(firstRecord.getDotVariable(), is("v7")); } @Test public void queryRecordDefaultSettings_withNullAttributeList() { insertNestedRecords(); List<String> backwardCompatibilty = null; Iterator<Page<NestedTestRecord>> results = mappedNestedTable.query(b -> b .queryConditional(keyEqualTo(k -> k.partitionValue("id-value-7"))) .attributesToProject(backwardCompatibilty).build()).iterator(); assertThat(results.hasNext(), is(true)); Page<NestedTestRecord> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items().size(), is(1)); NestedTestRecord firstRecord = page.items().get(0); assertThat(firstRecord.getOuterAttribOne(), is("id-value-7")); assertThat(firstRecord.getSort(), is(7)); assertThat(firstRecord.getInnerAttributeRecord().getAttribTwo(), is(7)); assertThat(firstRecord.getDotVariable(), is("v7")); } @Test public void queryAllRecordsDefaultSettings_withNestedProjectionNameEmptyNameMap() { insertNestedRecords(); assertThatExceptionOfType(Exception.class).isThrownBy( () -> { Iterator<Page<NestedTestRecord>> results = mappedNestedTable.query(b -> b.queryConditional( keyEqualTo(k -> k.partitionValue("id-value-3"))) .attributesToProject("").build()).iterator(); assertThat(results.hasNext(), is(true)); Page<NestedTestRecord> page = results.next(); }); assertThatExceptionOfType(Exception.class).isThrownBy( () -> { Iterator<Page<NestedTestRecord>> results = mappedNestedTable.query(b -> b.queryConditional( keyEqualTo(k -> k.partitionValue("id-value-3"))) .addNestedAttributeToProject(NestedAttributeName.create("")).build()).iterator(); assertThat(results.hasNext(), is(true)); Page<NestedTestRecord> page = results.next(); }); } }
4,126
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/VersionedRecordTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static software.amazon.awssdk.enhanced.dynamodb.extensions.VersionedRecordExtension.AttributeTags.versionAttribute; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.stringValue; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey; import java.util.Objects; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.Expression; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.extensions.VersionedRecordExtension; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema; import software.amazon.awssdk.enhanced.dynamodb.model.PutItemEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.UpdateItemEnhancedRequest; import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException; import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; public class VersionedRecordTest extends LocalDynamoDbSyncTestBase { private static class Record { private String id; private String attribute; private Integer version; private String getId() { return id; } private Record setId(String id) { this.id = id; return this; } private String getAttribute() { return attribute; } private Record setAttribute(String attribute) { this.attribute = attribute; return this; } private Integer getVersion() { return version; } private Record setVersion(Integer version) { this.version = version; return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Record record = (Record) o; return Objects.equals(id, record.id) && Objects.equals(attribute, record.attribute) && Objects.equals(version, record.version); } @Override public int hashCode() { return Objects.hash(id, attribute, version); } } private static final TableSchema<Record> TABLE_SCHEMA = StaticTableSchema.builder(Record.class) .newItemSupplier(Record::new) .addAttribute(String.class, a -> a.name("id") .getter(Record::getId) .setter(Record::setId) .tags(primaryPartitionKey())) .addAttribute(String.class, a -> a.name("attribute") .getter(Record::getAttribute) .setter(Record::setAttribute)) .addAttribute(Integer.class, a -> a.name("version") .getter(Record::getVersion) .setter(Record::setVersion) .tags(versionAttribute())) .build(); private DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() .dynamoDbClient(getDynamoDbClient()) .extensions(VersionedRecordExtension.builder().build()) .build(); private DynamoDbTable<Record> mappedTable = enhancedClient.table(getConcreteTableName("table-name"), TABLE_SCHEMA); @Rule public ExpectedException exception = ExpectedException.none(); @Before public void createTable() { mappedTable.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput())); } @After public void deleteTable() { getDynamoDbClient().deleteTable(DeleteTableRequest.builder() .tableName(getConcreteTableName("table-name")) .build()); } @Test public void putNewRecordSetsInitialVersion() { mappedTable.putItem(r -> r.item(new Record().setId("id").setAttribute("one"))); Record result = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id"))); Record expectedResult = new Record().setId("id").setAttribute("one").setVersion(1); assertThat(result, is(expectedResult)); } @Test public void updateNewRecordSetsInitialVersion() { Record result = mappedTable.updateItem(r -> r.item(new Record().setId("id").setAttribute("one"))); Record expectedResult = new Record().setId("id").setAttribute("one").setVersion(1); assertThat(result, is(expectedResult)); } @Test public void putExistingRecordVersionMatches() { mappedTable.putItem(r -> r.item(new Record().setId("id").setAttribute("one"))); mappedTable.putItem(r -> r.item(new Record().setId("id").setAttribute("one").setVersion(1))); Record result = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id"))); Record expectedResult = new Record().setId("id").setAttribute("one").setVersion(2); assertThat(result, is(expectedResult)); } @Test public void putExistingRecordVersionMatchesConditionExpressionMatches() { mappedTable.putItem(r -> r.item(new Record().setId("id").setAttribute("one"))); Expression conditionExpression = Expression.builder() .expression("#k = :v OR #k = :v1") .putExpressionName("#k", "attribute") .putExpressionValue(":v", stringValue("wrong")) .putExpressionValue(":v1", stringValue("one")) .build(); mappedTable.putItem(PutItemEnhancedRequest.builder(Record.class) .item(new Record().setId("id").setAttribute("one").setVersion(1)) .conditionExpression(conditionExpression) .build()); Record result = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id"))); Record expectedResult = new Record().setId("id").setAttribute("one").setVersion(2); assertThat(result, is(expectedResult)); } @Test public void putExistingRecordVersionDoesNotMatchConditionExpressionMatches() { mappedTable.putItem(r -> r.item(new Record().setId("id").setAttribute("one"))); Expression conditionExpression = Expression.builder() .expression("#k = :v OR #k = :v1") .putExpressionName("#k", "attribute") .putExpressionValue(":v", stringValue("wrong")) .putExpressionValue(":v1", stringValue("one")) .build(); exception.expect(ConditionalCheckFailedException.class); mappedTable.putItem(PutItemEnhancedRequest.builder(Record.class) .item(new Record().setId("id").setAttribute("one").setVersion(2)) .conditionExpression(conditionExpression) .build()); } @Test public void putExistingRecordVersionMatchesConditionExpressionDoesNotMatch() { mappedTable.putItem(r -> r.item(new Record().setId("id").setAttribute("one"))); Expression conditionExpression = Expression.builder() .expression("#k = :v OR #k = :v1") .putExpressionName("#k", "attribute") .putExpressionValue(":v", stringValue("wrong")) .putExpressionValue(":v1", stringValue("wrong2")) .build(); exception.expect(ConditionalCheckFailedException.class); mappedTable.putItem(PutItemEnhancedRequest.builder(Record.class) .item(new Record().setId("id").setAttribute("one").setVersion(1)) .conditionExpression(conditionExpression) .build()); } @Test public void updateExistingRecordVersionMatchesConditionExpressionMatches() { mappedTable.putItem(r -> r.item(new Record().setId("id").setAttribute("one"))); Expression conditionExpression = Expression.builder() .expression("#k = :v OR #k = :v1") .putExpressionName("#k", "attribute") .putExpressionValue(":v", stringValue("wrong")) .putExpressionValue(":v1", stringValue("one")) .build(); mappedTable.updateItem(UpdateItemEnhancedRequest.builder(Record.class) .item(new Record().setId("id").setAttribute("one").setVersion(1)) .conditionExpression(conditionExpression) .build()); Record result = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id"))); Record expectedResult = new Record().setId("id").setAttribute("one").setVersion(2); assertThat(result, is(expectedResult)); } @Test public void updateExistingRecordVersionDoesNotMatchConditionExpressionMatches() { mappedTable.putItem(r -> r.item(new Record().setId("id").setAttribute("one"))); Expression conditionExpression = Expression.builder() .expression("#k = :v OR #k = :v1") .putExpressionName("#k", "attribute") .putExpressionValue(":v", stringValue("wrong")) .putExpressionValue(":v1", stringValue("one")) .build(); exception.expect(ConditionalCheckFailedException.class); mappedTable.updateItem(UpdateItemEnhancedRequest.builder(Record.class) .item(new Record().setId("id").setAttribute("one").setVersion(2)) .conditionExpression(conditionExpression) .build()); } @Test public void updateExistingRecordVersionMatchesConditionExpressionDoesNotMatch() { mappedTable.putItem(r -> r.item(new Record().setId("id").setAttribute("one"))); Expression conditionExpression = Expression.builder() .expression("#k = :v OR #k = :v1") .putExpressionName("#k", "attribute") .putExpressionValue(":v", stringValue("wrong")) .putExpressionValue(":v1", stringValue("wrong2")) .build(); exception.expect(ConditionalCheckFailedException.class); mappedTable.updateItem(UpdateItemEnhancedRequest.builder(Record.class) .item(new Record().setId("id").setAttribute("one").setVersion(1)) .conditionExpression(conditionExpression) .build()); } @Test public void updateExistingRecordVersionMatches() { mappedTable.putItem(r -> r.item(new Record().setId("id").setAttribute("one"))); Record result = mappedTable.updateItem(r -> r.item(new Record().setId("id").setAttribute("one").setVersion(1))); Record expectedResult = new Record().setId("id").setAttribute("one").setVersion(2); assertThat(result, is(expectedResult)); } @Test(expected = ConditionalCheckFailedException.class) public void putNewRecordTwice() { mappedTable.putItem(r -> r.item(new Record().setId("id").setAttribute("one"))); mappedTable.putItem(r -> r.item(new Record().setId("id").setAttribute("one"))); } @Test(expected = ConditionalCheckFailedException.class) public void updateNewRecordTwice() { mappedTable.updateItem(r -> r.item(new Record().setId("id").setAttribute("one"))); mappedTable.updateItem(r -> r.item(new Record().setId("id").setAttribute("one"))); } @Test(expected = ConditionalCheckFailedException.class) public void putRecordWithWrongVersionNumber() { mappedTable.putItem(r -> r.item(new Record().setId("id").setAttribute("one"))); mappedTable.putItem(r -> r.item(new Record().setId("id").setAttribute("one").setVersion(2))); } }
4,127
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/AsyncBasicControlPlaneTableOperationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests; import static org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primarySortKey; import java.util.Objects; import org.junit.After; import org.junit.Before; import org.junit.Test; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbAsyncTable; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedAsyncClient; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.internal.client.DefaultDynamoDbEnhancedAsyncClient; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema; import software.amazon.awssdk.enhanced.dynamodb.model.CreateTableEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.DescribeTableEnhancedResponse; import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; public class AsyncBasicControlPlaneTableOperationTest extends LocalDynamoDbAsyncTestBase { private static final TableSchema<Record> TABLE_SCHEMA = StaticTableSchema.builder(Record.class) .newItemSupplier(Record::new) .addAttribute(String.class, a -> a.name("id") .getter(Record::getId) .setter(Record::setId) .tags(primaryPartitionKey())) .addAttribute(Integer.class, a -> a.name("sort") .getter(Record::getSort) .setter(Record::setSort) .tags(primarySortKey())) .build(); private final String tableName = getConcreteTableName("table-name"); private final DynamoDbEnhancedAsyncClient enhancedAsyncClient = DefaultDynamoDbEnhancedAsyncClient.builder() .dynamoDbClient(getDynamoDbAsyncClient()) .build(); private final DynamoDbAsyncTable<AsyncBasicControlPlaneTableOperationTest.Record> asyncMappedTable = enhancedAsyncClient.table(tableName, TABLE_SCHEMA); @Before public void createTable() { asyncMappedTable.createTable( CreateTableEnhancedRequest.builder() .provisionedThroughput(getDefaultProvisionedThroughput()) .build()).join(); getDynamoDbAsyncClient().waiter().waitUntilTableExists(b -> b.tableName(tableName)).join(); } @After public void deleteTable() { getDynamoDbAsyncClient().deleteTable(DeleteTableRequest.builder() .tableName(tableName) .build()) .join(); getDynamoDbAsyncClient().waiter().waitUntilTableNotExists(b -> b.tableName(tableName)).join(); } @Test public void describeTable() { DescribeTableEnhancedResponse describeTableEnhancedResponse = asyncMappedTable.describeTable().join(); assertThat(describeTableEnhancedResponse.table()).isNotNull(); assertThat(describeTableEnhancedResponse.table().tableName()).isEqualTo(tableName); } private static class Record { private String id; private Integer sort; private String getId() { return id; } private Record setId(String id) { this.id = id; return this; } private Integer getSort() { return sort; } private Record setSort(Integer sort) { this.sort = sort; return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Record record = (Record) o; return Objects.equals(id, record.id) && Objects.equals(sort, record.sort); } @Override public int hashCode() { return Objects.hash(id, sort); } } }
4,128
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/AsyncPutItemWithResponseTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests; import static org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey; import java.util.Objects; import org.junit.After; import org.junit.Before; import org.junit.Test; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbAsyncTable; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedAsyncClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema; import software.amazon.awssdk.enhanced.dynamodb.model.PutItemEnhancedResponse; import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; import software.amazon.awssdk.services.dynamodb.model.ReturnConsumedCapacity; import software.amazon.awssdk.services.dynamodb.model.ReturnValue; public class AsyncPutItemWithResponseTest extends LocalDynamoDbAsyncTestBase { private static class Record { private Integer id; private String stringAttr1; private Integer getId() { return id; } private Record setId(Integer id) { this.id = id; return this; } private String getStringAttr1() { return stringAttr1; } private Record setStringAttr1(String stringAttr1) { this.stringAttr1 = stringAttr1; return this; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Record record = (Record) o; return Objects.equals(id, record.id) && Objects.equals(stringAttr1, record.stringAttr1); } @Override public int hashCode() { return Objects.hash(id, stringAttr1); } } private static final TableSchema<Record> TABLE_SCHEMA = StaticTableSchema.builder(Record.class) .newItemSupplier(Record::new) .addAttribute(Integer.class, a -> a.name("id_1") .getter(Record::getId) .setter(Record::setId) .tags(primaryPartitionKey())) .addAttribute(String.class, a -> a.name("stringAttr1") .getter(Record::getStringAttr1) .setter(Record::setStringAttr1)) .build(); private final DynamoDbEnhancedAsyncClient enhancedClient = DynamoDbEnhancedAsyncClient.builder() .dynamoDbClient(getDynamoDbAsyncClient()) .build(); private final DynamoDbAsyncTable<Record> mappedTable1 = enhancedClient.table(getConcreteTableName("table-name-1"), TABLE_SCHEMA); @Before public void createTable() { mappedTable1.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput())) .join(); } @After public void deleteTable() { getDynamoDbAsyncClient().deleteTable(DeleteTableRequest.builder() .tableName(getConcreteTableName("table-name-1")) .build()) .join(); } @Test public void returnValues_unset_attributesNull() { Record record = new Record().setId(1).setStringAttr1("a"); mappedTable1.putItem(record).join(); record.setStringAttr1("b"); PutItemEnhancedResponse<Record> response = mappedTable1.putItemWithResponse(r -> r.item(record)).join(); assertThat(response.attributes()).isNull(); } @Test public void returnValues_allOld_attributesMapped() { Record original = new Record().setId(1).setStringAttr1("a"); mappedTable1.putItem(original).join(); Record update = new Record().setId(1).setStringAttr1("b"); PutItemEnhancedResponse<Record> response = mappedTable1.putItemWithResponse(r -> r.returnValues(ReturnValue.ALL_OLD) .item(update)) .join(); Record returned = response.attributes(); assertThat(returned).isEqualTo(original); } @Test public void returnConsumedCapacity_unset_consumedCapacityNull() { Record record = new Record().setId(1).setStringAttr1("a"); PutItemEnhancedResponse<Record> response = mappedTable1.putItemWithResponse(r -> r.item(record)).join(); assertThat(response.consumedCapacity()).isNull(); } @Test public void returnConsumedCapacity_set_consumedCapacityNotNull() { Record record = new Record().setId(1).setStringAttr1("a"); PutItemEnhancedResponse<Record> response = mappedTable1.putItemWithResponse(r -> r.item(record) .returnConsumedCapacity(ReturnConsumedCapacity.TOTAL)) .join(); assertThat(response.consumedCapacity()).isNotNull(); } // Note: DynamoDB Local does not support returning ItemCollectionMetrics. See AsyncPutItemWithResponseIntegrationTest for // additional testing for this method. @Test public void returnItemCollectionMetrics_unset_itemCollectionMetricsNull() { Record record = new Record().setId(1); PutItemEnhancedResponse<Record> response = mappedTable1.putItemWithResponse(r -> r.item(record)) .join(); assertThat(response.consumedCapacity()).isNull(); } }
4,129
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/LocalDynamoDbSyncTestBase.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests; import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; public class LocalDynamoDbSyncTestBase extends LocalDynamoDbTestBase { private DynamoDbClient dynamoDbClient = localDynamoDb().createClient(); protected DynamoDbClient getDynamoDbClient() { return dynamoDbClient; } }
4,130
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/AutoGeneratedTimestampRecordTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, AutoTimestamp 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests; import static java.util.stream.Collectors.toList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static software.amazon.awssdk.enhanced.dynamodb.extensions.AutoGeneratedTimestampRecordExtension.AttributeTags.autoGeneratedTimestampAttribute; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.stringValue; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.updateBehavior; import java.time.Clock; import java.time.Instant; import java.time.ZoneOffset; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.UUID; import java.util.stream.IntStream; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.mockito.Mockito; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.Expression; import software.amazon.awssdk.enhanced.dynamodb.OperationContext; import software.amazon.awssdk.enhanced.dynamodb.TableMetadata; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.converters.EpochMillisFormatTestConverter; import software.amazon.awssdk.enhanced.dynamodb.converters.TimeFormatUpdateTestConverter; import software.amazon.awssdk.enhanced.dynamodb.extensions.AutoGeneratedTimestampRecordExtension; import software.amazon.awssdk.enhanced.dynamodb.internal.extensions.DefaultDynamoDbExtensionContext; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.DefaultOperationContext; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema; import software.amazon.awssdk.enhanced.dynamodb.mapper.UpdateBehavior; import software.amazon.awssdk.enhanced.dynamodb.model.PutItemEnhancedRequest; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException; import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; import software.amazon.awssdk.services.dynamodb.model.GetItemRequest; import software.amazon.awssdk.services.dynamodb.model.GetItemResponse; public class AutoGeneratedTimestampRecordTest extends LocalDynamoDbSyncTestBase { public static final Instant MOCKED_INSTANT_NOW = Instant.now(Clock.fixed(Instant.parse("2019-01-13T14:00:00Z"), ZoneOffset.UTC)); public static final Instant MOCKED_INSTANT_UPDATE_ONE = Instant.now(Clock.fixed(Instant.parse("2019-01-14T14:00:00Z"), ZoneOffset.UTC)); public static final Instant MOCKED_INSTANT_UPDATE_TWO = Instant.now(Clock.fixed(Instant.parse("2019-01-15T14:00:00Z"), ZoneOffset.UTC)); private static final String TABLE_NAME = "table-name"; private static final OperationContext PRIMARY_CONTEXT = DefaultOperationContext.create(TABLE_NAME, TableMetadata.primaryIndexName()); private static final TableSchema<FlattenedRecord> FLATTENED_TABLE_SCHEMA = StaticTableSchema.builder(FlattenedRecord.class) .newItemSupplier(FlattenedRecord::new) .addAttribute(Instant.class, a -> a.name("generated") .getter(FlattenedRecord::getGenerated) .setter(FlattenedRecord::setGenerated) .tags(autoGeneratedTimestampAttribute())) .build(); private static final TableSchema<Record> TABLE_SCHEMA = StaticTableSchema.builder(Record.class) .newItemSupplier(Record::new) .addAttribute(String.class, a -> a.name("id") .getter(Record::getId) .setter(Record::setId) .tags(primaryPartitionKey())) .addAttribute(String.class, a -> a.name("attribute") .getter(Record::getAttribute) .setter(Record::setAttribute)) .addAttribute(Instant.class, a -> a.name("lastUpdatedDate") .getter(Record::getLastUpdatedDate) .setter(Record::setLastUpdatedDate) .tags(autoGeneratedTimestampAttribute())) .addAttribute(Instant.class, a -> a.name("createdDate") .getter(Record::getCreatedDate) .setter(Record::setCreatedDate) .tags(autoGeneratedTimestampAttribute(), updateBehavior(UpdateBehavior.WRITE_IF_NOT_EXISTS))) .addAttribute(Instant.class, a -> a.name("lastUpdatedDateInEpochMillis") .getter(Record::getLastUpdatedDateInEpochMillis) .setter(Record::setLastUpdatedDateInEpochMillis) .attributeConverter(EpochMillisFormatTestConverter.create()) .tags(autoGeneratedTimestampAttribute())) .addAttribute(Instant.class, a -> a.name("convertedLastUpdatedDate") .getter(Record::getConvertedLastUpdatedDate) .setter(Record::setConvertedLastUpdatedDate) .attributeConverter(TimeFormatUpdateTestConverter.create()) .tags(autoGeneratedTimestampAttribute())) .flatten(FLATTENED_TABLE_SCHEMA, Record::getFlattenedRecord, Record::setFlattenedRecord) .build(); private final List<Map<String, AttributeValue>> fakeItems = IntStream.range(0, 4) .mapToObj($ -> createUniqueFakeItem()) .map(fakeItem -> TABLE_SCHEMA.itemToMap(fakeItem, true)) .collect(toList()); private final DynamoDbTable<Record> mappedTable; private final Clock mockCLock = Mockito.mock(Clock.class); private final DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() .dynamoDbClient(getDynamoDbClient()) .extensions(AutoGeneratedTimestampRecordExtension.builder().baseClock(mockCLock).build()) .build(); private final String concreteTableName; @Rule public ExpectedException thrown = ExpectedException.none(); { concreteTableName = getConcreteTableName("table-name"); mappedTable = enhancedClient.table(concreteTableName, TABLE_SCHEMA); } public static Record createUniqueFakeItem() { Record record = new Record(); record.setId(UUID.randomUUID().toString()); return record; } @Before public void createTable() { Mockito.when(mockCLock.instant()).thenReturn(MOCKED_INSTANT_NOW); mappedTable.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput())); } @After public void deleteTable() { getDynamoDbClient().deleteTable(DeleteTableRequest.builder() .tableName(getConcreteTableName("table-name")) .build()); } @Test public void putNewRecordSetsInitialAutoGeneratedTimestamp() { Record item = new Record().setId("id").setAttribute("one"); mappedTable.putItem(r -> r.item(item)); Record result = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id"))); GetItemResponse itemAsStoredInDDB = getItemAsStoredFromDDB(); FlattenedRecord flattenedRecord = new FlattenedRecord().setGenerated(MOCKED_INSTANT_NOW); Record expectedRecord = new Record().setId("id") .setAttribute("one") .setLastUpdatedDate(MOCKED_INSTANT_NOW) .setConvertedLastUpdatedDate(MOCKED_INSTANT_NOW) .setCreatedDate(MOCKED_INSTANT_NOW) .setLastUpdatedDateInEpochMillis(MOCKED_INSTANT_NOW) .setFlattenedRecord(flattenedRecord); assertThat(result, is(expectedRecord)); // The data in DDB is stored in converted time format assertThat(itemAsStoredInDDB.item().get("convertedLastUpdatedDate").s(), is("13 01 2019 14:00:00")); } @Test public void updateNewRecordSetsAutoFormattedDate() { Record result = mappedTable.updateItem(r -> r.item(new Record().setId("id").setAttribute("one"))); GetItemResponse itemAsStoredInDDB = getItemAsStoredFromDDB(); FlattenedRecord flattenedRecord = new FlattenedRecord().setGenerated(MOCKED_INSTANT_NOW); Record expectedRecord = new Record().setId("id") .setAttribute("one") .setLastUpdatedDate(MOCKED_INSTANT_NOW) .setConvertedLastUpdatedDate(MOCKED_INSTANT_NOW) .setCreatedDate(MOCKED_INSTANT_NOW) .setLastUpdatedDateInEpochMillis(MOCKED_INSTANT_NOW) .setFlattenedRecord(flattenedRecord); assertThat(result, is(expectedRecord)); // The data in DDB is stored in converted time format assertThat(itemAsStoredInDDB.item().get("convertedLastUpdatedDate").s(), is("13 01 2019 14:00:00")); } @Test public void putExistingRecordUpdatedWithAutoFormattedTimestamps() { mappedTable.putItem(r -> r.item(new Record().setId("id").setAttribute("one"))); Record result = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id"))); GetItemResponse itemAsStoredInDDB = getItemAsStoredFromDDB(); FlattenedRecord flattenedRecord = new FlattenedRecord().setGenerated(MOCKED_INSTANT_NOW); Record expectedRecord = new Record().setId("id") .setAttribute("one") .setLastUpdatedDate(MOCKED_INSTANT_NOW) .setConvertedLastUpdatedDate(MOCKED_INSTANT_NOW) .setCreatedDate(MOCKED_INSTANT_NOW) .setLastUpdatedDateInEpochMillis(MOCKED_INSTANT_NOW) .setFlattenedRecord(flattenedRecord); assertThat(result, is(expectedRecord)); // The data in DDB is stored in converted time format assertThat(itemAsStoredInDDB.item().get("convertedLastUpdatedDate").s(), is("13 01 2019 14:00:00")); Mockito.when(mockCLock.instant()).thenReturn(MOCKED_INSTANT_UPDATE_ONE); mappedTable.putItem(r -> r.item(new Record().setId("id").setAttribute("one"))); result = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id"))); itemAsStoredInDDB = getItemAsStoredFromDDB(); flattenedRecord = new FlattenedRecord().setGenerated(MOCKED_INSTANT_UPDATE_ONE); expectedRecord = new Record().setId("id") .setAttribute("one") .setLastUpdatedDate(MOCKED_INSTANT_UPDATE_ONE) .setConvertedLastUpdatedDate(MOCKED_INSTANT_UPDATE_ONE) // Note : Since we are doing PutItem second time, the createDate gets updated, .setCreatedDate(MOCKED_INSTANT_UPDATE_ONE) .setLastUpdatedDateInEpochMillis(MOCKED_INSTANT_UPDATE_ONE) .setFlattenedRecord(flattenedRecord); System.out.println("result "+result); assertThat(result, is(expectedRecord)); // The data in DDB is stored in converted time format assertThat(itemAsStoredInDDB.item().get("convertedLastUpdatedDate").s(), is("14 01 2019 14:00:00")); } @Test public void putItemFollowedByUpdates() { mappedTable.putItem(r -> r.item(new Record().setId("id").setAttribute("one"))); Record result = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id"))); GetItemResponse itemAsStoredInDDB = getItemAsStoredFromDDB(); FlattenedRecord flattenedRecord = new FlattenedRecord().setGenerated(MOCKED_INSTANT_NOW); Record expectedRecord = new Record().setId("id") .setAttribute("one") .setLastUpdatedDate(MOCKED_INSTANT_NOW) .setConvertedLastUpdatedDate(MOCKED_INSTANT_NOW) .setCreatedDate(MOCKED_INSTANT_NOW) .setLastUpdatedDateInEpochMillis(MOCKED_INSTANT_NOW) .setFlattenedRecord(flattenedRecord); assertThat(result, is(expectedRecord)); // The data in DDB is stored in converted time format assertThat(itemAsStoredInDDB.item().get("convertedLastUpdatedDate").s(), is("13 01 2019 14:00:00")); //First Update Mockito.when(mockCLock.instant()).thenReturn(MOCKED_INSTANT_UPDATE_ONE); result = mappedTable.updateItem(r -> r.item(new Record().setId("id").setAttribute("one"))); itemAsStoredInDDB = getItemAsStoredFromDDB(); flattenedRecord = new FlattenedRecord().setGenerated(MOCKED_INSTANT_UPDATE_ONE); expectedRecord = new Record().setId("id") .setAttribute("one") .setLastUpdatedDate(MOCKED_INSTANT_UPDATE_ONE) .setConvertedLastUpdatedDate(MOCKED_INSTANT_UPDATE_ONE) .setCreatedDate(MOCKED_INSTANT_NOW) .setLastUpdatedDateInEpochMillis(MOCKED_INSTANT_UPDATE_ONE) .setFlattenedRecord(flattenedRecord); assertThat(result, is(expectedRecord)); // The data in DDB is stored in converted time format assertThat(itemAsStoredInDDB.item().get("convertedLastUpdatedDate").s(), is("14 01 2019 14:00:00")); //Second Update Mockito.when(mockCLock.instant()).thenReturn(MOCKED_INSTANT_UPDATE_TWO); result = mappedTable.updateItem(r -> r.item(new Record().setId("id").setAttribute("one"))); itemAsStoredInDDB = getItemAsStoredFromDDB(); flattenedRecord = new FlattenedRecord().setGenerated(MOCKED_INSTANT_UPDATE_TWO); expectedRecord = new Record().setId("id") .setAttribute("one") .setLastUpdatedDate(MOCKED_INSTANT_UPDATE_TWO) .setConvertedLastUpdatedDate(MOCKED_INSTANT_UPDATE_TWO) .setCreatedDate(MOCKED_INSTANT_NOW) .setLastUpdatedDateInEpochMillis(MOCKED_INSTANT_UPDATE_TWO) .setFlattenedRecord(flattenedRecord); assertThat(result, is(expectedRecord)); // The data in DDB is stored in converted time format assertThat(itemAsStoredInDDB.item().get("convertedLastUpdatedDate").s(), is("15 01 2019 14:00:00")); System.out.println(Instant.ofEpochMilli(Long.parseLong(itemAsStoredInDDB.item().get("lastUpdatedDateInEpochMillis").n()))); assertThat(Long.parseLong(itemAsStoredInDDB.item().get("lastUpdatedDateInEpochMillis").n()), is(MOCKED_INSTANT_UPDATE_TWO.toEpochMilli())); } @Test public void putExistingRecordWithConditionExpressions() { mappedTable.putItem(r -> r.item(new Record().setId("id").setAttribute("one"))); Record result = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id"))); GetItemResponse itemAsStoredInDDB = getItemAsStoredFromDDB(); FlattenedRecord flattenedRecord = new FlattenedRecord().setGenerated(MOCKED_INSTANT_NOW); Record expectedRecord = new Record().setId("id") .setAttribute("one") .setLastUpdatedDate(MOCKED_INSTANT_NOW) .setConvertedLastUpdatedDate(MOCKED_INSTANT_NOW) .setCreatedDate(MOCKED_INSTANT_NOW) .setLastUpdatedDateInEpochMillis(MOCKED_INSTANT_NOW) .setFlattenedRecord(flattenedRecord); assertThat(result, is(expectedRecord)); // The data in DDB is stored in converted time format assertThat(itemAsStoredInDDB.item().get("convertedLastUpdatedDate").s(), is("13 01 2019 14:00:00")); Expression conditionExpression = Expression.builder() .expression("#k = :v OR #k = :v1") .putExpressionName("#k", "attribute") .putExpressionValue(":v", stringValue("one")) .putExpressionValue(":v1", stringValue("wrong2")) .build(); Mockito.when(mockCLock.instant()).thenReturn(MOCKED_INSTANT_UPDATE_ONE); mappedTable.putItem(PutItemEnhancedRequest.builder(Record.class) .item(new Record().setId("id").setAttribute("one")) .conditionExpression(conditionExpression) .build()); result = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id"))); flattenedRecord = new FlattenedRecord().setGenerated(MOCKED_INSTANT_UPDATE_ONE); expectedRecord = new Record().setId("id") .setAttribute("one") .setLastUpdatedDate(MOCKED_INSTANT_UPDATE_ONE) .setConvertedLastUpdatedDate(MOCKED_INSTANT_UPDATE_ONE) // Note that this is a second putItem call so create date is updated. .setCreatedDate(MOCKED_INSTANT_UPDATE_ONE) .setLastUpdatedDateInEpochMillis(MOCKED_INSTANT_UPDATE_ONE) .setFlattenedRecord(flattenedRecord); assertThat(result, is(expectedRecord)); } @Test public void updateExistingRecordWithConditionExpressions() { mappedTable.updateItem(r -> r.item(new Record().setId("id").setAttribute("one"))); GetItemResponse itemAsStoredInDDB = getItemAsStoredFromDDB(); // The data in DDB is stored in converted time format assertThat(itemAsStoredInDDB.item().get("convertedLastUpdatedDate").s(), is("13 01 2019 14:00:00")); Expression conditionExpression = Expression.builder() .expression("#k = :v OR #k = :v1") .putExpressionName("#k", "attribute") .putExpressionValue(":v", stringValue("one")) .putExpressionValue(":v1", stringValue("wrong2")) .build(); Mockito.when(mockCLock.instant()).thenReturn(MOCKED_INSTANT_UPDATE_ONE); mappedTable.updateItem(r -> r.item(new Record().setId("id").setAttribute("one")) .conditionExpression(conditionExpression)); Record result = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id"))); FlattenedRecord flattenedRecord = new FlattenedRecord().setGenerated(MOCKED_INSTANT_UPDATE_ONE); Record expectedRecord = new Record().setId("id") .setAttribute("one") .setLastUpdatedDate(MOCKED_INSTANT_UPDATE_ONE) .setConvertedLastUpdatedDate(MOCKED_INSTANT_UPDATE_ONE) .setCreatedDate(MOCKED_INSTANT_NOW) .setLastUpdatedDateInEpochMillis(MOCKED_INSTANT_UPDATE_ONE) .setFlattenedRecord(flattenedRecord); assertThat(result, is(expectedRecord)); } @Test public void putItemConditionTestFailure() { mappedTable.putItem(r -> r.item(new Record().setId("id").setAttribute("one"))); Expression conditionExpression = Expression.builder() .expression("#k = :v OR #k = :v1") .putExpressionName("#k", "attribute") .putExpressionValue(":v", stringValue("wrong1")) .putExpressionValue(":v1", stringValue("wrong2")) .build(); thrown.expect(ConditionalCheckFailedException.class); mappedTable.putItem(PutItemEnhancedRequest.builder(Record.class) .item(new Record().setId("id").setAttribute("one")) .conditionExpression(conditionExpression) .build()); } @Test public void updateItemConditionTestFailure() { mappedTable.updateItem(r -> r.item(new Record().setId("id").setAttribute("one"))); Expression conditionExpression = Expression.builder() .expression("#k = :v OR #k = :v1") .putExpressionName("#k", "attribute") .putExpressionValue(":v", stringValue("wrong1")) .putExpressionValue(":v1", stringValue("wrong2")) .build(); thrown.expect(ConditionalCheckFailedException.class); mappedTable.putItem(PutItemEnhancedRequest.builder(Record.class) .item(new Record().setId("id").setAttribute("one")) .conditionExpression(conditionExpression) .build()); } @Test public void incorrectTypeForAutoUpdateTimestampThrowsException(){ thrown.expect(IllegalArgumentException.class); thrown.expectMessage("Attribute 'lastUpdatedDate' of Class type class java.lang.String is not a suitable " + "Java Class type to be used as a Auto Generated Timestamp attribute. Only java.time." + "Instant Class type is supported."); StaticTableSchema.builder(RecordWithStringUpdateDate.class) .newItemSupplier(RecordWithStringUpdateDate::new) .addAttribute(String.class, a -> a.name("id") .getter(RecordWithStringUpdateDate::getId) .setter(RecordWithStringUpdateDate::setId) .tags(primaryPartitionKey())) .addAttribute(String.class, a -> a.name("lastUpdatedDate") .getter(RecordWithStringUpdateDate::getLastUpdatedDate) .setter(RecordWithStringUpdateDate::setLastUpdatedDate) .tags(autoGeneratedTimestampAttribute())) .build(); } private DefaultDynamoDbExtensionContext getExtensionContext() { return DefaultDynamoDbExtensionContext.builder() .tableMetadata(TABLE_SCHEMA.tableMetadata()) .operationContext(PRIMARY_CONTEXT) .tableSchema(TABLE_SCHEMA) .items(fakeItems.get(0)).build(); } private GetItemResponse getItemAsStoredFromDDB() { Map<String, AttributeValue> key = new HashMap<>(); key.put("id", AttributeValue.builder().s("id").build()); return getDynamoDbClient().getItem(GetItemRequest .builder().tableName(concreteTableName) .key(key) .consistentRead(true).build()); } private static class Record { private String id; private String attribute; private Instant createdDate; private Instant lastUpdatedDate; private Instant convertedLastUpdatedDate; private Instant lastUpdatedDateInEpochMillis; private FlattenedRecord flattenedRecord; private String getId() { return id; } private Record setId(String id) { this.id = id; return this; } private String getAttribute() { return attribute; } private Record setAttribute(String attribute) { this.attribute = attribute; return this; } private Instant getLastUpdatedDate() { return lastUpdatedDate; } private Record setLastUpdatedDate(Instant lastUpdatedDate) { this.lastUpdatedDate = lastUpdatedDate; return this; } private Instant getCreatedDate() { return createdDate; } private Record setCreatedDate(Instant createdDate) { this.createdDate = createdDate; return this; } private Instant getConvertedLastUpdatedDate() { return convertedLastUpdatedDate; } private Record setConvertedLastUpdatedDate(Instant convertedLastUpdatedDate) { this.convertedLastUpdatedDate = convertedLastUpdatedDate; return this; } private Instant getLastUpdatedDateInEpochMillis() { return lastUpdatedDateInEpochMillis; } private Record setLastUpdatedDateInEpochMillis(Instant lastUpdatedDateInEpochMillis) { this.lastUpdatedDateInEpochMillis = lastUpdatedDateInEpochMillis; return this; } public FlattenedRecord getFlattenedRecord() { return flattenedRecord; } public Record setFlattenedRecord(FlattenedRecord flattenedRecord) { this.flattenedRecord = flattenedRecord; return this; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Record record = (Record) o; return Objects.equals(id, record.id) && Objects.equals(attribute, record.attribute) && Objects.equals(lastUpdatedDate, record.lastUpdatedDate) && Objects.equals(createdDate, record.createdDate) && Objects.equals(lastUpdatedDateInEpochMillis, record.lastUpdatedDateInEpochMillis) && Objects.equals(convertedLastUpdatedDate, record.convertedLastUpdatedDate) && Objects.equals(flattenedRecord, record.flattenedRecord); } @Override public int hashCode() { return Objects.hash(id, attribute, lastUpdatedDate, createdDate, lastUpdatedDateInEpochMillis, convertedLastUpdatedDate, flattenedRecord); } @Override public String toString() { return "Record{" + "id='" + id + '\'' + ", attribute='" + attribute + '\'' + ", createdDate=" + createdDate + ", lastUpdatedDate=" + lastUpdatedDate + ", convertedLastUpdatedDate=" + convertedLastUpdatedDate + ", lastUpdatedDateInEpochMillis=" + lastUpdatedDateInEpochMillis + ", flattenedRecord=" + flattenedRecord + '}'; } } private static class FlattenedRecord { private Instant generated; public Instant getGenerated() { return generated; } public FlattenedRecord setGenerated(Instant generated) { this.generated = generated; return this; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } FlattenedRecord that = (FlattenedRecord) o; return Objects.equals(generated, that.generated); } @Override public int hashCode() { return Objects.hash(generated); } @Override public String toString() { return "FlattenedRecord{" + "generated=" + generated + '}'; } } private static class RecordWithStringUpdateDate { private String id; private String lastUpdatedDate; private String getId() { return id; } private RecordWithStringUpdateDate setId(String id) { this.id = id; return this; } private String getLastUpdatedDate() { return lastUpdatedDate; } private RecordWithStringUpdateDate setLastUpdatedDate(String lastUpdatedDate) { this.lastUpdatedDate = lastUpdatedDate; return this; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } RecordWithStringUpdateDate record = (RecordWithStringUpdateDate) o; return Objects.equals(id, record.id) && Objects.equals(lastUpdatedDate, record.lastUpdatedDate); } @Override public int hashCode() { return Objects.hash(id, lastUpdatedDate); } @Override public String toString() { return "RecordWithStringUpdateDate{" + "id='" + id + '\'' + ", lastUpdatedDate=" + lastUpdatedDate + '}'; } } }
4,131
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/AsyncBasicScanTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.numberValue; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.stringValue; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primarySortKey; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.junit.After; import org.junit.Before; import org.junit.Test; import software.amazon.awssdk.core.async.SdkPublisher; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbAsyncTable; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedAsyncClient; import software.amazon.awssdk.enhanced.dynamodb.Expression; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.internal.client.DefaultDynamoDbEnhancedAsyncClient; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema; import software.amazon.awssdk.enhanced.dynamodb.model.Page; import software.amazon.awssdk.enhanced.dynamodb.model.ScanEnhancedRequest; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; public class AsyncBasicScanTest extends LocalDynamoDbAsyncTestBase { private static class Record { private String id; private Integer sort; private String getId() { return id; } private Record setId(String id) { this.id = id; return this; } private Integer getSort() { return sort; } private Record setSort(Integer sort) { this.sort = sort; return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Record record = (Record) o; return Objects.equals(id, record.id) && Objects.equals(sort, record.sort); } @Override public int hashCode() { return Objects.hash(id, sort); } } private static final TableSchema<Record> TABLE_SCHEMA = StaticTableSchema.builder(Record.class) .newItemSupplier(Record::new) .addAttribute(String.class, a -> a.name("id") .getter(Record::getId) .setter(Record::setId) .tags(primaryPartitionKey())) .addAttribute(Integer.class, a -> a.name("sort") .getter(Record::getSort) .setter(Record::setSort) .tags(primarySortKey())) .build(); private static final List<Record> RECORDS = IntStream.range(0, 10) .mapToObj(i -> new Record().setId("id-value").setSort(i)) .collect(Collectors.toList()); private DynamoDbEnhancedAsyncClient enhancedAsyncClient = DefaultDynamoDbEnhancedAsyncClient.builder() .dynamoDbClient(getDynamoDbAsyncClient()) .build(); private DynamoDbAsyncTable<Record> mappedTable = enhancedAsyncClient.table(getConcreteTableName("table-name"), TABLE_SCHEMA); private void insertRecords() { RECORDS.forEach(record -> mappedTable.putItem(r -> r.item(record)).join()); } @Before public void createTable() { mappedTable.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput())).join(); } @After public void deleteTable() { getDynamoDbAsyncClient().deleteTable(DeleteTableRequest.builder() .tableName(getConcreteTableName("table-name")) .build()).join(); } @Test public void scanAllRecordsDefaultSettings() { insertRecords(); SdkPublisher<Page<Record>> publisher = mappedTable.scan(ScanEnhancedRequest.builder().build()); List<Page<Record>> results = drainPublisher(publisher, 1); Page<Record> page = results.get(0); assertThat(page.items(), is(RECORDS)); assertThat(page.lastEvaluatedKey(), is(nullValue())); } @Test public void scanAllRecordsDefaultSettings_viaItems() { insertRecords(); SdkPublisher<Record> publisher = mappedTable.scan(ScanEnhancedRequest.builder().build()).items(); List<Record> results = drainPublisher(publisher, 10); assertThat(results, is(RECORDS)); } @Test public void scanAllRecordsWithFilter() { insertRecords(); Map<String, AttributeValue> expressionValues = new HashMap<>(); expressionValues.put(":min_value", numberValue(3)); expressionValues.put(":max_value", numberValue(5)); Expression expression = Expression.builder() .expression("sort >= :min_value AND sort <= :max_value") .expressionValues(expressionValues) .build(); SdkPublisher<Page<Record>> publisher = mappedTable.scan(ScanEnhancedRequest.builder().filterExpression(expression).build()); List<Page<Record>> results = drainPublisher(publisher, 1); Page<Record> page = results.get(0); assertThat(page.items(), is(RECORDS.stream().filter(r -> r.sort >= 3 && r.sort <= 5).collect(Collectors.toList()))); assertThat(page.lastEvaluatedKey(), is(nullValue())); } @Test public void scanAllRecordsWithFilter_viaItems() { insertRecords(); Map<String, AttributeValue> expressionValues = new HashMap<>(); expressionValues.put(":min_value", numberValue(3)); expressionValues.put(":max_value", numberValue(5)); Expression expression = Expression.builder() .expression("sort >= :min_value AND sort <= :max_value") .expressionValues(expressionValues) .build(); SdkPublisher<Record> publisher = mappedTable.scan(ScanEnhancedRequest.builder().filterExpression(expression).build()).items(); List<Record> results = drainPublisher(publisher, 3); assertThat(results, is(RECORDS.stream().filter(r -> r.sort >= 3 && r.sort <= 5).collect(Collectors.toList()))); } @Test public void scanLimit() { insertRecords(); SdkPublisher<Page<Record>> publisher = mappedTable.scan(r -> r.limit(5)); publisher.subscribe(page -> page.items().forEach(item -> System.out.println(item))); List<Page<Record>> results = drainPublisher(publisher, 3); Page<Record> page1 = results.get(0); Page<Record> page2 = results.get(1); Page<Record> page3 = results.get(2); assertThat(page1.items(), is(RECORDS.subList(0, 5))); assertThat(page1.lastEvaluatedKey(), is(getKeyMap(4))); assertThat(page2.items(), is(RECORDS.subList(5, 10))); assertThat(page2.lastEvaluatedKey(), is(getKeyMap(9))); assertThat(page3.items(), is(empty())); assertThat(page3.lastEvaluatedKey(), is(nullValue())); } @Test public void scanLimit_viaItems() { insertRecords(); SdkPublisher<Record> publisher = mappedTable.scan(r -> r.limit(5)).items(); List<Record> results = drainPublisher(publisher, 10); assertThat(results, is(RECORDS)); } @Test public void scanEmpty() { SdkPublisher<Page<Record>> publisher = mappedTable.scan(); List<Page<Record>> results = drainPublisher(publisher, 1); Page<Record> page = results.get(0); assertThat(page.items(), is(empty())); assertThat(page.lastEvaluatedKey(), is(nullValue())); } @Test public void scanEmpty_viaItems() { SdkPublisher<Record> publisher = mappedTable.scan().items(); List<Record> results = drainPublisher(publisher, 0); assertThat(results, is(empty())); } @Test public void scanExclusiveStartKey() { insertRecords(); SdkPublisher<Page<Record>> publisher = mappedTable.scan(ScanEnhancedRequest.builder().exclusiveStartKey(getKeyMap(7)).build()); List<Page<Record>> results = drainPublisher(publisher, 1); Page<Record> page = results.get(0); assertThat(page.items(), is(RECORDS.subList(8, 10))); assertThat(page.lastEvaluatedKey(), is(nullValue())); } @Test public void scanExclusiveStartKey_viaItems() { insertRecords(); SdkPublisher<Record> publisher = mappedTable.scan(ScanEnhancedRequest.builder().exclusiveStartKey(getKeyMap(7)).build()).items(); List<Record> results = drainPublisher(publisher, 2); assertThat(results, is(RECORDS.subList(8, 10))); } private Map<String, AttributeValue> getKeyMap(int sort) { Map<String, AttributeValue> result = new HashMap<>(); result.put("id", stringValue("id-value")); result.put("sort", numberValue(sort)); return Collections.unmodifiableMap(result); } }
4,132
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/BeanTableSchemaRecursiveTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests; import static org.assertj.core.api.Assertions.assertThat; import java.util.Collections; import java.util.Map; import org.junit.Test; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.RecursiveRecordBean; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.RecursiveRecordImmutable; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; public class BeanTableSchemaRecursiveTest { @Test public void recursiveRecord_document() { TableSchema<RecursiveRecordBean> tableSchema = TableSchema.fromClass(RecursiveRecordBean.class); RecursiveRecordImmutable recursiveRecordImmutable2 = RecursiveRecordImmutable.builder() .setAttribute(4) .build(); RecursiveRecordImmutable recursiveRecordImmutable1 = RecursiveRecordImmutable.builder() .setAttribute(3) .setRecursiveRecordImmutable(recursiveRecordImmutable2) .build(); RecursiveRecordBean recursiveRecordBean2 = new RecursiveRecordBean(); recursiveRecordBean2.setAttribute(2); recursiveRecordBean2.setRecursiveRecordImmutable(recursiveRecordImmutable1); RecursiveRecordBean recursiveRecordBean1 = new RecursiveRecordBean(); recursiveRecordBean1.setAttribute(1); recursiveRecordBean1.setRecursiveRecordBean(recursiveRecordBean2); Map<String, AttributeValue> itemMap = tableSchema.itemToMap(recursiveRecordBean1, true); assertThat(itemMap).hasSize(2); assertThat(itemMap).containsEntry("attribute", AttributeValue.builder().n("1").build()); assertThat(itemMap).hasEntrySatisfying("recursiveRecordBean", av -> { assertThat(av.hasM()).isTrue(); assertThat(av.m()).containsEntry("attribute", AttributeValue.builder().n("2").build()); assertThat(av.m()).hasEntrySatisfying("recursiveRecordImmutable", iav -> { assertThat(iav.hasM()).isTrue(); assertThat(iav.m()).containsEntry("attribute", AttributeValue.builder().n("3").build()); assertThat(iav.m()).hasEntrySatisfying("recursiveRecordImmutable", iav2 -> { assertThat(iav2.hasM()).isTrue(); assertThat(iav2.m()).containsEntry("attribute", AttributeValue.builder().n("4").build()); }); }); }); } @Test public void recursiveRecord_list() { TableSchema<RecursiveRecordBean> tableSchema = TableSchema.fromClass(RecursiveRecordBean.class); RecursiveRecordBean recursiveRecordBean2 = new RecursiveRecordBean(); recursiveRecordBean2.setAttribute(2); RecursiveRecordBean recursiveRecordBean1 = new RecursiveRecordBean(); recursiveRecordBean1.setAttribute(1); recursiveRecordBean1.setRecursiveRecordList(Collections.singletonList(recursiveRecordBean2)); Map<String, AttributeValue> itemMap = tableSchema.itemToMap(recursiveRecordBean1, true); assertThat(itemMap).hasSize(2); assertThat(itemMap).containsEntry("attribute", AttributeValue.builder().n("1").build()); assertThat(itemMap).hasEntrySatisfying("recursiveRecordList", av -> { assertThat(av.hasL()).isTrue(); assertThat(av.l()).hasOnlyOneElementSatisfying(listAv -> { assertThat(listAv.hasM()).isTrue(); assertThat(listAv.m()).containsEntry("attribute", AttributeValue.builder().n("2").build()); }); }); } }
4,133
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/VersionedRecordWithSpecialCharactersTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static software.amazon.awssdk.enhanced.dynamodb.extensions.VersionedRecordExtension.AttributeTags.versionAttribute; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.stringValue; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey; import java.util.Objects; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.Expression; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.extensions.VersionedRecordExtension; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema; import software.amazon.awssdk.enhanced.dynamodb.model.PutItemEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.UpdateItemEnhancedRequest; import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException; import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; public class VersionedRecordWithSpecialCharactersTest extends LocalDynamoDbSyncTestBase { private static class Record { private String id; private String _attribute; private Integer _version; private String getId() { return id; } private Record setId(String id) { this.id = id; return this; } private String get_attribute() { return _attribute; } private Record set_attribute(String _attribute) { this._attribute = _attribute; return this; } private Integer get_version() { return _version; } private Record set_version(Integer _version) { this._version = _version; return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Record record = (Record) o; return Objects.equals(id, record.id) && Objects.equals(_attribute, record._attribute) && Objects.equals(_version, record._version); } @Override public int hashCode() { return Objects.hash(id, _attribute, _version); } } private static final TableSchema<Record> TABLE_SCHEMA = StaticTableSchema.builder(Record.class) .newItemSupplier(Record::new) .addAttribute(String.class, a -> a.name("id") .getter(Record::getId) .setter(Record::setId) .tags(primaryPartitionKey())) .addAttribute(String.class, a -> a.name("_attribute") .getter(Record::get_attribute) .setter(Record::set_attribute)) .addAttribute(Integer.class, a -> a.name("_version") .getter(Record::get_version) .setter(Record::set_version) .tags(versionAttribute())) .build(); private DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() .dynamoDbClient(getDynamoDbClient()) .extensions(VersionedRecordExtension.builder().build()) .build(); private DynamoDbTable<Record> mappedTable = enhancedClient.table(getConcreteTableName("table-name"), TABLE_SCHEMA); @Rule public ExpectedException exception = ExpectedException.none(); @Before public void createTable() { mappedTable.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput())); } @After public void deleteTable() { getDynamoDbClient().deleteTable(DeleteTableRequest.builder() .tableName(getConcreteTableName("table-name")) .build()); } @Test public void putNewRecordSetsInitialVersion() { mappedTable.putItem(r -> r.item(new Record().setId("id").set_attribute("one"))); Record result = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id"))); Record expectedResult = new Record().setId("id").set_attribute("one").set_version(1); assertThat(result, is(expectedResult)); } @Test public void updateNewRecordSetsInitialVersion() { Record result = mappedTable.updateItem(r -> r.item(new Record().setId("id").set_attribute("one"))); Record expectedResult = new Record().setId("id").set_attribute("one").set_version(1); assertThat(result, is(expectedResult)); } @Test public void putExistingRecordVersionMatches() { mappedTable.putItem(r -> r.item(new Record().setId("id").set_attribute("one"))); mappedTable.putItem(r -> r.item(new Record().setId("id").set_attribute("one").set_version(1))); Record result = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id"))); Record expectedResult = new Record().setId("id").set_attribute("one").set_version(2); assertThat(result, is(expectedResult)); } @Test public void putExistingRecordVersionMatchesConditionExpressionMatches() { mappedTable.putItem(r -> r.item(new Record().setId("id").set_attribute("one"))); Expression conditionExpression = Expression.builder() .expression("#k = :v OR #k = :v1") .putExpressionName("#k", "_attribute") .putExpressionValue(":v", stringValue("wrong")) .putExpressionValue(":v1", stringValue("one")) .build(); mappedTable.putItem(PutItemEnhancedRequest.builder(Record.class) .item(new Record().setId("id").set_attribute("one").set_version(1)) .conditionExpression(conditionExpression) .build()); Record result = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id"))); Record expectedResult = new Record().setId("id").set_attribute("one").set_version(2); assertThat(result, is(expectedResult)); } @Test public void putExistingRecordVersionDoesNotMatchConditionExpressionMatches() { mappedTable.putItem(r -> r.item(new Record().setId("id").set_attribute("one"))); Expression conditionExpression = Expression.builder() .expression("#k = :v OR #k = :v1") .putExpressionName("#k", "_attribute") .putExpressionValue(":v", stringValue("wrong")) .putExpressionValue(":v1", stringValue("one")) .build(); exception.expect(ConditionalCheckFailedException.class); mappedTable.putItem(PutItemEnhancedRequest.builder(Record.class) .item(new Record().setId("id").set_attribute("one").set_version(2)) .conditionExpression(conditionExpression) .build()); } @Test public void putExistingRecordVersionMatchesConditionExpressionDoesNotMatch() { mappedTable.putItem(r -> r.item(new Record().setId("id").set_attribute("one"))); Expression conditionExpression = Expression.builder() .expression("#k = :v OR #k = :v1") .putExpressionName("#k", "attribute") .putExpressionValue(":v", stringValue("wrong")) .putExpressionValue(":v1", stringValue("wrong2")) .build(); exception.expect(ConditionalCheckFailedException.class); mappedTable.putItem(PutItemEnhancedRequest.builder(Record.class) .item(new Record().setId("id").set_attribute("one").set_version(1)) .conditionExpression(conditionExpression) .build()); } @Test public void updateExistingRecordVersionMatchesConditionExpressionMatches() { mappedTable.putItem(r -> r.item(new Record().setId("id").set_attribute("one"))); Expression conditionExpression = Expression.builder() .expression("#k = :v OR #k = :v1") .putExpressionName("#k", "_attribute") .putExpressionValue(":v", stringValue("wrong")) .putExpressionValue(":v1", stringValue("one")) .build(); mappedTable.updateItem(UpdateItemEnhancedRequest.builder(Record.class) .item(new Record().setId("id").set_attribute("one").set_version(1)) .conditionExpression(conditionExpression) .build()); Record result = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id"))); Record expectedResult = new Record().setId("id").set_attribute("one").set_version(2); assertThat(result, is(expectedResult)); } @Test public void updateExistingRecordVersionDoesNotMatchConditionExpressionMatches() { mappedTable.putItem(r -> r.item(new Record().setId("id").set_attribute("one"))); Expression conditionExpression = Expression.builder() .expression("#k = :v OR #k = :v1") .putExpressionName("#k", "_attribute") .putExpressionValue(":v", stringValue("wrong")) .putExpressionValue(":v1", stringValue("one")) .build(); exception.expect(ConditionalCheckFailedException.class); mappedTable.updateItem(UpdateItemEnhancedRequest.builder(Record.class) .item(new Record().setId("id").set_attribute("one").set_version(2)) .conditionExpression(conditionExpression) .build()); } @Test public void updateExistingRecordVersionMatchesConditionExpressionDoesNotMatch() { mappedTable.putItem(r -> r.item(new Record().setId("id").set_attribute("one"))); Expression conditionExpression = Expression.builder() .expression("#k = :v OR #k = :v1") .putExpressionName("#k", "attribute") .putExpressionValue(":v", stringValue("wrong")) .putExpressionValue(":v1", stringValue("wrong2")) .build(); exception.expect(ConditionalCheckFailedException.class); mappedTable.updateItem(UpdateItemEnhancedRequest.builder(Record.class) .item(new Record().setId("id").set_attribute("one").set_version(1)) .conditionExpression(conditionExpression) .build()); } @Test public void updateExistingRecordVersionMatches() { mappedTable.putItem(r -> r.item(new Record().setId("id").set_attribute("one"))); Record result = mappedTable.updateItem(r -> r.item(new Record().setId("id").set_attribute("one").set_version(1))); Record expectedResult = new Record().setId("id").set_attribute("one").set_version(2); assertThat(result, is(expectedResult)); } @Test(expected = ConditionalCheckFailedException.class) public void putRecordWithWrongVersionNumber() { mappedTable.putItem(r -> r.item(new Record().setId("id").set_attribute("one"))); mappedTable.putItem(r -> r.item(new Record().setId("id").set_attribute("one").set_version(2))); } }
4,134
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/PutItemWithResponseTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey; import java.util.Objects; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClientExtension; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbExtensionContext; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema; import software.amazon.awssdk.enhanced.dynamodb.model.PutItemEnhancedResponse; import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; import software.amazon.awssdk.services.dynamodb.model.ReturnConsumedCapacity; import software.amazon.awssdk.services.dynamodb.model.ReturnValue; public class PutItemWithResponseTest extends LocalDynamoDbSyncTestBase { private static class Record { private Integer id; private String stringAttr1; private Integer getId() { return id; } private Record setId(Integer id) { this.id = id; return this; } private String getStringAttr1() { return stringAttr1; } private Record setStringAttr1(String stringAttr1) { this.stringAttr1 = stringAttr1; return this; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Record record = (Record) o; return Objects.equals(id, record.id) && Objects.equals(stringAttr1, record.stringAttr1); } @Override public int hashCode() { return Objects.hash(id, stringAttr1); } } private static final TableSchema<Record> TABLE_SCHEMA = StaticTableSchema.builder(Record.class) .newItemSupplier(Record::new) .addAttribute(Integer.class, a -> a.name("id_1") .getter(Record::getId) .setter(Record::setId) .tags(primaryPartitionKey())) .addAttribute(String.class, a -> a.name("stringAttr1") .getter(Record::getStringAttr1) .setter(Record::setStringAttr1)) .build(); private DynamoDbEnhancedClient enhancedClient; private DynamoDbEnhancedClientExtension extension; private DynamoDbTable<Record> mappedTable1; @Before public void createTable() { extension = Mockito.spy(new NoOpExtension()); enhancedClient = DynamoDbEnhancedClient.builder() .dynamoDbClient(getDynamoDbClient()) .extensions(extension) .build(); mappedTable1 = enhancedClient.table(getConcreteTableName("table-name-1"), TABLE_SCHEMA); mappedTable1.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput())); } @After public void deleteTable() { getDynamoDbClient().deleteTable(DeleteTableRequest.builder() .tableName(getConcreteTableName("table-name-1")) .build()); } @Test public void returnValues_unset_attributesNull() { Record record = new Record().setId(1).setStringAttr1("a"); mappedTable1.putItem(record); record.setStringAttr1("b"); PutItemEnhancedResponse<Record> response = mappedTable1.putItemWithResponse(r -> r.item(record)); assertThat(response.attributes()).isNull(); } @Test public void returnValues_allOld_attributesMapped() { Record original = new Record().setId(1).setStringAttr1("a"); mappedTable1.putItem(original); Record update = new Record().setId(1).setStringAttr1("b"); PutItemEnhancedResponse<Record> response = mappedTable1.putItemWithResponse(r -> r.returnValues(ReturnValue.ALL_OLD) .item(update)); Record returned = response.attributes(); assertThat(returned).isEqualTo(original); } @Test public void returnValues_allOld_extensionInvokedOnReturnedValues() { Record original = new Record().setId(1).setStringAttr1("a"); mappedTable1.putItem(original); Record update = new Record().setId(1).setStringAttr1("b"); mappedTable1.putItemWithResponse(r -> r.returnValues(ReturnValue.ALL_OLD) .item(update)); Mockito.verify(extension).afterRead(any(DynamoDbExtensionContext.AfterRead.class)); Mockito.verify(extension, Mockito.times(2)).beforeWrite(any(DynamoDbExtensionContext.BeforeWrite.class)); } @Test public void returnConsumedCapacity_unset_consumedCapacityNull() { Record record = new Record().setId(1).setStringAttr1("a"); PutItemEnhancedResponse<Record> response = mappedTable1.putItemWithResponse(r -> r.item(record)); assertThat(response.consumedCapacity()).isNull(); } @Test public void returnConsumedCapacity_set_consumedCapacityNotNull() { Record record = new Record().setId(1).setStringAttr1("a"); PutItemEnhancedResponse<Record> response = mappedTable1.putItemWithResponse(r -> r.item(record) .returnConsumedCapacity(ReturnConsumedCapacity.TOTAL)); assertThat(response.consumedCapacity()).isNotNull(); } // Note: DynamoDB Local does not support returning ItemCollectionMetrics. See PutItemWithResponseIntegrationTest for // additional testing for this method. @Test public void returnItemCollectionMetrics_unset_itemCollectionMetricsNull() { Record record = new Record().setId(1); PutItemEnhancedResponse<Record> response = mappedTable1.putItemWithResponse(r -> r.item(record)); assertThat(response.consumedCapacity()).isNull(); } private static class NoOpExtension implements DynamoDbEnhancedClientExtension { } }
4,135
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/ImmutableTableSchemaRecursiveTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests; import static org.assertj.core.api.Assertions.assertThat; import java.util.Collections; import java.util.Map; import org.junit.jupiter.api.Test; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.RecursiveRecordBean; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.RecursiveRecordImmutable; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; public class ImmutableTableSchemaRecursiveTest { @Test public void recursiveRecord_document() { TableSchema<RecursiveRecordImmutable> tableSchema = TableSchema.fromClass(RecursiveRecordImmutable.class); RecursiveRecordBean recursiveRecordBean2 = new RecursiveRecordBean(); recursiveRecordBean2.setAttribute(4); RecursiveRecordBean recursiveRecordBean1 = new RecursiveRecordBean(); recursiveRecordBean1.setAttribute(3); recursiveRecordBean1.setRecursiveRecordBean(recursiveRecordBean2); RecursiveRecordImmutable recursiveRecordImmutable2 = RecursiveRecordImmutable.builder() .setAttribute(2) .setRecursiveRecordBean(recursiveRecordBean1) .build(); RecursiveRecordImmutable recursiveRecordImmutable1 = RecursiveRecordImmutable.builder() .setAttribute(1) .setRecursiveRecordImmutable(recursiveRecordImmutable2) .build(); Map<String, AttributeValue> itemMap = tableSchema.itemToMap(recursiveRecordImmutable1, true); assertThat(itemMap).hasSize(2); assertThat(itemMap).containsEntry("attribute", AttributeValue.builder().n("1").build()); assertThat(itemMap).hasEntrySatisfying("recursiveRecordImmutable", av -> { assertThat(av.hasM()).isTrue(); assertThat(av.m()).containsEntry("attribute", AttributeValue.builder().n("2").build()); assertThat(av.m()).hasEntrySatisfying("recursiveRecordBean", bav -> { assertThat(bav.hasM()).isTrue(); assertThat(bav.m()).containsEntry("attribute", AttributeValue.builder().n("3").build()); assertThat(bav.m()).hasEntrySatisfying("recursiveRecordBean", bav2 -> { assertThat(bav2.hasM()).isTrue(); assertThat(bav2.m()).containsEntry("attribute", AttributeValue.builder().n("4").build()); }); }); }); } @Test public void recursiveRecord_list() { TableSchema<RecursiveRecordImmutable> tableSchema = TableSchema.fromClass(RecursiveRecordImmutable.class); RecursiveRecordImmutable recursiveRecordImmutable2 = RecursiveRecordImmutable.builder() .setAttribute(2) .build(); RecursiveRecordImmutable recursiveRecordImmutable1 = RecursiveRecordImmutable.builder() .setAttribute(1) .setRecursiveRecordList(Collections.singletonList(recursiveRecordImmutable2)) .build(); Map<String, AttributeValue> itemMap = tableSchema.itemToMap(recursiveRecordImmutable1, true); assertThat(itemMap).hasSize(2); assertThat(itemMap).containsEntry("attribute", AttributeValue.builder().n("1").build()); assertThat(itemMap).hasEntrySatisfying("recursiveRecordList", av -> { assertThat(av.hasL()).isTrue(); assertThat(av.l()).hasOnlyOneElementSatisfying(listAv -> { assertThat(listAv.hasM()).isTrue(); assertThat(listAv.m()).containsEntry("attribute", AttributeValue.builder().n("2").build()); }); }); } }
4,136
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/DeleteItemWithResponseTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests; import static org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey; import java.util.Objects; import org.junit.After; import org.junit.Before; import org.junit.Test; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.Key; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema; import software.amazon.awssdk.enhanced.dynamodb.model.DeleteItemEnhancedResponse; import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; import software.amazon.awssdk.services.dynamodb.model.ReturnConsumedCapacity; public class DeleteItemWithResponseTest extends LocalDynamoDbSyncTestBase { private static class Record { private Integer id; private String stringAttr1; private Integer getId() { return id; } private Record setId(Integer id) { this.id = id; return this; } private String getStringAttr1() { return stringAttr1; } private Record setStringAttr1(String stringAttr1) { this.stringAttr1 = stringAttr1; return this; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Record record = (Record) o; return Objects.equals(id, record.id) && Objects.equals(stringAttr1, record.stringAttr1); } @Override public int hashCode() { return Objects.hash(id, stringAttr1); } } private static final TableSchema<Record> TABLE_SCHEMA = StaticTableSchema.builder(Record.class) .newItemSupplier(Record::new) .addAttribute(Integer.class, a -> a.name("id_1") .getter(Record::getId) .setter(Record::setId) .tags(primaryPartitionKey())) .addAttribute(String.class, a -> a.name("stringAttr1") .getter(Record::getStringAttr1) .setter(Record::setStringAttr1)) .build(); private DynamoDbEnhancedClient enhancedClient; private DynamoDbTable<Record> mappedTable1; @Before public void createTable() { enhancedClient = DynamoDbEnhancedClient.builder() .dynamoDbClient(getDynamoDbClient()) .build(); mappedTable1 = enhancedClient.table(getConcreteTableName("table-name-1"), TABLE_SCHEMA); mappedTable1.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput())); } @After public void deleteTable() { getDynamoDbClient().deleteTable(DeleteTableRequest.builder() .tableName(getConcreteTableName("table-name-1")) .build()); } // Note: DynamoDB local seems to always return the consumed capacity even if not specified on the request. See // AsyncDeleteItemWithResponseIntegrationTest for additional testing of this field against the actual service. @Test public void returnConsumedCapacity_set_consumedCapacityNotNull() { Key key = Key.builder().partitionValue(1).build(); DeleteItemEnhancedResponse<Record> response = mappedTable1.deleteItemWithResponse(r -> r.key(key) .returnConsumedCapacity(ReturnConsumedCapacity.TOTAL)); assertThat(response.consumedCapacity()).isNotNull(); } }
4,137
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/AsyncIndexQueryTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.numberValue; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.stringValue; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primarySortKey; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.secondaryPartitionKey; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.secondarySortKey; import static software.amazon.awssdk.enhanced.dynamodb.model.QueryConditional.keyEqualTo; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.junit.After; import org.junit.Before; import org.junit.Test; import software.amazon.awssdk.core.async.SdkPublisher; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbAsyncIndex; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbAsyncTable; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedAsyncClient; import software.amazon.awssdk.enhanced.dynamodb.Key; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.internal.client.DefaultDynamoDbEnhancedAsyncClient; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema; import software.amazon.awssdk.enhanced.dynamodb.model.CreateTableEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.EnhancedGlobalSecondaryIndex; import software.amazon.awssdk.enhanced.dynamodb.model.Page; import software.amazon.awssdk.enhanced.dynamodb.model.QueryConditional; import software.amazon.awssdk.enhanced.dynamodb.model.QueryEnhancedRequest; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; import software.amazon.awssdk.services.dynamodb.model.ProjectionType; public class AsyncIndexQueryTest extends LocalDynamoDbAsyncTestBase { private static class Record { private String id; private Integer sort; private Integer value; private String gsiId; private Integer gsiSort; private String getId() { return id; } private Record setId(String id) { this.id = id; return this; } private Integer getSort() { return sort; } private Record setSort(Integer sort) { this.sort = sort; return this; } private Integer getValue() { return value; } private Record setValue(Integer value) { this.value = value; return this; } private String getGsiId() { return gsiId; } private Record setGsiId(String gsiId) { this.gsiId = gsiId; return this; } private Integer getGsiSort() { return gsiSort; } private Record setGsiSort(Integer gsiSort) { this.gsiSort = gsiSort; return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Record record = (Record) o; return Objects.equals(id, record.id) && Objects.equals(sort, record.sort) && Objects.equals(value, record.value) && Objects.equals(gsiId, record.gsiId) && Objects.equals(gsiSort, record.gsiSort); } @Override public int hashCode() { return Objects.hash(id, sort, value, gsiId, gsiSort); } } private static final TableSchema<Record> TABLE_SCHEMA = StaticTableSchema.builder(Record.class) .newItemSupplier(Record::new) .addAttribute(String.class, a -> a.name("id") .getter(Record::getId) .setter(Record::setId) .tags(primaryPartitionKey())) .addAttribute(Integer.class, a -> a.name("sort") .getter(Record::getSort) .setter(Record::setSort) .tags(primarySortKey())) .addAttribute(Integer.class, a -> a.name("value") .getter(Record::getValue) .setter(Record::setValue)) .addAttribute(String.class, a -> a.name("gsi_id") .getter(Record::getGsiId) .setter(Record::setGsiId) .tags(secondaryPartitionKey("gsi_keys_only"))) .addAttribute(Integer.class, a -> a.name("gsi_sort") .getter(Record::getGsiSort) .setter(Record::setGsiSort) .tags(secondarySortKey("gsi_keys_only"))) .build(); private static final List<Record> RECORDS = IntStream.range(0, 10) .mapToObj(i -> new Record() .setId("id-value") .setSort(i) .setValue(i) .setGsiId("gsi-id-value") .setGsiSort(i)) .collect(Collectors.toList()); private static final List<Record> KEYS_ONLY_RECORDS = RECORDS.stream() .map(record -> new Record() .setId(record.id) .setSort(record.sort) .setGsiId(record.gsiId) .setGsiSort(record.gsiSort)) .collect(Collectors.toList()); private DynamoDbEnhancedAsyncClient enhancedAsyncClient = DefaultDynamoDbEnhancedAsyncClient.builder() .dynamoDbClient(getDynamoDbAsyncClient()) .build(); private DynamoDbAsyncTable<Record> mappedTable = enhancedAsyncClient.table(getConcreteTableName("table-name"), TABLE_SCHEMA); private DynamoDbAsyncIndex<Record> keysOnlyMappedIndex = mappedTable.index("gsi_keys_only"); private void insertRecords() { RECORDS.forEach(record -> mappedTable.putItem(r -> r.item(record)).join()); } @Before public void createTable() { mappedTable.createTable( CreateTableEnhancedRequest.builder() .provisionedThroughput(getDefaultProvisionedThroughput()) .globalSecondaryIndices(EnhancedGlobalSecondaryIndex.builder() .indexName("gsi_keys_only") .projection(p -> p.projectionType(ProjectionType.KEYS_ONLY)) .provisionedThroughput(getDefaultProvisionedThroughput()) .build()) .build()) .join(); } @After public void deleteTable() { getDynamoDbAsyncClient().deleteTable(DeleteTableRequest.builder() .tableName(getConcreteTableName("table-name")) .build()) .join(); } @Test public void queryAllRecordsDefaultSettings_usingShortcutForm() { insertRecords(); SdkPublisher<Page<Record>> publisher = keysOnlyMappedIndex.query(keyEqualTo(k -> k.partitionValue("gsi-id-value"))); List<Page<Record>> results = drainPublisher(publisher, 1); Page<Record> page = results.get(0); assertThat(page.items(), is(KEYS_ONLY_RECORDS)); assertThat(page.lastEvaluatedKey(), is(nullValue())); } @Test public void queryBetween() { insertRecords(); Key fromKey = Key.builder().partitionValue("gsi-id-value").sortValue(3).build(); Key toKey = Key.builder().partitionValue("gsi-id-value").sortValue(5).build(); SdkPublisher<Page<Record>> publisher = keysOnlyMappedIndex.query(r -> r.queryConditional(QueryConditional.sortBetween(fromKey, toKey))); List<Page<Record>> results = drainPublisher(publisher, 1); Page<Record> page = results.get(0); assertThat(page.items(), is(KEYS_ONLY_RECORDS.stream().filter(r -> r.sort >= 3 && r.sort <= 5).collect(Collectors.toList()))); assertThat(page.lastEvaluatedKey(), is(nullValue())); } @Test public void queryLimit() { insertRecords(); SdkPublisher<Page<Record>> publisher = keysOnlyMappedIndex.query(QueryEnhancedRequest.builder() .queryConditional(keyEqualTo(k -> k.partitionValue("gsi-id-value"))) .limit(5) .build()); List<Page<Record>> results = drainPublisher(publisher, 3); Page<Record> page1 = results.get(0); Page<Record> page2 = results.get(1); Page<Record> page3 = results.get(2); Map<String, AttributeValue> expectedLastEvaluatedKey1 = new HashMap<>(); expectedLastEvaluatedKey1.put("id", stringValue(KEYS_ONLY_RECORDS.get(4).getId())); expectedLastEvaluatedKey1.put("sort", numberValue(KEYS_ONLY_RECORDS.get(4).getSort())); expectedLastEvaluatedKey1.put("gsi_id", stringValue(KEYS_ONLY_RECORDS.get(4).getGsiId())); expectedLastEvaluatedKey1.put("gsi_sort", numberValue(KEYS_ONLY_RECORDS.get(4).getGsiSort())); Map<String, AttributeValue> expectedLastEvaluatedKey2 = new HashMap<>(); expectedLastEvaluatedKey2.put("id", stringValue(KEYS_ONLY_RECORDS.get(9).getId())); expectedLastEvaluatedKey2.put("sort", numberValue(KEYS_ONLY_RECORDS.get(9).getSort())); expectedLastEvaluatedKey2.put("gsi_id", stringValue(KEYS_ONLY_RECORDS.get(9).getGsiId())); expectedLastEvaluatedKey2.put("gsi_sort", numberValue(KEYS_ONLY_RECORDS.get(9).getGsiSort())); assertThat(page1.items(), is(KEYS_ONLY_RECORDS.subList(0, 5))); assertThat(page1.lastEvaluatedKey(), is(expectedLastEvaluatedKey1)); assertThat(page2.items(), is(KEYS_ONLY_RECORDS.subList(5, 10))); assertThat(page2.lastEvaluatedKey(), is(expectedLastEvaluatedKey2)); assertThat(page3.items(), is(empty())); assertThat(page3.lastEvaluatedKey(), is(nullValue())); } @Test public void queryEmpty() { SdkPublisher<Page<Record>> publisher = keysOnlyMappedIndex.query(r -> r.queryConditional(keyEqualTo(k -> k.partitionValue("gsi-id-value")))); List<Page<Record>> results = drainPublisher(publisher, 1); Page<Record> page = results.get(0); assertThat(page.items(), is(empty())); assertThat(page.lastEvaluatedKey(), is(nullValue())); } @Test public void queryExclusiveStartKey() { insertRecords(); Map<String, AttributeValue> expectedLastEvaluatedKey = new HashMap<>(); expectedLastEvaluatedKey.put("id", stringValue(KEYS_ONLY_RECORDS.get(7).getId())); expectedLastEvaluatedKey.put("sort", numberValue(KEYS_ONLY_RECORDS.get(7).getSort())); expectedLastEvaluatedKey.put("gsi_id", stringValue(KEYS_ONLY_RECORDS.get(7).getGsiId())); expectedLastEvaluatedKey.put("gsi_sort", numberValue(KEYS_ONLY_RECORDS.get(7).getGsiSort())); SdkPublisher<Page<Record>> publisher = keysOnlyMappedIndex.query(QueryEnhancedRequest.builder() .queryConditional(keyEqualTo(k -> k.partitionValue("gsi-id-value"))) .exclusiveStartKey(expectedLastEvaluatedKey) .build()); List<Page<Record>> results = drainPublisher(publisher, 1); Page<Record> page = results.get(0); assertThat(page.items(), is(KEYS_ONLY_RECORDS.subList(8, 10))); assertThat(page.lastEvaluatedKey(), is(nullValue())); } }
4,138
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/AsyncBatchGetItemTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.nullValue; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.junit.After; import org.junit.Before; import org.junit.Test; import software.amazon.awssdk.core.async.SdkPublisher; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbAsyncTable; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedAsyncClient; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.internal.client.DefaultDynamoDbEnhancedAsyncClient; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema; import software.amazon.awssdk.enhanced.dynamodb.model.BatchGetItemEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.BatchGetResultPage; import software.amazon.awssdk.enhanced.dynamodb.model.BatchGetResultPagePublisher; import software.amazon.awssdk.enhanced.dynamodb.model.ReadBatch; import software.amazon.awssdk.services.dynamodb.model.ConsumedCapacity; import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; import software.amazon.awssdk.services.dynamodb.model.ReturnConsumedCapacity; public class AsyncBatchGetItemTest extends LocalDynamoDbAsyncTestBase { private static class Record1 { private Integer id; private String stringAttr; private Integer getId() { return id; } private String getStringAttr() { return stringAttr; } private Record1 setId(Integer id) { this.id = id; return this; } private Record1 setStringAttr(String str) { this.stringAttr = str; return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Record1 record1 = (Record1) o; return Objects.equals(id, record1.id) && Objects.equals(stringAttr, record1.stringAttr); } @Override public int hashCode() { return Objects.hash(id, stringAttr); } } private static class Record2 { private Integer id; private String stringAttr; private Integer getId() { return id; } private String getStringAttr() { return stringAttr; } private Record2 setId(Integer id) { this.id = id; return this; } private Record2 setStringAttr(String str) { this.stringAttr = str; return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Record2 record2 = (Record2) o; return Objects.equals(id, record2.id) && Objects.equals(stringAttr, record2.stringAttr); } @Override public int hashCode() { return Objects.hash(id, stringAttr); } } private static final TableSchema<Record1> TABLE_SCHEMA_1 = StaticTableSchema.builder(Record1.class) .newItemSupplier(Record1::new) .addAttribute(Integer.class, a -> a.name("id_1") .getter(Record1::getId) .setter(Record1::setId) .tags(primaryPartitionKey())) .addAttribute(String.class, a -> a.name("str_1") .getter(Record1::getStringAttr) .setter(Record1::setStringAttr)) .build(); private static final TableSchema<Record2> TABLE_SCHEMA_2 = StaticTableSchema.builder(Record2.class) .newItemSupplier(Record2::new) .addAttribute(Integer.class, a -> a.name("id_2") .getter(Record2::getId) .setter(Record2::setId) .tags(primaryPartitionKey())) .addAttribute(String.class, a -> a.name("str_1") .getter(Record2::getStringAttr) .setter(Record2::setStringAttr)) .build(); private final DynamoDbEnhancedAsyncClient enhancedAsyncClient = DefaultDynamoDbEnhancedAsyncClient.builder() .dynamoDbClient(getDynamoDbAsyncClient()) .build(); private final String tableName1 = getConcreteTableName("table-name-1"); private final String tableName2 = getConcreteTableName("table-name-2"); private final DynamoDbAsyncTable<Record1> mappedTable1 = enhancedAsyncClient.table(tableName1, TABLE_SCHEMA_1); private final DynamoDbAsyncTable<Record2> mappedTable2 = enhancedAsyncClient.table(tableName2, TABLE_SCHEMA_2); private static final List<Record1> RECORDS_1 = IntStream.range(0, 2) .mapToObj(i -> new Record1().setId(i).setStringAttr(getStringAttrValue(80_000))) .collect(Collectors.toList()); private static final List<Record2> RECORDS_2 = IntStream.range(0, 2) .mapToObj(i -> new Record2().setId(i).setStringAttr(getStringAttrValue(40_000))) .collect(Collectors.toList()); @Before public void createTable() { mappedTable1.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput())).join(); mappedTable2.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput())).join(); } @After public void deleteTable() { getDynamoDbAsyncClient().deleteTable(DeleteTableRequest.builder() .tableName(tableName1) .build()).join(); getDynamoDbAsyncClient().deleteTable(DeleteTableRequest.builder() .tableName(tableName2) .build()).join(); } private void insertRecords() { RECORDS_1.forEach(record -> mappedTable1.putItem(r -> r.item(record)).join()); RECORDS_2.forEach(record -> mappedTable2.putItem(r -> r.item(record)).join()); } @Test public void getRecordsFromMultipleTables() { insertRecords(); SdkPublisher<BatchGetResultPage> publisher = batchGetResultPageSdkPublisherForBothTables(); List<BatchGetResultPage> results = drainPublisher(publisher, 1); assertThat(results.size(), is(1)); BatchGetResultPage page = results.get(0); assertThat(page.consumedCapacity(), empty()); List<Record1> record1List = page.resultsForTable(mappedTable1); assertThat(record1List.size(), is(2)); assertThat(record1List, containsInAnyOrder(RECORDS_1.get(0), RECORDS_1.get(1))); List<Record2> record2List = page.resultsForTable(mappedTable2); assertThat(record2List.size(), is(2)); assertThat(record2List, containsInAnyOrder(RECORDS_2.get(0), RECORDS_2.get(1))); } @Test public void getRecordsFromMultipleTables_viaFlattenedItems() { insertRecords(); BatchGetResultPagePublisher publisher = batchGetResultPageSdkPublisherForBothTables(); List<Record1> table1Results = drainPublisher(publisher.resultsForTable(mappedTable1), 2); assertThat(table1Results.size(), is(2)); assertThat(table1Results, containsInAnyOrder(RECORDS_1.toArray())); List<Record2> table2Results = drainPublisher(publisher.resultsForTable(mappedTable2), 2); assertThat(table1Results.size(), is(2)); assertThat(table2Results, containsInAnyOrder(RECORDS_2.toArray())); } @Test public void notFoundRecordReturnsNull() { insertRecords(); BatchGetItemEnhancedRequest batchGetItemEnhancedRequest = requestWithNotFoundRecord(); SdkPublisher<BatchGetResultPage> publisher = enhancedAsyncClient.batchGetItem(batchGetItemEnhancedRequest); List<BatchGetResultPage> results = drainPublisher(publisher, 1); assertThat(results.size(), is(1)); BatchGetResultPage page = results.get(0); List<Record1> record1List = page.resultsForTable(mappedTable1); assertThat(record1List.size(), is(1)); assertThat(record1List.get(0).getId(), is(0)); List<Record2> record2List = page.resultsForTable(mappedTable2); assertThat(record2List.size(), is(2)); assertThat(record2List, containsInAnyOrder(RECORDS_2.get(0), RECORDS_2.get(1))); } @Test public void notFoundRecordReturnsNull_viaFlattenedItems() { insertRecords(); BatchGetItemEnhancedRequest batchGetItemEnhancedRequest = requestWithNotFoundRecord(); BatchGetResultPagePublisher publisher = enhancedAsyncClient.batchGetItem(batchGetItemEnhancedRequest); List<Record1> resultsForTable1 = drainPublisher(publisher.resultsForTable(mappedTable1), 1); assertThat(resultsForTable1.size(), is(1)); assertThat(resultsForTable1.get(0).getId(), is(0)); List<Record2> record2List = drainPublisher(publisher.resultsForTable(mappedTable2), 2); assertThat(record2List.size(), is(2)); assertThat(record2List, containsInAnyOrder(RECORDS_2.toArray())); } @Test public void getRecordsFromMultipleTables_withReturnConsumedCapacity() { insertRecords(); SdkPublisher<BatchGetResultPage> publisher = batchGetResultPageSdkPublisherForBothTables(ReturnConsumedCapacity.TOTAL); List<BatchGetResultPage> results = drainPublisher(publisher, 1); assertThat(results.size(), is(1)); BatchGetResultPage page = results.get(0); assertThat(page.consumedCapacity(), not(nullValue())); assertThat(page.consumedCapacity(), hasSize(2)); assertThat(page.consumedCapacity(), containsInAnyOrder( ConsumedCapacity.builder().tableName(tableName1).capacityUnits(20.0).build(), ConsumedCapacity.builder().tableName(tableName2).capacityUnits(10.0).build() )); List<Record1> record1List = page.resultsForTable(mappedTable1); assertThat(record1List.size(), is(2)); assertThat(record1List, containsInAnyOrder(RECORDS_1.get(0), RECORDS_1.get(1))); List<Record2> record2List = page.resultsForTable(mappedTable2); assertThat(record2List.size(), is(2)); assertThat(record2List, containsInAnyOrder(RECORDS_2.get(0), RECORDS_2.get(1))); } @Test public void notFoundRecords_withReturnConsumedCapacity() { insertRecords(); BatchGetItemEnhancedRequest batchGetItemEnhancedRequest = requestWithNotFoundRecord().toBuilder() .returnConsumedCapacity(ReturnConsumedCapacity.TOTAL) .build(); SdkPublisher<BatchGetResultPage> publisher = enhancedAsyncClient.batchGetItem(batchGetItemEnhancedRequest); List<BatchGetResultPage> results = drainPublisher(publisher, 1); assertThat(results.size(), is(1)); BatchGetResultPage page = results.get(0); assertThat(page.consumedCapacity(), containsInAnyOrder( ConsumedCapacity.builder().tableName(tableName1).capacityUnits(10.0).build(), ConsumedCapacity.builder().tableName(tableName2).capacityUnits(10.0).build() )); List<Record1> record1List = page.resultsForTable(mappedTable1); assertThat(record1List.size(), is(1)); assertThat(record1List.get(0).getId(), is(0)); List<Record2> record2List = page.resultsForTable(mappedTable2); assertThat(record2List.size(), is(2)); assertThat(record2List, containsInAnyOrder(RECORDS_2.get(0), RECORDS_2.get(1))); } private BatchGetItemEnhancedRequest requestWithNotFoundRecord() { return BatchGetItemEnhancedRequest.builder() .readBatches( ReadBatch.builder(Record1.class) .mappedTableResource(mappedTable1) .addGetItem(r -> r.key(k -> k.partitionValue(0))) .build(), ReadBatch.builder(Record2.class) .mappedTableResource(mappedTable2) .addGetItem(r -> r.key(k -> k.partitionValue(0))) .build(), ReadBatch.builder(Record2.class) .mappedTableResource(mappedTable2) .addGetItem(r -> r.key(k -> k.partitionValue(1))) .build(), ReadBatch.builder(Record1.class) .mappedTableResource(mappedTable1) .addGetItem(r -> r.key(k -> k.partitionValue(5))) .build()) .build(); } private BatchGetResultPagePublisher batchGetResultPageSdkPublisherForBothTables() { return batchGetResultPageSdkPublisherForBothTables(null); } private BatchGetResultPagePublisher batchGetResultPageSdkPublisherForBothTables(ReturnConsumedCapacity retConsumedCapacity) { return enhancedAsyncClient.batchGetItem( r -> r.returnConsumedCapacity(retConsumedCapacity) .readBatches( ReadBatch.builder(Record1.class) .mappedTableResource(mappedTable1) .addGetItem(i -> i.key(k -> k.partitionValue(0))) .build(), ReadBatch.builder(Record2.class) .mappedTableResource(mappedTable2) .addGetItem(i -> i.key(k -> k.partitionValue(0))) .build(), ReadBatch.builder(Record2.class) .mappedTableResource(mappedTable2) .addGetItem(i -> i.key(k -> k.partitionValue(1))) .build(), ReadBatch.builder(Record1.class) .mappedTableResource(mappedTable1) .addGetItem(i -> i.key(k -> k.partitionValue(1))) .build() ) ); } private static String getStringAttrValue(int nChars) { char[] bytes = new char[nChars]; Arrays.fill(bytes, 'a'); return new String(bytes); } }
4,139
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/TransactGetItemsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.junit.After; import org.junit.Before; import org.junit.Test; import software.amazon.awssdk.enhanced.dynamodb.Document; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.Key; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema; import software.amazon.awssdk.enhanced.dynamodb.model.TransactGetItemsEnhancedRequest; import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; public class TransactGetItemsTest extends LocalDynamoDbSyncTestBase { private static class Record1 { private Integer id; private Integer getId() { return id; } private Record1 setId(Integer id) { this.id = id; return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Record1 record1 = (Record1) o; return Objects.equals(id, record1.id); } @Override public int hashCode() { return Objects.hash(id); } } private static class Record2 { private Integer id; private Integer getId() { return id; } private Record2 setId(Integer id) { this.id = id; return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Record2 record2 = (Record2) o; return Objects.equals(id, record2.id); } @Override public int hashCode() { return Objects.hash(id); } } private static final TableSchema<Record1> TABLE_SCHEMA_1 = StaticTableSchema.builder(Record1.class) .newItemSupplier(Record1::new) .addAttribute(Integer.class, a -> a.name("id_1") .getter(Record1::getId) .setter(Record1::setId) .tags(primaryPartitionKey())) .build(); private static final TableSchema<Record2> TABLE_SCHEMA_2 = StaticTableSchema.builder(Record2.class) .newItemSupplier(Record2::new) .addAttribute(Integer.class, a -> a.name("id_2") .getter(Record2::getId) .setter(Record2::setId) .tags(primaryPartitionKey())) .build(); private DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() .dynamoDbClient(getDynamoDbClient()) .build(); private DynamoDbTable<Record1> mappedTable1 = enhancedClient.table(getConcreteTableName("table-name-1"), TABLE_SCHEMA_1); private DynamoDbTable<Record2> mappedTable2 = enhancedClient.table(getConcreteTableName("table-name-2"), TABLE_SCHEMA_2); private static final List<Record1> RECORDS_1 = IntStream.range(0, 2) .mapToObj(i -> new Record1().setId(i)) .collect(Collectors.toList()); private static final List<Record2> RECORDS_2 = IntStream.range(0, 2) .mapToObj(i -> new Record2().setId(i)) .collect(Collectors.toList()); @Before public void createTable() { mappedTable1.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput())); mappedTable2.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput())); } @After public void deleteTable() { getDynamoDbClient().deleteTable(DeleteTableRequest.builder() .tableName(getConcreteTableName("table-name-1")) .build()); getDynamoDbClient().deleteTable(DeleteTableRequest.builder() .tableName(getConcreteTableName("table-name-2")) .build()); } private void insertRecords() { RECORDS_1.forEach(record -> mappedTable1.putItem(r -> r.item(record))); RECORDS_2.forEach(record -> mappedTable2.putItem(r -> r.item(record))); } @Test public void getRecordsFromMultipleTables() { insertRecords(); TransactGetItemsEnhancedRequest transactGetItemsEnhancedRequest = TransactGetItemsEnhancedRequest.builder() .addGetItem(mappedTable1, Key.builder().partitionValue(0).build()) .addGetItem(mappedTable2, Key.builder().partitionValue(0).build()) .addGetItem(mappedTable2, Key.builder().partitionValue(1).build()) .addGetItem(mappedTable1, Key.builder().partitionValue(1).build()) .build(); List<Document> results = enhancedClient.transactGetItems(transactGetItemsEnhancedRequest); assertThat(results.size(), is(4)); assertThat(results.get(0).getItem(mappedTable1), is(RECORDS_1.get(0))); assertThat(results.get(1).getItem(mappedTable2), is(RECORDS_2.get(0))); assertThat(results.get(2).getItem(mappedTable2), is(RECORDS_2.get(1))); assertThat(results.get(3).getItem(mappedTable1), is(RECORDS_1.get(1))); } @Test public void notFoundRecordReturnsNull() { insertRecords(); TransactGetItemsEnhancedRequest transactGetItemsEnhancedRequest = TransactGetItemsEnhancedRequest.builder() .addGetItem(mappedTable1, Key.builder().partitionValue(0).build()) .addGetItem(mappedTable2, Key.builder().partitionValue(0).build()) .addGetItem(mappedTable2, Key.builder().partitionValue(5).build()) .addGetItem(mappedTable1, Key.builder().partitionValue(1).build()) .build(); List<Document> results = enhancedClient.transactGetItems(transactGetItemsEnhancedRequest); assertThat(results.size(), is(4)); assertThat(results.get(0).getItem(mappedTable1), is(RECORDS_1.get(0))); assertThat(results.get(1).getItem(mappedTable2), is(RECORDS_2.get(0))); assertThat(results.get(2).getItem(mappedTable2), is(nullValue())); assertThat(results.get(3).getItem(mappedTable1), is(RECORDS_1.get(1))); } }
4,140
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/BatchGetItemTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.is; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.junit.After; import org.junit.Before; import org.junit.Test; import software.amazon.awssdk.core.pagination.sync.SdkIterable; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema; import software.amazon.awssdk.enhanced.dynamodb.model.BatchGetItemEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.BatchGetResultPage; import software.amazon.awssdk.enhanced.dynamodb.model.BatchGetResultPageIterable; import software.amazon.awssdk.enhanced.dynamodb.model.ReadBatch; import software.amazon.awssdk.services.dynamodb.model.ConsumedCapacity; import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; import software.amazon.awssdk.services.dynamodb.model.ReturnConsumedCapacity; public class BatchGetItemTest extends LocalDynamoDbSyncTestBase { private static class Record1 { private Integer id; private String stringAttr; private Integer getId() { return id; } private String getStringAttr() { return stringAttr; } private Record1 setId(Integer id) { this.id = id; return this; } private Record1 setStringAttr(String str) { this.stringAttr = str; return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Record1 record1 = (Record1) o; return Objects.equals(id, record1.id) && Objects.equals(stringAttr, record1.stringAttr); } @Override public int hashCode() { return Objects.hash(id, stringAttr); } } private static class Record2 { private Integer id; private String stringAttr; private Integer getId() { return id; } private String getStringAttr() { return stringAttr; } private Record2 setId(Integer id) { this.id = id; return this; } private Record2 setStringAttr(String str) { this.stringAttr = str; return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Record2 record2 = (Record2) o; return Objects.equals(id, record2.id) && Objects.equals(stringAttr, record2.stringAttr); } @Override public int hashCode() { return Objects.hash(id, stringAttr); } } private static final TableSchema<Record1> TABLE_SCHEMA_1 = StaticTableSchema.builder(Record1.class) .newItemSupplier(Record1::new) .addAttribute(Integer.class, a -> a.name("id_1") .getter(Record1::getId) .setter(Record1::setId) .tags(primaryPartitionKey())) .addAttribute(String.class, a -> a.name("str_1") .getter(Record1::getStringAttr) .setter(Record1::setStringAttr)) .build(); private static final TableSchema<Record2> TABLE_SCHEMA_2 = StaticTableSchema.builder(Record2.class) .newItemSupplier(Record2::new) .addAttribute(Integer.class, a -> a.name("id_2") .getter(Record2::getId) .setter(Record2::setId) .tags(primaryPartitionKey())) .addAttribute(String.class, a -> a.name("str_1") .getter(Record2::getStringAttr) .setter(Record2::setStringAttr)) .build(); private DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() .dynamoDbClient(getDynamoDbClient()) .build(); private final String tableName1 = getConcreteTableName("table-name-1"); private final String tableName2 = getConcreteTableName("table-name-2"); private final DynamoDbTable<Record1> mappedTable1 = enhancedClient.table(tableName1, TABLE_SCHEMA_1); private final DynamoDbTable<Record2> mappedTable2 = enhancedClient.table(tableName2, TABLE_SCHEMA_2); private static final List<Record1> RECORDS_1 = IntStream.range(0, 2) .mapToObj(i -> new Record1().setId(i).setStringAttr(getStringAttrValue(80_000))) .collect(Collectors.toList()); private static final List<Record2> RECORDS_2 = IntStream.range(0, 2) .mapToObj(i -> new Record2().setId(i).setStringAttr(getStringAttrValue(40_000))) .collect(Collectors.toList()); @Before public void createTable() { mappedTable1.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput())); mappedTable2.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput())); } @After public void deleteTable() { getDynamoDbClient().deleteTable(DeleteTableRequest.builder() .tableName(tableName1) .build()); getDynamoDbClient().deleteTable(DeleteTableRequest.builder() .tableName(tableName2) .build()); } private void insertRecords() { RECORDS_1.forEach(record -> mappedTable1.putItem(r -> r.item(record))); RECORDS_2.forEach(record -> mappedTable2.putItem(r -> r.item(record))); } @Test public void getRecordsFromMultipleTables() { insertRecords(); SdkIterable<BatchGetResultPage> results = getBatchGetResultPagesForBothTables(); assertThat(results.stream().count(), is(1L)); results.iterator().forEachRemaining(page -> { assertThat(page.consumedCapacity(), empty()); List<Record1> table1Results = page.resultsForTable(mappedTable1); assertThat(table1Results.size(), is(2)); assertThat(table1Results.get(0).id, is(0)); assertThat(table1Results.get(1).id, is(1)); assertThat(page.resultsForTable(mappedTable2).size(), is(2)); }); } @Test public void getRecordsFromMultipleTables_viaFlattenedItems() { insertRecords(); BatchGetResultPageIterable results = getBatchGetResultPagesForBothTables(); SdkIterable<Record1> recordsList1 = results.resultsForTable(mappedTable1); assertThat(recordsList1, containsInAnyOrder(RECORDS_1.toArray())); SdkIterable<Record2> recordsList2 = results.resultsForTable(mappedTable2); assertThat(recordsList2, containsInAnyOrder(RECORDS_2.toArray())); } @Test public void notFoundRecordIgnored() { insertRecords(); BatchGetItemEnhancedRequest batchGetItemEnhancedRequest = batchGetItemEnhancedRequestWithNotFoundRecord(); SdkIterable<BatchGetResultPage> results = enhancedClient.batchGetItem(batchGetItemEnhancedRequest); assertThat(results.stream().count(), is(1L)); results.iterator().forEachRemaining((page) -> { assertThat(page.consumedCapacity(), empty()); List<Record1> mappedTable1Results = page.resultsForTable(mappedTable1); assertThat(mappedTable1Results.size(), is(1)); assertThat(mappedTable1Results.get(0).id, is(0)); assertThat(page.resultsForTable(mappedTable2).size(), is(2)); }); } @Test public void notFoundRecordIgnored_viaFlattenedItems() { insertRecords(); BatchGetItemEnhancedRequest batchGetItemEnhancedRequest = batchGetItemEnhancedRequestWithNotFoundRecord(); BatchGetResultPageIterable pageIterable = enhancedClient.batchGetItem(batchGetItemEnhancedRequest); assertThat(pageIterable.stream().count(), is(1L)); List<Record1> recordsList1 = pageIterable.resultsForTable(mappedTable1).stream().collect(Collectors.toList()); assertThat(recordsList1, is(RECORDS_1.subList(0, 1))); SdkIterable<Record2> recordsList2 = pageIterable.resultsForTable(mappedTable2); assertThat(recordsList2, containsInAnyOrder(RECORDS_2.toArray())); } @Test public void getRecordsFromMultipleTables_withReturnConsumedCapacity() { insertRecords(); SdkIterable<BatchGetResultPage> results = getBatchGetResultPagesForBothTables(ReturnConsumedCapacity.TOTAL); assertThat(results.stream().count(), is(1L)); results.iterator().forEachRemaining(page -> { assertThat(page.consumedCapacity(), containsInAnyOrder( ConsumedCapacity.builder().tableName(tableName1).capacityUnits(20.0).build(), ConsumedCapacity.builder().tableName(tableName2).capacityUnits(10.0).build() )); List<Record1> table1Results = page.resultsForTable(mappedTable1); assertThat(table1Results.size(), is(2)); assertThat(table1Results.get(0).id, is(0)); assertThat(table1Results.get(1).id, is(1)); assertThat(page.resultsForTable(mappedTable2).size(), is(2)); }); } @Test public void notFoundRecordIgnored_withReturnConsumedCapacity() { insertRecords(); BatchGetItemEnhancedRequest batchGetItemEnhancedRequest = batchGetItemEnhancedRequestWithNotFoundRecord() .toBuilder() .returnConsumedCapacity(ReturnConsumedCapacity.TOTAL) .build(); SdkIterable<BatchGetResultPage> results = enhancedClient.batchGetItem(batchGetItemEnhancedRequest); assertThat(results.stream().count(), is(1L)); results.iterator().forEachRemaining(page -> { assertThat(page.consumedCapacity(), containsInAnyOrder( ConsumedCapacity.builder().tableName(tableName1).capacityUnits(10.0).build(), ConsumedCapacity.builder().tableName(tableName2).capacityUnits(10.0).build() )); List<Record1> mappedTable1Results = page.resultsForTable(mappedTable1); assertThat(mappedTable1Results.size(), is(1)); assertThat(mappedTable1Results.get(0).id, is(0)); assertThat(page.resultsForTable(mappedTable2).size(), is(2)); }); } private BatchGetItemEnhancedRequest batchGetItemEnhancedRequestWithNotFoundRecord() { return BatchGetItemEnhancedRequest.builder() .readBatches( ReadBatch.builder(Record1.class) .mappedTableResource(mappedTable1) .addGetItem(r -> r.key(k -> k.partitionValue(0))) .build(), ReadBatch.builder(Record2.class) .mappedTableResource(mappedTable2) .addGetItem(r -> r.key(k -> k.partitionValue(0))) .build(), ReadBatch.builder(Record2.class) .mappedTableResource(mappedTable2) .addGetItem(r -> r.key(k -> k.partitionValue(1))) .build(), ReadBatch.builder(Record1.class) .mappedTableResource(mappedTable1) .addGetItem(r -> r.key(k -> k.partitionValue(5))) .build()) .build(); } private BatchGetResultPageIterable getBatchGetResultPagesForBothTables() { return getBatchGetResultPagesForBothTables(null); } private BatchGetResultPageIterable getBatchGetResultPagesForBothTables(ReturnConsumedCapacity returnConsumedCapacity) { return enhancedClient.batchGetItem(r -> r.returnConsumedCapacity(returnConsumedCapacity).readBatches( ReadBatch.builder(Record1.class) .mappedTableResource(mappedTable1) .addGetItem(i -> i.key(k -> k.partitionValue(0))) .build(), ReadBatch.builder(Record2.class) .mappedTableResource(mappedTable2) .addGetItem(i -> i.key(k -> k.partitionValue(0))) .build(), ReadBatch.builder(Record2.class) .mappedTableResource(mappedTable2) .addGetItem(i -> i.key(k -> k.partitionValue(1))) .build(), ReadBatch.builder(Record1.class) .mappedTableResource(mappedTable1) .addGetItem(i -> i.key(k -> k.partitionValue(1))) .build())); } private static String getStringAttrValue(int nChars) { char[] bytes = new char[nChars]; Arrays.fill(bytes, 'a'); return new String(bytes); } }
4,141
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/AnnotatedImmutableTableSchemaTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests; import static org.assertj.core.api.Assertions.assertThat; import org.junit.After; import org.junit.Test; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.ImmutableFakeItem; import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughput; public class AnnotatedImmutableTableSchemaTest extends LocalDynamoDbSyncTestBase { private static final String TABLE_NAME = "table-name"; private final DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() .dynamoDbClient(getDynamoDbClient()) .build(); @After public void deleteTable() { getDynamoDbClient().deleteTable(DeleteTableRequest.builder() .tableName(getConcreteTableName(TABLE_NAME)) .build()); } @Test public void simpleItem_putAndGet() { TableSchema<ImmutableFakeItem> tableSchema = TableSchema.fromClass(ImmutableFakeItem.class); DynamoDbTable<ImmutableFakeItem> mappedTable = enhancedClient.table(getConcreteTableName(TABLE_NAME), tableSchema); mappedTable.createTable(r -> r.provisionedThroughput(ProvisionedThroughput.builder() .readCapacityUnits(5L) .writeCapacityUnits(5L) .build())); ImmutableFakeItem immutableFakeItem = ImmutableFakeItem.builder() .id("id123") .attribute("test-value") .build(); mappedTable.putItem(immutableFakeItem); ImmutableFakeItem readItem = mappedTable.getItem(immutableFakeItem); assertThat(readItem).isEqualTo(immutableFakeItem); } }
4,142
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/BufferingSubscriber.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; public class BufferingSubscriber<T> implements Subscriber<T> { private final CountDownLatch latch = new CountDownLatch(1); private final List<T> bufferedItems = new ArrayList<>(); private volatile Throwable bufferedError = null; private volatile boolean isCompleted = false; @Override public void onSubscribe(Subscription subscription) { subscription.request(Long.MAX_VALUE); } @Override public void onNext(T t) { bufferedItems.add(t); } @Override public void onError(Throwable throwable) { this.bufferedError = throwable; this.latch.countDown(); } @Override public void onComplete() { this.isCompleted = true; this.latch.countDown(); } public void waitForCompletion(long timeoutInMillis) { try { this.latch.await(timeoutInMillis, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { throw new RuntimeException(e); } } public List<T> bufferedItems() { return bufferedItems; } public Throwable bufferedError() { return bufferedError; } public boolean isCompleted() { return isCompleted; } }
4,143
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/UpdateItemWithResponseTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests; import static org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey; import java.util.Objects; import org.junit.After; import org.junit.Before; import org.junit.Test; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema; import software.amazon.awssdk.enhanced.dynamodb.model.UpdateItemEnhancedResponse; import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; import software.amazon.awssdk.services.dynamodb.model.ReturnConsumedCapacity; public class UpdateItemWithResponseTest extends LocalDynamoDbSyncTestBase { private static class Record { private Integer id; private String stringAttr1; private Integer getId() { return id; } private Record setId(Integer id) { this.id = id; return this; } private String getStringAttr1() { return stringAttr1; } private Record setStringAttr1(String stringAttr1) { this.stringAttr1 = stringAttr1; return this; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Record record = (Record) o; return Objects.equals(id, record.id) && Objects.equals(stringAttr1, record.stringAttr1); } @Override public int hashCode() { return Objects.hash(id, stringAttr1); } } private static final TableSchema<Record> TABLE_SCHEMA = StaticTableSchema.builder(Record.class) .newItemSupplier(Record::new) .addAttribute(Integer.class, a -> a.name("id_1") .getter(Record::getId) .setter(Record::setId) .tags(primaryPartitionKey())) .addAttribute(String.class, a -> a.name("stringAttr1") .getter(Record::getStringAttr1) .setter(Record::setStringAttr1)) .build(); private DynamoDbEnhancedClient enhancedClient; private DynamoDbTable<Record> mappedTable1; @Before public void createTable() { enhancedClient = DynamoDbEnhancedClient.builder() .dynamoDbClient(getDynamoDbClient()) .build(); mappedTable1 = enhancedClient.table(getConcreteTableName("table-name-1"), TABLE_SCHEMA); mappedTable1.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput())); } @After public void deleteTable() { getDynamoDbClient().deleteTable(DeleteTableRequest.builder() .tableName(getConcreteTableName("table-name-1")) .build()); } @Test public void newValuesMapped() { Record original = new Record().setId(1).setStringAttr1("attr"); mappedTable1.putItem(original); Record updated = new Record().setId(1).setStringAttr1("attr2"); UpdateItemEnhancedResponse<Record> response = mappedTable1.updateItemWithResponse(r -> r.item(updated)); assertThat(response.attributes()).isEqualTo(updated); } @Test public void returnConsumedCapacity_unset_consumedCapacityNull() { Record original = new Record().setId(1).setStringAttr1("attr"); mappedTable1.putItem(original); Record updated = new Record().setId(1).setStringAttr1("attr2"); UpdateItemEnhancedResponse<Record> response = mappedTable1.updateItemWithResponse(r -> r.item(updated)); assertThat(response.consumedCapacity()).isNull(); } @Test public void returnConsumedCapacity_set_consumedCapacityNotNull() { Record original = new Record().setId(1).setStringAttr1("attr"); mappedTable1.putItem(original); Record updated = new Record().setId(1).setStringAttr1("attr2"); UpdateItemEnhancedResponse<Record> response = mappedTable1.updateItemWithResponse(r -> r.item(updated) .returnConsumedCapacity(ReturnConsumedCapacity.TOTAL)); assertThat(response.consumedCapacity()).isNotNull(); } @Test public void returnItemCollectionMetrics_unset_itemCollectionMetricsNull() { Record original = new Record().setId(1).setStringAttr1("attr"); mappedTable1.putItem(original); Record updated = new Record().setId(1).setStringAttr1("attr2"); UpdateItemEnhancedResponse<Record> response = mappedTable1.updateItemWithResponse(r -> r.item(updated)); assertThat(response.itemCollectionMetrics()).isNull(); } }
4,144
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/UpdateExpressionTest.java
package software.amazon.awssdk.enhanced.dynamodb.functionaltests; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.After; import org.junit.Test; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClientExtension; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbExtensionContext; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.extensions.WriteModification; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.RecordForUpdateExpressions; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.OperationName; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.UpdateItemOperation; import software.amazon.awssdk.enhanced.dynamodb.internal.update.UpdateExpressionConverter; import software.amazon.awssdk.enhanced.dynamodb.update.AddAction; import software.amazon.awssdk.enhanced.dynamodb.update.DeleteAction; import software.amazon.awssdk.enhanced.dynamodb.update.UpdateExpression; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.DynamoDbException; import software.amazon.awssdk.utils.CollectionUtils; public class UpdateExpressionTest extends LocalDynamoDbSyncTestBase { private static final Set<String> SET_ATTRIBUTE_INIT_VALUE = Stream.of("YELLOW", "BLUE", "RED", "GREEN") .collect(Collectors.toSet()); private static final Set<String> SET_ATTRIBUTE_DELETE = Stream.of("YELLOW", "RED").collect(Collectors.toSet()); private static final String NUMBER_ATTRIBUTE_REF = "extensionNumberAttribute"; private static final long NUMBER_ATTRIBUTE_VALUE = 5L; private static final String NUMBER_ATTRIBUTE_VALUE_REF = ":increment_value_ref"; private static final String SET_ATTRIBUTE_REF = "extensionSetAttribute"; private static final TableSchema<RecordForUpdateExpressions> TABLE_SCHEMA = TableSchema.fromClass(RecordForUpdateExpressions.class); private DynamoDbTable<RecordForUpdateExpressions> mappedTable; private void initClientWithExtensions(DynamoDbEnhancedClientExtension... extensions) { DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() .dynamoDbClient(getDynamoDbClient()) .extensions(extensions) .build(); mappedTable = enhancedClient.table(getConcreteTableName("table-name"), TABLE_SCHEMA); mappedTable.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput())); } @After public void deleteTable() { getDynamoDbClient().deleteTable(r -> r.tableName(getConcreteTableName("table-name"))); } @Test public void attribute_notInPojo_notFilteredInExtension_ignoresNulls_updatesNormally() { initClientWithExtensions(new ItemPreservingUpdateExtension()); RecordForUpdateExpressions record = createRecordWithoutExtensionAttributes(); mappedTable.updateItem(r -> r.item(record).ignoreNulls(true)); RecordForUpdateExpressions persistedRecord = mappedTable.getItem(record); assertThat(persistedRecord.getStringAttribute()).isEqualTo("init"); assertThat(persistedRecord.getExtensionNumberAttribute()).isEqualTo(5L); } /** * This test case represents the most likely extension UpdateExpression use case; * an attribute is set in the extensions and isn't present in the request POJO item, and there is no change in * the request to set ignoreNull to true. * <p> * By default, ignorNull is false, so attributes that aren't set on the request are deleted from the DDB table through * the updateItemOperation generating REMOVE actions for those attributes. This is prevented by * {@link UpdateItemOperation} using {@link UpdateExpressionConverter#findAttributeNames(UpdateExpression)} * to not create REMOVE actions attributes it finds referenced in an extension UpdateExpression. * Therefore, this use case updates normally. */ @Test public void attribute_notInPojo_notFilteredInExtension_defaultSetsNull_updatesNormally() { initClientWithExtensions(new ItemPreservingUpdateExtension()); RecordForUpdateExpressions record = createRecordWithoutExtensionAttributes(); mappedTable.updateItem(r -> r.item(record)); RecordForUpdateExpressions persistedRecord = mappedTable.getItem(record); assertThat(persistedRecord.getStringAttribute()).isEqualTo("init"); assertThat(persistedRecord.getExtensionNumberAttribute()).isEqualTo(5L); } @Test public void attribute_notInPojo_filteredInExtension_ignoresNulls_updatesNormally() { initClientWithExtensions(new ItemFilteringUpdateExtension()); RecordForUpdateExpressions record = createRecordWithoutExtensionAttributes(); record.setExtensionSetAttribute(SET_ATTRIBUTE_INIT_VALUE); mappedTable.putItem(record); record.setStringAttribute("init"); mappedTable.updateItem(r -> r.item(record).ignoreNulls(true)); verifySetAttribute(record); } @Test public void attribute_notInPojo_filteredInExtension_defaultSetsNull_updatesNormally() { initClientWithExtensions(new ItemFilteringUpdateExtension()); RecordForUpdateExpressions record = createRecordWithoutExtensionAttributes(); record.setExtensionSetAttribute(SET_ATTRIBUTE_INIT_VALUE); mappedTable.putItem(record); record.setStringAttribute("init"); mappedTable.updateItem(r -> r.item(record)); verifySetAttribute(record); } /** * The extension adds an UpdateExpression with the number attribute, and the request * results in an UpdateExpression with the number attribute. This causes DDB to reject the request. */ @Test public void attribute_inPojo_notFilteredInExtension_ignoresNulls_ddbError() { initClientWithExtensions(new ItemPreservingUpdateExtension()); RecordForUpdateExpressions record = createRecordWithoutExtensionAttributes(); record.setExtensionNumberAttribute(100L); verifyDDBError(record, true); } @Test public void attribute_inPojo_notFilteredInExtension_defaultSetsNull_ddbError() { initClientWithExtensions(new ItemPreservingUpdateExtension()); RecordForUpdateExpressions record = createRecordWithoutExtensionAttributes(); record.setExtensionNumberAttribute(100L); verifyDDBError(record, false); } /** * When the extension filters the transact item representing the request POJO attributes and removes the attribute * from the POJO if it's there, only the extension UpdateExpression will reference the attribute and no DDB * conflict results. */ @Test public void attribute_inPojo_filteredInExtension_ignoresNulls_updatesNormally() { initClientWithExtensions(new ItemFilteringUpdateExtension()); RecordForUpdateExpressions record = createRecordWithoutExtensionAttributes(); record.setExtensionSetAttribute(SET_ATTRIBUTE_INIT_VALUE); mappedTable.putItem(record); record.setStringAttribute("init"); record.setExtensionSetAttribute(Stream.of("PURPLE").collect(Collectors.toSet())); mappedTable.updateItem(r -> r.item(record).ignoreNulls(true)); verifySetAttribute(record); } @Test public void attribute_inPojo_filteredInExtension_defaultSetsNull_updatesNormally() { initClientWithExtensions(new ItemFilteringUpdateExtension()); RecordForUpdateExpressions record = createRecordWithoutExtensionAttributes(); record.setExtensionSetAttribute(SET_ATTRIBUTE_INIT_VALUE); mappedTable.putItem(record); record.setStringAttribute("init"); record.setExtensionSetAttribute(Stream.of("PURPLE").collect(Collectors.toSet())); mappedTable.updateItem(r -> r.item(record)); verifySetAttribute(record); } @Test public void chainedExtensions_noDuplicates_ignoresNulls_updatesNormally() { initClientWithExtensions(new ItemPreservingUpdateExtension(), new ItemFilteringUpdateExtension()); RecordForUpdateExpressions putRecord = createRecordWithoutExtensionAttributes(); putRecord.setExtensionNumberAttribute(11L); putRecord.setExtensionSetAttribute(SET_ATTRIBUTE_INIT_VALUE); mappedTable.putItem(putRecord); RecordForUpdateExpressions updateRecord = createRecordWithoutExtensionAttributes(); updateRecord.setStringAttribute("updated"); mappedTable.updateItem(r -> r.item(updateRecord).ignoreNulls(true)); Set<String> expectedSetExtensionAttribute = Stream.of("BLUE", "GREEN").collect(Collectors.toSet()); RecordForUpdateExpressions persistedRecord = mappedTable.getItem(mappedTable.keyFrom(putRecord)); assertThat(persistedRecord.getExtensionNumberAttribute()).isEqualTo(16L); assertThat(persistedRecord.getExtensionSetAttribute()).isEqualTo(expectedSetExtensionAttribute); } @Test public void chainedExtensions_duplicateAttributes_sameValue_sameValueRef_ddbError() { initClientWithExtensions(new ItemPreservingUpdateExtension(), new ItemPreservingUpdateExtension()); verifyDDBError(createRecordWithoutExtensionAttributes(), false); } @Test public void chainedExtensions_duplicateAttributes_sameValue_differentValueRef_ddbError() { initClientWithExtensions(new ItemPreservingUpdateExtension(), new ItemPreservingUpdateExtension(NUMBER_ATTRIBUTE_VALUE, ":ref")); verifyDDBError(createRecordWithoutExtensionAttributes(), false); } @Test public void chainedExtensions_duplicateAttributes_differentValue_differentValueRef_ddbError() { initClientWithExtensions(new ItemPreservingUpdateExtension(), new ItemPreservingUpdateExtension(13L, ":ref")); verifyDDBError(createRecordWithoutExtensionAttributes(), false); } @Test public void chainedExtensions_duplicateAttributes_differentValue_sameValueRef_operationMergeError() { initClientWithExtensions(new ItemPreservingUpdateExtension(), new ItemPreservingUpdateExtension(10L, NUMBER_ATTRIBUTE_VALUE_REF)); RecordForUpdateExpressions record = createRecordWithoutExtensionAttributes(); assertThatThrownBy(() ->mappedTable.updateItem(r -> r.item(record))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Attempt to coalesce two expressions with conflicting expression values") .hasMessageContaining(NUMBER_ATTRIBUTE_VALUE_REF); } @Test public void chainedExtensions_duplicateAttributes_invalidValueRef_operationMergeError() { initClientWithExtensions(new ItemPreservingUpdateExtension(), new ItemPreservingUpdateExtension(10L, "illegal")); RecordForUpdateExpressions record = createRecordWithoutExtensionAttributes(); assertThatThrownBy(() ->mappedTable.updateItem(r -> r.item(record))) .isInstanceOf(DynamoDbException.class) .hasMessageContaining("ExpressionAttributeValues contains invalid key") .hasMessageContaining("illegal"); } private void verifyDDBError(RecordForUpdateExpressions record, boolean ignoreNulls) { assertThatThrownBy(() -> mappedTable.updateItem(r -> r.item(record).ignoreNulls(ignoreNulls))) .isInstanceOf(DynamoDbException.class) .hasMessageContaining("Two document paths") .hasMessageContaining(NUMBER_ATTRIBUTE_REF); } private void verifySetAttribute(RecordForUpdateExpressions record) { Set<String> expectedAttribute = Stream.of("BLUE", "GREEN").collect(Collectors.toSet()); RecordForUpdateExpressions persistedRecord = mappedTable.getItem(record); assertThat(persistedRecord.getStringAttribute()).isEqualTo("init"); assertThat(persistedRecord.getExtensionNumberAttribute()).isNull(); assertThat(persistedRecord.getExtensionSetAttribute()).isEqualTo(expectedAttribute); } private RecordForUpdateExpressions createRecordWithoutExtensionAttributes() { RecordForUpdateExpressions record = new RecordForUpdateExpressions(); record.setId("1"); record.setStringAttribute("init"); return record; } private static final class ItemPreservingUpdateExtension implements DynamoDbEnhancedClientExtension { private long incrementValue; private String valueRef; private ItemPreservingUpdateExtension() { this(NUMBER_ATTRIBUTE_VALUE, NUMBER_ATTRIBUTE_VALUE_REF); } private ItemPreservingUpdateExtension(long incrementValue, String valueRef) { this.incrementValue = incrementValue; this.valueRef = valueRef; } @Override public WriteModification beforeWrite(DynamoDbExtensionContext.BeforeWrite context) { UpdateExpression updateExpression = UpdateExpression.builder().addAction(addToNumericAttribute(NUMBER_ATTRIBUTE_REF)).build(); return WriteModification.builder().updateExpression(updateExpression).build(); } private AddAction addToNumericAttribute(String attributeName) { AttributeValue actualValue = AttributeValue.builder().n(Long.toString(incrementValue)).build(); return AddAction.builder() .path(attributeName) .value(valueRef) .putExpressionValue(valueRef, actualValue) .build(); } } private static final class ItemFilteringUpdateExtension implements DynamoDbEnhancedClientExtension { @Override public WriteModification beforeWrite(DynamoDbExtensionContext.BeforeWrite context) { Map<String, AttributeValue> transformedItemMap = context.items(); if ( context.operationName() == OperationName.UPDATE_ITEM) { List<String> attributesToFilter = Arrays.asList(SET_ATTRIBUTE_REF); transformedItemMap = CollectionUtils.filterMap(transformedItemMap, e -> !attributesToFilter.contains(e.getKey())); } UpdateExpression updateExpression = UpdateExpression.builder().addAction(deleteFromList(SET_ATTRIBUTE_REF)).build(); return WriteModification.builder() .updateExpression(updateExpression) .transformedItem(transformedItemMap) .build(); } private DeleteAction deleteFromList(String attributeName) { AttributeValue actualValue = AttributeValue.builder().ss(SET_ATTRIBUTE_DELETE).build(); String valueName = ":toDelete"; return DeleteAction.builder() .path(attributeName) .value(valueName) .putExpressionValue(valueName, actualValue) .build(); } } }
4,145
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/AsyncTransactWriteItemsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests; import static java.util.Collections.singletonMap; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.fail; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.stringValue; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey; import java.util.List; import java.util.Objects; import java.util.concurrent.CompletionException; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.junit.After; import org.junit.Before; import org.junit.Test; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbAsyncTable; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedAsyncClient; import software.amazon.awssdk.enhanced.dynamodb.Expression; import software.amazon.awssdk.enhanced.dynamodb.Key; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.internal.client.DefaultDynamoDbEnhancedAsyncClient; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema; import software.amazon.awssdk.enhanced.dynamodb.model.ConditionCheck; import software.amazon.awssdk.enhanced.dynamodb.model.TransactWriteItemsEnhancedRequest; import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; import software.amazon.awssdk.services.dynamodb.model.TransactionCanceledException; public class AsyncTransactWriteItemsTest extends LocalDynamoDbAsyncTestBase { private static class Record1 { private Integer id; private String attribute; private Integer getId() { return id; } private Record1 setId(Integer id) { this.id = id; return this; } private String getAttribute() { return attribute; } private Record1 setAttribute(String attribute) { this.attribute = attribute; return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Record1 record1 = (Record1) o; return Objects.equals(id, record1.id) && Objects.equals(attribute, record1.attribute); } @Override public int hashCode() { return Objects.hash(id, attribute); } } private static class Record2 { private Integer id; private String attribute; private Integer getId() { return id; } private Record2 setId(Integer id) { this.id = id; return this; } private String getAttribute() { return attribute; } private Record2 setAttribute(String attribute) { this.attribute = attribute; return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Record2 record2 = (Record2) o; return Objects.equals(id, record2.id) && Objects.equals(attribute, record2.attribute); } @Override public int hashCode() { return Objects.hash(id, attribute); } } private static final TableSchema<Record1> TABLE_SCHEMA_1 = StaticTableSchema.builder(Record1.class) .newItemSupplier(Record1::new) .addAttribute(Integer.class, a -> a.name("id_1") .getter(Record1::getId) .setter(Record1::setId) .tags(primaryPartitionKey())) .addAttribute(String.class, a -> a.name("attribute") .getter(Record1::getAttribute) .setter(Record1::setAttribute)) .build(); private static final TableSchema<Record2> TABLE_SCHEMA_2 = StaticTableSchema.builder(Record2.class) .newItemSupplier(Record2::new) .addAttribute(Integer.class, a -> a.name("id_2") .getter(Record2::getId) .setter(Record2::setId) .tags(primaryPartitionKey())) .addAttribute(String.class, a -> a.name("attribute") .getter(Record2::getAttribute) .setter(Record2::setAttribute)) .build(); private DynamoDbEnhancedAsyncClient enhancedAsyncClient = DefaultDynamoDbEnhancedAsyncClient.builder() .dynamoDbClient(getDynamoDbAsyncClient()) .build(); private DynamoDbAsyncTable<Record1> mappedTable1 = enhancedAsyncClient.table(getConcreteTableName("table-name-1"), TABLE_SCHEMA_1); private DynamoDbAsyncTable<Record2> mappedTable2 = enhancedAsyncClient.table(getConcreteTableName("table-name-2"), TABLE_SCHEMA_2); private static final List<Record1> RECORDS_1 = IntStream.range(0, 2) .mapToObj(i -> new Record1().setId(i).setAttribute(Integer.toString(i))) .collect(Collectors.toList()); private static final List<Record2> RECORDS_2 = IntStream.range(0, 2) .mapToObj(i -> new Record2().setId(i).setAttribute(Integer.toString(i))) .collect(Collectors.toList()); @Before public void createTable() { mappedTable1.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput())).join(); mappedTable2.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput())).join(); } @After public void deleteTable() { getDynamoDbAsyncClient().deleteTable(DeleteTableRequest.builder() .tableName(getConcreteTableName("table-name-1")) .build()).join(); getDynamoDbAsyncClient().deleteTable(DeleteTableRequest.builder() .tableName(getConcreteTableName("table-name-2")) .build()).join(); } @Test public void singlePut() { enhancedAsyncClient.transactWriteItems( TransactWriteItemsEnhancedRequest.builder() .addPutItem(mappedTable1, RECORDS_1.get(0)) .build()).join(); Record1 record = mappedTable1.getItem(r -> r.key(k -> k.partitionValue(0))).join(); assertThat(record, is(RECORDS_1.get(0))); } @Test public void multiplePut() { enhancedAsyncClient.transactWriteItems( TransactWriteItemsEnhancedRequest.builder() .addPutItem(mappedTable1, RECORDS_1.get(0)) .addPutItem(mappedTable2, RECORDS_2.get(0)) .build()).join(); Record1 record1 = mappedTable1.getItem(r -> r.key(k -> k.partitionValue(0))).join(); Record2 record2 = mappedTable2.getItem(r -> r.key(k -> k.partitionValue(0))).join(); assertThat(record1, is(RECORDS_1.get(0))); assertThat(record2, is(RECORDS_2.get(0))); } @Test public void singleUpdate() { enhancedAsyncClient.transactWriteItems( TransactWriteItemsEnhancedRequest.builder() .addUpdateItem(mappedTable1, RECORDS_1.get(0)) .build()).join(); Record1 record = mappedTable1.getItem(r -> r.key(k -> k.partitionValue(0))).join(); assertThat(record, is(RECORDS_1.get(0))); } @Test public void multipleUpdate() { enhancedAsyncClient.transactWriteItems( TransactWriteItemsEnhancedRequest.builder() .addUpdateItem(mappedTable1, RECORDS_1.get(0)) .addUpdateItem(mappedTable2, RECORDS_2.get(0)) .build()).join(); Record1 record1 = mappedTable1.getItem(r -> r.key(k -> k.partitionValue(0))).join(); Record2 record2 = mappedTable2.getItem(r -> r.key(k -> k.partitionValue(0))).join(); assertThat(record1, is(RECORDS_1.get(0))); assertThat(record2, is(RECORDS_2.get(0))); } @Test public void singleDelete() { mappedTable1.putItem(r -> r.item(RECORDS_1.get(0))).join(); enhancedAsyncClient.transactWriteItems( TransactWriteItemsEnhancedRequest.builder() .addDeleteItem(mappedTable1, RECORDS_1.get(0)) .build()).join(); Record1 record = mappedTable1.getItem(r -> r.key(k -> k.partitionValue(0))).join(); assertThat(record, is(nullValue())); } @Test public void multipleDelete() { mappedTable1.putItem(r -> r.item(RECORDS_1.get(0))).join(); mappedTable2.putItem(r -> r.item(RECORDS_2.get(0))).join(); enhancedAsyncClient.transactWriteItems( TransactWriteItemsEnhancedRequest.builder() .addDeleteItem(mappedTable1, RECORDS_1.get(0)) .addDeleteItem(mappedTable2, RECORDS_2.get(0)) .build()).join(); Record1 record1 = mappedTable1.getItem(r -> r.key(k -> k.partitionValue(0))).join(); Record2 record2 = mappedTable2.getItem(r -> r.key(k -> k.partitionValue(0))).join(); assertThat(record1, is(nullValue())); assertThat(record2, is(nullValue())); } @Test public void singleConditionCheck() { mappedTable1.putItem(r -> r.item(RECORDS_1.get(0))).join(); Expression conditionExpression = Expression.builder() .expression("#attribute = :attribute") .expressionValues(singletonMap(":attribute", stringValue("0"))) .expressionNames(singletonMap("#attribute", "attribute")) .build(); Key key = Key.builder().partitionValue(0).build(); enhancedAsyncClient.transactWriteItems( TransactWriteItemsEnhancedRequest.builder() .addConditionCheck(mappedTable1, ConditionCheck.builder() .key(key) .conditionExpression(conditionExpression) .build()) .build()).join(); } @Test public void multiConditionCheck() { mappedTable1.putItem(r -> r.item(RECORDS_1.get(0))).join(); mappedTable2.putItem(r -> r.item(RECORDS_2.get(0))).join(); Expression conditionExpression = Expression.builder() .expression("#attribute = :attribute") .expressionValues(singletonMap(":attribute", stringValue("0"))) .expressionNames(singletonMap("#attribute", "attribute")) .build(); Key key1 = Key.builder().partitionValue(0).build(); Key key2 = Key.builder().partitionValue(0).build(); enhancedAsyncClient.transactWriteItems( TransactWriteItemsEnhancedRequest.builder() .addConditionCheck(mappedTable1, ConditionCheck.builder() .key(key1) .conditionExpression(conditionExpression) .build()) .addConditionCheck(mappedTable2, ConditionCheck.builder() .key(key2) .conditionExpression(conditionExpression) .build()) .build()).join(); } @Test public void mixedCommands() { mappedTable1.putItem(r -> r.item(RECORDS_1.get(0))).join(); mappedTable2.putItem(r -> r.item(RECORDS_2.get(0))).join(); Expression conditionExpression = Expression.builder() .expression("#attribute = :attribute") .expressionValues(singletonMap(":attribute", stringValue("0"))) .expressionNames(singletonMap("#attribute", "attribute")) .build(); Key key = Key.builder().partitionValue(0).build(); TransactWriteItemsEnhancedRequest transactWriteItemsEnhancedRequest = TransactWriteItemsEnhancedRequest.builder() .addConditionCheck(mappedTable1, ConditionCheck.builder() .key(key) .conditionExpression(conditionExpression) .build()) .addPutItem(mappedTable2, RECORDS_2.get(1)) .addUpdateItem(mappedTable1, RECORDS_1.get(1)) .addDeleteItem(mappedTable2, RECORDS_2.get(0)) .build(); enhancedAsyncClient.transactWriteItems(transactWriteItemsEnhancedRequest).join(); assertThat(mappedTable1.getItem(r -> r.key(k -> k.partitionValue(1))).join(), is(RECORDS_1.get(1))); assertThat(mappedTable2.getItem(r -> r.key(k -> k.partitionValue(0))).join(), is(nullValue())); assertThat(mappedTable2.getItem(r -> r.key(k -> k.partitionValue(1))).join(), is(RECORDS_2.get(1))); } @Test public void mixedCommands_conditionCheckFailsTransaction() { mappedTable1.putItem(r -> r.item(RECORDS_1.get(0))).join(); mappedTable2.putItem(r -> r.item(RECORDS_2.get(0))).join(); Expression conditionExpression = Expression.builder() .expression("#attribute = :attribute") .expressionValues(singletonMap(":attribute", stringValue("1"))) .expressionNames(singletonMap("#attribute", "attribute")) .build(); Key key = Key.builder().partitionValue(0).build(); TransactWriteItemsEnhancedRequest transactWriteItemsEnhancedRequest = TransactWriteItemsEnhancedRequest.builder() .addPutItem(mappedTable2, RECORDS_2.get(1)) .addUpdateItem(mappedTable1, RECORDS_1.get(1)) .addConditionCheck(mappedTable1, ConditionCheck.builder() .key(key) .conditionExpression(conditionExpression) .build()) .addDeleteItem(mappedTable2, RECORDS_2.get(0)) .build(); try { enhancedAsyncClient.transactWriteItems(transactWriteItemsEnhancedRequest).join(); fail("Expected CompletionException to be thrown"); } catch (CompletionException e) { assertThat(e.getCause(), instanceOf(TransactionCanceledException.class)); } assertThat(mappedTable1.getItem(r -> r.key(k -> k.partitionValue(1))).join(), is(nullValue())); assertThat(mappedTable2.getItem(r -> r.key(k -> k.partitionValue(0))).join(), is(RECORDS_2.get(0))); assertThat(mappedTable2.getItem(r -> r.key(k -> k.partitionValue(1))).join(), is(nullValue())); } }
4,146
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/FailedConversionSyncTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.Iterator; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.Key; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeEnum; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeEnumRecord; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeEnumShortenedRecord; import software.amazon.awssdk.enhanced.dynamodb.model.Page; import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; public class FailedConversionSyncTest extends LocalDynamoDbSyncTestBase { private static final TableSchema<FakeEnumRecord> TABLE_SCHEMA = TableSchema.fromClass(FakeEnumRecord.class); private static final TableSchema<FakeEnumShortenedRecord> SHORT_TABLE_SCHEMA = TableSchema.fromClass(FakeEnumShortenedRecord.class); private final DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() .dynamoDbClient(getDynamoDbClient()) .build(); private final DynamoDbTable<FakeEnumRecord> mappedTable = enhancedClient.table(getConcreteTableName("table-name"), TABLE_SCHEMA); private final DynamoDbTable<FakeEnumShortenedRecord> mappedShortTable = enhancedClient.table(getConcreteTableName("table-name"), SHORT_TABLE_SCHEMA); @Rule public ExpectedException exception = ExpectedException.none(); @Before public void createTable() { mappedTable.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput())); } @After public void deleteTable() { getDynamoDbClient().deleteTable(DeleteTableRequest.builder() .tableName(getConcreteTableName("table-name")) .build()); } @Test public void exceptionOnRead() { FakeEnumRecord record = new FakeEnumRecord(); record.setId("123"); record.setEnumAttribute(FakeEnum.TWO); mappedTable.putItem(record); assertThatThrownBy(() -> mappedShortTable.getItem(Key.builder().partitionValue("123").build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("TWO") .hasMessageContaining("FakeEnumShortened"); } @Test public void iterableExceptionOnRead() { FakeEnumRecord record = new FakeEnumRecord(); record.setId("1"); record.setEnumAttribute(FakeEnum.ONE); mappedTable.putItem(record); record.setId("2"); record.setEnumAttribute(FakeEnum.TWO); mappedTable.putItem(record); Iterator<Page<FakeEnumShortenedRecord>> results = mappedShortTable.scan(r -> r.limit(1)).iterator(); assertThatThrownBy(() -> { // We can't guarantee the order they will be returned results.next(); results.next(); }).isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("TWO") .hasMessageContaining("FakeEnumShortened"); } }
4,147
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/BasicCrudTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.stringValue; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primarySortKey; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.secondaryPartitionKey; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.secondarySortKey; import java.util.Objects; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.Expression; import software.amazon.awssdk.enhanced.dynamodb.Key; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema; import software.amazon.awssdk.enhanced.dynamodb.model.DeleteItemEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.EnhancedGlobalSecondaryIndex; import software.amazon.awssdk.enhanced.dynamodb.model.PutItemEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.UpdateItemEnhancedRequest; import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException; import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; import software.amazon.awssdk.services.dynamodb.model.ProjectionType; public class BasicCrudTest extends LocalDynamoDbSyncTestBase { private static final String ATTRIBUTE_NAME_WITH_SPECIAL_CHARACTERS = "a*t:t.r-i#bute +3/4(&?5=@)<6>!ch$ar%"; private static class Record { private String id; private String sort; private String attribute; private String attribute2; private String attribute3; private String getId() { return id; } private Record setId(String id) { this.id = id; return this; } private String getSort() { return sort; } private Record setSort(String sort) { this.sort = sort; return this; } private String getAttribute() { return attribute; } private Record setAttribute(String attribute) { this.attribute = attribute; return this; } private String getAttribute2() { return attribute2; } private Record setAttribute2(String attribute2) { this.attribute2 = attribute2; return this; } private String getAttribute3() { return attribute3; } private Record setAttribute3(String attribute3) { this.attribute3 = attribute3; return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Record record = (Record) o; return Objects.equals(id, record.id) && Objects.equals(sort, record.sort) && Objects.equals(attribute, record.attribute) && Objects.equals(attribute2, record.attribute2) && Objects.equals(attribute3, record.attribute3); } @Override public int hashCode() { return Objects.hash(id, sort, attribute, attribute2, attribute3); } } private static class ShortRecord { private String id; private String sort; private String attribute; private String getId() { return id; } private ShortRecord setId(String id) { this.id = id; return this; } private String getSort() { return sort; } private ShortRecord setSort(String sort) { this.sort = sort; return this; } private String getAttribute() { return attribute; } private ShortRecord setAttribute(String attribute) { this.attribute = attribute; return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ShortRecord that = (ShortRecord) o; return Objects.equals(id, that.id) && Objects.equals(sort, that.sort) && Objects.equals(attribute, that.attribute); } @Override public int hashCode() { return Objects.hash(id, sort, attribute); } } private static final TableSchema<Record> TABLE_SCHEMA = StaticTableSchema.builder(Record.class) .newItemSupplier(Record::new) .addAttribute(String.class, a -> a.name("id") .getter(Record::getId) .setter(Record::setId) .tags(primaryPartitionKey())) .addAttribute(String.class, a -> a.name("sort") .getter(Record::getSort) .setter(Record::setSort) .tags(primarySortKey())) .addAttribute(String.class, a -> a.name("attribute") .getter(Record::getAttribute) .setter(Record::setAttribute)) .addAttribute(String.class, a -> a.name("attribute2*") .getter(Record::getAttribute2) .setter(Record::setAttribute2) .tags(secondaryPartitionKey("gsi_1"))) .addAttribute(String.class, a -> a.name(ATTRIBUTE_NAME_WITH_SPECIAL_CHARACTERS) .getter(Record::getAttribute3) .setter(Record::setAttribute3) .tags(secondarySortKey("gsi_1"))) .build(); private static final TableSchema<ShortRecord> SHORT_TABLE_SCHEMA = StaticTableSchema.builder(ShortRecord.class) .newItemSupplier(ShortRecord::new) .addAttribute(String.class, a -> a.name("id") .getter(ShortRecord::getId) .setter(ShortRecord::setId) .tags(primaryPartitionKey())) .addAttribute(String.class, a -> a.name("sort") .getter(ShortRecord::getSort) .setter(ShortRecord::setSort) .tags(primarySortKey())) .addAttribute(String.class, a -> a.name("attribute") .getter(ShortRecord::getAttribute) .setter(ShortRecord::setAttribute)) .build(); private DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() .dynamoDbClient(getDynamoDbClient()) .build(); private DynamoDbTable<Record> mappedTable = enhancedClient.table(getConcreteTableName("table-name"), TABLE_SCHEMA); private DynamoDbTable<ShortRecord> mappedShortTable = enhancedClient.table(getConcreteTableName("table-name"), SHORT_TABLE_SCHEMA); @Rule public ExpectedException exception = ExpectedException.none(); @Before public void createTable() { mappedTable.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput()) .globalSecondaryIndices( EnhancedGlobalSecondaryIndex.builder() .indexName("gsi_1") .projection(p -> p.projectionType(ProjectionType.ALL)) .provisionedThroughput(getDefaultProvisionedThroughput()) .build())); } @After public void deleteTable() { getDynamoDbClient().deleteTable(DeleteTableRequest.builder() .tableName(getConcreteTableName("table-name")) .build()); } @Test public void putThenGetItemUsingKey() { Record record = new Record() .setId("id-value") .setSort("sort-value") .setAttribute("one") .setAttribute2("two") .setAttribute3("three"); mappedTable.putItem(r -> r.item(record)); Record result = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id-value").sortValue("sort-value"))); assertThat(result, is(record)); } @Test public void putThenGetItemUsingKeyItem() { Record record = new Record() .setId("id-value") .setSort("sort-value") .setAttribute("one") .setAttribute2("two") .setAttribute3("three"); mappedTable.putItem(r -> r.item(record)); Record keyItem = new Record(); keyItem.setId("id-value"); keyItem.setSort("sort-value"); Record result = mappedTable.getItem(keyItem); assertThat(result, is(record)); } @Test public void getNonExistentItem() { Record result = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id-value").sortValue("sort-value"))); assertThat(result, is(nullValue())); } @Test public void putTwiceThenGetItem() { Record record = new Record() .setId("id-value") .setSort("sort-value") .setAttribute("one") .setAttribute2("two") .setAttribute3("three"); mappedTable.putItem(r -> r.item(record)); Record record2 = new Record() .setId("id-value") .setSort("sort-value") .setAttribute("four") .setAttribute2("five") .setAttribute3("six"); mappedTable.putItem(r -> r.item(record2)); Record result = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id-value").sortValue("sort-value"))); assertThat(result, is(record2)); } @Test public void putThenDeleteItem_usingShortcutForm() { Record record = new Record() .setId("id-value") .setSort("sort-value") .setAttribute("one") .setAttribute2("two") .setAttribute3("three"); mappedTable.putItem(record); Record beforeDeleteResult = mappedTable.deleteItem(Key.builder().partitionValue("id-value").sortValue("sort-value").build()); Record afterDeleteResult = mappedTable.getItem(Key.builder().partitionValue("id-value").sortValue("sort-value").build()); assertThat(beforeDeleteResult, is(record)); assertThat(afterDeleteResult, is(nullValue())); } @Test public void putThenDeleteItem_usingKeyItemForm() { Record record = new Record() .setId("id-value") .setSort("sort-value") .setAttribute("one") .setAttribute2("two") .setAttribute3("three"); mappedTable.putItem(record); Record beforeDeleteResult = mappedTable.deleteItem(record); Record afterDeleteResult = mappedTable.getItem(Key.builder().partitionValue("id-value").sortValue("sort-value").build()); assertThat(beforeDeleteResult, is(record)); assertThat(afterDeleteResult, is(nullValue())); } @Test public void putWithConditionThatSucceeds() { Record record = new Record() .setId("id-value") .setSort("sort-value") .setAttribute("one") .setAttribute2("two") .setAttribute3("three"); mappedTable.putItem(r -> r.item(record)); record.setAttribute("four"); Expression conditionExpression = Expression.builder() .expression("#key = :value OR #key1 = :value1") .putExpressionName("#key", "attribute") .putExpressionName("#key1", ATTRIBUTE_NAME_WITH_SPECIAL_CHARACTERS) .putExpressionValue(":value", stringValue("wrong")) .putExpressionValue(":value1", stringValue("three")) .build(); mappedTable.putItem(PutItemEnhancedRequest.builder(Record.class) .item(record) .conditionExpression(conditionExpression).build()); Record result = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id-value").sortValue("sort-value"))); assertThat(result, is(record)); } @Test public void putWithConditionThatFails() { Record record = new Record() .setId("id-value") .setSort("sort-value") .setAttribute("one") .setAttribute2("two") .setAttribute3("three"); mappedTable.putItem(r -> r.item(record)); record.setAttribute("four"); Expression conditionExpression = Expression.builder() .expression("#key = :value OR #key1 = :value1") .putExpressionName("#key", "attribute") .putExpressionName("#key1", ATTRIBUTE_NAME_WITH_SPECIAL_CHARACTERS) .putExpressionValue(":value", stringValue("wrong")) .putExpressionValue(":value1", stringValue("wrong")) .build(); exception.expect(ConditionalCheckFailedException.class); mappedTable.putItem(PutItemEnhancedRequest.builder(Record.class) .item(record) .conditionExpression(conditionExpression).build()); } @Test public void deleteNonExistentItem() { Record result = mappedTable.deleteItem(r -> r.key(k -> k.partitionValue("id-value").sortValue("sort-value"))); assertThat(result, is(nullValue())); } @Test public void deleteWithConditionThatSucceeds() { Record record = new Record() .setId("id-value") .setSort("sort-value") .setAttribute("one") .setAttribute2("two") .setAttribute3("three"); mappedTable.putItem(r -> r.item(record)); Expression conditionExpression = Expression.builder() .expression("#key = :value OR #key1 = :value1") .putExpressionName("#key", "attribute") .putExpressionName("#key1", ATTRIBUTE_NAME_WITH_SPECIAL_CHARACTERS) .putExpressionValue(":value", stringValue("wrong")) .putExpressionValue(":value1", stringValue("three")) .build(); Key key = mappedTable.keyFrom(record); mappedTable.deleteItem(DeleteItemEnhancedRequest.builder().key(key).conditionExpression(conditionExpression).build()); Record result = mappedTable.getItem(r -> r.key(key)); assertThat(result, is(nullValue())); } @Test public void deleteWithConditionThatFails() { Record record = new Record() .setId("id-value") .setSort("sort-value") .setAttribute("one") .setAttribute2("two") .setAttribute3("three"); mappedTable.putItem(r -> r.item(record)); Expression conditionExpression = Expression.builder() .expression("#key = :value OR #key1 = :value1") .putExpressionName("#key", "attribute") .putExpressionName("#key1", ATTRIBUTE_NAME_WITH_SPECIAL_CHARACTERS) .putExpressionValue(":value", stringValue("wrong")) .putExpressionValue(":value1", stringValue("wrong")) .build(); exception.expect(ConditionalCheckFailedException.class); mappedTable.deleteItem(DeleteItemEnhancedRequest.builder().key(mappedTable.keyFrom(record)) .conditionExpression(conditionExpression) .build()); } @Test public void updateOverwriteCompleteRecord_usingShortcutForm() { Record record = new Record() .setId("id-value") .setSort("sort-value") .setAttribute("one") .setAttribute2("two") .setAttribute3("three"); mappedTable.putItem(record); Record record2 = new Record() .setId("id-value") .setSort("sort-value") .setAttribute("four") .setAttribute2("five") .setAttribute3("six"); Record result = mappedTable.updateItem(record2); assertThat(result, is(record2)); } @Test public void updateCreatePartialRecord() { Record record = new Record() .setId("id-value") .setSort("sort-value") .setAttribute("one"); Record result = mappedTable.updateItem(r -> r.item(record)); assertThat(result, is(record)); } @Test public void updateCreateKeyOnlyRecord() { Record record = new Record() .setId("id-value") .setSort("sort-value"); Record result = mappedTable.updateItem(r -> r.item(record)); assertThat(result, is(record)); } @Test public void updateOverwriteModelledNulls() { Record record = new Record() .setId("id-value") .setSort("sort-value") .setAttribute("one") .setAttribute2("two") .setAttribute3("three"); mappedTable.putItem(r -> r.item(record)); Record record2 = new Record() .setId("id-value") .setSort("sort-value") .setAttribute("four"); Record result = mappedTable.updateItem(r -> r.item(record2)); assertThat(result, is(record2)); } @Test public void updateCanIgnoreNullsAndDoPartialUpdate() { Record record = new Record() .setId("id-value") .setSort("sort-value") .setAttribute("one") .setAttribute2("two") .setAttribute3("three"); mappedTable.putItem(r -> r.item(record)); Record record2 = new Record() .setId("id-value") .setSort("sort-value") .setAttribute("four"); Record result = mappedTable.updateItem(UpdateItemEnhancedRequest.builder(Record.class) .item(record2) .ignoreNulls(true) .build()); Record expectedResult = new Record() .setId("id-value") .setSort("sort-value") .setAttribute("four") .setAttribute2("two") .setAttribute3("three"); assertThat(result, is(expectedResult)); } @Test public void updateShortRecordDoesPartialUpdate() { Record record = new Record() .setId("id-value") .setSort("sort-value") .setAttribute("one") .setAttribute2("two") .setAttribute3("three"); mappedTable.putItem(r -> r.item(record)); ShortRecord record2 = new ShortRecord() .setId("id-value") .setSort("sort-value") .setAttribute("four"); ShortRecord shortResult = mappedShortTable.updateItem(r -> r.item(record2)); Record result = mappedTable.getItem(r -> r.key(k -> k.partitionValue(record.getId()).sortValue(record.getSort()))); Record expectedResult = new Record() .setId("id-value") .setSort("sort-value") .setAttribute("four") .setAttribute2("two") .setAttribute3("three"); assertThat(result, is(expectedResult)); assertThat(shortResult, is(record2)); } @Test public void updateKeyOnlyExistingRecordDoesNothing() { Record record = new Record() .setId("id-value") .setSort("sort-value") .setAttribute("one") .setAttribute2("two") .setAttribute3("three"); mappedTable.putItem(r -> r.item(record)); Record updateRecord = new Record().setId("id-value").setSort("sort-value"); Record result = mappedTable.updateItem(UpdateItemEnhancedRequest.builder(Record.class) .item(updateRecord) .ignoreNulls(true) .build()); assertThat(result, is(record)); } @Test public void updateWithConditionThatSucceeds() { Record record = new Record() .setId("id-value") .setSort("sort-value") .setAttribute("one") .setAttribute2("two") .setAttribute3("three"); mappedTable.putItem(r -> r.item(record)); record.setAttribute("four"); Expression conditionExpression = Expression.builder() .expression("#key = :value OR #key1 = :value1") .putExpressionName("#key", "attribute") .putExpressionName("#key1", ATTRIBUTE_NAME_WITH_SPECIAL_CHARACTERS) .putExpressionValue(":value", stringValue("wrong")) .putExpressionValue(":value1", stringValue("three")) .build(); mappedTable.updateItem(UpdateItemEnhancedRequest.builder(Record.class) .item(record) .conditionExpression(conditionExpression) .build()); Record result = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id-value").sortValue("sort-value"))); assertThat(result, is(record)); } @Test public void updateWithConditionThatFails() { Record record = new Record() .setId("id-value") .setSort("sort-value") .setAttribute("one") .setAttribute2("two") .setAttribute3("three"); mappedTable.putItem(r -> r.item(record)); record.setAttribute("four"); Expression conditionExpression = Expression.builder() .expression("#key = :value OR #key1 = :value1") .putExpressionName("#key", "attribute") .putExpressionName("#key1", ATTRIBUTE_NAME_WITH_SPECIAL_CHARACTERS) .putExpressionValue(":value", stringValue("wrong")) .putExpressionValue(":value1", stringValue("wrong")) .build(); exception.expect(ConditionalCheckFailedException.class); mappedTable.updateItem(UpdateItemEnhancedRequest.builder(Record.class) .item(record) .conditionExpression(conditionExpression) .build()); } @Test public void getAShortRecordWithNewModelledFields() { ShortRecord shortRecord = new ShortRecord() .setId("id-value") .setSort("sort-value") .setAttribute("one"); mappedShortTable.putItem(r -> r.item(shortRecord)); Record expectedRecord = new Record() .setId("id-value") .setSort("sort-value") .setAttribute("one"); Record result = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id-value").sortValue("sort-value"))); assertThat(result, is(expectedRecord)); } }
4,148
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/AsyncIndexScanTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.numberValue; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.stringValue; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primarySortKey; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.secondaryPartitionKey; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.secondarySortKey; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.junit.After; import org.junit.Before; import org.junit.Test; import software.amazon.awssdk.core.async.SdkPublisher; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbAsyncIndex; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbAsyncTable; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedAsyncClient; import software.amazon.awssdk.enhanced.dynamodb.Expression; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.internal.client.DefaultDynamoDbEnhancedAsyncClient; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema; import software.amazon.awssdk.enhanced.dynamodb.model.EnhancedGlobalSecondaryIndex; import software.amazon.awssdk.enhanced.dynamodb.model.Page; import software.amazon.awssdk.enhanced.dynamodb.model.ScanEnhancedRequest; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; import software.amazon.awssdk.services.dynamodb.model.ProjectionType; public class AsyncIndexScanTest extends LocalDynamoDbAsyncTestBase { private static class Record { private String id; private Integer sort; private Integer value; private String gsiId; private Integer gsiSort; private String getId() { return id; } private Record setId(String id) { this.id = id; return this; } private Integer getSort() { return sort; } private Record setSort(Integer sort) { this.sort = sort; return this; } private Integer getValue() { return value; } private Record setValue(Integer value) { this.value = value; return this; } private String getGsiId() { return gsiId; } private Record setGsiId(String gsiId) { this.gsiId = gsiId; return this; } private Integer getGsiSort() { return gsiSort; } private Record setGsiSort(Integer gsiSort) { this.gsiSort = gsiSort; return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Record record = (Record) o; return Objects.equals(id, record.id) && Objects.equals(sort, record.sort) && Objects.equals(value, record.value) && Objects.equals(gsiId, record.gsiId) && Objects.equals(gsiSort, record.gsiSort); } @Override public int hashCode() { return Objects.hash(id, sort, value, gsiId, gsiSort); } } private static final TableSchema<Record> TABLE_SCHEMA = StaticTableSchema.builder(Record.class) .newItemSupplier(Record::new) .addAttribute(String.class, a -> a.name("id") .getter(Record::getId) .setter(Record::setId) .tags(primaryPartitionKey())) .addAttribute(Integer.class, a -> a.name("sort") .getter(Record::getSort) .setter(Record::setSort) .tags(primarySortKey())) .addAttribute(Integer.class, a -> a.name("value") .getter(Record::getValue) .setter(Record::setValue)) .addAttribute(String.class, a -> a.name("gsi_id") .getter(Record::getGsiId) .setter(Record::setGsiId) .tags(secondaryPartitionKey("gsi_keys_only"))) .addAttribute(Integer.class, a -> a.name("gsi_sort") .getter(Record::getGsiSort) .setter(Record::setGsiSort) .tags(secondarySortKey("gsi_keys_only"))) .build(); private static final List<Record> RECORDS = IntStream.range(0, 10) .mapToObj(i -> new Record() .setId("id-value") .setSort(i) .setValue(i) .setGsiId("gsi-id-value") .setGsiSort(i)) .collect(Collectors.toList()); private static final List<Record> KEYS_ONLY_RECORDS = RECORDS.stream() .map(record -> new Record() .setId(record.id) .setSort(record.sort) .setGsiId(record.gsiId) .setGsiSort(record.gsiSort)) .collect(Collectors.toList()); private DynamoDbEnhancedAsyncClient enhancedAsyncClient = DefaultDynamoDbEnhancedAsyncClient.builder() .dynamoDbClient(getDynamoDbAsyncClient()) .build(); private DynamoDbAsyncTable<Record> mappedTable = enhancedAsyncClient.table(getConcreteTableName("table-name"), TABLE_SCHEMA); private DynamoDbAsyncIndex<Record> keysOnlyMappedIndex = mappedTable.index("gsi_keys_only"); private void insertRecords() { RECORDS.forEach(record -> mappedTable.putItem(r -> r.item(record)).join()); } @Before public void createTable() { mappedTable.createTable( r -> r.provisionedThroughput(getDefaultProvisionedThroughput()) .globalSecondaryIndices( EnhancedGlobalSecondaryIndex.builder() .indexName("gsi_keys_only") .projection(p -> p.projectionType(ProjectionType.KEYS_ONLY)) .provisionedThroughput(getDefaultProvisionedThroughput()).build())) .join(); } @After public void deleteTable() { getDynamoDbAsyncClient().deleteTable(DeleteTableRequest.builder() .tableName(getConcreteTableName("table-name")) .build()).join(); } @Test public void scanAllRecordsDefaultSettings() { insertRecords(); SdkPublisher<Page<Record>> publisher = keysOnlyMappedIndex.scan(ScanEnhancedRequest.builder().build()); List<Page<Record>> results = drainPublisher(publisher, 1); Page<Record> page = results.get(0); assertThat(page.items(), is(KEYS_ONLY_RECORDS)); assertThat(page.lastEvaluatedKey(), is(nullValue())); } @Test public void scanAllRecordsWithFilter() { insertRecords(); Map<String, AttributeValue> expressionValues = new HashMap<>(); expressionValues.put(":min_value", numberValue(3)); expressionValues.put(":max_value", numberValue(5)); Expression expression = Expression.builder() .expression("sort >= :min_value AND sort <= :max_value") .expressionValues(expressionValues) .build(); SdkPublisher<Page<Record>> publisher = keysOnlyMappedIndex.scan(ScanEnhancedRequest.builder() .filterExpression(expression) .build()); List<Page<Record>> results = drainPublisher(publisher, 1); Page<Record> page = results.get(0); assertThat(page.items(), is(KEYS_ONLY_RECORDS.stream().filter(r -> r.sort >= 3 && r.sort <= 5).collect(Collectors.toList()))); assertThat(page.lastEvaluatedKey(), is(nullValue())); } @Test public void scanLimit() { insertRecords(); SdkPublisher<Page<Record>> publisher = keysOnlyMappedIndex.scan(r -> r.limit(5)); List<Page<Record>> results = drainPublisher(publisher, 3); Page<Record> page1 = results.get(0); Page<Record> page2 = results.get(1); Page<Record> page3 = results.get(2); assertThat(page1.items(), is(KEYS_ONLY_RECORDS.subList(0, 5))); assertThat(page1.lastEvaluatedKey(), is(getKeyMap(4))); assertThat(page2.items(), is(KEYS_ONLY_RECORDS.subList(5, 10))); assertThat(page2.lastEvaluatedKey(), is(getKeyMap(9))); assertThat(page3.items(), is(empty())); assertThat(page3.lastEvaluatedKey(), is(nullValue())); } @Test public void scanEmpty() { SdkPublisher<Page<Record>> publisher = keysOnlyMappedIndex.scan(); List<Page<Record>> results = drainPublisher(publisher, 1); Page<Record> page = results.get(0); assertThat(page.items(), is(empty())); assertThat(page.lastEvaluatedKey(), is(nullValue())); } @Test public void scanExclusiveStartKey() { insertRecords(); SdkPublisher<Page<Record>> publisher = keysOnlyMappedIndex.scan(ScanEnhancedRequest.builder().exclusiveStartKey(getKeyMap(7)).build()); List<Page<Record>> results = drainPublisher(publisher, 1); Page<Record> page = results.get(0); assertThat(page.items(), is(KEYS_ONLY_RECORDS.subList(8, 10))); assertThat(page.lastEvaluatedKey(), is(nullValue())); } private Map<String, AttributeValue> getKeyMap(int sort) { Map<String, AttributeValue> result = new HashMap<>(); result.put("id", stringValue(KEYS_ONLY_RECORDS.get(sort).getId())); result.put("sort", numberValue(KEYS_ONLY_RECORDS.get(sort).getSort())); result.put("gsi_id", stringValue(KEYS_ONLY_RECORDS.get(sort).getGsiId())); result.put("gsi_sort", numberValue(KEYS_ONLY_RECORDS.get(sort).getGsiSort())); return Collections.unmodifiableMap(result); } }
4,149
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/LocalDynamoDb.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests; import static org.assertj.core.api.Assertions.assertThat; import java.io.IOException; import java.net.ServerSocket; import java.net.URI; import java.util.Optional; import com.amazonaws.services.dynamodbv2.local.main.ServerRunner; import com.amazonaws.services.dynamodbv2.local.server.DynamoDBProxyServer; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; /** * Wrapper for a local DynamoDb server used in testing. Each instance of this class will find a new port to run on, * so multiple instances can be safely run simultaneously. Each instance of this service uses memory as a storage medium * and is thus completely ephemeral; no data will be persisted between stops and starts. * * LocalDynamoDb localDynamoDb = new LocalDynamoDb(); * localDynamoDb.start(); // Start the service running locally on host * DynamoDbClient dynamoDbClient = localDynamoDb.createClient(); * ... // Do your testing with the client * localDynamoDb.stop(); // Stop the service and free up resources * * If possible it's recommended to keep a single running instance for all your tests, as it can be slow to teardown * and create new servers for every test, but there have been observed problems when dropping tables between tests for * this scenario, so it's best to write your tests to be resilient to tables that already have data in them. */ class LocalDynamoDb { private DynamoDBProxyServer server; private int port; /** * Start the local DynamoDb service and run in background */ void start() { port = getFreePort(); String portString = Integer.toString(port); try { server = createServer(portString); server.start(); } catch (Exception e) { throw propagate(e); } } /** * Create a standard AWS v2 SDK client pointing to the local DynamoDb instance * @return A DynamoDbClient pointing to the local DynamoDb instance */ DynamoDbClient createClient() { String endpoint = String.format("http://localhost:%d", port); return DynamoDbClient.builder() .endpointOverride(URI.create(endpoint)) // The region is meaningless for local DynamoDb but required for client builder validation .region(Region.US_EAST_1) .credentialsProvider(StaticCredentialsProvider.create( AwsBasicCredentials.create("dummy-key", "dummy-secret"))) .overrideConfiguration(o -> o.addExecutionInterceptor(new VerifyUserAgentInterceptor())) .build(); } DynamoDbAsyncClient createAsyncClient() { String endpoint = String.format("http://localhost:%d", port); return DynamoDbAsyncClient.builder() .endpointOverride(URI.create(endpoint)) .region(Region.US_EAST_1) .credentialsProvider(StaticCredentialsProvider.create( AwsBasicCredentials.create("dummy-key", "dummy-secret"))) .overrideConfiguration(o -> o.addExecutionInterceptor(new VerifyUserAgentInterceptor())) .build(); } /** * Stops the local DynamoDb service and frees up resources it is using. */ void stop() { try { server.stop(); } catch (Exception e) { throw propagate(e); } } private DynamoDBProxyServer createServer(String portString) throws Exception { return ServerRunner.createServerFromCommandLineArgs( new String[]{ "-inMemory", "-port", portString }); } private int getFreePort() { try { ServerSocket socket = new ServerSocket(0); int port = socket.getLocalPort(); socket.close(); return port; } catch (IOException ioe) { throw propagate(ioe); } } private static RuntimeException propagate(Exception e) { if (e instanceof RuntimeException) { throw (RuntimeException)e; } throw new RuntimeException(e); } private static class VerifyUserAgentInterceptor implements ExecutionInterceptor { @Override public void beforeTransmission(Context.BeforeTransmission context, ExecutionAttributes executionAttributes) { Optional<String> headers = context.httpRequest().firstMatchingHeader("User-agent"); assertThat(headers).isPresent(); assertThat(headers.get()).contains("hll/ddb-enh"); } } }
4,150
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/LocalDynamoDbAsyncTestBase.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import java.util.List; import software.amazon.awssdk.core.async.SdkPublisher; import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient; public class LocalDynamoDbAsyncTestBase extends LocalDynamoDbTestBase { private DynamoDbAsyncClient dynamoDbAsyncClient = localDynamoDb().createAsyncClient(); protected DynamoDbAsyncClient getDynamoDbAsyncClient() { return dynamoDbAsyncClient; } public static <T> List<T> drainPublisher(SdkPublisher<T> publisher, int expectedNumberOfResults) { BufferingSubscriber<T> subscriber = new BufferingSubscriber<>(); publisher.subscribe(subscriber); subscriber.waitForCompletion(5000L); assertThat(subscriber.isCompleted(), is(true)); assertThat(subscriber.bufferedError(), is(nullValue())); assertThat(subscriber.bufferedItems().size(), is(expectedNumberOfResults)); return subscriber.bufferedItems(); } public static <T> List<T> drainPublisherToError(SdkPublisher<T> publisher, int expectedNumberOfResults, Class<? extends Throwable> expectedError) { BufferingSubscriber<T> subscriber = new BufferingSubscriber<>(); publisher.subscribe(subscriber); subscriber.waitForCompletion(1000L); assertThat(subscriber.isCompleted(), is(false)); assertThat(subscriber.bufferedError(), instanceOf(expectedError)); assertThat(subscriber.bufferedItems().size(), is(expectedNumberOfResults)); return subscriber.bufferedItems(); } }
4,151
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/FlattenTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey; import java.util.Objects; import org.junit.After; import org.junit.Before; import org.junit.Test; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema; import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; public class FlattenTest extends LocalDynamoDbSyncTestBase { private static class Record { private String id; private Document document; private String getId() { return id; } private Record setId(String id) { this.id = id; return this; } private Document getDocument() { return document; } private Record setDocument(Document document) { this.document = document; return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Record record = (Record) o; return Objects.equals(id, record.id) && Objects.equals(document, record.document); } @Override public int hashCode() { return Objects.hash(id, document); } } private static class Document { private String documentAttribute1; private String documentAttribute2; private String documentAttribute3; private String getDocumentAttribute1() { return documentAttribute1; } private Document setDocumentAttribute1(String documentAttribute1) { this.documentAttribute1 = documentAttribute1; return this; } private String getDocumentAttribute2() { return documentAttribute2; } private Document setDocumentAttribute2(String documentAttribute2) { this.documentAttribute2 = documentAttribute2; return this; } private String getDocumentAttribute3() { return documentAttribute3; } private Document setDocumentAttribute3(String documentAttribute3) { this.documentAttribute3 = documentAttribute3; return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Document document = (Document) o; return Objects.equals(documentAttribute1, document.documentAttribute1) && Objects.equals(documentAttribute2, document.documentAttribute2) && Objects.equals(documentAttribute3, document.documentAttribute3); } @Override public int hashCode() { return Objects.hash(documentAttribute1, documentAttribute2, documentAttribute3); } } private static final StaticTableSchema<Document> DOCUMENT_SCHEMA = StaticTableSchema.builder(Document.class) .newItemSupplier(Document::new) .addAttribute(String.class, a -> a.name("documentAttribute1") .getter(Document::getDocumentAttribute1) .setter(Document::setDocumentAttribute1)) .addAttribute(String.class, a -> a.name("documentAttribute2") .getter(Document::getDocumentAttribute2) .setter(Document::setDocumentAttribute2)) .addAttribute(String.class, a -> a.name("documentAttribute3") .getter(Document::getDocumentAttribute3) .setter(Document::setDocumentAttribute3)) .build(); private static final TableSchema<Record> TABLE_SCHEMA = StaticTableSchema.builder(Record.class) .newItemSupplier(Record::new) .addAttribute(String.class, a -> a.name("id") .getter(Record::getId) .setter(Record::setId) .tags(primaryPartitionKey())) .flatten(DOCUMENT_SCHEMA, Record::getDocument, Record::setDocument) .build(); private DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() .dynamoDbClient(getDynamoDbClient()) .build(); private DynamoDbTable<Record> mappedTable = enhancedClient.table(getConcreteTableName("table-name"), TABLE_SCHEMA); @Before public void createTable() { mappedTable.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput())); } @After public void deleteTable() { getDynamoDbClient().deleteTable(DeleteTableRequest.builder() .tableName(getConcreteTableName("table-name")) .build()); } @Test public void update_allValues() { Document document = new Document() .setDocumentAttribute1("one") .setDocumentAttribute2("two") .setDocumentAttribute3("three"); Record record = new Record() .setId("id-value") .setDocument(document); Record updatedRecord = mappedTable.updateItem(r -> r.item(record)); Record fetchedRecord = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id-value"))); assertThat(updatedRecord, is(record)); assertThat(fetchedRecord, is(record)); } @Test public void update_someValues() { Document document = new Document() .setDocumentAttribute1("one") .setDocumentAttribute2("two"); Record record = new Record() .setId("id-value") .setDocument(document); Record updatedRecord = mappedTable.updateItem(r -> r.item(record)); Record fetchedRecord = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id-value"))); assertThat(updatedRecord, is(record)); assertThat(fetchedRecord, is(record)); } @Test public void update_nullDocument() { Record record = new Record() .setId("id-value"); Record updatedRecord = mappedTable.updateItem(r -> r.item(record)); Record fetchedRecord = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id-value"))); assertThat(updatedRecord, is(record)); assertThat(fetchedRecord, is(record)); } }
4,152
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/BasicControlPlaneTableOperationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests; import static org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primarySortKey; import java.util.Objects; import org.junit.After; import org.junit.Before; import org.junit.Test; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema; import software.amazon.awssdk.enhanced.dynamodb.model.CreateTableEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.DescribeTableEnhancedResponse; import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; public class BasicControlPlaneTableOperationTest extends LocalDynamoDbSyncTestBase { private static final TableSchema<Record> TABLE_SCHEMA = StaticTableSchema.builder(Record.class) .newItemSupplier(Record::new) .addAttribute(String.class, a -> a.name("id") .getter(Record::getId) .setter(Record::setId) .tags(primaryPartitionKey())) .addAttribute(Integer.class, a -> a.name("sort") .getter(Record::getSort) .setter(Record::setSort) .tags(primarySortKey())) .build(); private final String tableName = getConcreteTableName("table-name"); private final DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() .dynamoDbClient(getDynamoDbClient()) .build(); private final DynamoDbTable<Record> mappedTable = enhancedClient.table(getConcreteTableName("table-name"), TABLE_SCHEMA); @Before public void createTable() { mappedTable.createTable( CreateTableEnhancedRequest.builder() .provisionedThroughput(getDefaultProvisionedThroughput()) .build()); getDynamoDbClient().waiter().waitUntilTableExists(b -> b.tableName(tableName)); } @After public void deleteTable() { getDynamoDbClient().deleteTable(DeleteTableRequest.builder() .tableName(tableName) .build()); getDynamoDbClient().waiter().waitUntilTableNotExists(b -> b.tableName(tableName)); } @Test public void describeTable() { DescribeTableEnhancedResponse describeTableEnhancedResponse = mappedTable.describeTable(); assertThat(describeTableEnhancedResponse.table()).isNotNull(); assertThat(describeTableEnhancedResponse.table().tableName()).isEqualTo(tableName); } private static class Record { private String id; private Integer sort; private String getId() { return id; } private Record setId(String id) { this.id = id; return this; } private Integer getSort() { return sort; } private Record setSort(Integer sort) { this.sort = sort; return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Record record = (Record) o; return Objects.equals(id, record.id) && Objects.equals(sort, record.sort); } @Override public int hashCode() { return Objects.hash(id, sort); } } }
4,153
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/FailedConversionAsyncTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.List; import java.util.concurrent.CompletionException; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbAsyncTable; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedAsyncClient; import software.amazon.awssdk.enhanced.dynamodb.Key; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeEnum; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeEnumRecord; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeEnumShortened; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeEnumShortenedRecord; import software.amazon.awssdk.enhanced.dynamodb.model.Page; import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; public class FailedConversionAsyncTest extends LocalDynamoDbAsyncTestBase { private static final TableSchema<FakeEnumRecord> TABLE_SCHEMA = TableSchema.fromClass(FakeEnumRecord.class); private static final TableSchema<FakeEnumShortenedRecord> SHORT_TABLE_SCHEMA = TableSchema.fromClass(FakeEnumShortenedRecord.class); private final DynamoDbEnhancedAsyncClient enhancedClient = DynamoDbEnhancedAsyncClient.builder() .dynamoDbClient(getDynamoDbAsyncClient()) .build(); private final DynamoDbAsyncTable<FakeEnumRecord> mappedTable = enhancedClient.table(getConcreteTableName("table-name"), TABLE_SCHEMA); private final DynamoDbAsyncTable<FakeEnumShortenedRecord> mappedShortTable = enhancedClient.table(getConcreteTableName("table-name"), SHORT_TABLE_SCHEMA); @Rule public ExpectedException exception = ExpectedException.none(); @Before public void createTable() { mappedTable.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput())).join(); } @After public void deleteTable() { getDynamoDbAsyncClient().deleteTable(DeleteTableRequest.builder() .tableName(getConcreteTableName("table-name")) .build()).join(); } @Test public void exceptionOnRead() { FakeEnumRecord record = new FakeEnumRecord(); record.setId("123"); record.setEnumAttribute(FakeEnum.TWO); mappedTable.putItem(record).join(); assertThatThrownBy(() -> mappedShortTable.getItem(Key.builder().partitionValue("123").build()).join()) .isInstanceOf(CompletionException.class) .hasCauseInstanceOf(IllegalArgumentException.class) .hasMessageContaining("TWO") .hasMessageContaining("FakeEnumShortened"); } @Test public void iterableExceptionOnRead() { FakeEnumRecord record = new FakeEnumRecord(); record.setId("1"); record.setEnumAttribute(FakeEnum.ONE); mappedTable.putItem(record).join(); record.setId("2"); record.setEnumAttribute(FakeEnum.TWO); mappedTable.putItem(record).join(); List<Page<FakeEnumShortenedRecord>> results = drainPublisherToError(mappedShortTable.scan(r -> r.limit(1)), 1, IllegalArgumentException.class); assertThat(results).hasOnlyOneElementSatisfying( page -> assertThat(page.items()).hasOnlyOneElementSatisfying(item -> { assertThat(item.getId()).isEqualTo("1"); assertThat(item.getEnumAttribute()).isEqualTo(FakeEnumShortened.ONE); })); } }
4,154
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/BasicScanTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.numberValue; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.stringValue; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primarySortKey; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.junit.After; import org.junit.Before; import org.junit.Test; import software.amazon.awssdk.core.pagination.sync.SdkIterable; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.Expression; import software.amazon.awssdk.enhanced.dynamodb.NestedAttributeName; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.InnerAttributeRecord; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.NestedTestRecord; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema; import software.amazon.awssdk.enhanced.dynamodb.model.Page; import software.amazon.awssdk.enhanced.dynamodb.model.ScanEnhancedRequest; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; public class BasicScanTest extends LocalDynamoDbSyncTestBase { private static class Record { private String id; private Integer sort; private String getId() { return id; } private Record setId(String id) { this.id = id; return this; } private Integer getSort() { return sort; } private Record setSort(Integer sort) { this.sort = sort; return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Record record = (Record) o; return Objects.equals(id, record.id) && Objects.equals(sort, record.sort); } @Override public int hashCode() { return Objects.hash(id, sort); } } private static final TableSchema<Record> TABLE_SCHEMA = StaticTableSchema.builder(Record.class) .newItemSupplier(Record::new) .addAttribute(String.class, a -> a.name("id") .getter(Record::getId) .setter(Record::setId) .tags(primaryPartitionKey())) .addAttribute(Integer.class, a -> a.name("sort") .getter(Record::getSort) .setter(Record::setSort) .tags(primarySortKey())) .build(); private static final List<Record> RECORDS = IntStream.range(0, 10) .mapToObj(i -> new Record().setId("id-value").setSort(i)) .collect(Collectors.toList()); private static final List<NestedTestRecord> NESTED_TEST_RECORDS = IntStream.range(0, 10) .mapToObj(i -> { final NestedTestRecord nestedTestRecord = new NestedTestRecord(); nestedTestRecord.setOuterAttribOne("id-value-" + i); nestedTestRecord.setSort(i); final InnerAttributeRecord innerAttributeRecord = new InnerAttributeRecord(); innerAttributeRecord.setAttribOne("attribOne-"+i); innerAttributeRecord.setAttribTwo(i); nestedTestRecord.setInnerAttributeRecord(innerAttributeRecord); nestedTestRecord.setDotVariable("v"+i); return nestedTestRecord; }) .collect(Collectors.toList()); private DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() .dynamoDbClient(getDynamoDbClient()) .build(); private DynamoDbTable<Record> mappedTable = enhancedClient.table(getConcreteTableName("table-name"), TABLE_SCHEMA); private DynamoDbTable<NestedTestRecord> mappedNestedTable = enhancedClient.table(getConcreteTableName("nested-table-name"), TableSchema.fromClass(NestedTestRecord.class)); private void insertRecords() { RECORDS.forEach(record -> mappedTable.putItem(r -> r.item(record))); } private void insertNestedRecords() { NESTED_TEST_RECORDS.forEach(nestedTestRecord -> mappedNestedTable.putItem(r -> r.item(nestedTestRecord))); } @Before public void createTable() { mappedTable.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput())); mappedNestedTable.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput())); } @After public void deleteTable() { getDynamoDbClient().deleteTable(DeleteTableRequest.builder() .tableName(getConcreteTableName("table-name")) .build()); getDynamoDbClient().deleteTable(DeleteTableRequest.builder() .tableName(getConcreteTableName("nested-table-name")) .build()); } @Test public void scanAllRecordsDefaultSettings() { insertRecords(); mappedTable.scan(ScanEnhancedRequest.builder().build()) .forEach(p -> p.items().forEach(item -> System.out.println(item))); Iterator<Page<Record>> results = mappedTable.scan(ScanEnhancedRequest.builder().build()).iterator(); assertThat(results.hasNext(), is(true)); Page<Record> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items(), is(RECORDS)); assertThat(page.lastEvaluatedKey(), is(nullValue())); } @Test public void queryAllRecordsDefaultSettings_withProjection() { insertRecords(); Iterator<Page<Record>> results = mappedTable.scan(b -> b.attributesToProject("sort")).iterator(); assertThat(results.hasNext(), is(true)); Page<Record> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items().size(), is(RECORDS.size())); Record firstRecord = page.items().get(0); assertThat(firstRecord.id, is(nullValue())); assertThat(firstRecord.sort, is(0)); } @Test public void scanAllRecordsDefaultSettings_viaItems() { insertRecords(); SdkIterable<Record> items = mappedTable.scan(ScanEnhancedRequest.builder().limit(2).build()).items(); assertThat(items.stream().collect(Collectors.toList()), is(RECORDS)); } @Test public void scanAllRecordsWithFilter() { insertRecords(); Map<String, AttributeValue> expressionValues = new HashMap<>(); expressionValues.put(":min_value", numberValue(3)); expressionValues.put(":max_value", numberValue(5)); Expression expression = Expression.builder() .expression("sort >= :min_value AND sort <= :max_value") .expressionValues(expressionValues) .build(); Iterator<Page<Record>> results = mappedTable.scan(ScanEnhancedRequest.builder().filterExpression(expression).build()).iterator(); assertThat(results.hasNext(), is(true)); Page<Record> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items(), is(RECORDS.stream().filter(r -> r.sort >= 3 && r.sort <= 5).collect(Collectors.toList()))); assertThat(page.lastEvaluatedKey(), is(nullValue())); } @Test public void scanAllRecordsWithFilterAndProjection() { insertRecords(); Map<String, AttributeValue> expressionValues = new HashMap<>(); expressionValues.put(":min_value", numberValue(3)); expressionValues.put(":max_value", numberValue(5)); Expression expression = Expression.builder() .expression("#sort >= :min_value AND #sort <= :max_value") .expressionValues(expressionValues) .putExpressionName("#sort", "sort") .build(); Iterator<Page<Record>> results = mappedTable.scan( ScanEnhancedRequest.builder() .attributesToProject("sort") .filterExpression(expression) .build() ).iterator(); assertThat(results.hasNext(), is(true)); Page<Record> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items(), hasSize(3)); Record record = page.items().get(0); assertThat(record.id, is(nullValue())); assertThat(record.sort, is(3)); } @Test public void scanLimit() { insertRecords(); Iterator<Page<Record>> results = mappedTable.scan(r -> r.limit(5)).iterator(); assertThat(results.hasNext(), is(true)); Page<Record> page1 = results.next(); assertThat(results.hasNext(), is(true)); Page<Record> page2 = results.next(); assertThat(results.hasNext(), is(true)); Page<Record> page3 = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page1.items(), is(RECORDS.subList(0, 5))); assertThat(page1.lastEvaluatedKey(), is(getKeyMap(4))); assertThat(page2.items(), is(RECORDS.subList(5, 10))); assertThat(page2.lastEvaluatedKey(), is(getKeyMap(9))); assertThat(page3.items(), is(empty())); assertThat(page3.lastEvaluatedKey(), is(nullValue())); } @Test public void scanLimit_viaItems() { insertRecords(); SdkIterable<Record> results = mappedTable.scan(r -> r.limit(5)).items(); assertThat(results.stream().collect(Collectors.toList()), is(RECORDS)); } @Test public void scanEmpty() { Iterator<Page<Record>> results = mappedTable.scan().iterator(); assertThat(results.hasNext(), is(true)); Page<Record> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items(), is(empty())); assertThat(page.lastEvaluatedKey(), is(nullValue())); } @Test public void scanEmpty_viaItems() { Iterator<Record> results = mappedTable.scan().items().iterator(); assertThat(results.hasNext(), is(false)); } @Test public void scanExclusiveStartKey() { insertRecords(); Iterator<Page<Record>> results = mappedTable.scan(r -> r.exclusiveStartKey(getKeyMap(7))).iterator(); assertThat(results.hasNext(), is(true)); Page<Record> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items(), is(RECORDS.subList(8, 10))); assertThat(page.lastEvaluatedKey(), is(nullValue())); } @Test public void scanExclusiveStartKey_viaItems() { insertRecords(); SdkIterable<Record> results = mappedTable.scan(r -> r.exclusiveStartKey(getKeyMap(7))).items(); assertThat(results.stream().collect(Collectors.toList()), is(RECORDS.subList(8, 10))); } private Map<String, AttributeValue> getKeyMap(int sort) { Map<String, AttributeValue> result = new HashMap<>(); result.put("id", stringValue("id-value")); result.put("sort", numberValue(sort)); return Collections.unmodifiableMap(result); } @Test public void scanAllRecordsWithFilterAndNestedProjectionSingleAttribute() { insertNestedRecords(); Map<String, AttributeValue> expressionValues = new HashMap<>(); expressionValues.put(":min_value", numberValue(3)); expressionValues.put(":max_value", numberValue(5)); Expression expression = Expression.builder() .expression("#sort >= :min_value AND #sort <= :max_value") .expressionValues(expressionValues) .putExpressionName("#sort", "sort") .build(); Iterator<Page<NestedTestRecord>> results = mappedNestedTable.scan( ScanEnhancedRequest.builder() .filterExpression(expression) .addNestedAttributesToProject( NestedAttributeName.create(Arrays.asList("innerAttributeRecord","attribOne"))) .build() ).iterator(); assertThat(results.hasNext(), is(true)); Page<NestedTestRecord> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items().size(), is(3)); Collections.sort(page.items(), (item1, item2) -> item1.getInnerAttributeRecord().getAttribOne() .compareTo(item2.getInnerAttributeRecord().getAttribOne())); NestedTestRecord firstRecord = page.items().get(0); assertThat(firstRecord.getOuterAttribOne(), is(nullValue())); assertThat(firstRecord.getSort(), is(nullValue())); assertThat(firstRecord.getInnerAttributeRecord().getAttribOne(), is("attribOne-3")); assertThat(firstRecord.getInnerAttributeRecord().getAttribTwo(), is(nullValue())); //Attribute repeated with new and old attributeToProject results = mappedNestedTable.scan( ScanEnhancedRequest.builder() .filterExpression(expression) .addNestedAttributesToProject(NestedAttributeName.create("sort")) .addAttributeToProject("sort") .build() ).iterator(); assertThat(results.hasNext(), is(true)); page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items().size(), is(3)); Collections.sort(page.items(), (item1, item2) -> item1.getSort() .compareTo(item2.getSort())); firstRecord = page.items().get(0); assertThat(firstRecord.getOuterAttribOne(), is(nullValue())); assertThat(firstRecord.getSort(), is(3)); assertThat(firstRecord.getInnerAttributeRecord(), is(nullValue())); assertThat(firstRecord.getInnerAttributeRecord(), is(nullValue())); results = mappedNestedTable.scan( ScanEnhancedRequest.builder() .filterExpression(expression) .addNestedAttributeToProject( NestedAttributeName.create(Arrays.asList("innerAttributeRecord","attribOne"))) .build() ).iterator(); assertThat(results.hasNext(), is(true)); page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items().size(), is(3)); Collections.sort(page.items(), (item1, item2) -> item1.getInnerAttributeRecord().getAttribOne() .compareTo(item2.getInnerAttributeRecord().getAttribOne())); firstRecord = page.items().get(0); assertThat(firstRecord.getOuterAttribOne(), is(nullValue())); assertThat(firstRecord.getSort(), is(nullValue())); assertThat(firstRecord.getInnerAttributeRecord().getAttribOne(), is("attribOne-3")); assertThat(firstRecord.getInnerAttributeRecord().getAttribTwo(), is(nullValue())); } @Test public void scanAllRecordsWithFilterAndNestedProjectionMultipleAttribute() { insertNestedRecords(); Map<String, AttributeValue> expressionValues = new HashMap<>(); expressionValues.put(":min_value", numberValue(3)); expressionValues.put(":max_value", numberValue(5)); Expression expression = Expression.builder() .expression("#sort >= :min_value AND #sort <= :max_value") .expressionValues(expressionValues) .putExpressionName("#sort", "sort") .build(); final ScanEnhancedRequest build = ScanEnhancedRequest.builder() .filterExpression(expression) .addAttributeToProject("outerAttribOne") .addNestedAttributesToProject(Arrays.asList(NestedAttributeName.builder().elements("innerAttributeRecord") .addElement("attribOne").build())) .addNestedAttributeToProject(NestedAttributeName.builder() .elements(Arrays.asList("innerAttributeRecord", "attribTwo")).build()) .build(); Iterator<Page<NestedTestRecord>> results = mappedNestedTable.scan( build ).iterator(); assertThat(results.hasNext(), is(true)); Page<NestedTestRecord> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items().size(), is(3)); Collections.sort(page.items(), (item1, item2) -> item1.getInnerAttributeRecord().getAttribOne() .compareTo(item2.getInnerAttributeRecord().getAttribOne())); NestedTestRecord firstRecord = page.items().get(0); assertThat(firstRecord.getOuterAttribOne(), is("id-value-3")); assertThat(firstRecord.getSort(), is(nullValue())); assertThat(firstRecord.getInnerAttributeRecord().getAttribOne(), is("attribOne-3")); assertThat(firstRecord.getInnerAttributeRecord().getAttribTwo(), is(3)); } @Test public void scanAllRecordsWithNonExistigKeyName() { insertNestedRecords(); Map<String, AttributeValue> expressionValues = new HashMap<>(); expressionValues.put(":min_value", numberValue(3)); expressionValues.put(":max_value", numberValue(5)); Expression expression = Expression.builder() .expression("#sort >= :min_value AND #sort <= :max_value") .expressionValues(expressionValues) .putExpressionName("#sort", "sort") .build(); Iterator<Page<NestedTestRecord>> results = mappedNestedTable.scan( ScanEnhancedRequest.builder() .filterExpression(expression) .addNestedAttributesToProject(NestedAttributeName.builder().addElement("nonExistent").build()) .build() ).iterator(); assertThat(results.hasNext(), is(true)); Page<NestedTestRecord> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items().size(), is(3)); NestedTestRecord firstRecord = page.items().get(0); assertThat(firstRecord, is(nullValue())); } @Test public void scanAllRecordsWithDotInAttributeKeyName() { insertNestedRecords(); Map<String, AttributeValue> expressionValues = new HashMap<>(); expressionValues.put(":min_value", numberValue(3)); expressionValues.put(":max_value", numberValue(5)); Expression expression = Expression.builder() .expression("#sort >= :min_value AND #sort <= :max_value") .expressionValues(expressionValues) .putExpressionName("#sort", "sort") .build(); Iterator<Page<NestedTestRecord>> results = mappedNestedTable.scan( ScanEnhancedRequest.builder() .filterExpression(expression) .addNestedAttributesToProject(NestedAttributeName .create("test.com")).build() ).iterator(); assertThat(results.hasNext(), is(true)); Page<NestedTestRecord> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items().size(), is(3)); Collections.sort(page.items(), (item1, item2) -> item1.getDotVariable() .compareTo(item2.getDotVariable())); NestedTestRecord firstRecord = page.items().get(0); assertThat(firstRecord.getOuterAttribOne(), is(nullValue())); assertThat(firstRecord.getSort(), is(nullValue())); assertThat(firstRecord.getDotVariable(), is("v3")); assertThat(firstRecord.getInnerAttributeRecord(), is(nullValue())); assertThat(firstRecord.getInnerAttributeRecord(), is(nullValue())); } @Test public void scanAllRecordsWithSameNamesRepeated() { //Attribute repeated with new and old attributeToProject insertNestedRecords(); Map<String, AttributeValue> expressionValues = new HashMap<>(); expressionValues.put(":min_value", numberValue(3)); expressionValues.put(":max_value", numberValue(5)); Expression expression = Expression.builder() .expression("#sort >= :min_value AND #sort <= :max_value") .expressionValues(expressionValues) .putExpressionName("#sort", "sort") .build(); Iterator<Page<NestedTestRecord> >results = mappedNestedTable.scan( ScanEnhancedRequest.builder() .filterExpression(expression) .addNestedAttributesToProject(NestedAttributeName.builder().elements("sort").build()) .addAttributeToProject("sort") .build() ).iterator(); assertThat(results.hasNext(), is(true)); Page<NestedTestRecord> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items().size(), is(3)); Collections.sort(page.items(), (item1, item2) -> item1.getSort() .compareTo(item2.getSort())); NestedTestRecord firstRecord = page.items().get(0); assertThat(firstRecord.getOuterAttribOne(), is(nullValue())); assertThat(firstRecord.getSort(), is(3)); assertThat(firstRecord.getInnerAttributeRecord(), is(nullValue())); assertThat(firstRecord.getInnerAttributeRecord(), is(nullValue())); } @Test public void scanAllRecordsWithEmptyList() { //Attribute repeated with new and old attributeToProject insertNestedRecords(); Map<String, AttributeValue> expressionValues = new HashMap<>(); expressionValues.put(":min_value", numberValue(3)); expressionValues.put(":max_value", numberValue(5)); Expression expression = Expression.builder() .expression("#sort >= :min_value AND #sort <= :max_value") .expressionValues(expressionValues) .putExpressionName("#sort", "sort") .build(); Iterator<Page<NestedTestRecord> >results = mappedNestedTable.scan( ScanEnhancedRequest.builder() .filterExpression(expression) .addNestedAttributesToProject(new ArrayList<>()) .build() ).iterator(); assertThat(results.hasNext(), is(true)); Page<NestedTestRecord> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items().size(), is(3)); Collections.sort(page.items(), (item1, item2) -> item1.getSort() .compareTo(item2.getSort())); NestedTestRecord firstRecord = page.items().get(0); assertThat(firstRecord.getOuterAttribOne(), is("id-value-3")); assertThat(firstRecord.getSort(), is(3)); assertThat(firstRecord.getInnerAttributeRecord().getAttribTwo(), is(3)); assertThat(firstRecord.getInnerAttributeRecord().getAttribOne(), is("attribOne-3")); } @Test public void scanAllRecordsWithNullAttributesToProject() { //Attribute repeated with new and old attributeToProject insertNestedRecords(); List<String> backwardCompatibilityNull = null; Map<String, AttributeValue> expressionValues = new HashMap<>(); expressionValues.put(":min_value", numberValue(3)); expressionValues.put(":max_value", numberValue(5)); Expression expression = Expression.builder() .expression("#sort >= :min_value AND #sort <= :max_value") .expressionValues(expressionValues) .putExpressionName("#sort", "sort") .build(); Iterator<Page<NestedTestRecord> >results = mappedNestedTable.scan( ScanEnhancedRequest.builder() .filterExpression(expression) .attributesToProject("test.com") .attributesToProject(backwardCompatibilityNull) .build() ).iterator(); assertThat(results.hasNext(), is(true)); Page<NestedTestRecord> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items().size(), is(3)); Collections.sort(page.items(), (item1, item2) -> item1.getSort() .compareTo(item2.getSort())); NestedTestRecord firstRecord = page.items().get(0); assertThat(firstRecord.getOuterAttribOne(), is("id-value-3")); assertThat(firstRecord.getSort(), is(3)); assertThat(firstRecord.getInnerAttributeRecord().getAttribTwo(), is(3)); assertThat(firstRecord.getInnerAttributeRecord().getAttribOne(), is("attribOne-3")); } @Test public void scanAllRecordsWithNestedProjectionNameEmptyNameMap() { insertNestedRecords(); Map<String, AttributeValue> expressionValues = new HashMap<>(); expressionValues.put(":min_value", numberValue(3)); expressionValues.put(":max_value", numberValue(5)); Expression expression = Expression.builder() .expression("#sort >= :min_value AND #sort <= :max_value") .expressionValues(expressionValues) .putExpressionName("#sort", "sort") .build(); final Iterator<Page<NestedTestRecord>> results = mappedNestedTable.scan( ScanEnhancedRequest.builder() .filterExpression(expression) .addNestedAttributesToProject(NestedAttributeName.builder().elements("").build()).build() ).iterator(); assertThatExceptionOfType(Exception.class).isThrownBy(() -> { final boolean b = results.hasNext(); Page<NestedTestRecord> next = results.next(); }).withMessageContaining("ExpressionAttributeNames contains invalid value"); final Iterator<Page<NestedTestRecord>> resultsAttributeToProject = mappedNestedTable.scan( ScanEnhancedRequest.builder() .filterExpression(expression) .addAttributeToProject("").build() ).iterator(); assertThatExceptionOfType(Exception.class).isThrownBy(() -> { final boolean b = resultsAttributeToProject.hasNext(); Page<NestedTestRecord> next = resultsAttributeToProject.next(); }); } }
4,155
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/FlattenWithTagsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primarySortKey; import java.util.Objects; import org.junit.After; import org.junit.Before; import org.junit.Test; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema; import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; public class FlattenWithTagsTest extends LocalDynamoDbSyncTestBase { private static class Record { private String id; private Document document; private String getId() { return id; } private Record setId(String id) { this.id = id; return this; } private Document getDocument() { return document; } private Record setDocument(Document document) { this.document = document; return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Record record = (Record) o; return Objects.equals(id, record.id) && Objects.equals(document, record.document); } @Override public int hashCode() { return Objects.hash(id, document); } } private static class Document { private String documentAttribute1; private String documentAttribute2; private String documentAttribute3; private String getDocumentAttribute1() { return documentAttribute1; } private Document setDocumentAttribute1(String documentAttribute1) { this.documentAttribute1 = documentAttribute1; return this; } private String getDocumentAttribute2() { return documentAttribute2; } private Document setDocumentAttribute2(String documentAttribute2) { this.documentAttribute2 = documentAttribute2; return this; } private String getDocumentAttribute3() { return documentAttribute3; } private Document setDocumentAttribute3(String documentAttribute3) { this.documentAttribute3 = documentAttribute3; return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Document document = (Document) o; return Objects.equals(documentAttribute1, document.documentAttribute1) && Objects.equals(documentAttribute2, document.documentAttribute2) && Objects.equals(documentAttribute3, document.documentAttribute3); } @Override public int hashCode() { return Objects.hash(documentAttribute1, documentAttribute2, documentAttribute3); } } private static final StaticTableSchema<Document> DOCUMENT_SCHEMA = StaticTableSchema.builder(Document.class) .newItemSupplier(Document::new) .addAttribute(String.class, a -> a.name("documentAttribute1") .getter(Document::getDocumentAttribute1) .setter(Document::setDocumentAttribute1) .addTag(primarySortKey())) .addAttribute(String.class, a -> a.name("documentAttribute2") .getter(Document::getDocumentAttribute2) .setter(Document::setDocumentAttribute2)) .addAttribute(String.class, a -> a.name("documentAttribute3") .getter(Document::getDocumentAttribute3) .setter(Document::setDocumentAttribute3)) .build(); private static final TableSchema<Record> TABLE_SCHEMA = StaticTableSchema.builder(Record.class) .newItemSupplier(Record::new) .addAttribute(String.class, a -> a.name("id") .getter(Record::getId) .setter(Record::setId) .tags(primaryPartitionKey())) .flatten(DOCUMENT_SCHEMA, Record::getDocument, Record::setDocument) .build(); private DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() .dynamoDbClient(getDynamoDbClient()) .build(); private DynamoDbTable<Record> mappedTable = enhancedClient.table(getConcreteTableName("table-name"), TABLE_SCHEMA); @Before public void createTable() { mappedTable.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput())); } @After public void deleteTable() { getDynamoDbClient().deleteTable(DeleteTableRequest.builder() .tableName(getConcreteTableName("table-name")) .build()); } @Test public void update_allValues() { Document document = new Document() .setDocumentAttribute1("one") .setDocumentAttribute2("two") .setDocumentAttribute3("three"); Record record = new Record() .setId("id-value") .setDocument(document); Record updatedRecord = mappedTable.updateItem(r -> r.item(record)); Record fetchedRecord = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id-value").sortValue("one"))); assertThat(updatedRecord, is(record)); assertThat(fetchedRecord, is(record)); } @Test public void update_someValues() { Document document = new Document() .setDocumentAttribute1("one") .setDocumentAttribute2("two"); Record record = new Record() .setId("id-value") .setDocument(document); Record updatedRecord = mappedTable.updateItem(r -> r.item(record)); Record fetchedRecord = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id-value").sortValue("one"))); assertThat(updatedRecord, is(record)); assertThat(fetchedRecord, is(record)); } }
4,156
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/AsyncTransactGetItemsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.junit.After; import org.junit.Before; import org.junit.Test; import software.amazon.awssdk.enhanced.dynamodb.Document; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbAsyncTable; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedAsyncClient; import software.amazon.awssdk.enhanced.dynamodb.Key; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.internal.client.DefaultDynamoDbEnhancedAsyncClient; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema; import software.amazon.awssdk.enhanced.dynamodb.model.TransactGetItemsEnhancedRequest; import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; public class AsyncTransactGetItemsTest extends LocalDynamoDbAsyncTestBase { private static class Record1 { private Integer id; private Integer getId() { return id; } private Record1 setId(Integer id) { this.id = id; return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Record1 record1 = (Record1) o; return Objects.equals(id, record1.id); } @Override public int hashCode() { return Objects.hash(id); } } private static class Record2 { private Integer id; private Integer getId() { return id; } private Record2 setId(Integer id) { this.id = id; return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Record2 record2 = (Record2) o; return Objects.equals(id, record2.id); } @Override public int hashCode() { return Objects.hash(id); } } private static final TableSchema<Record1> TABLE_SCHEMA_1 = StaticTableSchema.builder(Record1.class) .newItemSupplier(Record1::new) .addAttribute(Integer.class, a -> a.name("id_1") .getter(Record1::getId) .setter(Record1::setId) .tags(primaryPartitionKey())) .build(); private static final TableSchema<Record2> TABLE_SCHEMA_2 = StaticTableSchema.builder(Record2.class) .newItemSupplier(Record2::new) .addAttribute(Integer.class, a -> a.name("id_2") .getter(Record2::getId) .setter(Record2::setId) .tags(primaryPartitionKey())) .build(); private DynamoDbEnhancedAsyncClient enhancedAsyncClient = DefaultDynamoDbEnhancedAsyncClient.builder() .dynamoDbClient(getDynamoDbAsyncClient()) .build(); private DynamoDbAsyncTable<Record1> mappedTable1 = enhancedAsyncClient.table(getConcreteTableName("table-name-1"), TABLE_SCHEMA_1); private DynamoDbAsyncTable<Record2> mappedTable2 = enhancedAsyncClient.table(getConcreteTableName("table-name-2"), TABLE_SCHEMA_2); private static final List<Record1> RECORDS_1 = IntStream.range(0, 2) .mapToObj(i -> new Record1().setId(i)) .collect(Collectors.toList()); private static final List<Record2> RECORDS_2 = IntStream.range(0, 2) .mapToObj(i -> new Record2().setId(i)) .collect(Collectors.toList()); @Before public void createTable() { mappedTable1.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput())).join(); mappedTable2.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput())).join(); } @After public void deleteTable() { getDynamoDbAsyncClient().deleteTable(DeleteTableRequest.builder() .tableName(getConcreteTableName("table-name-1")) .build()).join(); getDynamoDbAsyncClient().deleteTable(DeleteTableRequest.builder() .tableName(getConcreteTableName("table-name-2")) .build()).join(); } private void insertRecords() { RECORDS_1.forEach(record -> mappedTable1.putItem(r -> r.item(record)).join()); RECORDS_2.forEach(record -> mappedTable2.putItem(r -> r.item(record)).join()); } @Test public void getRecordsFromMultipleTables() { insertRecords(); TransactGetItemsEnhancedRequest transactGetItemsEnhancedRequest = TransactGetItemsEnhancedRequest.builder() .addGetItem(mappedTable1, Key.builder().partitionValue(0).build()) .addGetItem(mappedTable2, Key.builder().partitionValue(0).build()) .addGetItem(mappedTable2, Key.builder().partitionValue(1).build()) .addGetItem(mappedTable1, Key.builder().partitionValue(1).build()) .build(); List<Document> results = enhancedAsyncClient.transactGetItems(transactGetItemsEnhancedRequest).join(); assertThat(results.size(), is(4)); assertThat(results.get(0).getItem(mappedTable1), is(RECORDS_1.get(0))); assertThat(results.get(1).getItem(mappedTable2), is(RECORDS_2.get(0))); assertThat(results.get(2).getItem(mappedTable2), is(RECORDS_2.get(1))); assertThat(results.get(3).getItem(mappedTable1), is(RECORDS_1.get(1))); } @Test public void notFoundRecordReturnsNull() { insertRecords(); TransactGetItemsEnhancedRequest transactGetItemsEnhancedRequest = TransactGetItemsEnhancedRequest.builder() .addGetItem(mappedTable1, Key.builder().partitionValue(0).build()) .addGetItem(mappedTable2, Key.builder().partitionValue(0).build()) .addGetItem(mappedTable2, Key.builder().partitionValue(5).build()) .addGetItem(mappedTable1, Key.builder().partitionValue(1).build()) .build(); List<Document> results = enhancedAsyncClient.transactGetItems(transactGetItemsEnhancedRequest).join(); assertThat(results.size(), is(4)); assertThat(results.get(0).getItem(mappedTable1), is(RECORDS_1.get(0))); assertThat(results.get(1).getItem(mappedTable2), is(RECORDS_2.get(0))); assertThat(results.get(2).getItem(mappedTable2), is(nullValue())); assertThat(results.get(3).getItem(mappedTable1), is(RECORDS_1.get(1))); } }
4,157
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/GetItemWithResponseTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests; import static org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey; import java.util.Arrays; import java.util.Objects; import org.assertj.core.data.Offset; import org.junit.After; import org.junit.Before; import org.junit.Test; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema; import software.amazon.awssdk.enhanced.dynamodb.model.GetItemEnhancedResponse; import software.amazon.awssdk.services.dynamodb.model.ConsumedCapacity; import software.amazon.awssdk.services.dynamodb.model.ReturnConsumedCapacity; public class GetItemWithResponseTest extends LocalDynamoDbSyncTestBase { private static final String TEST_TABLE_NAME = "get-item-table-name-2"; private static final TableSchema<Record> TABLE_SCHEMA = StaticTableSchema.builder(Record.class) .newItemSupplier(Record::new) .addAttribute(Integer.class, a -> a.name("id_1") .getter(Record::getId) .setter(Record::setId) .tags(primaryPartitionKey())) .addAttribute(String.class, a -> a.name("stringAttr1") .getter(Record::getStringAttr1) .setter(Record::setStringAttr1)) .build(); private final DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() .dynamoDbClient(getDynamoDbClient()) .build(); private final DynamoDbTable<Record> mappedTable1 = enhancedClient.table( getConcreteTableName(TEST_TABLE_NAME), TABLE_SCHEMA ); @Before public void createTable() { mappedTable1.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput())); } @After public void deleteTable() { getDynamoDbClient().deleteTable(r -> r.tableName(getConcreteTableName(TEST_TABLE_NAME))); } @Test public void getItemWithResponse_when_recordIsAbsent() { GetItemEnhancedResponse<Record> response = mappedTable1.getItemWithResponse( r -> r.key(k -> k.partitionValue(404)) ); assertThat(response.attributes()).isNull(); assertThat(response.consumedCapacity()).isNull(); } @Test public void getItemWithResponse_when_recordIsPresent() { Record original = new Record().setId(1).setStringAttr1("a"); mappedTable1.putItem(original); GetItemEnhancedResponse<Record> response = mappedTable1.getItemWithResponse( r -> r.key(k -> k.partitionValue(original.getId())) ); assertThat(response.attributes()).isNotNull(); assertThat(response.attributes()).isEqualTo(original); assertThat(response.consumedCapacity()).isNull(); } @Test public void getItemWithResponse_withReturnConsumedCapacity_when_recordIsAbsent_eventuallyConsistent() { GetItemEnhancedResponse<Record> response = mappedTable1.getItemWithResponse( r -> r.key(k -> k.partitionValue(404)) .returnConsumedCapacity(ReturnConsumedCapacity.TOTAL) .consistentRead(false) ); assertThat(response.attributes()).isNull(); ConsumedCapacity consumedCapacity = response.consumedCapacity(); assertThat(consumedCapacity).isNotNull(); assertThat(consumedCapacity.capacityUnits()).isCloseTo(0.5, Offset.offset(0.01)); } @Test public void getItemWithResponse_withReturnConsumedCapacity_when_recordIsAbsent_stronglyConsistent() { GetItemEnhancedResponse<Record> response = mappedTable1.getItemWithResponse( r -> r.key(k -> k.partitionValue(404)) .returnConsumedCapacity(ReturnConsumedCapacity.TOTAL) .consistentRead(true) ); assertThat(response.attributes()).isNull(); ConsumedCapacity consumedCapacity = response.consumedCapacity(); assertThat(consumedCapacity).isNotNull(); assertThat(consumedCapacity.capacityUnits()).isCloseTo(1.0, Offset.offset(0.01)); } @Test public void getItemWithResponse_withReturnConsumedCapacity_when_recordIsPresent_eventuallyConsistent() { Record original = new Record().setId(126).setStringAttr1(getStringAttrValue(100_000)); mappedTable1.putItem(original); GetItemEnhancedResponse<Record> response = mappedTable1.getItemWithResponse( r -> r.key(k -> k.partitionValue(126)) .returnConsumedCapacity(ReturnConsumedCapacity.TOTAL) .consistentRead(false) ); assertThat(response.attributes()).isEqualTo(original); ConsumedCapacity consumedCapacity = response.consumedCapacity(); assertThat(consumedCapacity).isNotNull(); assertThat(consumedCapacity.capacityUnits()).isCloseTo(12.5, Offset.offset(0.01)); } @Test public void getItemWithResponse_withReturnConsumedCapacity_when_recordIsPresent_stronglyConsistent() { Record original = new Record().setId(142).setStringAttr1(getStringAttrValue(100_000)); mappedTable1.putItem(original); GetItemEnhancedResponse<Record> response = mappedTable1.getItemWithResponse( r -> r.key(k -> k.partitionValue(142)) .returnConsumedCapacity(ReturnConsumedCapacity.TOTAL) .consistentRead(true) ); assertThat(response.attributes()).isEqualTo(original); ConsumedCapacity consumedCapacity = response.consumedCapacity(); assertThat(consumedCapacity).isNotNull(); assertThat(consumedCapacity.capacityUnits()).isCloseTo(25.0, Offset.offset(0.01)); } private static String getStringAttrValue(int numChars) { char[] chars = new char[numChars]; Arrays.fill(chars, 'a'); return new String(chars); } private static class Record { private Integer id; private String stringAttr1; private Integer getId() { return id; } private Record setId(Integer id) { this.id = id; return this; } private String getStringAttr1() { return stringAttr1; } private Record setStringAttr1(String stringAttr1) { this.stringAttr1 = stringAttr1; return this; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Record record = (Record) o; return Objects.equals(id, record.id) && Objects.equals(stringAttr1, record.stringAttr1); } @Override public int hashCode() { return Objects.hash(id, stringAttr1); } } }
4,158
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/LocalDynamoDbTestBase.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests; import java.util.UUID; import org.junit.AfterClass; import org.junit.BeforeClass; import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughput; public class LocalDynamoDbTestBase { private static final LocalDynamoDb localDynamoDb = new LocalDynamoDb(); private static final ProvisionedThroughput DEFAULT_PROVISIONED_THROUGHPUT = ProvisionedThroughput.builder() .readCapacityUnits(50L) .writeCapacityUnits(50L) .build(); private String uniqueTableSuffix = UUID.randomUUID().toString(); @BeforeClass public static void initializeLocalDynamoDb() { localDynamoDb.start(); } @AfterClass public static void stopLocalDynamoDb() { localDynamoDb.stop(); } protected static LocalDynamoDb localDynamoDb() { return localDynamoDb; } protected String getConcreteTableName(String logicalTableName) { return logicalTableName + "_" + uniqueTableSuffix; } protected ProvisionedThroughput getDefaultProvisionedThroughput() { return DEFAULT_PROVISIONED_THROUGHPUT; } }
4,159
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/TransactWriteItemsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests; import static java.util.Collections.singletonMap; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.fail; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.stringValue; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.junit.After; import org.junit.Before; import org.junit.Test; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.Expression; import software.amazon.awssdk.enhanced.dynamodb.Key; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema; import software.amazon.awssdk.enhanced.dynamodb.model.ConditionCheck; import software.amazon.awssdk.enhanced.dynamodb.model.TransactDeleteItemEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.TransactPutItemEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.TransactUpdateItemEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.TransactWriteItemsEnhancedRequest; import software.amazon.awssdk.services.dynamodb.model.CancellationReason; import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; import software.amazon.awssdk.services.dynamodb.model.ReturnValuesOnConditionCheckFailure; import software.amazon.awssdk.services.dynamodb.model.TransactionCanceledException; public class TransactWriteItemsTest extends LocalDynamoDbSyncTestBase { private static class Record1 { private Integer id; private String attribute; private Integer getId() { return id; } private Record1 setId(Integer id) { this.id = id; return this; } private String getAttribute() { return attribute; } private Record1 setAttribute(String attribute) { this.attribute = attribute; return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Record1 record1 = (Record1) o; return Objects.equals(id, record1.id) && Objects.equals(attribute, record1.attribute); } @Override public int hashCode() { return Objects.hash(id, attribute); } } private static class Record2 { private Integer id; private String attribute; private Integer getId() { return id; } private Record2 setId(Integer id) { this.id = id; return this; } private String getAttribute() { return attribute; } private Record2 setAttribute(String attribute) { this.attribute = attribute; return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Record2 record2 = (Record2) o; return Objects.equals(id, record2.id) && Objects.equals(attribute, record2.attribute); } @Override public int hashCode() { return Objects.hash(id, attribute); } } private static final TableSchema<Record1> TABLE_SCHEMA_1 = StaticTableSchema.builder(Record1.class) .newItemSupplier(Record1::new) .addAttribute(Integer.class, a -> a.name("id_1") .getter(Record1::getId) .setter(Record1::setId) .tags(primaryPartitionKey())) .addAttribute(String.class, a -> a.name("attribute") .getter(Record1::getAttribute) .setter(Record1::setAttribute)) .build(); private static final TableSchema<Record2> TABLE_SCHEMA_2 = StaticTableSchema.builder(Record2.class) .newItemSupplier(Record2::new) .addAttribute(Integer.class, a -> a.name("id_2") .getter(Record2::getId) .setter(Record2::setId) .tags(primaryPartitionKey())) .addAttribute(String.class, a -> a.name("attribute") .getter(Record2::getAttribute) .setter(Record2::setAttribute)) .build(); private DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() .dynamoDbClient(getDynamoDbClient()) .build(); private DynamoDbTable<Record1> mappedTable1 = enhancedClient.table(getConcreteTableName("table-name-1"), TABLE_SCHEMA_1); private DynamoDbTable<Record2> mappedTable2 = enhancedClient.table(getConcreteTableName("table-name-2"), TABLE_SCHEMA_2); private static final List<Record1> RECORDS_1 = IntStream.range(0, 2) .mapToObj(i -> new Record1().setId(i).setAttribute(Integer.toString(i))) .collect(Collectors.toList()); private static final List<Record2> RECORDS_2 = IntStream.range(0, 2) .mapToObj(i -> new Record2().setId(i).setAttribute(Integer.toString(i))) .collect(Collectors.toList()); @Before public void createTable() { mappedTable1.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput())); mappedTable2.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput())); } @After public void deleteTable() { getDynamoDbClient().deleteTable(DeleteTableRequest.builder() .tableName(getConcreteTableName("table-name-1")) .build()); getDynamoDbClient().deleteTable(DeleteTableRequest.builder() .tableName(getConcreteTableName("table-name-2")) .build()); } @Test public void singlePut() { enhancedClient.transactWriteItems( TransactWriteItemsEnhancedRequest.builder() .addPutItem(mappedTable1, RECORDS_1.get(0)) .build()); Record1 record = mappedTable1.getItem(r -> r.key(k -> k.partitionValue(0))); assertThat(record, is(RECORDS_1.get(0))); } @Test public void multiplePut() { enhancedClient.transactWriteItems( TransactWriteItemsEnhancedRequest.builder() .addPutItem(mappedTable1, RECORDS_1.get(0)) .addPutItem(mappedTable2, RECORDS_2.get(0)) .build()); Record1 record1 = mappedTable1.getItem(r -> r.key(k -> k.partitionValue(0))); Record2 record2 = mappedTable2.getItem(r -> r.key(k -> k.partitionValue(0))); assertThat(record1, is(RECORDS_1.get(0))); assertThat(record2, is(RECORDS_2.get(0))); } @Test public void singleUpdate() { enhancedClient.transactWriteItems( TransactWriteItemsEnhancedRequest.builder() .addUpdateItem(mappedTable1, RECORDS_1.get(0)) .build()); Record1 record = mappedTable1.getItem(r -> r.key(k -> k.partitionValue(0))); assertThat(record, is(RECORDS_1.get(0))); } @Test public void multipleUpdate() { enhancedClient.transactWriteItems( TransactWriteItemsEnhancedRequest.builder() .addUpdateItem(mappedTable1, RECORDS_1.get(0)) .addUpdateItem(mappedTable2, RECORDS_2.get(0)) .build()); Record1 record1 = mappedTable1.getItem(r -> r.key(k -> k.partitionValue(0))); Record2 record2 = mappedTable2.getItem(r -> r.key(k -> k.partitionValue(0))); assertThat(record1, is(RECORDS_1.get(0))); assertThat(record2, is(RECORDS_2.get(0))); } @Test public void singleDelete() { mappedTable1.putItem(r -> r.item(RECORDS_1.get(0))); enhancedClient.transactWriteItems( TransactWriteItemsEnhancedRequest.builder() .addDeleteItem(mappedTable1, RECORDS_1.get(0)) .build()); Record1 record = mappedTable1.getItem(r -> r.key(k -> k.partitionValue(0))); assertThat(record, is(nullValue())); } @Test public void multipleDelete() { mappedTable1.putItem(r -> r.item(RECORDS_1.get(0))); mappedTable2.putItem(r -> r.item(RECORDS_2.get(0))); enhancedClient.transactWriteItems( TransactWriteItemsEnhancedRequest.builder() .addDeleteItem(mappedTable1, RECORDS_1.get(0)) .addDeleteItem(mappedTable2, RECORDS_2.get(0)) .build()); Record1 record1 = mappedTable1.getItem(r -> r.key(k -> k.partitionValue(0))); Record2 record2 = mappedTable2.getItem(r -> r.key(k -> k.partitionValue(0))); assertThat(record1, is(nullValue())); assertThat(record2, is(nullValue())); } @Test public void singleConditionCheck() { mappedTable1.putItem(r -> r.item(RECORDS_1.get(0))); Expression conditionExpression = Expression.builder() .expression("#attribute = :attribute") .expressionValues(singletonMap(":attribute", stringValue("0"))) .expressionNames(singletonMap("#attribute", "attribute")) .build(); Key key = Key.builder().partitionValue(0).build(); enhancedClient.transactWriteItems( TransactWriteItemsEnhancedRequest.builder() .addConditionCheck(mappedTable1, ConditionCheck.builder() .key(key) .conditionExpression(conditionExpression) .build()) .build()); } @Test public void multiConditionCheck() { mappedTable1.putItem(r -> r.item(RECORDS_1.get(0))); mappedTable2.putItem(r -> r.item(RECORDS_2.get(0))); Expression conditionExpression = Expression.builder() .expression("#attribute = :attribute") .expressionValues(singletonMap(":attribute", stringValue("0"))) .expressionNames(singletonMap("#attribute", "attribute")) .build(); Key key1 = Key.builder().partitionValue(0).build(); Key key2 = Key.builder().partitionValue(0).build(); enhancedClient.transactWriteItems( TransactWriteItemsEnhancedRequest.builder() .addConditionCheck(mappedTable1, ConditionCheck.builder() .key(key1) .conditionExpression(conditionExpression) .build()) .addConditionCheck(mappedTable2, ConditionCheck.builder() .key(key2) .conditionExpression(conditionExpression) .build()) .build()); } @Test public void mixedCommands() { mappedTable1.putItem(r -> r.item(RECORDS_1.get(0))); mappedTable2.putItem(r -> r.item(RECORDS_2.get(0))); Expression conditionExpression = Expression.builder() .expression("#attribute = :attribute") .expressionValues(singletonMap(":attribute", stringValue("0"))) .expressionNames(singletonMap("#attribute", "attribute")) .build(); Key key = Key.builder().partitionValue(0).build(); TransactWriteItemsEnhancedRequest transactWriteItemsEnhancedRequest = TransactWriteItemsEnhancedRequest.builder() .addConditionCheck(mappedTable1, ConditionCheck.builder() .key(key) .conditionExpression(conditionExpression) .build()) .addPutItem(mappedTable2, RECORDS_2.get(1)) .addUpdateItem(mappedTable1,RECORDS_1.get(1)) .addDeleteItem(mappedTable2, RECORDS_2.get(0)) .build(); enhancedClient.transactWriteItems(transactWriteItemsEnhancedRequest); assertThat(mappedTable1.getItem(r -> r.key(k -> k.partitionValue(1))), is(RECORDS_1.get(1))); assertThat(mappedTable2.getItem(r -> r.key(k -> k.partitionValue(0))), is(nullValue())); assertThat(mappedTable2.getItem(r -> r.key(k -> k.partitionValue(1))), is(RECORDS_2.get(1))); } @Test public void mixedCommands_conditionCheckFailsTransaction() { mappedTable1.putItem(r -> r.item(RECORDS_1.get(0))); mappedTable2.putItem(r -> r.item(RECORDS_2.get(0))); Expression conditionExpression = Expression.builder() .expression("#attribute = :attribute") .expressionValues(singletonMap(":attribute", stringValue("1"))) .expressionNames(singletonMap("#attribute", "attribute")) .build(); Key key = Key.builder().partitionValue(0).build(); TransactWriteItemsEnhancedRequest transactWriteItemsEnhancedRequest = TransactWriteItemsEnhancedRequest.builder() .addPutItem(mappedTable2, RECORDS_2.get(1)) .addUpdateItem(mappedTable1, RECORDS_1.get(1)) .addConditionCheck(mappedTable1, ConditionCheck.builder() .key(key) .conditionExpression(conditionExpression) .build()) .addDeleteItem(mappedTable2, RECORDS_2.get(0)) .build(); try { enhancedClient.transactWriteItems(transactWriteItemsEnhancedRequest); fail("Expected TransactionCanceledException to be thrown"); } catch(TransactionCanceledException ignored) { } assertThat(mappedTable1.getItem(r -> r.key(k -> k.partitionValue(1))), is(nullValue())); assertThat(mappedTable2.getItem(r -> r.key(k -> k.partitionValue(0))), is(RECORDS_2.get(0))); assertThat(mappedTable2.getItem(r -> r.key(k -> k.partitionValue(1))), is(nullValue())); } @Test public void mixedCommands_returnValuesOnConditionCheckFailureSet_allConditionsFail() { mappedTable1.putItem(r -> r.item(RECORDS_1.get(0))); mappedTable1.putItem(r -> r.item(RECORDS_1.get(1))); mappedTable2.putItem(r -> r.item(RECORDS_2.get(0))); Expression conditionExpression = Expression.builder() .expression("#attribute = :attribute") .expressionValues(singletonMap(":attribute", stringValue("99"))) .expressionNames(singletonMap("#attribute", "attribute")) .build(); Key key0 = Key.builder().partitionValue(0).build(); Key key1 = Key.builder().partitionValue(1).build(); ReturnValuesOnConditionCheckFailure returnValues = ReturnValuesOnConditionCheckFailure.ALL_OLD; TransactPutItemEnhancedRequest<Record2> putItemRequest = TransactPutItemEnhancedRequest.builder(Record2.class) .conditionExpression(conditionExpression) .item(RECORDS_2.get(0)) .returnValuesOnConditionCheckFailure(returnValues) .build(); TransactUpdateItemEnhancedRequest<Record1> updateItemRequest = TransactUpdateItemEnhancedRequest.builder(Record1.class) .conditionExpression(conditionExpression) .item(RECORDS_1.get(0)) .returnValuesOnConditionCheckFailure(returnValues) .build(); TransactDeleteItemEnhancedRequest deleteItemRequest = TransactDeleteItemEnhancedRequest.builder() .key(key1) .conditionExpression(conditionExpression) .returnValuesOnConditionCheckFailure(returnValues) .build(); TransactWriteItemsEnhancedRequest transactWriteItemsEnhancedRequest = TransactWriteItemsEnhancedRequest.builder() .addPutItem(mappedTable2, putItemRequest) .addUpdateItem(mappedTable1, updateItemRequest) .addConditionCheck(mappedTable1, ConditionCheck.builder() .key(key0) .conditionExpression(conditionExpression) .returnValuesOnConditionCheckFailure(returnValues) .build()) .addDeleteItem(mappedTable1, deleteItemRequest) .build(); try { enhancedClient.transactWriteItems(transactWriteItemsEnhancedRequest); fail("Expected TransactionCanceledException to be thrown"); } catch(TransactionCanceledException e) { List<CancellationReason> cancellationReasons = e.cancellationReasons(); assertThat(cancellationReasons.size(), is(4)); cancellationReasons.forEach(r -> assertThat(r.item().isEmpty(), is(false))); } } }
4,160
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/AsyncGetItemWithResponseTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests; import static org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey; import java.util.Arrays; import java.util.Objects; import org.assertj.core.data.Offset; import org.junit.After; import org.junit.Before; import org.junit.Test; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbAsyncTable; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedAsyncClient; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema; import software.amazon.awssdk.enhanced.dynamodb.model.GetItemEnhancedResponse; import software.amazon.awssdk.services.dynamodb.model.ConsumedCapacity; import software.amazon.awssdk.services.dynamodb.model.ReturnConsumedCapacity; public class AsyncGetItemWithResponseTest extends LocalDynamoDbAsyncTestBase { private static final String TEST_TABLE_NAME = "get-item-table-name-2"; private static final TableSchema<Record> TABLE_SCHEMA = StaticTableSchema.builder(Record.class) .newItemSupplier(Record::new) .addAttribute(Integer.class, a -> a.name("id_1") .getter(Record::getId) .setter(Record::setId) .tags(primaryPartitionKey())) .addAttribute(String.class, a -> a.name("stringAttr1") .getter(Record::getStringAttr1) .setter(Record::setStringAttr1)) .build(); private final DynamoDbEnhancedAsyncClient enhancedClient = DynamoDbEnhancedAsyncClient.builder() .dynamoDbClient(getDynamoDbAsyncClient()) .build(); private final DynamoDbAsyncTable<Record> mappedTable1 = enhancedClient.table( getConcreteTableName(TEST_TABLE_NAME), TABLE_SCHEMA ); @Before public void createTable() { mappedTable1.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput())).join(); } @After public void deleteTable() { getDynamoDbAsyncClient().deleteTable(r -> r.tableName(getConcreteTableName(TEST_TABLE_NAME))).join(); } @Test public void getItemWithResponse_when_recordIsAbsent() { GetItemEnhancedResponse<Record> response = mappedTable1.getItemWithResponse( r -> r.key(k -> k.partitionValue(404)) ).join(); assertThat(response.attributes()).isNull(); assertThat(response.consumedCapacity()).isNull(); } @Test public void getItemWithResponse_when_recordIsPresent() { Record original = new Record().setId(1).setStringAttr1("a"); mappedTable1.putItem(original).join(); GetItemEnhancedResponse<Record> response = mappedTable1.getItemWithResponse( r -> r.key(k -> k.partitionValue(original.getId())) ).join(); assertThat(response.attributes()).isEqualTo(original); assertThat(response.consumedCapacity()).isNull(); } @Test public void getItemWithResponse_withReturnConsumedCapacity_when_recordIsAbsent_eventuallyConsistent() { GetItemEnhancedResponse<Record> response = mappedTable1.getItemWithResponse( r -> r.key(k -> k.partitionValue(404)) .returnConsumedCapacity(ReturnConsumedCapacity.TOTAL) .consistentRead(false) ).join(); assertThat(response.attributes()).isNull(); ConsumedCapacity consumedCapacity = response.consumedCapacity(); assertThat(consumedCapacity).isNotNull(); assertThat(consumedCapacity.capacityUnits()).isCloseTo(0.5, Offset.offset(0.01)); } @Test public void getItemWithResponse_withReturnConsumedCapacity_when_recordIsAbsent_stronglyConsistent() { GetItemEnhancedResponse<Record> response = mappedTable1.getItemWithResponse( r -> r.key(k -> k.partitionValue(404)) .returnConsumedCapacity(ReturnConsumedCapacity.TOTAL) .consistentRead(true) ).join(); assertThat(response.attributes()).isNull(); ConsumedCapacity consumedCapacity = response.consumedCapacity(); assertThat(consumedCapacity).isNotNull(); assertThat(consumedCapacity.capacityUnits()).isCloseTo(1.0, Offset.offset(0.01)); } @Test public void getItemWithResponse_withReturnConsumedCapacity_when_recordIsPresent_eventuallyConsistent() { Record original = new Record().setId(126).setStringAttr1(getStringAttrValue(100_000)); mappedTable1.putItem(original).join(); GetItemEnhancedResponse<Record> response = mappedTable1.getItemWithResponse( r -> r.key(k -> k.partitionValue(126)) .returnConsumedCapacity(ReturnConsumedCapacity.TOTAL) .consistentRead(false) ).join(); assertThat(response.attributes()).isEqualTo(original); ConsumedCapacity consumedCapacity = response.consumedCapacity(); assertThat(consumedCapacity).isNotNull(); assertThat(consumedCapacity.capacityUnits()).isCloseTo(12.5, Offset.offset(0.01)); } @Test public void getItemWithResponse_withReturnConsumedCapacity_when_recordIsPresent_stronglyConsistent() { Record original = new Record().setId(142).setStringAttr1(getStringAttrValue(100_000)); mappedTable1.putItem(original).join(); GetItemEnhancedResponse<Record> response = mappedTable1.getItemWithResponse( r -> r.key(k -> k.partitionValue(142)) .returnConsumedCapacity(ReturnConsumedCapacity.TOTAL) .consistentRead(true) ).join(); assertThat(response.attributes()).isEqualTo(original); ConsumedCapacity consumedCapacity = response.consumedCapacity(); assertThat(consumedCapacity).isNotNull(); assertThat(consumedCapacity.capacityUnits()).isCloseTo(25.0, Offset.offset(0.01)); } private static String getStringAttrValue(int numChars) { char[] chars = new char[numChars]; Arrays.fill(chars, 'a'); return new String(chars); } private static class Record { private Integer id; private String stringAttr1; private Integer getId() { return id; } private Record setId(Integer id) { this.id = id; return this; } private String getStringAttr1() { return stringAttr1; } private Record setStringAttr1(String stringAttr1) { this.stringAttr1 = stringAttr1; return this; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Record record = (Record) o; return Objects.equals(id, record.id) && Objects.equals(stringAttr1, record.stringAttr1); } @Override public int hashCode() { return Objects.hash(id, stringAttr1); } } }
4,161
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/UpdateBehaviorTest.java
package software.amazon.awssdk.enhanced.dynamodb.functionaltests; import static org.assertj.core.api.Assertions.assertThat; import java.time.Instant; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.After; import org.junit.Before; import org.junit.Test; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.extensions.AutoGeneratedTimestampRecordExtension; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.NestedRecordWithUpdateBehavior; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.RecordWithUpdateBehaviors; import software.amazon.awssdk.enhanced.dynamodb.internal.client.ExtensionResolver; public class UpdateBehaviorTest extends LocalDynamoDbSyncTestBase { private static final Instant INSTANT_1 = Instant.parse("2020-05-03T10:00:00Z"); private static final Instant INSTANT_2 = Instant.parse("2020-05-03T10:05:00Z"); private static final Instant FAR_FUTURE_INSTANT = Instant.parse("9999-05-03T10:05:00Z"); private static final TableSchema<RecordWithUpdateBehaviors> TABLE_SCHEMA = TableSchema.fromClass(RecordWithUpdateBehaviors.class); private final DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() .dynamoDbClient(getDynamoDbClient()).extensions( Stream.concat(ExtensionResolver.defaultExtensions().stream(), Stream.of(AutoGeneratedTimestampRecordExtension.create())).collect(Collectors.toList())) .build(); private final DynamoDbTable<RecordWithUpdateBehaviors> mappedTable = enhancedClient.table(getConcreteTableName("table-name"), TABLE_SCHEMA); @Before public void createTable() { mappedTable.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput())); } @After public void deleteTable() { getDynamoDbClient().deleteTable(r -> r.tableName(getConcreteTableName("table-name"))); } @Test public void updateBehaviors_firstUpdate() { Instant currentTime = Instant.now(); RecordWithUpdateBehaviors record = new RecordWithUpdateBehaviors(); record.setId("id123"); record.setCreatedOn(INSTANT_1); record.setLastUpdatedOn(INSTANT_2); mappedTable.updateItem(record); RecordWithUpdateBehaviors persistedRecord = mappedTable.getItem(record); assertThat(persistedRecord.getVersion()).isEqualTo(1L); assertThat(persistedRecord.getCreatedOn()).isEqualTo(INSTANT_1); assertThat(persistedRecord.getLastUpdatedOn()).isEqualTo(INSTANT_2); assertThat(persistedRecord.getLastAutoUpdatedOn()).isAfterOrEqualTo(currentTime); assertThat(persistedRecord.getFormattedLastAutoUpdatedOn().getEpochSecond()) .isGreaterThanOrEqualTo(currentTime.getEpochSecond()); assertThat(persistedRecord.getLastAutoUpdatedOnMillis().getEpochSecond()).isGreaterThanOrEqualTo(currentTime.getEpochSecond()); assertThat(persistedRecord.getCreatedAutoUpdateOn()).isAfterOrEqualTo(currentTime); } @Test public void updateBehaviors_secondUpdate() { Instant beforeUpdateInstant = Instant.now(); RecordWithUpdateBehaviors record = new RecordWithUpdateBehaviors(); record.setId("id123"); record.setCreatedOn(INSTANT_1); record.setLastUpdatedOn(INSTANT_2); mappedTable.updateItem(record); RecordWithUpdateBehaviors persistedRecord = mappedTable.getItem(record); assertThat(persistedRecord.getVersion()).isEqualTo(1L); Instant firstUpdatedTime = persistedRecord.getLastAutoUpdatedOn(); Instant createdAutoUpdateOn = persistedRecord.getCreatedAutoUpdateOn(); assertThat(firstUpdatedTime).isAfterOrEqualTo(beforeUpdateInstant); assertThat(persistedRecord.getFormattedLastAutoUpdatedOn().getEpochSecond()) .isGreaterThanOrEqualTo(beforeUpdateInstant.getEpochSecond()); record.setVersion(1L); record.setCreatedOn(INSTANT_2); record.setLastUpdatedOn(INSTANT_2); mappedTable.updateItem(record); persistedRecord = mappedTable.getItem(record); assertThat(persistedRecord.getVersion()).isEqualTo(2L); assertThat(persistedRecord.getCreatedOn()).isEqualTo(INSTANT_1); assertThat(persistedRecord.getLastUpdatedOn()).isEqualTo(INSTANT_2); Instant secondUpdatedTime = persistedRecord.getLastAutoUpdatedOn(); assertThat(secondUpdatedTime).isAfterOrEqualTo(firstUpdatedTime); assertThat(persistedRecord.getCreatedAutoUpdateOn()).isEqualTo(createdAutoUpdateOn); } @Test public void updateBehaviors_removal() { RecordWithUpdateBehaviors record = new RecordWithUpdateBehaviors(); record.setId("id123"); record.setCreatedOn(INSTANT_1); record.setLastUpdatedOn(INSTANT_2); record.setLastAutoUpdatedOn(FAR_FUTURE_INSTANT); mappedTable.updateItem(record); RecordWithUpdateBehaviors persistedRecord = mappedTable.getItem(record); Instant createdAutoUpdateOn = persistedRecord.getCreatedAutoUpdateOn(); assertThat(persistedRecord.getLastAutoUpdatedOn()).isBefore(FAR_FUTURE_INSTANT); record.setVersion(1L); record.setCreatedOn(null); record.setLastUpdatedOn(null); record.setLastAutoUpdatedOn(null); mappedTable.updateItem(record); persistedRecord = mappedTable.getItem(record); assertThat(persistedRecord.getCreatedOn()).isNull(); assertThat(persistedRecord.getLastUpdatedOn()).isNull(); assertThat(persistedRecord.getLastAutoUpdatedOn()).isNotNull(); assertThat(persistedRecord.getCreatedAutoUpdateOn()).isEqualTo(createdAutoUpdateOn); } @Test public void updateBehaviors_transactWriteItems_secondUpdate() { RecordWithUpdateBehaviors record = new RecordWithUpdateBehaviors(); record.setId("id123"); record.setCreatedOn(INSTANT_1); record.setLastUpdatedOn(INSTANT_2); record.setLastAutoUpdatedOn(INSTANT_2); RecordWithUpdateBehaviors firstUpdatedRecord = mappedTable.updateItem(record); record.setVersion(1L); record.setCreatedOn(INSTANT_2); record.setLastUpdatedOn(INSTANT_2); record.setLastAutoUpdatedOn(INSTANT_2); enhancedClient.transactWriteItems(r -> r.addUpdateItem(mappedTable, record)); RecordWithUpdateBehaviors persistedRecord = mappedTable.getItem(record); assertThat(persistedRecord.getCreatedOn()).isEqualTo(INSTANT_1); assertThat(persistedRecord.getLastUpdatedOn()).isEqualTo(INSTANT_2); assertThat(persistedRecord.getLastAutoUpdatedOn()).isAfterOrEqualTo(INSTANT_2); assertThat(persistedRecord.getCreatedAutoUpdateOn()).isEqualTo(firstUpdatedRecord.getCreatedAutoUpdateOn()); } /** * Currently, nested records are not updated through extensions. */ @Test public void updateBehaviors_nested() { NestedRecordWithUpdateBehavior nestedRecord = new NestedRecordWithUpdateBehavior(); nestedRecord.setId("id456"); RecordWithUpdateBehaviors record = new RecordWithUpdateBehaviors(); record.setId("id123"); record.setCreatedOn(INSTANT_1); record.setLastUpdatedOn(INSTANT_2); record.setNestedRecord(nestedRecord); mappedTable.updateItem(record); RecordWithUpdateBehaviors persistedRecord = mappedTable.getItem(record); assertThat(persistedRecord.getVersion()).isEqualTo(1L); assertThat(persistedRecord.getNestedRecord()).isNotNull(); assertThat(persistedRecord.getNestedRecord().getNestedVersionedAttribute()).isNull(); assertThat(persistedRecord.getNestedRecord().getNestedCounter()).isNull(); assertThat(persistedRecord.getNestedRecord().getNestedUpdateBehaviorAttribute()).isNull(); assertThat(persistedRecord.getNestedRecord().getNestedTimeAttribute()).isNull(); } }
4,162
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/models/RecordWithUpdateBehaviors.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests.models; import java.time.Instant; import software.amazon.awssdk.enhanced.dynamodb.converters.EpochMillisFormatTestConverter; import software.amazon.awssdk.enhanced.dynamodb.converters.TimeFormatUpdateTestConverter; import software.amazon.awssdk.enhanced.dynamodb.extensions.annotations.DynamoDbAutoGeneratedTimestampAttribute; import software.amazon.awssdk.enhanced.dynamodb.extensions.annotations.DynamoDbVersionAttribute; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbAttribute; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbConvertedBy; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbUpdateBehavior; import static software.amazon.awssdk.enhanced.dynamodb.mapper.UpdateBehavior.WRITE_IF_NOT_EXISTS; @DynamoDbBean public class RecordWithUpdateBehaviors { private String id; private Instant createdOn; private Instant lastUpdatedOn; private Instant createdAutoUpdateOn; private Instant lastAutoUpdatedOn; private Long version; private Instant lastAutoUpdatedOnMillis; private Instant formattedLastAutoUpdatedOn; private NestedRecordWithUpdateBehavior nestedRecord; @DynamoDbPartitionKey public String getId() { return id; } public void setId(String id) { this.id = id; } @DynamoDbUpdateBehavior(WRITE_IF_NOT_EXISTS) @DynamoDbAttribute("created-on") // Forces a test on attribute name cleaning public Instant getCreatedOn() { return createdOn; } public void setCreatedOn(Instant createdOn) { this.createdOn = createdOn; } public Instant getLastUpdatedOn() { return lastUpdatedOn; } public void setLastUpdatedOn(Instant lastUpdatedOn) { this.lastUpdatedOn = lastUpdatedOn; } @DynamoDbUpdateBehavior(WRITE_IF_NOT_EXISTS) @DynamoDbAutoGeneratedTimestampAttribute public Instant getCreatedAutoUpdateOn() { return createdAutoUpdateOn; } public void setCreatedAutoUpdateOn(Instant createdAutoUpdateOn) { this.createdAutoUpdateOn = createdAutoUpdateOn; } @DynamoDbAutoGeneratedTimestampAttribute public Instant getLastAutoUpdatedOn() { return lastAutoUpdatedOn; } public void setLastAutoUpdatedOn(Instant lastAutoUpdatedOn) { this.lastAutoUpdatedOn = lastAutoUpdatedOn; } @DynamoDbVersionAttribute public Long getVersion() { return version; } public void setVersion(Long version) { this.version = version; } @DynamoDbConvertedBy(EpochMillisFormatTestConverter.class) @DynamoDbAutoGeneratedTimestampAttribute public Instant getLastAutoUpdatedOnMillis() { return lastAutoUpdatedOnMillis; } public void setLastAutoUpdatedOnMillis(Instant lastAutoUpdatedOnMillis) { this.lastAutoUpdatedOnMillis = lastAutoUpdatedOnMillis; } @DynamoDbConvertedBy(TimeFormatUpdateTestConverter.class) @DynamoDbAutoGeneratedTimestampAttribute public Instant getFormattedLastAutoUpdatedOn() { return formattedLastAutoUpdatedOn; } public void setFormattedLastAutoUpdatedOn(Instant formattedLastAutoUpdatedOn) { this.formattedLastAutoUpdatedOn = formattedLastAutoUpdatedOn; } public NestedRecordWithUpdateBehavior getNestedRecord() { return nestedRecord; } public void setNestedRecord(NestedRecordWithUpdateBehavior nestedRecord) { this.nestedRecord = nestedRecord; } }
4,163
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/models/FakeItemWithBinaryKey.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests.models; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey; import java.util.Objects; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema; public class FakeItemWithBinaryKey { private static final StaticTableSchema<FakeItemWithBinaryKey> FAKE_ITEM_WITH_BINARY_KEY_SCHEMA = StaticTableSchema.builder(FakeItemWithBinaryKey.class) .newItemSupplier(FakeItemWithBinaryKey::new) .addAttribute(SdkBytes.class, a -> a.name("id") .getter(FakeItemWithBinaryKey::getId) .setter(FakeItemWithBinaryKey::setId) .tags(primaryPartitionKey())) .build(); private SdkBytes id; public static StaticTableSchema<FakeItemWithBinaryKey> getTableSchema() { return FAKE_ITEM_WITH_BINARY_KEY_SCHEMA; } public SdkBytes getId() { return id; } public void setId(SdkBytes id) { this.id = id; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; FakeItemWithBinaryKey that = (FakeItemWithBinaryKey) o; return Objects.equals(id, that.id); } @Override public int hashCode() { return Objects.hash(id); } }
4,164
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/models/FakeItemAbstractSubclass2.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests.models; import java.util.Objects; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema; abstract class FakeItemAbstractSubclass2 { private static final StaticTableSchema<FakeItemAbstractSubclass2> FAKE_ITEM_MAPPER = StaticTableSchema.builder(FakeItemAbstractSubclass2.class) .addAttribute(String.class, a -> a.name("abstract_subclass_2") .getter(FakeItemAbstractSubclass2::getSubclassAttribute2) .setter(FakeItemAbstractSubclass2::setSubclassAttribute2)) .flatten(FakeItemComposedSubclass2.getTableSchema(), FakeItemAbstractSubclass2::getComposedAttribute2, FakeItemAbstractSubclass2::setComposedAttribute2) .build(); private String subclassAttribute2; private FakeItemComposedSubclass2 composedAttribute2; static StaticTableSchema<FakeItemAbstractSubclass2> getSubclass2TableSchema() { return FAKE_ITEM_MAPPER; } FakeItemAbstractSubclass2() { composedAttribute2 = new FakeItemComposedSubclass2(); } public String getSubclassAttribute2() { return subclassAttribute2; } public void setSubclassAttribute2(String subclassAttribute2) { this.subclassAttribute2 = subclassAttribute2; } public FakeItemComposedSubclass2 getComposedAttribute2() { return composedAttribute2; } public void setComposedAttribute2(FakeItemComposedSubclass2 composedAttribute2) { this.composedAttribute2 = composedAttribute2; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; FakeItemAbstractSubclass2 that = (FakeItemAbstractSubclass2) o; return Objects.equals(subclassAttribute2, that.subclassAttribute2) && Objects.equals(composedAttribute2, that.composedAttribute2); } @Override public int hashCode() { return Objects.hash(subclassAttribute2, composedAttribute2); } }
4,165
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/models/InnerAttribConverter.java
package software.amazon.awssdk.enhanced.dynamodb.functionaltests.models; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import software.amazon.awssdk.enhanced.dynamodb.AttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType; import software.amazon.awssdk.enhanced.dynamodb.EnhancedType; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import java.util.HashMap; import java.util.Map; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.stringValue; /** * Event Payload Converter to save the record on the class */ public class InnerAttribConverter<T> implements AttributeConverter<T> { private final ObjectMapper objectMapper; /** * This No Args constuctor is needed by the DynamoDbConvertedBy annotation */ public InnerAttribConverter() { this.objectMapper = new ObjectMapper(); this.objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); final AttributeValue dd = stringValue("dd"); AttributeConverter<String> attributeConverter = null; AttributeValueType attributeValueType = null; EnhancedType enhancedType = null; // add this to preserve the same offset (don't convert to UTC) this.objectMapper.configure(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE, false); } @Override public AttributeValue transformFrom(final T input) { Map<String, AttributeValue> map = null; if (input != null) { map = new HashMap<>(); InnerAttributeRecord innerAttributeRecord = (InnerAttributeRecord) input; if (innerAttributeRecord.getAttribOne() != null) { final AttributeValue attributeValue = stringValue(innerAttributeRecord.getAttribOne()); map.put("attribOne", stringValue(innerAttributeRecord.getAttribOne())); } if (innerAttributeRecord.getAttribTwo() != null) { map.put("attribTwo", stringValue(String.valueOf(innerAttributeRecord.getAttribTwo()))); } } return AttributeValue.builder().m(map).build(); } @Override public T transformTo(final AttributeValue attributeValue) { InnerAttributeRecord innerMetadata = new InnerAttributeRecord(); if (attributeValue.m().get("attribOne") != null) { innerMetadata.setAttribOne(attributeValue.m().get("attribOne").s()); } if (attributeValue.m().get("attribTwo") != null) { innerMetadata.setAttribTwo(Integer.valueOf(attributeValue.m().get("attribTwo").s())); } return (T) innerMetadata; } @Override public EnhancedType<T> type() { return (EnhancedType<T>) EnhancedType.of(InnerAttributeRecord.class); } @Override public AttributeValueType attributeValueType() { return AttributeValueType.S; } }
4,166
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/models/FakeEnumShortened.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests.models; public enum FakeEnumShortened { ONE, }
4,167
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/models/FakeItemWithIndices.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests.models; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primarySortKey; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.secondaryPartitionKey; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.secondarySortKey; import java.util.UUID; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema; public class FakeItemWithIndices { private static final StaticTableSchema<FakeItemWithIndices> FAKE_ITEM_MAPPER = StaticTableSchema.builder(FakeItemWithIndices.class) .newItemSupplier(FakeItemWithIndices::new) .addAttribute(String.class, a -> a.name("id") .getter(FakeItemWithIndices::getId) .setter(FakeItemWithIndices::setId) .tags(primaryPartitionKey())) .addAttribute(String.class, a -> a.name("sort") .getter(FakeItemWithIndices::getSort) .setter(FakeItemWithIndices::setSort) .tags(primarySortKey())) .addAttribute(String.class, a -> a.name("gsi_id") .getter(FakeItemWithIndices::getGsiId) .setter(FakeItemWithIndices::setGsiId) .tags(secondaryPartitionKey("gsi_1"), secondaryPartitionKey("gsi_2"))) .addAttribute(String.class, a -> a.name("gsi_sort") .getter(FakeItemWithIndices::getGsiSort) .setter(FakeItemWithIndices::setGsiSort) .tags(secondarySortKey("gsi_1"))) .addAttribute(String.class, a -> a.name("lsi_sort") .getter(FakeItemWithIndices::getLsiSort) .setter(FakeItemWithIndices::setLsiSort) .tags(secondarySortKey("lsi_1"))) .build(); private String id; private String sort; private String gsiId; private String gsiSort; private String lsiSort; public FakeItemWithIndices() { } public FakeItemWithIndices(String id, String sort, String gsiId, String gsiSort, String lsiSort) { this.id = id; this.sort = sort; this.gsiId = gsiId; this.gsiSort = gsiSort; this.lsiSort = lsiSort; } public static Builder builder() { return new Builder(); } public static StaticTableSchema<FakeItemWithIndices> getTableSchema() { return FAKE_ITEM_MAPPER; } public static FakeItemWithIndices createUniqueFakeItemWithIndices() { return FakeItemWithIndices.builder() .id(UUID.randomUUID().toString()) .sort(UUID.randomUUID().toString()) .gsiId(UUID.randomUUID().toString()) .gsiSort(UUID.randomUUID().toString()) .lsiSort(UUID.randomUUID().toString()) .build(); } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getSort() { return sort; } public void setSort(String sort) { this.sort = sort; } public String getGsiId() { return gsiId; } public void setGsiId(String gsiId) { this.gsiId = gsiId; } public String getGsiSort() { return gsiSort; } public void setGsiSort(String gsiSort) { this.gsiSort = gsiSort; } public String getLsiSort() { return lsiSort; } public void setLsiSort(String lsiSort) { this.lsiSort = lsiSort; } public static class Builder { private String id; private String sort; private String gsiId; private String gsiSort; private String lsiSort; public Builder id(String id) { this.id = id; return this; } public Builder sort(String sort) { this.sort = sort; return this; } public Builder gsiId(String gsiId) { this.gsiId = gsiId; return this; } public Builder gsiSort(String gsiSort) { this.gsiSort = gsiSort; return this; } public Builder lsiSort(String lsiSort) { this.lsiSort = lsiSort; return this; } public FakeItemWithIndices build() { return new FakeItemWithIndices(id, sort, gsiId, gsiSort, lsiSort); } } }
4,168
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/models/FakeItemComposedSubclass.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests.models; import java.util.Objects; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema; public class FakeItemComposedSubclass extends FakeItemComposedAbstractSubclass { private static final StaticTableSchema<FakeItemComposedSubclass> ITEM_MAPPER = StaticTableSchema.builder(FakeItemComposedSubclass.class) .newItemSupplier(FakeItemComposedSubclass::new) .addAttribute(String.class, a -> a.name("composed_subclass") .getter(FakeItemComposedSubclass::getComposedAttribute) .setter(FakeItemComposedSubclass::setComposedAttribute)) .extend(FakeItemComposedAbstractSubclass.getSubclassTableSchema()) .build(); private String composedAttribute; public static StaticTableSchema<FakeItemComposedSubclass> getTableSchema() { return ITEM_MAPPER; } public String getComposedAttribute() { return composedAttribute; } public void setComposedAttribute(String composedAttribute) { this.composedAttribute = composedAttribute; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (! super.equals(o)) return false; FakeItemComposedSubclass that = (FakeItemComposedSubclass) o; return Objects.equals(composedAttribute, that.composedAttribute); } @Override public int hashCode() { return Objects.hash(super.hashCode(), composedAttribute); } }
4,169
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/models/FakeItemComposedSubclass2.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests.models; import java.util.Objects; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema; public class FakeItemComposedSubclass2 extends FakeItemComposedAbstractSubclass2 { private static final StaticTableSchema<FakeItemComposedSubclass2> ITEM_MAPPER = StaticTableSchema.builder(FakeItemComposedSubclass2.class) .newItemSupplier(FakeItemComposedSubclass2::new) .extend(getSubclassTableSchema()) .addAttribute(String.class, a -> a.name("composed_subclass_2") .getter(FakeItemComposedSubclass2::getComposedAttribute2) .setter(FakeItemComposedSubclass2::setComposedAttribute2)) .build(); private String composedAttribute2; public static StaticTableSchema<FakeItemComposedSubclass2> getTableSchema() { return ITEM_MAPPER; } public String getComposedAttribute2() { return composedAttribute2; } public void setComposedAttribute2(String composedAttribute2) { this.composedAttribute2 = composedAttribute2; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (! super.equals(o)) return false; FakeItemComposedSubclass2 that = (FakeItemComposedSubclass2) o; return Objects.equals(composedAttribute2, that.composedAttribute2); } @Override public int hashCode() { return Objects.hash(super.hashCode(), composedAttribute2); } }
4,170
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/models/InnerAttributeRecord.java
package software.amazon.awssdk.enhanced.dynamodb.functionaltests.models; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey; public class InnerAttributeRecord { private String attribOne; private Integer attribTwo; @DynamoDbPartitionKey public String getAttribOne() { return attribOne; } public void setAttribOne(String attribOne) { this.attribOne = attribOne; } public Integer getAttribTwo() { return attribTwo; } public void setAttribTwo(Integer attribTwo) { this.attribTwo = attribTwo; } @Override public String toString() { return "InnerAttributeRecord{" + "attribOne='" + attribOne + '\'' + ", attribTwo=" + attribTwo + '}'; } }
4,171
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/models/FakeEnumRecord.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests.models; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey; @DynamoDbBean public class FakeEnumRecord { private String id; private FakeEnum enumAttribute; @DynamoDbPartitionKey public String getId() { return id; } public void setId(String id) { this.id = id; } public FakeEnum getEnumAttribute() { return enumAttribute; } public void setEnumAttribute(FakeEnum enumAttribute) { this.enumAttribute = enumAttribute; } }
4,172
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/models/RecursiveRecordImmutable.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests.models; import java.util.List; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbImmutable; @DynamoDbImmutable(builder = RecursiveRecordImmutable.Builder.class) public final class RecursiveRecordImmutable { private final int attribute; private final RecursiveRecordImmutable recursiveRecordImmutable; private final RecursiveRecordBean recursiveRecordBean; private final List<RecursiveRecordImmutable> recursiveRecordImmutableList; private RecursiveRecordImmutable(Builder b) { this.attribute = b.attribute; this.recursiveRecordImmutable = b.recursiveRecordImmutable; this.recursiveRecordBean = b.recursiveRecordBean; this.recursiveRecordImmutableList = b.recursiveRecordImmutableList; } public int getAttribute() { return attribute; } public RecursiveRecordImmutable getRecursiveRecordImmutable() { return recursiveRecordImmutable; } public RecursiveRecordBean getRecursiveRecordBean() { return recursiveRecordBean; } public List<RecursiveRecordImmutable> getRecursiveRecordList() { return recursiveRecordImmutableList; } public static Builder builder() { return new Builder(); } public static final class Builder { private int attribute; private RecursiveRecordImmutable recursiveRecordImmutable; private RecursiveRecordBean recursiveRecordBean; private List<RecursiveRecordImmutable> recursiveRecordImmutableList; private Builder() { } public Builder setAttribute(int attribute) { this.attribute = attribute; return this; } public Builder setRecursiveRecordImmutable(RecursiveRecordImmutable recursiveRecordImmutable) { this.recursiveRecordImmutable = recursiveRecordImmutable; return this; } public Builder setRecursiveRecordBean(RecursiveRecordBean recursiveRecordBean) { this.recursiveRecordBean = recursiveRecordBean; return this; } public Builder setRecursiveRecordList(List<RecursiveRecordImmutable> recursiveRecordImmutableList) { this.recursiveRecordImmutableList = recursiveRecordImmutableList; return this; } public RecursiveRecordImmutable build() { return new RecursiveRecordImmutable(this); } } }
4,173
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/models/RecursiveRecordBean.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests.models; import java.util.List; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean; @DynamoDbBean public final class RecursiveRecordBean { private int attribute; private RecursiveRecordBean recursiveRecordBean; private RecursiveRecordImmutable recursiveRecordImmutable; private List<RecursiveRecordBean> recursiveRecordBeanList; public int getAttribute() { return attribute; } public void setAttribute(int attribute) { this.attribute = attribute; } public RecursiveRecordBean getRecursiveRecordBean() { return recursiveRecordBean; } public void setRecursiveRecordBean(RecursiveRecordBean recursiveRecordBean) { this.recursiveRecordBean = recursiveRecordBean; } public RecursiveRecordImmutable getRecursiveRecordImmutable() { return recursiveRecordImmutable; } public void setRecursiveRecordImmutable(RecursiveRecordImmutable recursiveRecordImmutable) { this.recursiveRecordImmutable = recursiveRecordImmutable; } public List<RecursiveRecordBean> getRecursiveRecordList() { return recursiveRecordBeanList; } public void setRecursiveRecordList(List<RecursiveRecordBean> recursiveRecordBeanList) { this.recursiveRecordBeanList = recursiveRecordBeanList; } }
4,174
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/models/FakeItemWithNumericSort.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests.models; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primarySortKey; import java.util.Random; import java.util.UUID; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema; public class FakeItemWithNumericSort { private static final Random RANDOM = new Random(); private static final StaticTableSchema<FakeItemWithNumericSort> FAKE_ITEM_MAPPER = StaticTableSchema.builder(FakeItemWithNumericSort.class) .newItemSupplier(FakeItemWithNumericSort::new) .addAttribute(String.class, a -> a.name("id") .getter(FakeItemWithNumericSort::getId) .setter(FakeItemWithNumericSort::setId) .addTag(primaryPartitionKey())) .addAttribute(Integer.class, a -> a.name("sort") .getter(FakeItemWithNumericSort::getSort) .setter(FakeItemWithNumericSort::setSort) .addTag(primarySortKey())) .build(); private String id; private Integer sort; public FakeItemWithNumericSort() { } public FakeItemWithNumericSort(String id, Integer sort) { this.id = id; this.sort = sort; } public static Builder builder() { return new Builder(); } public static StaticTableSchema<FakeItemWithNumericSort> getTableSchema() { return FAKE_ITEM_MAPPER; } public static FakeItemWithNumericSort createUniqueFakeItemWithSort() { return FakeItemWithNumericSort.builder() .id(UUID.randomUUID().toString()) .sort(RANDOM.nextInt()) .build(); } public String getId() { return id; } public void setId(String id) { this.id = id; } public Integer getSort() { return sort; } public void setSort(Integer sort) { this.sort = sort; } public static class Builder { private String id; private Integer sort; public Builder id(String id) { this.id = id; return this; } public Builder sort(Integer sort) { this.sort = sort; return this; } public FakeItemWithNumericSort build() { return new FakeItemWithNumericSort(id, sort); } } }
4,175
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/models/FakeItemWithByteBufferKey.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests.models; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema; import java.nio.ByteBuffer; import java.util.Objects; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey; public class FakeItemWithByteBufferKey { private static final StaticTableSchema<FakeItemWithByteBufferKey> FAKE_ITEM_WITH_BINARY_KEY_SCHEMA = StaticTableSchema.builder(FakeItemWithByteBufferKey.class) .newItemSupplier(FakeItemWithByteBufferKey::new) .addAttribute(SdkBytes.class, a -> a.name("id") .getter(FakeItemWithByteBufferKey::getIdAsSdkBytes) .setter(FakeItemWithByteBufferKey::setIdAsSdkBytes) .tags(primaryPartitionKey())) .build(); private ByteBuffer id; public static StaticTableSchema<FakeItemWithByteBufferKey> getTableSchema() { return FAKE_ITEM_WITH_BINARY_KEY_SCHEMA; } public ByteBuffer getId() { return id; } public void setId(ByteBuffer id) { this.id = id; } public SdkBytes getIdAsSdkBytes() { return SdkBytes.fromByteBuffer(id); } public void setIdAsSdkBytes(SdkBytes id) { this.id = id.asByteBuffer(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; FakeItemWithByteBufferKey that = (FakeItemWithByteBufferKey) o; return Objects.equals(id, that.id); } @Override public int hashCode() { return Objects.hash(id); } }
4,176
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/models/FakeEnum.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests.models; public enum FakeEnum { ONE, TWO }
4,177
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/models/FakeItemAbstractSubclass.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests.models; import java.util.Objects; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema; abstract class FakeItemAbstractSubclass extends FakeItemAbstractSubclass2 { private static final StaticTableSchema<FakeItemAbstractSubclass> FAKE_ITEM_MAPPER = StaticTableSchema.builder(FakeItemAbstractSubclass.class) .addAttribute(String.class, a -> a.name("subclass_attribute") .getter(FakeItemAbstractSubclass::getSubclassAttribute) .setter(FakeItemAbstractSubclass::setSubclassAttribute)) .flatten(FakeItemComposedSubclass.getTableSchema(), FakeItemAbstractSubclass::getComposedAttribute, FakeItemAbstractSubclass::setComposedAttribute) .extend(FakeItemAbstractSubclass2.getSubclass2TableSchema()) .build(); private String subclassAttribute; private FakeItemComposedSubclass composedAttribute; static StaticTableSchema<FakeItemAbstractSubclass> getSubclassTableSchema() { return FAKE_ITEM_MAPPER; } FakeItemAbstractSubclass() { composedAttribute = new FakeItemComposedSubclass(); } public String getSubclassAttribute() { return subclassAttribute; } public void setSubclassAttribute(String subclassAttribute) { this.subclassAttribute = subclassAttribute; } public FakeItemComposedSubclass getComposedAttribute() { return composedAttribute; } public void setComposedAttribute(FakeItemComposedSubclass composedAttribute) { this.composedAttribute = composedAttribute; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (! super.equals(o)) return false; FakeItemAbstractSubclass that = (FakeItemAbstractSubclass) o; return Objects.equals(subclassAttribute, that.subclassAttribute) && Objects.equals(composedAttribute, that.composedAttribute); } @Override public int hashCode() { return Objects.hash(super.hashCode(), subclassAttribute, composedAttribute); } }
4,178
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/models/FakeEnumShortenedRecord.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests.models; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey; @DynamoDbBean public class FakeEnumShortenedRecord { private String id; private FakeEnumShortened enumAttribute; @DynamoDbPartitionKey public String getId() { return id; } public void setId(String id) { this.id = id; } public FakeEnumShortened getEnumAttribute() { return enumAttribute; } public void setEnumAttribute(FakeEnumShortened enumAttribute) { this.enumAttribute = enumAttribute; } }
4,179
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/models/FakeItemComposedClass.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests.models; import java.util.Objects; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema; public class FakeItemComposedClass { private static final StaticTableSchema<FakeItemComposedClass> ITEM_MAPPER = StaticTableSchema.builder(FakeItemComposedClass.class) .addAttribute(String.class, a -> a.name("composed_attribute") .getter(FakeItemComposedClass::getComposedAttribute) .setter(FakeItemComposedClass::setComposedAttribute)) .newItemSupplier(FakeItemComposedClass::new) .build(); private String composedAttribute; public FakeItemComposedClass() { } public FakeItemComposedClass(String composedAttribute) { this.composedAttribute = composedAttribute; } public static Builder builder() { return new Builder(); } public static StaticTableSchema<FakeItemComposedClass> getTableSchema() { return ITEM_MAPPER; } public String getComposedAttribute() { return composedAttribute; } public void setComposedAttribute(String composedAttribute) { this.composedAttribute = composedAttribute; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; FakeItemComposedClass that = (FakeItemComposedClass) o; return Objects.equals(composedAttribute, that.composedAttribute); } @Override public int hashCode() { return Objects.hash(composedAttribute); } public static class Builder { private String composedAttribute; public Builder composedAttribute(String composedAttribute) { this.composedAttribute = composedAttribute; return this; } public FakeItemComposedClass build() { return new FakeItemComposedClass(composedAttribute); } } }
4,180
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/models/FakeItemComposedAbstractSubclass2.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests.models; import java.util.Objects; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema; abstract class FakeItemComposedAbstractSubclass2 { private static final StaticTableSchema<FakeItemComposedAbstractSubclass2> FAKE_ITEM_MAPPER = StaticTableSchema.builder(FakeItemComposedAbstractSubclass2.class) .addAttribute(String.class, a -> a.name("composed_abstract_subclass_2") .getter(FakeItemComposedAbstractSubclass2::getComposedSubclassAttribute2) .setter(FakeItemComposedAbstractSubclass2::setComposedSubclassAttribute2)) .build(); private String composedSubclassAttribute2; static StaticTableSchema<FakeItemComposedAbstractSubclass2> getSubclassTableSchema() { return FAKE_ITEM_MAPPER; } public String getComposedSubclassAttribute2() { return composedSubclassAttribute2; } public void setComposedSubclassAttribute2(String composedSubclassAttribute2) { this.composedSubclassAttribute2 = composedSubclassAttribute2; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; FakeItemComposedAbstractSubclass2 that = (FakeItemComposedAbstractSubclass2) o; return Objects.equals(composedSubclassAttribute2, that.composedSubclassAttribute2); } @Override public int hashCode() { return Objects.hash(composedSubclassAttribute2); } }
4,181
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/models/NestedTestRecord.java
package software.amazon.awssdk.enhanced.dynamodb.functionaltests.models; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.*; @DynamoDbBean public class NestedTestRecord { private String outerAttribOne; private Integer sort; private InnerAttributeRecord innerAttributeRecord; private String dotVariable; @DynamoDbPartitionKey public String getOuterAttribOne() { return outerAttribOne; } public void setOuterAttribOne(String outerAttribOne) { this.outerAttribOne = outerAttribOne; } @DynamoDbSortKey public Integer getSort() { return sort; } public void setSort(Integer sort) { this.sort = sort; } @DynamoDbConvertedBy(InnerAttribConverter.class) public InnerAttributeRecord getInnerAttributeRecord() { return innerAttributeRecord; } public void setInnerAttributeRecord(InnerAttributeRecord innerAttributeRecord) { this.innerAttributeRecord = innerAttributeRecord; } @DynamoDbAttribute("test.com") public String getDotVariable() { return dotVariable; } public void setDotVariable(String dotVariable) { this.dotVariable = dotVariable; } @Override public String toString() { return "NestedTestRecord{" + "outerAttribOne='" + outerAttribOne + '\'' + ", sort=" + sort + ", innerAttributeRecord=" + innerAttributeRecord + ", dotVariable='" + dotVariable + '\'' + '}'; } }
4,182
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/models/FakeItemWithSort.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests.models; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primarySortKey; import java.util.Objects; import java.util.UUID; import software.amazon.awssdk.enhanced.dynamodb.TableMetadata; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema; public class FakeItemWithSort { private static final StaticTableSchema<FakeItemWithSort> FAKE_ITEM_MAPPER = StaticTableSchema.builder(FakeItemWithSort.class) .newItemSupplier(FakeItemWithSort::new) .addAttribute(String.class, a -> a.name("id") .getter(FakeItemWithSort::getId) .setter(FakeItemWithSort::setId) .tags(primaryPartitionKey())) .addAttribute(String.class, a -> a.name("sort") .getter(FakeItemWithSort::getSort) .setter(FakeItemWithSort::setSort) .tags(primarySortKey())) .addAttribute(String.class, a -> a.name("other_attribute_1") .getter(FakeItemWithSort::getOtherAttribute1) .setter(FakeItemWithSort::setOtherAttribute1)) .addAttribute(String.class, a -> a.name("other_attribute_2") .getter(FakeItemWithSort::getOtherAttribute2) .setter(FakeItemWithSort::setOtherAttribute2)) .build(); private String id; private String sort; private String otherAttribute1; private String otherAttribute2; public FakeItemWithSort() { } public FakeItemWithSort(String id, String sort, String otherAttribute1, String otherAttribute2) { this.id = id; this.sort = sort; this.otherAttribute1 = otherAttribute1; this.otherAttribute2 = otherAttribute2; } public static Builder builder() { return new Builder(); } public static StaticTableSchema<FakeItemWithSort> getTableSchema() { return FAKE_ITEM_MAPPER; } public static TableMetadata getTableMetadata() { return FAKE_ITEM_MAPPER.tableMetadata(); } public static FakeItemWithSort createUniqueFakeItemWithSort() { return FakeItemWithSort.builder() .id(UUID.randomUUID().toString()) .sort(UUID.randomUUID().toString()) .build(); } public static FakeItemWithSort createUniqueFakeItemWithoutSort() { return FakeItemWithSort.builder() .id(UUID.randomUUID().toString()) .build(); } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getSort() { return sort; } public void setSort(String sort) { this.sort = sort; } public String getOtherAttribute1() { return otherAttribute1; } public void setOtherAttribute1(String otherAttribute1) { this.otherAttribute1 = otherAttribute1; } public String getOtherAttribute2() { return otherAttribute2; } public void setOtherAttribute2(String otherAttribute2) { this.otherAttribute2 = otherAttribute2; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } FakeItemWithSort that = (FakeItemWithSort) o; return Objects.equals(id, that.id) && Objects.equals(sort, that.sort) && Objects.equals(otherAttribute1, that.otherAttribute1) && Objects.equals(otherAttribute2, that.otherAttribute2); } @Override public int hashCode() { return Objects.hash(id, sort, otherAttribute1, otherAttribute2); } public static class Builder { private String id; private String sort; private String otherAttribute1; private String otherAttribute2; public Builder id(String id) { this.id = id; return this; } public Builder sort(String sort) { this.sort = sort; return this; } public Builder otherAttribute1(String otherAttribute1) { this.otherAttribute1 = otherAttribute1; return this; } public Builder otherAttribute2(String otherAttribute2) { this.otherAttribute2 = otherAttribute2; return this; } public FakeItemWithSort build() { return new FakeItemWithSort(id, sort, otherAttribute1, otherAttribute2); } } }
4,183
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/models/ImmutableFakeItem.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests.models; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbImmutable; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey; @DynamoDbImmutable(builder = ImmutableFakeItem.Builder.class) public class ImmutableFakeItem { private final String id; private final String attribute; private ImmutableFakeItem(Builder b) { this.id = b.id; this.attribute = b.attribute; } public static Builder builder() { return new Builder(); } public String attribute() { return attribute; } @DynamoDbPartitionKey public String id() { return id; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ImmutableFakeItem that = (ImmutableFakeItem) o; if (id != null ? !id.equals(that.id) : that.id != null) { return false; } return attribute != null ? attribute.equals(that.attribute) : that.attribute == null; } @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + (attribute != null ? attribute.hashCode() : 0); return result; } public static final class Builder { private String id; private String attribute; public Builder id(String id) { this.id = id; return this; } public Builder attribute(String attribute) { this.attribute = attribute; return this; } public ImmutableFakeItem build() { return new ImmutableFakeItem(this); } } }
4,184
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/models/AtomicCounterRecord.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests.models; import software.amazon.awssdk.enhanced.dynamodb.extensions.annotations.DynamoDbAtomicCounter; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey; @DynamoDbBean public class AtomicCounterRecord { private String id; private Long defaultCounter; private Long customCounter; private Long decreasingCounter; private String attribute1; @DynamoDbPartitionKey public String getId() { return id; } public void setId(String id) { this.id = id; } @DynamoDbAtomicCounter public Long getDefaultCounter() { return defaultCounter; } public void setDefaultCounter(Long counter) { this.defaultCounter = counter; } @DynamoDbAtomicCounter(delta = 5, startValue = 10) public Long getCustomCounter() { return customCounter; } public void setCustomCounter(Long counter) { this.customCounter = counter; } @DynamoDbAtomicCounter(delta = -1, startValue = -20) public Long getDecreasingCounter() { return decreasingCounter; } public void setDecreasingCounter(Long counter) { this.decreasingCounter = counter; } public String getAttribute1() { return attribute1; } public void setAttribute1(String attribute1) { this.attribute1 = attribute1; } }
4,185
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/models/NestedRecordWithUpdateBehavior.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests.models; import static software.amazon.awssdk.enhanced.dynamodb.mapper.UpdateBehavior.WRITE_IF_NOT_EXISTS; import java.time.Instant; import software.amazon.awssdk.enhanced.dynamodb.extensions.annotations.DynamoDbAtomicCounter; import software.amazon.awssdk.enhanced.dynamodb.extensions.annotations.DynamoDbAutoGeneratedTimestampAttribute; import software.amazon.awssdk.enhanced.dynamodb.extensions.annotations.DynamoDbVersionAttribute; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbUpdateBehavior; @DynamoDbBean public class NestedRecordWithUpdateBehavior { private String id; private String nestedUpdateBehaviorAttribute; private Long nestedVersionedAttribute; private Instant nestedTimeAttribute; private Long nestedCounter; @DynamoDbPartitionKey public String getId() { return id; } public void setId(String id) { this.id = id; } @DynamoDbUpdateBehavior(WRITE_IF_NOT_EXISTS) public String getNestedUpdateBehaviorAttribute() { return nestedUpdateBehaviorAttribute; } public void setNestedUpdateBehaviorAttribute(String nestedUpdateBehaviorAttribute) { this.nestedUpdateBehaviorAttribute = nestedUpdateBehaviorAttribute; } @DynamoDbVersionAttribute public Long getNestedVersionedAttribute() { return nestedVersionedAttribute; } public void setNestedVersionedAttribute(Long nestedVersionedAttribute) { this.nestedVersionedAttribute = nestedVersionedAttribute; } @DynamoDbAutoGeneratedTimestampAttribute public Instant getNestedTimeAttribute() { return nestedTimeAttribute; } public void setNestedTimeAttribute(Instant nestedTimeAttribute) { this.nestedTimeAttribute = nestedTimeAttribute; } @DynamoDbAtomicCounter public Long getNestedCounter() { return nestedCounter; } public void setNestedCounter(Long nestedCounter) { this.nestedCounter = nestedCounter; } }
4,186
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/models/RecordForUpdateExpressions.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests.models; import static software.amazon.awssdk.enhanced.dynamodb.mapper.UpdateBehavior.WRITE_IF_NOT_EXISTS; import java.util.Set; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbUpdateBehavior; @DynamoDbBean public class RecordForUpdateExpressions { private String id; private String stringAttribute1; private Long extensionAttribute1; private Set<String> extensionAttribute2; @DynamoDbPartitionKey public String getId() { return id; } public void setId(String id) { this.id = id; } @DynamoDbUpdateBehavior(WRITE_IF_NOT_EXISTS) public String getStringAttribute() { return stringAttribute1; } public void setStringAttribute(String stringAttribute1) { this.stringAttribute1 = stringAttribute1; } public Long getExtensionNumberAttribute() { return extensionAttribute1; } public void setExtensionNumberAttribute(Long extensionAttribute1) { this.extensionAttribute1 = extensionAttribute1; } public Set<String> getExtensionSetAttribute() { return extensionAttribute2; } public void setExtensionSetAttribute(Set<String> extensionAttribute2) { this.extensionAttribute2 = extensionAttribute2; } }
4,187
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/models/FakeItemComposedAbstractSubclass.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests.models; import java.util.Objects; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema; abstract class FakeItemComposedAbstractSubclass { private static final StaticTableSchema<FakeItemComposedAbstractSubclass> FAKE_ITEM_MAPPER = StaticTableSchema.builder(FakeItemComposedAbstractSubclass.class) .addAttribute(String.class, a -> a.name("composed_abstract_subclass") .getter(FakeItemComposedAbstractSubclass::getComposedSubclassAttribute) .setter(FakeItemComposedAbstractSubclass::setComposedSubclassAttribute)) .build(); private String composedSubclassAttribute; static StaticTableSchema<FakeItemComposedAbstractSubclass> getSubclassTableSchema() { return FAKE_ITEM_MAPPER; } public String getComposedSubclassAttribute() { return composedSubclassAttribute; } public void setComposedSubclassAttribute(String composedSubclassAttribute) { this.composedSubclassAttribute = composedSubclassAttribute; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; FakeItemComposedAbstractSubclass that = (FakeItemComposedAbstractSubclass) o; return Objects.equals(composedSubclassAttribute, that.composedSubclassAttribute); } @Override public int hashCode() { return Objects.hash(composedSubclassAttribute); } }
4,188
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/models/InnerAttribConverterProvider.java
package software.amazon.awssdk.enhanced.dynamodb.functionaltests.models; import java.util.Map; import software.amazon.awssdk.enhanced.dynamodb.AttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.AttributeConverterProvider; import software.amazon.awssdk.enhanced.dynamodb.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.converters.document.CustomClassForDocumentAPI; import software.amazon.awssdk.enhanced.dynamodb.converters.document.CustomClassForDocumentAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.converters.document.CustomIntegerAttributeConverter; import software.amazon.awssdk.utils.ImmutableMap; /** * InnerAttribConverterProvider to save the InnerAttribConverter on the class. */ public class InnerAttribConverterProvider<T> implements AttributeConverterProvider { private final Map<EnhancedType<?>, AttributeConverter<?>> converterCache = ImmutableMap.of( EnhancedType.of(InnerAttributeRecord.class), new InnerAttribConverter<T>() ); @Override public <T> AttributeConverter<T> converterFor(EnhancedType<T> enhancedType) { return (AttributeConverter<T>) converterCache.get(enhancedType); } }
4,189
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/models/FakeItem.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests.models; import static software.amazon.awssdk.enhanced.dynamodb.extensions.VersionedRecordExtension.AttributeTags.versionAttribute; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey; import java.util.Objects; import java.util.UUID; import software.amazon.awssdk.enhanced.dynamodb.TableMetadata; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema; public class FakeItem extends FakeItemAbstractSubclass { private static final StaticTableSchema<FakeItem> FAKE_ITEM_MAPPER = StaticTableSchema.builder(FakeItem.class) .newItemSupplier(FakeItem::new) .flatten(FakeItemComposedClass.getTableSchema(), FakeItem::getComposedObject, FakeItem::setComposedObject) .extend(getSubclassTableSchema()) .addAttribute(String.class, a -> a.name("id") .getter(FakeItem::getId) .setter(FakeItem::setId) .addTag(primaryPartitionKey())) .addAttribute(Integer.class, a -> a.name("version") .getter(FakeItem::getVersion) .setter(FakeItem::setVersion) .addTag(versionAttribute())) .build(); private String id; private Integer version; private FakeItemComposedClass composedObject; public FakeItem() { } public FakeItem(String id, Integer version, FakeItemComposedClass composedObject) { this.id = id; this.version = version; this.composedObject = composedObject; } public static Builder builder() { return new Builder(); } public static TableSchema<FakeItem> getTableSchema() { return FAKE_ITEM_MAPPER; } public static TableMetadata getTableMetadata() { return FAKE_ITEM_MAPPER.tableMetadata(); } public static FakeItem createUniqueFakeItem() { return FakeItem.builder() .id(UUID.randomUUID().toString()) .build(); } public String getId() { return id; } public void setId(String id) { this.id = id; } public Integer getVersion() { return version; } public void setVersion(Integer version) { this.version = version; } public FakeItemComposedClass getComposedObject() { return composedObject; } public void setComposedObject(FakeItemComposedClass composedObject) { this.composedObject = composedObject; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (! super.equals(o)) return false; FakeItem fakeItem = (FakeItem) o; return Objects.equals(id, fakeItem.id) && Objects.equals(version, fakeItem.version) && Objects.equals(composedObject, fakeItem.composedObject); } @Override public int hashCode() { return Objects.hash(super.hashCode(), id, version, composedObject); } public static class Builder { private String id; private Integer version; private FakeItemComposedClass composedObject; public Builder id(String id) { this.id = id; return this; } public Builder version(Integer version) { this.version = version; return this; } public Builder composedObject(FakeItemComposedClass composedObject) { this.composedObject = composedObject; return this; } public FakeItem build() { return new FakeItem(id, version, composedObject); } } }
4,190
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/document/IndexScanTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests.document; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static software.amazon.awssdk.enhanced.dynamodb.AttributeConverterProvider.defaultProvider; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.numberValue; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.stringValue; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbIndex; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.Expression; import software.amazon.awssdk.enhanced.dynamodb.TableMetadata; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.document.EnhancedDocument; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.LocalDynamoDbSyncTestBase; import software.amazon.awssdk.enhanced.dynamodb.model.CreateTableEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.EnhancedGlobalSecondaryIndex; import software.amazon.awssdk.enhanced.dynamodb.model.Page; import software.amazon.awssdk.enhanced.dynamodb.model.ScanEnhancedRequest; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; import software.amazon.awssdk.services.dynamodb.model.ProjectionType; public class IndexScanTest extends LocalDynamoDbSyncTestBase { private DynamoDbClient lowLevelClient; private DynamoDbTable<EnhancedDocument> docMappedtable ; @Rule public ExpectedException exception = ExpectedException.none(); private DynamoDbEnhancedClient enhancedClient; private final String tableName = getConcreteTableName("table-name"); DynamoDbIndex<EnhancedDocument> keysOnlyMappedIndex ; @Before public void createTable() { lowLevelClient = getDynamoDbClient(); enhancedClient = DynamoDbEnhancedClient.builder() .dynamoDbClient(lowLevelClient) .build(); docMappedtable = enhancedClient.table(tableName, TableSchema.documentSchemaBuilder() .attributeConverterProviders(defaultProvider()) .addIndexPartitionKey(TableMetadata.primaryIndexName(), "id", AttributeValueType.S) .addIndexSortKey(TableMetadata.primaryIndexName(), "sort", AttributeValueType.N) .addIndexPartitionKey("gsi_keys_only", "gsi_id", AttributeValueType.S) .addIndexSortKey("gsi_keys_only", "gsi_sort", AttributeValueType.N) .attributeConverterProviders(defaultProvider()) .build()); docMappedtable.createTable(CreateTableEnhancedRequest.builder() .provisionedThroughput(getDefaultProvisionedThroughput()) .globalSecondaryIndices( EnhancedGlobalSecondaryIndex.builder() .indexName("gsi_keys_only") .projection(p -> p.projectionType(ProjectionType.KEYS_ONLY)) .provisionedThroughput(getDefaultProvisionedThroughput()) .build()) .build()); keysOnlyMappedIndex = docMappedtable.index("gsi_keys_only"); } private static final List<EnhancedDocument> DOCUMENTS = IntStream.range(0, 10) .mapToObj(i -> EnhancedDocument.builder() .attributeConverterProviders(defaultProvider()) .putString("id", "id-value") .putNumber("sort", i) .putNumber("value", i) .putString("gsi_id", "gsi-id-value") .putNumber("gsi_sort", i) .build() ).collect(Collectors.toList()); private static final List<EnhancedDocument> KEYS_ONLY_DOCUMENTS = DOCUMENTS.stream() .map(record -> EnhancedDocument.builder() .attributeConverterProviders(defaultProvider()) .putString("id", record.getString("id")) .putNumber("sort", record.getNumber("sort")) .putString("gsi_id", record.getString("gsi_id")) .putNumber("gsi_sort", record.getNumber("gsi_sort")).build() ) .collect(Collectors.toList()); private void insertDocuments() { DOCUMENTS.forEach(document -> docMappedtable.putItem(r -> r.item(document))); } @After public void deleteTable() { getDynamoDbClient().deleteTable(DeleteTableRequest.builder() .tableName(tableName) .build()); } @Test public void scanAllRecordsDefaultSettings() { insertDocuments(); Iterator<Page<EnhancedDocument>> results = keysOnlyMappedIndex.scan(ScanEnhancedRequest.builder().build()).iterator(); assertThat(results.hasNext(), is(true)); Page<EnhancedDocument> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items().stream().map(i -> i.toMap()).collect(Collectors.toList()), is(KEYS_ONLY_DOCUMENTS.stream().map(i -> i.toMap()).collect(Collectors.toList()))); assertThat(page.lastEvaluatedKey(), is(nullValue())); } @Test public void scanAllRecordsWithFilter() { insertDocuments(); Map<String, AttributeValue> expressionValues = new HashMap<>(); expressionValues.put(":min_value", numberValue(3)); expressionValues.put(":max_value", numberValue(5)); Expression expression = Expression.builder() .expression("sort >= :min_value AND sort <= :max_value") .expressionValues(expressionValues) .build(); Iterator<Page<EnhancedDocument>> results = keysOnlyMappedIndex.scan(ScanEnhancedRequest.builder().filterExpression(expression).build()).iterator(); assertThat(results.hasNext(), is(true)); Page<EnhancedDocument> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items().stream().map(i -> i.toMap()).collect(Collectors.toList()), is(KEYS_ONLY_DOCUMENTS.stream().filter(r -> r.getNumber("sort").intValue() >= 3 && r.getNumber("sort").intValue() <= 5).map(i -> i.toMap()).collect(Collectors.toList()))); assertThat(page.lastEvaluatedKey(), is(nullValue())); } @Test public void scanLimit() { insertDocuments(); Iterator<Page<EnhancedDocument>> results = keysOnlyMappedIndex.scan(r -> r.limit(5)).iterator(); assertThat(results.hasNext(), is(true)); Page<EnhancedDocument> page1 = results.next(); assertThat(results.hasNext(), is(true)); Page<EnhancedDocument> page2 = results.next(); assertThat(results.hasNext(), is(true)); Page<EnhancedDocument> page3 = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page1.items().stream().map(i -> i.toMap()).collect(Collectors.toList()), is(KEYS_ONLY_DOCUMENTS.subList(0, 5).stream().map(i -> i.toMap()).collect(Collectors.toList()))); assertThat(page1.lastEvaluatedKey(), is(getKeyMap(4))); assertThat(page2.items().stream().map(i -> i.toMap()).collect(Collectors.toList()), is(KEYS_ONLY_DOCUMENTS.subList(5, 10).stream().map(i -> i.toMap()).collect(Collectors.toList()))); assertThat(page2.lastEvaluatedKey(), is(getKeyMap(9))); assertThat(page3.items(), is(empty())); assertThat(page3.lastEvaluatedKey(), is(nullValue())); } @Test public void scanEmpty() { Iterator<Page<EnhancedDocument>> results = keysOnlyMappedIndex.scan().iterator(); assertThat(results.hasNext(), is(true)); Page<EnhancedDocument> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items(), is(empty())); assertThat(page.lastEvaluatedKey(), is(nullValue())); } @Test public void scanExclusiveStartKey() { insertDocuments(); Iterator<Page<EnhancedDocument>> results = keysOnlyMappedIndex.scan(r -> r.exclusiveStartKey(getKeyMap(7))).iterator(); assertThat(results.hasNext(), is(true)); Page<EnhancedDocument> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items().stream().map(i -> i.toMap()).collect(Collectors.toList()), is(KEYS_ONLY_DOCUMENTS.subList(8, 10).stream().map(i -> i.toMap()).collect(Collectors.toList()))); assertThat(page.lastEvaluatedKey(), is(nullValue())); } private Map<String, AttributeValue> getKeyMap(int sort) { Map<String, AttributeValue> result = new HashMap<>(); result.put("id", stringValue(KEYS_ONLY_DOCUMENTS.get(sort).getString("id"))); result.put("sort", numberValue(KEYS_ONLY_DOCUMENTS.get(sort).getNumber("sort"))); result.put("gsi_id", stringValue(KEYS_ONLY_DOCUMENTS.get(sort).getString("gsi_id"))); result.put("gsi_sort", numberValue(KEYS_ONLY_DOCUMENTS.get(sort).getNumber("gsi_sort"))); return Collections.unmodifiableMap(result); } }
4,191
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/document/BasicAsyncCrudTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests.document; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static software.amazon.awssdk.enhanced.dynamodb.AttributeConverterProvider.defaultProvider; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.stringValue; import java.util.Collection; import java.util.LinkedHashMap; import java.util.Map; import java.util.concurrent.CompletionException; import java.util.concurrent.ExecutionException; import org.assertj.core.api.Assertions; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbAsyncTable; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedAsyncClient; import software.amazon.awssdk.enhanced.dynamodb.Expression; import software.amazon.awssdk.enhanced.dynamodb.Key; import software.amazon.awssdk.enhanced.dynamodb.TableMetadata; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.document.EnhancedDocument; import software.amazon.awssdk.enhanced.dynamodb.document.EnhancedDocumentTestData; import software.amazon.awssdk.enhanced.dynamodb.document.TestData; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.LocalDynamoDbAsyncTestBase; import software.amazon.awssdk.enhanced.dynamodb.model.DeleteItemEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.PutItemEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.UpdateItemEnhancedRequest; import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException; import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; import software.amazon.awssdk.services.dynamodb.model.GetItemResponse; @RunWith(Parameterized.class) public class BasicAsyncCrudTest extends LocalDynamoDbAsyncTestBase { private static final String ATTRIBUTE_NAME_WITH_SPECIAL_CHARACTERS = "a*t:t.r-i#bute+3/4(&?5=@)<6>!ch$ar%"; private final TestData testData; @Rule public ExpectedException exception = ExpectedException.none(); private DynamoDbEnhancedAsyncClient enhancedClient; private final String tableName = getConcreteTableName("table-name"); private DynamoDbAsyncClient lowLevelClient; private DynamoDbAsyncTable<EnhancedDocument> docMappedtable ; @Before public void setUp(){ lowLevelClient = getDynamoDbAsyncClient(); enhancedClient = DynamoDbEnhancedAsyncClient.builder() .dynamoDbClient(lowLevelClient) .build(); docMappedtable = enhancedClient.table(tableName, TableSchema.documentSchemaBuilder() .addIndexPartitionKey(TableMetadata.primaryIndexName(), "id", AttributeValueType.S) .addIndexSortKey(TableMetadata.primaryIndexName(), "sort", AttributeValueType.S) .attributeConverterProviders(defaultProvider()) .build()); docMappedtable.createTable().join(); } public BasicAsyncCrudTest(TestData testData) { this.testData = testData; } @Parameterized.Parameters public static Collection<TestData> parameters() throws Exception { return EnhancedDocumentTestData.testDataInstance().getAllGenericScenarios(); } private static EnhancedDocument appendKeysToDoc(TestData testData) { EnhancedDocument enhancedDocument = testData.getEnhancedDocument().toBuilder() .putString("id", "id-value") .putString("sort", "sort-value").build(); return enhancedDocument; } private static Map<String, AttributeValue> simpleKey() { Map<String, AttributeValue> key = new LinkedHashMap<>(); key.put("id", AttributeValue.fromS("id-value")); key.put("sort", AttributeValue.fromS("sort-value")); return key; } private static Map<String, AttributeValue> appendKeysToTestDataAttributeMap(Map<String, AttributeValue> attributeValueMap) { Map<String, AttributeValue> result = new LinkedHashMap<>(attributeValueMap); result.put("id", AttributeValue.fromS("id-value")); result.put("sort", AttributeValue.fromS("sort-value")); return result; } @After public void deleteTable() { getDynamoDbAsyncClient().deleteTable(DeleteTableRequest.builder() .tableName(tableName) .build()).join(); } @Test public void putThenGetItemUsingKey() { EnhancedDocument enhancedDocument = appendKeysToDoc(testData); docMappedtable.putItem(enhancedDocument).join(); Map<String, AttributeValue> key = simpleKey(); GetItemResponse lowLevelGet = lowLevelClient.getItem(r -> r.key(key).tableName(tableName)).join(); Assertions.assertThat(lowLevelGet.item()).isEqualTo(enhancedDocument.toMap()); } @Test public void putThenGetItemUsingKeyItem() throws ExecutionException, InterruptedException { EnhancedDocument enhancedDocument = appendKeysToDoc(testData); docMappedtable.putItem(r -> r.item(enhancedDocument)).join(); EnhancedDocument result = docMappedtable.getItem(EnhancedDocument.builder() .attributeConverterProviders(testData.getAttributeConverterProvider()) .putString("id", "id-value") .putString("sort", "sort-value") .build()).join(); Map<String, AttributeValue> attributeValueMap = appendKeysToTestDataAttributeMap(testData.getDdbItemMap()); Assertions.assertThat(result.toMap()).isEqualTo(enhancedDocument.toMap()); Assertions.assertThat(result.toMap()).isEqualTo(attributeValueMap); } @Test public void getNonExistentItem() { EnhancedDocument item = docMappedtable.getItem(r -> r.key(k -> k.partitionValue("id-value").sortValue("sort-value"))).join(); Assertions.assertThat(item).isNull(); } @Test public void updateOverwriteCompleteItem_usingShortcutForm() { EnhancedDocument enhancedDocument = appendKeysToDoc(testData).toBuilder() .putString("attribute", "one") .putString("attribute2", "two") .putString("attribute3", "three") .build(); docMappedtable.putItem(enhancedDocument).join(); // Updating new Items other than the one present in testData EnhancedDocument updateDocument = EnhancedDocument.builder() .putString("id", "id-value") .putString("sort", "sort-value") .putString("attribute", "four") .putString("attribute2", "five") .putString("attribute3", "six") .build(); EnhancedDocument result = docMappedtable.updateItem(updateDocument).join(); Map<String, AttributeValue> updatedItemMap = new LinkedHashMap<>(testData.getDdbItemMap()); updatedItemMap.put("attribute", AttributeValue.fromS("four")); updatedItemMap.put("attribute2", AttributeValue.fromS("five")); updatedItemMap.put("attribute3", AttributeValue.fromS("six")); updatedItemMap.put("id", AttributeValue.fromS("id-value")); updatedItemMap.put("sort", AttributeValue.fromS("sort-value")); Map<String, AttributeValue> key = simpleKey(); GetItemResponse lowLevelGet = lowLevelClient.getItem(r -> r.key(key).tableName(tableName)).join(); Assertions.assertThat(lowLevelGet.item()).isEqualTo(result.toMap()); Assertions.assertThat(lowLevelGet.item()).isEqualTo(updatedItemMap); } @Test public void putTwiceThenGetItem() { EnhancedDocument enhancedDocument = appendKeysToDoc(testData).toBuilder() .putString("attribute", "one") .putString("attribute2", "two") .putString("attribute3", "three") .build(); docMappedtable.putItem(enhancedDocument).join(); // Updating new Items other than the one present in testData EnhancedDocument updateDocument = EnhancedDocument.builder() .attributeConverterProviders(defaultProvider()) .putString("id", "id-value") .putString("sort", "sort-value") .putString("attribute", "four") .putString("attribute2", "five") .putString("attribute3", "six") .build(); docMappedtable.putItem(r -> r.item(updateDocument)).join(); Map<String, AttributeValue> key = simpleKey(); GetItemResponse lowLevelGet = lowLevelClient.getItem(r -> r.key(key).tableName(tableName)).join(); // All the items are overwritten Assertions.assertThat(lowLevelGet.item()).isEqualTo(updateDocument.toMap()); EnhancedDocument docGetItem = docMappedtable.getItem(r -> r.key(k -> k.partitionValue("id-value").sortValue("sort-value" ))).join(); Assertions.assertThat(lowLevelGet.item()).isEqualTo(docGetItem.toMap()); } @Test public void putThenDeleteItem_usingShortcutForm() { EnhancedDocument enhancedDocument = appendKeysToDoc(testData).toBuilder() .putString("attribute", "one") .putString("attribute2", "two") .putString("attribute3", "three") .build(); Map<String, AttributeValue> key = simpleKey(); docMappedtable.putItem(r -> r.item(enhancedDocument)).join(); GetItemResponse lowLevelGetBeforeDelete = lowLevelClient.getItem(r -> r.key(key).tableName(tableName)).join(); EnhancedDocument beforeDeleteResult = docMappedtable.deleteItem(Key.builder().partitionValue("id-value").sortValue("sort-value").build()).join(); EnhancedDocument afterDeleteDoc = docMappedtable.getItem(Key.builder().partitionValue("id-value").sortValue("sort-value").build()).join(); GetItemResponse lowLevelGetAfterDelete = lowLevelClient.getItem(r -> r.key(key).tableName(tableName)).join(); assertThat(enhancedDocument.toMap(), is(EnhancedDocument.fromAttributeValueMap(lowLevelGetBeforeDelete.item()).toMap())); assertThat(beforeDeleteResult.toMap(), is(enhancedDocument.toMap())); assertThat(beforeDeleteResult.toMap(), is(lowLevelGetBeforeDelete.item())); assertThat(afterDeleteDoc, is(nullValue())); assertThat(lowLevelGetAfterDelete.item().size(), is(0)); } @Test public void putThenDeleteItem_usingKeyItemForm() { EnhancedDocument enhancedDocument = appendKeysToDoc(testData).toBuilder() .putString("attribute", "one") .putString("attribute2", "two") .putString("attribute3", "three") .build(); docMappedtable.putItem(enhancedDocument).join(); EnhancedDocument beforeDeleteResult = docMappedtable.deleteItem(enhancedDocument).join(); EnhancedDocument afterDeleteResult = docMappedtable.getItem(Key.builder().partitionValue("id-value").sortValue("sort-value").build()).join(); assertThat(beforeDeleteResult.toMap(), is(enhancedDocument.toMap())); assertThat(afterDeleteResult, is(nullValue())); Map<String, AttributeValue> key = simpleKey(); GetItemResponse lowLevelGetBeforeDelete = lowLevelClient.getItem(r -> r.key(key).tableName(tableName)).join(); assertThat(lowLevelGetBeforeDelete.item().size(), is(0)); } @Test public void putWithConditionThatSucceeds() { EnhancedDocument enhancedDocument = appendKeysToDoc(testData).toBuilder() .putString("attribute", "one") .putString("attribute2", "two") .putString("attribute3", "three") .build(); docMappedtable.putItem(r -> r.item(enhancedDocument)).join(); EnhancedDocument newDoc = enhancedDocument.toBuilder().putString("attribute", "four").build(); Expression conditionExpression = Expression.builder() .expression("#key = :value OR #key1 = :value1") .putExpressionName("#key", "attribute") .putExpressionName("#key1", ATTRIBUTE_NAME_WITH_SPECIAL_CHARACTERS) .putExpressionValue(":value", stringValue("one")) .putExpressionValue(":value1", stringValue("three")) .build(); docMappedtable.putItem(PutItemEnhancedRequest.builder(EnhancedDocument.class) .item(newDoc) .conditionExpression(conditionExpression).build()).join(); EnhancedDocument result = docMappedtable.getItem(r -> r.key(k -> k.partitionValue("id-value").sortValue("sort-value"))).join(); assertThat(result.toMap(), is(newDoc.toMap())); } @Test public void putWithConditionThatFails() throws ExecutionException, InterruptedException { EnhancedDocument enhancedDocument = appendKeysToDoc(testData).toBuilder() .putString("attribute", "one") .putString("attribute2", "two") .putString("attribute3", "three") .build(); docMappedtable.putItem(r -> r.item(enhancedDocument)).join(); EnhancedDocument newDoc = enhancedDocument.toBuilder().putString("attribute", "four").build(); Expression conditionExpression = Expression.builder() .expression("#key = :value OR #key1 = :value1") .putExpressionName("#key", "attribute") .putExpressionName("#key1", ATTRIBUTE_NAME_WITH_SPECIAL_CHARACTERS) .putExpressionValue(":value", stringValue("wrong")) .putExpressionValue(":value1", stringValue("wrong")) .build(); exception.expect(CompletionException.class); exception.expectCause(instanceOf(ConditionalCheckFailedException.class)); docMappedtable.putItem(PutItemEnhancedRequest.builder(EnhancedDocument.class) .item(newDoc) .conditionExpression(conditionExpression).build()).join(); } @Test public void deleteNonExistentItem() { EnhancedDocument result = docMappedtable.deleteItem(r -> r.key(k -> k.partitionValue("id-value").sortValue("sort-value"))).join(); assertThat(result, is(nullValue())); } @Test public void deleteWithConditionThatSucceeds() { EnhancedDocument enhancedDocument = appendKeysToDoc(testData).toBuilder() .putString("attribute", "one") .putString("attribute2", "two") .putString(ATTRIBUTE_NAME_WITH_SPECIAL_CHARACTERS, "three") .build(); docMappedtable.putItem(r -> r.item(enhancedDocument)).join(); Expression conditionExpression = Expression.builder() .expression("#key = :value OR #key1 = :value1") .putExpressionName("#key", "attribute") .putExpressionName("#key1", ATTRIBUTE_NAME_WITH_SPECIAL_CHARACTERS) .putExpressionValue(":value", stringValue("wrong")) .putExpressionValue(":value1", stringValue("three")) .build(); Key key = docMappedtable.keyFrom(enhancedDocument); docMappedtable.deleteItem(DeleteItemEnhancedRequest.builder().key(key).conditionExpression(conditionExpression).build()).join(); EnhancedDocument result = docMappedtable.getItem(r -> r.key(key)).join(); assertThat(result, is(nullValue())); } @Test public void deleteWithConditionThatFails() { EnhancedDocument enhancedDocument = appendKeysToDoc(testData).toBuilder() .putString("attribute", "one") .putString("attribute2", "two") .putString(ATTRIBUTE_NAME_WITH_SPECIAL_CHARACTERS, "three") .build(); docMappedtable.putItem(r -> r.item(enhancedDocument)).join(); Expression conditionExpression = Expression.builder() .expression("#key = :value OR #key1 = :value1") .putExpressionName("#key", "attribute") .putExpressionName("#key1", ATTRIBUTE_NAME_WITH_SPECIAL_CHARACTERS) .putExpressionValue(":value", stringValue("wrong")) .putExpressionValue(":value1", stringValue("wrong")) .build(); exception.expect(CompletionException.class); exception.expectCause(instanceOf(ConditionalCheckFailedException.class)); docMappedtable.deleteItem(DeleteItemEnhancedRequest.builder().key(docMappedtable.keyFrom(enhancedDocument)) .conditionExpression(conditionExpression) .build()).join(); } @Test public void updateOverwriteCompleteRecord_usingShortcutForm() { EnhancedDocument enhancedDocument = appendKeysToDoc(testData).toBuilder() .putString("attribute", "one") .putString("attribute2", "two") .putString(ATTRIBUTE_NAME_WITH_SPECIAL_CHARACTERS, "three") .build(); docMappedtable.putItem(enhancedDocument).join(); // Updating new Items other than the one present in testData EnhancedDocument.Builder updateDocBuilder = EnhancedDocument.builder() .attributeConverterProviders(defaultProvider()) .putString("id", "id-value") .putString("sort", "sort-value") .putString("attribute", "four") .putString("attribute2", "five") .putString(ATTRIBUTE_NAME_WITH_SPECIAL_CHARACTERS, "six"); EnhancedDocument expectedDocument = updateDocBuilder.build(); // Explicitly Nullify each of the previous members testData.getEnhancedDocument().toMap().keySet().forEach(r -> { updateDocBuilder.putNull(r); }); EnhancedDocument updateDocument = updateDocBuilder.build(); EnhancedDocument result = docMappedtable.updateItem(updateDocument).join(); assertThat(result.toMap(), is(expectedDocument.toMap())); assertThat(result.toJson(), is("{\"a*t:t.r-i#bute+3/4(&?5=@)<6>!ch$ar%\":\"six\",\"attribute\":\"four\"," + "\"attribute2\":\"five\",\"id\":\"id-value\",\"sort\":\"sort-value\"}")); } @Test public void updateCreatePartialRecord() { EnhancedDocument.Builder docBuilder = appendKeysToDoc(testData).toBuilder() .putString("attribute", "one"); EnhancedDocument updateDoc = docBuilder.build(); /** * Explicitly removing AttributeNull Value that are added in testData for testing. * This should not be treated as Null in partial update, because for a Document, an AttributeValue.fromNul(true) with a * Null value is treated as Null or non-existent during updateItem. */ testData.getEnhancedDocument().toMap().entrySet().forEach(entry -> { if (AttributeValue.fromNul(true).equals(entry.getValue())) { docBuilder.remove(entry.getKey()); } }); EnhancedDocument expectedDocUpdate = docBuilder.build(); EnhancedDocument result = docMappedtable.updateItem(r -> r.item(updateDoc)).join(); assertThat(result.toMap(), is(expectedDocUpdate.toMap())); } @Test public void updateCreateKeyOnlyRecord() { EnhancedDocument.Builder updateDocBuilder = appendKeysToDoc(testData).toBuilder(); EnhancedDocument expectedDocument = EnhancedDocument.builder() .attributeConverterProviders(defaultProvider()) .putString("id", "id-value") .putString("sort", "sort-value").build(); testData.getEnhancedDocument().toMap().keySet().forEach(r -> { updateDocBuilder.putNull(r); }); EnhancedDocument cleanedUpDoc = updateDocBuilder.build(); EnhancedDocument result = docMappedtable.updateItem(r -> r.item(cleanedUpDoc)).join(); assertThat(result.toMap(), is(expectedDocument.toMap())); } @Test public void updateOverwriteModelledNulls() { EnhancedDocument enhancedDocument = appendKeysToDoc(testData).toBuilder() .putString("attribute", "one") .putString("attribute2", "two") .putString(ATTRIBUTE_NAME_WITH_SPECIAL_CHARACTERS, "three") .build(); docMappedtable.putItem(r -> r.item(enhancedDocument)).join(); EnhancedDocument updateDocument = EnhancedDocument.builder().attributeConverterProviders(defaultProvider()) .putString("id", "id-value") .putString("sort", "sort-value") .putString("attribute", "four") .putNull("attribute2") .putNull(ATTRIBUTE_NAME_WITH_SPECIAL_CHARACTERS).build(); EnhancedDocument result = docMappedtable.updateItem(r -> r.item(updateDocument)).join(); assertThat(result.isPresent("attribute2"), is(false)); assertThat(result.isPresent(ATTRIBUTE_NAME_WITH_SPECIAL_CHARACTERS), is(false)); assertThat(result.getString("attribute"), is("four")); testData.getEnhancedDocument().toMap().entrySet().forEach(entry -> { if (AttributeValue.fromNul(true).equals(entry.getValue())) { assertThat(result.isPresent(entry.getKey()), is(true)); } else { assertThat(result.toMap().get(entry.getKey()), is(testData.getDdbItemMap().get(entry.getKey()))); } }); } @Test public void updateCanIgnoreNullsDoesNotIgnoreNullAttributeValues() { EnhancedDocument enhancedDocument = appendKeysToDoc(testData).toBuilder() .putString("attribute", "one") .putString("attribute2", "two") .putString(ATTRIBUTE_NAME_WITH_SPECIAL_CHARACTERS, "three") .build(); docMappedtable.putItem(r -> r.item(enhancedDocument)).join(); EnhancedDocument updateDocument = EnhancedDocument.builder() .putString("id", "id-value") .putString("sort", "sort-value") .putNull("attribute") .putNull(ATTRIBUTE_NAME_WITH_SPECIAL_CHARACTERS) .build(); EnhancedDocument result = docMappedtable.updateItem(UpdateItemEnhancedRequest.builder(EnhancedDocument.class) .item(updateDocument) .ignoreNulls(true) .build()).join(); EnhancedDocument expectedResult = appendKeysToDoc(testData).toBuilder() .putString("attribute2", "two") .build(); assertThat(result.toMap(), is(expectedResult.toMap())); } @Test public void updateKeyOnlyExistingRecordDoesNothing() { EnhancedDocument enhancedDocument = appendKeysToDoc(testData); docMappedtable.putItem(r -> r.item(enhancedDocument)).join(); EnhancedDocument hashKeyAndSortOnly = EnhancedDocument.builder() .putString("id", "id-value") .putString("sort", "sort-value").build(); EnhancedDocument result = docMappedtable.updateItem(UpdateItemEnhancedRequest.builder(EnhancedDocument.class) .item(hashKeyAndSortOnly) .ignoreNulls(true) .build()).join(); assertThat(result.toMap(), is(enhancedDocument.toMap())); } @Test public void updateWithConditionThatSucceeds() { EnhancedDocument enhancedDocument = appendKeysToDoc(testData).toBuilder() .putString("attribute", "one") .putString("attribute2", "two") .putString(ATTRIBUTE_NAME_WITH_SPECIAL_CHARACTERS, "three") .build(); docMappedtable.putItem(r -> r.item(enhancedDocument)).join(); EnhancedDocument newDoc = EnhancedDocument.builder() .attributeConverterProviders(defaultProvider()) .putString("id", "id-value") .putString("sort", "sort-value") .putString("attribute", "four") .build(); Expression conditionExpression = Expression.builder() .expression("#key = :value OR #key1 = :value1") .putExpressionName("#key", "attribute") .putExpressionName("#key1", ATTRIBUTE_NAME_WITH_SPECIAL_CHARACTERS) .putExpressionValue(":value", stringValue("wrong")) .putExpressionValue(":value1", stringValue("three")) .build(); docMappedtable.updateItem(UpdateItemEnhancedRequest.builder(EnhancedDocument.class) .item(newDoc) .conditionExpression(conditionExpression) .build()).join(); EnhancedDocument result = docMappedtable.getItem(r -> r.key(k -> k.partitionValue("id-value").sortValue("sort-value"))).join(); assertThat(result.toMap(), is(enhancedDocument.toBuilder().putString("attribute", "four").build().toMap())); } @Test public void updateWithConditionThatFails() { EnhancedDocument enhancedDocument = appendKeysToDoc(testData).toBuilder() .putString("attribute", "one") .putString("attribute2", "two") .putString(ATTRIBUTE_NAME_WITH_SPECIAL_CHARACTERS, "three") .build(); docMappedtable.putItem(r -> r.item(enhancedDocument)).join(); EnhancedDocument newDoc = EnhancedDocument.builder() .attributeConverterProviders(defaultProvider()) .putString("id", "id-value") .putString("sort", "sort-value") .putString("attribute", "four") .build(); Expression conditionExpression = Expression.builder() .expression("#key = :value OR #key1 = :value1") .putExpressionName("#key", "attribute") .putExpressionName("#key1", ATTRIBUTE_NAME_WITH_SPECIAL_CHARACTERS) .putExpressionValue(":value", stringValue("wrong")) .putExpressionValue(":value1", stringValue("wrong")) .build(); exception.expect(CompletionException.class); exception.expectCause(instanceOf(ConditionalCheckFailedException.class)); docMappedtable.updateItem(UpdateItemEnhancedRequest.builder(EnhancedDocument.class) .item(newDoc) .conditionExpression(conditionExpression) .build()).join(); } }
4,192
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/document/IndexQueryTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests.document; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static software.amazon.awssdk.enhanced.dynamodb.AttributeConverterProvider.defaultProvider; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.numberValue; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.stringValue; import static software.amazon.awssdk.enhanced.dynamodb.model.QueryConditional.keyEqualTo; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbIndex; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.Key; import software.amazon.awssdk.enhanced.dynamodb.TableMetadata; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.document.EnhancedDocument; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.LocalDynamoDbSyncTestBase; import software.amazon.awssdk.enhanced.dynamodb.model.CreateTableEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.EnhancedGlobalSecondaryIndex; import software.amazon.awssdk.enhanced.dynamodb.model.Page; import software.amazon.awssdk.enhanced.dynamodb.model.QueryConditional; import software.amazon.awssdk.enhanced.dynamodb.model.QueryEnhancedRequest; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; import software.amazon.awssdk.services.dynamodb.model.ProjectionType; public class IndexQueryTest extends LocalDynamoDbSyncTestBase { private DynamoDbClient lowLevelClient; private DynamoDbTable<EnhancedDocument> docMappedtable ; @Rule public ExpectedException exception = ExpectedException.none(); private DynamoDbEnhancedClient enhancedClient; private final String tableName = getConcreteTableName("doc-table-name"); DynamoDbIndex<EnhancedDocument> keysOnlyMappedIndex ; @Before public void createTable() { lowLevelClient = getDynamoDbClient(); enhancedClient = DynamoDbEnhancedClient.builder() .dynamoDbClient(lowLevelClient) .build(); docMappedtable = enhancedClient.table(tableName, TableSchema.documentSchemaBuilder() .attributeConverterProviders(defaultProvider()) .addIndexPartitionKey(TableMetadata.primaryIndexName(), "id", AttributeValueType.S) .addIndexSortKey(TableMetadata.primaryIndexName(), "sort", AttributeValueType.N) .addIndexPartitionKey("gsi_keys_only", "gsi_id", AttributeValueType.S) .addIndexSortKey("gsi_keys_only", "gsi_sort", AttributeValueType.N) .attributeConverterProviders(defaultProvider()) .build()); docMappedtable.createTable(CreateTableEnhancedRequest.builder() .provisionedThroughput(getDefaultProvisionedThroughput()) .globalSecondaryIndices( EnhancedGlobalSecondaryIndex.builder() .indexName("gsi_keys_only") .projection(p -> p.projectionType(ProjectionType.KEYS_ONLY)) .provisionedThroughput(getDefaultProvisionedThroughput()) .build()) .build()); keysOnlyMappedIndex = docMappedtable.index("gsi_keys_only"); } private static final List<EnhancedDocument> DOCUMENTS = IntStream.range(0, 10) .mapToObj(i -> EnhancedDocument.builder() .attributeConverterProviders(defaultProvider()) .putString("id", "id-value") .putNumber("sort", i) .putNumber("value", i) .putString("gsi_id", "gsi-id-value") .putNumber("gsi_sort", i) .build() ).collect(Collectors.toList()); private static final List<EnhancedDocument> KEYS_ONLY_DOCUMENTS = DOCUMENTS.stream() .map(record -> EnhancedDocument.builder() .attributeConverterProviders(defaultProvider()) .putString("id", record.getString("id")) .putNumber("sort", record.getNumber("sort")) .putString("gsi_id", record.getString("gsi_id")) .putNumber("gsi_sort", record.getNumber("gsi_sort")).build() ) .collect(Collectors.toList()); private void insertDocuments() { DOCUMENTS.forEach(document -> docMappedtable.putItem(r -> r.item(document))); } @After public void deleteTable() { getDynamoDbClient().deleteTable(DeleteTableRequest.builder() .tableName(tableName) .build()); } @Test public void queryAllRecordsDefaultSettings_usingShortcutForm() { insertDocuments(); Iterator<Page<EnhancedDocument>> results = keysOnlyMappedIndex.query(keyEqualTo(k -> k.partitionValue("gsi-id-value"))).iterator(); assertThat(results.hasNext(), is(true)); Page<EnhancedDocument> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items().stream().map(i -> i.toMap()).collect(Collectors.toList()), is(KEYS_ONLY_DOCUMENTS.stream().map(i -> i.toMap()).collect(Collectors.toList()))); assertThat(page.lastEvaluatedKey(), is(nullValue())); } @Test public void queryBetween() { insertDocuments(); Key fromKey = Key.builder().partitionValue("gsi-id-value").sortValue(3).build(); Key toKey = Key.builder().partitionValue("gsi-id-value").sortValue(5).build(); Iterator<Page<EnhancedDocument>> results = keysOnlyMappedIndex.query(r -> r.queryConditional(QueryConditional.sortBetween(fromKey, toKey))).iterator(); assertThat(results.hasNext(), is(true)); Page<EnhancedDocument> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items().stream().map(i -> i.toMap()).collect(Collectors.toList()), is(KEYS_ONLY_DOCUMENTS.stream().filter(r -> r.getNumber("sort").intValue() >= 3 && r.getNumber("sort").intValue() <= 5) .map( j -> j.toMap()).collect(Collectors.toList()))); assertThat(page.lastEvaluatedKey(), is(nullValue())); } @Test public void queryLimit() { insertDocuments(); Iterator<Page<EnhancedDocument>> results = keysOnlyMappedIndex.query(QueryEnhancedRequest.builder() .queryConditional(keyEqualTo(k -> k.partitionValue("gsi-id-value"))) .limit(5) .build()) .iterator(); assertThat(results.hasNext(), is(true)); Page<EnhancedDocument> page1 = results.next(); assertThat(results.hasNext(), is(true)); Page<EnhancedDocument> page2 = results.next(); assertThat(results.hasNext(), is(true)); Page<EnhancedDocument> page3 = results.next(); assertThat(results.hasNext(), is(false)); Map<String, AttributeValue> expectedLastEvaluatedKey1 = new HashMap<>(); expectedLastEvaluatedKey1.put("id", stringValue(KEYS_ONLY_DOCUMENTS.get(4).getString("id"))); expectedLastEvaluatedKey1.put("sort", numberValue(KEYS_ONLY_DOCUMENTS.get(4).getNumber("sort"))); expectedLastEvaluatedKey1.put("gsi_id", stringValue(KEYS_ONLY_DOCUMENTS.get(4).getString("gsi_id"))); expectedLastEvaluatedKey1.put("gsi_sort", numberValue(KEYS_ONLY_DOCUMENTS.get(4).getNumber("gsi_sort"))); Map<String, AttributeValue> expectedLastEvaluatedKey2 = new HashMap<>(); expectedLastEvaluatedKey2.put("id", stringValue(KEYS_ONLY_DOCUMENTS.get(9).getString("id"))); expectedLastEvaluatedKey2.put("sort", numberValue(KEYS_ONLY_DOCUMENTS.get(9).getNumber("sort"))); expectedLastEvaluatedKey2.put("gsi_id", stringValue(KEYS_ONLY_DOCUMENTS.get(9).getString("gsi_id"))); expectedLastEvaluatedKey2.put("gsi_sort", numberValue(KEYS_ONLY_DOCUMENTS.get(9).getNumber("gsi_sort"))); assertThat(page1.items().stream().map(i -> i.toMap()).collect(Collectors.toList()), is(KEYS_ONLY_DOCUMENTS.subList(0, 5).stream().map( i -> i.toMap()).collect(Collectors.toList()))); assertThat(page1.lastEvaluatedKey(), is(expectedLastEvaluatedKey1)); assertThat(page2.items().stream().map(i -> i.toMap()).collect(Collectors.toList()), is(KEYS_ONLY_DOCUMENTS.subList(5, 10).stream().map( i -> i.toMap()).collect(Collectors.toList()))); assertThat(page2.lastEvaluatedKey(), is(expectedLastEvaluatedKey2)); assertThat(page3.items().stream().map(i -> i.toMap()).collect(Collectors.toList()), is(empty())); assertThat(page3.lastEvaluatedKey(), is(nullValue())); } @Test public void queryEmpty() { Iterator<Page<EnhancedDocument>> results = keysOnlyMappedIndex.query(r -> r.queryConditional(keyEqualTo(k -> k.partitionValue("gsi-id-value")))).iterator(); assertThat(results.hasNext(), is(true)); Page<EnhancedDocument> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items(), is(empty())); assertThat(page.lastEvaluatedKey(), is(nullValue())); } @Test public void queryExclusiveStartKey() { insertDocuments(); Map<String, AttributeValue> expectedLastEvaluatedKey = new HashMap<>(); expectedLastEvaluatedKey.put("id", stringValue(KEYS_ONLY_DOCUMENTS.get(7).getString("id"))); expectedLastEvaluatedKey.put("sort", numberValue(KEYS_ONLY_DOCUMENTS.get(7).getNumber("sort"))); expectedLastEvaluatedKey.put("gsi_id", stringValue(KEYS_ONLY_DOCUMENTS.get(7).getString("gsi_id"))); expectedLastEvaluatedKey.put("gsi_sort", numberValue(KEYS_ONLY_DOCUMENTS.get(7).getNumber("gsi_sort"))); Iterator<Page<EnhancedDocument>> results = keysOnlyMappedIndex.query(QueryEnhancedRequest.builder() .queryConditional(keyEqualTo(k -> k.partitionValue("gsi-id-value"))) .exclusiveStartKey(expectedLastEvaluatedKey).build()) .iterator(); assertThat(results.hasNext(), is(true)); Page<EnhancedDocument> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items().stream().map(i -> i.toMap()).collect(Collectors.toList()), is(KEYS_ONLY_DOCUMENTS.subList(8, 10).stream().map(i -> i.toMap()).collect(Collectors.toList()))); assertThat(page.lastEvaluatedKey(), is(nullValue())); } }
4,193
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/document/BasicQueryTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests.document; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static software.amazon.awssdk.enhanced.dynamodb.AttributeConverterProvider.defaultProvider; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.numberValue; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.stringValue; import static software.amazon.awssdk.enhanced.dynamodb.model.QueryConditional.keyEqualTo; import static software.amazon.awssdk.enhanced.dynamodb.model.QueryConditional.sortBetween; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import software.amazon.awssdk.core.pagination.sync.SdkIterable; import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.Expression; import software.amazon.awssdk.enhanced.dynamodb.Key; import software.amazon.awssdk.enhanced.dynamodb.NestedAttributeName; import software.amazon.awssdk.enhanced.dynamodb.TableMetadata; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.document.EnhancedDocument; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.LocalDynamoDbSyncTestBase; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.InnerAttribConverterProvider; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.InnerAttributeRecord; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.NestedTestRecord; import software.amazon.awssdk.enhanced.dynamodb.model.Page; import software.amazon.awssdk.enhanced.dynamodb.model.PageIterable; import software.amazon.awssdk.enhanced.dynamodb.model.QueryEnhancedRequest; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; public class BasicQueryTest extends LocalDynamoDbSyncTestBase { private DynamoDbClient lowLevelClient; private DynamoDbTable<EnhancedDocument> docMappedtable ; private DynamoDbTable<EnhancedDocument> neseteddocMappedtable ; @Rule public ExpectedException exception = ExpectedException.none(); private DynamoDbEnhancedClient enhancedClient; private final String tableName = getConcreteTableName("doc-table-name"); private final String nestedTableName = getConcreteTableName("doc-nested-table-name"); @Before public void createTable() { lowLevelClient = getDynamoDbClient(); enhancedClient = DynamoDbEnhancedClient.builder() .dynamoDbClient(lowLevelClient) .build(); docMappedtable = enhancedClient.table(tableName, TableSchema.documentSchemaBuilder() .attributeConverterProviders(defaultProvider()) .addIndexPartitionKey(TableMetadata.primaryIndexName(), "id", AttributeValueType.S) .addIndexSortKey(TableMetadata.primaryIndexName(), "sort", AttributeValueType.N) .attributeConverterProviders(defaultProvider()) .build()); docMappedtable.createTable(); neseteddocMappedtable = enhancedClient.table(nestedTableName, TableSchema.documentSchemaBuilder() .attributeConverterProviders( new InnerAttribConverterProvider<>(), defaultProvider()) .addIndexPartitionKey(TableMetadata.primaryIndexName(), "outerAttribOne", AttributeValueType.S) .addIndexSortKey(TableMetadata.primaryIndexName(), "sort", AttributeValueType.N) .build()); neseteddocMappedtable.createTable(); } @After public void deleteTable() { getDynamoDbClient().deleteTable(DeleteTableRequest.builder() .tableName(tableName) .build()); getDynamoDbClient().deleteTable(DeleteTableRequest.builder() .tableName(nestedTableName) .build()); } private static final List<EnhancedDocument> DOCUMENTS = IntStream.range(0, 10) .mapToObj(i -> EnhancedDocument.builder() .putString("id", "id-value") .putNumber("sort", i) .putNumber("value", i) .build() ).collect(Collectors.toList()); private static final List<EnhancedDocument> DOCUMENTS_WITH_PROVIDERS = IntStream.range(0, 10) .mapToObj(i -> EnhancedDocument.builder() .attributeConverterProviders(defaultProvider()) .putString("id", "id-value") .putNumber("sort", i) .putNumber("value", i) .build() ).collect(Collectors.toList()); public static EnhancedDocument createDocumentFromNestedRecord(NestedTestRecord nestedTestRecord){ EnhancedDocument.Builder enhancedDocument = EnhancedDocument.builder(); if (nestedTestRecord.getOuterAttribOne() != null) { enhancedDocument.putString("outerAttribOne", nestedTestRecord.getOuterAttribOne()); } if (nestedTestRecord.getSort() != null) { enhancedDocument.putNumber("sort", nestedTestRecord.getSort()); } if (nestedTestRecord.getDotVariable() != null) { enhancedDocument.putString("test.com", nestedTestRecord.getDotVariable()); } InnerAttributeRecord innerAttributeRecord = nestedTestRecord.getInnerAttributeRecord(); if (innerAttributeRecord != null) { enhancedDocument.put("innerAttributeRecord", innerAttributeRecord, EnhancedType.of(InnerAttributeRecord.class)); } return enhancedDocument.build(); } private static final List<EnhancedDocument> NESTED_TEST_DOCUMENTS = IntStream.range(0, 10) .mapToObj(i -> { final NestedTestRecord nestedTestRecord = new NestedTestRecord(); nestedTestRecord.setOuterAttribOne("id-value-" + i); nestedTestRecord.setSort(i); final InnerAttributeRecord innerAttributeRecord = new InnerAttributeRecord(); innerAttributeRecord.setAttribOne("attribOne-"+i); innerAttributeRecord.setAttribTwo(i); nestedTestRecord.setInnerAttributeRecord(innerAttributeRecord); nestedTestRecord.setDotVariable("v"+i); return nestedTestRecord; }) .map(BasicQueryTest::createDocumentFromNestedRecord) .collect(Collectors.toList()); private static final List<NestedTestRecord> NESTED_TEST_RECORDS = IntStream.range(0, 10) .mapToObj(i -> { final NestedTestRecord nestedTestRecord = new NestedTestRecord(); nestedTestRecord.setOuterAttribOne("id-value-" + i); nestedTestRecord.setSort(i); final InnerAttributeRecord innerAttributeRecord = new InnerAttributeRecord(); innerAttributeRecord.setAttribOne("attribOne-"+i); innerAttributeRecord.setAttribTwo(i); nestedTestRecord.setInnerAttributeRecord(innerAttributeRecord); nestedTestRecord.setDotVariable("v"+i); return nestedTestRecord; }) .collect(Collectors.toList()); private void insertDocuments() { DOCUMENTS.forEach(document -> docMappedtable.putItem(r -> r.item(document))); NESTED_TEST_DOCUMENTS.forEach(nestedDocs -> neseteddocMappedtable.putItem(r -> r.item(nestedDocs))); } private void insertNestedDocuments() { NESTED_TEST_DOCUMENTS.forEach(nestedDocs -> neseteddocMappedtable.putItem(r -> r.item(nestedDocs))); } @Test public void queryAllRecordsDefaultSettings_shortcutForm() { insertDocuments(); Iterator<Page<EnhancedDocument>> results = docMappedtable.query(keyEqualTo(k -> k.partitionValue("id-value"))).iterator(); assertThat(results.hasNext(), is(true)); Page<EnhancedDocument> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items().stream().map(i -> i.toJson()).collect(Collectors.toList()), is(DOCUMENTS.stream().map(i -> i .toBuilder() .attributeConverterProviders(new InnerAttribConverterProvider<>(), defaultProvider()) .build() .toJson()).collect(Collectors.toList()))); assertThat(page.lastEvaluatedKey(), is(nullValue())); } @Test public void queryAllRecordsDefaultSettings_withProjection() { insertDocuments(); Iterator<Page<EnhancedDocument>> results = docMappedtable.query(b -> b .queryConditional(keyEqualTo(k -> k.partitionValue("id-value"))) .attributesToProject("value") ).iterator(); assertThat(results.hasNext(), is(true)); Page<EnhancedDocument> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items().size(), is(DOCUMENTS.size())); EnhancedDocument firstRecord = page.items().get(0); assertThat(firstRecord.getString("id"), is(nullValue())); assertThat(firstRecord.getNumber("sort"), is(nullValue())); assertThat(firstRecord.getNumber("value").intValue(), is(0)); } @Test public void queryAllRecordsDefaultSettings_shortcutForm_viaItems() { insertDocuments(); PageIterable<EnhancedDocument> query = docMappedtable.query(keyEqualTo(k -> k.partitionValue("id-value"))); SdkIterable<EnhancedDocument> results = query.items(); assertThat(results.stream().map(i -> i.toJson()).collect(Collectors.toList()), is(DOCUMENTS.stream().map(i -> i .toBuilder() .attributeConverterProviders(new InnerAttribConverterProvider<>(), defaultProvider()) .build() .toJson()).collect(Collectors.toList()))); } @Test public void queryAllRecordsWithFilter() { insertDocuments(); Map<String, AttributeValue> expressionValues = new HashMap<>(); expressionValues.put(":min_value", numberValue(3)); expressionValues.put(":max_value", numberValue(5)); Expression expression = Expression.builder() .expression("#value >= :min_value AND #value <= :max_value") .expressionValues(expressionValues) .expressionNames(Collections.singletonMap("#value", "value")) .build(); Iterator<Page<EnhancedDocument>> results = docMappedtable.query(QueryEnhancedRequest.builder() .queryConditional(keyEqualTo(k -> k.partitionValue("id-value"))) .filterExpression(expression) .build()) .iterator(); assertThat(results.hasNext(), is(true)); Page<EnhancedDocument> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items().stream().map(i -> i.toJson()).collect(Collectors.toList()), is(DOCUMENTS_WITH_PROVIDERS.stream().filter(r -> r.getNumber("sort").intValue() >= 3 && r.getNumber("sort").intValue() <= 5) .map(doc -> doc.toJson()) .collect(Collectors.toList()))); assertThat(page.lastEvaluatedKey(), is(nullValue())); } @Test public void queryAllRecordsWithFilterAndProjection() { insertDocuments(); Map<String, AttributeValue> expressionValues = new HashMap<>(); expressionValues.put(":min_value", numberValue(3)); expressionValues.put(":max_value", numberValue(5)); Expression expression = Expression.builder() .expression("#value >= :min_value AND #value <= :max_value") .expressionValues(expressionValues) .expressionNames(Collections.singletonMap("#value", "value")) .build(); Iterator<Page<EnhancedDocument>> results = docMappedtable.query(QueryEnhancedRequest.builder() .queryConditional(keyEqualTo(k -> k.partitionValue("id-value"))) .filterExpression(expression) .attributesToProject("value") .build()) .iterator(); assertThat(results.hasNext(), is(true)); Page<EnhancedDocument> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items(), hasSize(3)); assertThat(page.lastEvaluatedKey(), is(nullValue())); EnhancedDocument record = page.items().get(0); assertThat(record.getString("id"), nullValue()); assertThat(record.getNumber("sort"), nullValue()); assertThat(record.getNumber("value").intValue(), is(3)); } @Test public void queryBetween() { insertDocuments(); Key fromKey = Key.builder().partitionValue("id-value").sortValue(3).build(); Key toKey = Key.builder().partitionValue("id-value").sortValue(5).build(); Iterator<Page<EnhancedDocument>> results = docMappedtable.query(r -> r.queryConditional(sortBetween(fromKey, toKey))).iterator(); assertThat(results.hasNext(), is(true)); Page<EnhancedDocument> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items().stream().map(i -> i.toJson()).collect(Collectors.toList()), is(DOCUMENTS_WITH_PROVIDERS.stream().filter(r -> r.getNumber("sort").intValue() >= 3 && r.getNumber("sort").intValue() <= 5) .map(doc -> doc.toJson()) .collect(Collectors.toList()))); assertThat(page.lastEvaluatedKey(), is(nullValue())); } @Test public void queryLimit() { insertDocuments(); Iterator<Page<EnhancedDocument>> results = docMappedtable.query(QueryEnhancedRequest.builder() .queryConditional(keyEqualTo(k -> k.partitionValue("id-value"))) .limit(5) .build()) .iterator(); assertThat(results.hasNext(), is(true)); Page<EnhancedDocument> page1 = results.next(); assertThat(results.hasNext(), is(true)); Page<EnhancedDocument> page2 = results.next(); assertThat(results.hasNext(), is(true)); Page<EnhancedDocument> page3 = results.next(); assertThat(results.hasNext(), is(false)); Map<String, AttributeValue> expectedLastEvaluatedKey1 = new HashMap<>(); expectedLastEvaluatedKey1.put("id", stringValue("id-value")); expectedLastEvaluatedKey1.put("sort", numberValue(4)); Map<String, AttributeValue> expectedLastEvaluatedKey2 = new HashMap<>(); expectedLastEvaluatedKey2.put("id", stringValue("id-value")); expectedLastEvaluatedKey2.put("sort", numberValue(9)); assertThat(page1.items().stream().map(i -> i.toJson()).collect(Collectors.toList()), is(DOCUMENTS_WITH_PROVIDERS.subList(0, 5).stream().map( doc -> doc.toJson()).collect(Collectors.toList()))); assertThat(page1.lastEvaluatedKey(), is(expectedLastEvaluatedKey1)); assertThat(page2.items().stream().map(i -> i.toJson()).collect(Collectors.toList()), is(DOCUMENTS_WITH_PROVIDERS.subList(5, 10).stream().map( doc -> doc.toJson()).collect(Collectors.toList()))); assertThat(page2.lastEvaluatedKey(), is(expectedLastEvaluatedKey2)); assertThat(page3.items().stream().map(i -> i.toJson()).collect(Collectors.toList()), is(empty())); assertThat(page3.lastEvaluatedKey(), is(nullValue())); } @Test public void queryEmpty() { Iterator<Page<EnhancedDocument>> results = docMappedtable.query(r -> r.queryConditional(keyEqualTo(k -> k.partitionValue("id-value")))).iterator(); assertThat(results.hasNext(), is(true)); Page<EnhancedDocument> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items(), is(empty())); assertThat(page.lastEvaluatedKey(), is(nullValue())); } @Test public void queryEmpty_viaItems() { PageIterable<EnhancedDocument> query = docMappedtable.query(keyEqualTo(k -> k.partitionValue("id-value"))); SdkIterable<EnhancedDocument> results = query.items(); assertThat(results.stream().collect(Collectors.toList()), is(empty())); } @Test public void queryExclusiveStartKey() { Map<String, AttributeValue> exclusiveStartKey = new HashMap<>(); exclusiveStartKey.put("id", stringValue("id-value")); exclusiveStartKey.put("sort", numberValue(7)); insertDocuments(); Iterator<Page<EnhancedDocument>> results = docMappedtable.query(QueryEnhancedRequest.builder() .queryConditional(keyEqualTo(k -> k.partitionValue("id-value"))) .exclusiveStartKey(exclusiveStartKey) .build()) .iterator(); assertThat(results.hasNext(), is(true)); Page<EnhancedDocument> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items().stream().map(doc -> doc.toJson()).collect(Collectors.toList()), is(DOCUMENTS_WITH_PROVIDERS.subList(8, 10).stream().map(i -> i.toJson()).collect(Collectors.toList()))); assertThat(page.lastEvaluatedKey(), is(nullValue())); } @Test public void queryExclusiveStartKey_viaItems() { Map<String, AttributeValue> exclusiveStartKey = new HashMap<>(); exclusiveStartKey.put("id", stringValue("id-value")); exclusiveStartKey.put("sort", numberValue(7)); insertDocuments(); SdkIterable<EnhancedDocument> results = docMappedtable.query(QueryEnhancedRequest.builder() .queryConditional(keyEqualTo(k -> k.partitionValue("id-value"))) .exclusiveStartKey(exclusiveStartKey) .build()) .items(); assertThat(results.stream().map(doc -> doc.toJson()).collect(Collectors.toList()), is(DOCUMENTS_WITH_PROVIDERS.subList(8, 10).stream().map(i -> i.toJson()).collect(Collectors.toList()))); } @Test public void queryNestedRecord_SingleAttributeName() { insertNestedDocuments(); Iterator<Page<EnhancedDocument>> results = neseteddocMappedtable.query(b -> b .queryConditional(keyEqualTo(k -> k.partitionValue("id-value-1"))) .addNestedAttributeToProject(NestedAttributeName.builder().addElement("innerAttributeRecord") .addElement("attribOne").build())).iterator(); assertThat(results.hasNext(), is(true)); Page<EnhancedDocument> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items().size(), is(1)); EnhancedDocument firstRecord = page.items().get(0); assertThat(firstRecord.getString("outerAttribOne"), is(nullValue())); assertThat(firstRecord.getString("sort"), is(nullValue())); assertThat(firstRecord.get("innerAttributeRecord", EnhancedType.of(InnerAttributeRecord.class)).getAttribOne(), is("attribOne-1")); assertThat(firstRecord.get("innerAttributeRecord", EnhancedType.of(InnerAttributeRecord.class)).getAttribTwo(), is(nullValue())); results = neseteddocMappedtable.query(b -> b .queryConditional(keyEqualTo(k -> k.partitionValue("id-value-1"))) .addAttributeToProject("sort")).iterator(); assertThat(results.hasNext(), is(true)); page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items().size(), is(1)); firstRecord = page.items().get(0); assertThat(firstRecord.getString("outerAttribOne"), is(nullValue())); assertThat(firstRecord.getNumber("sort").intValue(), is(1)); assertThat(firstRecord.get("innerAttributeRecord", EnhancedType.of(InnerAttributeRecord.class)), is(nullValue())); } @Test public void queryNestedRecord_withAttributeNameList() { insertNestedDocuments(); Iterator<Page<EnhancedDocument>> results = neseteddocMappedtable.query(b -> b .queryConditional(keyEqualTo(k -> k.partitionValue("id-value-1"))) .addNestedAttributesToProject(Arrays.asList( NestedAttributeName.builder().elements("innerAttributeRecord", "attribOne").build(), NestedAttributeName.builder().addElement("outerAttribOne").build())) .addNestedAttributesToProject(NestedAttributeName.builder() .addElements(Arrays.asList("innerAttributeRecord", "attribTwo")).build())).iterator(); assertThat(results.hasNext(), is(true)); Page<EnhancedDocument> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items().size(), is(1)); EnhancedDocument firstRecord = page.items().get(0); assertThat(firstRecord.getString("outerAttribOne"), is("id-value-1")); assertThat(firstRecord.getNumber("sort"), is(nullValue())); assertThat(firstRecord.get("innerAttributeRecord", EnhancedType.of(InnerAttributeRecord.class)).getAttribOne(), is( "attribOne-1")); assertThat(firstRecord.get("innerAttributeRecord", EnhancedType.of(InnerAttributeRecord.class)).getAttribTwo(), is(1)); } @Test public void queryNestedRecord_withAttributeNameListAndStringAttributeToProjectAppended() { insertNestedDocuments(); Iterator<Page<EnhancedDocument>> results = neseteddocMappedtable.query(b -> b .queryConditional(keyEqualTo(k -> k.partitionValue("id-value-1"))) .addNestedAttributesToProject(Arrays.asList( NestedAttributeName.builder().elements("innerAttributeRecord","attribOne").build())) .addNestedAttributesToProject(NestedAttributeName.create("innerAttributeRecord","attribTwo")) .addAttributeToProject("sort")).iterator(); assertThat(results.hasNext(), is(true)); Page<EnhancedDocument> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items().size(), is(1)); EnhancedDocument firstRecord = page.items().get(0); assertThat(firstRecord.getString("outerAttribOne"), is(is(nullValue()))); assertThat(firstRecord.getNumber("sort").intValue(), is(1)); assertThat(firstRecord.get("innerAttributeRecord", EnhancedType.of(InnerAttributeRecord.class)).getAttribOne(), is( "attribOne-1")); assertThat(firstRecord.get("innerAttributeRecord", EnhancedType.of(InnerAttributeRecord.class)).getAttribTwo(), is(1)); } @Test public void queryAllRecordsDefaultSettings_withNestedProjectionNamesNotInNameMap() { insertNestedDocuments(); Iterator<Page<EnhancedDocument>> results = neseteddocMappedtable.query(b -> b .queryConditional(keyEqualTo(k -> k.partitionValue("id-value-1"))) .addNestedAttributeToProject( NestedAttributeName.builder().addElement("nonExistentSlot").build())).iterator(); assertThat(results.hasNext(), is(true)); Page<EnhancedDocument> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items().size(), is(1)); EnhancedDocument firstRecord = page.items().get(0); assertThat(firstRecord, is(nullValue())); } @Test public void queryRecordDefaultSettings_withDotInTheName() { insertNestedDocuments(); Iterator<Page<EnhancedDocument>> results = neseteddocMappedtable.query(b -> b .queryConditional(keyEqualTo(k -> k.partitionValue("id-value-7"))) .addNestedAttributeToProject( NestedAttributeName.create("test.com"))).iterator(); assertThat(results.hasNext(), is(true)); Page<EnhancedDocument> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items().size(), is(1)); EnhancedDocument firstRecord = page.items().get(0); assertThat(firstRecord.getString("outerAttribOne"), is(is(nullValue()))); assertThat(firstRecord.getNumber("sort"), is(is(nullValue()))); assertThat(firstRecord.get("innerAttributeRecord", EnhancedType.of(InnerAttributeRecord.class)) , is(nullValue())); assertThat(firstRecord.getString("test.com"), is("v7")); Iterator<Page<EnhancedDocument>> resultWithAttributeToProject = neseteddocMappedtable.query(b -> b .queryConditional(keyEqualTo(k -> k.partitionValue("id-value-7"))) .attributesToProject( "test.com").build()).iterator(); assertThat(resultWithAttributeToProject.hasNext(), is(true)); Page<EnhancedDocument> pageResult = resultWithAttributeToProject.next(); assertThat(resultWithAttributeToProject.hasNext(), is(false)); assertThat(pageResult.items().size(), is(1)); EnhancedDocument record = pageResult.items().get(0); assertThat(record.getString("outerAttribOne"), is(is(nullValue()))); assertThat(record.getNumber("sort"), is(is(nullValue()))); assertThat(firstRecord.get("innerAttributeRecord", EnhancedType.of(InnerAttributeRecord.class)) , is(nullValue())); assertThat(record.getString("test.com"), is("v7")); } @Test public void queryRecordDefaultSettings_withEmptyAttributeList() { insertNestedDocuments(); Iterator<Page<EnhancedDocument>> results = neseteddocMappedtable.query(b -> b .queryConditional(keyEqualTo(k -> k.partitionValue("id-value-7"))) .attributesToProject(new ArrayList<>()).build()).iterator(); assertThat(results.hasNext(), is(true)); Page<EnhancedDocument> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items().size(), is(1)); EnhancedDocument firstRecord = page.items().get(0); assertThat(firstRecord.getString("outerAttribOne"), is("id-value-7")); assertThat(firstRecord.getNumber("sort").intValue(), is(7)); assertThat(firstRecord.get("innerAttributeRecord", EnhancedType.of(InnerAttributeRecord.class)).getAttribTwo(), is(7)); assertThat(firstRecord.getString("test.com"), is("v7")); } @Test public void queryRecordDefaultSettings_withNullAttributeList() { insertNestedDocuments(); List<String> backwardCompatibilty = null; Iterator<Page<EnhancedDocument>> results = neseteddocMappedtable.query(b -> b .queryConditional(keyEqualTo(k -> k.partitionValue("id-value-7"))) .attributesToProject(backwardCompatibilty).build()).iterator(); assertThat(results.hasNext(), is(true)); Page<EnhancedDocument> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items().size(), is(1)); EnhancedDocument firstRecord = page.items().get(0); assertThat(firstRecord.getString("outerAttribOne"), is("id-value-7")); assertThat(firstRecord.getNumber("sort").intValue(), is(7)); assertThat(firstRecord.get("innerAttributeRecord", EnhancedType.of(InnerAttributeRecord.class)).getAttribTwo(), is(7)); assertThat(firstRecord.getString("test.com"), is("v7")); } @Test public void queryAllRecordsDefaultSettings_withNestedProjectionNameEmptyNameMap() { insertNestedDocuments(); assertThatExceptionOfType(Exception.class).isThrownBy( () -> { Iterator<Page<EnhancedDocument>> results = neseteddocMappedtable.query(b -> b.queryConditional( keyEqualTo(k -> k.partitionValue("id-value-3"))) .attributesToProject("").build()).iterator(); assertThat(results.hasNext(), is(true)); Page<EnhancedDocument> page = results.next(); }); assertThatExceptionOfType(Exception.class).isThrownBy( () -> { Iterator<Page<EnhancedDocument>> results = neseteddocMappedtable.query(b -> b.queryConditional( keyEqualTo(k -> k.partitionValue("id-value-3"))) .addNestedAttributeToProject(NestedAttributeName.create("")).build()).iterator(); assertThat(results.hasNext(), is(true)); Page<EnhancedDocument> page = results.next(); }); } }
4,194
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/document/BasicCrudTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests.document; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static software.amazon.awssdk.enhanced.dynamodb.AttributeConverterProvider.defaultProvider; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.stringValue; import java.util.Collection; import java.util.LinkedHashMap; import java.util.Map; import org.assertj.core.api.Assertions; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.Expression; import software.amazon.awssdk.enhanced.dynamodb.Key; import software.amazon.awssdk.enhanced.dynamodb.TableMetadata; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.document.EnhancedDocument; import software.amazon.awssdk.enhanced.dynamodb.document.EnhancedDocumentTestData; import software.amazon.awssdk.enhanced.dynamodb.document.TestData; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.LocalDynamoDbSyncTestBase; import software.amazon.awssdk.enhanced.dynamodb.model.DeleteItemEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.PutItemEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.UpdateItemEnhancedRequest; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException; import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; import software.amazon.awssdk.services.dynamodb.model.GetItemResponse; @RunWith(Parameterized.class) public class BasicCrudTest extends LocalDynamoDbSyncTestBase { private static final String ATTRIBUTE_NAME_WITH_SPECIAL_CHARACTERS = "a*t:t.r-i#bute+3/4(&?5=@)<6>!ch$ar%"; private final TestData testData; @Rule public ExpectedException exception = ExpectedException.none(); private DynamoDbEnhancedClient enhancedClient; private final String tableName = getConcreteTableName("table-name"); private DynamoDbClient lowLevelClient; private DynamoDbTable<EnhancedDocument> docMappedtable ; @Before public void setUp(){ lowLevelClient = getDynamoDbClient(); enhancedClient = DynamoDbEnhancedClient.builder() .dynamoDbClient(lowLevelClient) .build(); docMappedtable = enhancedClient.table(tableName, TableSchema.documentSchemaBuilder() .addIndexPartitionKey(TableMetadata.primaryIndexName(), "id", AttributeValueType.S) .addIndexSortKey(TableMetadata.primaryIndexName(), "sort", AttributeValueType.S) .attributeConverterProviders(defaultProvider()) .build()); docMappedtable.createTable(); } public BasicCrudTest(TestData testData) { this.testData = testData; } @Parameterized.Parameters public static Collection<TestData> parameters() throws Exception { return EnhancedDocumentTestData.testDataInstance().getAllGenericScenarios(); } private static EnhancedDocument appendKeysToDoc(TestData testData) { EnhancedDocument enhancedDocument = testData.getEnhancedDocument().toBuilder() .putString("id", "id-value") .putString("sort", "sort-value").build(); return enhancedDocument; } private static Map<String, AttributeValue> simpleKey() { Map<String, AttributeValue> key = new LinkedHashMap<>(); key.put("id", AttributeValue.fromS("id-value")); key.put("sort", AttributeValue.fromS("sort-value")); return key; } private static Map<String, AttributeValue> appendKeysToTestDataAttributeMap(Map<String, AttributeValue> attributeValueMap) { Map<String, AttributeValue> result = new LinkedHashMap<>(attributeValueMap); result.put("id", AttributeValue.fromS("id-value")); result.put("sort", AttributeValue.fromS("sort-value")); return result; } @After public void deleteTable() { getDynamoDbClient().deleteTable(DeleteTableRequest.builder() .tableName(tableName) .build()); } @Test public void putThenGetItemUsingKey() { EnhancedDocument enhancedDocument = appendKeysToDoc(testData); docMappedtable.putItem(enhancedDocument); Map<String, AttributeValue> key = simpleKey(); GetItemResponse lowLevelGet = lowLevelClient.getItem(r -> r.key(key).tableName(tableName)); Assertions.assertThat(lowLevelGet.item()).isEqualTo(enhancedDocument.toMap()); } @Test public void putThenGetItemUsingKeyItem() { EnhancedDocument enhancedDocument = appendKeysToDoc(testData); docMappedtable.putItem(r -> r.item(enhancedDocument)); EnhancedDocument result = docMappedtable.getItem(EnhancedDocument.builder() .attributeConverterProviders(testData.getAttributeConverterProvider()) .putString("id", "id-value") .putString("sort", "sort-value") .build()); Map<String, AttributeValue> attributeValueMap = appendKeysToTestDataAttributeMap(testData.getDdbItemMap()); Assertions.assertThat(result.toMap()).isEqualTo(enhancedDocument.toMap()); Assertions.assertThat(result.toMap()).isEqualTo(attributeValueMap); } @Test public void getNonExistentItem() { EnhancedDocument item = docMappedtable.getItem(r -> r.key(k -> k.partitionValue("id-value").sortValue("sort-value"))); Assertions.assertThat(item).isNull(); } @Test public void updateOverwriteCompleteItem_usingShortcutForm() { EnhancedDocument enhancedDocument = appendKeysToDoc(testData).toBuilder() .putString("attribute", "one") .putString("attribute2", "two") .putString("attribute3", "three") .build(); docMappedtable.putItem(enhancedDocument); // Updating new Items other than the one present in testData EnhancedDocument updateDocument = EnhancedDocument.builder() .putString("id", "id-value") .putString("sort", "sort-value") .putString("attribute", "four") .putString("attribute2", "five") .putString("attribute3", "six") .build(); EnhancedDocument result = docMappedtable.updateItem(updateDocument); Map<String, AttributeValue> updatedItemMap = new LinkedHashMap<>(testData.getDdbItemMap()); updatedItemMap.put("attribute", AttributeValue.fromS("four")); updatedItemMap.put("attribute2", AttributeValue.fromS("five")); updatedItemMap.put("attribute3", AttributeValue.fromS("six")); updatedItemMap.put("id", AttributeValue.fromS("id-value")); updatedItemMap.put("sort", AttributeValue.fromS("sort-value")); Map<String, AttributeValue> key = simpleKey(); GetItemResponse lowLevelGet = lowLevelClient.getItem(r -> r.key(key).tableName(tableName)); Assertions.assertThat(lowLevelGet.item()).isEqualTo(result.toMap()); Assertions.assertThat(lowLevelGet.item()).isEqualTo(updatedItemMap); } @Test public void putTwiceThenGetItem() { EnhancedDocument enhancedDocument = appendKeysToDoc(testData).toBuilder() .putString("attribute", "one") .putString("attribute2", "two") .putString("attribute3", "three") .build(); docMappedtable.putItem(enhancedDocument); // Updating new Items other than the one present in testData EnhancedDocument updateDocument = EnhancedDocument.builder() .attributeConverterProviders(defaultProvider()) .putString("id", "id-value") .putString("sort", "sort-value") .putString("attribute", "four") .putString("attribute2", "five") .putString("attribute3", "six") .build(); docMappedtable.putItem(r -> r.item(updateDocument)); Map<String, AttributeValue> key = simpleKey(); GetItemResponse lowLevelGet = lowLevelClient.getItem(r -> r.key(key).tableName(tableName)); // All the items are overwritten Assertions.assertThat(lowLevelGet.item()).isEqualTo(updateDocument.toMap()); EnhancedDocument docGetItem = docMappedtable.getItem(r -> r.key(k -> k.partitionValue("id-value").sortValue("sort-value" ))); Assertions.assertThat(lowLevelGet.item()).isEqualTo(docGetItem.toMap()); } @Test public void putThenDeleteItem_usingShortcutForm() { EnhancedDocument enhancedDocument = appendKeysToDoc(testData).toBuilder() .putString("attribute", "one") .putString("attribute2", "two") .putString("attribute3", "three") .build(); Map<String, AttributeValue> key = simpleKey(); docMappedtable.putItem(r -> r.item(enhancedDocument)); GetItemResponse lowLevelGetBeforeDelete = lowLevelClient.getItem(r -> r.key(key).tableName(tableName)); EnhancedDocument beforeDeleteResult = docMappedtable.deleteItem(Key.builder().partitionValue("id-value").sortValue("sort-value").build()); EnhancedDocument afterDeleteDoc = docMappedtable.getItem(Key.builder().partitionValue("id-value").sortValue("sort-value").build()); GetItemResponse lowLevelGetAfterDelete = lowLevelClient.getItem(r -> r.key(key).tableName(tableName)); assertThat(enhancedDocument.toMap(), is(EnhancedDocument.fromAttributeValueMap(lowLevelGetBeforeDelete.item()).toMap())); assertThat(beforeDeleteResult.toMap(), is(enhancedDocument.toMap())); assertThat(beforeDeleteResult.toMap(), is(lowLevelGetBeforeDelete.item())); assertThat(afterDeleteDoc, is(nullValue())); assertThat(lowLevelGetAfterDelete.item().size(), is(0)); } @Test public void putThenDeleteItem_usingKeyItemForm() { EnhancedDocument enhancedDocument = appendKeysToDoc(testData).toBuilder() .putString("attribute", "one") .putString("attribute2", "two") .putString("attribute3", "three") .build(); docMappedtable.putItem(enhancedDocument); EnhancedDocument beforeDeleteResult = docMappedtable.deleteItem(enhancedDocument); EnhancedDocument afterDeleteResult = docMappedtable.getItem(Key.builder().partitionValue("id-value").sortValue("sort-value").build()); assertThat(beforeDeleteResult.toMap(), is(enhancedDocument.toMap())); assertThat(afterDeleteResult, is(nullValue())); Map<String, AttributeValue> key = simpleKey(); GetItemResponse lowLevelGetBeforeDelete = lowLevelClient.getItem(r -> r.key(key).tableName(tableName)); assertThat(lowLevelGetBeforeDelete.item().size(), is(0)); } @Test public void putWithConditionThatSucceeds() { EnhancedDocument enhancedDocument = appendKeysToDoc(testData).toBuilder() .putString("attribute", "one") .putString("attribute2", "two") .putString("attribute3", "three") .build(); docMappedtable.putItem(r -> r.item(enhancedDocument)); EnhancedDocument newDoc = enhancedDocument.toBuilder().putString("attribute", "four").build(); Expression conditionExpression = Expression.builder() .expression("#key = :value OR #key1 = :value1") .putExpressionName("#key", "attribute") .putExpressionName("#key1", ATTRIBUTE_NAME_WITH_SPECIAL_CHARACTERS) .putExpressionValue(":value", stringValue("one")) .putExpressionValue(":value1", stringValue("three")) .build(); docMappedtable.putItem(PutItemEnhancedRequest.builder(EnhancedDocument.class) .item(newDoc) .conditionExpression(conditionExpression).build()); EnhancedDocument result = docMappedtable.getItem(r -> r.key(k -> k.partitionValue("id-value").sortValue("sort-value"))); assertThat(result.toMap(), is(newDoc.toMap())); } @Test public void putWithConditionThatFails() { EnhancedDocument enhancedDocument = appendKeysToDoc(testData).toBuilder() .putString("attribute", "one") .putString("attribute2", "two") .putString("attribute3", "three") .build(); docMappedtable.putItem(r -> r.item(enhancedDocument)); EnhancedDocument newDoc = enhancedDocument.toBuilder().putString("attribute", "four").build(); Expression conditionExpression = Expression.builder() .expression("#key = :value OR #key1 = :value1") .putExpressionName("#key", "attribute") .putExpressionName("#key1", ATTRIBUTE_NAME_WITH_SPECIAL_CHARACTERS) .putExpressionValue(":value", stringValue("wrong")) .putExpressionValue(":value1", stringValue("wrong")) .build(); exception.expect(ConditionalCheckFailedException.class); docMappedtable.putItem(PutItemEnhancedRequest.builder(EnhancedDocument.class) .item(newDoc) .conditionExpression(conditionExpression).build()); } @Test public void deleteNonExistentItem() { EnhancedDocument result = docMappedtable.deleteItem(r -> r.key(k -> k.partitionValue("id-value").sortValue("sort-value"))); assertThat(result, is(nullValue())); } @Test public void deleteWithConditionThatSucceeds() { EnhancedDocument enhancedDocument = appendKeysToDoc(testData).toBuilder() .putString("attribute", "one") .putString("attribute2", "two") .putString(ATTRIBUTE_NAME_WITH_SPECIAL_CHARACTERS, "three") .build(); docMappedtable.putItem(r -> r.item(enhancedDocument)); Expression conditionExpression = Expression.builder() .expression("#key = :value OR #key1 = :value1") .putExpressionName("#key", "attribute") .putExpressionName("#key1", ATTRIBUTE_NAME_WITH_SPECIAL_CHARACTERS) .putExpressionValue(":value", stringValue("wrong")) .putExpressionValue(":value1", stringValue("three")) .build(); Key key = docMappedtable.keyFrom(enhancedDocument); docMappedtable.deleteItem(DeleteItemEnhancedRequest.builder().key(key).conditionExpression(conditionExpression).build()); EnhancedDocument result = docMappedtable.getItem(r -> r.key(key)); assertThat(result, is(nullValue())); } @Test public void deleteWithConditionThatFails() { EnhancedDocument enhancedDocument = appendKeysToDoc(testData).toBuilder() .putString("attribute", "one") .putString("attribute2", "two") .putString(ATTRIBUTE_NAME_WITH_SPECIAL_CHARACTERS, "three") .build(); docMappedtable.putItem(r -> r.item(enhancedDocument)); Expression conditionExpression = Expression.builder() .expression("#key = :value OR #key1 = :value1") .putExpressionName("#key", "attribute") .putExpressionName("#key1", ATTRIBUTE_NAME_WITH_SPECIAL_CHARACTERS) .putExpressionValue(":value", stringValue("wrong")) .putExpressionValue(":value1", stringValue("wrong")) .build(); exception.expect(ConditionalCheckFailedException.class); docMappedtable.deleteItem(DeleteItemEnhancedRequest.builder().key(docMappedtable.keyFrom(enhancedDocument)) .conditionExpression(conditionExpression) .build()); } @Test public void updateOverwriteCompleteRecord_usingShortcutForm() { EnhancedDocument enhancedDocument = appendKeysToDoc(testData).toBuilder() .putString("attribute", "one") .putString("attribute2", "two") .putString(ATTRIBUTE_NAME_WITH_SPECIAL_CHARACTERS, "three") .build(); docMappedtable.putItem(enhancedDocument); // Updating new Items other than the one present in testData EnhancedDocument.Builder updateDocBuilder = EnhancedDocument.builder() .attributeConverterProviders(defaultProvider()) .putString("id", "id-value") .putString("sort", "sort-value") .putString("attribute", "four") .putString("attribute2", "five") .putString(ATTRIBUTE_NAME_WITH_SPECIAL_CHARACTERS, "six"); EnhancedDocument expectedDocument = updateDocBuilder.build(); // Explicitly Nullify each of the previous members testData.getEnhancedDocument().toMap().keySet().forEach(r -> { updateDocBuilder.putNull(r); System.out.println(r); }); EnhancedDocument updateDocument = updateDocBuilder.build(); EnhancedDocument result = docMappedtable.updateItem(updateDocument); assertThat(result.toMap(), is(expectedDocument.toMap())); assertThat(result.toJson(), is("{\"a*t:t.r-i#bute+3/4(&?5=@)<6>!ch$ar%\":\"six\",\"attribute\":\"four\"," + "\"attribute2\":\"five\",\"id\":\"id-value\",\"sort\":\"sort-value\"}")); } @Test public void updateCreatePartialRecord() { EnhancedDocument.Builder docBuilder = appendKeysToDoc(testData).toBuilder() .putString("attribute", "one"); EnhancedDocument updateDoc = docBuilder.build(); /** * Explicitly removing AttributeNull Value that are added in testData for testing. * This should not be treated as Null in partial update, because for a Document, an AttributeValue.fromNul(true) with a * Null value is treated as Null or non-existent during updateItem. */ testData.getEnhancedDocument().toMap().entrySet().forEach(entry -> { if (AttributeValue.fromNul(true).equals(entry.getValue())) { docBuilder.remove(entry.getKey()); } }); EnhancedDocument expectedDocUpdate = docBuilder.build(); EnhancedDocument result = docMappedtable.updateItem(r -> r.item(updateDoc)); assertThat(result.toMap(), is(expectedDocUpdate.toMap())); } @Test public void updateCreateKeyOnlyRecord() { EnhancedDocument.Builder updateDocBuilder = appendKeysToDoc(testData).toBuilder(); EnhancedDocument expectedDocument = EnhancedDocument.builder() .attributeConverterProviders(defaultProvider()) .putString("id", "id-value") .putString("sort", "sort-value").build(); testData.getEnhancedDocument().toMap().keySet().forEach(r -> { updateDocBuilder.putNull(r); }); EnhancedDocument cleanedUpDoc = updateDocBuilder.build(); EnhancedDocument result = docMappedtable.updateItem(r -> r.item(cleanedUpDoc)); assertThat(result.toMap(), is(expectedDocument.toMap())); } @Test public void updateOverwriteModelledNulls() { EnhancedDocument enhancedDocument = appendKeysToDoc(testData).toBuilder() .putString("attribute", "one") .putString("attribute2", "two") .putString(ATTRIBUTE_NAME_WITH_SPECIAL_CHARACTERS, "three") .build(); docMappedtable.putItem(r -> r.item(enhancedDocument)); EnhancedDocument updateDocument = EnhancedDocument.builder().attributeConverterProviders(defaultProvider()) .putString("id", "id-value") .putString("sort", "sort-value") .putString("attribute", "four") .putNull("attribute2") .putNull(ATTRIBUTE_NAME_WITH_SPECIAL_CHARACTERS).build(); EnhancedDocument result = docMappedtable.updateItem(r -> r.item(updateDocument)); assertThat(result.isPresent("attribute2"), is(false)); assertThat(result.isPresent(ATTRIBUTE_NAME_WITH_SPECIAL_CHARACTERS), is(false)); assertThat(result.getString("attribute"), is("four")); testData.getEnhancedDocument().toMap().entrySet().forEach(entry -> { if (AttributeValue.fromNul(true).equals(entry.getValue())) { assertThat(result.isPresent(entry.getKey()), is(true)); } else { assertThat(result.toMap().get(entry.getKey()), is(testData.getDdbItemMap().get(entry.getKey()))); } }); } @Test public void updateCanIgnoreNullsDoesNotIgnoreNullAttributeValues() { EnhancedDocument enhancedDocument = appendKeysToDoc(testData).toBuilder() .putString("attribute", "one") .putString("attribute2", "two") .putString(ATTRIBUTE_NAME_WITH_SPECIAL_CHARACTERS, "three") .build(); docMappedtable.putItem(r -> r.item(enhancedDocument)); EnhancedDocument updateDocument = EnhancedDocument.builder() .putString("id", "id-value") .putString("sort", "sort-value") .putNull("attribute") .putNull(ATTRIBUTE_NAME_WITH_SPECIAL_CHARACTERS) .build(); EnhancedDocument result = docMappedtable.updateItem(UpdateItemEnhancedRequest.builder(EnhancedDocument.class) .item(updateDocument) .ignoreNulls(true) .build()); EnhancedDocument expectedResult = appendKeysToDoc(testData).toBuilder() .putString("attribute2", "two") .build(); assertThat(result.toMap(), is(expectedResult.toMap())); } @Test public void updateKeyOnlyExistingRecordDoesNothing() { EnhancedDocument enhancedDocument = appendKeysToDoc(testData); docMappedtable.putItem(r -> r.item(enhancedDocument)); EnhancedDocument hashKeyAndSortOnly = EnhancedDocument.builder() .putString("id", "id-value") .putString("sort", "sort-value").build(); EnhancedDocument result = docMappedtable.updateItem(UpdateItemEnhancedRequest.builder(EnhancedDocument.class) .item(hashKeyAndSortOnly) .ignoreNulls(true) .build()); assertThat(result.toMap(), is(enhancedDocument.toMap())); } @Test public void updateWithConditionThatSucceeds() { EnhancedDocument enhancedDocument = appendKeysToDoc(testData).toBuilder() .putString("attribute", "one") .putString("attribute2", "two") .putString(ATTRIBUTE_NAME_WITH_SPECIAL_CHARACTERS, "three") .build(); docMappedtable.putItem(r -> r.item(enhancedDocument)); EnhancedDocument newDoc = EnhancedDocument.builder() .attributeConverterProviders(defaultProvider()) .putString("id", "id-value") .putString("sort", "sort-value") .putString("attribute", "four") .build(); Expression conditionExpression = Expression.builder() .expression("#key = :value OR #key1 = :value1") .putExpressionName("#key", "attribute") .putExpressionName("#key1", ATTRIBUTE_NAME_WITH_SPECIAL_CHARACTERS) .putExpressionValue(":value", stringValue("wrong")) .putExpressionValue(":value1", stringValue("three")) .build(); docMappedtable.updateItem(UpdateItemEnhancedRequest.builder(EnhancedDocument.class) .item(newDoc) .conditionExpression(conditionExpression) .build()); EnhancedDocument result = docMappedtable.getItem(r -> r.key(k -> k.partitionValue("id-value").sortValue("sort-value"))); assertThat(result.toMap(), is(enhancedDocument.toBuilder().putString("attribute", "four").build().toMap())); } @Test public void updateWithConditionThatFails() { EnhancedDocument enhancedDocument = appendKeysToDoc(testData).toBuilder() .putString("attribute", "one") .putString("attribute2", "two") .putString(ATTRIBUTE_NAME_WITH_SPECIAL_CHARACTERS, "three") .build(); docMappedtable.putItem(r -> r.item(enhancedDocument)); EnhancedDocument newDoc = EnhancedDocument.builder() .attributeConverterProviders(defaultProvider()) .putString("id", "id-value") .putString("sort", "sort-value") .putString("attribute", "four") .build(); Expression conditionExpression = Expression.builder() .expression("#key = :value OR #key1 = :value1") .putExpressionName("#key", "attribute") .putExpressionName("#key1", ATTRIBUTE_NAME_WITH_SPECIAL_CHARACTERS) .putExpressionValue(":value", stringValue("wrong")) .putExpressionValue(":value1", stringValue("wrong")) .build(); exception.expect(ConditionalCheckFailedException.class); docMappedtable.updateItem(UpdateItemEnhancedRequest.builder(EnhancedDocument.class) .item(newDoc) .conditionExpression(conditionExpression) .build()); } }
4,195
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/document/ComplexInputItemsTests.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests.document; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static software.amazon.awssdk.enhanced.dynamodb.AttributeConverterProvider.defaultProvider; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.After; import org.junit.Before; import org.junit.Test; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.TableMetadata; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.document.EnhancedDocument; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.LocalDynamoDbSyncTestBase; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; public class ComplexInputItemsTests extends LocalDynamoDbSyncTestBase { private final String tableName = getConcreteTableName("table-name"); private DynamoDbEnhancedClient enhancedClient; private DynamoDbClient lowLevelClient; private DynamoDbTable<EnhancedDocument> docMappedtable; @Before public void setUp() { lowLevelClient = getDynamoDbClient(); enhancedClient = DynamoDbEnhancedClient.builder() .dynamoDbClient(lowLevelClient) .build(); docMappedtable = enhancedClient.table(tableName, TableSchema.documentSchemaBuilder() .addIndexPartitionKey(TableMetadata.primaryIndexName(), "id", AttributeValueType.S) .addIndexSortKey(TableMetadata.primaryIndexName(), "sort", AttributeValueType.N) .attributeConverterProviders(defaultProvider()) .build()); docMappedtable.createTable(); } @After public void deleteTable() { getDynamoDbClient().deleteTable(DeleteTableRequest.builder() .tableName(tableName) .build()); } @Test public void getAndPutDocumentWithNoAttributeConverters() { docMappedtable.putItem(EnhancedDocument.builder() .putString("id", "one") .putNumber("sort", 1) .putString("element", "noAttributeConverter") .build()); EnhancedDocument noConverterInGetItem = docMappedtable.getItem(EnhancedDocument.builder() .putString("id", "one") .putNumber("sort", 1) .build()); assertThat(noConverterInGetItem.toJson(), is("{\"id\":\"one\",\"sort\":1,\"element\":\"noAttributeConverter\"}")); } @Test public void bytesInAlTypes() { Map<String, SdkBytes> bytesMap = new LinkedHashMap<>(); bytesMap.put("key1", SdkBytes.fromByteArray("1".getBytes(StandardCharsets.UTF_8))); bytesMap.put("key2", SdkBytes.fromByteArray("2".getBytes(StandardCharsets.UTF_8))); EnhancedDocument enhancedDocument = EnhancedDocument.builder() .putString("id", "allTypesBytes") .putNumber("sort", 2) .put("put", SdkBytes.fromUtf8String("1"), SdkBytes.class) .putBytes("putBytes", SdkBytes.fromByteBuffer(ByteBuffer.wrap("1".getBytes(StandardCharsets.UTF_8)))) .putBytesSet("putBytesSet", Stream.of(SdkBytes.fromUtf8String("1"), SdkBytes.fromUtf8String("2")).collect(Collectors.toCollection(LinkedHashSet::new))) .putList("putBytesList", Stream.of(SdkBytes.fromUtf8String("1"), SdkBytes.fromUtf8String("2")).collect(Collectors.toList()), EnhancedType.of(SdkBytes.class)) .putMap("bytesMap", bytesMap, EnhancedType.of(String.class), EnhancedType.of(SdkBytes.class)) .build(); docMappedtable.putItem(enhancedDocument); EnhancedDocument retrievedItem = docMappedtable.getItem(EnhancedDocument.builder() .putString("id", "allTypesBytes") .putNumber("sort", 2) .build()); assertThat(retrievedItem.toJson(), is("{\"putBytesSet\":[\"MQ==\",\"Mg==\"],\"putBytes\":\"MQ==\",\"putBytesList\":[\"MQ==\",\"Mg==\"],\"id\":\"allTypesBytes\",\"sort\":2,\"bytesMap\":{\"key1\":\"MQ==\",\"key2\":\"Mg==\"},\"put\":\"MQ==\"}" )); } }
4,196
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/document/BasicScanTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.functionaltests.document; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static software.amazon.awssdk.enhanced.dynamodb.AttributeConverterProvider.defaultProvider; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.numberValue; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.stringValue; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import software.amazon.awssdk.core.pagination.sync.SdkIterable; import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.Expression; import software.amazon.awssdk.enhanced.dynamodb.NestedAttributeName; import software.amazon.awssdk.enhanced.dynamodb.TableMetadata; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.document.EnhancedDocument; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.LocalDynamoDbSyncTestBase; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.InnerAttribConverterProvider; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.InnerAttributeRecord; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.NestedTestRecord; import software.amazon.awssdk.enhanced.dynamodb.model.Page; import software.amazon.awssdk.enhanced.dynamodb.model.ScanEnhancedRequest; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest; public class BasicScanTest extends LocalDynamoDbSyncTestBase { private DynamoDbClient lowLevelClient; private DynamoDbTable<EnhancedDocument> docMappedtable ; private DynamoDbTable<EnhancedDocument> neseteddocMappedtable ; @Rule public ExpectedException exception = ExpectedException.none(); private DynamoDbEnhancedClient enhancedClient; private final String tableName = getConcreteTableName("doc-table-name"); private final String nestedTableName = getConcreteTableName("doc-nested-table-name"); @Before public void createTable() { lowLevelClient = getDynamoDbClient(); enhancedClient = DynamoDbEnhancedClient.builder() .dynamoDbClient(lowLevelClient) .build(); docMappedtable = enhancedClient.table(tableName, TableSchema.documentSchemaBuilder() .attributeConverterProviders(defaultProvider()) .addIndexPartitionKey(TableMetadata.primaryIndexName(), "id", AttributeValueType.S) .addIndexSortKey(TableMetadata.primaryIndexName(), "sort", AttributeValueType.N) .attributeConverterProviders(defaultProvider()) .build()); docMappedtable.createTable(); neseteddocMappedtable = enhancedClient.table(nestedTableName, TableSchema.documentSchemaBuilder() .attributeConverterProviders( new InnerAttribConverterProvider<>(), defaultProvider()) .addIndexPartitionKey(TableMetadata.primaryIndexName(), "outerAttribOne", AttributeValueType.S) .addIndexSortKey(TableMetadata.primaryIndexName(), "sort", AttributeValueType.N) .build()); neseteddocMappedtable.createTable(); } private static final List<EnhancedDocument> DOCUMENTS = IntStream.range(0, 10) .mapToObj(i -> EnhancedDocument.builder() .putString("id", "id-value") .putNumber("sort", i) .putNumber("value", i) .build() ).collect(Collectors.toList()); private static final List<EnhancedDocument> DOCUMENTS_WITH_PROVIDERS = IntStream.range(0, 10) .mapToObj(i -> EnhancedDocument.builder() .attributeConverterProviders(defaultProvider()) .putString("id", "id-value") .putNumber("sort", i) .putNumber("value", i) .build() ).collect(Collectors.toList()); private static final List<EnhancedDocument> NESTED_TEST_DOCUMENTS = IntStream.range(0, 10) .mapToObj(i -> { final NestedTestRecord nestedTestRecord = new NestedTestRecord(); nestedTestRecord.setOuterAttribOne("id-value-" + i); nestedTestRecord.setSort(i); final InnerAttributeRecord innerAttributeRecord = new InnerAttributeRecord(); innerAttributeRecord.setAttribOne("attribOne-"+i); innerAttributeRecord.setAttribTwo(i); nestedTestRecord.setInnerAttributeRecord(innerAttributeRecord); nestedTestRecord.setDotVariable("v"+i); return nestedTestRecord; }) .map(BasicQueryTest::createDocumentFromNestedRecord) .collect(Collectors.toList()); private void insertDocuments() { DOCUMENTS.forEach(document -> docMappedtable.putItem(r -> r.item(document))); NESTED_TEST_DOCUMENTS.forEach(nestedDocs -> neseteddocMappedtable.putItem(r -> r.item(nestedDocs))); } private void insertNestedDocuments() { NESTED_TEST_DOCUMENTS.forEach(nestedDocs -> neseteddocMappedtable.putItem(r -> r.item(nestedDocs))); } @After public void deleteTable() { getDynamoDbClient().deleteTable(DeleteTableRequest.builder() .tableName(tableName) .build()); getDynamoDbClient().deleteTable(DeleteTableRequest.builder() .tableName(nestedTableName) .build()); } @Test public void scanAllRecordsDefaultSettings() { insertDocuments(); docMappedtable.scan(ScanEnhancedRequest.builder().build()) .forEach(p -> p.items().forEach(item -> System.out.println(item))); Iterator<Page<EnhancedDocument>> results = docMappedtable.scan(ScanEnhancedRequest.builder().build()).iterator(); assertThat(results.hasNext(), is(true)); Page<EnhancedDocument> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items().stream().map(doc -> doc.toJson()).collect(Collectors.toList()), is(DOCUMENTS_WITH_PROVIDERS.stream().map(i -> i.toJson()).collect(Collectors.toList()))); assertThat(page.lastEvaluatedKey(), is(nullValue())); } @Test public void queryAllRecordsDefaultSettings_withProjection() { insertDocuments(); Iterator<Page<EnhancedDocument>> results = docMappedtable.scan(b -> b.attributesToProject("sort")).iterator(); assertThat(results.hasNext(), is(true)); Page<EnhancedDocument> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items().size(), is(DOCUMENTS.size())); EnhancedDocument firstRecord = page.items().get(0); assertThat(firstRecord.getString("id"), is(nullValue())); assertThat(firstRecord.getNumber("sort").intValue(), is(0)); } @Test public void scanAllRecordsDefaultSettings_viaItems() { insertDocuments(); SdkIterable<EnhancedDocument> items = docMappedtable.scan(ScanEnhancedRequest.builder().limit(2).build()).items(); assertThat(items.stream().map(i->i.toJson()).collect(Collectors.toList()), is(DOCUMENTS_WITH_PROVIDERS.stream().map(i -> i.toJson()).collect(Collectors.toList()))); } @Test public void scanAllRecordsWithFilter() { insertDocuments(); Map<String, AttributeValue> expressionValues = new HashMap<>(); expressionValues.put(":min_value", numberValue(3)); expressionValues.put(":max_value", numberValue(5)); Expression expression = Expression.builder() .expression("sort >= :min_value AND sort <= :max_value") .expressionValues(expressionValues) .build(); Iterator<Page<EnhancedDocument>> results = docMappedtable.scan(ScanEnhancedRequest.builder().filterExpression(expression).build()).iterator(); assertThat(results.hasNext(), is(true)); Page<EnhancedDocument> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items().stream().map(i -> i.toJson()).collect(Collectors.toList()), is(DOCUMENTS_WITH_PROVIDERS.stream().filter(r -> r.getNumber("sort").intValue() >= 3 && r.getNumber("sort").intValue() <= 5) .map( j -> j.toJson()) .collect(Collectors.toList()))); assertThat(page.lastEvaluatedKey(), is(nullValue())); } @Test public void scanAllRecordsWithFilterAndProjection() { insertDocuments(); Map<String, AttributeValue> expressionValues = new HashMap<>(); expressionValues.put(":min_value", numberValue(3)); expressionValues.put(":max_value", numberValue(5)); Expression expression = Expression.builder() .expression("#sort >= :min_value AND #sort <= :max_value") .expressionValues(expressionValues) .putExpressionName("#sort", "sort") .build(); Iterator<Page<EnhancedDocument>> results = docMappedtable.scan( ScanEnhancedRequest.builder() .attributesToProject("sort") .filterExpression(expression) .build() ).iterator(); assertThat(results.hasNext(), is(true)); Page<EnhancedDocument> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items(), hasSize(3)); EnhancedDocument record = page.items().get(0); assertThat(record.getString("id"), is(nullValue())); assertThat(record.getNumber("sort").intValue(), is(3)); } @Test public void scanLimit() { insertDocuments(); Iterator<Page<EnhancedDocument>> results = docMappedtable.scan(r -> r.limit(5)).iterator(); assertThat(results.hasNext(), is(true)); Page<EnhancedDocument> page1 = results.next(); assertThat(results.hasNext(), is(true)); Page<EnhancedDocument> page2 = results.next(); assertThat(results.hasNext(), is(true)); Page<EnhancedDocument> page3 = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page1.items().stream().map( i -> i.toJson()).collect(Collectors.toList()), is(DOCUMENTS_WITH_PROVIDERS.subList(0, 5).stream().map( i -> i.toJson()).collect(Collectors.toList()))); assertThat(page1.lastEvaluatedKey(), is(getKeyMap(4))); assertThat(page2.items().stream().map( i -> i.toJson()).collect(Collectors.toList()), is(DOCUMENTS_WITH_PROVIDERS.subList(5, 10).stream().map( i -> i.toJson()).collect(Collectors.toList()))); assertThat(page2.lastEvaluatedKey(), is(getKeyMap(9))); assertThat(page3.items(), is(empty())); assertThat(page3.lastEvaluatedKey(), is(nullValue())); } @Test public void scanLimit_viaItems() { insertDocuments(); SdkIterable<EnhancedDocument> results = docMappedtable.scan(r -> r.limit(5)).items(); assertThat(results.stream().map(i -> i.toJson()) .collect(Collectors.toList()), is(DOCUMENTS_WITH_PROVIDERS.stream().map(i ->i.toJson()).collect(Collectors.toList()))); } @Test public void scanEmpty() { Iterator<Page<EnhancedDocument>> results = docMappedtable.scan().iterator(); assertThat(results.hasNext(), is(true)); Page<EnhancedDocument> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items(), is(empty())); assertThat(page.lastEvaluatedKey(), is(nullValue())); } @Test public void scanEmpty_viaItems() { Iterator<EnhancedDocument> results = docMappedtable.scan().items().iterator(); assertThat(results.hasNext(), is(false)); } @Test public void scanExclusiveStartKey() { insertDocuments(); Iterator<Page<EnhancedDocument>> results = docMappedtable.scan(r -> r.exclusiveStartKey(getKeyMap(7))).iterator(); assertThat(results.hasNext(), is(true)); Page<EnhancedDocument> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items().stream().map(i -> i.toJson()).collect(Collectors.toList()), is(DOCUMENTS_WITH_PROVIDERS.subList(8, 10).stream().map( i -> i.toJson()).collect(Collectors.toList()))); assertThat(page.lastEvaluatedKey(), is(nullValue())); } @Test public void scanExclusiveStartKey_viaItems() { insertDocuments(); SdkIterable<EnhancedDocument> results = docMappedtable.scan(r -> r.exclusiveStartKey(getKeyMap(7))).items(); assertThat(results.stream().map( i-> i.toJson()).collect(Collectors.toList()), is(DOCUMENTS_WITH_PROVIDERS.subList(8, 10).stream().map( i-> i.toJson()).collect(Collectors.toList()))); } private Map<String, AttributeValue> getKeyMap(int sort) { Map<String, AttributeValue> result = new HashMap<>(); result.put("id", stringValue("id-value")); result.put("sort", numberValue(sort)); return Collections.unmodifiableMap(result); } @Test public void scanAllRecordsWithFilterAndNestedProjectionSingleAttribute() { insertNestedDocuments(); Map<String, AttributeValue> expressionValues = new HashMap<>(); expressionValues.put(":min_value", numberValue(3)); expressionValues.put(":max_value", numberValue(5)); Expression expression = Expression.builder() .expression("#sort >= :min_value AND #sort <= :max_value") .expressionValues(expressionValues) .putExpressionName("#sort", "sort") .build(); Iterator<Page<EnhancedDocument>> results = neseteddocMappedtable.scan( ScanEnhancedRequest.builder() .filterExpression(expression) .addNestedAttributesToProject( NestedAttributeName.create(Arrays.asList("innerAttributeRecord","attribOne"))) .build() ).iterator(); assertThat(results.hasNext(), is(true)); Page<EnhancedDocument> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items().size(), is(3)); Collections.sort(page.items(), (item1, item2) -> item1.get("innerAttributeRecord", EnhancedType.of(InnerAttributeRecord.class)).getAttribOne() .compareTo(item2.get("innerAttributeRecord", EnhancedType.of(InnerAttributeRecord.class)).getAttribOne())); EnhancedDocument firstRecord = page.items().get(0); assertThat(firstRecord.getString("outerAttribOne"), is(nullValue())); assertThat(firstRecord.getNumber("sort"), is(nullValue())); assertThat(firstRecord.get("innerAttributeRecord", EnhancedType.of(InnerAttributeRecord.class)).getAttribOne(), is( "attribOne-3")); assertThat(firstRecord.get("innerAttributeRecord", EnhancedType.of(InnerAttributeRecord.class)).getAttribTwo(), is(nullValue())); //Attribute repeated with new and old attributeToProject results = neseteddocMappedtable.scan( ScanEnhancedRequest.builder() .filterExpression(expression) .addNestedAttributesToProject(NestedAttributeName.create("sort")) .addAttributeToProject("sort") .build() ).iterator(); assertThat(results.hasNext(), is(true)); page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items().size(), is(3)); Collections.sort(page.items(), (item1, item2) -> item1.getNumber("sort").bigDecimalValue() .compareTo(item2.getNumber("sort").bigDecimalValue())); firstRecord = page.items().get(0); assertThat(firstRecord.get("outerAttribOne", EnhancedType.of(InnerAttributeRecord.class)), is(nullValue())); assertThat(firstRecord.getNumber("sort").intValue(), is(3)); assertThat(firstRecord.get("innerAttributeRecord", EnhancedType.of(InnerAttributeRecord.class)), is(nullValue())); assertThat(firstRecord.get("innerAttributeRecord", EnhancedType.of(InnerAttributeRecord.class)), is(nullValue())); results = neseteddocMappedtable.scan( ScanEnhancedRequest.builder() .filterExpression(expression) .addNestedAttributeToProject( NestedAttributeName.create(Arrays.asList("innerAttributeRecord","attribOne"))) .build() ).iterator(); assertThat(results.hasNext(), is(true)); page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items().size(), is(3)); Collections.sort(page.items(), (item1, item2) -> item1.get("innerAttributeRecord", EnhancedType.of(InnerAttributeRecord.class)).getAttribOne() .compareTo(item2.get("innerAttributeRecord", EnhancedType.of(InnerAttributeRecord.class)).getAttribOne())); firstRecord = page.items().get(0); assertThat(firstRecord.getString("outerAttribOne"), is(nullValue())); assertThat(firstRecord.getNumber("sort"), is(nullValue())); assertThat(firstRecord.get("innerAttributeRecord", EnhancedType.of(InnerAttributeRecord.class)).getAttribOne(), is( "attribOne-3")); assertThat(firstRecord.get("innerAttributeRecord", EnhancedType.of(InnerAttributeRecord.class)).getAttribTwo(), is(nullValue())); } @Test public void scanAllRecordsWithFilterAndNestedProjectionMultipleAttribute() { insertNestedDocuments(); Map<String, AttributeValue> expressionValues = new HashMap<>(); expressionValues.put(":min_value", numberValue(3)); expressionValues.put(":max_value", numberValue(5)); Expression expression = Expression.builder() .expression("#sort >= :min_value AND #sort <= :max_value") .expressionValues(expressionValues) .putExpressionName("#sort", "sort") .build(); final ScanEnhancedRequest build = ScanEnhancedRequest.builder() .filterExpression(expression) .addAttributeToProject("outerAttribOne") .addNestedAttributesToProject(Arrays.asList(NestedAttributeName.builder().elements("innerAttributeRecord") .addElement("attribOne").build())) .addNestedAttributeToProject(NestedAttributeName.builder() .elements(Arrays.asList("innerAttributeRecord", "attribTwo")).build()) .build(); Iterator<Page<EnhancedDocument>> results = neseteddocMappedtable.scan( build ).iterator(); assertThat(results.hasNext(), is(true)); Page<EnhancedDocument> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items().size(), is(3)); Collections.sort(page.items(), (item1, item2) -> item1.get("innerAttributeRecord", EnhancedType.of(InnerAttributeRecord.class)).getAttribOne() .compareTo(item2.get("innerAttributeRecord", EnhancedType.of(InnerAttributeRecord.class)).getAttribOne())); EnhancedDocument firstRecord = page.items().get(0); assertThat(firstRecord.getString("outerAttribOne"), is("id-value-3")); assertThat(firstRecord.getNumber("sort"), is(nullValue())); assertThat(firstRecord.get("innerAttributeRecord", EnhancedType.of(InnerAttributeRecord.class)).getAttribOne(), is( "attribOne-3")); assertThat(firstRecord.get("innerAttributeRecord", EnhancedType.of(InnerAttributeRecord.class)).getAttribTwo(), is(3)); } @Test public void scanAllRecordsWithNonExistigKeyName() { insertNestedDocuments(); Map<String, AttributeValue> expressionValues = new HashMap<>(); expressionValues.put(":min_value", numberValue(3)); expressionValues.put(":max_value", numberValue(5)); Expression expression = Expression.builder() .expression("#sort >= :min_value AND #sort <= :max_value") .expressionValues(expressionValues) .putExpressionName("#sort", "sort") .build(); Iterator<Page<EnhancedDocument>> results = neseteddocMappedtable.scan( ScanEnhancedRequest.builder() .filterExpression(expression) .addNestedAttributesToProject(NestedAttributeName.builder().addElement("nonExistent").build()) .build() ).iterator(); assertThat(results.hasNext(), is(true)); Page<EnhancedDocument> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items().size(), is(3)); EnhancedDocument firstRecord = page.items().get(0); assertThat(firstRecord, is(nullValue())); } @Test public void scanAllRecordsWithDotInAttributeKeyName() { insertNestedDocuments(); Map<String, AttributeValue> expressionValues = new HashMap<>(); expressionValues.put(":min_value", numberValue(3)); expressionValues.put(":max_value", numberValue(5)); Expression expression = Expression.builder() .expression("#sort >= :min_value AND #sort <= :max_value") .expressionValues(expressionValues) .putExpressionName("#sort", "sort") .build(); Iterator<Page<EnhancedDocument>> results = neseteddocMappedtable.scan( ScanEnhancedRequest.builder() .filterExpression(expression) .addNestedAttributesToProject(NestedAttributeName .create("test.com")).build() ).iterator(); assertThat(results.hasNext(), is(true)); Page<EnhancedDocument> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items().size(), is(3)); Collections.sort(page.items(), (item1, item2) -> item1.getString("test.com") .compareTo(item2.getString("test.com"))); EnhancedDocument firstRecord = page.items().get(0); assertThat(firstRecord.getString("uterAttribOne"), is(nullValue())); assertThat(firstRecord.getNumber("sort"), is(nullValue())); assertThat(firstRecord.getString("test.com"), is("v3")); assertThat(firstRecord.get("innerAttributeRecord", EnhancedType.of(InnerAttributeRecord.class)), is(nullValue())); assertThat(firstRecord.get("innerAttributeRecord", EnhancedType.of(InnerAttributeRecord.class)), is(nullValue())); } @Test public void scanAllRecordsWithSameNamesRepeated() { //Attribute repeated with new and old attributeToProject insertNestedDocuments(); Map<String, AttributeValue> expressionValues = new HashMap<>(); expressionValues.put(":min_value", numberValue(3)); expressionValues.put(":max_value", numberValue(5)); Expression expression = Expression.builder() .expression("#sort >= :min_value AND #sort <= :max_value") .expressionValues(expressionValues) .putExpressionName("#sort", "sort") .build(); Iterator<Page<EnhancedDocument> >results = neseteddocMappedtable.scan( ScanEnhancedRequest.builder() .filterExpression(expression) .addNestedAttributesToProject(NestedAttributeName.builder().elements("sort").build()) .addAttributeToProject("sort") .build() ).iterator(); assertThat(results.hasNext(), is(true)); Page<EnhancedDocument> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items().size(), is(3)); Collections.sort(page.items(), (item1, item2) -> item1.getNumber("sort").bigDecimalValue() .compareTo(item2.getNumber("sort").bigDecimalValue())); EnhancedDocument firstRecord = page.items().get(0); assertThat(firstRecord.getString("outerAttribOne"), is(nullValue())); assertThat(firstRecord.getNumber("sort").intValue(), is(3)); assertThat(firstRecord.get("innerAttributeRecord", EnhancedType.of(InnerAttributeRecord.class)), is(nullValue())); assertThat(firstRecord.get("innerAttributeRecord", EnhancedType.of(InnerAttributeRecord.class)), is(nullValue())); } @Test public void scanAllRecordsWithEmptyList() { //Attribute repeated with new and old attributeToProject insertNestedDocuments(); Map<String, AttributeValue> expressionValues = new HashMap<>(); expressionValues.put(":min_value", numberValue(3)); expressionValues.put(":max_value", numberValue(5)); Expression expression = Expression.builder() .expression("#sort >= :min_value AND #sort <= :max_value") .expressionValues(expressionValues) .putExpressionName("#sort", "sort") .build(); Iterator<Page<EnhancedDocument> >results = neseteddocMappedtable.scan( ScanEnhancedRequest.builder() .filterExpression(expression) .addNestedAttributesToProject(new ArrayList<>()) .build() ).iterator(); assertThat(results.hasNext(), is(true)); Page<EnhancedDocument> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items().size(), is(3)); Collections.sort(page.items(), (item1, item2) -> item1.getNumber("sort").bigDecimalValue() .compareTo(item2.getNumber("sort").bigDecimalValue())); EnhancedDocument firstRecord = page.items().get(0); assertThat(firstRecord.getString("outerAttribOne"), is("id-value-3")); assertThat(firstRecord.getNumber("sort").intValue(), is(3)); assertThat(firstRecord.get("innerAttributeRecord", EnhancedType.of(InnerAttributeRecord.class)).getAttribTwo(), is(3)); assertThat(firstRecord.get("innerAttributeRecord", EnhancedType.of(InnerAttributeRecord.class)).getAttribOne(), is("attribOne-3")); } @Test public void scanAllRecordsWithNullAttributesToProject() { //Attribute repeated with new and old attributeToProject insertNestedDocuments(); List<String> backwardCompatibilityNull = null; Map<String, AttributeValue> expressionValues = new HashMap<>(); expressionValues.put(":min_value", numberValue(3)); expressionValues.put(":max_value", numberValue(5)); Expression expression = Expression.builder() .expression("#sort >= :min_value AND #sort <= :max_value") .expressionValues(expressionValues) .putExpressionName("#sort", "sort") .build(); Iterator<Page<EnhancedDocument> >results = neseteddocMappedtable.scan( ScanEnhancedRequest.builder() .filterExpression(expression) .attributesToProject("test.com") .attributesToProject(backwardCompatibilityNull) .build() ).iterator(); assertThat(results.hasNext(), is(true)); Page<EnhancedDocument> page = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page.items().size(), is(3)); Collections.sort(page.items(), (item1, item2) -> item1.getNumber("sort").bigDecimalValue() .compareTo(item2.getNumber("sort").bigDecimalValue())); EnhancedDocument firstRecord = page.items().get(0); assertThat(firstRecord.getString("outerAttribOne"), is("id-value-3")); assertThat(firstRecord.getNumber("sort").intValue(), is(3)); assertThat(firstRecord.get("innerAttributeRecord", EnhancedType.of(InnerAttributeRecord.class)).getAttribTwo(), is(3)); assertThat(firstRecord.get("innerAttributeRecord", EnhancedType.of(InnerAttributeRecord.class)).getAttribOne(), is( "attribOne-3")); } @Test public void scanAllRecordsWithNestedProjectionNameEmptyNameMap() { insertNestedDocuments(); Map<String, AttributeValue> expressionValues = new HashMap<>(); expressionValues.put(":min_value", numberValue(3)); expressionValues.put(":max_value", numberValue(5)); Expression expression = Expression.builder() .expression("#sort >= :min_value AND #sort <= :max_value") .expressionValues(expressionValues) .putExpressionName("#sort", "sort") .build(); final Iterator<Page<EnhancedDocument>> results = neseteddocMappedtable.scan( ScanEnhancedRequest.builder() .filterExpression(expression) .addNestedAttributesToProject(NestedAttributeName.builder().elements("").build()).build() ).iterator(); assertThatExceptionOfType(Exception.class).isThrownBy(() -> { final boolean b = results.hasNext(); Page<EnhancedDocument> next = results.next(); }).withMessageContaining("ExpressionAttributeNames contains invalid " + "value"); final Iterator<Page<EnhancedDocument>> resultsAttributeToProject = neseteddocMappedtable.scan( ScanEnhancedRequest.builder() .filterExpression(expression) .addAttributeToProject("").build() ).iterator(); assertThatExceptionOfType(Exception.class).isThrownBy(() -> { final boolean b = resultsAttributeToProject.hasNext(); Page<EnhancedDocument> next = resultsAttributeToProject.next(); }); } }
4,197
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper/StaticAttributeTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.mapper; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.function.BiConsumer; import java.util.function.Function; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.enhanced.dynamodb.AttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.EnhancedType; @RunWith(MockitoJUnitRunner.class) public class StaticAttributeTest { private static final Function<Object, String> TEST_GETTER = x -> "test-getter"; private static final BiConsumer<Object, String> TEST_SETTER = (x, y) -> {}; @Mock private StaticAttributeTag mockTag; @Mock private StaticAttributeTag mockTag2; @Mock private AttributeConverter<String> attributeConverter; @Test public void build_maximal() { StaticAttribute<Object, String> staticAttribute = StaticAttribute.builder(Object.class, String.class) .name("test-attribute") .getter(TEST_GETTER) .setter(TEST_SETTER) .tags(mockTag) .attributeConverter(attributeConverter) .build(); assertThat(staticAttribute.name()).isEqualTo("test-attribute"); assertThat(staticAttribute.getter()).isSameAs(TEST_GETTER); assertThat(staticAttribute.setter()).isSameAs(TEST_SETTER); assertThat(staticAttribute.tags()).containsExactly(mockTag); assertThat(staticAttribute.type()).isEqualTo(EnhancedType.of(String.class)); assertThat(staticAttribute.attributeConverter()).isSameAs(attributeConverter); } @Test public void build_minimal() { StaticAttribute<Object, String> staticAttribute = StaticAttribute.builder(Object.class, String.class) .name("test-attribute") .getter(TEST_GETTER) .setter(TEST_SETTER) .build(); assertThat(staticAttribute.name()).isEqualTo("test-attribute"); assertThat(staticAttribute.getter()).isSameAs(TEST_GETTER); assertThat(staticAttribute.setter()).isSameAs(TEST_SETTER); assertThat(staticAttribute.tags()).isEmpty(); assertThat(staticAttribute.type()).isEqualTo(EnhancedType.of(String.class)); } @Test public void build_missing_name() { assertThatThrownBy(() -> StaticAttribute.builder(Object.class, String.class) .getter(TEST_GETTER) .setter(TEST_SETTER) .build()) .isInstanceOf(NullPointerException.class) .hasMessageContaining("name"); } @Test public void build_missing_getter() { assertThatThrownBy(() -> StaticAttribute.builder(Object.class, String.class) .name("test-attribute") .setter(TEST_SETTER) .build()) .isInstanceOf(NullPointerException.class) .hasMessageContaining("getter"); } @Test public void build_missing_setter() { assertThatThrownBy(() -> StaticAttribute.builder(Object.class, String.class) .name("test-attribute") .getter(TEST_GETTER) .build()) .isInstanceOf(NullPointerException.class) .hasMessageContaining("setter"); } @Test public void toBuilder() { StaticAttribute<Object, String> staticAttribute = StaticAttribute.builder(Object.class, String.class) .name("test-attribute") .getter(TEST_GETTER) .setter(TEST_SETTER) .tags(mockTag, mockTag2) .attributeConverter(attributeConverter) .build(); StaticAttribute<Object, String> clonedAttribute = staticAttribute.toBuilder().build(); assertThat(clonedAttribute.name()).isEqualTo("test-attribute"); assertThat(clonedAttribute.getter()).isSameAs(TEST_GETTER); assertThat(clonedAttribute.setter()).isSameAs(TEST_SETTER); assertThat(clonedAttribute.tags()).containsExactly(mockTag, mockTag2); assertThat(clonedAttribute.type()).isEqualTo(EnhancedType.of(String.class)); assertThat(clonedAttribute.attributeConverter()).isSameAs(attributeConverter); } @Test public void build_addTag_single() { StaticAttribute<Object, String> staticAttribute = StaticAttribute.builder(Object.class, String.class) .name("test-attribute") .getter(TEST_GETTER) .setter(TEST_SETTER) .addTag(mockTag) .build(); assertThat(staticAttribute.tags()).containsExactly(mockTag); } @Test public void build_addTag_multiple() { StaticAttribute<Object, String> staticAttribute = StaticAttribute.builder(Object.class, String.class) .name("test-attribute") .getter(TEST_GETTER) .setter(TEST_SETTER) .addTag(mockTag) .addTag(mockTag2) .build(); assertThat(staticAttribute.tags()).containsExactly(mockTag, mockTag2); } @Test public void build_addAttributeConverter() { StaticAttribute<Object, String> staticAttribute = StaticAttribute.builder(Object.class, String.class) .name("test-attribute") .getter(TEST_GETTER) .setter(TEST_SETTER) .attributeConverter(attributeConverter) .build(); AttributeConverter<String> attributeConverterR = staticAttribute.attributeConverter(); assertThat(attributeConverterR).isEqualTo(attributeConverter); } }
4,198
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper/StaticImmutableTableSchemaExtendTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.mapper; import static org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Test; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; public class StaticImmutableTableSchemaExtendTest { private static final ImmutableRecord TEST_RECORD = ImmutableRecord.builder() .id("id123") .attribute1("one") .attribute2(2) .attribute3("three") .build(); private static final Map<String, AttributeValue> ITEM_MAP; static { Map<String, AttributeValue> map = new HashMap<>(); map.put("id", AttributeValue.builder().s("id123").build()); map.put("attribute1", AttributeValue.builder().s("one").build()); map.put("attribute2", AttributeValue.builder().n("2").build()); map.put("attribute3", AttributeValue.builder().s("three").build()); ITEM_MAP = Collections.unmodifiableMap(map); } private final TableSchema<ImmutableRecord> immutableTableSchema = TableSchema.builder(ImmutableRecord.class, ImmutableRecord.Builder.class) .newItemBuilder(ImmutableRecord::builder, ImmutableRecord.Builder::build) .addAttribute(String.class, a -> a.name("id") .getter(ImmutableRecord::id) .setter(ImmutableRecord.Builder::id) .tags(primaryPartitionKey())) .addAttribute(String.class, a -> a.name("attribute1") .getter(ImmutableRecord::attribute1) .setter(ImmutableRecord.Builder::attribute1)) .addAttribute(int.class, a -> a.name("attribute2") .getter(ImmutableRecord::attribute2) .setter(ImmutableRecord.Builder::attribute2)) .extend(TableSchema.builder(SuperRecord.class, SuperRecord.Builder.class) .addAttribute(String.class, a -> a.name("attribute3") .getter(SuperRecord::attribute3) .setter(SuperRecord.Builder::attribute3)) .build()) .build(); @Test public void itemToMap() { Map<String, AttributeValue> result = immutableTableSchema.itemToMap(TEST_RECORD, false); assertThat(result).isEqualTo(ITEM_MAP); } @Test public void mapToItem() { ImmutableRecord record = immutableTableSchema.mapToItem(ITEM_MAP); assertThat(record).isEqualTo(TEST_RECORD); } public static class ImmutableRecord extends SuperRecord { private final String id; private final String attribute1; private final int attribute2; public ImmutableRecord(Builder b) { super(b); this.id = b.id; this.attribute1 = b.attribute1; this.attribute2 = b.attribute2; } public static Builder builder() { return new Builder(); } public String id() { return id; } public String attribute1() { return attribute1; } public int attribute2() { return attribute2; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ImmutableRecord that = (ImmutableRecord) o; if (attribute2 != that.attribute2) return false; if (id != null ? !id.equals(that.id) : that.id != null) return false; return attribute1 != null ? attribute1.equals(that.attribute1) : that.attribute1 == null; } @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + (attribute1 != null ? attribute1.hashCode() : 0); result = 31 * result + attribute2; return result; } public static class Builder extends SuperRecord.Builder<Builder> { private String id; private String attribute1; private int attribute2; public Builder id(String id) { this.id = id; return this; } public Builder attribute1(String attribute1) { this.attribute1 = attribute1; return this; } public Builder attribute2(int attribute2) { this.attribute2 = attribute2; return this; } public ImmutableRecord build() { return new ImmutableRecord(this); } } } public static class SuperRecord { private final String attribute3; public SuperRecord(Builder<?> b) { this.attribute3 = b.attribute3; } public String attribute3() { return attribute3; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SuperRecord that = (SuperRecord) o; return attribute3 != null ? attribute3.equals(that.attribute3) : that.attribute3 == null; } @Override public int hashCode() { return attribute3 != null ? attribute3.hashCode() : 0; } public static class Builder<T extends Builder<T>> { private String attribute3; public T attribute3(String attribute3) { this.attribute3 = attribute3; return (T) this; } } } }
4,199