index
int64
0
0
repo_id
stringlengths
26
205
file_path
stringlengths
51
246
content
stringlengths
8
433k
__index_level_0__
int64
0
10k
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); } } }
3,900
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; } }
3,901
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); } } }
3,902
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); } }
3,903
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 }
3,904
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); } }
3,905
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; } }
3,906
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); } } }
3,907
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); } }
3,908
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 + '\'' + '}'; } }
3,909
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); } } }
3,910
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); } } }
3,911
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; } }
3,912
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; } }
3,913
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; } }
3,914
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); } }
3,915
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); } }
3,916
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); } } }
3,917
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); } }
3,918
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(); } }
3,919
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())); } }
3,920
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(); }); } }
3,921
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()); } }
3,922
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==\"}" )); } }
3,923
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(); }); } }
3,924
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); } }
3,925
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; } } } }
3,926
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/BeanTableSchemaTest.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 java.util.Collections.emptyMap; import static java.util.Collections.singletonMap; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasEntry; import static org.hamcrest.Matchers.is; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.binaryValue; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.nullAttributeValue; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.numberValue; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.stringValue; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Optional; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.enhanced.dynamodb.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues; import software.amazon.awssdk.enhanced.dynamodb.mapper.testbeans.AbstractBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.testbeans.AbstractImmutable; import software.amazon.awssdk.enhanced.dynamodb.mapper.testbeans.AttributeConverterBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.testbeans.AttributeConverterNoConstructorBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.testbeans.CommonTypesBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.testbeans.DocumentBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.testbeans.EmptyConverterProvidersInvalidBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.testbeans.EmptyConverterProvidersValidBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.testbeans.EnumBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.testbeans.ExtendedBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.testbeans.FlattenedBeanBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.testbeans.FlattenedImmutableBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.testbeans.IgnoredAttributeBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.testbeans.InvalidBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.testbeans.ListBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.testbeans.MapBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.testbeans.MultipleConverterProvidersBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.testbeans.NestedBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.testbeans.NestedBeanIgnoreNulls; import software.amazon.awssdk.enhanced.dynamodb.mapper.testbeans.NoConstructorConverterProvidersBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.testbeans.ParameterizedAbstractBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.testbeans.ParameterizedDocumentBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.testbeans.PrimitiveTypesBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.testbeans.RemappedAttributeBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.testbeans.SecondaryIndexBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.testbeans.SetBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.testbeans.SetterAnnotatedBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.testbeans.SimpleBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.testbeans.SingleConverterProvidersBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.testbeans.SortKeyBean; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; @RunWith(MockitoJUnitRunner.class) public class BeanTableSchemaTest { @Rule public ExpectedException exception = ExpectedException.none(); @Test public void simpleBean_correctlyAssignsPrimaryPartitionKey() { BeanTableSchema<SimpleBean> beanTableSchema = BeanTableSchema.create(SimpleBean.class); assertThat(beanTableSchema.tableMetadata().primaryPartitionKey(), is("id")); } @Test public void sortKeyBean_correctlyAssignsSortKey() { BeanTableSchema<SortKeyBean> beanTableSchema = BeanTableSchema.create(SortKeyBean.class); assertThat(beanTableSchema.tableMetadata().primarySortKey(), is(Optional.of("sort"))); } @Test public void simpleBean_hasNoSortKey() { BeanTableSchema<SimpleBean> beanTableSchema = BeanTableSchema.create(SimpleBean.class); assertThat(beanTableSchema.tableMetadata().primarySortKey(), is(Optional.empty())); } @Test public void simpleBean_hasNoAdditionalKeys() { BeanTableSchema<SimpleBean> beanTableSchema = BeanTableSchema.create(SimpleBean.class); assertThat(beanTableSchema.tableMetadata().allKeys(), contains("id")); } @Test public void sortKeyBean_hasNoAdditionalKeys() { BeanTableSchema<SortKeyBean> beanTableSchema = BeanTableSchema.create(SortKeyBean.class); assertThat(beanTableSchema.tableMetadata().allKeys(), containsInAnyOrder("id", "sort")); } @Test public void secondaryIndexBean_definesGsiCorrectly() { BeanTableSchema<SecondaryIndexBean> beanTableSchema = BeanTableSchema.create(SecondaryIndexBean.class); assertThat(beanTableSchema.tableMetadata().indexPartitionKey("gsi"), is("sort")); assertThat(beanTableSchema.tableMetadata().indexSortKey("gsi"), is(Optional.of("attribute"))); } @Test public void secondaryIndexBean_definesLsiCorrectly() { BeanTableSchema<SecondaryIndexBean> beanTableSchema = BeanTableSchema.create(SecondaryIndexBean.class); assertThat(beanTableSchema.tableMetadata().indexPartitionKey("lsi"), is("id")); assertThat(beanTableSchema.tableMetadata().indexSortKey("lsi"), is(Optional.of("attribute"))); } @Test public void dynamoDbIgnore_propertyIsIgnored() { BeanTableSchema<IgnoredAttributeBean> beanTableSchema = BeanTableSchema.create(IgnoredAttributeBean.class); IgnoredAttributeBean ignoredAttributeBean = new IgnoredAttributeBean(); ignoredAttributeBean.setId("id-value"); ignoredAttributeBean.setIntegerAttribute(123); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(ignoredAttributeBean, false); assertThat(itemMap.size(), is(1)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); } @Test public void transient_propertyIsIgnored() { BeanTableSchema<IgnoredAttributeBean> beanTableSchema = BeanTableSchema.create(IgnoredAttributeBean.class); IgnoredAttributeBean ignoredAttributeBean = new IgnoredAttributeBean(); ignoredAttributeBean.setId("id-value"); ignoredAttributeBean.setInteger2Attribute(123); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(ignoredAttributeBean, false); assertThat(itemMap.size(), is(1)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); } @Test public void setterAnnotations_alsoWork() { BeanTableSchema<SetterAnnotatedBean> beanTableSchema = BeanTableSchema.create(SetterAnnotatedBean.class); SetterAnnotatedBean setterAnnotatedBean = new SetterAnnotatedBean(); setterAnnotatedBean.setId("id-value"); setterAnnotatedBean.setIntegerAttribute(123); setterAnnotatedBean.setInteger2Attribute(123); assertThat(beanTableSchema.tableMetadata().primaryPartitionKey(), is("id")); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(setterAnnotatedBean, false); assertThat(itemMap.size(), is(1)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); } @Test public void dynamoDbAttribute_remapsAttributeName() { BeanTableSchema<RemappedAttributeBean> beanTableSchema = BeanTableSchema.create(RemappedAttributeBean.class); assertThat(beanTableSchema.tableMetadata().primaryPartitionKey(), is("remappedAttribute")); } @Test public void dynamoDbFlatten_correctlyFlattensBeanAttributes() { BeanTableSchema<FlattenedBeanBean> beanTableSchema = BeanTableSchema.create(FlattenedBeanBean.class); AbstractBean abstractBean = new AbstractBean(); abstractBean.setAttribute2("two"); FlattenedBeanBean flattenedBeanBean = new FlattenedBeanBean(); flattenedBeanBean.setId("id-value"); flattenedBeanBean.setAttribute1("one"); flattenedBeanBean.setAbstractBean(abstractBean); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(flattenedBeanBean, false); assertThat(itemMap.size(), is(3)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("attribute1", stringValue("one"))); assertThat(itemMap, hasEntry("attribute2", stringValue("two"))); } @Test public void dynamoDbPreserveEmptyObject_shouldInitializeAsEmptyClass() { BeanTableSchema<NestedBean> beanTableSchema = BeanTableSchema.create(NestedBean.class); AbstractBean innerPreserveEmptyBean = new AbstractBean(); NestedBean bean = new NestedBean(); bean.setInnerBean(innerPreserveEmptyBean); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(bean, true); NestedBean nestedBean = beanTableSchema.mapToItem(itemMap); assertThat(nestedBean.getInnerBean(), is(innerPreserveEmptyBean)); } @Test public void dynamoDbIgnoreNulls_shouldOmitNulls() { BeanTableSchema<NestedBeanIgnoreNulls> beanTableSchema = BeanTableSchema.create(NestedBeanIgnoreNulls.class); NestedBeanIgnoreNulls bean = new NestedBeanIgnoreNulls(); bean.setInnerBean1(new AbstractBean()); bean.setInnerBean2(new AbstractBean()); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(bean, true); AttributeValue expectedMapForInnerBean1 = AttributeValue.builder().m(new HashMap<>()).build(); assertThat(itemMap.size(), is(2)); assertThat(itemMap, hasEntry("innerBean1", expectedMapForInnerBean1)); assertThat(itemMap.get("innerBean2").m(), hasEntry("attribute2", nullAttributeValue())); } @Test public void dynamoDbIgnoreNulls_onList_shouldOmitNulls() { BeanTableSchema<NestedBeanIgnoreNulls> beanTableSchema = BeanTableSchema.create(NestedBeanIgnoreNulls.class); NestedBeanIgnoreNulls bean = new NestedBeanIgnoreNulls(); bean.setInnerBeanList1(Collections.singletonList(new AbstractBean())); bean.setInnerBeanList2(Collections.singletonList(new AbstractBean())); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(bean, true); AttributeValue expectedMapForInnerBean1 = AttributeValue.builder().l(l -> l.m(emptyMap())).build(); AttributeValue expectedMapForInnerBean2 = AttributeValue.builder() .l(l -> l.m(singletonMap("attribute2", nullAttributeValue()))) .build(); assertThat(itemMap.size(), is(2)); assertThat(itemMap, hasEntry("innerBeanList1", expectedMapForInnerBean1)); assertThat(itemMap, hasEntry("innerBeanList2", expectedMapForInnerBean2)); } @Test public void dynamoDbFlatten_correctlyFlattensImmutableAttributes() { BeanTableSchema<FlattenedImmutableBean> beanTableSchema = BeanTableSchema.create(FlattenedImmutableBean.class); AbstractImmutable abstractImmutable = AbstractImmutable.builder().attribute2("two").build(); FlattenedImmutableBean flattenedImmutableBean = new FlattenedImmutableBean(); flattenedImmutableBean.setId("id-value"); flattenedImmutableBean.setAttribute1("one"); flattenedImmutableBean.setAbstractImmutable(abstractImmutable); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(flattenedImmutableBean, false); assertThat(itemMap.size(), is(3)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("attribute1", stringValue("one"))); assertThat(itemMap, hasEntry("attribute2", stringValue("two"))); } @Test public void documentBean_correctlyMapsBeanAttributes() { BeanTableSchema<DocumentBean> beanTableSchema = BeanTableSchema.create(DocumentBean.class); AbstractBean abstractBean = new AbstractBean(); abstractBean.setAttribute2("two"); DocumentBean documentBean = new DocumentBean(); documentBean.setId("id-value"); documentBean.setAttribute1("one"); documentBean.setAbstractBean(abstractBean); AttributeValue expectedDocument = AttributeValue.builder() .m(singletonMap("attribute2", stringValue("two"))) .build(); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(documentBean, true); assertThat(itemMap.size(), is(3)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("attribute1", stringValue("one"))); assertThat(itemMap, hasEntry("abstractBean", expectedDocument)); } @Test public void documentBean_list_correctlyMapsBeanAttributes() { BeanTableSchema<DocumentBean> beanTableSchema = BeanTableSchema.create(DocumentBean.class); AbstractBean abstractBean1 = new AbstractBean(); abstractBean1.setAttribute2("two"); AbstractBean abstractBean2 = new AbstractBean(); abstractBean2.setAttribute2("three"); DocumentBean documentBean = new DocumentBean(); documentBean.setId("id-value"); documentBean.setAttribute1("one"); documentBean.setAbstractBeanList(Arrays.asList(abstractBean1, abstractBean2)); AttributeValue expectedDocument1 = AttributeValue.builder() .m(singletonMap("attribute2", stringValue("two"))) .build(); AttributeValue expectedDocument2 = AttributeValue.builder() .m(singletonMap("attribute2", stringValue("three"))) .build(); AttributeValue expectedList = AttributeValue.builder().l(expectedDocument1, expectedDocument2).build(); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(documentBean, true); assertThat(itemMap.size(), is(3)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("attribute1", stringValue("one"))); assertThat(itemMap, hasEntry("abstractBeanList", expectedList)); } @Test public void documentBean_map_correctlyMapsBeanAttributes() { BeanTableSchema<DocumentBean> beanTableSchema = BeanTableSchema.create(DocumentBean.class); AbstractBean abstractBean1 = new AbstractBean(); abstractBean1.setAttribute2("two"); AbstractBean abstractBean2 = new AbstractBean(); abstractBean2.setAttribute2("three"); DocumentBean documentBean = new DocumentBean(); documentBean.setId("id-value"); documentBean.setAttribute1("one"); Map<String, AbstractBean> abstractBeanMap = new HashMap<>(); abstractBeanMap.put("key1", abstractBean1); abstractBeanMap.put("key2", abstractBean2); documentBean.setAbstractBeanMap(abstractBeanMap); AttributeValue expectedDocument1 = AttributeValue.builder() .m(singletonMap("attribute2", stringValue("two"))) .build(); AttributeValue expectedDocument2 = AttributeValue.builder() .m(singletonMap("attribute2", stringValue("three"))) .build(); Map<String, AttributeValue> expectedAttributeValueMap = new HashMap<>(); expectedAttributeValueMap.put("key1", expectedDocument1); expectedAttributeValueMap.put("key2", expectedDocument2); AttributeValue expectedMap = AttributeValue.builder().m(expectedAttributeValueMap).build(); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(documentBean, true); assertThat(itemMap.size(), is(3)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("attribute1", stringValue("one"))); assertThat(itemMap, hasEntry("abstractBeanMap", expectedMap)); } @Test public void documentBean_correctlyMapsImmutableAttributes() { BeanTableSchema<DocumentBean> beanTableSchema = BeanTableSchema.create(DocumentBean.class); AbstractImmutable abstractImmutable = AbstractImmutable.builder().attribute2("two").build(); DocumentBean documentBean = new DocumentBean(); documentBean.setId("id-value"); documentBean.setAttribute1("one"); documentBean.setAbstractImmutable(abstractImmutable); AttributeValue expectedDocument = AttributeValue.builder() .m(singletonMap("attribute2", stringValue("two"))) .build(); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(documentBean, true); assertThat(itemMap.size(), is(3)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("attribute1", stringValue("one"))); assertThat(itemMap, hasEntry("abstractImmutable", expectedDocument)); } @Test public void documentBean_list_correctlyMapsImmutableAttributes() { BeanTableSchema<DocumentBean> beanTableSchema = BeanTableSchema.create(DocumentBean.class); AbstractImmutable abstractImmutable1 = AbstractImmutable.builder().attribute2("two").build(); AbstractImmutable abstractImmutable2 = AbstractImmutable.builder().attribute2("three").build(); DocumentBean documentBean = new DocumentBean(); documentBean.setId("id-value"); documentBean.setAttribute1("one"); documentBean.setAbstractImmutableList(Arrays.asList(abstractImmutable1, abstractImmutable2)); AttributeValue expectedDocument1 = AttributeValue.builder() .m(singletonMap("attribute2", stringValue("two"))) .build(); AttributeValue expectedDocument2 = AttributeValue.builder() .m(singletonMap("attribute2", stringValue("three"))) .build(); AttributeValue expectedList = AttributeValue.builder().l(expectedDocument1, expectedDocument2).build(); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(documentBean, true); assertThat(itemMap.size(), is(3)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("attribute1", stringValue("one"))); assertThat(itemMap, hasEntry("abstractImmutableList", expectedList)); } @Test public void documentBean_map_correctlyMapsImmutableAttributes() { BeanTableSchema<DocumentBean> beanTableSchema = BeanTableSchema.create(DocumentBean.class); AbstractImmutable abstractImmutable1 = AbstractImmutable.builder().attribute2("two").build(); AbstractImmutable abstractImmutable2 = AbstractImmutable.builder().attribute2("three").build(); DocumentBean documentBean = new DocumentBean(); documentBean.setId("id-value"); documentBean.setAttribute1("one"); Map<String, AbstractImmutable> abstractImmutableMap = new HashMap<>(); abstractImmutableMap.put("key1", abstractImmutable1); abstractImmutableMap.put("key2", abstractImmutable2); documentBean.setAbstractImmutableMap(abstractImmutableMap); AttributeValue expectedDocument1 = AttributeValue.builder() .m(singletonMap("attribute2", stringValue("two"))) .build(); AttributeValue expectedDocument2 = AttributeValue.builder() .m(singletonMap("attribute2", stringValue("three"))) .build(); Map<String, AttributeValue> expectedAttributeValueMap = new HashMap<>(); expectedAttributeValueMap.put("key1", expectedDocument1); expectedAttributeValueMap.put("key2", expectedDocument2); AttributeValue expectedMap = AttributeValue.builder().m(expectedAttributeValueMap).build(); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(documentBean, true); assertThat(itemMap.size(), is(3)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("attribute1", stringValue("one"))); assertThat(itemMap, hasEntry("abstractImmutableMap", expectedMap)); } @Test public void parameterizedDocumentBean_correctlyMapsAttributes() { BeanTableSchema<ParameterizedDocumentBean> beanTableSchema = BeanTableSchema.create(ParameterizedDocumentBean.class); ParameterizedAbstractBean<String> abstractBean = new ParameterizedAbstractBean<>(); abstractBean.setAttribute2("two"); ParameterizedDocumentBean documentBean = new ParameterizedDocumentBean(); documentBean.setId("id-value"); documentBean.setAttribute1("one"); documentBean.setAbstractBean(abstractBean); AttributeValue expectedDocument = AttributeValue.builder() .m(singletonMap("attribute2", stringValue("two"))) .build(); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(documentBean, true); assertThat(itemMap.size(), is(3)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("attribute1", stringValue("one"))); assertThat(itemMap, hasEntry("abstractBean", expectedDocument)); } @Test public void parameterizedDocumentBean_list_correctlyMapsAttributes() { BeanTableSchema<ParameterizedDocumentBean> beanTableSchema = BeanTableSchema.create(ParameterizedDocumentBean.class); ParameterizedAbstractBean<String> abstractBean1 = new ParameterizedAbstractBean<>(); abstractBean1.setAttribute2("two"); ParameterizedAbstractBean<String> abstractBean2 = new ParameterizedAbstractBean<>(); abstractBean2.setAttribute2("three"); ParameterizedDocumentBean documentBean = new ParameterizedDocumentBean(); documentBean.setId("id-value"); documentBean.setAttribute1("one"); documentBean.setAbstractBeanList(Arrays.asList(abstractBean1, abstractBean2)); AttributeValue expectedDocument1 = AttributeValue.builder() .m(singletonMap("attribute2", stringValue("two"))) .build(); AttributeValue expectedDocument2 = AttributeValue.builder() .m(singletonMap("attribute2", stringValue("three"))) .build(); AttributeValue expectedList = AttributeValue.builder().l(expectedDocument1, expectedDocument2).build(); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(documentBean, true); assertThat(itemMap.size(), is(3)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("attribute1", stringValue("one"))); assertThat(itemMap, hasEntry("abstractBeanList", expectedList)); } @Test public void parameterizedDocumentBean_map_correctlyMapsAttributes() { BeanTableSchema<ParameterizedDocumentBean> beanTableSchema = BeanTableSchema.create(ParameterizedDocumentBean.class); ParameterizedAbstractBean<String> abstractBean1 = new ParameterizedAbstractBean<>(); abstractBean1.setAttribute2("two"); ParameterizedAbstractBean<String> abstractBean2 = new ParameterizedAbstractBean<>(); abstractBean2.setAttribute2("three"); ParameterizedDocumentBean documentBean = new ParameterizedDocumentBean(); documentBean.setId("id-value"); documentBean.setAttribute1("one"); Map<String, ParameterizedAbstractBean<String>> abstractBeanMap = new HashMap<>(); abstractBeanMap.put("key1", abstractBean1); abstractBeanMap.put("key2", abstractBean2); documentBean.setAbstractBeanMap(abstractBeanMap); AttributeValue expectedDocument1 = AttributeValue.builder() .m(singletonMap("attribute2", stringValue("two"))) .build(); AttributeValue expectedDocument2 = AttributeValue.builder() .m(singletonMap("attribute2", stringValue("three"))) .build(); Map<String, AttributeValue> expectedAttributeValueMap = new HashMap<>(); expectedAttributeValueMap.put("key1", expectedDocument1); expectedAttributeValueMap.put("key2", expectedDocument2); AttributeValue expectedMap = AttributeValue.builder().m(expectedAttributeValueMap).build(); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(documentBean, true); assertThat(itemMap.size(), is(3)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("attribute1", stringValue("one"))); assertThat(itemMap, hasEntry("abstractBeanMap", expectedMap)); } @Test public void extendedBean_correctlyExtendsAttributes() { BeanTableSchema<ExtendedBean> beanTableSchema = BeanTableSchema.create(ExtendedBean.class); ExtendedBean extendedBean = new ExtendedBean(); extendedBean.setId("id-value"); extendedBean.setAttribute1("one"); extendedBean.setAttribute2("two"); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(extendedBean, false); assertThat(itemMap.size(), is(3)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("attribute1", stringValue("one"))); assertThat(itemMap, hasEntry("attribute2", stringValue("two"))); } @Test(expected = IllegalArgumentException.class) public void invalidBean_throwsIllegalArgumentException() { BeanTableSchema.create(InvalidBean.class); } @Test public void itemToMap_nullAttribute_ignoreNullsTrue() { BeanTableSchema<SimpleBean> beanTableSchema = BeanTableSchema.create(SimpleBean.class); SimpleBean simpleBean = new SimpleBean(); simpleBean.setId("id-value"); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(simpleBean, true); assertThat(itemMap.size(), is(1)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); } @Test public void itemToMap_nullAttribute_ignoreNullsFalse() { BeanTableSchema<SimpleBean> beanTableSchema = BeanTableSchema.create(SimpleBean.class); SimpleBean simpleBean = new SimpleBean(); simpleBean.setId("id-value"); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(simpleBean, false); assertThat(itemMap.size(), is(2)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("integerAttribute", AttributeValues.nullAttributeValue())); } @Test public void itemToMap_nonNullAttribute() { BeanTableSchema<SimpleBean> beanTableSchema = BeanTableSchema.create(SimpleBean.class); SimpleBean simpleBean = new SimpleBean(); simpleBean.setId("id-value"); simpleBean.setIntegerAttribute(123); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(simpleBean, false); assertThat(itemMap.size(), is(2)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("integerAttribute", numberValue(123))); } @Test public void mapToItem_createsItem() { BeanTableSchema<SimpleBean> beanTableSchema = BeanTableSchema.create(SimpleBean.class); Map<String, AttributeValue> itemMap = new HashMap<>(); itemMap.put("id", stringValue("id-value")); itemMap.put("integerAttribute", numberValue(123)); SimpleBean expectedBean = new SimpleBean(); expectedBean.setId("id-value"); expectedBean.setIntegerAttribute(123); SimpleBean result = beanTableSchema.mapToItem(itemMap); assertThat(result, is(expectedBean)); } @Test public void attributeValue_returnsValue() { BeanTableSchema<SimpleBean> beanTableSchema = BeanTableSchema.create(SimpleBean.class); SimpleBean simpleBean = new SimpleBean(); simpleBean.setId("id-value"); simpleBean.setIntegerAttribute(123); assertThat(beanTableSchema.attributeValue(simpleBean, "integerAttribute"), is(numberValue(123))); } @Test public void enumBean_invalidEnum() { BeanTableSchema<EnumBean> beanTableSchema = BeanTableSchema.create(EnumBean.class); Map<String, AttributeValue> itemMap = new HashMap<>(); itemMap.put("id", stringValue("id-value")); itemMap.put("testEnum", stringValue("invalid-value")); exception.expect(IllegalArgumentException.class); exception.expectMessage("invalid-value"); exception.expectMessage("TestEnum"); beanTableSchema.mapToItem(itemMap); } @Test public void enumBean_singleEnum() { BeanTableSchema<EnumBean> beanTableSchema = BeanTableSchema.create(EnumBean.class); EnumBean enumBean = new EnumBean(); enumBean.setId("id-value"); enumBean.setTestEnum(EnumBean.TestEnum.ONE); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(enumBean, true); assertThat(itemMap.size(), is(2)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("testEnum", stringValue("ONE"))); EnumBean reverse = beanTableSchema.mapToItem(itemMap); assertThat(reverse, is(equalTo(enumBean))); } @Test public void enumBean_listEnum() { BeanTableSchema<EnumBean> beanTableSchema = BeanTableSchema.create(EnumBean.class); EnumBean enumBean = new EnumBean(); enumBean.setId("id-value"); enumBean.setTestEnumList(Arrays.asList(EnumBean.TestEnum.ONE, EnumBean.TestEnum.TWO)); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(enumBean, true); AttributeValue expectedAttributeValue = AttributeValue.builder() .l(stringValue("ONE"), stringValue("TWO")) .build(); assertThat(itemMap.size(), is(2)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("testEnumList", expectedAttributeValue)); EnumBean reverse = beanTableSchema.mapToItem(itemMap); assertThat(reverse, is(equalTo(enumBean))); } @Test public void listBean_stringList() { BeanTableSchema<ListBean> beanTableSchema = BeanTableSchema.create(ListBean.class); ListBean listBean = new ListBean(); listBean.setId("id-value"); listBean.setStringList(Arrays.asList("one", "two", "three")); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(listBean, true); AttributeValue expectedAttributeValue = AttributeValue.builder() .l(stringValue("one"), stringValue("two"), stringValue("three")) .build(); assertThat(itemMap.size(), is(2)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("stringList", expectedAttributeValue)); ListBean reverse = beanTableSchema.mapToItem(itemMap); assertThat(reverse, is(equalTo(listBean))); } @Test public void listBean_stringListList() { BeanTableSchema<ListBean> beanTableSchema = BeanTableSchema.create(ListBean.class); ListBean listBean = new ListBean(); listBean.setId("id-value"); listBean.setStringListList(Arrays.asList(Arrays.asList("one", "two"), Arrays.asList("three", "four"))); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(listBean, true); AttributeValue list1 = AttributeValue.builder().l(stringValue("one"), stringValue("two")).build(); AttributeValue list2 = AttributeValue.builder().l(stringValue("three"), stringValue("four")).build(); AttributeValue expectedAttributeValue = AttributeValue.builder() .l(list1, list2) .build(); assertThat(itemMap.size(), is(2)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("stringListList", expectedAttributeValue)); ListBean reverse = beanTableSchema.mapToItem(itemMap); assertThat(reverse, is(equalTo(listBean))); } @Test public void setBean_stringSet() { BeanTableSchema<SetBean> beanTableSchema = BeanTableSchema.create(SetBean.class); SetBean setBean = new SetBean(); setBean.setId("id-value"); LinkedHashSet<String> stringSet = new LinkedHashSet<>(); stringSet.add("one"); stringSet.add("two"); stringSet.add("three"); setBean.setStringSet(stringSet); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(setBean, true); AttributeValue expectedAttributeValue = AttributeValue.builder() .ss("one", "two", "three") .build(); assertThat(itemMap.size(), is(2)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("stringSet", expectedAttributeValue)); SetBean reverse = beanTableSchema.mapToItem(itemMap); assertThat(reverse, is(equalTo(setBean))); } @Test public void setBean_integerSet() { BeanTableSchema<SetBean> beanTableSchema = BeanTableSchema.create(SetBean.class); SetBean setBean = new SetBean(); setBean.setId("id-value"); LinkedHashSet<Integer> integerSet = new LinkedHashSet<>(); integerSet.add(1); integerSet.add(2); integerSet.add(3); setBean.setIntegerSet(integerSet); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(setBean, true); AttributeValue expectedAttributeValue = AttributeValue.builder() .ns("1", "2", "3") .build(); assertThat(itemMap.size(), is(2)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("integerSet", expectedAttributeValue)); SetBean reverse = beanTableSchema.mapToItem(itemMap); assertThat(reverse, is(equalTo(setBean))); } @Test public void setBean_longSet() { BeanTableSchema<SetBean> beanTableSchema = BeanTableSchema.create(SetBean.class); SetBean setBean = new SetBean(); setBean.setId("id-value"); LinkedHashSet<Long> longSet = new LinkedHashSet<>(); longSet.add(1L); longSet.add(2L); longSet.add(3L); setBean.setLongSet(longSet); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(setBean, true); AttributeValue expectedAttributeValue = AttributeValue.builder() .ns("1", "2", "3") .build(); assertThat(itemMap.size(), is(2)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("longSet", expectedAttributeValue)); SetBean reverse = beanTableSchema.mapToItem(itemMap); assertThat(reverse, is(equalTo(setBean))); } @Test public void setBean_shortSet() { BeanTableSchema<SetBean> beanTableSchema = BeanTableSchema.create(SetBean.class); SetBean setBean = new SetBean(); setBean.setId("id-value"); LinkedHashSet<Short> shortSet = new LinkedHashSet<>(); shortSet.add((short)1); shortSet.add((short)2); shortSet.add((short)3); setBean.setShortSet(shortSet); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(setBean, true); AttributeValue expectedAttributeValue = AttributeValue.builder() .ns("1", "2", "3") .build(); assertThat(itemMap.size(), is(2)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("shortSet", expectedAttributeValue)); SetBean reverse = beanTableSchema.mapToItem(itemMap); assertThat(reverse, is(equalTo(setBean))); } @Test public void setBean_byteSet() { BeanTableSchema<SetBean> beanTableSchema = BeanTableSchema.create(SetBean.class); SetBean setBean = new SetBean(); setBean.setId("id-value"); LinkedHashSet<Byte> byteSet = new LinkedHashSet<>(); byteSet.add((byte)1); byteSet.add((byte)2); byteSet.add((byte)3); setBean.setByteSet(byteSet); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(setBean, true); AttributeValue expectedAttributeValue = AttributeValue.builder() .ns("1", "2", "3") .build(); assertThat(itemMap.size(), is(2)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("byteSet", expectedAttributeValue)); SetBean reverse = beanTableSchema.mapToItem(itemMap); assertThat(reverse, is(equalTo(setBean))); } @Test public void setBean_doubleSet() { BeanTableSchema<SetBean> beanTableSchema = BeanTableSchema.create(SetBean.class); SetBean setBean = new SetBean(); setBean.setId("id-value"); LinkedHashSet<Double> doubleSet = new LinkedHashSet<>(); doubleSet.add(1.1); doubleSet.add(2.2); doubleSet.add(3.3); setBean.setDoubleSet(doubleSet); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(setBean, true); AttributeValue expectedAttributeValue = AttributeValue.builder() .ns("1.1", "2.2", "3.3") .build(); assertThat(itemMap.size(), is(2)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("doubleSet", expectedAttributeValue)); SetBean reverse = beanTableSchema.mapToItem(itemMap); assertThat(reverse, is(equalTo(setBean))); } @Test public void setBean_floatSet() { BeanTableSchema<SetBean> beanTableSchema = BeanTableSchema.create(SetBean.class); SetBean setBean = new SetBean(); setBean.setId("id-value"); LinkedHashSet<Float> floatSet = new LinkedHashSet<>(); floatSet.add(1.1f); floatSet.add(2.2f); floatSet.add(3.3f); setBean.setFloatSet(floatSet); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(setBean, true); AttributeValue expectedAttributeValue = AttributeValue.builder() .ns("1.1", "2.2", "3.3") .build(); assertThat(itemMap.size(), is(2)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("floatSet", expectedAttributeValue)); SetBean reverse = beanTableSchema.mapToItem(itemMap); assertThat(reverse, is(equalTo(setBean))); } @Test public void setBean_binarySet() { SdkBytes buffer1 = SdkBytes.fromString("one", StandardCharsets.UTF_8); SdkBytes buffer2 = SdkBytes.fromString("two", StandardCharsets.UTF_8); SdkBytes buffer3 = SdkBytes.fromString("three", StandardCharsets.UTF_8); BeanTableSchema<SetBean> beanTableSchema = BeanTableSchema.create(SetBean.class); SetBean setBean = new SetBean(); setBean.setId("id-value"); LinkedHashSet<SdkBytes> binarySet = new LinkedHashSet<>(); binarySet.add(buffer1); binarySet.add(buffer2); binarySet.add(buffer3); setBean.setBinarySet(binarySet); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(setBean, true); AttributeValue expectedAttributeValue = AttributeValue.builder() .bs(buffer1, buffer2, buffer3) .build(); assertThat(itemMap.size(), is(2)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("binarySet", expectedAttributeValue)); SetBean reverse = beanTableSchema.mapToItem(itemMap); assertThat(reverse, is(equalTo(setBean))); } @Test public void mapBean_stringStringMap() { BeanTableSchema<MapBean> beanTableSchema = BeanTableSchema.create(MapBean.class); MapBean mapBean = new MapBean(); mapBean.setId("id-value"); Map<String, String> testMap = new HashMap<>(); testMap.put("one", "two"); testMap.put("three", "four"); mapBean.setStringMap(testMap); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(mapBean, true); Map<String, AttributeValue> expectedMap = new HashMap<>(); expectedMap.put("one", stringValue("two")); expectedMap.put("three", stringValue("four")); AttributeValue expectedMapValue = AttributeValue.builder() .m(expectedMap) .build(); assertThat(itemMap.size(), is(2)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("stringMap", expectedMapValue)); MapBean reverse = beanTableSchema.mapToItem(itemMap); assertThat(reverse, is(equalTo(mapBean))); } @Test public void mapBean_mapWithNullValue() { BeanTableSchema<MapBean> beanTableSchema = BeanTableSchema.create(MapBean.class); MapBean mapBean = new MapBean(); mapBean.setId("id-value"); Map<String, String> testMap = new HashMap<>(); testMap.put("one", null); testMap.put("three", "four"); mapBean.setStringMap(testMap); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(mapBean, true); Map<String, AttributeValue> expectedMap = new HashMap<>(); expectedMap.put("one", AttributeValues.nullAttributeValue()); expectedMap.put("three", stringValue("four")); AttributeValue expectedMapValue = AttributeValue.builder() .m(expectedMap) .build(); assertThat(itemMap.size(), is(2)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("stringMap", expectedMapValue)); MapBean reverse = beanTableSchema.mapToItem(itemMap); assertThat(reverse, is(equalTo(mapBean))); } @Test public void mapBean_nestedStringMap() { BeanTableSchema<MapBean> beanTableSchema = BeanTableSchema.create(MapBean.class); MapBean mapBean = new MapBean(); mapBean.setId("id-value"); Map<String, Map<String, String>> testMap = new HashMap<>(); testMap.put("five", singletonMap("one", "two")); testMap.put("six", singletonMap("three", "four")); mapBean.setNestedStringMap(testMap); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(mapBean, true); Map<String, AttributeValue> expectedMap = new HashMap<>(); expectedMap.put("five", AttributeValue.builder().m(singletonMap("one", stringValue("two"))).build()); expectedMap.put("six", AttributeValue.builder().m(singletonMap("three", stringValue("four"))).build()); AttributeValue expectedMapValue = AttributeValue.builder() .m(expectedMap) .build(); assertThat(itemMap.size(), is(2)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("nestedStringMap", expectedMapValue)); MapBean reverse = beanTableSchema.mapToItem(itemMap); assertThat(reverse, is(equalTo(mapBean))); } @Test public void commonTypesBean() { BeanTableSchema<CommonTypesBean> beanTableSchema = BeanTableSchema.create(CommonTypesBean.class); CommonTypesBean commonTypesBean = new CommonTypesBean(); SdkBytes binaryLiteral = SdkBytes.fromString("test-string", StandardCharsets.UTF_8); commonTypesBean.setId("id-value"); commonTypesBean.setBooleanAttribute(true); commonTypesBean.setIntegerAttribute(123); commonTypesBean.setLongAttribute(234L); commonTypesBean.setShortAttribute((short) 345); commonTypesBean.setByteAttribute((byte) 45); commonTypesBean.setDoubleAttribute(56.7); commonTypesBean.setFloatAttribute((float) 67.8); commonTypesBean.setBinaryAttribute(binaryLiteral); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(commonTypesBean, true); assertThat(itemMap.size(), is(9)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("booleanAttribute", AttributeValue.builder().bool(true).build())); assertThat(itemMap, hasEntry("integerAttribute", numberValue(123))); assertThat(itemMap, hasEntry("longAttribute", numberValue(234))); assertThat(itemMap, hasEntry("shortAttribute", numberValue(345))); assertThat(itemMap, hasEntry("byteAttribute", numberValue(45))); assertThat(itemMap, hasEntry("doubleAttribute", numberValue(56.7))); assertThat(itemMap, hasEntry("floatAttribute", numberValue(67.8))); assertThat(itemMap, hasEntry("binaryAttribute", binaryValue(binaryLiteral))); CommonTypesBean reverse = beanTableSchema.mapToItem(itemMap); assertThat(reverse, is(equalTo(commonTypesBean))); } @Test public void primitiveTypesBean() { BeanTableSchema<PrimitiveTypesBean> beanTableSchema = BeanTableSchema.create(PrimitiveTypesBean.class); PrimitiveTypesBean primitiveTypesBean = new PrimitiveTypesBean(); primitiveTypesBean.setId("id-value"); primitiveTypesBean.setBooleanAttribute(true); primitiveTypesBean.setIntegerAttribute(123); primitiveTypesBean.setLongAttribute(234L); primitiveTypesBean.setShortAttribute((short) 345); primitiveTypesBean.setByteAttribute((byte) 45); primitiveTypesBean.setDoubleAttribute(56.7); primitiveTypesBean.setFloatAttribute((float) 67.8); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(primitiveTypesBean, true); assertThat(itemMap.size(), is(8)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("booleanAttribute", AttributeValue.builder().bool(true).build())); assertThat(itemMap, hasEntry("integerAttribute", numberValue(123))); assertThat(itemMap, hasEntry("longAttribute", numberValue(234))); assertThat(itemMap, hasEntry("shortAttribute", numberValue(345))); assertThat(itemMap, hasEntry("byteAttribute", numberValue(45))); assertThat(itemMap, hasEntry("doubleAttribute", numberValue(56.7))); assertThat(itemMap, hasEntry("floatAttribute", numberValue(67.8))); PrimitiveTypesBean reverse = beanTableSchema.mapToItem(itemMap); assertThat(reverse, is(equalTo(primitiveTypesBean))); } @Test public void itemToMap_specificAttributes() { BeanTableSchema<CommonTypesBean> beanTableSchema = BeanTableSchema.create(CommonTypesBean.class); CommonTypesBean commonTypesBean = new CommonTypesBean(); commonTypesBean.setId("id-value"); commonTypesBean.setIntegerAttribute(123); commonTypesBean.setLongAttribute(234L); commonTypesBean.setFloatAttribute((float) 67.8); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(commonTypesBean, Arrays.asList("longAttribute", "floatAttribute")); assertThat(itemMap.size(), is(2)); assertThat(itemMap, hasEntry("longAttribute", numberValue(234))); assertThat(itemMap, hasEntry("floatAttribute", numberValue(67.8))); } @Test public void itemType_returnsCorrectClass() { BeanTableSchema<SimpleBean> beanTableSchema = BeanTableSchema.create(SimpleBean.class); assertThat(beanTableSchema.itemType(), is(equalTo(EnhancedType.of(SimpleBean.class)))); } @Test public void attributeConverterWithoutConstructor_throwsIllegalArgumentException() { exception.expect(IllegalArgumentException.class); exception.expectMessage("default constructor"); BeanTableSchema.create(AttributeConverterNoConstructorBean.class); } @Test public void usesCustomAttributeConverter() { BeanTableSchema<AttributeConverterBean> beanTableSchema = BeanTableSchema.create(AttributeConverterBean.class); AttributeConverterBean.AttributeItem attributeItem = new AttributeConverterBean.AttributeItem(); attributeItem.setInnerValue("inner-value"); AttributeConverterBean converterBean = new AttributeConverterBean(); converterBean.setId("id-value"); converterBean.setIntegerAttribute(123); converterBean.setAttributeItem(attributeItem); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(converterBean, false); assertThat(itemMap.size(), is(3)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("integerAttribute", numberValue(123))); assertThat(itemMap, hasEntry("attributeItem", stringValue("inner-value"))); AttributeConverterBean reverse = beanTableSchema.mapToItem(itemMap); assertThat(reverse, is(equalTo(converterBean))); } @Test public void converterProviderWithoutConstructor_throwsIllegalArgumentException() { exception.expect(IllegalArgumentException.class); exception.expectMessage("default constructor"); BeanTableSchema.create(NoConstructorConverterProvidersBean.class); } @Test public void usesCustomAttributeConverterProvider() { BeanTableSchema<SingleConverterProvidersBean> beanTableSchema = BeanTableSchema.create(SingleConverterProvidersBean.class); SingleConverterProvidersBean converterBean = new SingleConverterProvidersBean(); converterBean.setId("id-value"); converterBean.setIntegerAttribute(123); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(converterBean, false); assertThat(itemMap.size(), is(2)); assertThat(itemMap, hasEntry("id", stringValue("id-value-custom"))); assertThat(itemMap, hasEntry("integerAttribute", numberValue(133))); SingleConverterProvidersBean reverse = beanTableSchema.mapToItem(itemMap); assertThat(reverse.getId(), is(equalTo("id-value-custom"))); assertThat(reverse.getIntegerAttribute(), is(equalTo(133))); } @Test public void usesCustomAttributeConverterProviders() { BeanTableSchema<MultipleConverterProvidersBean> beanTableSchema = BeanTableSchema.create(MultipleConverterProvidersBean.class); MultipleConverterProvidersBean converterBean = new MultipleConverterProvidersBean(); converterBean.setId("id-value"); converterBean.setIntegerAttribute(123); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(converterBean, false); assertThat(itemMap.size(), is(2)); assertThat(itemMap, hasEntry("id", stringValue("id-value-custom"))); assertThat(itemMap, hasEntry("integerAttribute", numberValue(133))); MultipleConverterProvidersBean reverse = beanTableSchema.mapToItem(itemMap); assertThat(reverse.getId(), is(equalTo("id-value-custom"))); assertThat(reverse.getIntegerAttribute(), is(equalTo(133))); } @Test public void emptyConverterProviderList_fails_whenAttributeConvertersAreMissing() { exception.expect(NullPointerException.class); BeanTableSchema.create(EmptyConverterProvidersInvalidBean.class); } @Test public void emptyConverterProviderList_correct_whenAttributeConvertersAreSupplied() { BeanTableSchema<EmptyConverterProvidersValidBean> beanTableSchema = BeanTableSchema.create(EmptyConverterProvidersValidBean.class); EmptyConverterProvidersValidBean converterBean = new EmptyConverterProvidersValidBean(); converterBean.setId("id-value"); converterBean.setIntegerAttribute(123); Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(converterBean, false); assertThat(itemMap.size(), is(2)); assertThat(itemMap, hasEntry("id", stringValue("id-value-custom"))); assertThat(itemMap, hasEntry("integerAttribute", numberValue(133))); EmptyConverterProvidersValidBean reverse = beanTableSchema.mapToItem(itemMap); assertThat(reverse.getId(), is(equalTo("id-value-custom"))); assertThat(reverse.getIntegerAttribute(), is(equalTo(133))); } }
3,927
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/StaticImmutableTableSchemaFlattenTest.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.Arrays; import java.util.Collection; 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 StaticImmutableTableSchemaFlattenTest { private static final ImmutableRecord TEST_RECORD = ImmutableRecord.builder() .id("id123") .attribute1("1") .child1( ImmutableRecord.builder() .attribute1("2a") .child1( ImmutableRecord.builder() .attribute1("3a") .build() ) .child2( ImmutableRecord.builder() .attribute1("3b") .build() ) .build() ) .child2( ImmutableRecord.builder() .attribute1("2b") .child1( ImmutableRecord.builder() .attribute1("4a") .build() ) .child2( ImmutableRecord.builder() .attribute1("4b") .build() ) .build() ) .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("1").build()); map.put("attribute2a", AttributeValue.builder().s("2a").build()); map.put("attribute2b", AttributeValue.builder().s("2b").build()); map.put("attribute3a", AttributeValue.builder().s("3a").build()); map.put("attribute3b", AttributeValue.builder().s("3b").build()); map.put("attribute4a", AttributeValue.builder().s("4a").build()); map.put("attribute4b", AttributeValue.builder().s("4b").build()); ITEM_MAP = Collections.unmodifiableMap(map); } private final TableSchema<ImmutableRecord> childTableSchema4a = TableSchema.builder(ImmutableRecord.class, ImmutableRecord.Builder.class) .newItemBuilder(ImmutableRecord::builder, ImmutableRecord.Builder::build) .addAttribute(String.class, a -> a.name("attribute4a") .getter(ImmutableRecord::attribute1) .setter(ImmutableRecord.Builder::attribute1)) .build(); private final TableSchema<ImmutableRecord> childTableSchema4b = TableSchema.builder(ImmutableRecord.class, ImmutableRecord.Builder.class) .newItemBuilder(ImmutableRecord::builder, ImmutableRecord.Builder::build) .addAttribute(String.class, a -> a.name("attribute4b") .getter(ImmutableRecord::attribute1) .setter(ImmutableRecord.Builder::attribute1)) .build(); private final TableSchema<ImmutableRecord> childTableSchema3a = TableSchema.builder(ImmutableRecord.class, ImmutableRecord.Builder.class) .newItemBuilder(ImmutableRecord::builder, ImmutableRecord.Builder::build) .addAttribute(String.class, a -> a.name("attribute3a") .getter(ImmutableRecord::attribute1) .setter(ImmutableRecord.Builder::attribute1)) .build(); private final TableSchema<ImmutableRecord> childTableSchema3b = TableSchema.builder(ImmutableRecord.class, ImmutableRecord.Builder.class) .newItemBuilder(ImmutableRecord::builder, ImmutableRecord.Builder::build) .addAttribute(String.class, a -> a.name("attribute3b") .getter(ImmutableRecord::attribute1) .setter(ImmutableRecord.Builder::attribute1)) .build(); private final TableSchema<ImmutableRecord> childTableSchema2a = TableSchema.builder(ImmutableRecord.class, ImmutableRecord.Builder.class) .newItemBuilder(ImmutableRecord::builder, ImmutableRecord.Builder::build) .addAttribute(String.class, a -> a.name("attribute2a") .getter(ImmutableRecord::attribute1) .setter(ImmutableRecord.Builder::attribute1)) .flatten(childTableSchema3a, ImmutableRecord::getChild1, ImmutableRecord.Builder::child1) .flatten(childTableSchema3b, ImmutableRecord::getChild2, ImmutableRecord.Builder::child2) .build(); private final TableSchema<ImmutableRecord> childTableSchema2b = TableSchema.builder(ImmutableRecord.class, ImmutableRecord.Builder.class) .newItemBuilder(ImmutableRecord::builder, ImmutableRecord.Builder::build) .addAttribute(String.class, a -> a.name("attribute2b") .getter(ImmutableRecord::attribute1) .setter(ImmutableRecord.Builder::attribute1)) .flatten(childTableSchema4a, ImmutableRecord::getChild1, ImmutableRecord.Builder::child1) .flatten(childTableSchema4b, ImmutableRecord::getChild2, ImmutableRecord.Builder::child2) .build(); 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)) .flatten(childTableSchema2a, ImmutableRecord::getChild1, ImmutableRecord.Builder::child1) .flatten(childTableSchema2b, ImmutableRecord::getChild2, ImmutableRecord.Builder::child2) .build(); @Test public void itemToMap_completeRecord() { Map<String, AttributeValue> result = immutableTableSchema.itemToMap(TEST_RECORD, false); assertThat(result).isEqualTo(ITEM_MAP); } @Test public void itemToMap_specificAttributes() { Map<String, AttributeValue> result = immutableTableSchema.itemToMap(TEST_RECORD, Arrays.asList("attribute1", "attribute2a", "attribute4b")); Map<String, AttributeValue> expectedResult = new HashMap<>(); expectedResult.put("attribute1", AttributeValue.builder().s("1").build()); expectedResult.put("attribute2a", AttributeValue.builder().s("2a").build()); expectedResult.put("attribute4b", AttributeValue.builder().s("4b").build()); assertThat(result).isEqualTo(expectedResult); } @Test public void itemToMap_specificAttribute() { AttributeValue result = immutableTableSchema.attributeValue(TEST_RECORD, "attribute4b"); assertThat(result).isEqualTo(AttributeValue.builder().s("4b").build()); } @Test public void mapToItem() { ImmutableRecord record = immutableTableSchema.mapToItem(ITEM_MAP); assertThat(record).isEqualTo(TEST_RECORD); } @Test public void attributeNames() { Collection<String> result = immutableTableSchema.attributeNames(); assertThat(result).containsExactlyInAnyOrder(ITEM_MAP.keySet().toArray(new String[]{})); } @Test public void converterForAttribute() { ITEM_MAP.forEach((key, attributeValue) -> { assertThat(immutableTableSchema.converterForAttribute(key)).isNotNull(); }); } public static class ImmutableRecord { private final String id; private final String attribute1; private final ImmutableRecord child1; private final ImmutableRecord child2; private ImmutableRecord(Builder b) { this.id = b.id; this.attribute1 = b.attribute1; this.child1 = b.child1; this.child2 = b.child2; } public static Builder builder() { return new Builder(); } public String id() { return id; } public String attribute1() { return attribute1; } public ImmutableRecord getChild1() { return child1; } public ImmutableRecord getChild2() { return child2; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ImmutableRecord that = (ImmutableRecord) o; if (id != null ? !id.equals(that.id) : that.id != null) return false; if (attribute1 != null ? !attribute1.equals(that.attribute1) : that.attribute1 != null) return false; if (child1 != null ? !child1.equals(that.child1) : that.child1 != null) return false; return child2 != null ? child2.equals(that.child2) : that.child2 == null; } @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + (attribute1 != null ? attribute1.hashCode() : 0); result = 31 * result + (child1 != null ? child1.hashCode() : 0); result = 31 * result + (child2 != null ? child2.hashCode() : 0); return result; } public static class Builder { private String id; private String attribute1; private ImmutableRecord child1; private ImmutableRecord child2; public Builder id(String id) { this.id = id; return this; } public Builder attribute1(String attribute1) { this.attribute1 = attribute1; return this; } public Builder child1(ImmutableRecord child1) { this.child1 = child1; return this; } public Builder child2(ImmutableRecord child2) { this.child2 = child2; return this; } public ImmutableRecord build() { return new ImmutableRecord(this); } } } }
3,928
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/StaticTableSchemaTest.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 java.nio.charset.StandardCharsets.UTF_8; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static java.util.Collections.singletonMap; import static java.util.stream.Collectors.toList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasEntry; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.nullAttributeValue; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.stringValue; import java.math.BigDecimal; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Consumer; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; 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.AttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.AttributeConverterProvider; import software.amazon.awssdk.enhanced.dynamodb.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.TableMetadata; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItem; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItemComposedClass; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItemWithSort; import software.amazon.awssdk.enhanced.dynamodb.mapper.testbeans.EntityEnvelopeBean; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; @RunWith(MockitoJUnitRunner.class) public class StaticTableSchemaTest { private static final String TABLE_TAG_KEY = "table-tag-key"; private static final String TABLE_TAG_VALUE = "table-tag-value"; private static final AttributeValue ATTRIBUTE_VALUE_B = AttributeValue.builder().bool(true).build(); private static final AttributeValue ATTRIBUTE_VALUE_S = AttributeValue.builder().s("test-string").build(); private static final StaticTableSchema<FakeDocument> FAKE_DOCUMENT_TABLE_SCHEMA = StaticTableSchema.builder(FakeDocument.class) .newItemSupplier(FakeDocument::new) .addAttribute(String.class, a -> a.name("documentString") .getter(FakeDocument::getDocumentString) .setter(FakeDocument::setDocumentString)) .addAttribute(Integer.class, a -> a.name("documentInteger") .getter(FakeDocument::getDocumentInteger) .setter(FakeDocument::setDocumentInteger)) .build(); private static final FakeMappedItem FAKE_ITEM = FakeMappedItem.builder() .aPrimitiveBoolean(true) .aBoolean(true) .aString("test-string") .build(); private static class FakeMappedItem { private boolean aPrimitiveBoolean; private Boolean aBoolean; private String aString; private Integer anInteger; private int aPrimitiveInteger; private Byte aByte; private byte aPrimitiveByte; private Long aLong; private long aPrimitiveLong; private Short aShort; private short aPrimitiveShort; private Double aDouble; private double aPrimitiveDouble; private Float aFloat; private float aPrimitiveFloat; private BigDecimal aBigDecimal; private SdkBytes aBinaryValue; private FakeDocument aFakeDocument; private Set<String> aStringSet; private Set<Integer> anIntegerSet; private Set<Byte> aByteSet; private Set<Long> aLongSet; private Set<Short> aShortSet; private Set<Double> aDoubleSet; private Set<Float> aFloatSet; private Set<SdkBytes> aBinarySet; private List<Integer> anIntegerList; private List<List<FakeDocument>> aNestedStructure; private Map<String, String> aStringMap; private Map<Integer, Double> aIntDoubleMap; private TestEnum testEnum; FakeMappedItem() { } FakeMappedItem(boolean aPrimitiveBoolean, Boolean aBoolean, String aString, Integer anInteger, int aPrimitiveInteger, Byte aByte, byte aPrimitiveByte, Long aLong, long aPrimitiveLong, Short aShort, short aPrimitiveShort, Double aDouble, double aPrimitiveDouble, Float aFloat, float aPrimitiveFloat, BigDecimal aBigDecimal, SdkBytes aBinaryValue, FakeDocument aFakeDocument, Set<String> aStringSet, Set<Integer> anIntegerSet, Set<Byte> aByteSet, Set<Long> aLongSet, Set<Short> aShortSet, Set<Double> aDoubleSet, Set<Float> aFloatSet, Set<SdkBytes> aBinarySet, List<Integer> anIntegerList, List<List<FakeDocument>> aNestedStructure, Map<String, String> aStringMap, Map<Integer, Double> aIntDoubleMap, TestEnum testEnum) { this.aPrimitiveBoolean = aPrimitiveBoolean; this.aBoolean = aBoolean; this.aString = aString; this.anInteger = anInteger; this.aPrimitiveInteger = aPrimitiveInteger; this.aByte = aByte; this.aPrimitiveByte = aPrimitiveByte; this.aLong = aLong; this.aPrimitiveLong = aPrimitiveLong; this.aShort = aShort; this.aPrimitiveShort = aPrimitiveShort; this.aDouble = aDouble; this.aPrimitiveDouble = aPrimitiveDouble; this.aFloat = aFloat; this.aPrimitiveFloat = aPrimitiveFloat; this.aBigDecimal = aBigDecimal; this.aBinaryValue = aBinaryValue; this.aFakeDocument = aFakeDocument; this.aStringSet = aStringSet; this.anIntegerSet = anIntegerSet; this.aByteSet = aByteSet; this.aLongSet = aLongSet; this.aShortSet = aShortSet; this.aDoubleSet = aDoubleSet; this.aFloatSet = aFloatSet; this.aBinarySet = aBinarySet; this.anIntegerList = anIntegerList; this.aNestedStructure = aNestedStructure; this.aStringMap = aStringMap; this.aIntDoubleMap = aIntDoubleMap; this.testEnum = testEnum; } public static Builder builder() { return new Builder(); } boolean isAPrimitiveBoolean() { return aPrimitiveBoolean; } void setAPrimitiveBoolean(boolean aPrimitiveBoolean) { this.aPrimitiveBoolean = aPrimitiveBoolean; } Boolean getABoolean() { return aBoolean; } void setABoolean(Boolean aBoolean) { this.aBoolean = aBoolean; } String getAString() { return aString; } void setAString(String aString) { this.aString = aString; } Integer getAnInteger() { return anInteger; } void setAnInteger(Integer anInteger) { this.anInteger = anInteger; } int getAPrimitiveInteger() { return aPrimitiveInteger; } void setAPrimitiveInteger(int aPrimitiveInteger) { this.aPrimitiveInteger = aPrimitiveInteger; } Byte getAByte() { return aByte; } void setAByte(Byte aByte) { this.aByte = aByte; } byte getAPrimitiveByte() { return aPrimitiveByte; } void setAPrimitiveByte(byte aPrimitiveByte) { this.aPrimitiveByte = aPrimitiveByte; } Long getALong() { return aLong; } void setALong(Long aLong) { this.aLong = aLong; } long getAPrimitiveLong() { return aPrimitiveLong; } void setAPrimitiveLong(long aPrimitiveLong) { this.aPrimitiveLong = aPrimitiveLong; } Short getAShort() { return aShort; } void setAShort(Short aShort) { this.aShort = aShort; } short getAPrimitiveShort() { return aPrimitiveShort; } void setAPrimitiveShort(short aPrimitiveShort) { this.aPrimitiveShort = aPrimitiveShort; } Double getADouble() { return aDouble; } void setADouble(Double aDouble) { this.aDouble = aDouble; } double getAPrimitiveDouble() { return aPrimitiveDouble; } void setAPrimitiveDouble(double aPrimitiveDouble) { this.aPrimitiveDouble = aPrimitiveDouble; } Float getAFloat() { return aFloat; } void setAFloat(Float aFloat) { this.aFloat = aFloat; } BigDecimal aBigDecimal() { return aBigDecimal; } void setABigDecimal(BigDecimal aBigDecimal) { this.aBigDecimal = aBigDecimal; } float getAPrimitiveFloat() { return aPrimitiveFloat; } void setAPrimitiveFloat(float aPrimitiveFloat) { this.aPrimitiveFloat = aPrimitiveFloat; } SdkBytes getABinaryValue() { return aBinaryValue; } void setABinaryValue(SdkBytes aBinaryValue) { this.aBinaryValue = aBinaryValue; } FakeDocument getAFakeDocument() { return aFakeDocument; } void setAFakeDocument(FakeDocument aFakeDocument) { this.aFakeDocument = aFakeDocument; } Set<String> getAStringSet() { return aStringSet; } void setAStringSet(Set<String> aStringSet) { this.aStringSet = aStringSet; } Set<Integer> getAnIntegerSet() { return anIntegerSet; } void setAnIntegerSet(Set<Integer> anIntegerSet) { this.anIntegerSet = anIntegerSet; } Set<Byte> getAByteSet() { return aByteSet; } void setAByteSet(Set<Byte> aByteSet) { this.aByteSet = aByteSet; } Set<Long> getALongSet() { return aLongSet; } void setALongSet(Set<Long> aLongSet) { this.aLongSet = aLongSet; } Set<Short> getAShortSet() { return aShortSet; } void setAShortSet(Set<Short> aShortSet) { this.aShortSet = aShortSet; } Set<Double> getADoubleSet() { return aDoubleSet; } void setADoubleSet(Set<Double> aDoubleSet) { this.aDoubleSet = aDoubleSet; } Set<Float> getAFloatSet() { return aFloatSet; } void setAFloatSet(Set<Float> aFloatSet) { this.aFloatSet = aFloatSet; } Set<SdkBytes> getABinarySet() { return aBinarySet; } void setABinarySet(Set<SdkBytes> aBinarySet) { this.aBinarySet = aBinarySet; } List<Integer> getAnIntegerList() { return anIntegerList; } void setAnIntegerList(List<Integer> anIntegerList) { this.anIntegerList = anIntegerList; } List<List<FakeDocument>> getANestedStructure() { return aNestedStructure; } void setANestedStructure(List<List<FakeDocument>> aNestedStructure) { this.aNestedStructure = aNestedStructure; } Map<String, String> getAStringMap() { return aStringMap; } void setAStringMap(Map<String, String> aStringMap) { this.aStringMap = aStringMap; } Map<Integer, Double> getAIntDoubleMap() { return aIntDoubleMap; } void setAIntDoubleMap(Map<Integer, Double> aIntDoubleMap) { this.aIntDoubleMap = aIntDoubleMap; } TestEnum getTestEnum() { return testEnum; } void setTestEnum(TestEnum testEnum) { this.testEnum = testEnum; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } FakeMappedItem that = (FakeMappedItem) o; return aPrimitiveBoolean == that.aPrimitiveBoolean && aPrimitiveInteger == that.aPrimitiveInteger && aPrimitiveByte == that.aPrimitiveByte && aPrimitiveLong == that.aPrimitiveLong && aPrimitiveShort == that.aPrimitiveShort && Double.compare(that.aPrimitiveDouble, aPrimitiveDouble) == 0 && Float.compare(that.aPrimitiveFloat, aPrimitiveFloat) == 0 && Objects.equals(aBoolean, that.aBoolean) && Objects.equals(aString, that.aString) && Objects.equals(anInteger, that.anInteger) && Objects.equals(aByte, that.aByte) && Objects.equals(aLong, that.aLong) && Objects.equals(aShort, that.aShort) && Objects.equals(aDouble, that.aDouble) && Objects.equals(aFloat, that.aFloat) && Objects.equals(aBinaryValue, that.aBinaryValue) && Objects.equals(aFakeDocument, that.aFakeDocument) && Objects.equals(aStringSet, that.aStringSet) && Objects.equals(anIntegerSet, that.anIntegerSet) && Objects.equals(aByteSet, that.aByteSet) && Objects.equals(aLongSet, that.aLongSet) && Objects.equals(aShortSet, that.aShortSet) && Objects.equals(aDoubleSet, that.aDoubleSet) && Objects.equals(aFloatSet, that.aFloatSet) && Objects.equals(aBinarySet, that.aBinarySet) && Objects.equals(anIntegerList, that.anIntegerList) && Objects.equals(aNestedStructure, that.aNestedStructure) && Objects.equals(aStringMap, that.aStringMap) && Objects.equals(aIntDoubleMap, that.aIntDoubleMap) && Objects.equals(testEnum, that.testEnum); } @Override public int hashCode() { return Objects.hash(aPrimitiveBoolean, aBoolean, aString, anInteger, aPrimitiveInteger, aByte, aPrimitiveByte, aLong, aPrimitiveLong, aShort, aPrimitiveShort, aDouble, aPrimitiveDouble, aFloat, aPrimitiveFloat, aBinaryValue, aFakeDocument, aStringSet, anIntegerSet, aByteSet, aLongSet, aShortSet, aDoubleSet, aFloatSet, aBinarySet, anIntegerList, aNestedStructure, aStringMap, aIntDoubleMap, testEnum); } public enum TestEnum { ONE, TWO, THREE; } private static class Builder { private boolean aPrimitiveBoolean; private Boolean aBoolean; private String aString; private Integer anInteger; private int aPrimitiveInteger; private Byte aByte; private byte aPrimitiveByte; private Long aLong; private long aPrimitiveLong; private Short aShort; private short aPrimitiveShort; private Double aDouble; private double aPrimitiveDouble; private Float aFloat; private float aPrimitiveFloat; private BigDecimal aBigDecimal; private SdkBytes aBinaryValue; private FakeDocument aFakeDocument; private Set<String> aStringSet; private Set<Integer> anIntegerSet; private Set<Byte> aByteSet; private Set<Long> aLongSet; private Set<Short> aShortSet; private Set<Double> aDoubleSet; private Set<Float> aFloatSet; private Set<SdkBytes> aBinarySet; private List<Integer> anIntegerList; private List<List<FakeDocument>> aNestedStructure; private Map<String, String> aStringMap; private Map<Integer, Double> aIntDoubleMap; private TestEnum testEnum; Builder aPrimitiveBoolean(boolean aPrimitiveBoolean) { this.aPrimitiveBoolean = aPrimitiveBoolean; return this; } Builder aBoolean(Boolean aBoolean) { this.aBoolean = aBoolean; return this; } Builder aString(String aString) { this.aString = aString; return this; } Builder anInteger(Integer anInteger) { this.anInteger = anInteger; return this; } Builder aPrimitiveInteger(int aPrimitiveInteger) { this.aPrimitiveInteger = aPrimitiveInteger; return this; } Builder aByte(Byte aByte) { this.aByte = aByte; return this; } Builder aPrimitiveByte(byte aPrimitiveByte) { this.aPrimitiveByte = aPrimitiveByte; return this; } Builder aLong(Long aLong) { this.aLong = aLong; return this; } Builder aPrimitiveLong(long aPrimitiveLong) { this.aPrimitiveLong = aPrimitiveLong; return this; } Builder aShort(Short aShort) { this.aShort = aShort; return this; } Builder aPrimitiveShort(short aPrimitiveShort) { this.aPrimitiveShort = aPrimitiveShort; return this; } Builder aDouble(Double aDouble) { this.aDouble = aDouble; return this; } Builder aPrimitiveDouble(double aPrimitiveDouble) { this.aPrimitiveDouble = aPrimitiveDouble; return this; } Builder aFloat(Float aFloat) { this.aFloat = aFloat; return this; } Builder aPrimitiveFloat(float aPrimitiveFloat) { this.aPrimitiveFloat = aPrimitiveFloat; return this; } Builder aBigDecimal(BigDecimal aBigDecimal) { this.aBigDecimal = aBigDecimal; return this; } Builder aBinaryValue(SdkBytes aBinaryValue) { this.aBinaryValue = aBinaryValue; return this; } Builder aFakeDocument(FakeDocument aFakeDocument) { this.aFakeDocument = aFakeDocument; return this; } Builder aStringSet(Set<String> aStringSet) { this.aStringSet = aStringSet; return this; } Builder anIntegerSet(Set<Integer> anIntegerSet) { this.anIntegerSet = anIntegerSet; return this; } Builder aByteSet(Set<Byte> aByteSet) { this.aByteSet = aByteSet; return this; } Builder aLongSet(Set<Long> aLongSet) { this.aLongSet = aLongSet; return this; } Builder aShortSet(Set<Short> aShortSet) { this.aShortSet = aShortSet; return this; } Builder aDoubleSet(Set<Double> aDoubleSet) { this.aDoubleSet = aDoubleSet; return this; } Builder aFloatSet(Set<Float> aFloatSet) { this.aFloatSet = aFloatSet; return this; } Builder aBinarySet(Set<SdkBytes> aBinarySet) { this.aBinarySet = aBinarySet; return this; } Builder anIntegerList(List<Integer> anIntegerList) { this.anIntegerList = anIntegerList; return this; } Builder aNestedStructure(List<List<FakeDocument>> aNestedStructure) { this.aNestedStructure = aNestedStructure; return this; } Builder aStringMap(Map<String, String> aStringMap) { this.aStringMap = aStringMap; return this; } Builder aIntDoubleMap(Map<Integer, Double> aIntDoubleMap) { this.aIntDoubleMap = aIntDoubleMap; return this; } Builder testEnum(TestEnum testEnum) { this.testEnum = testEnum; return this; } public FakeMappedItem build() { return new FakeMappedItem(aPrimitiveBoolean, aBoolean, aString, anInteger, aPrimitiveInteger, aByte, aPrimitiveByte, aLong, aPrimitiveLong, aShort, aPrimitiveShort, aDouble, aPrimitiveDouble, aFloat, aPrimitiveFloat, aBigDecimal, aBinaryValue, aFakeDocument, aStringSet, anIntegerSet, aByteSet, aLongSet, aShortSet, aDoubleSet, aFloatSet, aBinarySet, anIntegerList, aNestedStructure, aStringMap, aIntDoubleMap, testEnum); } } } private static class FakeDocument { private String documentString; private Integer documentInteger; FakeDocument() { } private FakeDocument(String documentString, Integer documentInteger) { this.documentString = documentString; this.documentInteger = documentInteger; } private static FakeDocument of(String documentString, Integer documentInteger) { return new FakeDocument(documentString, documentInteger); } String getDocumentString() { return documentString; } void setDocumentString(String documentString) { this.documentString = documentString; } Integer getDocumentInteger() { return documentInteger; } void setDocumentInteger(Integer documentInteger) { this.documentInteger = documentInteger; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } FakeDocument that = (FakeDocument) o; return Objects.equals(documentString, that.documentString) && Objects.equals(documentInteger, that.documentInteger); } @Override public int hashCode() { return Objects.hash(documentString, documentInteger); } } private static class FakeAbstractSubclass extends FakeAbstractSuperclass { } private static class FakeBrokenClass { FakeAbstractSuperclass abstractObject; FakeAbstractSuperclass getAbstractObject() { return abstractObject; } void setAbstractObject(FakeAbstractSuperclass abstractObject) { this.abstractObject = abstractObject; } } private static abstract class FakeAbstractSuperclass { private String aString; String getAString() { return aString; } void setAString(String aString) { this.aString = aString; } } private static final Collection<StaticAttribute<FakeMappedItem, ?>> ATTRIBUTES = Arrays.asList( StaticAttribute.builder(FakeMappedItem.class, Boolean.class) .name("a_primitive_boolean") .getter(FakeMappedItem::isAPrimitiveBoolean) .setter(FakeMappedItem::setAPrimitiveBoolean) .build(), StaticAttribute.builder(FakeMappedItem.class, Boolean.class) .name("a_boolean") .getter(FakeMappedItem::getABoolean) .setter(FakeMappedItem::setABoolean) .build(), StaticAttribute.builder(FakeMappedItem.class, String.class) .name("a_string") .getter(FakeMappedItem::getAString) .setter(FakeMappedItem::setAString) .build() ); private StaticTableSchema<FakeMappedItem> createSimpleTableSchema() { return StaticTableSchema.builder(FakeMappedItem.class) .newItemSupplier(FakeMappedItem::new) .attributes(ATTRIBUTES) .build(); } private static class TestStaticTableTag implements StaticTableTag { @Override public Consumer<StaticTableMetadata.Builder> modifyMetadata() { return metadata -> metadata.addCustomMetadataObject(TABLE_TAG_KEY, TABLE_TAG_VALUE); } } @Mock private AttributeConverterProvider provider1; @Mock private AttributeConverterProvider provider2; @Mock private AttributeConverter<String> attributeConverter1; @Mock private AttributeConverter<String> attributeConverter2; @Rule public ExpectedException exception = ExpectedException.none(); @Test public void itemType_returnsCorrectClass() { assertThat(FakeItem.getTableSchema().itemType(), is(equalTo(EnhancedType.of(FakeItem.class)))); } @Test public void itemType_returnsCorrectClassWhenBuiltWithEnhancedType() { StaticTableSchema<FakeMappedItem> tableSchema = StaticTableSchema.builder(EnhancedType.of(FakeMappedItem.class)) .newItemSupplier(FakeMappedItem::new) .attributes(ATTRIBUTES) .build(); assertThat(tableSchema.itemType(), is(equalTo(EnhancedType.of(FakeMappedItem.class)))); } @Test public void getTableMetadata_hasCorrectFields() { TableMetadata tableMetadata = FakeItemWithSort.getTableSchema().tableMetadata(); assertThat(tableMetadata.primaryPartitionKey(), is("id")); assertThat(tableMetadata.primarySortKey(), is(Optional.of("sort"))); } @Test public void itemToMap_returnsCorrectMapWithMultipleAttributes() { Map<String, AttributeValue> attributeMap = createSimpleTableSchema().itemToMap(FAKE_ITEM, false); assertThat(attributeMap.size(), is(3)); assertThat(attributeMap, hasEntry("a_boolean", ATTRIBUTE_VALUE_B)); assertThat(attributeMap, hasEntry("a_primitive_boolean", ATTRIBUTE_VALUE_B)); assertThat(attributeMap, hasEntry("a_string", ATTRIBUTE_VALUE_S)); } @Test public void itemToMap_omitsNullAttributes() { FakeMappedItem fakeMappedItemWithNulls = FakeMappedItem.builder().aPrimitiveBoolean(true).build(); Map<String, AttributeValue> attributeMap = createSimpleTableSchema().itemToMap(fakeMappedItemWithNulls, true); assertThat(attributeMap.size(), is(1)); assertThat(attributeMap, hasEntry("a_primitive_boolean", ATTRIBUTE_VALUE_B)); } @Test public void itemToMap_filtersAttributes() { Map<String, AttributeValue> attributeMap = createSimpleTableSchema() .itemToMap(FAKE_ITEM, asList("a_boolean", "a_string")); assertThat(attributeMap.size(), is(2)); assertThat(attributeMap, hasEntry("a_boolean", ATTRIBUTE_VALUE_B)); assertThat(attributeMap, hasEntry("a_string", ATTRIBUTE_VALUE_S)); } @Test(expected = IllegalArgumentException.class) public void itemToMap_attributeNotFound_throwsIllegalArgumentException() { createSimpleTableSchema().itemToMap(FAKE_ITEM, singletonList("unknown_key")); } @Test public void mapToItem_returnsCorrectItemWithMultipleAttributes() { Map<String, AttributeValue> attributeValueMap = new HashMap<>(); attributeValueMap.put("a_boolean", ATTRIBUTE_VALUE_B); attributeValueMap.put("a_primitive_boolean", ATTRIBUTE_VALUE_B); attributeValueMap.put("a_string", ATTRIBUTE_VALUE_S); FakeMappedItem fakeMappedItem = createSimpleTableSchema().mapToItem(Collections.unmodifiableMap(attributeValueMap)); assertThat(fakeMappedItem, is(FAKE_ITEM)); } @Test public void mapToItem_unknownAttributes_doNotCauseErrors() { Map<String, AttributeValue> attributeValueMap = new HashMap<>(); attributeValueMap.put("unknown_attribute", ATTRIBUTE_VALUE_S); createSimpleTableSchema().mapToItem(Collections.unmodifiableMap(attributeValueMap)); } @Test(expected = IllegalArgumentException.class) public void mapToItem_attributesWrongType_throwsException() { Map<String, AttributeValue> attributeValueMap = new HashMap<>(); attributeValueMap.put("a_boolean", ATTRIBUTE_VALUE_S); attributeValueMap.put("a_primitive_boolean", ATTRIBUTE_VALUE_S); attributeValueMap.put("a_string", ATTRIBUTE_VALUE_B); createSimpleTableSchema().mapToItem(Collections.unmodifiableMap(attributeValueMap)); } @Test public void mapperCanHandleEnum() { verifyNullableAttribute(EnhancedType.of(FakeMappedItem.TestEnum.class), a -> a.name("value") .getter(FakeMappedItem::getTestEnum) .setter(FakeMappedItem::setTestEnum), FakeMappedItem.builder().testEnum(FakeMappedItem.TestEnum.ONE).build(), AttributeValue.builder().s("ONE").build()); } @Test public void mapperCanHandleDocument() { FakeDocument fakeDocument = FakeDocument.of("test-123", 123); Map<String, AttributeValue> expectedMap = new HashMap<>(); expectedMap.put("documentInteger", AttributeValue.builder().n("123").build()); expectedMap.put("documentString", AttributeValue.builder().s("test-123").build()); verifyNullableAttribute(EnhancedType.documentOf(FakeDocument.class, FAKE_DOCUMENT_TABLE_SCHEMA), a -> a.name("value") .getter(FakeMappedItem::getAFakeDocument) .setter(FakeMappedItem::setAFakeDocument), FakeMappedItem.builder().aFakeDocument(fakeDocument).build(), AttributeValue.builder().m(expectedMap).build()); } @Test public void mapperCanHandleDocumentWithNullValues() { verifyNullAttribute(EnhancedType.documentOf(FakeDocument.class, FAKE_DOCUMENT_TABLE_SCHEMA), a -> a.name("value") .getter(FakeMappedItem::getAFakeDocument) .setter(FakeMappedItem::setAFakeDocument), FakeMappedItem.builder().build()); } @Test public void mapperCanHandleInteger() { verifyNullableAttribute(EnhancedType.of(Integer.class), a -> a.name("value") .getter(FakeMappedItem::getAnInteger) .setter(FakeMappedItem::setAnInteger), FakeMappedItem.builder().anInteger(123).build(), AttributeValue.builder().n("123").build()); } @Test public void mapperCanHandlePrimitiveInteger() { verifyAttribute(EnhancedType.of(int.class), a -> a.name("value") .getter(FakeMappedItem::getAPrimitiveInteger) .setter(FakeMappedItem::setAPrimitiveInteger), FakeMappedItem.builder().aPrimitiveInteger(123).build(), AttributeValue.builder().n("123").build()); } @Test public void mapperCanHandleBoolean() { verifyNullableAttribute(EnhancedType.of(Boolean.class), a -> a.name("value") .getter(FakeMappedItem::getABoolean) .setter(FakeMappedItem::setABoolean), FakeMappedItem.builder().aBoolean(true).build(), AttributeValue.builder().bool(true).build()); } @Test public void mapperCanHandlePrimitiveBoolean() { verifyAttribute(EnhancedType.of(boolean.class), a -> a.name("value") .getter(FakeMappedItem::isAPrimitiveBoolean) .setter(FakeMappedItem::setAPrimitiveBoolean), FakeMappedItem.builder().aPrimitiveBoolean(true).build(), AttributeValue.builder().bool(true).build()); } @Test public void mapperCanHandleString() { verifyNullableAttribute(EnhancedType.of(String.class), a -> a.name("value") .getter(FakeMappedItem::getAString) .setter(FakeMappedItem::setAString), FakeMappedItem.builder().aString("onetwothree").build(), AttributeValue.builder().s("onetwothree").build()); } @Test public void mapperCanHandleLong() { verifyNullableAttribute(EnhancedType.of(Long.class), a -> a.name("value") .getter(FakeMappedItem::getALong) .setter(FakeMappedItem::setALong), FakeMappedItem.builder().aLong(123L).build(), AttributeValue.builder().n("123").build()); } @Test public void mapperCanHandlePrimitiveLong() { verifyAttribute(EnhancedType.of(long.class), a -> a.name("value") .getter(FakeMappedItem::getAPrimitiveLong) .setter(FakeMappedItem::setAPrimitiveLong), FakeMappedItem.builder().aPrimitiveLong(123L).build(), AttributeValue.builder().n("123").build()); } @Test public void mapperCanHandleShort() { verifyNullableAttribute(EnhancedType.of(Short.class), a -> a.name("value") .getter(FakeMappedItem::getAShort) .setter(FakeMappedItem::setAShort), FakeMappedItem.builder().aShort((short)123).build(), AttributeValue.builder().n("123").build()); } @Test public void mapperCanHandlePrimitiveShort() { verifyAttribute(EnhancedType.of(short.class), a -> a.name("value") .getter(FakeMappedItem::getAPrimitiveShort) .setter(FakeMappedItem::setAPrimitiveShort), FakeMappedItem.builder().aPrimitiveShort((short)123).build(), AttributeValue.builder().n("123").build()); } @Test public void mapperCanHandleByte() { verifyNullableAttribute(EnhancedType.of(Byte.class), a -> a.name("value") .getter(FakeMappedItem::getAByte) .setter(FakeMappedItem::setAByte), FakeMappedItem.builder().aByte((byte)123).build(), AttributeValue.builder().n("123").build()); } @Test public void mapperCanHandlePrimitiveByte() { verifyAttribute(EnhancedType.of(byte.class), a -> a.name("value") .getter(FakeMappedItem::getAPrimitiveByte) .setter(FakeMappedItem::setAPrimitiveByte), FakeMappedItem.builder().aPrimitiveByte((byte)123).build(), AttributeValue.builder().n("123").build()); } @Test public void mapperCanHandleDouble() { verifyNullableAttribute(EnhancedType.of(Double.class), a -> a.name("value") .getter(FakeMappedItem::getADouble) .setter(FakeMappedItem::setADouble), FakeMappedItem.builder().aDouble(1.23).build(), AttributeValue.builder().n("1.23").build()); } @Test public void mapperCanHandlePrimitiveDouble() { verifyAttribute(EnhancedType.of(double.class), a -> a.name("value") .getter(FakeMappedItem::getAPrimitiveDouble) .setter(FakeMappedItem::setAPrimitiveDouble), FakeMappedItem.builder().aPrimitiveDouble(1.23).build(), AttributeValue.builder().n("1.23").build()); } @Test public void mapperCanHandleFloat() { verifyNullableAttribute(EnhancedType.of(Float.class), a -> a.name("value") .getter(FakeMappedItem::getAFloat) .setter(FakeMappedItem::setAFloat), FakeMappedItem.builder().aFloat(1.23f).build(), AttributeValue.builder().n("1.23").build()); } @Test public void mapperCanHandlePrimitiveFloat() { verifyAttribute(EnhancedType.of(float.class), a -> a.name("value") .getter(FakeMappedItem::getAPrimitiveFloat) .setter(FakeMappedItem::setAPrimitiveFloat), FakeMappedItem.builder().aPrimitiveFloat(1.23f).build(), AttributeValue.builder().n("1.23").build()); } @Test public void mapperCanHandleBinary() { SdkBytes sdkBytes = SdkBytes.fromString("test", UTF_8); verifyNullableAttribute(EnhancedType.of(SdkBytes.class), a -> a.name("value") .getter(FakeMappedItem::getABinaryValue) .setter(FakeMappedItem::setABinaryValue), FakeMappedItem.builder().aBinaryValue(sdkBytes).build(), AttributeValue.builder().b(sdkBytes).build()); } @Test public void mapperCanHandleSimpleList() { verifyNullableAttribute(EnhancedType.listOf(Integer.class), a -> a.name("value") .getter(FakeMappedItem::getAnIntegerList) .setter(FakeMappedItem::setAnIntegerList), FakeMappedItem.builder().anIntegerList(asList(1, 2, 3)).build(), AttributeValue.builder().l(asList(AttributeValue.builder().n("1").build(), AttributeValue.builder().n("2").build(), AttributeValue.builder().n("3").build())).build()); } @Test public void mapperCanHandleNestedLists() { FakeMappedItem fakeMappedItem = FakeMappedItem.builder() .aNestedStructure(singletonList(singletonList(FakeDocument.of("nested", null)))) .build(); Map<String, AttributeValue> documentMap = new HashMap<>(); documentMap.put("documentString", AttributeValue.builder().s("nested").build()); documentMap.put("documentInteger", AttributeValue.builder().nul(true).build()); AttributeValue attributeValue = AttributeValue.builder() .l(singletonList(AttributeValue.builder() .l(AttributeValue.builder().m(documentMap).build()) .build())) .build(); verifyNullableAttribute( EnhancedType.listOf(EnhancedType.listOf(EnhancedType.documentOf(FakeDocument.class, FAKE_DOCUMENT_TABLE_SCHEMA))), a -> a.name("value") .getter(FakeMappedItem::getANestedStructure) .setter(FakeMappedItem::setANestedStructure), fakeMappedItem, attributeValue); } @Test public void mapperCanHandleIntegerSet() { Set<Integer> valueSet = new HashSet<>(asList(1, 2, 3)); List<String> expectedList = valueSet.stream().map(Objects::toString).collect(toList()); verifyNullableAttribute(EnhancedType.setOf(Integer.class), a -> a.name("value") .getter(FakeMappedItem::getAnIntegerSet) .setter(FakeMappedItem::setAnIntegerSet), FakeMappedItem.builder().anIntegerSet(valueSet).build(), AttributeValue.builder().ns(expectedList).build()); } @Test public void mapperCanHandleStringSet() { Set<String> valueSet = new HashSet<>(asList("one", "two", "three")); List<String> expectedList = valueSet.stream().map(Objects::toString).collect(toList()); verifyNullableAttribute(EnhancedType.setOf(String.class), a -> a.name("value") .getter(FakeMappedItem::getAStringSet) .setter(FakeMappedItem::setAStringSet), FakeMappedItem.builder().aStringSet(valueSet).build(), AttributeValue.builder().ss(expectedList).build()); } @Test public void mapperCanHandleLongSet() { Set<Long> valueSet = new HashSet<>(asList(1L, 2L, 3L)); List<String> expectedList = valueSet.stream().map(Objects::toString).collect(toList()); verifyNullableAttribute(EnhancedType.setOf(Long.class), a -> a.name("value") .getter(FakeMappedItem::getALongSet) .setter(FakeMappedItem::setALongSet), FakeMappedItem.builder().aLongSet(valueSet).build(), AttributeValue.builder().ns(expectedList).build()); } @Test public void mapperCanHandleShortSet() { Set<Short> valueSet = new HashSet<>(asList((short) 1, (short) 2, (short) 3)); List<String> expectedList = valueSet.stream().map(Objects::toString).collect(toList()); verifyNullableAttribute(EnhancedType.setOf(Short.class), a -> a.name("value") .getter(FakeMappedItem::getAShortSet) .setter(FakeMappedItem::setAShortSet), FakeMappedItem.builder().aShortSet(valueSet).build(), AttributeValue.builder().ns(expectedList).build()); } @Test public void mapperCanHandleByteSet() { Set<Byte> valueSet = new HashSet<>(asList((byte) 1, (byte) 2, (byte) 3)); List<String> expectedList = valueSet.stream().map(Objects::toString).collect(toList()); verifyNullableAttribute(EnhancedType.setOf(Byte.class), a -> a.name("value") .getter(FakeMappedItem::getAByteSet) .setter(FakeMappedItem::setAByteSet), FakeMappedItem.builder().aByteSet(valueSet).build(), AttributeValue.builder().ns(expectedList).build()); } @Test public void mapperCanHandleDoubleSet() { Set<Double> valueSet = new HashSet<>(asList(1.2, 3.4, 5.6)); List<String> expectedList = valueSet.stream().map(Object::toString).collect(toList()); verifyNullableAttribute(EnhancedType.setOf(Double.class), a -> a.name("value") .getter(FakeMappedItem::getADoubleSet) .setter(FakeMappedItem::setADoubleSet), FakeMappedItem.builder().aDoubleSet(valueSet).build(), AttributeValue.builder().ns(expectedList).build()); } @Test public void mapperCanHandleFloatSet() { Set<Float> valueSet = new HashSet<>(asList(1.2f, 3.4f, 5.6f)); List<String> expectedList = valueSet.stream().map(Object::toString).collect(toList()); verifyNullableAttribute(EnhancedType.setOf(Float.class), a -> a.name("value") .getter(FakeMappedItem::getAFloatSet) .setter(FakeMappedItem::setAFloatSet), FakeMappedItem.builder().aFloatSet(valueSet).build(), AttributeValue.builder().ns(expectedList).build()); } @Test public void mapperCanHandleGenericMap() { Map<String, String> stringMap = new ConcurrentHashMap<>(); stringMap.put("one", "two"); stringMap.put("three", "four"); Map<String, AttributeValue> attributeValueMap = new HashMap<>(); attributeValueMap.put("one", AttributeValue.builder().s("two").build()); attributeValueMap.put("three", AttributeValue.builder().s("four").build()); verifyNullableAttribute(EnhancedType.mapOf(String.class, String.class), a -> a.name("value") .getter(FakeMappedItem::getAStringMap) .setter(FakeMappedItem::setAStringMap), FakeMappedItem.builder().aStringMap(stringMap).build(), AttributeValue.builder().m(attributeValueMap).build()); } @Test public void mapperCanHandleMapWithNullValue() { Map<String, String> stringMap = new HashMap<>(); stringMap.put("one", null); stringMap.put("two", "three"); Map<String, AttributeValue> attributeValueMap = new HashMap<>(); attributeValueMap.put("one", AttributeValue.builder().nul(true).build()); attributeValueMap.put("two", AttributeValue.builder().s("three").build()); verifyNullableAttribute(EnhancedType.mapOf(String.class, String.class), a -> a.name("value") .getter(FakeMappedItem::getAStringMap) .setter(FakeMappedItem::setAStringMap), FakeMappedItem.builder().aStringMap(stringMap).build(), AttributeValue.builder().m(attributeValueMap).build()); } @Test public void mapperCanHandleIntDoubleMap() { Map<Integer, Double> intDoubleMap = new ConcurrentHashMap<>(); intDoubleMap.put(1, 1.0); intDoubleMap.put(2, 3.0); Map<String, AttributeValue> attributeValueMap = new HashMap<>(); attributeValueMap.put("1", AttributeValue.builder().n("1.0").build()); attributeValueMap.put("2", AttributeValue.builder().n("3.0").build()); verifyNullableAttribute(EnhancedType.mapOf(Integer.class, Double.class), a -> a.name("value") .getter(FakeMappedItem::getAIntDoubleMap) .setter(FakeMappedItem::setAIntDoubleMap), FakeMappedItem.builder().aIntDoubleMap(intDoubleMap).build(), AttributeValue.builder().m(attributeValueMap).build()); } @Test public void getAttributeValue_correctlyMapsSuperclassAttributes() { FakeItem fakeItem = FakeItem.builder().id("id-value").build(); fakeItem.setSubclassAttribute("subclass-value"); AttributeValue attributeValue = FakeItem.getTableSchema().attributeValue(fakeItem, "subclass_attribute"); assertThat(attributeValue, is(AttributeValue.builder().s("subclass-value").build())); } @Test public void getAttributeValue_correctlyMapsComposedClassAttributes() { FakeItem fakeItem = FakeItem.builder().id("id-value") .composedObject(FakeItemComposedClass.builder().composedAttribute("composed-value").build()) .build(); AttributeValue attributeValue = FakeItem.getTableSchema().attributeValue(fakeItem, "composed_attribute"); assertThat(attributeValue, is(AttributeValue.builder().s("composed-value").build())); } @Test public void mapToItem_correctlyConstructsComposedClass() { Map<String, AttributeValue> itemMap = new HashMap<>(); itemMap.put("id", AttributeValue.builder().s("id-value").build()); itemMap.put("composed_attribute", AttributeValue.builder().s("composed-value").build()); FakeItem fakeItem = FakeItem.getTableSchema().mapToItem(itemMap); assertThat(fakeItem, is(FakeItem.builder() .id("id-value") .composedObject(FakeItemComposedClass.builder() .composedAttribute("composed-value") .build()) .build())); } @Test public void buildAbstractTableSchema() { StaticTableSchema<FakeMappedItem> tableSchema = StaticTableSchema.builder(FakeMappedItem.class) .addAttribute(String.class, a -> a.name("aString") .getter(FakeMappedItem::getAString) .setter(FakeMappedItem::setAString)) .build(); assertThat(tableSchema.itemToMap(FAKE_ITEM, false), is(singletonMap("aString", stringValue("test-string")))); exception.expect(UnsupportedOperationException.class); exception.expectMessage("abstract"); tableSchema.mapToItem(singletonMap("aString", stringValue("test-string"))); } @Test public void buildAbstractWithFlatten() { StaticTableSchema<FakeMappedItem> tableSchema = StaticTableSchema.builder(FakeMappedItem.class) .flatten(FAKE_DOCUMENT_TABLE_SCHEMA, FakeMappedItem::getAFakeDocument, FakeMappedItem::setAFakeDocument) .build(); FakeDocument document = FakeDocument.of("test-string", null); FakeMappedItem item = FakeMappedItem.builder().aFakeDocument(document).build(); assertThat(tableSchema.itemToMap(item, true), is(singletonMap("documentString", AttributeValue.builder().s("test-string").build()))); } @Test public void buildAbstractExtends() { StaticTableSchema<FakeAbstractSuperclass> superclassTableSchema = StaticTableSchema.builder(FakeAbstractSuperclass.class) .addAttribute(String.class, a -> a.name("aString") .getter(FakeAbstractSuperclass::getAString) .setter(FakeAbstractSuperclass::setAString)) .build(); StaticTableSchema<FakeAbstractSubclass> subclassTableSchema = StaticTableSchema.builder(FakeAbstractSubclass.class) .extend(superclassTableSchema) .build(); FakeAbstractSubclass item = new FakeAbstractSubclass(); item.setAString("test-string"); assertThat(subclassTableSchema.itemToMap(item, true), is(singletonMap("aString", AttributeValue.builder().s("test-string").build()))); } @Test public void buildAbstractTagWith() { StaticTableSchema<FakeDocument> abstractTableSchema = StaticTableSchema .builder(FakeDocument.class) .tags(new TestStaticTableTag()) .build(); assertThat(abstractTableSchema.tableMetadata().customMetadataObject(TABLE_TAG_KEY, String.class), is(Optional.of(TABLE_TAG_VALUE))); } @Test public void buildConcreteTagWith() { StaticTableSchema<FakeDocument> concreteTableSchema = StaticTableSchema .builder(FakeDocument.class) .newItemSupplier(FakeDocument::new) .tags(new TestStaticTableTag()) .build(); assertThat(concreteTableSchema.tableMetadata().customMetadataObject(TABLE_TAG_KEY, String.class), is(Optional.of(TABLE_TAG_VALUE))); } @Test public void instantiateFlattenedAbstractClassShouldThrowException() { StaticTableSchema<FakeAbstractSuperclass> superclassTableSchema = StaticTableSchema.builder(FakeAbstractSuperclass.class) .addAttribute(String.class, a -> a.name("aString") .getter(FakeAbstractSuperclass::getAString) .setter(FakeAbstractSuperclass::setAString)) .build(); exception.expect(IllegalArgumentException.class); exception.expectMessage("abstract"); StaticTableSchema.builder(FakeBrokenClass.class) .newItemSupplier(FakeBrokenClass::new) .flatten(superclassTableSchema, FakeBrokenClass::getAbstractObject, FakeBrokenClass::setAbstractObject); } @Test public void addSingleAttributeConverterProvider() { when(provider1.converterFor(EnhancedType.of(String.class))).thenReturn(attributeConverter1); StaticTableSchema<FakeMappedItem> tableSchema = StaticTableSchema.builder(FakeMappedItem.class) .newItemSupplier(FakeMappedItem::new) .addAttribute(String.class, a -> a.name("aString") .getter(FakeMappedItem::getAString) .setter(FakeMappedItem::setAString)) .attributeConverterProviders(provider1) .build(); assertThat(tableSchema.attributeConverterProvider(), is(provider1)); } @Test public void usesCustomAttributeConverterProvider() { String originalString = "test-string"; String expectedString = "test-string-custom"; when(provider1.converterFor(EnhancedType.of(String.class))).thenReturn(attributeConverter1); when(attributeConverter1.transformFrom(any())).thenReturn(AttributeValue.builder().s(expectedString).build()); StaticTableSchema<FakeMappedItem> tableSchema = StaticTableSchema.builder(FakeMappedItem.class) .newItemSupplier(FakeMappedItem::new) .addAttribute(String.class, a -> a.name("aString") .getter(FakeMappedItem::getAString) .setter(FakeMappedItem::setAString)) .attributeConverterProviders(provider1) .build(); Map<String, AttributeValue> resultMap = tableSchema.itemToMap(FakeMappedItem.builder().aString(originalString).build(), false); assertThat(resultMap.get("aString").s(), is(expectedString)); } @Test public void usesCustomAttributeConverterProviders() { String originalString = "test-string"; String expectedString = "test-string-custom"; when(provider2.converterFor(EnhancedType.of(String.class))).thenReturn(attributeConverter2); when(attributeConverter2.transformFrom(any())).thenReturn(AttributeValue.builder().s(expectedString).build()); StaticTableSchema<FakeMappedItem> tableSchema = StaticTableSchema.builder(FakeMappedItem.class) .newItemSupplier(FakeMappedItem::new) .addAttribute(String.class, a -> a.name("aString") .getter(FakeMappedItem::getAString) .setter(FakeMappedItem::setAString)) .attributeConverterProviders(provider1, provider2) .build(); Map<String, AttributeValue> resultMap = tableSchema.itemToMap(FakeMappedItem.builder().aString(originalString).build(), false); assertThat(resultMap.get("aString").s(), is(expectedString)); } @Test public void noConverterProvider_throwsException_whenMissingAttributeConverters() { exception.expect(NullPointerException.class); StaticTableSchema<FakeMappedItem> tableSchema = StaticTableSchema.builder(FakeMappedItem.class) .newItemSupplier(FakeMappedItem::new) .addAttribute(String.class, a -> a.name("aString") .getter(FakeMappedItem::getAString) .setter(FakeMappedItem::setAString)) .attributeConverterProviders(Collections.emptyList()) .build(); } @Test public void noConverterProvider_handlesCorrectly_whenAttributeConvertersAreSupplied() { String originalString = "test-string"; String expectedString = "test-string-custom"; when(attributeConverter1.transformFrom(any())).thenReturn(AttributeValue.builder().s(expectedString).build()); StaticTableSchema<FakeMappedItem> tableSchema = StaticTableSchema.builder(FakeMappedItem.class) .newItemSupplier(FakeMappedItem::new) .addAttribute(String.class, a -> a.name("aString") .getter(FakeMappedItem::getAString) .setter(FakeMappedItem::setAString) .attributeConverter(attributeConverter1)) .attributeConverterProviders(Collections.emptyList()) .build(); Map<String, AttributeValue> resultMap = tableSchema.itemToMap(FakeMappedItem.builder().aString(originalString).build(), false); assertThat(resultMap.get("aString").s(), is(expectedString)); } @Test public void builder_canBuildForGenericClassType() { StaticTableSchema<EntityEnvelopeBean<String>> envelopeTableSchema = StaticTableSchema.builder(new EnhancedType<EntityEnvelopeBean<String>>() {}) .newItemSupplier(EntityEnvelopeBean::new) .addAttribute(String.class, a -> a.name("entity") .getter(EntityEnvelopeBean::getEntity) .setter(EntityEnvelopeBean::setEntity)) .build(); EntityEnvelopeBean<String> testEnvelope = new EntityEnvelopeBean<>(); testEnvelope.setEntity("test-value"); Map<String, AttributeValue> expectedMap = Collections.singletonMap("entity", AttributeValue.fromS("test-value")); assertThat(envelopeTableSchema.itemToMap(testEnvelope, false), equalTo(expectedMap)); assertThat(envelopeTableSchema.mapToItem(expectedMap).getEntity(), equalTo("test-value")); } private <R> void verifyAttribute(EnhancedType<R> attributeType, Consumer<StaticAttribute.Builder<FakeMappedItem, R>> staticAttribute, FakeMappedItem fakeMappedItem, AttributeValue attributeValue) { StaticTableSchema<FakeMappedItem> tableSchema = StaticTableSchema.builder(FakeMappedItem.class) .newItemSupplier(FakeMappedItem::new) .addAttribute(attributeType, staticAttribute) .build(); Map<String, AttributeValue> expectedMap = singletonMap("value", attributeValue); Map<String, AttributeValue> resultMap = tableSchema.itemToMap(fakeMappedItem, false); assertThat(resultMap, is(expectedMap)); FakeMappedItem resultItem = tableSchema.mapToItem(expectedMap); assertThat(resultItem, is(fakeMappedItem)); } private <R> void verifyNullAttribute(EnhancedType<R> attributeType, Consumer<StaticAttribute.Builder<FakeMappedItem, R>> staticAttribute, FakeMappedItem fakeMappedItem) { StaticTableSchema<FakeMappedItem> tableSchema = StaticTableSchema.builder(FakeMappedItem.class) .newItemSupplier(FakeMappedItem::new) .addAttribute(attributeType, staticAttribute) .build(); Map<String, AttributeValue> expectedMap = singletonMap("value", nullAttributeValue()); Map<String, AttributeValue> resultMap = tableSchema.itemToMap(fakeMappedItem, false); assertThat(resultMap, is(expectedMap)); FakeMappedItem resultItem = tableSchema.mapToItem(expectedMap); assertThat(resultItem, is(nullValue())); } private <R> void verifyNullableAttribute(EnhancedType<R> attributeType, Consumer<StaticAttribute.Builder<FakeMappedItem, R>> staticAttribute, FakeMappedItem fakeMappedItem, AttributeValue attributeValue) { verifyAttribute(attributeType, staticAttribute, fakeMappedItem, attributeValue); verifyNullAttribute(attributeType, staticAttribute, FakeMappedItem.builder().build()); } }
3,929
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/StaticTableMetadataTest.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.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.is; import static software.amazon.awssdk.enhanced.dynamodb.TableMetadata.primaryIndexName; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.Optional; 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.TableMetadata; import software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType; public class StaticTableMetadataTest { private static final String INDEX_NAME = "test_index"; private static final String ATTRIBUTE_NAME = "test_attribute"; private static final String ATTRIBUTE_NAME_2 = "test_attribute_2"; @Rule public ExpectedException exception = ExpectedException.none(); @Test public void setAndRetrievePrimaryPartitionKey() { TableMetadata tableMetadata = StaticTableMetadata.builder() .addIndexPartitionKey(primaryIndexName(), ATTRIBUTE_NAME, AttributeValueType.S) .build(); assertThat(tableMetadata.primaryPartitionKey(), is(ATTRIBUTE_NAME)); } @Test public void setAndRetrievePrimarySortKey() { TableMetadata tableMetadata = StaticTableMetadata.builder() .addIndexSortKey(primaryIndexName(), ATTRIBUTE_NAME, AttributeValueType.S) .build(); assertThat(tableMetadata.primarySortKey(), is(Optional.of(ATTRIBUTE_NAME))); } @Test(expected = IllegalArgumentException.class) public void retrieveUnsetPrimaryPartitionKey() { TableMetadata tableMetadata = StaticTableMetadata.builder().build(); tableMetadata.primaryPartitionKey(); } @Test(expected = IllegalArgumentException.class) public void retrieveUnsetPrimaryPartitionKey_withSortKeySet() { TableMetadata tableMetadata = StaticTableMetadata.builder() .addIndexSortKey(primaryIndexName(), ATTRIBUTE_NAME, AttributeValueType.S) .build(); tableMetadata.primaryPartitionKey(); } @Test public void retrieveUnsetPrimarySortKey() { TableMetadata tableMetadata = StaticTableMetadata.builder() .addIndexPartitionKey(primaryIndexName(), ATTRIBUTE_NAME, AttributeValueType.S) .build(); assertThat(tableMetadata.primarySortKey(), is(Optional.empty())); } @Test public void setAndRetrieveSecondaryPartitionKey() { TableMetadata tableMetadata = StaticTableMetadata.builder() .addIndexPartitionKey(INDEX_NAME, ATTRIBUTE_NAME, AttributeValueType.S) .build(); assertThat(tableMetadata.indexPartitionKey(INDEX_NAME), is(ATTRIBUTE_NAME)); } @Test public void setAndRetrieveSecondarySortKey() { TableMetadata tableMetadata = StaticTableMetadata.builder() .addIndexSortKey(INDEX_NAME, ATTRIBUTE_NAME, AttributeValueType.S) .build(); assertThat(tableMetadata.indexSortKey(INDEX_NAME), is(Optional.of(ATTRIBUTE_NAME))); } @Test(expected = IllegalArgumentException.class) public void retrieveUnsetSecondaryPartitionKey() { TableMetadata tableMetadata = StaticTableMetadata.builder().build(); tableMetadata.indexPartitionKey(INDEX_NAME); } @Test public void retrieveSecondaryPartitionKeyForLocalIndex() { TableMetadata tableMetadata = StaticTableMetadata.builder() .addIndexPartitionKey(primaryIndexName(), ATTRIBUTE_NAME, AttributeValueType.S) .addIndexSortKey(INDEX_NAME, ATTRIBUTE_NAME_2, AttributeValueType.S) .build(); assertThat(tableMetadata.indexPartitionKey(INDEX_NAME), is(ATTRIBUTE_NAME)); } @Test public void retrieveUnsetSecondarySortKey() { TableMetadata tableMetadata = StaticTableMetadata.builder() .addIndexPartitionKey(INDEX_NAME, ATTRIBUTE_NAME, AttributeValueType.S) .build(); assertThat(tableMetadata.indexSortKey(INDEX_NAME), is(Optional.empty())); } @Test(expected = IllegalArgumentException.class) public void setSamePartitionKeyTwice() { StaticTableMetadata.builder() .addIndexPartitionKey("idx", "id", AttributeValueType.S) .addIndexPartitionKey("idx", "id", AttributeValueType.S) .build(); } @Test(expected = IllegalArgumentException.class) public void setSameSortKeyTwice() { StaticTableMetadata.builder() .addIndexSortKey("idx", "id", AttributeValueType.S) .addIndexSortKey("idx", "id", AttributeValueType.S) .build(); } @Test public void getPrimaryKeys_partitionAndSort() { TableMetadata tableMetadata = StaticTableMetadata.builder() .addIndexPartitionKey(primaryIndexName(), "primary_id", AttributeValueType.S) .addIndexSortKey(primaryIndexName(), "primary_sort", AttributeValueType.S) .addIndexPartitionKey(INDEX_NAME, "dummy", AttributeValueType.S) .addIndexSortKey(INDEX_NAME, "dummy2", AttributeValueType.S) .build(); assertThat(tableMetadata.primaryKeys(), containsInAnyOrder("primary_id", "primary_sort")); } @Test public void getPrimaryKeys_partition() { TableMetadata tableMetadata = StaticTableMetadata.builder() .addIndexPartitionKey(primaryIndexName(), "primary_id", AttributeValueType.S) .addIndexPartitionKey(INDEX_NAME, "dummy", AttributeValueType.S) .addIndexSortKey(INDEX_NAME, "dummy2", AttributeValueType.S) .build(); assertThat(tableMetadata.primaryKeys(), contains("primary_id")); } @Test(expected = IllegalArgumentException.class) public void getPrimaryKeys_unset() { TableMetadata tableMetadata = StaticTableMetadata.builder() .addIndexPartitionKey(INDEX_NAME, "dummy", AttributeValueType.S) .addIndexSortKey(INDEX_NAME, "dummy2", AttributeValueType.S) .build(); tableMetadata.primaryKeys(); } @Test public void getIndexKeys_partitionAndSort() { TableMetadata tableMetadata = StaticTableMetadata.builder() .addIndexPartitionKey(primaryIndexName(), "primary_id", AttributeValueType.S) .addIndexSortKey(primaryIndexName(), "primary_sort", AttributeValueType.S) .addIndexPartitionKey(INDEX_NAME, "dummy", AttributeValueType.S) .addIndexSortKey(INDEX_NAME, "dummy2", AttributeValueType.S) .build(); assertThat(tableMetadata.indexKeys(INDEX_NAME), containsInAnyOrder("dummy", "dummy2")); } @Test public void getIndexKeys_partition() { TableMetadata tableMetadata = StaticTableMetadata.builder() .addIndexPartitionKey(primaryIndexName(), "primary_id", AttributeValueType.S) .addIndexSortKey(primaryIndexName(), "primary_sort", AttributeValueType.S) .addIndexPartitionKey(INDEX_NAME, "dummy", AttributeValueType.S) .build(); assertThat(tableMetadata.indexKeys(INDEX_NAME), contains("dummy")); } @Test(expected = IllegalArgumentException.class) public void getIndexKeys_unset() { TableMetadata tableMetadata = StaticTableMetadata.builder() .addIndexPartitionKey(primaryIndexName(), "primary_id", AttributeValueType.S) .addIndexSortKey(primaryIndexName(), "primary_sort", AttributeValueType.S) .build(); tableMetadata.indexKeys(INDEX_NAME); } @Test public void getIndexKeys_sortOnly() { TableMetadata tableMetadata = StaticTableMetadata.builder() .addIndexPartitionKey(primaryIndexName(), "primary_id", AttributeValueType.S) .addIndexSortKey(primaryIndexName(), "primary_sort", AttributeValueType.S) .addIndexSortKey(INDEX_NAME, "dummy", AttributeValueType.S) .build(); assertThat(tableMetadata.indexKeys(INDEX_NAME), containsInAnyOrder("primary_id", "dummy")); } @Test public void getAllKeys() { TableMetadata tableMetadata = StaticTableMetadata.builder() .addIndexPartitionKey(primaryIndexName(), "primary_id", AttributeValueType.S) .addIndexSortKey(primaryIndexName(), "primary_sort", AttributeValueType.S) .addIndexPartitionKey(INDEX_NAME, "dummy", AttributeValueType.S) .addIndexSortKey(INDEX_NAME, "dummy2", AttributeValueType.S) .build(); assertThat(tableMetadata.allKeys(), containsInAnyOrder("primary_id", "primary_sort", "dummy", "dummy2")); } @Test public void getScalarAttributeValueType() { TableMetadata tableMetadata = StaticTableMetadata.builder() .addIndexPartitionKey(primaryIndexName(), "primary_id", AttributeValueType.S) .addIndexSortKey(primaryIndexName(), "primary_sort", AttributeValueType.N) .addIndexPartitionKey(INDEX_NAME, "dummy", AttributeValueType.B) .addIndexSortKey(INDEX_NAME, "dummy2", AttributeValueType.BOOL) .build(); assertThat(tableMetadata.scalarAttributeType("primary_id"), is(Optional.of(ScalarAttributeType.S))); assertThat(tableMetadata.scalarAttributeType("primary_sort"), is(Optional.of(ScalarAttributeType.N))); assertThat(tableMetadata.scalarAttributeType("dummy"), is(Optional.of(ScalarAttributeType.B))); assertThat(tableMetadata.scalarAttributeType("dummy2"), is(Optional.empty())); } @Test public void setAndRetrieveSimpleCustomMetadata() { TableMetadata tableMetadata = StaticTableMetadata.builder() .addCustomMetadataObject("custom-key", 123) .build(); assertThat(tableMetadata.customMetadataObject("custom-key", Integer.class), is(Optional.of(123))); } @Test public void setAndRetrieveCustomMetadataCollection() { TableMetadata tableMetadata = StaticTableMetadata.builder() .addCustomMetadataObject("custom-key", Collections.singleton("123")) .addCustomMetadataObject("custom-key", Collections.singleton("456")) .build(); Collection<String> metadataObject = tableMetadata.customMetadataObject("custom-key", Collection.class).orElse(null); assertThat(metadataObject.size(), is(2)); assertThat(metadataObject, contains("123", "456")); } @Test public void setAndRetrieveCustomMetadataMap() { TableMetadata tableMetadata = StaticTableMetadata.builder() .addCustomMetadataObject("custom-key", Collections.singletonMap("key1", "123")) .addCustomMetadataObject("custom-key", Collections.singletonMap("key2", "456")) .build(); Map<String, String> metadataObject = tableMetadata.customMetadataObject("custom-key", Map.class).orElse(null); assertThat(metadataObject.size(), is(2)); assertThat(metadataObject.get("key1"), is("123")); assertThat(metadataObject.get("key2"), is("456")); } @Test public void retrieveUnsetCustomMetadata() { TableMetadata tableMetadata = StaticTableMetadata.builder().build(); assertThat(tableMetadata.customMetadataObject("custom-key", Integer.class), is(Optional.empty())); } @Test(expected = IllegalArgumentException.class) public void setAndRetrieveCustomMetadataOfUnassignableType() { TableMetadata tableMetadata = StaticTableMetadata.builder() .addCustomMetadataObject("custom-key", 123.45) .build(); tableMetadata.customMetadataObject("custom-key", Integer.class); } @Test public void setAndRetrieveCustomMetadataOfDifferentButAssignableType() { TableMetadata tableMetadata = StaticTableMetadata.builder() .addCustomMetadataObject("custom-key", 123.45f) .build(); assertThat(tableMetadata.customMetadataObject("custom-key", Number.class), is(Optional.of(123.45f))); } @Test public void mergeFullIntoEmpty() { StaticTableMetadata tableMetadata = StaticTableMetadata.builder() .addIndexPartitionKey(primaryIndexName(), "primary_id", AttributeValueType.S) .addIndexSortKey(primaryIndexName(), "primary_sort", AttributeValueType.S) .addIndexPartitionKey(INDEX_NAME, "dummy", AttributeValueType.S) .addIndexSortKey(INDEX_NAME, "dummy2", AttributeValueType.S) .addCustomMetadataObject("custom1", "value1") .addCustomMetadataObject("custom2", "value2") .addCustomMetadataObject("custom-key", Collections.singletonMap("key1", "123")) .addCustomMetadataObject("custom-key", Collections.singletonMap("key2", "456")) .build(); StaticTableMetadata mergedTableMetadata = StaticTableMetadata.builder().mergeWith(tableMetadata).build(); assertThat(mergedTableMetadata, is(tableMetadata)); } @Test public void mergeEmptyIntoFull() { StaticTableMetadata emptyTableMetadata = StaticTableMetadata.builder().build(); StaticTableMetadata.Builder tableMetadataBuilder = StaticTableMetadata.builder() .addIndexPartitionKey(primaryIndexName(), "primary_id", AttributeValueType.S) .addIndexSortKey(primaryIndexName(), "primary_sort", AttributeValueType.S) .addIndexPartitionKey(INDEX_NAME, "dummy", AttributeValueType.S) .addIndexSortKey(INDEX_NAME, "dummy2", AttributeValueType.S) .addCustomMetadataObject("custom1", "value1") .addCustomMetadataObject("custom2", "value2") .addCustomMetadataObject("custom-key", Collections.singletonMap("key1", "123")) .addCustomMetadataObject("custom-key", Collections.singletonMap("key2", "456")); StaticTableMetadata original = tableMetadataBuilder.build(); StaticTableMetadata merged = tableMetadataBuilder.mergeWith(emptyTableMetadata).build(); assertThat(merged, is(original)); } @Test public void mergeWithDuplicateIndexPartitionKey() { StaticTableMetadata.Builder builder = StaticTableMetadata.builder().addIndexPartitionKey(INDEX_NAME, "id", AttributeValueType.S); exception.expect(IllegalArgumentException.class); exception.expectMessage("partition key"); exception.expectMessage(INDEX_NAME); builder.mergeWith(builder.build()); } @Test public void mergeWithDuplicateIndexSortKey() { StaticTableMetadata.Builder builder = StaticTableMetadata.builder().addIndexSortKey(INDEX_NAME, "id", AttributeValueType.S); exception.expect(IllegalArgumentException.class); exception.expectMessage("sort key"); exception.expectMessage(INDEX_NAME); builder.mergeWith(builder.build()); } @Test public void mergeWithDuplicateSingleCustomMetadata() { StaticTableMetadata.Builder builder = StaticTableMetadata.builder().addCustomMetadataObject(INDEX_NAME, "id"); exception.expect(IllegalArgumentException.class); exception.expectMessage("custom metadata"); exception.expectMessage(INDEX_NAME); builder.mergeWith(builder.build()); } @Test public void mergeWithCustomMetadataCollection() { StaticTableMetadata original = StaticTableMetadata.builder() .addCustomMetadataObject("custom-key", Collections.singleton("123")) .build(); StaticTableMetadata.Builder mergedBuilder = StaticTableMetadata.builder().addCustomMetadataObject("custom-key", Collections.singleton("456")); StaticTableMetadata merged = mergedBuilder.mergeWith(original).build(); Collection<String> metadataObject = merged.customMetadataObject("custom-key", Collection.class).orElse(null); assertThat(metadataObject.size(), is(2)); assertThat(metadataObject, contains("123", "456")); } @Test public void mergeWithCustomMetadataMap() { StaticTableMetadata original = StaticTableMetadata.builder() .addCustomMetadataObject("custom-key", Collections.singletonMap("key1", "123")) .build(); StaticTableMetadata.Builder mergedBuilder = StaticTableMetadata.builder().addCustomMetadataObject("custom-key", Collections.singletonMap("key2", "456")); StaticTableMetadata merged = mergedBuilder.mergeWith(original).build(); Map<String, String> metadataObject = merged.customMetadataObject("custom-key", Map.class).orElse(null); assertThat(metadataObject.size(), is(2)); assertThat(metadataObject.get("key1"), is("123")); assertThat(metadataObject.get("key2"), is("456")); } }
3,930
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/StaticImmutableTableSchemaTest.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 java.nio.charset.StandardCharsets.UTF_8; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static java.util.Collections.singletonMap; import static java.util.stream.Collectors.toList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasEntry; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; import static software.amazon.awssdk.enhanced.dynamodb.extensions.VersionedRecordExtension.AttributeTags.versionAttribute; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.nullAttributeValue; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.stringValue; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey; import java.math.BigDecimal; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Consumer; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; 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.AttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.AttributeConverterProvider; import software.amazon.awssdk.enhanced.dynamodb.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.TableMetadata; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItem; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItemComposedClass; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItemWithSort; import software.amazon.awssdk.enhanced.dynamodb.mapper.testimmutables.EntityEnvelopeImmutable; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; @RunWith(MockitoJUnitRunner.class) public class StaticImmutableTableSchemaTest { private static final String TABLE_TAG_KEY = "table-tag-key"; private static final String TABLE_TAG_VALUE = "table-tag-value"; private static final AttributeValue ATTRIBUTE_VALUE_B = AttributeValue.builder().bool(true).build(); private static final AttributeValue ATTRIBUTE_VALUE_S = AttributeValue.builder().s("test-string").build(); private static final StaticTableSchema<FakeDocument> FAKE_DOCUMENT_TABLE_SCHEMA = StaticTableSchema.builder(FakeDocument.class) .newItemSupplier(FakeDocument::new) .addAttribute(String.class, a -> a.name("documentString") .getter(FakeDocument::getDocumentString) .setter(FakeDocument::setDocumentString)) .addAttribute(Integer.class, a -> a.name("documentInteger") .getter(FakeDocument::getDocumentInteger) .setter(FakeDocument::setDocumentInteger)) .build(); private static final FakeMappedItem FAKE_ITEM = FakeMappedItem.builder() .aPrimitiveBoolean(true) .aBoolean(true) .aString("test-string") .build(); private static class FakeMappedItem { private boolean aPrimitiveBoolean; private Boolean aBoolean; private String aString; private Integer anInteger; private int aPrimitiveInteger; private Byte aByte; private byte aPrimitiveByte; private Long aLong; private long aPrimitiveLong; private Short aShort; private short aPrimitiveShort; private Double aDouble; private double aPrimitiveDouble; private Float aFloat; private float aPrimitiveFloat; private BigDecimal aBigDecimal; private SdkBytes aBinaryValue; private FakeDocument aFakeDocument; private Set<String> aStringSet; private Set<Integer> anIntegerSet; private Set<Byte> aByteSet; private Set<Long> aLongSet; private Set<Short> aShortSet; private Set<Double> aDoubleSet; private Set<Float> aFloatSet; private Set<SdkBytes> aBinarySet; private List<Integer> anIntegerList; private List<List<FakeDocument>> aNestedStructure; private Map<String, String> aStringMap; private Map<Integer, Double> aIntDoubleMap; private TestEnum testEnum; FakeMappedItem() { } FakeMappedItem(boolean aPrimitiveBoolean, Boolean aBoolean, String aString, Integer anInteger, int aPrimitiveInteger, Byte aByte, byte aPrimitiveByte, Long aLong, long aPrimitiveLong, Short aShort, short aPrimitiveShort, Double aDouble, double aPrimitiveDouble, Float aFloat, float aPrimitiveFloat, BigDecimal aBigDecimal, SdkBytes aBinaryValue, FakeDocument aFakeDocument, Set<String> aStringSet, Set<Integer> anIntegerSet, Set<Byte> aByteSet, Set<Long> aLongSet, Set<Short> aShortSet, Set<Double> aDoubleSet, Set<Float> aFloatSet, Set<SdkBytes> aBinarySet, List<Integer> anIntegerList, List<List<FakeDocument>> aNestedStructure, Map<String, String> aStringMap, Map<Integer, Double> aIntDoubleMap, TestEnum testEnum) { this.aPrimitiveBoolean = aPrimitiveBoolean; this.aBoolean = aBoolean; this.aString = aString; this.anInteger = anInteger; this.aPrimitiveInteger = aPrimitiveInteger; this.aByte = aByte; this.aPrimitiveByte = aPrimitiveByte; this.aLong = aLong; this.aPrimitiveLong = aPrimitiveLong; this.aShort = aShort; this.aPrimitiveShort = aPrimitiveShort; this.aDouble = aDouble; this.aPrimitiveDouble = aPrimitiveDouble; this.aFloat = aFloat; this.aPrimitiveFloat = aPrimitiveFloat; this.aBigDecimal = aBigDecimal; this.aBinaryValue = aBinaryValue; this.aFakeDocument = aFakeDocument; this.aStringSet = aStringSet; this.anIntegerSet = anIntegerSet; this.aByteSet = aByteSet; this.aLongSet = aLongSet; this.aShortSet = aShortSet; this.aDoubleSet = aDoubleSet; this.aFloatSet = aFloatSet; this.aBinarySet = aBinarySet; this.anIntegerList = anIntegerList; this.aNestedStructure = aNestedStructure; this.aStringMap = aStringMap; this.aIntDoubleMap = aIntDoubleMap; this.testEnum = testEnum; } public static Builder builder() { return new Builder(); } boolean isAPrimitiveBoolean() { return aPrimitiveBoolean; } void setAPrimitiveBoolean(boolean aPrimitiveBoolean) { this.aPrimitiveBoolean = aPrimitiveBoolean; } Boolean getABoolean() { return aBoolean; } void setABoolean(Boolean aBoolean) { this.aBoolean = aBoolean; } String getAString() { return aString; } void setAString(String aString) { this.aString = aString; } Integer getAnInteger() { return anInteger; } void setAnInteger(Integer anInteger) { this.anInteger = anInteger; } int getAPrimitiveInteger() { return aPrimitiveInteger; } void setAPrimitiveInteger(int aPrimitiveInteger) { this.aPrimitiveInteger = aPrimitiveInteger; } Byte getAByte() { return aByte; } void setAByte(Byte aByte) { this.aByte = aByte; } byte getAPrimitiveByte() { return aPrimitiveByte; } void setAPrimitiveByte(byte aPrimitiveByte) { this.aPrimitiveByte = aPrimitiveByte; } Long getALong() { return aLong; } void setALong(Long aLong) { this.aLong = aLong; } long getAPrimitiveLong() { return aPrimitiveLong; } void setAPrimitiveLong(long aPrimitiveLong) { this.aPrimitiveLong = aPrimitiveLong; } Short getAShort() { return aShort; } void setAShort(Short aShort) { this.aShort = aShort; } short getAPrimitiveShort() { return aPrimitiveShort; } void setAPrimitiveShort(short aPrimitiveShort) { this.aPrimitiveShort = aPrimitiveShort; } Double getADouble() { return aDouble; } void setADouble(Double aDouble) { this.aDouble = aDouble; } double getAPrimitiveDouble() { return aPrimitiveDouble; } void setAPrimitiveDouble(double aPrimitiveDouble) { this.aPrimitiveDouble = aPrimitiveDouble; } Float getAFloat() { return aFloat; } void setAFloat(Float aFloat) { this.aFloat = aFloat; } BigDecimal aBigDecimal() { return aBigDecimal; } void setABigDecimal(BigDecimal aBigDecimal) { this.aBigDecimal = aBigDecimal; } float getAPrimitiveFloat() { return aPrimitiveFloat; } void setAPrimitiveFloat(float aPrimitiveFloat) { this.aPrimitiveFloat = aPrimitiveFloat; } SdkBytes getABinaryValue() { return aBinaryValue; } void setABinaryValue(SdkBytes aBinaryValue) { this.aBinaryValue = aBinaryValue; } FakeDocument getAFakeDocument() { return aFakeDocument; } void setAFakeDocument(FakeDocument aFakeDocument) { this.aFakeDocument = aFakeDocument; } Set<String> getAStringSet() { return aStringSet; } void setAStringSet(Set<String> aStringSet) { this.aStringSet = aStringSet; } Set<Integer> getAnIntegerSet() { return anIntegerSet; } void setAnIntegerSet(Set<Integer> anIntegerSet) { this.anIntegerSet = anIntegerSet; } Set<Byte> getAByteSet() { return aByteSet; } void setAByteSet(Set<Byte> aByteSet) { this.aByteSet = aByteSet; } Set<Long> getALongSet() { return aLongSet; } void setALongSet(Set<Long> aLongSet) { this.aLongSet = aLongSet; } Set<Short> getAShortSet() { return aShortSet; } void setAShortSet(Set<Short> aShortSet) { this.aShortSet = aShortSet; } Set<Double> getADoubleSet() { return aDoubleSet; } void setADoubleSet(Set<Double> aDoubleSet) { this.aDoubleSet = aDoubleSet; } Set<Float> getAFloatSet() { return aFloatSet; } void setAFloatSet(Set<Float> aFloatSet) { this.aFloatSet = aFloatSet; } Set<SdkBytes> getABinarySet() { return aBinarySet; } void setABinarySet(Set<SdkBytes> aBinarySet) { this.aBinarySet = aBinarySet; } List<Integer> getAnIntegerList() { return anIntegerList; } void setAnIntegerList(List<Integer> anIntegerList) { this.anIntegerList = anIntegerList; } List<List<FakeDocument>> getANestedStructure() { return aNestedStructure; } void setANestedStructure(List<List<FakeDocument>> aNestedStructure) { this.aNestedStructure = aNestedStructure; } Map<String, String> getAStringMap() { return aStringMap; } void setAStringMap(Map<String, String> aStringMap) { this.aStringMap = aStringMap; } Map<Integer, Double> getAIntDoubleMap() { return aIntDoubleMap; } void setAIntDoubleMap(Map<Integer, Double> aIntDoubleMap) { this.aIntDoubleMap = aIntDoubleMap; } TestEnum getTestEnum() { return testEnum; } void setTestEnum(TestEnum testEnum) { this.testEnum = testEnum; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } FakeMappedItem that = (FakeMappedItem) o; return aPrimitiveBoolean == that.aPrimitiveBoolean && aPrimitiveInteger == that.aPrimitiveInteger && aPrimitiveByte == that.aPrimitiveByte && aPrimitiveLong == that.aPrimitiveLong && aPrimitiveShort == that.aPrimitiveShort && Double.compare(that.aPrimitiveDouble, aPrimitiveDouble) == 0 && Float.compare(that.aPrimitiveFloat, aPrimitiveFloat) == 0 && Objects.equals(aBoolean, that.aBoolean) && Objects.equals(aString, that.aString) && Objects.equals(anInteger, that.anInteger) && Objects.equals(aByte, that.aByte) && Objects.equals(aLong, that.aLong) && Objects.equals(aShort, that.aShort) && Objects.equals(aDouble, that.aDouble) && Objects.equals(aFloat, that.aFloat) && Objects.equals(aBinaryValue, that.aBinaryValue) && Objects.equals(aFakeDocument, that.aFakeDocument) && Objects.equals(aStringSet, that.aStringSet) && Objects.equals(anIntegerSet, that.anIntegerSet) && Objects.equals(aByteSet, that.aByteSet) && Objects.equals(aLongSet, that.aLongSet) && Objects.equals(aShortSet, that.aShortSet) && Objects.equals(aDoubleSet, that.aDoubleSet) && Objects.equals(aFloatSet, that.aFloatSet) && Objects.equals(aBinarySet, that.aBinarySet) && Objects.equals(anIntegerList, that.anIntegerList) && Objects.equals(aNestedStructure, that.aNestedStructure) && Objects.equals(aStringMap, that.aStringMap) && Objects.equals(aIntDoubleMap, that.aIntDoubleMap) && Objects.equals(testEnum, that.testEnum); } @Override public int hashCode() { return Objects.hash(aPrimitiveBoolean, aBoolean, aString, anInteger, aPrimitiveInteger, aByte, aPrimitiveByte, aLong, aPrimitiveLong, aShort, aPrimitiveShort, aDouble, aPrimitiveDouble, aFloat, aPrimitiveFloat, aBinaryValue, aFakeDocument, aStringSet, anIntegerSet, aByteSet, aLongSet, aShortSet, aDoubleSet, aFloatSet, aBinarySet, anIntegerList, aNestedStructure, aStringMap, aIntDoubleMap, testEnum); } public enum TestEnum { ONE, TWO, THREE; } private static class Builder { private boolean aPrimitiveBoolean; private Boolean aBoolean; private String aString; private Integer anInteger; private int aPrimitiveInteger; private Byte aByte; private byte aPrimitiveByte; private Long aLong; private long aPrimitiveLong; private Short aShort; private short aPrimitiveShort; private Double aDouble; private double aPrimitiveDouble; private Float aFloat; private float aPrimitiveFloat; private BigDecimal aBigDecimal; private SdkBytes aBinaryValue; private FakeDocument aFakeDocument; private Set<String> aStringSet; private Set<Integer> anIntegerSet; private Set<Byte> aByteSet; private Set<Long> aLongSet; private Set<Short> aShortSet; private Set<Double> aDoubleSet; private Set<Float> aFloatSet; private Set<SdkBytes> aBinarySet; private List<Integer> anIntegerList; private List<List<FakeDocument>> aNestedStructure; private Map<String, String> aStringMap; private Map<Integer, Double> aIntDoubleMap; private TestEnum testEnum; Builder aPrimitiveBoolean(boolean aPrimitiveBoolean) { this.aPrimitiveBoolean = aPrimitiveBoolean; return this; } Builder aBoolean(Boolean aBoolean) { this.aBoolean = aBoolean; return this; } Builder aString(String aString) { this.aString = aString; return this; } Builder anInteger(Integer anInteger) { this.anInteger = anInteger; return this; } Builder aPrimitiveInteger(int aPrimitiveInteger) { this.aPrimitiveInteger = aPrimitiveInteger; return this; } Builder aByte(Byte aByte) { this.aByte = aByte; return this; } Builder aPrimitiveByte(byte aPrimitiveByte) { this.aPrimitiveByte = aPrimitiveByte; return this; } Builder aLong(Long aLong) { this.aLong = aLong; return this; } Builder aPrimitiveLong(long aPrimitiveLong) { this.aPrimitiveLong = aPrimitiveLong; return this; } Builder aShort(Short aShort) { this.aShort = aShort; return this; } Builder aPrimitiveShort(short aPrimitiveShort) { this.aPrimitiveShort = aPrimitiveShort; return this; } Builder aDouble(Double aDouble) { this.aDouble = aDouble; return this; } Builder aPrimitiveDouble(double aPrimitiveDouble) { this.aPrimitiveDouble = aPrimitiveDouble; return this; } Builder aFloat(Float aFloat) { this.aFloat = aFloat; return this; } Builder aPrimitiveFloat(float aPrimitiveFloat) { this.aPrimitiveFloat = aPrimitiveFloat; return this; } Builder aBigDecimal(BigDecimal aBigDecimal) { this.aBigDecimal = aBigDecimal; return this; } Builder aBinaryValue(SdkBytes aBinaryValue) { this.aBinaryValue = aBinaryValue; return this; } Builder aFakeDocument(FakeDocument aFakeDocument) { this.aFakeDocument = aFakeDocument; return this; } Builder aStringSet(Set<String> aStringSet) { this.aStringSet = aStringSet; return this; } Builder anIntegerSet(Set<Integer> anIntegerSet) { this.anIntegerSet = anIntegerSet; return this; } Builder aByteSet(Set<Byte> aByteSet) { this.aByteSet = aByteSet; return this; } Builder aLongSet(Set<Long> aLongSet) { this.aLongSet = aLongSet; return this; } Builder aShortSet(Set<Short> aShortSet) { this.aShortSet = aShortSet; return this; } Builder aDoubleSet(Set<Double> aDoubleSet) { this.aDoubleSet = aDoubleSet; return this; } Builder aFloatSet(Set<Float> aFloatSet) { this.aFloatSet = aFloatSet; return this; } Builder aBinarySet(Set<SdkBytes> aBinarySet) { this.aBinarySet = aBinarySet; return this; } Builder anIntegerList(List<Integer> anIntegerList) { this.anIntegerList = anIntegerList; return this; } Builder aNestedStructure(List<List<FakeDocument>> aNestedStructure) { this.aNestedStructure = aNestedStructure; return this; } Builder aStringMap(Map<String, String> aStringMap) { this.aStringMap = aStringMap; return this; } Builder aIntDoubleMap(Map<Integer, Double> aIntDoubleMap) { this.aIntDoubleMap = aIntDoubleMap; return this; } Builder testEnum(TestEnum testEnum) { this.testEnum = testEnum; return this; } public StaticImmutableTableSchemaTest.FakeMappedItem build() { return new StaticImmutableTableSchemaTest.FakeMappedItem(aPrimitiveBoolean, aBoolean, aString, anInteger, aPrimitiveInteger, aByte, aPrimitiveByte, aLong, aPrimitiveLong, aShort, aPrimitiveShort, aDouble, aPrimitiveDouble, aFloat, aPrimitiveFloat, aBigDecimal, aBinaryValue, aFakeDocument, aStringSet, anIntegerSet, aByteSet, aLongSet, aShortSet, aDoubleSet, aFloatSet, aBinarySet, anIntegerList, aNestedStructure, aStringMap, aIntDoubleMap, testEnum); } } } private static class FakeDocument { private String documentString; private Integer documentInteger; FakeDocument() { } private FakeDocument(String documentString, Integer documentInteger) { this.documentString = documentString; this.documentInteger = documentInteger; } private static FakeDocument of(String documentString, Integer documentInteger) { return new FakeDocument(documentString, documentInteger); } String getDocumentString() { return documentString; } void setDocumentString(String documentString) { this.documentString = documentString; } Integer getDocumentInteger() { return documentInteger; } void setDocumentInteger(Integer documentInteger) { this.documentInteger = documentInteger; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } FakeDocument that = (FakeDocument) o; return Objects.equals(documentString, that.documentString) && Objects.equals(documentInteger, that.documentInteger); } @Override public int hashCode() { return Objects.hash(documentString, documentInteger); } } private static class FakeAbstractSubclass extends FakeAbstractSuperclass { } private static class FakeBrokenClass { FakeAbstractSuperclass abstractObject; FakeAbstractSuperclass getAbstractObject() { return abstractObject; } void setAbstractObject(FakeAbstractSuperclass abstractObject) { this.abstractObject = abstractObject; } } private static abstract class FakeAbstractSuperclass { private String aString; String getAString() { return aString; } void setAString(String aString) { this.aString = aString; } } private static final Collection<StaticAttribute<FakeMappedItem, ?>> ATTRIBUTES = Arrays.asList( StaticAttribute.builder(FakeMappedItem.class, Boolean.class) .name("a_primitive_boolean") .getter(FakeMappedItem::isAPrimitiveBoolean) .setter(FakeMappedItem::setAPrimitiveBoolean) .build(), StaticAttribute.builder(FakeMappedItem.class, Boolean.class) .name("a_boolean") .getter(FakeMappedItem::getABoolean) .setter(FakeMappedItem::setABoolean) .build(), StaticAttribute.builder(FakeMappedItem.class, String.class) .name("a_string") .getter(FakeMappedItem::getAString) .setter(FakeMappedItem::setAString) .build() ); private StaticTableSchema<FakeMappedItem> createSimpleTableSchema() { return StaticTableSchema.builder(FakeMappedItem.class) .newItemSupplier(FakeMappedItem::new) .attributes(ATTRIBUTES) .build(); } private static class TestStaticTableTag implements StaticTableTag { @Override public Consumer<StaticTableMetadata.Builder> modifyMetadata() { return metadata -> metadata.addCustomMetadataObject(TABLE_TAG_KEY, TABLE_TAG_VALUE); } } @Mock private AttributeConverterProvider provider1; @Mock private AttributeConverterProvider provider2; @Mock private AttributeConverter<String> attributeConverter1; @Mock private AttributeConverter<String> attributeConverter2; @Rule public ExpectedException exception = ExpectedException.none(); @Test public void itemType_returnsCorrectClass() { assertThat(FakeItem.getTableSchema().itemType(), is(equalTo(EnhancedType.of(FakeItem.class)))); } @Test public void itemType_returnsCorrectClassWhenBuiltWithEnhancedType() { StaticImmutableTableSchema<FakeMappedItem, FakeMappedItem.Builder> tableSchema = StaticImmutableTableSchema.builder(EnhancedType.of(FakeMappedItem.class), EnhancedType.of(FakeMappedItem.Builder.class)) .newItemBuilder(FakeMappedItem::builder, FakeMappedItem.Builder::build) .build(); assertThat(tableSchema.itemType(), is(equalTo(EnhancedType.of(FakeMappedItem.class)))); } @Test public void getTableMetadata_hasCorrectFields() { TableMetadata tableMetadata = FakeItemWithSort.getTableSchema().tableMetadata(); assertThat(tableMetadata.primaryPartitionKey(), is("id")); assertThat(tableMetadata.primarySortKey(), is(Optional.of("sort"))); } @Test public void itemToMap_returnsCorrectMapWithMultipleAttributes() { Map<String, AttributeValue> attributeMap = createSimpleTableSchema().itemToMap(FAKE_ITEM, false); assertThat(attributeMap.size(), is(3)); assertThat(attributeMap, hasEntry("a_boolean", ATTRIBUTE_VALUE_B)); assertThat(attributeMap, hasEntry("a_primitive_boolean", ATTRIBUTE_VALUE_B)); assertThat(attributeMap, hasEntry("a_string", ATTRIBUTE_VALUE_S)); } @Test public void itemToMap_omitsNullAttributes() { FakeMappedItem fakeMappedItemWithNulls = FakeMappedItem.builder().aPrimitiveBoolean(true).build(); Map<String, AttributeValue> attributeMap = createSimpleTableSchema().itemToMap(fakeMappedItemWithNulls, true); assertThat(attributeMap.size(), is(1)); assertThat(attributeMap, hasEntry("a_primitive_boolean", ATTRIBUTE_VALUE_B)); } @Test public void itemToMap_filtersAttributes() { Map<String, AttributeValue> attributeMap = createSimpleTableSchema() .itemToMap(FAKE_ITEM, asList("a_boolean", "a_string")); assertThat(attributeMap.size(), is(2)); assertThat(attributeMap, hasEntry("a_boolean", ATTRIBUTE_VALUE_B)); assertThat(attributeMap, hasEntry("a_string", ATTRIBUTE_VALUE_S)); } @Test(expected = IllegalArgumentException.class) public void itemToMap_attributeNotFound_throwsIllegalArgumentException() { createSimpleTableSchema().itemToMap(FAKE_ITEM, singletonList("unknown_key")); } @Test public void mapToItem_returnsCorrectItemWithMultipleAttributes() { Map<String, AttributeValue> attributeValueMap = new HashMap<>(); attributeValueMap.put("a_boolean", ATTRIBUTE_VALUE_B); attributeValueMap.put("a_primitive_boolean", ATTRIBUTE_VALUE_B); attributeValueMap.put("a_string", ATTRIBUTE_VALUE_S); FakeMappedItem fakeMappedItem = createSimpleTableSchema().mapToItem(Collections.unmodifiableMap(attributeValueMap)); assertThat(fakeMappedItem, is(FAKE_ITEM)); } @Test public void mapToItem_unknownAttributes_doNotCauseErrors() { Map<String, AttributeValue> attributeValueMap = new HashMap<>(); attributeValueMap.put("unknown_attribute", ATTRIBUTE_VALUE_S); createSimpleTableSchema().mapToItem(Collections.unmodifiableMap(attributeValueMap)); } @Test(expected = IllegalArgumentException.class) public void mapToItem_attributesWrongType_throwsException() { Map<String, AttributeValue> attributeValueMap = new HashMap<>(); attributeValueMap.put("a_boolean", ATTRIBUTE_VALUE_S); attributeValueMap.put("a_primitive_boolean", ATTRIBUTE_VALUE_S); attributeValueMap.put("a_string", ATTRIBUTE_VALUE_B); createSimpleTableSchema().mapToItem(Collections.unmodifiableMap(attributeValueMap)); } @Test public void mapperCanHandleEnum() { verifyNullableAttribute(EnhancedType.of(FakeMappedItem.TestEnum.class), a -> a.name("value") .getter(FakeMappedItem::getTestEnum) .setter(FakeMappedItem::setTestEnum), FakeMappedItem.builder().testEnum(FakeMappedItem.TestEnum.ONE).build(), AttributeValue.builder().s("ONE").build()); } @Test public void mapperCanHandleDocument() { FakeDocument fakeDocument = FakeDocument.of("test-123", 123); Map<String, AttributeValue> expectedMap = new HashMap<>(); expectedMap.put("documentInteger", AttributeValue.builder().n("123").build()); expectedMap.put("documentString", AttributeValue.builder().s("test-123").build()); verifyNullableAttribute(EnhancedType.documentOf(FakeDocument.class, FAKE_DOCUMENT_TABLE_SCHEMA), a -> a.name("value") .getter(FakeMappedItem::getAFakeDocument) .setter(FakeMappedItem::setAFakeDocument), FakeMappedItem.builder().aFakeDocument(fakeDocument).build(), AttributeValue.builder().m(expectedMap).build()); } @Test public void mapperCanHandleDocumentWithNullValues() { verifyNullAttribute(EnhancedType.documentOf(FakeDocument.class, FAKE_DOCUMENT_TABLE_SCHEMA), a -> a.name("value") .getter(FakeMappedItem::getAFakeDocument) .setter(FakeMappedItem::setAFakeDocument), FakeMappedItem.builder().build()); } @Test public void mapperCanHandleInteger() { verifyNullableAttribute(EnhancedType.of(Integer.class), a -> a.name("value") .getter(FakeMappedItem::getAnInteger) .setter(FakeMappedItem::setAnInteger), FakeMappedItem.builder().anInteger(123).build(), AttributeValue.builder().n("123").build()); } @Test public void mapperCanHandlePrimitiveInteger() { verifyAttribute(EnhancedType.of(int.class), a -> a.name("value") .getter(FakeMappedItem::getAPrimitiveInteger) .setter(FakeMappedItem::setAPrimitiveInteger), FakeMappedItem.builder().aPrimitiveInteger(123).build(), AttributeValue.builder().n("123").build()); } @Test public void mapperCanHandleBoolean() { verifyNullableAttribute(EnhancedType.of(Boolean.class), a -> a.name("value") .getter(FakeMappedItem::getABoolean) .setter(FakeMappedItem::setABoolean), FakeMappedItem.builder().aBoolean(true).build(), AttributeValue.builder().bool(true).build()); } @Test public void mapperCanHandlePrimitiveBoolean() { verifyAttribute(EnhancedType.of(boolean.class), a -> a.name("value") .getter(FakeMappedItem::isAPrimitiveBoolean) .setter(FakeMappedItem::setAPrimitiveBoolean), FakeMappedItem.builder().aPrimitiveBoolean(true).build(), AttributeValue.builder().bool(true).build()); } @Test public void mapperCanHandleString() { verifyNullableAttribute(EnhancedType.of(String.class), a -> a.name("value") .getter(FakeMappedItem::getAString) .setter(FakeMappedItem::setAString), FakeMappedItem.builder().aString("onetwothree").build(), AttributeValue.builder().s("onetwothree").build()); } @Test public void mapperCanHandleLong() { verifyNullableAttribute(EnhancedType.of(Long.class), a -> a.name("value") .getter(FakeMappedItem::getALong) .setter(FakeMappedItem::setALong), FakeMappedItem.builder().aLong(123L).build(), AttributeValue.builder().n("123").build()); } @Test public void mapperCanHandlePrimitiveLong() { verifyAttribute(EnhancedType.of(long.class), a -> a.name("value") .getter(FakeMappedItem::getAPrimitiveLong) .setter(FakeMappedItem::setAPrimitiveLong), FakeMappedItem.builder().aPrimitiveLong(123L).build(), AttributeValue.builder().n("123").build()); } @Test public void mapperCanHandleShort() { verifyNullableAttribute(EnhancedType.of(Short.class), a -> a.name("value") .getter(FakeMappedItem::getAShort) .setter(FakeMappedItem::setAShort), FakeMappedItem.builder().aShort((short)123).build(), AttributeValue.builder().n("123").build()); } @Test public void mapperCanHandlePrimitiveShort() { verifyAttribute(EnhancedType.of(short.class), a -> a.name("value") .getter(FakeMappedItem::getAPrimitiveShort) .setter(FakeMappedItem::setAPrimitiveShort), FakeMappedItem.builder().aPrimitiveShort((short)123).build(), AttributeValue.builder().n("123").build()); } @Test public void mapperCanHandleByte() { verifyNullableAttribute(EnhancedType.of(Byte.class), a -> a.name("value") .getter(FakeMappedItem::getAByte) .setter(FakeMappedItem::setAByte), FakeMappedItem.builder().aByte((byte)123).build(), AttributeValue.builder().n("123").build()); } @Test public void mapperCanHandlePrimitiveByte() { verifyAttribute(EnhancedType.of(byte.class), a -> a.name("value") .getter(FakeMappedItem::getAPrimitiveByte) .setter(FakeMappedItem::setAPrimitiveByte), FakeMappedItem.builder().aPrimitiveByte((byte)123).build(), AttributeValue.builder().n("123").build()); } @Test public void mapperCanHandleDouble() { verifyNullableAttribute(EnhancedType.of(Double.class), a -> a.name("value") .getter(FakeMappedItem::getADouble) .setter(FakeMappedItem::setADouble), FakeMappedItem.builder().aDouble(1.23).build(), AttributeValue.builder().n("1.23").build()); } @Test public void mapperCanHandlePrimitiveDouble() { verifyAttribute(EnhancedType.of(double.class), a -> a.name("value") .getter(FakeMappedItem::getAPrimitiveDouble) .setter(FakeMappedItem::setAPrimitiveDouble), FakeMappedItem.builder().aPrimitiveDouble(1.23).build(), AttributeValue.builder().n("1.23").build()); } @Test public void mapperCanHandleFloat() { verifyNullableAttribute(EnhancedType.of(Float.class), a -> a.name("value") .getter(FakeMappedItem::getAFloat) .setter(FakeMappedItem::setAFloat), FakeMappedItem.builder().aFloat(1.23f).build(), AttributeValue.builder().n("1.23").build()); } @Test public void mapperCanHandlePrimitiveFloat() { verifyAttribute(EnhancedType.of(float.class), a -> a.name("value") .getter(FakeMappedItem::getAPrimitiveFloat) .setter(FakeMappedItem::setAPrimitiveFloat), FakeMappedItem.builder().aPrimitiveFloat(1.23f).build(), AttributeValue.builder().n("1.23").build()); } @Test public void mapperCanHandleBinary() { SdkBytes sdkBytes = SdkBytes.fromString("test", UTF_8); verifyNullableAttribute(EnhancedType.of(SdkBytes.class), a -> a.name("value") .getter(FakeMappedItem::getABinaryValue) .setter(FakeMappedItem::setABinaryValue), FakeMappedItem.builder().aBinaryValue(sdkBytes).build(), AttributeValue.builder().b(sdkBytes).build()); } @Test public void mapperCanHandleSimpleList() { verifyNullableAttribute(EnhancedType.listOf(Integer.class), a -> a.name("value") .getter(FakeMappedItem::getAnIntegerList) .setter(FakeMappedItem::setAnIntegerList), FakeMappedItem.builder().anIntegerList(asList(1, 2, 3)).build(), AttributeValue.builder().l(asList(AttributeValue.builder().n("1").build(), AttributeValue.builder().n("2").build(), AttributeValue.builder().n("3").build())).build()); } @Test public void mapperCanHandleNestedLists() { FakeMappedItem fakeMappedItem = FakeMappedItem.builder() .aNestedStructure(singletonList(singletonList(FakeDocument.of("nested", null)))) .build(); Map<String, AttributeValue> documentMap = new HashMap<>(); documentMap.put("documentString", AttributeValue.builder().s("nested").build()); documentMap.put("documentInteger", AttributeValue.builder().nul(true).build()); AttributeValue attributeValue = AttributeValue.builder() .l(singletonList(AttributeValue.builder() .l(AttributeValue.builder().m(documentMap).build()) .build())) .build(); verifyNullableAttribute( EnhancedType.listOf(EnhancedType.listOf(EnhancedType.documentOf(FakeDocument.class, FAKE_DOCUMENT_TABLE_SCHEMA))), a -> a.name("value") .getter(FakeMappedItem::getANestedStructure) .setter(FakeMappedItem::setANestedStructure), fakeMappedItem, attributeValue); } @Test public void mapperCanHandleIntegerSet() { Set<Integer> valueSet = new HashSet<>(asList(1, 2, 3)); List<String> expectedList = valueSet.stream().map(Objects::toString).collect(toList()); verifyNullableAttribute(EnhancedType.setOf(Integer.class), a -> a.name("value") .getter(FakeMappedItem::getAnIntegerSet) .setter(FakeMappedItem::setAnIntegerSet), FakeMappedItem.builder().anIntegerSet(valueSet).build(), AttributeValue.builder().ns(expectedList).build()); } @Test public void mapperCanHandleStringSet() { Set<String> valueSet = new HashSet<>(asList("one", "two", "three")); List<String> expectedList = valueSet.stream().map(Objects::toString).collect(toList()); verifyNullableAttribute(EnhancedType.setOf(String.class), a -> a.name("value") .getter(FakeMappedItem::getAStringSet) .setter(FakeMappedItem::setAStringSet), FakeMappedItem.builder().aStringSet(valueSet).build(), AttributeValue.builder().ss(expectedList).build()); } @Test public void mapperCanHandleLongSet() { Set<Long> valueSet = new HashSet<>(asList(1L, 2L, 3L)); List<String> expectedList = valueSet.stream().map(Objects::toString).collect(toList()); verifyNullableAttribute(EnhancedType.setOf(Long.class), a -> a.name("value") .getter(FakeMappedItem::getALongSet) .setter(FakeMappedItem::setALongSet), FakeMappedItem.builder().aLongSet(valueSet).build(), AttributeValue.builder().ns(expectedList).build()); } @Test public void mapperCanHandleShortSet() { Set<Short> valueSet = new HashSet<>(asList((short) 1, (short) 2, (short) 3)); List<String> expectedList = valueSet.stream().map(Objects::toString).collect(toList()); verifyNullableAttribute(EnhancedType.setOf(Short.class), a -> a.name("value") .getter(FakeMappedItem::getAShortSet) .setter(FakeMappedItem::setAShortSet), FakeMappedItem.builder().aShortSet(valueSet).build(), AttributeValue.builder().ns(expectedList).build()); } @Test public void mapperCanHandleByteSet() { Set<Byte> valueSet = new HashSet<>(asList((byte) 1, (byte) 2, (byte) 3)); List<String> expectedList = valueSet.stream().map(Objects::toString).collect(toList()); verifyNullableAttribute(EnhancedType.setOf(Byte.class), a -> a.name("value") .getter(FakeMappedItem::getAByteSet) .setter(FakeMappedItem::setAByteSet), FakeMappedItem.builder().aByteSet(valueSet).build(), AttributeValue.builder().ns(expectedList).build()); } @Test public void mapperCanHandleDoubleSet() { Set<Double> valueSet = new HashSet<>(asList(1.2, 3.4, 5.6)); List<String> expectedList = valueSet.stream().map(Object::toString).collect(toList()); verifyNullableAttribute(EnhancedType.setOf(Double.class), a -> a.name("value") .getter(FakeMappedItem::getADoubleSet) .setter(FakeMappedItem::setADoubleSet), FakeMappedItem.builder().aDoubleSet(valueSet).build(), AttributeValue.builder().ns(expectedList).build()); } @Test public void mapperCanHandleFloatSet() { Set<Float> valueSet = new HashSet<>(asList(1.2f, 3.4f, 5.6f)); List<String> expectedList = valueSet.stream().map(Object::toString).collect(toList()); verifyNullableAttribute(EnhancedType.setOf(Float.class), a -> a.name("value") .getter(FakeMappedItem::getAFloatSet) .setter(FakeMappedItem::setAFloatSet), FakeMappedItem.builder().aFloatSet(valueSet).build(), AttributeValue.builder().ns(expectedList).build()); } @Test public void mapperCanHandleGenericMap() { Map<String, String> stringMap = new ConcurrentHashMap<>(); stringMap.put("one", "two"); stringMap.put("three", "four"); Map<String, AttributeValue> attributeValueMap = new HashMap<>(); attributeValueMap.put("one", AttributeValue.builder().s("two").build()); attributeValueMap.put("three", AttributeValue.builder().s("four").build()); verifyNullableAttribute(EnhancedType.mapOf(String.class, String.class), a -> a.name("value") .getter(FakeMappedItem::getAStringMap) .setter(FakeMappedItem::setAStringMap), FakeMappedItem.builder().aStringMap(stringMap).build(), AttributeValue.builder().m(attributeValueMap).build()); } @Test public void mapperCanHandleIntDoubleMap() { Map<Integer, Double> intDoubleMap = new ConcurrentHashMap<>(); intDoubleMap.put(1, 1.0); intDoubleMap.put(2, 3.0); Map<String, AttributeValue> attributeValueMap = new HashMap<>(); attributeValueMap.put("1", AttributeValue.builder().n("1.0").build()); attributeValueMap.put("2", AttributeValue.builder().n("3.0").build()); verifyNullableAttribute(EnhancedType.mapOf(Integer.class, Double.class), a -> a.name("value") .getter(FakeMappedItem::getAIntDoubleMap) .setter(FakeMappedItem::setAIntDoubleMap), FakeMappedItem.builder().aIntDoubleMap(intDoubleMap).build(), AttributeValue.builder().m(attributeValueMap).build()); } @Test public void getAttributeValue_correctlyMapsSuperclassAttributes() { FakeItem fakeItem = FakeItem.builder().id("id-value").build(); fakeItem.setSubclassAttribute("subclass-value"); AttributeValue attributeValue = FakeItem.getTableSchema().attributeValue(fakeItem, "subclass_attribute"); assertThat(attributeValue, is(AttributeValue.builder().s("subclass-value").build())); } @Test public void getAttributeValue_correctlyMapsComposedClassAttributes() { FakeItem fakeItem = FakeItem.builder().id("id-value") .composedObject(FakeItemComposedClass.builder().composedAttribute("composed-value").build()) .build(); AttributeValue attributeValue = FakeItem.getTableSchema().attributeValue(fakeItem, "composed_attribute"); assertThat(attributeValue, is(AttributeValue.builder().s("composed-value").build())); } @Test public void mapToItem_correctlyConstructsComposedClass() { Map<String, AttributeValue> itemMap = new HashMap<>(); itemMap.put("id", AttributeValue.builder().s("id-value").build()); itemMap.put("composed_attribute", AttributeValue.builder().s("composed-value").build()); FakeItem fakeItem = FakeItem.getTableSchema().mapToItem(itemMap); assertThat(fakeItem, is(FakeItem.builder() .id("id-value") .composedObject(FakeItemComposedClass.builder() .composedAttribute("composed-value") .build()) .build())); } @Test public void mapToItem_preserveEmptyBean_shouldInitializeEmptyBean() { FakeItem fakeItem = new FakeItem(); Map<String, AttributeValue> itemMap = FakeItem.getTableSchema().itemToMap(fakeItem, false); FakeItem result = FakeItem.getTableSchema().mapToItem(itemMap, true); assertThat(result, is(fakeItem)); } @Test public void mapToItem_nestedBeanPreserveEmptyBean_shouldInitializeEmptyBean() { StaticTableSchema<FakeItem> staticTableSchema = StaticTableSchema.builder(FakeItem.class) .newItemSupplier(FakeItem::new) .flatten(FakeItemComposedClass.getTableSchema(), FakeItem::getComposedObject, FakeItem::setComposedObject) .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())) .addAttribute(EnhancedType.documentOf(FakeItemComposedClass.class, FakeItemComposedClass.getTableSchema(), b -> b.preserveEmptyObject(true)), a -> a.name("composedObject").getter(FakeItem::getComposedObject) .setter(FakeItem::setComposedObject)) .build(); FakeItemComposedClass nestedBean = new FakeItemComposedClass(); FakeItem fakeItem = new FakeItem("1", 1, nestedBean); Map<String, AttributeValue> itemMap = staticTableSchema.itemToMap(fakeItem, false); FakeItem result = staticTableSchema.mapToItem(itemMap); assertThat(result.getComposedObject(), is(nestedBean)); } @Test public void itemToMap_nestedBeanIgnoreNulls_shouldOmitNullFields() { StaticTableSchema<FakeItem> staticTableSchema = StaticTableSchema.builder(FakeItem.class) .newItemSupplier(FakeItem::new) .addAttribute(String.class, a -> a.name("id") .getter(FakeItem::getId) .setter(FakeItem::setId) .addTag(primaryPartitionKey())) .addAttribute(EnhancedType.documentOf(FakeItemComposedClass.class, FakeItemComposedClass.getTableSchema(), b -> b.ignoreNulls(true)), a -> a.name("composedObject").getter(FakeItem::getComposedObject) .setter(FakeItem::setComposedObject)) .build(); FakeItemComposedClass nestedBean = new FakeItemComposedClass(); FakeItem fakeItem = new FakeItem("1", 1, nestedBean); Map<String, AttributeValue> itemMap = staticTableSchema.itemToMap(fakeItem, true); AttributeValue expectedAttributeValue = AttributeValue.builder().m(new HashMap<>()).build(); assertThat(itemMap.size(), is(2)); System.out.println(itemMap); assertThat(itemMap, hasEntry("composedObject", expectedAttributeValue)); } @Test public void buildAbstractTableSchema() { StaticTableSchema<FakeMappedItem> tableSchema = StaticTableSchema.builder(FakeMappedItem.class) .addAttribute(String.class, a -> a.name("aString") .getter(FakeMappedItem::getAString) .setter(FakeMappedItem::setAString)) .build(); assertThat(tableSchema.itemToMap(FAKE_ITEM, false), is(singletonMap("aString", stringValue("test-string")))); exception.expect(UnsupportedOperationException.class); exception.expectMessage("abstract"); tableSchema.mapToItem(singletonMap("aString", stringValue("test-string"))); } @Test public void buildAbstractWithFlatten() { StaticTableSchema<FakeMappedItem> tableSchema = StaticTableSchema.builder(FakeMappedItem.class) .flatten(FAKE_DOCUMENT_TABLE_SCHEMA, FakeMappedItem::getAFakeDocument, FakeMappedItem::setAFakeDocument) .build(); FakeDocument document = FakeDocument.of("test-string", null); FakeMappedItem item = FakeMappedItem.builder().aFakeDocument(document).build(); assertThat(tableSchema.itemToMap(item, true), is(singletonMap("documentString", AttributeValue.builder().s("test-string").build()))); } @Test public void buildAbstractExtends() { StaticTableSchema<FakeAbstractSuperclass> superclassTableSchema = StaticTableSchema.builder(FakeAbstractSuperclass.class) .addAttribute(String.class, a -> a.name("aString") .getter(FakeAbstractSuperclass::getAString) .setter(FakeAbstractSuperclass::setAString)) .build(); StaticTableSchema<FakeAbstractSubclass> subclassTableSchema = StaticTableSchema.builder(FakeAbstractSubclass.class) .extend(superclassTableSchema) .build(); FakeAbstractSubclass item = new FakeAbstractSubclass(); item.setAString("test-string"); assertThat(subclassTableSchema.itemToMap(item, true), is(singletonMap("aString", AttributeValue.builder().s("test-string").build()))); } @Test public void buildAbstractTagWith() { StaticTableSchema<FakeDocument> abstractTableSchema = StaticTableSchema .builder(FakeDocument.class) .tags(new TestStaticTableTag()) .build(); assertThat(abstractTableSchema.tableMetadata().customMetadataObject(TABLE_TAG_KEY, String.class), is(Optional.of(TABLE_TAG_VALUE))); } @Test public void buildConcreteTagWith() { StaticTableSchema<FakeDocument> concreteTableSchema = StaticTableSchema .builder(FakeDocument.class) .newItemSupplier(FakeDocument::new) .tags(new TestStaticTableTag()) .build(); assertThat(concreteTableSchema.tableMetadata().customMetadataObject(TABLE_TAG_KEY, String.class), is(Optional.of(TABLE_TAG_VALUE))); } @Test public void instantiateFlattenedAbstractClassShouldThrowException() { StaticTableSchema<FakeAbstractSuperclass> superclassTableSchema = StaticTableSchema.builder(FakeAbstractSuperclass.class) .addAttribute(String.class, a -> a.name("aString") .getter(FakeAbstractSuperclass::getAString) .setter(FakeAbstractSuperclass::setAString)) .build(); exception.expect(IllegalArgumentException.class); exception.expectMessage("abstract"); StaticTableSchema.builder(FakeBrokenClass.class) .newItemSupplier(FakeBrokenClass::new) .flatten(superclassTableSchema, FakeBrokenClass::getAbstractObject, FakeBrokenClass::setAbstractObject); } @Test public void addSingleAttributeConverterProvider() { when(provider1.converterFor(EnhancedType.of(String.class))).thenReturn(attributeConverter1); StaticTableSchema<FakeMappedItem> tableSchema = StaticTableSchema.builder(FakeMappedItem.class) .newItemSupplier(FakeMappedItem::new) .addAttribute(String.class, a -> a.name("aString") .getter(FakeMappedItem::getAString) .setter(FakeMappedItem::setAString)) .attributeConverterProviders(provider1) .build(); assertThat(tableSchema.attributeConverterProvider(), is(provider1)); } @Test public void usesCustomAttributeConverterProvider() { String originalString = "test-string"; String expectedString = "test-string-custom"; when(provider1.converterFor(EnhancedType.of(String.class))).thenReturn(attributeConverter1); when(attributeConverter1.transformFrom(any())).thenReturn(AttributeValue.builder().s(expectedString).build()); StaticTableSchema<FakeMappedItem> tableSchema = StaticTableSchema.builder(FakeMappedItem.class) .newItemSupplier(FakeMappedItem::new) .addAttribute(String.class, a -> a.name("aString") .getter(FakeMappedItem::getAString) .setter(FakeMappedItem::setAString)) .attributeConverterProviders(provider1) .build(); Map<String, AttributeValue> resultMap = tableSchema.itemToMap(FakeMappedItem.builder().aString(originalString).build(), false); assertThat(resultMap.get("aString").s(), is(expectedString)); } @Test public void usesCustomAttributeConverterProviders() { String originalString = "test-string"; String expectedString = "test-string-custom"; when(provider2.converterFor(EnhancedType.of(String.class))).thenReturn(attributeConverter2); when(attributeConverter2.transformFrom(any())).thenReturn(AttributeValue.builder().s(expectedString).build()); StaticTableSchema<FakeMappedItem> tableSchema = StaticTableSchema.builder(FakeMappedItem.class) .newItemSupplier(FakeMappedItem::new) .addAttribute(String.class, a -> a.name("aString") .getter(FakeMappedItem::getAString) .setter(FakeMappedItem::setAString)) .attributeConverterProviders(provider1, provider2) .build(); Map<String, AttributeValue> resultMap = tableSchema.itemToMap(FakeMappedItem.builder().aString(originalString).build(), false); assertThat(resultMap.get("aString").s(), is(expectedString)); } @Test public void noConverterProvider_throwsException_whenMissingAttributeConverters() { exception.expect(NullPointerException.class); StaticTableSchema<FakeMappedItem> tableSchema = StaticTableSchema.builder(FakeMappedItem.class) .newItemSupplier(FakeMappedItem::new) .addAttribute(String.class, a -> a.name("aString") .getter(FakeMappedItem::getAString) .setter(FakeMappedItem::setAString)) .attributeConverterProviders(Collections.emptyList()) .build(); } @Test public void noConverterProvider_handlesCorrectly_whenAttributeConvertersAreSupplied() { String originalString = "test-string"; String expectedString = "test-string-custom"; when(attributeConverter1.transformFrom(any())).thenReturn(AttributeValue.builder().s(expectedString).build()); StaticTableSchema<FakeMappedItem> tableSchema = StaticTableSchema.builder(FakeMappedItem.class) .newItemSupplier(FakeMappedItem::new) .addAttribute(String.class, a -> a.name("aString") .getter(FakeMappedItem::getAString) .setter(FakeMappedItem::setAString) .attributeConverter(attributeConverter1)) .attributeConverterProviders(Collections.emptyList()) .build(); Map<String, AttributeValue> resultMap = tableSchema.itemToMap(FakeMappedItem.builder().aString(originalString).build(), false); assertThat(resultMap.get("aString").s(), is(expectedString)); } @Test public void builder_canBuildForGenericClassType() { StaticImmutableTableSchema<EntityEnvelopeImmutable<String>, EntityEnvelopeImmutable.Builder<String>> envelopeTableSchema = StaticImmutableTableSchema.builder(new EnhancedType<EntityEnvelopeImmutable<String>>() {}, new EnhancedType<EntityEnvelopeImmutable.Builder<String>>() {}) .newItemBuilder(EntityEnvelopeImmutable.Builder::new, EntityEnvelopeImmutable.Builder::build) .addAttribute(String.class, a -> a.name("entity") .getter(EntityEnvelopeImmutable::entity) .setter(EntityEnvelopeImmutable.Builder::setEntity)) .build(); EntityEnvelopeImmutable<String> testEnvelope = new EntityEnvelopeImmutable<>("test-value"); Map<String, AttributeValue> expectedMap = Collections.singletonMap("entity", AttributeValue.fromS("test-value")); assertThat(envelopeTableSchema.itemToMap(testEnvelope, false), equalTo(expectedMap)); assertThat(envelopeTableSchema.mapToItem(expectedMap).entity(), equalTo("test-value")); } private <R> void verifyAttribute(EnhancedType<R> attributeType, Consumer<StaticAttribute.Builder<FakeMappedItem, R>> staticAttribute, FakeMappedItem fakeMappedItem, AttributeValue attributeValue) { StaticTableSchema<FakeMappedItem> tableSchema = StaticTableSchema.builder(FakeMappedItem.class) .newItemSupplier(FakeMappedItem::new) .addAttribute(attributeType, staticAttribute) .build(); Map<String, AttributeValue> expectedMap = singletonMap("value", attributeValue); Map<String, AttributeValue> resultMap = tableSchema.itemToMap(fakeMappedItem, false); assertThat(resultMap, is(expectedMap)); FakeMappedItem resultItem = tableSchema.mapToItem(expectedMap); assertThat(resultItem, is(fakeMappedItem)); } private <R> void verifyNullAttribute(EnhancedType<R> attributeType, Consumer<StaticAttribute.Builder<FakeMappedItem, R>> staticAttribute, FakeMappedItem fakeMappedItem) { StaticTableSchema<FakeMappedItem> tableSchema = StaticTableSchema.builder(FakeMappedItem.class) .newItemSupplier(FakeMappedItem::new) .addAttribute(attributeType, staticAttribute) .build(); Map<String, AttributeValue> expectedMap = singletonMap("value", nullAttributeValue()); Map<String, AttributeValue> resultMap = tableSchema.itemToMap(fakeMappedItem, false); assertThat(resultMap, is(expectedMap)); FakeMappedItem resultItem = tableSchema.mapToItem(expectedMap); assertThat(resultItem, is(nullValue())); } private <R> void verifyNullableAttribute(EnhancedType<R> attributeType, Consumer<StaticAttribute.Builder<FakeMappedItem, R>> staticAttribute, FakeMappedItem fakeMappedItem, AttributeValue attributeValue) { verifyAttribute(attributeType, staticAttribute, fakeMappedItem, attributeValue); verifyNullAttribute(attributeType, staticAttribute, FakeMappedItem.builder().build()); } }
3,931
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/ImmutableAttributeTest.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 static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; import java.util.Objects; 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.AttributeConverterProvider; import software.amazon.awssdk.enhanced.dynamodb.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.internal.mapper.ResolvedImmutableAttribute; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; @RunWith(MockitoJUnitRunner.class) public class ImmutableAttributeTest { 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; private static class SimpleItem { private String aString; SimpleItem(String aString) { this.aString = aString; } String getAString() { return this.aString; } void setAString(String aString) { this.aString = aString; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SimpleItem that = (SimpleItem) o; return aString == that.aString; } @Override public int hashCode() { return Objects.hash(aString); } } @Test public void build_maximal() { ImmutableAttribute<Object, Object, String> immutableAttribute = ImmutableAttribute.builder(Object.class, Object.class, String.class) .name("test-attribute") .getter(TEST_GETTER) .setter(TEST_SETTER) .tags(mockTag) .attributeConverter(attributeConverter) .build(); assertThat(immutableAttribute.name()).isEqualTo("test-attribute"); assertThat(immutableAttribute.getter()).isSameAs(TEST_GETTER); assertThat(immutableAttribute.setter()).isSameAs(TEST_SETTER); assertThat(immutableAttribute.tags()).containsExactly(mockTag); assertThat(immutableAttribute.type()).isEqualTo(EnhancedType.of(String.class)); assertThat(immutableAttribute.attributeConverter()).isSameAs(attributeConverter); } @Test public void build_minimal() { ImmutableAttribute<Object, Object, String> immutableAttribute = ImmutableAttribute.builder(Object.class, Object.class, String.class) .name("test-attribute") .getter(TEST_GETTER) .setter(TEST_SETTER) .build(); assertThat(immutableAttribute.name()).isEqualTo("test-attribute"); assertThat(immutableAttribute.getter()).isSameAs(TEST_GETTER); assertThat(immutableAttribute.setter()).isSameAs(TEST_SETTER); assertThat(immutableAttribute.tags()).isEmpty(); assertThat(immutableAttribute.type()).isEqualTo(EnhancedType.of(String.class)); } @Test public void build_missing_name() { assertThatThrownBy(() -> ImmutableAttribute.builder(Object.class, Object.class, String.class) .getter(TEST_GETTER) .setter(TEST_SETTER) .build()) .isInstanceOf(NullPointerException.class) .hasMessageContaining("name"); } @Test public void build_missing_getter() { assertThatThrownBy(() -> ImmutableAttribute.builder(Object.class, Object.class, String.class) .name("test-attribute") .setter(TEST_SETTER) .build()) .isInstanceOf(NullPointerException.class) .hasMessageContaining("getter"); } @Test public void build_missing_setter() { assertThatThrownBy(() -> ImmutableAttribute.builder(Object.class, Object.class, String.class) .name("test-attribute") .getter(TEST_GETTER) .build()) .isInstanceOf(NullPointerException.class) .hasMessageContaining("setter"); } @Test public void toBuilder() { ImmutableAttribute<Object, Object, String> immutableAttribute = ImmutableAttribute.builder(Object.class, Object.class, String.class) .name("test-attribute") .getter(TEST_GETTER) .setter(TEST_SETTER) .tags(mockTag, mockTag2) .attributeConverter(attributeConverter) .build(); ImmutableAttribute<Object, Object, String> clonedAttribute = immutableAttribute.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() { ImmutableAttribute<Object, Object, String> immutableAttribute = ImmutableAttribute.builder(Object.class, Object.class, String.class) .name("test-attribute") .getter(TEST_GETTER) .setter(TEST_SETTER) .addTag(mockTag) .build(); assertThat(immutableAttribute.tags()).containsExactly(mockTag); } @Test public void build_addTag_multiple() { ImmutableAttribute<Object, Object, String> immutableAttribute = ImmutableAttribute.builder(Object.class, Object.class, String.class) .name("test-attribute") .getter(TEST_GETTER) .setter(TEST_SETTER) .addTag(mockTag) .addTag(mockTag2) .build(); assertThat(immutableAttribute.tags()).containsExactly(mockTag, mockTag2); } @Test public void build_addAttributeConverter() { ImmutableAttribute<Object, Object, String> immutableAttribute = ImmutableAttribute.builder(Object.class, Object.class, String.class) .name("test-attribute") .getter(TEST_GETTER) .setter(TEST_SETTER) .attributeConverter(attributeConverter) .build(); AttributeConverter<String> attributeConverterR = immutableAttribute.attributeConverter(); assertThat(attributeConverterR).isEqualTo(attributeConverter); } @Test public void resolve_uses_customConverter() { when(attributeConverter.transformFrom(any())).thenReturn(AttributeValue.builder().s("test-string-custom").build()); ImmutableAttribute<SimpleItem, SimpleItem, String> staticAttribute = ImmutableAttribute.builder(SimpleItem.class, SimpleItem.class, String.class) .name("test-attribute") .getter(SimpleItem::getAString) .setter(SimpleItem::setAString) .attributeConverter(attributeConverter) .build(); ResolvedImmutableAttribute<SimpleItem, SimpleItem> resolvedAttribute = staticAttribute.resolve(AttributeConverterProvider.defaultProvider()); Function<SimpleItem, AttributeValue> attributeValueFunction = resolvedAttribute.attributeGetterMethod(); SimpleItem item = new SimpleItem("test-string"); AttributeValue resultAttributeValue = attributeValueFunction.apply(item); assertThat(resultAttributeValue.s()).isEqualTo("test-string-custom"); } }
3,932
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/TableSchemaMetadataTest.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.atomicCounter; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.updateBehavior; import java.time.Instant; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Stream; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.extensions.AutoGeneratedTimestampRecordExtension; import software.amazon.awssdk.enhanced.dynamodb.internal.mapper.AtomicCounter; import software.amazon.awssdk.enhanced.dynamodb.mapper.testbeans.CustomMetadataBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.testbeans.CustomMetadataImmutableBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.testbeans.CustomMetadataItem; public class TableSchemaMetadataTest { private static List<TableSchema> tableSchemas; @BeforeAll static void initializeSchemas() { StaticTableSchema<CustomMetadataItem> staticTableSchema = StaticTableSchema.builder(CustomMetadataItem.class) .newItemSupplier(CustomMetadataItem::new) .addAttribute(String.class, a -> a.name("id") .getter(CustomMetadataItem::getId) .setter(CustomMetadataItem::setId) .addTag(primaryPartitionKey())) .addAttribute(String.class, a -> a.name("customMetadataObjectAttribute") .getter(CustomMetadataItem::getCustomMetadataObjectAttribute) .setter(CustomMetadataItem::setCustomMetadataObjectAttribute) .addTag(updateBehavior(UpdateBehavior.WRITE_IF_NOT_EXISTS))) .addAttribute(Instant.class, a -> a.name("customMetadataCollectionAttribute") .getter(CustomMetadataItem::getCustomMetadataCollectionAttribute) .setter(CustomMetadataItem::setCustomMetadataCollectionAttribute) .addTag(getTimestampTag())) .addAttribute(Long.class, a -> a.name("customMetadataMapAttribute") .getter(CustomMetadataItem::getCustomMetadataMapAttribute) .setter(CustomMetadataItem::setCustomMetadataMapAttribute) .addTag(atomicCounter())) .build(); tableSchemas = new ArrayList<>(); tableSchemas.add(BeanTableSchema.create(CustomMetadataBean.class)); tableSchemas.add(ImmutableTableSchema.create(CustomMetadataImmutableBean.class)); tableSchemas.add(staticTableSchema); } @ParameterizedTest @MethodSource("tableSchemas") void testCustomMetadataObjectTags(TableSchema tableSchema) { Optional<UpdateBehavior> customMetadataObject = tableSchema.tableMetadata().customMetadataObject("UpdateBehavior:customMetadataObjectAttribute", UpdateBehavior.class); assertThat(customMetadataObject).isPresent(); UpdateBehavior updateBehavior = customMetadataObject.get(); assertThat(updateBehavior).isEqualTo(UpdateBehavior.WRITE_IF_NOT_EXISTS); } @ParameterizedTest @MethodSource("tableSchemas") void testCustomMetadataCollectionTags(TableSchema tableSchema) { Optional<Collection> customMetadataCollection = tableSchema.tableMetadata().customMetadataObject("AutoGeneratedTimestampExtension:AutoGeneratedTimestampAttribute", Collection.class); assertThat(customMetadataCollection).isPresent(); Collection<String> timestamps = customMetadataCollection.get(); assertThat(timestamps).hasSize(1); String timestamp = timestamps.iterator().next(); assertThat(timestamp).isNotNull(); assertThat(timestamp).isEqualTo("customMetadataCollectionAttribute"); } @ParameterizedTest @MethodSource("tableSchemas") void testCustomMetadataMapTags(TableSchema tableSchema) { Optional<Map> customMetadataMap = tableSchema.tableMetadata() .customMetadataObject("AtomicCounter:Counters", Map.class); assertThat(customMetadataMap).isPresent(); Map<String, AtomicCounter> atomicCounters = customMetadataMap.get(); AtomicCounter customMetadataMapAttribute = atomicCounters.get("customMetadataMapAttribute"); assertThat(customMetadataMapAttribute).isNotNull(); assertThat(customMetadataMapAttribute.startValue().value()).isEqualTo(0L); assertThat(customMetadataMapAttribute.delta().value()).isEqualTo(1L); } static Stream<TableSchema> tableSchemas() { return tableSchemas.stream(); } static StaticAttributeTag getTimestampTag() { return AutoGeneratedTimestampRecordExtension.AttributeTags.autoGeneratedTimestampAttribute(); } }
3,933
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/ImmutableTableSchemaTest.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 java.util.Collections.singletonMap; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasEntry; import static org.hamcrest.Matchers.is; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.nullAttributeValue; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.stringValue; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Test; import software.amazon.awssdk.enhanced.dynamodb.mapper.testbeans.AbstractBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.testbeans.AbstractImmutable; import software.amazon.awssdk.enhanced.dynamodb.mapper.testbeans.DocumentImmutable; import software.amazon.awssdk.enhanced.dynamodb.mapper.testbeans.FlattenedBeanImmutable; import software.amazon.awssdk.enhanced.dynamodb.mapper.testbeans.FlattenedImmutableImmutable; import software.amazon.awssdk.enhanced.dynamodb.mapper.testbeans.NestedImmutable; import software.amazon.awssdk.enhanced.dynamodb.mapper.testbeans.NestedImmutableIgnoreNulls; import software.amazon.awssdk.enhanced.dynamodb.mapper.testbeans.ToBuilderImmutable; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; public class ImmutableTableSchemaTest { @Test public void documentImmutable_correctlyMapsBeanAttributes() { ImmutableTableSchema<DocumentImmutable> documentImmutableTableSchema = ImmutableTableSchema.create(DocumentImmutable.class); AbstractBean abstractBean = new AbstractBean(); abstractBean.setAttribute2("two"); DocumentImmutable documentImmutable = DocumentImmutable.builder().id("id-value") .attribute1("one") .abstractBean(abstractBean) .build(); AttributeValue expectedDocument = AttributeValue.builder() .m(singletonMap("attribute2", stringValue("two"))) .build(); Map<String, AttributeValue> itemMap = documentImmutableTableSchema.itemToMap(documentImmutable, true); assertThat(itemMap.size(), is(3)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("attribute1", stringValue("one"))); assertThat(itemMap, hasEntry("abstractBean", expectedDocument)); } @Test public void documentImmutable_list_correctlyMapsBeanAttributes() { ImmutableTableSchema<DocumentImmutable> documentImmutableTableSchema = ImmutableTableSchema.create(DocumentImmutable.class); AbstractBean abstractBean1 = new AbstractBean(); abstractBean1.setAttribute2("two"); AbstractBean abstractBean2 = new AbstractBean(); abstractBean2.setAttribute2("three"); DocumentImmutable documentImmutable = DocumentImmutable.builder() .id("id-value") .attribute1("one") .abstractBeanList(Arrays.asList(abstractBean1, abstractBean2)) .build(); AttributeValue expectedDocument1 = AttributeValue.builder() .m(singletonMap("attribute2", stringValue("two"))) .build(); AttributeValue expectedDocument2 = AttributeValue.builder() .m(singletonMap("attribute2", stringValue("three"))) .build(); AttributeValue expectedList = AttributeValue.builder().l(expectedDocument1, expectedDocument2).build(); Map<String, AttributeValue> itemMap = documentImmutableTableSchema.itemToMap(documentImmutable, true); assertThat(itemMap.size(), is(3)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("attribute1", stringValue("one"))); assertThat(itemMap, hasEntry("abstractBeanList", expectedList)); } @Test public void documentImmutable_map_correctlyMapsBeanAttributes() { ImmutableTableSchema<DocumentImmutable> documentImmutableTableSchema = ImmutableTableSchema.create(DocumentImmutable.class); AbstractBean abstractBean1 = new AbstractBean(); abstractBean1.setAttribute2("two"); AbstractBean abstractBean2 = new AbstractBean(); abstractBean2.setAttribute2("three"); Map<String, AbstractBean> abstractBeanMap = new HashMap<>(); abstractBeanMap.put("key1", abstractBean1); abstractBeanMap.put("key2", abstractBean2); DocumentImmutable documentImmutable = DocumentImmutable.builder() .id("id-value") .attribute1("one") .abstractBeanMap(abstractBeanMap) .build(); AttributeValue expectedDocument1 = AttributeValue.builder() .m(singletonMap("attribute2", stringValue("two"))) .build(); AttributeValue expectedDocument2 = AttributeValue.builder() .m(singletonMap("attribute2", stringValue("three"))) .build(); Map<String, AttributeValue> expectedAttributeValueMap = new HashMap<>(); expectedAttributeValueMap.put("key1", expectedDocument1); expectedAttributeValueMap.put("key2", expectedDocument2); AttributeValue expectedMap = AttributeValue.builder().m(expectedAttributeValueMap).build(); Map<String, AttributeValue> itemMap = documentImmutableTableSchema.itemToMap(documentImmutable, true); assertThat(itemMap.size(), is(3)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("attribute1", stringValue("one"))); assertThat(itemMap, hasEntry("abstractBeanMap", expectedMap)); } @Test public void documentImmutable_correctlyMapsImmutableAttributes() { ImmutableTableSchema<DocumentImmutable> documentImmutableTableSchema = ImmutableTableSchema.create(DocumentImmutable.class); AbstractImmutable abstractImmutable = AbstractImmutable.builder().attribute2("two").build(); DocumentImmutable documentImmutable = DocumentImmutable.builder().id("id-value") .attribute1("one") .abstractImmutable(abstractImmutable) .build(); AttributeValue expectedDocument = AttributeValue.builder() .m(singletonMap("attribute2", stringValue("two"))) .build(); Map<String, AttributeValue> itemMap = documentImmutableTableSchema.itemToMap(documentImmutable, true); assertThat(itemMap.size(), is(3)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("attribute1", stringValue("one"))); assertThat(itemMap, hasEntry("abstractImmutable", expectedDocument)); } @Test public void documentImmutable_list_correctlyMapsImmutableAttributes() { ImmutableTableSchema<DocumentImmutable> documentImmutableTableSchema = ImmutableTableSchema.create(DocumentImmutable.class); AbstractImmutable abstractImmutable1 = AbstractImmutable.builder().attribute2("two").build(); AbstractImmutable abstractImmutable2 = AbstractImmutable.builder().attribute2("three").build(); DocumentImmutable documentImmutable = DocumentImmutable.builder() .id("id-value") .attribute1("one") .abstractImmutableList(Arrays.asList(abstractImmutable1, abstractImmutable2)) .build(); AttributeValue expectedDocument1 = AttributeValue.builder() .m(singletonMap("attribute2", stringValue("two"))) .build(); AttributeValue expectedDocument2 = AttributeValue.builder() .m(singletonMap("attribute2", stringValue("three"))) .build(); AttributeValue expectedList = AttributeValue.builder().l(expectedDocument1, expectedDocument2).build(); Map<String, AttributeValue> itemMap = documentImmutableTableSchema.itemToMap(documentImmutable, true); assertThat(itemMap.size(), is(3)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("attribute1", stringValue("one"))); assertThat(itemMap, hasEntry("abstractImmutableList", expectedList)); } @Test public void documentImmutable_map_correctlyMapsImmutableAttributes() { ImmutableTableSchema<DocumentImmutable> documentImmutableTableSchema = ImmutableTableSchema.create(DocumentImmutable.class); AbstractImmutable abstractImmutable1 = AbstractImmutable.builder().attribute2("two").build(); AbstractImmutable abstractImmutable2 = AbstractImmutable.builder().attribute2("three").build(); Map<String, AbstractImmutable> abstractImmutableMap = new HashMap<>(); abstractImmutableMap.put("key1", abstractImmutable1); abstractImmutableMap.put("key2", abstractImmutable2); DocumentImmutable documentImmutable = DocumentImmutable.builder() .id("id-value") .attribute1("one") .abstractImmutableMap(abstractImmutableMap) .build(); AttributeValue expectedDocument1 = AttributeValue.builder() .m(singletonMap("attribute2", stringValue("two"))) .build(); AttributeValue expectedDocument2 = AttributeValue.builder() .m(singletonMap("attribute2", stringValue("three"))) .build(); Map<String, AttributeValue> expectedAttributeValueMap = new HashMap<>(); expectedAttributeValueMap.put("key1", expectedDocument1); expectedAttributeValueMap.put("key2", expectedDocument2); AttributeValue expectedMap = AttributeValue.builder().m(expectedAttributeValueMap).build(); Map<String, AttributeValue> itemMap = documentImmutableTableSchema.itemToMap(documentImmutable, true); assertThat(itemMap.size(), is(3)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("attribute1", stringValue("one"))); assertThat(itemMap, hasEntry("abstractImmutableMap", expectedMap)); } @Test public void dynamoDbFlatten_correctlyFlattensBeanAttributes() { ImmutableTableSchema<FlattenedBeanImmutable> tableSchema = ImmutableTableSchema.create(FlattenedBeanImmutable.class); AbstractBean abstractBean = new AbstractBean(); abstractBean.setAttribute2("two"); FlattenedBeanImmutable flattenedBeanImmutable = new FlattenedBeanImmutable.Builder().setId("id-value") .setAttribute1("one") .setAbstractBean(abstractBean) .build(); Map<String, AttributeValue> itemMap = tableSchema.itemToMap(flattenedBeanImmutable, false); assertThat(itemMap.size(), is(3)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("attribute1", stringValue("one"))); assertThat(itemMap, hasEntry("attribute2", stringValue("two"))); } @Test public void dynamoDbFlatten_correctlyFlattensImmutableAttributes() { ImmutableTableSchema<FlattenedImmutableImmutable> tableSchema = ImmutableTableSchema.create(FlattenedImmutableImmutable.class); AbstractImmutable abstractImmutable = AbstractImmutable.builder().attribute2("two").build(); FlattenedImmutableImmutable FlattenedImmutableImmutable = new FlattenedImmutableImmutable.Builder().setId("id-value") .setAttribute1("one") .setAbstractImmutable(abstractImmutable) .build(); Map<String, AttributeValue> itemMap = tableSchema.itemToMap(FlattenedImmutableImmutable, false); assertThat(itemMap.size(), is(3)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("attribute1", stringValue("one"))); assertThat(itemMap, hasEntry("attribute2", stringValue("two"))); } @Test public void dynamodbPreserveEmptyObject_shouldInitializeAsEmptyClass() { ImmutableTableSchema<NestedImmutable> tableSchema = ImmutableTableSchema.create(NestedImmutable.class); AbstractImmutable abstractImmutable = AbstractImmutable.builder().build(); NestedImmutable nestedImmutable = NestedImmutable.builder().integerAttribute(1) .innerBean(abstractImmutable) .build(); Map<String, AttributeValue> itemMap = tableSchema.itemToMap(nestedImmutable, false); assertThat(itemMap.size(), is(3)); NestedImmutable result = tableSchema.mapToItem(itemMap); assertThat(result.innerBean(), is(abstractImmutable)); } @Test public void dynamoDbIgnoreNulls_shouldOmitNulls() { ImmutableTableSchema<NestedImmutableIgnoreNulls> tableSchema = ImmutableTableSchema.create(NestedImmutableIgnoreNulls.class); NestedImmutableIgnoreNulls nestedImmutable = NestedImmutableIgnoreNulls.builder() .innerBean1(AbstractImmutable.builder().build()) .innerBean2(AbstractImmutable.builder().build()) .build(); Map<String, AttributeValue> itemMap = tableSchema.itemToMap(nestedImmutable, true); assertThat(itemMap.size(), is(2)); AttributeValue expectedMapForInnerBean1 = AttributeValue.builder().m(new HashMap<>()).build(); assertThat(itemMap, hasEntry("innerBean1", expectedMapForInnerBean1)); assertThat(itemMap.get("innerBean2").m(), hasEntry("attribute2", nullAttributeValue())); } @Test public void toBuilderImmutable_ignoresToBuilderMethod() { ImmutableTableSchema<ToBuilderImmutable> toBuilderImmutableTableSchema = ImmutableTableSchema.create(ToBuilderImmutable.class); ToBuilderImmutable toBuilderImmutable = ToBuilderImmutable.builder() .id("id-value") .attribute1("one") .build(); Map<String, AttributeValue> itemMap = toBuilderImmutableTableSchema.itemToMap(toBuilderImmutable, true); assertThat(itemMap.size(), is(2)); assertThat(itemMap, hasEntry("id", stringValue("id-value"))); assertThat(itemMap, hasEntry("attribute1", stringValue("one"))); } }
3,934
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper/testbeans/SortKeyBean.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.testbeans; 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.DynamoDbSortKey; @DynamoDbBean public class SortKeyBean { private String id; private Integer sort; @DynamoDbPartitionKey public String getId() { return this.id; } public void setId(String id) { this.id = id; } @DynamoDbSortKey public Integer getSort() { return sort; } public void setSort(Integer sort) { this.sort = sort; } }
3,935
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper/testbeans/EnumBean.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.testbeans; import java.util.List; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey; @DynamoDbBean public class EnumBean { private String id; private TestEnum testEnum; private List<TestEnum> testEnumList; @DynamoDbPartitionKey public String getId() { return this.id; } public void setId(String id) { this.id = id; } public TestEnum getTestEnum() { return testEnum; } public void setTestEnum(TestEnum testEnum) { this.testEnum = testEnum; } public List<TestEnum> getTestEnumList() { return testEnumList; } public void setTestEnumList(List<TestEnum> testEnumList) { this.testEnumList = testEnumList; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; EnumBean enumBean = (EnumBean) o; if (id != null ? !id.equals(enumBean.id) : enumBean.id != null) return false; if (testEnum != enumBean.testEnum) return false; return testEnumList != null ? testEnumList.equals(enumBean.testEnumList) : enumBean.testEnumList == null; } @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + (testEnum != null ? testEnum.hashCode() : 0); result = 31 * result + (testEnumList != null ? testEnumList.hashCode() : 0); return result; } public enum TestEnum { ONE, TWO, THREE; } }
3,936
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper/testbeans/NestedBean.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.testbeans; 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.DynamoDbPreserveEmptyObject; @DynamoDbBean public class NestedBean { private String id; private AbstractBean innerBean; @DynamoDbPartitionKey public String getId() { return this.id; } public void setId(String id) { this.id = id; } @DynamoDbPreserveEmptyObject public AbstractBean getInnerBean() { return innerBean; } public void setInnerBean(AbstractBean innerBean) { this.innerBean = innerBean; } }
3,937
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper/testbeans/ListBean.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.testbeans; import java.util.List; import java.util.Objects; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey; @DynamoDbBean public class ListBean { private String id; private List<String> stringList; private List<List<String>> stringListList; @DynamoDbPartitionKey public String getId() { return this.id; } public void setId(String id) { this.id = id; } public List<String> getStringList() { return stringList; } public void setStringList(List<String> stringList) { this.stringList = stringList; } public List<List<String>> getStringListList() { return stringListList; } public void setStringListList(List<List<String>> stringListList) { this.stringListList = stringListList; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ListBean listBean = (ListBean) o; return Objects.equals(id, listBean.id) && Objects.equals(stringList, listBean.stringList) && Objects.equals(stringListList, listBean.stringListList); } @Override public int hashCode() { return Objects.hash(id, stringList, stringListList); } }
3,938
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper/testbeans/AttributeConverterBean.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.testbeans; import java.util.Objects; 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.enhanced.dynamodb.internal.converter.attribute.EnhancedAttributeValue; 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.services.dynamodb.model.AttributeValue; @DynamoDbBean public class AttributeConverterBean { private String id; @DynamoDbPartitionKey public String getId() { return this.id; } public void setId(String id) { this.id = id; } private AttributeItem attributeItem; @DynamoDbConvertedBy(CustomAttributeConverter.class) public AttributeItem getAttributeItem() { return attributeItem; } public void setAttributeItem(AttributeItem attributeItem) { this.attributeItem = attributeItem; } private Integer integerAttribute; public Integer getIntegerAttribute() { return integerAttribute; } public void setIntegerAttribute(Integer integerAttribute) { this.integerAttribute = integerAttribute; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AttributeConverterBean that = (AttributeConverterBean) o; return Objects.equals(id, that.id) && Objects.equals(integerAttribute, that.integerAttribute) && Objects.equals(attributeItem, that.attributeItem); } @Override public int hashCode() { return Objects.hash(id, integerAttribute, attributeItem); } public static class CustomAttributeConverter implements AttributeConverter<AttributeItem> { public CustomAttributeConverter() { } @Override public AttributeValue transformFrom(AttributeItem input) { return EnhancedAttributeValue.fromString(input.getInnerValue()).toAttributeValue(); } @Override public AttributeItem transformTo(AttributeValue input) { return new AttributeItem(input.s()); } @Override public EnhancedType<AttributeItem> type() { return EnhancedType.of(AttributeItem.class); } @Override public AttributeValueType attributeValueType() { return AttributeValueType.S; } } public static class AttributeItem { private String innerValue; public AttributeItem() { } AttributeItem(String value) { innerValue = value; } public String getInnerValue() { return innerValue; } public void setInnerValue(String innerValue) { this.innerValue = innerValue; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AttributeItem that = (AttributeItem) o; return Objects.equals(innerValue, that.innerValue); } @Override public int hashCode() { return Objects.hash(innerValue); } } }
3,939
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper/testbeans/CustomMetadataItem.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.testbeans; import java.time.Instant; import java.util.Objects; public class CustomMetadataItem { private String id; private String customMetadataObjectAttribute; private Instant customMetadataCollectionAttribute; private Long customMetadataMapAttribute; public String getId() { return this.id; } public void setId(String id) { this.id = id; } public String getCustomMetadataObjectAttribute() { return customMetadataObjectAttribute; } public void setCustomMetadataObjectAttribute(String customMetadataObjectAttribute) { this.customMetadataObjectAttribute = customMetadataObjectAttribute; } public Instant getCustomMetadataCollectionAttribute() { return customMetadataCollectionAttribute; } public void setCustomMetadataCollectionAttribute(Instant customMetadataCollectionAttribute) { this.customMetadataCollectionAttribute = customMetadataCollectionAttribute; } public Long getCustomMetadataMapAttribute() { return customMetadataMapAttribute; } public void setCustomMetadataMapAttribute(Long customMetadataMapAttribute) { this.customMetadataMapAttribute = customMetadataMapAttribute; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CustomMetadataItem that = (CustomMetadataItem) o; return Objects.equals(id, that.id) && Objects.equals(customMetadataObjectAttribute, that.customMetadataObjectAttribute) && Objects.equals(customMetadataCollectionAttribute, that.customMetadataCollectionAttribute) && Objects.equals(customMetadataMapAttribute, that.customMetadataMapAttribute); } @Override public int hashCode() { return Objects.hash(id, customMetadataObjectAttribute, customMetadataCollectionAttribute, customMetadataMapAttribute); } }
3,940
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper/testbeans/PrimitiveTypesBean.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.testbeans; import java.util.Objects; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey; @DynamoDbBean public class PrimitiveTypesBean { private String id; private boolean booleanAttribute; private int integerAttribute; private long longAttribute; private short shortAttribute; private byte byteAttribute; private double doubleAttribute; private float floatAttribute; @DynamoDbPartitionKey public String getId() { return this.id; } public void setId(String id) { this.id = id; } public boolean isBooleanAttribute() { return booleanAttribute; } public void setBooleanAttribute(boolean booleanAttribute) { this.booleanAttribute = booleanAttribute; } public int getIntegerAttribute() { return integerAttribute; } public void setIntegerAttribute(int integerAttribute) { this.integerAttribute = integerAttribute; } public long getLongAttribute() { return longAttribute; } public void setLongAttribute(long longAttribute) { this.longAttribute = longAttribute; } public short getShortAttribute() { return shortAttribute; } public void setShortAttribute(short shortAttribute) { this.shortAttribute = shortAttribute; } public byte getByteAttribute() { return byteAttribute; } public void setByteAttribute(byte byteAttribute) { this.byteAttribute = byteAttribute; } public double getDoubleAttribute() { return doubleAttribute; } public void setDoubleAttribute(double doubleAttribute) { this.doubleAttribute = doubleAttribute; } public float getFloatAttribute() { return floatAttribute; } public void setFloatAttribute(float floatAttribute) { this.floatAttribute = floatAttribute; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PrimitiveTypesBean that = (PrimitiveTypesBean) o; return booleanAttribute == that.booleanAttribute && integerAttribute == that.integerAttribute && longAttribute == that.longAttribute && shortAttribute == that.shortAttribute && byteAttribute == that.byteAttribute && Double.compare(that.doubleAttribute, doubleAttribute) == 0 && Float.compare(that.floatAttribute, floatAttribute) == 0 && Objects.equals(id, that.id); } @Override public int hashCode() { return Objects.hash(id, booleanAttribute, integerAttribute, longAttribute, shortAttribute, byteAttribute, doubleAttribute, floatAttribute); } }
3,941
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper/testbeans/ToBuilderImmutable.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.testbeans; import java.util.List; import java.util.Map; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbImmutable; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey; @DynamoDbImmutable(builder = ToBuilderImmutable.Builder.class) public class ToBuilderImmutable { private final String id; private final String attribute1; private ToBuilderImmutable(Builder b) { this.id = b.id; this.attribute1 = b.attribute1; } @DynamoDbPartitionKey public String id() { return this.id; } public String attribute1() { return attribute1; } public Builder toBuilder() { return builder().id(this.id).attribute1(this.attribute1); } public static Builder builder() { return new Builder(); } public static final class Builder { private String id; private String attribute1; public Builder id(String id) { this.id = id; return this; } public Builder attribute1(String attribute1) { this.attribute1 = attribute1; return this; } public ToBuilderImmutable build() { return new ToBuilderImmutable(this); } } }
3,942
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper/testbeans/NestedBeanIgnoreNulls.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.testbeans; import java.util.List; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbIgnoreNulls; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey; @DynamoDbBean public class NestedBeanIgnoreNulls { private String id; private AbstractBean innerBean1; private AbstractBean innerBean2; private List<AbstractBean> innerBeanList1; private List<AbstractBean> innerBeanList2; @DynamoDbPartitionKey public String getId() { return this.id; } public void setId(String id) { this.id = id; } @DynamoDbIgnoreNulls public AbstractBean getInnerBean1() { return innerBean1; } public void setInnerBean1(AbstractBean innerBean) { this.innerBean1 = innerBean; } public AbstractBean getInnerBean2() { return innerBean2; } public void setInnerBean2(AbstractBean innerBean) { this.innerBean2 = innerBean; } @DynamoDbIgnoreNulls public List<AbstractBean> getInnerBeanList1() { return innerBeanList1; } public void setInnerBeanList1(List<AbstractBean> innerBeanList1) { this.innerBeanList1 = innerBeanList1; } public List<AbstractBean> getInnerBeanList2() { return innerBeanList2; } public void setInnerBeanList2(List<AbstractBean> innerBeanList2) { this.innerBeanList2 = innerBeanList2; } }
3,943
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper/testbeans/RemappedAttributeBean.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.testbeans; 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.DynamoDbPartitionKey; @DynamoDbBean public class RemappedAttributeBean { private String id; @DynamoDbPartitionKey @DynamoDbAttribute("remappedAttribute") public String getId() { return this.id; } public void setId(String id) { this.id = id; } }
3,944
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper/testbeans/InvalidBean.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.testbeans; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey; public class InvalidBean { private String id; @DynamoDbPartitionKey public String getId() { return this.id; } public void setId(String id) { this.id = id; } }
3,945
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper/testbeans/DocumentBean.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.testbeans; import java.util.List; import java.util.Map; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey; @DynamoDbBean public class DocumentBean { private String id; private String attribute1; private AbstractBean abstractBean; private AbstractImmutable abstractImmutable; private List<AbstractBean> abstractBeanList; private List<AbstractImmutable> abstractImmutableList; private Map<String, AbstractBean> abstractBeanMap; private Map<String, AbstractImmutable> abstractImmutableMap; @DynamoDbPartitionKey public String getId() { return this.id; } public void setId(String id) { this.id = id; } public String getAttribute1() { return attribute1; } public void setAttribute1(String attribute1) { this.attribute1 = attribute1; } public AbstractBean getAbstractBean() { return abstractBean; } public void setAbstractBean(AbstractBean abstractBean) { this.abstractBean = abstractBean; } public List<AbstractBean> getAbstractBeanList() { return abstractBeanList; } public void setAbstractBeanList(List<AbstractBean> abstractBeanList) { this.abstractBeanList = abstractBeanList; } public Map<String, AbstractBean> getAbstractBeanMap() { return abstractBeanMap; } public void setAbstractBeanMap(Map<String, AbstractBean> abstractBeanMap) { this.abstractBeanMap = abstractBeanMap; } public AbstractImmutable getAbstractImmutable() { return abstractImmutable; } public void setAbstractImmutable(AbstractImmutable abstractImmutable) { this.abstractImmutable = abstractImmutable; } public List<AbstractImmutable> getAbstractImmutableList() { return abstractImmutableList; } public void setAbstractImmutableList(List<AbstractImmutable> abstractImmutableList) { this.abstractImmutableList = abstractImmutableList; } public Map<String, AbstractImmutable> getAbstractImmutableMap() { return abstractImmutableMap; } public void setAbstractImmutableMap(Map<String, AbstractImmutable> abstractImmutableMap) { this.abstractImmutableMap = abstractImmutableMap; } }
3,946
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper/testbeans/CustomMetadataBean.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.testbeans; import java.time.Instant; import java.util.Objects; import software.amazon.awssdk.enhanced.dynamodb.extensions.annotations.DynamoDbAtomicCounter; import software.amazon.awssdk.enhanced.dynamodb.extensions.annotations.DynamoDbAutoGeneratedTimestampAttribute; import software.amazon.awssdk.enhanced.dynamodb.mapper.UpdateBehavior; 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 CustomMetadataBean { private String id; private String customMetadataObjectAttribute; private Instant customMetadataCollectionAttribute; private Long customMetadataMapAttribute; @DynamoDbPartitionKey public String getId() { return this.id; } public void setId(String id) { this.id = id; } @DynamoDbUpdateBehavior(UpdateBehavior.WRITE_IF_NOT_EXISTS) public String getCustomMetadataObjectAttribute() { return customMetadataObjectAttribute; } public void setCustomMetadataObjectAttribute(String customMetadataObjectAttribute) { this.customMetadataObjectAttribute = customMetadataObjectAttribute; } @DynamoDbAutoGeneratedTimestampAttribute public Instant getCustomMetadataCollectionAttribute() { return customMetadataCollectionAttribute; } public void setCustomMetadataCollectionAttribute(Instant customMetadataCollectionAttribute) { this.customMetadataCollectionAttribute = customMetadataCollectionAttribute; } @DynamoDbAtomicCounter public Long getCustomMetadataMapAttribute() { return customMetadataMapAttribute; } public void setCustomMetadataMapAttribute(Long customMetadataMapAttribute) { this.customMetadataMapAttribute = customMetadataMapAttribute; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CustomMetadataBean that = (CustomMetadataBean) o; return Objects.equals(id, that.id) && Objects.equals(customMetadataObjectAttribute, that.customMetadataObjectAttribute) && Objects.equals(customMetadataCollectionAttribute, that.customMetadataCollectionAttribute) && Objects.equals(customMetadataMapAttribute, that.customMetadataMapAttribute); } @Override public int hashCode() { return Objects.hash(id, customMetadataObjectAttribute, customMetadataCollectionAttribute, customMetadataMapAttribute); } }
3,947
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper/testbeans/MultipleConverterProvidersBean.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.testbeans; import java.util.Map; import java.util.Objects; import software.amazon.awssdk.enhanced.dynamodb.AttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.AttributeConverterProvider; import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType; import software.amazon.awssdk.enhanced.dynamodb.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.EnhancedAttributeValue; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.string.IntegerStringConverter; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.utils.ImmutableMap; @DynamoDbBean(converterProviders = { MultipleConverterProvidersBean.FirstAttributeConverterProvider.class, MultipleConverterProvidersBean.SecondAttributeConverterProvider.class}) public class MultipleConverterProvidersBean { private String id; private Integer integerAttribute; @DynamoDbPartitionKey public String getId() { return this.id; } public void setId(String id) { this.id = id; } public Integer getIntegerAttribute() { return integerAttribute; } public void setIntegerAttribute(Integer integerAttribute) { this.integerAttribute = integerAttribute; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MultipleConverterProvidersBean that = (MultipleConverterProvidersBean) o; return Objects.equals(id, that.id) && Objects.equals(integerAttribute, that.integerAttribute); } @Override public int hashCode() { return Objects.hash(id, integerAttribute); } public static class FirstAttributeConverterProvider implements AttributeConverterProvider { @SuppressWarnings("unchecked") @Override public <T> AttributeConverter<T> converterFor(EnhancedType<T> enhancedType) { return null; } } public static class SecondAttributeConverterProvider implements AttributeConverterProvider { private final Map<EnhancedType<?>, AttributeConverter<?>> converterCache = ImmutableMap.of( EnhancedType.of(String.class), new CustomStringAttributeConverter(), EnhancedType.of(Integer.class), new CustomIntegerAttributeConverter() ); @SuppressWarnings("unchecked") @Override public <T> AttributeConverter<T> converterFor(EnhancedType<T> enhancedType) { return (AttributeConverter<T>) converterCache.get(enhancedType); } } private static class CustomStringAttributeConverter implements AttributeConverter<String> { final static String DEFAULT_SUFFIX = "-custom"; @Override public AttributeValue transformFrom(String input) { return EnhancedAttributeValue.fromString(input + DEFAULT_SUFFIX).toAttributeValue(); } @Override public String transformTo(AttributeValue input) { return input.s(); } @Override public EnhancedType<String> type() { return EnhancedType.of(String.class); } @Override public AttributeValueType attributeValueType() { return AttributeValueType.S; } } private static class CustomIntegerAttributeConverter implements AttributeConverter<Integer> { final static Integer DEFAULT_INCREMENT = 10; @Override public AttributeValue transformFrom(Integer input) { return EnhancedAttributeValue.fromNumber(IntegerStringConverter.create().toString(input + DEFAULT_INCREMENT)) .toAttributeValue(); } @Override public Integer transformTo(AttributeValue input) { return Integer.valueOf(input.n()); } @Override public EnhancedType<Integer> type() { return EnhancedType.of(Integer.class); } @Override public AttributeValueType attributeValueType() { return AttributeValueType.N; } } }
3,948
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper/testbeans/SimpleBean.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.testbeans; import java.util.Objects; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey; @DynamoDbBean public class SimpleBean { private String id; private Integer integerAttribute; @DynamoDbPartitionKey public String getId() { return this.id; } public void setId(String id) { this.id = id; } public Integer getIntegerAttribute() { return integerAttribute; } public void setIntegerAttribute(Integer integerAttribute) { this.integerAttribute = integerAttribute; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SimpleBean that = (SimpleBean) o; return Objects.equals(id, that.id) && Objects.equals(integerAttribute, that.integerAttribute); } @Override public int hashCode() { return Objects.hash(id, integerAttribute); } }
3,949
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper/testbeans/EmptyConverterProvidersValidBean.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.testbeans; import java.util.Objects; 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.enhanced.dynamodb.internal.converter.attribute.EnhancedAttributeValue; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.string.IntegerStringConverter; 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.services.dynamodb.model.AttributeValue; @DynamoDbBean(converterProviders = {}) public class EmptyConverterProvidersValidBean { private String id; private Integer integerAttribute; @DynamoDbPartitionKey @DynamoDbConvertedBy(CustomStringAttributeConverter.class) public String getId() { return this.id; } public void setId(String id) { this.id = id; } @DynamoDbConvertedBy(CustomIntegerAttributeConverter.class) public Integer getIntegerAttribute() { return integerAttribute; } public void setIntegerAttribute(Integer integerAttribute) { this.integerAttribute = integerAttribute; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; EmptyConverterProvidersValidBean that = (EmptyConverterProvidersValidBean) o; return Objects.equals(id, that.id) && Objects.equals(integerAttribute, that.integerAttribute); } @Override public int hashCode() { return Objects.hash(id, integerAttribute); } public static class CustomStringAttributeConverter implements AttributeConverter<String> { final static String DEFAULT_SUFFIX = "-custom"; public CustomStringAttributeConverter() { } @Override public AttributeValue transformFrom(String input) { return EnhancedAttributeValue.fromString(input + DEFAULT_SUFFIX).toAttributeValue(); } @Override public String transformTo(AttributeValue input) { return input.s(); } @Override public EnhancedType<String> type() { return EnhancedType.of(String.class); } @Override public AttributeValueType attributeValueType() { return AttributeValueType.S; } } public static class CustomIntegerAttributeConverter implements AttributeConverter<Integer> { final static Integer DEFAULT_INCREMENT = 10; public CustomIntegerAttributeConverter() { } @Override public AttributeValue transformFrom(Integer input) { return EnhancedAttributeValue.fromNumber(IntegerStringConverter.create().toString(input + DEFAULT_INCREMENT)) .toAttributeValue(); } @Override public Integer transformTo(AttributeValue input) { return Integer.valueOf(input.n()); } @Override public EnhancedType<Integer> type() { return EnhancedType.of(Integer.class); } @Override public AttributeValueType attributeValueType() { return AttributeValueType.N; } } }
3,950
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper/testbeans/ParameterizedDocumentBean.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.testbeans; import java.util.List; import java.util.Map; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey; @DynamoDbBean public class ParameterizedDocumentBean { private String id; private String attribute1; private ParameterizedAbstractBean<String> abstractBean; private List<ParameterizedAbstractBean<String>> abstractBeanList; private Map<String, ParameterizedAbstractBean<String>> abstractBeanMap; @DynamoDbPartitionKey public String getId() { return this.id; } public void setId(String id) { this.id = id; } public String getAttribute1() { return attribute1; } public void setAttribute1(String attribute1) { this.attribute1 = attribute1; } public ParameterizedAbstractBean<String> getAbstractBean() { return abstractBean; } public void setAbstractBean(ParameterizedAbstractBean<String> abstractBean) { this.abstractBean = abstractBean; } public List<ParameterizedAbstractBean<String>> getAbstractBeanList() { return abstractBeanList; } public void setAbstractBeanList(List<ParameterizedAbstractBean<String>> abstractBeanList) { this.abstractBeanList = abstractBeanList; } public Map<String, ParameterizedAbstractBean<String>> getAbstractBeanMap() { return abstractBeanMap; } public void setAbstractBeanMap(Map<String, ParameterizedAbstractBean<String>> abstractBeanMap) { this.abstractBeanMap = abstractBeanMap; } }
3,951
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper/testbeans/FlattenedImmutableImmutable.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.testbeans; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbFlatten; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbImmutable; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey; @DynamoDbImmutable(builder = FlattenedImmutableImmutable.Builder.class) public class FlattenedImmutableImmutable { private final String id; private final String attribute1; private final AbstractImmutable abstractImmutable; private FlattenedImmutableImmutable(Builder b) { this.id = b.id; this.attribute1 = b.attribute1; this.abstractImmutable = b.abstractImmutable; } @DynamoDbPartitionKey public String getId() { return this.id; } public String getAttribute1() { return attribute1; } @DynamoDbFlatten public AbstractImmutable getAbstractImmutable() { return abstractImmutable; } public static final class Builder { private String id; private String attribute1; private AbstractImmutable abstractImmutable; public Builder setId(String id) { this.id = id; return this; } public Builder setAttribute1(String attribute1) { this.attribute1 = attribute1; return this; } public Builder setAbstractImmutable(AbstractImmutable abstractImmutable) { this.abstractImmutable = abstractImmutable; return this; } public FlattenedImmutableImmutable build() { return new FlattenedImmutableImmutable(this); } } }
3,952
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper/testbeans/CustomMetadataImmutableBean.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.testbeans; import java.time.Instant; import java.util.Objects; import software.amazon.awssdk.enhanced.dynamodb.extensions.annotations.DynamoDbAtomicCounter; import software.amazon.awssdk.enhanced.dynamodb.extensions.annotations.DynamoDbAutoGeneratedTimestampAttribute; import software.amazon.awssdk.enhanced.dynamodb.mapper.UpdateBehavior; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbImmutable; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbUpdateBehavior; @DynamoDbImmutable(builder = CustomMetadataImmutableBean.Builder.class) public class CustomMetadataImmutableBean { private final String id; private final String customMetadataObjectAttribute; private final Instant customMetadataCollectionAttribute; private final Long customMetadataMapAttribute; private CustomMetadataImmutableBean(CustomMetadataImmutableBean.Builder b) { this.id = b.id; this.customMetadataObjectAttribute = b.customMetadataObjectAttribute; this.customMetadataCollectionAttribute = b.customMetadataCollectionAttribute; this.customMetadataMapAttribute = b.customMetadataMapAttribute; } @DynamoDbPartitionKey public String id() { return id; } @DynamoDbUpdateBehavior(UpdateBehavior.WRITE_IF_NOT_EXISTS) public String customMetadataObjectAttribute() { return customMetadataObjectAttribute; } @DynamoDbAutoGeneratedTimestampAttribute public Instant customMetadataCollectionAttribute() { return customMetadataCollectionAttribute; } @DynamoDbAtomicCounter public Long customMetadataMapAttribute() { return customMetadataMapAttribute; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CustomMetadataImmutableBean that = (CustomMetadataImmutableBean) o; return Objects.equals(id, that.id) && Objects.equals(customMetadataObjectAttribute, that.customMetadataObjectAttribute) && Objects.equals(customMetadataCollectionAttribute, that.customMetadataCollectionAttribute) && Objects.equals(customMetadataMapAttribute, that.customMetadataMapAttribute); } @Override public int hashCode() { return Objects.hash(id, customMetadataObjectAttribute, customMetadataCollectionAttribute, customMetadataMapAttribute); } public static Builder builder() { return new Builder(); } public static final class Builder { private String id; private String customMetadataObjectAttribute; private Instant customMetadataCollectionAttribute; private Long customMetadataMapAttribute; public Builder id(String id) { this.id = id; return this; } public Builder customMetadataObjectAttribute(String customMetadataObjectAttribute) { this.customMetadataObjectAttribute = customMetadataObjectAttribute; return this; } public Builder customMetadataCollectionAttribute(Instant customMetadataCollectionAttribute) { this.customMetadataCollectionAttribute = customMetadataCollectionAttribute; return this; } public Builder customMetadataMapAttribute(Long customMetadataMapAttribute) { this.customMetadataMapAttribute = customMetadataMapAttribute; return this; } public CustomMetadataImmutableBean build() { return new CustomMetadataImmutableBean(this); } } }
3,953
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper/testbeans/SingleConverterProvidersBean.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.testbeans; import java.util.Map; import java.util.Objects; import software.amazon.awssdk.enhanced.dynamodb.AttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.AttributeConverterProvider; import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType; import software.amazon.awssdk.enhanced.dynamodb.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.EnhancedAttributeValue; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.string.IntegerStringConverter; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.utils.ImmutableMap; @DynamoDbBean(converterProviders = SingleConverterProvidersBean.CustomAttributeConverterProvider.class) public class SingleConverterProvidersBean { private String id; private Integer integerAttribute; @DynamoDbPartitionKey public String getId() { return this.id; } public void setId(String id) { this.id = id; } public Integer getIntegerAttribute() { return integerAttribute; } public void setIntegerAttribute(Integer integerAttribute) { this.integerAttribute = integerAttribute; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SingleConverterProvidersBean that = (SingleConverterProvidersBean) o; return Objects.equals(id, that.id) && Objects.equals(integerAttribute, that.integerAttribute); } @Override public int hashCode() { return Objects.hash(id, integerAttribute); } public static class CustomAttributeConverterProvider implements AttributeConverterProvider { private final Map<EnhancedType<?>, AttributeConverter<?>> converterCache = ImmutableMap.of( EnhancedType.of(String.class), new CustomStringAttributeConverter(), EnhancedType.of(Integer.class), new CustomIntegerAttributeConverter() ); @SuppressWarnings("unchecked") @Override public <T> AttributeConverter<T> converterFor(EnhancedType<T> enhancedType) { return (AttributeConverter<T>) converterCache.get(enhancedType); } } private static class CustomStringAttributeConverter implements AttributeConverter<String> { final static String DEFAULT_SUFFIX = "-custom"; @Override public AttributeValue transformFrom(String input) { return EnhancedAttributeValue.fromString(input + DEFAULT_SUFFIX).toAttributeValue(); } @Override public String transformTo(AttributeValue input) { return input.s(); } @Override public EnhancedType<String> type() { return EnhancedType.of(String.class); } @Override public AttributeValueType attributeValueType() { return AttributeValueType.S; } } private static class CustomIntegerAttributeConverter implements AttributeConverter<Integer> { final static Integer DEFAULT_INCREMENT = 10; @Override public AttributeValue transformFrom(Integer input) { return EnhancedAttributeValue.fromNumber(IntegerStringConverter.create().toString(input + DEFAULT_INCREMENT)) .toAttributeValue(); } @Override public Integer transformTo(AttributeValue input) { return Integer.valueOf(input.n()); } @Override public EnhancedType<Integer> type() { return EnhancedType.of(Integer.class); } @Override public AttributeValueType attributeValueType() { return AttributeValueType.N; } } }
3,954
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper/testbeans/SimpleImmutable.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.testbeans; import java.util.Objects; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbImmutable; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey; @DynamoDbImmutable(builder = SimpleImmutable.Builder.class) public class SimpleImmutable { private final String id; private final Integer integerAttribute; private SimpleImmutable(Builder b) { this.id = b.id; this.integerAttribute = b.integerAttribute; } @DynamoDbPartitionKey public String id() { return this.id; } public Integer integerAttribute() { return integerAttribute; } public static Builder builder() { return new Builder(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SimpleImmutable that = (SimpleImmutable) o; return Objects.equals(id, that.id) && Objects.equals(integerAttribute, that.integerAttribute); } @Override public int hashCode() { return Objects.hash(id, integerAttribute); } public static final class Builder { private String id; private Integer integerAttribute; private Builder() { } public Builder id(String id) { this.id = id; return this; } public Builder integerAttribute(Integer integerAttribute) { this.integerAttribute = integerAttribute; return this; } public SimpleImmutable build() { return new SimpleImmutable(this); } } }
3,955
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper/testbeans/NestedImmutableIgnoreNulls.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.testbeans; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbIgnoreNulls; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbImmutable; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey; @DynamoDbImmutable(builder = NestedImmutableIgnoreNulls.Builder.class) public class NestedImmutableIgnoreNulls { private final String id; private final AbstractImmutable innerBean1; private final AbstractImmutable innerBean2; private NestedImmutableIgnoreNulls(Builder b) { this.id = b.id; this.innerBean1 = b.innerBean1; this.innerBean2 = b.innerBean2; } @DynamoDbPartitionKey public String id() { return this.id; } @DynamoDbIgnoreNulls public AbstractImmutable innerBean1() { return innerBean1; } public AbstractImmutable innerBean2() { return innerBean2; } public static Builder builder() { return new Builder(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } NestedImmutableIgnoreNulls that = (NestedImmutableIgnoreNulls) o; if (id != null ? !id.equals(that.id) : that.id != null) { return false; } if (innerBean2 != null ? !innerBean2.equals(that.innerBean2) : that.innerBean2 != null) { return false; } return innerBean1 != null ? innerBean1.equals(that.innerBean1) : that.innerBean1 == null; } @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + (innerBean2 != null ? innerBean2.hashCode() : 0); result = 31 * result + (innerBean1 != null ? innerBean1.hashCode() : 0); return result; } public static final class Builder { private AbstractImmutable innerBean1; private String id; private AbstractImmutable innerBean2; private Builder() { } public Builder id(String id) { this.id = id; return this; } public Builder innerBean1(AbstractImmutable innerBean1) { this.innerBean1 = innerBean1; return this; } public Builder innerBean2(AbstractImmutable innerBean2) { this.innerBean2 = innerBean2; return this; } public NestedImmutableIgnoreNulls build() { return new NestedImmutableIgnoreNulls(this); } } }
3,956
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper/testbeans/SetBean.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.testbeans; import java.util.Objects; import java.util.Set; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey; @DynamoDbBean public class SetBean { private String id; private Set<String> stringSet; private Set<Integer> integerSet; private Set<Long> longSet; private Set<Short> shortSet; private Set<Byte> byteSet; private Set<Double> doubleSet; private Set<Float> floatSet; private Set<SdkBytes> binarySet; @DynamoDbPartitionKey public String getId() { return this.id; } public void setId(String id) { this.id = id; } public Set<String> getStringSet() { return stringSet; } public void setStringSet(Set<String> stringSet) { this.stringSet = stringSet; } public Set<Integer> getIntegerSet() { return integerSet; } public void setIntegerSet(Set<Integer> integerSet) { this.integerSet = integerSet; } public Set<Long> getLongSet() { return longSet; } public void setLongSet(Set<Long> longSet) { this.longSet = longSet; } public Set<Short> getShortSet() { return shortSet; } public void setShortSet(Set<Short> shortSet) { this.shortSet = shortSet; } public Set<Byte> getByteSet() { return byteSet; } public void setByteSet(Set<Byte> byteSet) { this.byteSet = byteSet; } public Set<Double> getDoubleSet() { return doubleSet; } public void setDoubleSet(Set<Double> doubleSet) { this.doubleSet = doubleSet; } public Set<Float> getFloatSet() { return floatSet; } public void setFloatSet(Set<Float> floatSet) { this.floatSet = floatSet; } public Set<SdkBytes> getBinarySet() { return binarySet; } public void setBinarySet(Set<SdkBytes> binarySet) { this.binarySet = binarySet; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SetBean setBean = (SetBean) o; return Objects.equals(id, setBean.id) && Objects.equals(stringSet, setBean.stringSet) && Objects.equals(integerSet, setBean.integerSet) && Objects.equals(longSet, setBean.longSet) && Objects.equals(shortSet, setBean.shortSet) && Objects.equals(byteSet, setBean.byteSet) && Objects.equals(doubleSet, setBean.doubleSet) && Objects.equals(floatSet, setBean.floatSet) && Objects.equals(binarySet, setBean.binarySet); } @Override public int hashCode() { return Objects.hash(id, stringSet, integerSet, longSet, shortSet, byteSet, doubleSet, floatSet, binarySet); } }
3,957
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper/testbeans/AbstractBean.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.testbeans; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean; @DynamoDbBean public class AbstractBean { private String attribute2; public String getAttribute2() { return attribute2; } public void setAttribute2(String attribute2) { this.attribute2 = attribute2; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } AbstractBean that = (AbstractBean) o; return attribute2 != null ? attribute2.equals(that.attribute2) : that.attribute2 == null; } @Override public int hashCode() { return attribute2 != null ? attribute2.hashCode() : 0; } }
3,958
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper/testbeans/CommonTypesBean.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.testbeans; import java.util.Objects; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey; @DynamoDbBean public class CommonTypesBean { private String id; private Boolean booleanAttribute; private Integer integerAttribute; private Long longAttribute; private Short shortAttribute; private Byte byteAttribute; private Double doubleAttribute; private Float floatAttribute; private SdkBytes binaryAttribute; @DynamoDbPartitionKey public String getId() { return this.id; } public void setId(String id) { this.id = id; } public Boolean getBooleanAttribute() { return booleanAttribute; } public void setBooleanAttribute(Boolean booleanAttribute) { this.booleanAttribute = booleanAttribute; } public Integer getIntegerAttribute() { return integerAttribute; } public void setIntegerAttribute(Integer integerAttribute) { this.integerAttribute = integerAttribute; } public Long getLongAttribute() { return longAttribute; } public void setLongAttribute(Long longAttribute) { this.longAttribute = longAttribute; } public Short getShortAttribute() { return shortAttribute; } public void setShortAttribute(Short shortAttribute) { this.shortAttribute = shortAttribute; } public Byte getByteAttribute() { return byteAttribute; } public void setByteAttribute(Byte byteAttribute) { this.byteAttribute = byteAttribute; } public Double getDoubleAttribute() { return doubleAttribute; } public void setDoubleAttribute(Double doubleAttribute) { this.doubleAttribute = doubleAttribute; } public Float getFloatAttribute() { return floatAttribute; } public void setFloatAttribute(Float floatAttribute) { this.floatAttribute = floatAttribute; } public SdkBytes getBinaryAttribute() { return binaryAttribute; } public void setBinaryAttribute(SdkBytes binaryAttribute) { this.binaryAttribute = binaryAttribute; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CommonTypesBean that = (CommonTypesBean) o; return Objects.equals(id, that.id) && Objects.equals(booleanAttribute, that.booleanAttribute) && Objects.equals(integerAttribute, that.integerAttribute) && Objects.equals(longAttribute, that.longAttribute) && Objects.equals(shortAttribute, that.shortAttribute) && Objects.equals(byteAttribute, that.byteAttribute) && Objects.equals(doubleAttribute, that.doubleAttribute) && Objects.equals(floatAttribute, that.floatAttribute) && Objects.equals(binaryAttribute, that.binaryAttribute); } @Override public int hashCode() { return Objects.hash(id, booleanAttribute, integerAttribute, longAttribute, shortAttribute, byteAttribute, doubleAttribute, floatAttribute, binaryAttribute); } }
3,959
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper/testbeans/DocumentImmutable.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.testbeans; import java.util.List; import java.util.Map; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbImmutable; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey; @DynamoDbImmutable(builder = DocumentImmutable.Builder.class) public class DocumentImmutable { private final String id; private final String attribute1; private final AbstractBean abstractBean; private final AbstractImmutable abstractImmutable; private final List<AbstractBean> abstractBeanList; private final List<AbstractImmutable> abstractImmutableList; private final Map<String, AbstractBean> abstractBeanMap; private final Map<String, AbstractImmutable> abstractImmutableMap; private DocumentImmutable(Builder b) { this.id = b.id; this.attribute1 = b.attribute1; this.abstractBean = b.abstractBean; this.abstractImmutable = b.abstractImmutable; this.abstractBeanList = b.abstractBeanList; this.abstractImmutableList = b.abstractImmutableList; this.abstractBeanMap = b.abstractBeanMap; this.abstractImmutableMap = b.abstractImmutableMap; } @DynamoDbPartitionKey public String id() { return this.id; } public String attribute1() { return attribute1; } public AbstractBean abstractBean() { return abstractBean; } public List<AbstractBean> abstractBeanList() { return abstractBeanList; } public Map<String, AbstractBean> abstractBeanMap() { return abstractBeanMap; } public AbstractImmutable abstractImmutable() { return abstractImmutable; } public List<AbstractImmutable> abstractImmutableList() { return abstractImmutableList; } public Map<String, AbstractImmutable> abstractImmutableMap() { return abstractImmutableMap; } public static Builder builder() { return new Builder(); } public static final class Builder { private String id; private String attribute1; private AbstractBean abstractBean; private AbstractImmutable abstractImmutable; private List<AbstractBean> abstractBeanList; private List<AbstractImmutable> abstractImmutableList; private Map<String, AbstractBean> abstractBeanMap; private Map<String, AbstractImmutable> abstractImmutableMap; public Builder id(String id) { this.id = id; return this; } public Builder attribute1(String attribute1) { this.attribute1 = attribute1; return this; } public Builder abstractBean(AbstractBean abstractBean) { this.abstractBean = abstractBean; return this; } public Builder abstractImmutable(AbstractImmutable abstractImmutable) { this.abstractImmutable = abstractImmutable; return this; } public Builder abstractBeanList(List<AbstractBean> abstractBeanList) { this.abstractBeanList = abstractBeanList; return this; } public Builder abstractImmutableList(List<AbstractImmutable> abstractImmutableList) { this.abstractImmutableList = abstractImmutableList; return this; } public Builder abstractBeanMap(Map<String, AbstractBean> abstractBeanMap) { this.abstractBeanMap = abstractBeanMap; return this; } public Builder abstractImmutableMap(Map<String, AbstractImmutable> abstractImmutableMap) { this.abstractImmutableMap = abstractImmutableMap; return this; } public DocumentImmutable build() { return new DocumentImmutable(this); } } }
3,960
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper/testbeans/FlattenedBeanBean.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.testbeans; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbFlatten; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey; @DynamoDbBean public class FlattenedBeanBean { private String id; private String attribute1; private AbstractBean abstractBean; @DynamoDbPartitionKey public String getId() { return this.id; } public void setId(String id) { this.id = id; } public String getAttribute1() { return attribute1; } public void setAttribute1(String attribute1) { this.attribute1 = attribute1; } @DynamoDbFlatten public AbstractBean getAbstractBean() { return abstractBean; } public void setAbstractBean(AbstractBean abstractBean) { this.abstractBean = abstractBean; } }
3,961
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper/testbeans/SecondaryIndexMatchingTableKeyBean.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.testbeans; 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.DynamoDbSecondaryPartitionKey; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbSecondarySortKey; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbSortKey; /** * A bean with a global secondary index that uses the same partition key as the table. */ @DynamoDbBean public class SecondaryIndexMatchingTableKeyBean { private String id; private Integer sort; private String attribute; @DynamoDbPartitionKey @DynamoDbSecondaryPartitionKey(indexNames = "gsi") public String getId() { return this.id; } public void setId(String id) { this.id = id; } @DynamoDbSortKey public Integer getSort() { return sort; } public void setSort(Integer sort) { this.sort = sort; } @DynamoDbSecondarySortKey(indexNames = "gsi") public String getAttribute() { return attribute; } public void setAttribute(String attribute) { this.attribute = attribute; } }
3,962
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper/testbeans/SecondaryIndexBean.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.testbeans; 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.DynamoDbSecondaryPartitionKey; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbSecondarySortKey; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbSortKey; /** * A bean with a local secondary index and a global secondary index. */ @DynamoDbBean public class SecondaryIndexBean { private String id; private Integer sort; private String attribute; @DynamoDbPartitionKey public String getId() { return this.id; } public void setId(String id) { this.id = id; } @DynamoDbSortKey @DynamoDbSecondaryPartitionKey(indexNames = "gsi") public Integer getSort() { return sort; } public void setSort(Integer sort) { this.sort = sort; } @DynamoDbSecondarySortKey(indexNames = {"lsi", "gsi"}) public String getAttribute() { return attribute; } public void setAttribute(String attribute) { this.attribute = attribute; } }
3,963
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper/testbeans/AbstractImmutable.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.testbeans; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbImmutable; @DynamoDbImmutable(builder = AbstractImmutable.Builder.class) public class AbstractImmutable { private final String attribute2; private AbstractImmutable(Builder b) { this.attribute2 = b.attribute2; } public String attribute2() { return attribute2; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } AbstractImmutable that = (AbstractImmutable) o; return attribute2 != null ? attribute2.equals(that.attribute2) : that.attribute2 == null; } @Override public int hashCode() { return attribute2 != null ? attribute2.hashCode() : 0; } public static Builder builder() { return new Builder(); } public static final class Builder { private String attribute2; public Builder attribute2(String attribute2) { this.attribute2 = attribute2; return this; } public AbstractImmutable build() { return new AbstractImmutable(this); } } }
3,964
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper/testbeans/FlattenedBeanImmutable.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.testbeans; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbFlatten; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbImmutable; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey; @DynamoDbImmutable(builder = FlattenedBeanImmutable.Builder.class) public class FlattenedBeanImmutable { private final String id; private final String attribute1; private final AbstractBean abstractBean; private FlattenedBeanImmutable(Builder b) { this.id = b.id; this.attribute1 = b.attribute1; this.abstractBean = b.abstractBean; } @DynamoDbPartitionKey public String getId() { return this.id; } public String getAttribute1() { return attribute1; } @DynamoDbFlatten public AbstractBean getAbstractBean() { return abstractBean; } public static final class Builder { private String id; private String attribute1; private AbstractBean abstractBean; public Builder setId(String id) { this.id = id; return this; } public Builder setAttribute1(String attribute1) { this.attribute1 = attribute1; return this; } public Builder setAbstractBean(AbstractBean abstractBean) { this.abstractBean = abstractBean; return this; } public FlattenedBeanImmutable build() { return new FlattenedBeanImmutable(this); } } }
3,965
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper/testbeans/ParameterizedAbstractBean.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.testbeans; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean; @DynamoDbBean public class ParameterizedAbstractBean<T> { private String attribute2; public String getAttribute2() { return attribute2; } public void setAttribute2(String attribute2) { this.attribute2 = attribute2; } }
3,966
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper/testbeans/AttributeConverterNoConstructorBean.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.testbeans; 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.enhanced.dynamodb.mapper.annotations.DynamoDbBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbConvertedBy; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; @DynamoDbBean public class AttributeConverterNoConstructorBean extends AbstractBean { private String id; @DynamoDbConvertedBy(AttributeConverterNoConstructorBean.CustomAttributeConverter.class) public String getId() { return this.id; } public void setId(String id) { this.id = id; } public static class CustomAttributeConverter implements AttributeConverter { private CustomAttributeConverter() { } @Override public AttributeValue transformFrom(Object input) { return null; } @Override public Object transformTo(AttributeValue input) { return null; } @Override public EnhancedType type() { return null; } @Override public AttributeValueType attributeValueType() { return null; } } }
3,967
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper/testbeans/EntityEnvelopeBean.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.testbeans; public class EntityEnvelopeBean<T> { private T entity; public T getEntity() { return this.entity; } public void setEntity(T entity) { this.entity = entity; } }
3,968
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper/testbeans/SetterAnnotatedBean.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.testbeans; import java.beans.Transient; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbIgnore; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey; @DynamoDbBean public class SetterAnnotatedBean { private String id; private Integer integerAttribute; private Integer integer2Attribute; public String getId() { return this.id; } @DynamoDbPartitionKey public void setId(String id) { this.id = id; } public Integer getIntegerAttribute() { return integerAttribute; } @DynamoDbIgnore public void setIntegerAttribute(Integer integerAttribute) { this.integerAttribute = integerAttribute; } public Integer getInteger2Attribute() { return integer2Attribute; } @Transient public void setInteger2Attribute(Integer integer2Attribute) { this.integer2Attribute = integer2Attribute; } }
3,969
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper/testbeans/EmptyConverterProvidersInvalidBean.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.testbeans; import java.util.Objects; 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.enhanced.dynamodb.internal.converter.attribute.EnhancedAttributeValue; 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.services.dynamodb.model.AttributeValue; @DynamoDbBean(converterProviders = {}) public class EmptyConverterProvidersInvalidBean { private String id; private Integer integerAttribute; @DynamoDbPartitionKey @DynamoDbConvertedBy(CustomStringAttributeConverter.class) public String getId() { return this.id; } public void setId(String id) { this.id = id; } public Integer getIntegerAttribute() { return integerAttribute; } public void setIntegerAttribute(Integer integerAttribute) { this.integerAttribute = integerAttribute; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; EmptyConverterProvidersInvalidBean that = (EmptyConverterProvidersInvalidBean) o; return Objects.equals(id, that.id) && Objects.equals(integerAttribute, that.integerAttribute); } @Override public int hashCode() { return Objects.hash(id, integerAttribute); } public static class CustomStringAttributeConverter implements AttributeConverter<String> { final static String DEFAULT_SUFFIX = "-custom"; public CustomStringAttributeConverter() { } @Override public AttributeValue transformFrom(String input) { return EnhancedAttributeValue.fromString(input + DEFAULT_SUFFIX).toAttributeValue(); } @Override public String transformTo(AttributeValue input) { return input.s(); } @Override public EnhancedType<String> type() { return EnhancedType.of(String.class); } @Override public AttributeValueType attributeValueType() { return AttributeValueType.S; } } }
3,970
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper/testbeans/IgnoredAttributeBean.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.testbeans; import java.beans.Transient; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbIgnore; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey; @DynamoDbBean public class IgnoredAttributeBean { private String id; private Integer integerAttribute; private Integer integer2Attribute; @DynamoDbPartitionKey public String getId() { return this.id; } public void setId(String id) { this.id = id; } @DynamoDbIgnore public Integer getIntegerAttribute() { return integerAttribute; } public void setIntegerAttribute(Integer integerAttribute) { this.integerAttribute = integerAttribute; } @Transient public Integer getInteger2Attribute() { return integer2Attribute; } public void setInteger2Attribute(Integer integer2Attribute) { this.integer2Attribute = integer2Attribute; } }
3,971
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper/testbeans/ExtendedBean.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.testbeans; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey; @DynamoDbBean public class ExtendedBean extends AbstractBean { private String id; private String attribute1; @DynamoDbPartitionKey public String getId() { return this.id; } public void setId(String id) { this.id = id; } public String getAttribute1() { return attribute1; } public void setAttribute1(String attribute1) { this.attribute1 = attribute1; } }
3,972
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper/testbeans/FlattenedImmutableBean.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.testbeans; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbFlatten; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey; @DynamoDbBean public class FlattenedImmutableBean { private String id; private String attribute1; private AbstractImmutable abstractImmutable; @DynamoDbPartitionKey public String getId() { return this.id; } public void setId(String id) { this.id = id; } public String getAttribute1() { return attribute1; } public void setAttribute1(String attribute1) { this.attribute1 = attribute1; } @DynamoDbFlatten public AbstractImmutable getAbstractImmutable() { return abstractImmutable; } public void setAbstractImmutable(AbstractImmutable abstractImmutable) { this.abstractImmutable = abstractImmutable; } }
3,973
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper/testbeans/NestedImmutable.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.testbeans; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbImmutable; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPreserveEmptyObject; @DynamoDbImmutable(builder = NestedImmutable.Builder.class) public class NestedImmutable { private final String id; private final Integer integerAttribute; private final AbstractImmutable innerBean; private NestedImmutable(Builder b) { this.id = b.id; this.integerAttribute = b.integerAttribute; this.innerBean = b.innerBean; } @DynamoDbPartitionKey public String id() { return this.id; } public Integer integerAttribute() { return integerAttribute; } @DynamoDbPreserveEmptyObject public AbstractImmutable innerBean() { return innerBean; } public static Builder builder() { return new Builder(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } NestedImmutable that = (NestedImmutable) o; if (id != null ? !id.equals(that.id) : that.id != null) { return false; } if (integerAttribute != null ? !integerAttribute.equals(that.integerAttribute) : that.integerAttribute != null) { return false; } return innerBean != null ? innerBean.equals(that.innerBean) : that.innerBean == null; } @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + (integerAttribute != null ? integerAttribute.hashCode() : 0); result = 31 * result + (innerBean != null ? innerBean.hashCode() : 0); return result; } public static final class Builder { private AbstractImmutable innerBean; private String id; private Integer integerAttribute; private Builder() { } public Builder id(String id) { this.id = id; return this; } public Builder integerAttribute(Integer integerAttribute) { this.integerAttribute = integerAttribute; return this; } public Builder innerBean(AbstractImmutable innerBean) { this.innerBean = innerBean; return this; } public NestedImmutable build() { return new NestedImmutable(this); } } }
3,974
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper/testbeans/MapBean.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.testbeans; import java.util.Map; import java.util.Objects; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey; @DynamoDbBean public class MapBean { private String id; private Map<String, String> stringMap; private Map<String, Map<String, String>> nestedStringMap; @DynamoDbPartitionKey public String getId() { return this.id; } public void setId(String id) { this.id = id; } public Map<String, String> getStringMap() { return stringMap; } public void setStringMap(Map<String, String> stringMap) { this.stringMap = stringMap; } public Map<String, Map<String, String>> getNestedStringMap() { return nestedStringMap; } public void setNestedStringMap(Map<String, Map<String, String>> nestedStringMap) { this.nestedStringMap = nestedStringMap; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MapBean mapBean = (MapBean) o; return Objects.equals(id, mapBean.id) && Objects.equals(stringMap, mapBean.stringMap) && Objects.equals(nestedStringMap, mapBean.nestedStringMap); } @Override public int hashCode() { return Objects.hash(id, stringMap, nestedStringMap); } }
3,975
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper/testbeans/NoConstructorConverterProvidersBean.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.testbeans; 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.mapper.annotations.DynamoDbBean; @DynamoDbBean(converterProviders = NoConstructorConverterProvidersBean.CustomAttributeConverterProvider.class) public class NoConstructorConverterProvidersBean extends AbstractBean { public static class CustomAttributeConverterProvider implements AttributeConverterProvider { private CustomAttributeConverterProvider() { } @SuppressWarnings("unchecked") @Override public <T> AttributeConverter<T> converterFor(EnhancedType<T> enhancedType) { return null; } } }
3,976
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/mapper/testimmutables/EntityEnvelopeImmutable.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.testimmutables; public class EntityEnvelopeImmutable<T> { private final T entity; public EntityEnvelopeImmutable(T entity) { this.entity = entity; } public T entity() { return this.entity; } public static class Builder<T> { private T entity; public void setEntity(T entity) { this.entity = entity; } public EntityEnvelopeImmutable<T> build() { return new EntityEnvelopeImmutable<>(this.entity); } } }
3,977
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/internal/ApplyUserAgentInterceptorTest.java
/* * Copyright 2010-2020 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.internal; import static org.assertj.core.api.Assertions.assertThat; import java.util.List; import java.util.Optional; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.RequestOverrideConfiguration; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.services.dynamodb.model.GetItemRequest; public class ApplyUserAgentInterceptorTest { private ApplyUserAgentInterceptor interceptor = new ApplyUserAgentInterceptor(); @Test public void ddbRequest_shouldModifyRequest() { GetItemRequest getItemRequest = GetItemRequest.builder().build(); SdkRequest sdkRequest = interceptor.modifyRequest(() -> getItemRequest, new ExecutionAttributes()); RequestOverrideConfiguration requestOverrideConfiguration = sdkRequest.overrideConfiguration().get(); assertThat(requestOverrideConfiguration.apiNames() .stream() .filter(a -> a.name() .equals("hll") && a.version().equals("ddb-enh")).findAny()) .isPresent(); } @Test public void otherRequest_shouldNotModifyRequest() { SdkRequest someOtherRequest = new SdkRequest() { @Override public List<SdkField<?>> sdkFields() { return null; } @Override public Optional<? extends RequestOverrideConfiguration> overrideConfiguration() { return Optional.empty(); } @Override public Builder toBuilder() { return null; } }; SdkRequest sdkRequest = interceptor.modifyRequest(() -> someOtherRequest, new ExecutionAttributes()); assertThat(sdkRequest).isEqualTo(someOtherRequest); } }
3,978
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/internal/EnhancedClientUtilsTest.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.internal; import static org.assertj.core.api.Assertions.assertThat; import java.util.HashMap; import java.util.Map; import java.util.Optional; import org.junit.jupiter.api.Test; import software.amazon.awssdk.enhanced.dynamodb.Key; import software.amazon.awssdk.enhanced.dynamodb.TableMetadata; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItem; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItemWithSort; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; public class EnhancedClientUtilsTest { private static final AttributeValue PARTITION_VALUE = AttributeValue.builder().s("id123").build(); private static final AttributeValue SORT_VALUE = AttributeValue.builder().s("sort123").build(); @Test public void createKeyFromMap_partitionOnly() { Map<String, AttributeValue> itemMap = new HashMap<>(); itemMap.put("id", PARTITION_VALUE); Key key = EnhancedClientUtils.createKeyFromMap(itemMap, FakeItem.getTableSchema(), TableMetadata.primaryIndexName()); assertThat(key.partitionKeyValue()).isEqualTo(PARTITION_VALUE); assertThat(key.sortKeyValue()).isEmpty(); } @Test public void createKeyFromMap_partitionAndSort() { Map<String, AttributeValue> itemMap = new HashMap<>(); itemMap.put("id", PARTITION_VALUE); itemMap.put("sort", SORT_VALUE); Key key = EnhancedClientUtils.createKeyFromMap(itemMap, FakeItemWithSort.getTableSchema(), TableMetadata.primaryIndexName()); assertThat(key.partitionKeyValue()).isEqualTo(PARTITION_VALUE); assertThat(key.sortKeyValue()).isEqualTo(Optional.of(SORT_VALUE)); } @Test public void cleanAttributeName_cleansSpecialCharacters() { String result = EnhancedClientUtils.cleanAttributeName("a*b.c-d:e#f+g:h/i(j)k&l<m>n?o=p!q@r%s$t|u"); assertThat(result).isEqualTo("a_b_c_d_e_f_g_h_i_j_k_l_m_n_o_p_q_r_s_t_u"); } }
3,979
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/internal/DefaultDocumentTest.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.internal; import static java.util.Collections.emptyMap; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.Map; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.enhanced.dynamodb.Document; 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.extensions.ReadModification; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItem; import software.amazon.awssdk.enhanced.dynamodb.internal.extensions.DefaultDynamoDbExtensionContext; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.DefaultOperationContext; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; @RunWith(MockitoJUnitRunner.class) public class DefaultDocumentTest { private static final String TABLE_NAME = "table-name"; @Mock private DynamoDbClient mockDynamoDbClient; @Mock private DynamoDbEnhancedClientExtension mockDynamoDbEnhancedClientExtension; private DynamoDbTable<FakeItem> createMappedTable(DynamoDbEnhancedClientExtension dynamoDbEnhancedClientExtension) { return DynamoDbEnhancedClient.builder() .dynamoDbClient(mockDynamoDbClient) .extensions(dynamoDbEnhancedClientExtension) .build() .table(TABLE_NAME, FakeItem.getTableSchema()); } @Test public void noExtension_mapsToItem() { FakeItem fakeItem = FakeItem.createUniqueFakeItem(); Map<String, AttributeValue> fakeItemMap = FakeItem.getTableSchema().itemToMap(fakeItem, true); Document defaultDocument = DefaultDocument.create(fakeItemMap); assertThat(defaultDocument.getItem(createMappedTable(null)), is(fakeItem)); } @Test public void extension_mapsToItem() { FakeItem fakeItem = FakeItem.createUniqueFakeItem(); FakeItem fakeItem2 = FakeItem.createUniqueFakeItem(); Map<String, AttributeValue> fakeItemMap = FakeItem.getTableSchema().itemToMap(fakeItem, true); Map<String, AttributeValue> fakeItemMap2 = FakeItem.getTableSchema().itemToMap(fakeItem2, true); when(mockDynamoDbEnhancedClientExtension.afterRead(any(DynamoDbExtensionContext.AfterRead.class))) .thenReturn(ReadModification.builder().transformedItem(fakeItemMap2).build()); Document defaultDocument = DefaultDocument.create(fakeItemMap); DynamoDbTable<FakeItem> mappedTable = createMappedTable(mockDynamoDbEnhancedClientExtension); assertThat(defaultDocument.getItem(mappedTable), is(fakeItem2)); verify(mockDynamoDbEnhancedClientExtension).afterRead(DefaultDynamoDbExtensionContext.builder() .tableMetadata(FakeItem.getTableMetadata()) .tableSchema(FakeItem.getTableSchema()) .operationContext(DefaultOperationContext.create(mappedTable.tableName())) .items(fakeItemMap).build() ); } @Test public void nullMapReturnsNullItem() { Document defaultDocument = DefaultDocument.create(null); assertThat(defaultDocument.getItem(createMappedTable(null)), is(nullValue())); } @Test public void emptyMapReturnsNullItem() { Document defaultDocument = DefaultDocument.create(emptyMap()); assertThat(defaultDocument.getItem(createMappedTable(null)), is(nullValue())); } }
3,980
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/internal
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/internal/immutable/MetaTableSchemaTest.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.internal.immutable; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.function.Consumer; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; 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.functionaltests.models.FakeItem; import software.amazon.awssdk.enhanced.dynamodb.internal.mapper.MetaTableSchema; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; @RunWith(MockitoJUnitRunner.class) public class MetaTableSchemaTest { private final MetaTableSchema<FakeItem> metaTableSchema = MetaTableSchema.create(FakeItem.class); private final FakeItem fakeItem = FakeItem.createUniqueFakeItem(); private final Map<String, AttributeValue> fakeMap = Collections.singletonMap("test", AttributeValue.builder().s("test").build()); @Rule public ExpectedException exception = ExpectedException.none(); @Mock private TableSchema<FakeItem> mockTableSchema; @Mock private EnhancedType<FakeItem> mockEnhancedType; @Test public void mapToItem() { metaTableSchema.initialize(mockTableSchema); when(mockTableSchema.mapToItem(any())).thenReturn(fakeItem); assertThat(metaTableSchema.mapToItem(fakeMap)).isSameAs(fakeItem); verify(mockTableSchema).mapToItem(fakeMap); } @Test public void mapToItem_notInitialized() { assertUninitialized(t -> t.mapToItem(fakeMap)); } @Test public void itemToMap_ignoreNulls() { metaTableSchema.initialize(mockTableSchema); when(mockTableSchema.itemToMap(any(FakeItem.class), any(boolean.class))).thenReturn(fakeMap); assertThat(metaTableSchema.itemToMap(fakeItem, true)).isSameAs(fakeMap); verify(mockTableSchema).itemToMap(fakeItem, true); assertThat(metaTableSchema.itemToMap(fakeItem, false)).isSameAs(fakeMap); verify(mockTableSchema).itemToMap(fakeItem, false); } @Test public void itemToMap_ignoreNulls_notInitialized() { assertUninitialized(t -> t.itemToMap(fakeItem, true)); } @Test public void itemToMap_attributes() { Collection<String> attributes = Collections.singletonList("test-attribute"); metaTableSchema.initialize(mockTableSchema); when(mockTableSchema.itemToMap(any(FakeItem.class), any())).thenReturn(fakeMap); assertThat(metaTableSchema.itemToMap(fakeItem, attributes)).isSameAs(fakeMap); verify(mockTableSchema).itemToMap(fakeItem, attributes); } @Test public void itemToMap_attributes_notInitialized() { assertUninitialized(t -> t.itemToMap(fakeItem, null)); } @Test public void attributeValue() { AttributeValue attributeValue = AttributeValue.builder().s("test-attribute").build(); metaTableSchema.initialize(mockTableSchema); when(mockTableSchema.attributeValue(any(), any())).thenReturn(attributeValue); assertThat(metaTableSchema.attributeValue(fakeItem, "test-name")).isSameAs(attributeValue); verify(mockTableSchema).attributeValue(fakeItem, "test-name"); } @Test public void attributeValue_notInitialized() { assertUninitialized(t -> t.attributeValue(fakeItem, "test")); } @Test public void tableMetadata() { TableMetadata mockTableMetadata = Mockito.mock(TableMetadata.class); metaTableSchema.initialize(mockTableSchema); when(mockTableSchema.tableMetadata()).thenReturn(mockTableMetadata); assertThat(metaTableSchema.tableMetadata()).isSameAs(mockTableMetadata); verify(mockTableSchema).tableMetadata(); } @Test public void tableMetadata_notInitialized() { assertUninitialized(TableSchema::tableMetadata); } @Test public void itemType() { metaTableSchema.initialize(mockTableSchema); when(mockTableSchema.itemType()).thenReturn(mockEnhancedType); assertThat(metaTableSchema.itemType()).isSameAs(mockEnhancedType); verify(mockTableSchema).itemType(); } @Test public void itemType_notInitialized() { assertUninitialized(TableSchema::itemType); } @Test public void attributeNames() { List<String> attributeNames = Collections.singletonList("attribute-names"); metaTableSchema.initialize(mockTableSchema); when(mockTableSchema.attributeNames()).thenReturn(attributeNames); assertThat(metaTableSchema.attributeNames()).isSameAs(attributeNames); verify(mockTableSchema).attributeNames(); } @Test public void attributeNames_notInitialized() { assertUninitialized(TableSchema::attributeNames); } @Test public void isAbstract() { metaTableSchema.initialize(mockTableSchema); when(mockTableSchema.isAbstract()).thenReturn(true); assertThat(metaTableSchema.isAbstract()).isTrue(); verify(mockTableSchema).isAbstract(); when(mockTableSchema.isAbstract()).thenReturn(false); assertThat(metaTableSchema.isAbstract()).isFalse(); verify(mockTableSchema, times(2)).isAbstract(); } @Test public void isAbstract_notInitialized() { assertUninitialized(TableSchema::isAbstract); } @Test public void doubleInitialize_throwsIllegalStateException() { metaTableSchema.initialize(mockTableSchema); exception.expect(IllegalStateException.class); exception.expectMessage("initialized"); metaTableSchema.initialize(mockTableSchema); } @Test public void isInitialized_uninitialized() { assertThat(metaTableSchema.isInitialized()).isFalse(); } @Test public void isInitialized_initialized() { metaTableSchema.initialize(mockTableSchema); assertThat(metaTableSchema.isInitialized()).isTrue(); } @Test public void concreteTableSchema_uninitialized() { exception.expect(IllegalStateException.class); exception.expectMessage("must be initialized"); metaTableSchema.concreteTableSchema(); } @Test public void concreteTableSchema_initialized() { metaTableSchema.initialize(mockTableSchema); assertThat(metaTableSchema.concreteTableSchema()).isSameAs(mockTableSchema); } private void assertUninitialized(Consumer<TableSchema<FakeItem>> methodToTest) { exception.expect(IllegalStateException.class); exception.expectMessage("must be initialized"); methodToTest.accept(metaTableSchema); } }
3,981
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/internal
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/internal/immutable/ImmutableIntrospectorTest.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.internal.immutable; import static org.assertj.core.api.Assertions.assertThat; import java.beans.Transient; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbIgnore; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbImmutable; public class ImmutableIntrospectorTest { @Rule public ExpectedException exception = ExpectedException.none(); @DynamoDbImmutable(builder = SimpleImmutableMixedStyle.Builder.class) private static final class SimpleImmutableMixedStyle { public String getAttribute1() { throw new UnsupportedOperationException(); } public Integer attribute2() { throw new UnsupportedOperationException(); } public Boolean isAttribute3() { throw new UnsupportedOperationException(); } public static final class Builder { public void setAttribute1(String attribute1) { throw new UnsupportedOperationException(); } public Builder attribute2(Integer attribute2) { throw new UnsupportedOperationException(); } public Void setAttribute3(Boolean attribute3) { throw new UnsupportedOperationException(); } public SimpleImmutableMixedStyle build() { throw new UnsupportedOperationException(); } } } @Test public void simpleImmutableMixedStyle() { ImmutableInfo<SimpleImmutableMixedStyle> immutableInfo = ImmutableIntrospector.getImmutableInfo(SimpleImmutableMixedStyle.class); assertThat(immutableInfo.immutableClass()).isSameAs(SimpleImmutableMixedStyle.class); assertThat(immutableInfo.builderClass()).isSameAs(SimpleImmutableMixedStyle.Builder.class); assertThat(immutableInfo.buildMethod().getReturnType()).isSameAs(SimpleImmutableMixedStyle.class); assertThat(immutableInfo.buildMethod().getParameterCount()).isZero(); assertThat(immutableInfo.staticBuilderMethod()).isNotPresent(); assertThat(immutableInfo.propertyDescriptors()).hasSize(3); assertThat(immutableInfo.propertyDescriptors()).anySatisfy(p -> { assertThat(p.name()).isEqualTo("attribute1"); assertThat(p.getter().getParameterCount()).isZero(); assertThat(p.getter().getReturnType()).isSameAs(String.class); assertThat(p.setter().getParameterCount()).isEqualTo(1); assertThat(p.setter().getParameterTypes()[0]).isSameAs(String.class); }); assertThat(immutableInfo.propertyDescriptors()).anySatisfy(p -> { assertThat(p.name()).isEqualTo("attribute2"); assertThat(p.getter().getParameterCount()).isZero(); assertThat(p.getter().getReturnType()).isSameAs(Integer.class); assertThat(p.setter().getParameterCount()).isEqualTo(1); assertThat(p.setter().getParameterTypes()[0]).isSameAs(Integer.class); }); assertThat(immutableInfo.propertyDescriptors()).anySatisfy(p -> { assertThat(p.name()).isEqualTo("attribute3"); assertThat(p.getter().getParameterCount()).isZero(); assertThat(p.getter().getReturnType()).isSameAs(Boolean.class); assertThat(p.setter().getParameterCount()).isEqualTo(1); assertThat(p.setter().getParameterTypes()[0]).isSameAs(Boolean.class); }); } @DynamoDbImmutable(builder = SimpleImmutableWithPrimitives.Builder.class) private static final class SimpleImmutableWithPrimitives { public int attribute() { throw new UnsupportedOperationException(); } public static final class Builder { public Builder attribute(int attribute) { throw new UnsupportedOperationException(); } public SimpleImmutableWithPrimitives build() { throw new UnsupportedOperationException(); } } } @Test public void simpleImmutableWithPrimitives() { ImmutableInfo<SimpleImmutableWithPrimitives> immutableInfo = ImmutableIntrospector.getImmutableInfo(SimpleImmutableWithPrimitives.class); assertThat(immutableInfo.immutableClass()).isSameAs(SimpleImmutableWithPrimitives.class); assertThat(immutableInfo.builderClass()).isSameAs(SimpleImmutableWithPrimitives.Builder.class); assertThat(immutableInfo.buildMethod().getReturnType()).isSameAs(SimpleImmutableWithPrimitives.class); assertThat(immutableInfo.buildMethod().getParameterCount()).isZero(); assertThat(immutableInfo.staticBuilderMethod()).isNotPresent(); assertThat(immutableInfo.propertyDescriptors()).hasOnlyOneElementSatisfying(p -> { assertThat(p.name()).isEqualTo("attribute"); assertThat(p.getter().getParameterCount()).isZero(); assertThat(p.getter().getReturnType()).isSameAs(int.class); assertThat(p.setter().getParameterCount()).isEqualTo(1); assertThat(p.setter().getParameterTypes()[0]).isSameAs(int.class); }); } @DynamoDbImmutable(builder = SimpleImmutableWithTrickyNames.Builder.class) private static final class SimpleImmutableWithTrickyNames { public String isAttribute() { throw new UnsupportedOperationException(); } public String getGetAttribute() { throw new UnsupportedOperationException(); } public String getSetAttribute() { throw new UnsupportedOperationException(); } public static final class Builder { public Builder isAttribute(String isAttribute) { throw new UnsupportedOperationException(); } public Builder getAttribute(String getAttribute) { throw new UnsupportedOperationException(); } public Builder setSetAttribute(String setAttribute) { throw new UnsupportedOperationException(); } public SimpleImmutableWithTrickyNames build() { throw new UnsupportedOperationException(); } } } @Test public void simpleImmutableWithTrickyNames() { ImmutableInfo<SimpleImmutableWithTrickyNames> immutableInfo = ImmutableIntrospector.getImmutableInfo(SimpleImmutableWithTrickyNames.class); assertThat(immutableInfo.immutableClass()).isSameAs(SimpleImmutableWithTrickyNames.class); assertThat(immutableInfo.builderClass()).isSameAs(SimpleImmutableWithTrickyNames.Builder.class); assertThat(immutableInfo.buildMethod().getReturnType()).isSameAs(SimpleImmutableWithTrickyNames.class); assertThat(immutableInfo.buildMethod().getParameterCount()).isZero(); assertThat(immutableInfo.staticBuilderMethod()).isNotPresent(); assertThat(immutableInfo.propertyDescriptors()).hasSize(3); assertThat(immutableInfo.propertyDescriptors()).anySatisfy(p -> { assertThat(p.name()).isEqualTo("isAttribute"); assertThat(p.getter().getParameterCount()).isZero(); assertThat(p.getter().getReturnType()).isSameAs(String.class); assertThat(p.setter().getParameterCount()).isEqualTo(1); assertThat(p.setter().getParameterTypes()[0]).isSameAs(String.class); }); assertThat(immutableInfo.propertyDescriptors()).anySatisfy(p -> { assertThat(p.name()).isEqualTo("getAttribute"); assertThat(p.getter().getParameterCount()).isZero(); assertThat(p.getter().getReturnType()).isSameAs(String.class); assertThat(p.setter().getParameterCount()).isEqualTo(1); assertThat(p.setter().getParameterTypes()[0]).isSameAs(String.class); }); assertThat(immutableInfo.propertyDescriptors()).anySatisfy(p -> { assertThat(p.name()).isEqualTo("setAttribute"); assertThat(p.getter().getParameterCount()).isZero(); assertThat(p.getter().getReturnType()).isSameAs(String.class); assertThat(p.setter().getParameterCount()).isEqualTo(1); assertThat(p.setter().getParameterTypes()[0]).isSameAs(String.class); }); } @DynamoDbImmutable(builder = ImmutableWithNoMatchingSetter.Builder.class) private static final class ImmutableWithNoMatchingSetter { public int rightAttribute() { throw new UnsupportedOperationException(); } public static final class Builder { public Builder wrongAttribute(int attribute) { throw new UnsupportedOperationException(); } public ImmutableWithNoMatchingSetter build() { throw new UnsupportedOperationException(); } } } @Test public void immutableWithNoMatchingSetter() { exception.expect(IllegalArgumentException.class); exception.expectMessage("rightAttribute"); exception.expectMessage("matching setter"); ImmutableIntrospector.getImmutableInfo(ImmutableWithNoMatchingSetter.class); } @DynamoDbImmutable(builder = ImmutableWithGetterParams.Builder.class) private static final class ImmutableWithGetterParams { public int rightAttribute(String illegalParam) { throw new UnsupportedOperationException(); } public static final class Builder { public Builder rightAttribute(int rightAttribute) { throw new UnsupportedOperationException(); } public ImmutableWithGetterParams build() { throw new UnsupportedOperationException(); } } } @Test public void immutableWithGetterParams() { exception.expect(IllegalArgumentException.class); exception.expectMessage("rightAttribute"); exception.expectMessage("getter"); exception.expectMessage("parameters"); ImmutableIntrospector.getImmutableInfo(ImmutableWithGetterParams.class); } @DynamoDbImmutable(builder = ImmutableWithVoidAttribute.Builder.class) private static final class ImmutableWithVoidAttribute { public Void rightAttribute() { throw new UnsupportedOperationException(); } public static final class Builder { public Builder rightAttribute(Void rightAttribute) { throw new UnsupportedOperationException(); } public ImmutableWithVoidAttribute build() { throw new UnsupportedOperationException(); } } } @Test public void immutableWithVoidAttribute() { exception.expect(IllegalArgumentException.class); exception.expectMessage("rightAttribute"); exception.expectMessage("getter"); exception.expectMessage("void"); ImmutableIntrospector.getImmutableInfo(ImmutableWithVoidAttribute.class); } @DynamoDbImmutable(builder = ImmutableWithNoMatchingGetter.Builder.class) private static final class ImmutableWithNoMatchingGetter { public static final class Builder { public Builder rightAttribute(int attribute) { throw new UnsupportedOperationException(); } public ImmutableWithNoMatchingGetter build() { throw new UnsupportedOperationException(); } } } @Test public void immutableWithNoMatchingGetter() { exception.expect(IllegalArgumentException.class); exception.expectMessage("rightAttribute"); exception.expectMessage("matching getter"); ImmutableIntrospector.getImmutableInfo(ImmutableWithNoMatchingGetter.class); } @DynamoDbImmutable(builder = ImmutableWithNoBuildMethod.Builder.class) private static final class ImmutableWithNoBuildMethod { public int rightAttribute() { throw new UnsupportedOperationException(); } public static final class Builder { public Builder rightAttribute(int attribute) { throw new UnsupportedOperationException(); } } } @Test public void immutableWithNoBuildMethod() { exception.expect(IllegalArgumentException.class); exception.expectMessage("build"); ImmutableIntrospector.getImmutableInfo(ImmutableWithNoBuildMethod.class); } @DynamoDbImmutable(builder = ImmutableWithWrongSetter.Builder.class) private static final class ImmutableWithWrongSetter { public int rightAttribute() { throw new UnsupportedOperationException(); } public static final class Builder { public Builder rightAttribute(String attribute) { throw new UnsupportedOperationException(); } public ImmutableWithWrongSetter build() { throw new UnsupportedOperationException(); } } } @Test public void immutableWithWrongSetter() { exception.expect(IllegalArgumentException.class); exception.expectMessage("rightAttribute"); exception.expectMessage("matching setter"); ImmutableIntrospector.getImmutableInfo(ImmutableWithWrongSetter.class); } @DynamoDbImmutable(builder = ImmutableWithWrongBuildType.Builder.class) private static final class ImmutableWithWrongBuildType { public int rightAttribute() { throw new UnsupportedOperationException(); } public static final class Builder { public Builder rightAttribute(int attribute) { throw new UnsupportedOperationException(); } public String build() { throw new UnsupportedOperationException(); } } } @Test public void immutableWithWrongBuildType() { exception.expect(IllegalArgumentException.class); exception.expectMessage("build"); ImmutableIntrospector.getImmutableInfo(ImmutableWithWrongBuildType.class); } private static final class ImmutableMissingAnnotation { public int rightAttribute() { throw new UnsupportedOperationException(); } public static final class Builder { public Builder rightAttribute(int attribute) { throw new UnsupportedOperationException(); } public ImmutableMissingAnnotation build() { throw new UnsupportedOperationException(); } } } @Test public void immutableMissingAnnotation() { exception.expect(IllegalArgumentException.class); exception.expectMessage("@DynamoDbImmutable"); ImmutableIntrospector.getImmutableInfo(ImmutableMissingAnnotation.class); } @DynamoDbImmutable(builder = SimpleImmutableWithIgnoredGetter.Builder.class) private static final class SimpleImmutableWithIgnoredGetter { public int attribute() { throw new UnsupportedOperationException(); } @DynamoDbIgnore public int ignoreMe() { throw new UnsupportedOperationException(); } @Transient public int ignoreMeToo() { throw new UnsupportedOperationException(); } public static final class Builder { public Builder attribute(int attribute) { throw new UnsupportedOperationException(); } public SimpleImmutableWithIgnoredGetter build() { throw new UnsupportedOperationException(); } } } @Test public void simpleImmutableWithIgnoredGetters() { ImmutableInfo<SimpleImmutableWithIgnoredGetter> immutableInfo = ImmutableIntrospector.getImmutableInfo(SimpleImmutableWithIgnoredGetter.class); assertThat(immutableInfo.immutableClass()).isSameAs(SimpleImmutableWithIgnoredGetter.class); assertThat(immutableInfo.builderClass()).isSameAs(SimpleImmutableWithIgnoredGetter.Builder.class); assertThat(immutableInfo.buildMethod().getReturnType()).isSameAs(SimpleImmutableWithIgnoredGetter.class); assertThat(immutableInfo.buildMethod().getParameterCount()).isZero(); assertThat(immutableInfo.staticBuilderMethod()).isNotPresent(); assertThat(immutableInfo.propertyDescriptors()).hasOnlyOneElementSatisfying(p -> { assertThat(p.name()).isEqualTo("attribute"); assertThat(p.getter().getParameterCount()).isZero(); assertThat(p.getter().getReturnType()).isSameAs(int.class); assertThat(p.setter().getParameterCount()).isEqualTo(1); assertThat(p.setter().getParameterTypes()[0]).isSameAs(int.class); }); } @DynamoDbImmutable(builder = SimpleImmutableWithIgnoredSetter.Builder.class) private static final class SimpleImmutableWithIgnoredSetter { public int attribute() { throw new UnsupportedOperationException(); } public static final class Builder { public Builder attribute(int attribute) { throw new UnsupportedOperationException(); } @DynamoDbIgnore public int ignoreMe() { throw new UnsupportedOperationException(); } @Transient public int ignoreMeToo() { throw new UnsupportedOperationException(); } public SimpleImmutableWithIgnoredSetter build() { throw new UnsupportedOperationException(); } } } @Test public void simpleImmutableWithIgnoredSetter() { ImmutableInfo<SimpleImmutableWithIgnoredSetter> immutableInfo = ImmutableIntrospector.getImmutableInfo(SimpleImmutableWithIgnoredSetter.class); assertThat(immutableInfo.immutableClass()).isSameAs(SimpleImmutableWithIgnoredSetter.class); assertThat(immutableInfo.builderClass()).isSameAs(SimpleImmutableWithIgnoredSetter.Builder.class); assertThat(immutableInfo.buildMethod().getReturnType()).isSameAs(SimpleImmutableWithIgnoredSetter.class); assertThat(immutableInfo.buildMethod().getParameterCount()).isZero(); assertThat(immutableInfo.staticBuilderMethod()).isNotPresent(); assertThat(immutableInfo.propertyDescriptors()).hasOnlyOneElementSatisfying(p -> { assertThat(p.name()).isEqualTo("attribute"); assertThat(p.getter().getParameterCount()).isZero(); assertThat(p.getter().getReturnType()).isSameAs(int.class); assertThat(p.setter().getParameterCount()).isEqualTo(1); assertThat(p.setter().getParameterTypes()[0]).isSameAs(int.class); }); } private static class ExtendedImmutableBase { public int baseAttribute() { throw new UnsupportedOperationException(); } public static class Builder { public Builder baseAttribute(int attribute) { throw new UnsupportedOperationException(); } } } @DynamoDbImmutable(builder = ExtendedImmutable.Builder.class) private static final class ExtendedImmutable extends ExtendedImmutableBase { public int childAttribute() { throw new UnsupportedOperationException(); } public static final class Builder extends ExtendedImmutableBase.Builder { public Builder childAttribute(int attribute) { throw new UnsupportedOperationException(); } public ExtendedImmutable build() { throw new UnsupportedOperationException(); } } } @Test public void extendedImmutable() { ImmutableInfo<ExtendedImmutable> immutableInfo = ImmutableIntrospector.getImmutableInfo(ExtendedImmutable.class); assertThat(immutableInfo.immutableClass()).isSameAs(ExtendedImmutable.class); assertThat(immutableInfo.builderClass()).isSameAs(ExtendedImmutable.Builder.class); assertThat(immutableInfo.buildMethod().getReturnType()).isSameAs(ExtendedImmutable.class); assertThat(immutableInfo.buildMethod().getParameterCount()).isZero(); assertThat(immutableInfo.staticBuilderMethod()).isNotPresent(); assertThat(immutableInfo.propertyDescriptors()).hasSize(2); assertThat(immutableInfo.propertyDescriptors()).anySatisfy(p -> { assertThat(p.name()).isEqualTo("baseAttribute"); assertThat(p.getter().getParameterCount()).isZero(); assertThat(p.getter().getReturnType()).isSameAs(int.class); assertThat(p.setter().getParameterCount()).isEqualTo(1); assertThat(p.setter().getParameterTypes()[0]).isSameAs(int.class); }); assertThat(immutableInfo.propertyDescriptors()).anySatisfy(p -> { assertThat(p.name()).isEqualTo("childAttribute"); assertThat(p.getter().getParameterCount()).isZero(); assertThat(p.getter().getReturnType()).isSameAs(int.class); assertThat(p.setter().getParameterCount()).isEqualTo(1); assertThat(p.setter().getParameterTypes()[0]).isSameAs(int.class); }); } @DynamoDbImmutable(builder = ImmutableWithPrimitiveBoolean.Builder.class) private static final class ImmutableWithPrimitiveBoolean { public boolean isAttribute() { throw new UnsupportedOperationException(); } public static final class Builder { public Builder attribute(boolean attribute) { throw new UnsupportedOperationException(); } public ImmutableWithPrimitiveBoolean build() { throw new UnsupportedOperationException(); } } } @Test public void immutableWithPrimitiveBoolean() { ImmutableInfo<ImmutableWithPrimitiveBoolean> immutableInfo = ImmutableIntrospector.getImmutableInfo(ImmutableWithPrimitiveBoolean.class); assertThat(immutableInfo.immutableClass()).isSameAs(ImmutableWithPrimitiveBoolean.class); assertThat(immutableInfo.builderClass()).isSameAs(ImmutableWithPrimitiveBoolean.Builder.class); assertThat(immutableInfo.buildMethod().getReturnType()).isSameAs(ImmutableWithPrimitiveBoolean.class); assertThat(immutableInfo.buildMethod().getParameterCount()).isZero(); assertThat(immutableInfo.staticBuilderMethod()).isNotPresent(); assertThat(immutableInfo.propertyDescriptors()).hasOnlyOneElementSatisfying(p -> { assertThat(p.name()).isEqualTo("attribute"); assertThat(p.getter().getParameterCount()).isZero(); assertThat(p.getter().getReturnType()).isSameAs(boolean.class); assertThat(p.setter().getParameterCount()).isEqualTo(1); assertThat(p.setter().getParameterTypes()[0]).isSameAs(boolean.class); }); } @DynamoDbImmutable(builder = ImmutableWithStaticBuilder.Builder.class) private static final class ImmutableWithStaticBuilder { public boolean isAttribute() { throw new UnsupportedOperationException(); } public static Builder builder() { throw new UnsupportedOperationException(); } public static final class Builder { private Builder() { } public Builder attribute(boolean attribute) { throw new UnsupportedOperationException(); } public ImmutableWithStaticBuilder build() { throw new UnsupportedOperationException(); } } } @Test public void immutableWithStaticBuilder() { ImmutableInfo<ImmutableWithStaticBuilder> immutableInfo = ImmutableIntrospector.getImmutableInfo(ImmutableWithStaticBuilder.class); assertThat(immutableInfo.immutableClass()).isSameAs(ImmutableWithStaticBuilder.class); assertThat(immutableInfo.builderClass()).isSameAs(ImmutableWithStaticBuilder.Builder.class); assertThat(immutableInfo.buildMethod().getReturnType()).isSameAs(ImmutableWithStaticBuilder.class); assertThat(immutableInfo.buildMethod().getParameterCount()).isZero(); assertThat(immutableInfo.staticBuilderMethod()) .hasValueSatisfying(m -> assertThat(m.getName()).isEqualTo("builder")); assertThat(immutableInfo.propertyDescriptors()).hasOnlyOneElementSatisfying(p -> { assertThat(p.name()).isEqualTo("attribute"); assertThat(p.getter().getParameterCount()).isZero(); assertThat(p.getter().getReturnType()).isSameAs(boolean.class); assertThat(p.setter().getParameterCount()).isEqualTo(1); assertThat(p.setter().getParameterTypes()[0]).isSameAs(boolean.class); }); } }
3,982
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/internal
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/internal/update/UpdateExpressionConverterTest.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.internal.update; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; import software.amazon.awssdk.enhanced.dynamodb.Expression; import software.amazon.awssdk.enhanced.dynamodb.update.AddAction; import software.amazon.awssdk.enhanced.dynamodb.update.DeleteAction; import software.amazon.awssdk.enhanced.dynamodb.update.RemoveAction; import software.amazon.awssdk.enhanced.dynamodb.update.SetAction; import software.amazon.awssdk.enhanced.dynamodb.update.UpdateAction; import software.amazon.awssdk.enhanced.dynamodb.update.UpdateExpression; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.utils.StringUtils; /** * When converting, SetAction, DeleteAction and AddAction work similarly. Advanced test cases thus only need to test * using one of these types of action. RemoveAction, lacking expression values, work slightly differently. * */ @TestMethodOrder(MethodOrderer.MethodName.class) class UpdateExpressionConverterTest { private static final String KEY_TOKEN = "#PRE_"; private static final String VALUE_TOKEN = ":PRE_"; @Test void convert_emptyExpression() { UpdateExpression updateExpression = UpdateExpression.builder().build(); Expression expression = UpdateExpressionConverter.toExpression(updateExpression); assertThat(expression.expression()).isEmpty(); assertThat(expression.expressionNames()).isEmpty(); assertThat(expression.expressionValues()).isEmpty(); } @Test void convert_removeAction_single() { UpdateExpression updateExpression = createUpdateExpression(removeAction("attribute1", null)); Expression expression = UpdateExpressionConverter.toExpression(updateExpression); assertThat(expression.expression()).isEqualTo("REMOVE attribute1"); assertThat(expression.expressionNames()).isEmpty(); assertThat(expression.expressionValues()).isEmpty(); } @Test void convert_removeActions() { UpdateExpression updateExpression = createUpdateExpression(removeAction("attribute1", null), removeAction("attribute2", null)); Expression expression = UpdateExpressionConverter.toExpression(updateExpression); assertThat(expression.expression()).isEqualTo("REMOVE attribute1, attribute2"); assertThat(expression.expressionNames()).isEmpty(); assertThat(expression.expressionValues()).isEmpty(); } @Test void convert_removeActions_uniqueNameTokens() { UpdateExpression updateExpression = createUpdateExpression(removeAction("attribute1", KEY_TOKEN), removeAction("attribute2", KEY_TOKEN)); Expression expression = UpdateExpressionConverter.toExpression(updateExpression); Map<String, String> expectedExpressionNames = new HashMap<>(); expectedExpressionNames.put("#PRE_attribute1", "attribute1"); expectedExpressionNames.put("#PRE_attribute2", "attribute2"); assertThat(expression.expression()).isEqualTo("REMOVE #PRE_attribute1, #PRE_attribute2"); assertThat(expression.expressionNames()).containsExactlyEntriesOf(expectedExpressionNames); assertThat(expression.expressionValues()).isEmpty(); } /** * Attributes with the same name are simply added to the list. There is no check to compare the contents * of two remove action paths. * * This would fail when calling DDB; note that UpdateItemOperation always prefixes attribute names and the probability of * this use case is low. */ @Test void convert_removeActions_duplicateAttributes_createsDdbFailExpression() { UpdateExpression updateExpression = createUpdateExpression(removeAction("attribute1", null), removeAction("attribute1", null)); Expression expression = UpdateExpressionConverter.toExpression(updateExpression); assertThat(expression.expression()).isEqualTo("REMOVE attribute1, attribute1"); assertThat(expression.expressionNames()).isEmpty(); assertThat(expression.expressionValues()).isEmpty(); } /** * The joining logic in {@link Expression#joinNames(Map, Map)} will be merge the two entries, since here the * same key will point at the same value. * * This would fail when calling DDB; note that UpdateItemOperation always prefixes attribute names and the probability of * this use case is low. */ @Test void convert_removeActions_duplicateAttributes_uniqueNameTokens_createsDdbFailExpression() { UpdateExpression updateExpression = createUpdateExpression(removeAction("attribute1", KEY_TOKEN), removeAction("attribute1", KEY_TOKEN)); Expression expression = UpdateExpressionConverter.toExpression(updateExpression); assertThat(expression.expression()).isEqualTo("REMOVE #PRE_attribute1, #PRE_attribute1"); assertThat(expression.expressionNames()).hasSize(1); assertThat(expression.expressionValues()).isEmpty(); } /** * This is the same case as using a name prefix with the same attribute name, i.e. `duplicateAttributes_uniqueNameTokens` */ @Test void convert_removeActions_duplicateAttributes_duplicateNameTokens_createsDdbFailExpression() { UpdateExpression updateExpression = createUpdateExpression( RemoveAction.builder().path("attribute_ref").putExpressionName("attribute_ref", "attribute1").build(), RemoveAction.builder().path("attribute_ref").putExpressionName("attribute_ref", "attribute1").build()); Expression expression = UpdateExpressionConverter.toExpression(updateExpression); assertThat(expression.expression()).isEqualTo("REMOVE attribute_ref, attribute_ref"); assertThat(expression.expressionNames()).hasSize(1); assertThat(expression.expressionValues()).isEmpty(); } @Test void convert_removeActions_uniqueAttributes_duplicateNameTokens_error() { UpdateExpression updateExpression = createUpdateExpression( RemoveAction.builder().path("attribute_ref").putExpressionName("attribute_ref", "attribute1").build(), RemoveAction.builder().path("attribute_ref").putExpressionName("attribute_ref", "attribute2").build()); assertThatThrownBy(() -> UpdateExpressionConverter.toExpression(updateExpression)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Attempt to coalesce two expressions with conflicting expression names") .hasMessageContaining("attribute_ref"); } @Test void convert_setAction_single() { UpdateExpression updateExpression = createUpdateExpression(setAction("attribute1", string("val1"), null, VALUE_TOKEN)); Expression expression = UpdateExpressionConverter.toExpression(updateExpression); assertThat(expression.expression()).isEqualTo("SET attribute1 = :PRE_attribute1"); assertThat(expression.expressionNames()).isEmpty(); assertThat(expression.expressionValues()).containsEntry(":PRE_attribute1", string("val1")); } @Test void convert_setActions() { UpdateExpression updateExpression = createUpdateExpression(setAction("attribute1", string("val1"), null, VALUE_TOKEN), setAction("attribute2", string("val2"), null, VALUE_TOKEN)); Expression expression = UpdateExpressionConverter.toExpression(updateExpression); Map<String, AttributeValue> expectedExpressionValues = new HashMap<>(); expectedExpressionValues.put(":PRE_attribute1", string("val1")); expectedExpressionValues.put(":PRE_attribute2", string("val2")); assertThat(expression.expression()).isEqualTo("SET attribute1 = :PRE_attribute1, attribute2 = :PRE_attribute2"); assertThat(expression.expressionNames()).isEmpty(); assertThat(expression.expressionValues()).containsExactlyEntriesOf(expectedExpressionValues); } @Test void convert_setActions_uniqueNameTokens() { UpdateExpression updateExpression = createUpdateExpression(setAction("attribute1", string("val1"), KEY_TOKEN, VALUE_TOKEN), setAction("attribute2", string("val2"), KEY_TOKEN, VALUE_TOKEN)); Expression expression = UpdateExpressionConverter.toExpression(updateExpression); Map<String, String> expectedExpressionNames = new HashMap<>(); expectedExpressionNames.put("#PRE_attribute1", "attribute1"); expectedExpressionNames.put("#PRE_attribute2", "attribute2"); Map<String, AttributeValue> expectedExpressionValues = new HashMap<>(); expectedExpressionValues.put(":PRE_attribute1", string("val1")); expectedExpressionValues.put(":PRE_attribute2", string("val2")); assertThat(expression.expression()).isEqualTo("SET #PRE_attribute1 = :PRE_attribute1, #PRE_attribute2 = :PRE_attribute2"); assertThat(expression.expressionNames()).containsExactlyEntriesOf(expectedExpressionNames); assertThat(expression.expressionValues()).containsExactlyEntriesOf(expectedExpressionValues); } @Test void convert_deleteAction_single() { UpdateExpression updateExpression = createUpdateExpression(deleteAction("attribute1", string("val1"), null, VALUE_TOKEN)); Expression expression = UpdateExpressionConverter.toExpression(updateExpression); assertThat(expression.expression()).isEqualTo("DELETE attribute1 :PRE_attribute1"); assertThat(expression.expressionNames()).isEmpty(); assertThat(expression.expressionValues()).containsEntry(":PRE_attribute1", string("val1")); } @Test void convert_deleteActions() { UpdateExpression updateExpression = createUpdateExpression(deleteAction("attribute1", string("val1"), null, VALUE_TOKEN), deleteAction("attribute2", string("val2"), null, VALUE_TOKEN)); Expression expression = UpdateExpressionConverter.toExpression(updateExpression); Map<String, AttributeValue> expectedExpressionValues = new HashMap<>(); expectedExpressionValues.put(":PRE_attribute1", string("val1")); expectedExpressionValues.put(":PRE_attribute2", string("val2")); assertThat(expression.expression()).isEqualTo("DELETE attribute1 :PRE_attribute1, attribute2 :PRE_attribute2"); assertThat(expression.expressionNames()).isEmpty(); assertThat(expression.expressionValues()).containsExactlyEntriesOf(expectedExpressionValues); } @Test void convert_deleteActions_uniqueNameTokens() { UpdateExpression updateExpression = createUpdateExpression(deleteAction("attribute1", string("val1"), KEY_TOKEN, VALUE_TOKEN), deleteAction("attribute2", string("val2"), KEY_TOKEN, VALUE_TOKEN)); Expression expression = UpdateExpressionConverter.toExpression(updateExpression); Map<String, String> expectedExpressionNames = new HashMap<>(); expectedExpressionNames.put("#PRE_attribute1", "attribute1"); expectedExpressionNames.put("#PRE_attribute2", "attribute2"); Map<String, AttributeValue> expectedExpressionValues = new HashMap<>(); expectedExpressionValues.put(":PRE_attribute1", string("val1")); expectedExpressionValues.put(":PRE_attribute2", string("val2")); assertThat(expression.expression()).isEqualTo("DELETE #PRE_attribute1 :PRE_attribute1, #PRE_attribute2 :PRE_attribute2"); assertThat(expression.expressionNames()).containsExactlyEntriesOf(expectedExpressionNames); assertThat(expression.expressionValues()).containsExactlyEntriesOf(expectedExpressionValues); } /** * The joining logic in {@link Expression#joinValues(Map, Map)} will be throw an error, because the same key * is pointing to different values. Actions that use expression value maps (Add, Delete, Set) exhibit the same behavior. */ @Test void convert_deleteActions_duplicateAttributes_error() { UpdateExpression updateExpression = createUpdateExpression(deleteAction("attribute1", string("val1"), null, VALUE_TOKEN), deleteAction("attribute1", string("val2"), null, VALUE_TOKEN)); assertThatThrownBy(() -> UpdateExpressionConverter.toExpression(updateExpression)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Attempt to coalesce two expressions with conflicting expression values") .hasMessageContaining(":PRE_attribute1"); } /** * The joining logic in {@link Expression#joinValues(Map, Map)} will be throw an error, because the same key * is pointing to different values. Actions that use expression value maps (Add, Delete, Set) exhibit the same behavior. */ @Test void convert_deleteActions_duplicateAttributes_uniqueNameTokens_error() { UpdateExpression updateExpression = createUpdateExpression(deleteAction("attribute1", string("val1"), KEY_TOKEN, VALUE_TOKEN), deleteAction("attribute1", string("val2"), KEY_TOKEN, VALUE_TOKEN)); assertThatThrownBy(() -> UpdateExpressionConverter.toExpression(updateExpression)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Attempt to coalesce two expressions with conflicting expression values") .hasMessageContaining(":PRE_attribute1"); } /** * The joining logic in {@link Expression#joinValues(Map, Map)} will be merge the two entries, since here the * same key will point at the same value. * * This would fail when calling DDB; note that UpdateItemOperation always prefixes attribute names and the probability of * this use case is low. */ @Test void convert_deleteActions_duplicateAttributes_duplicateValueTokens_createsDdbFailExpression() { UpdateExpression updateExpression = createUpdateExpression( DeleteAction.builder().path("attribute1").value("attribute_ref").putExpressionValue("attribute_ref", string("val1")).build(), DeleteAction.builder().path("attribute1").value("attribute_ref").putExpressionValue("attribute_ref", string("val1")).build()); Expression expression = UpdateExpressionConverter.toExpression(updateExpression); assertThat(expression.expression()).isEqualTo("DELETE attribute1 attribute_ref, attribute1 attribute_ref"); assertThat(expression.expressionNames()).isEmpty(); assertThat(expression.expressionValues()).containsEntry("attribute_ref", string("val1")); } @Test void convert_deleteActions_uniqueAttributes_duplicateValueTokens_error() { UpdateExpression updateExpression = createUpdateExpression( DeleteAction.builder().path("attribute1").value("attribute_ref").putExpressionValue("attribute_ref", string("val1")).build(), DeleteAction.builder().path("attribute2").value("attribute_ref").putExpressionValue("attribute_ref", string("val2")).build()); assertThatThrownBy(() -> UpdateExpressionConverter.toExpression(updateExpression)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Attempt to coalesce two expressions with conflicting expression values") .hasMessageContaining("attribute_ref"); } @Test void convert_addAction_single() { UpdateExpression updateExpression = createUpdateExpression(addAction("attribute1", string("val1"), null, VALUE_TOKEN)); Expression expression = UpdateExpressionConverter.toExpression(updateExpression); assertThat(expression.expression()).isEqualTo("ADD attribute1 :PRE_attribute1"); assertThat(expression.expressionNames()).isEmpty(); assertThat(expression.expressionValues()).containsEntry(":PRE_attribute1", string("val1")); } @Test void convert_addActions() { UpdateExpression updateExpression = createUpdateExpression(addAction("attribute1", string("val1"), null, VALUE_TOKEN), addAction("attribute2", string("val2"), null, VALUE_TOKEN)); Expression expression = UpdateExpressionConverter.toExpression(updateExpression); Map<String, AttributeValue> expectedExpressionValues = new HashMap<>(); expectedExpressionValues.put(":PRE_attribute1", string("val1")); expectedExpressionValues.put(":PRE_attribute2", string("val2")); assertThat(expression.expression()).isEqualTo("ADD attribute1 :PRE_attribute1, attribute2 :PRE_attribute2"); assertThat(expression.expressionNames()).isEmpty(); assertThat(expression.expressionValues()).containsExactlyEntriesOf(expectedExpressionValues); } @Test void convert_addActions_uniqueNameTokens() { UpdateExpression updateExpression = createUpdateExpression(addAction("attribute1", string("val1"), KEY_TOKEN, VALUE_TOKEN), addAction("attribute2", string("val2"), KEY_TOKEN, VALUE_TOKEN)); Expression expression = UpdateExpressionConverter.toExpression(updateExpression); Map<String, String> expectedExpressionNames = new HashMap<>(); expectedExpressionNames.put("#PRE_attribute1", "attribute1"); expectedExpressionNames.put("#PRE_attribute2", "attribute2"); Map<String, AttributeValue> expectedExpressionValues = new HashMap<>(); expectedExpressionValues.put(":PRE_attribute1", string("val1")); expectedExpressionValues.put(":PRE_attribute2", string("val2")); assertThat(expression.expression()).isEqualTo("ADD #PRE_attribute1 :PRE_attribute1, #PRE_attribute2 :PRE_attribute2"); assertThat(expression.expressionNames()).containsExactlyEntriesOf(expectedExpressionNames); assertThat(expression.expressionValues()).containsExactlyEntriesOf(expectedExpressionValues); } @Test void convert_mixedActions() { UpdateExpression updateExpression = createUpdateExpression(addAction("attribute1", string("val1"), null, VALUE_TOKEN), deleteAction("attribute2", string("val2"), null, VALUE_TOKEN), removeAction("attribute3", null), setAction("attribute4", string("val4"), null, VALUE_TOKEN), deleteAction("attribute5", string("val5"), null, VALUE_TOKEN), setAction("attribute6", string("val6"), null, VALUE_TOKEN), removeAction("attribute7", null), addAction("attribute8", string("val8"), null, VALUE_TOKEN), removeAction("attribute9", null)); Expression expression = UpdateExpressionConverter.toExpression(updateExpression); assertThat(expression.expression()).isEqualTo( "SET attribute4 = :PRE_attribute4, attribute6 = :PRE_attribute6 " + "REMOVE attribute3, attribute7, attribute9 " + "DELETE attribute2 :PRE_attribute2, attribute5 :PRE_attribute5 " + "ADD attribute1 :PRE_attribute1, attribute8 :PRE_attribute8" ); assertThat(expression.expressionNames()).isEmpty(); assertThat(expression.expressionValues()).hasSize(6); } @Test void convert_mixedActions_uniqueNameTokens() { UpdateExpression updateExpression = createUpdateExpression(addAction("attribute1", string("val1"), KEY_TOKEN, VALUE_TOKEN), deleteAction("attribute2", string("val2"), KEY_TOKEN, VALUE_TOKEN), removeAction("attribute3", KEY_TOKEN), setAction("attribute4", string("val4"), KEY_TOKEN, VALUE_TOKEN), deleteAction("attribute5", string("val5"), KEY_TOKEN, VALUE_TOKEN), setAction("attribute6", string("val6"), KEY_TOKEN, VALUE_TOKEN), removeAction("attribute7", KEY_TOKEN), addAction("attribute8", string("val8"), KEY_TOKEN, VALUE_TOKEN), removeAction("attribute9", KEY_TOKEN)); Expression expression = UpdateExpressionConverter.toExpression(updateExpression); assertThat(expression.expression()).isEqualTo( "SET #PRE_attribute4 = :PRE_attribute4, #PRE_attribute6 = :PRE_attribute6 " + "REMOVE #PRE_attribute3, #PRE_attribute7, #PRE_attribute9 " + "DELETE #PRE_attribute2 :PRE_attribute2, #PRE_attribute5 :PRE_attribute5 " + "ADD #PRE_attribute1 :PRE_attribute1, #PRE_attribute8 :PRE_attribute8" ); assertThat(expression.expressionNames()).hasSize(9); assertThat(expression.expressionValues()).hasSize(6); } @Test void convert_mixedActions_duplicateAttributes_error() { UpdateExpression updateExpression = createUpdateExpression(deleteAction("attribute1", string("val1"), KEY_TOKEN, VALUE_TOKEN), addAction("attribute1", string("val2"), KEY_TOKEN, VALUE_TOKEN)); assertThatThrownBy(() -> UpdateExpressionConverter.toExpression(updateExpression)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Attempt to coalesce two expressions with conflicting expression values") .hasMessageContaining(":PRE_attribute1"); } @Test void findAttributeNames_emptyExpression_returnEmptyList() { UpdateExpression updateExpression = UpdateExpression.builder().build(); List<String> attributes = UpdateExpressionConverter.findAttributeNames(updateExpression); assertThat(attributes).isEmpty(); } @Test void findAttributeNames_noComposedNames_noTokens() { UpdateExpression updateExpression = createUpdateExpression(addAction("attribute1", string("val1"), null, VALUE_TOKEN), deleteAction("attribute2", string("val2"), null, VALUE_TOKEN), removeAction("attribute3", null), setAction("attribute4", string("val4"), null, VALUE_TOKEN)); List<String> attributes = UpdateExpressionConverter.findAttributeNames(updateExpression); assertThat(attributes).containsExactlyInAnyOrder("attribute1", "attribute2", "attribute3", "attribute4"); } @Test void findAttributeNames_noComposedNames_tokens() { UpdateExpression updateExpression = createUpdateExpression(addAction("attribute1", string("val1"), KEY_TOKEN, VALUE_TOKEN), deleteAction("attribute2", string("val2"), KEY_TOKEN, VALUE_TOKEN), removeAction("attribute3", KEY_TOKEN), setAction("attribute4", string("val4"), KEY_TOKEN, VALUE_TOKEN)); List<String> attributes = UpdateExpressionConverter.findAttributeNames(updateExpression); assertThat(attributes).containsExactlyInAnyOrder("attribute1", "attribute2", "attribute3", "attribute4"); } @Test void findAttributeNames_noComposedNames_duplicates() { UpdateExpression updateExpression = createUpdateExpression(addAction("attribute1", string("val1"), null, VALUE_TOKEN), deleteAction("attribute1", string("val2"), KEY_TOKEN, VALUE_TOKEN)); List<String> attributes = UpdateExpressionConverter.findAttributeNames(updateExpression); assertThat(attributes).containsExactlyInAnyOrder("attribute1", "attribute1"); } @Test void findAttributeNames_composedNames_noTokens() { UpdateExpression updateExpression = createUpdateExpression(addAction("attribute1.#nested", string("val1"), null, VALUE_TOKEN), deleteAction("attribute2.nested", string("val2"), null, VALUE_TOKEN), removeAction("attribute3[1]", null), setAction("attribute4[1].nested", string("val4"), null, VALUE_TOKEN)); List<String> attributes = UpdateExpressionConverter.findAttributeNames(updateExpression); assertThat(attributes).containsExactlyInAnyOrder("attribute1", "attribute2", "attribute3", "attribute4"); } @Test void findAttributeNames_composedNames_tokens() { UpdateExpression updateExpression = createUpdateExpression(addAction("attribute1.nested[1]", string("val1"), KEY_TOKEN, VALUE_TOKEN), deleteAction("attribute2.nested", string("val2"), KEY_TOKEN, VALUE_TOKEN), removeAction("attribute3[1]", KEY_TOKEN), setAction("attribute4[1].nested", string("val4"), KEY_TOKEN, VALUE_TOKEN)); List<String> attributes = UpdateExpressionConverter.findAttributeNames(updateExpression); assertThat(attributes).containsExactlyInAnyOrder("attribute1", "attribute2", "attribute3", "attribute4"); } @Test void findAttributeNames_composedNames_duplicates() { UpdateExpression updateExpression = createUpdateExpression(addAction("attribute1[1]", string("val1"), null, VALUE_TOKEN), deleteAction("attribute1.nested", string("val2"), KEY_TOKEN, VALUE_TOKEN)); List<String> attributes = UpdateExpressionConverter.findAttributeNames(updateExpression); assertThat(attributes).containsExactlyInAnyOrder("attribute1", "attribute1"); } private static RemoveAction removeAction(String attributeName, String keyToken) { RemoveAction.Builder builder = RemoveAction.builder() .path(attributeName); if (!StringUtils.isEmpty(keyToken)) { builder.path(keyRef(attributeName, keyToken)); builder.putExpressionName(keyRef(attributeName, keyToken), attributeName); } return builder.build(); } private static SetAction setAction(String attributeName, AttributeValue value, String keyToken, String valueToken) { SetAction.Builder builder = SetAction.builder() .path(attributeName) .value(valueRef(attributeName, valueToken)) .putExpressionValue(valueRef(attributeName, valueToken), value); if (!StringUtils.isEmpty(keyToken)) { builder.path(keyRef(attributeName, keyToken)); builder.putExpressionName(keyRef(attributeName, keyToken), attributeName); } return builder.build(); } private static DeleteAction deleteAction(String attributeName, AttributeValue value, String keyToken, String valueToken) { DeleteAction.Builder builder = DeleteAction.builder() .path(attributeName) .value(valueRef(attributeName, valueToken)) .putExpressionValue(valueRef(attributeName, valueToken), value); if (!StringUtils.isEmpty(keyToken)) { builder.path(keyRef(attributeName, keyToken)); builder.putExpressionName(keyRef(attributeName, keyToken), attributeName); } return builder.build(); } private static AddAction addAction(String attributeName, AttributeValue value, String keyToken, String valueToken) { AddAction.Builder builder = AddAction.builder() .path(attributeName) .value(valueRef(attributeName, valueToken)) .putExpressionValue(valueRef(attributeName, valueToken), value); if (!StringUtils.isEmpty(keyToken)) { builder.path(keyRef(attributeName, keyToken)); builder.putExpressionName(keyRef(attributeName, keyToken), attributeName); } return builder.build(); } private UpdateExpression createUpdateExpression(UpdateAction... actions) { return UpdateExpression.builder().actions(actions).build(); } private AttributeValue string(String s) { return AttributeValue.builder().s(s).build(); } private static String keyRef(String key, String token) { return token + key; } private static String valueRef(String value, String valueToken) { return valueToken + value; } }
3,983
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/internal
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/internal/converter/ChainConverterProviderTest.java
package software.amazon.awssdk.enhanced.dynamodb.internal.converter; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import nl.jqno.equalsverifier.EqualsVerifier; 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.AttributeConverterProvider; import software.amazon.awssdk.enhanced.dynamodb.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.extensions.WriteModification; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.StringAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.update.AddAction; import software.amazon.awssdk.enhanced.dynamodb.update.RemoveAction; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; @RunWith(MockitoJUnitRunner.class) public class ChainConverterProviderTest { @Mock private AttributeConverterProvider mockConverterProvider1; @Mock private AttributeConverterProvider mockConverterProvider2; @Mock private AttributeConverter mockAttributeConverter1; @Mock private AttributeConverter mockAttributeConverter2; @Test public void checkSingleProviderChain() { ChainConverterProvider chain = ChainConverterProvider.create(mockConverterProvider1); List providerQueue = chain.chainedProviders(); assertThat(providerQueue.size()).isEqualTo(1); assertThat(providerQueue.get(0)).isEqualTo(mockConverterProvider1); } @Test public void checkMultipleProviderChain() { ChainConverterProvider chain = ChainConverterProvider.create(mockConverterProvider1, mockConverterProvider2); List providerQueue = chain.chainedProviders(); assertThat(providerQueue.size()).isEqualTo(2); assertThat(providerQueue.get(0)).isEqualTo(mockConverterProvider1); assertThat(providerQueue.get(1)).isEqualTo(mockConverterProvider2); } @Test public void resolveSingleProviderChain() { when(mockConverterProvider1.converterFor(any())).thenReturn(mockAttributeConverter1); ChainConverterProvider chain = ChainConverterProvider.create(mockConverterProvider1); assertThat(chain.converterFor(EnhancedType.of(String.class))).isSameAs(mockAttributeConverter1); } @Test public void resolveMultipleProviderChain_noMatch() { ChainConverterProvider chain = ChainConverterProvider.create(mockConverterProvider1, mockConverterProvider2); assertThat(chain.converterFor(EnhancedType.of(String.class))).isNull(); } @Test public void resolveMultipleProviderChain_matchSecond() { when(mockConverterProvider2.converterFor(any())).thenReturn(mockAttributeConverter2); ChainConverterProvider chain = ChainConverterProvider.create(mockConverterProvider1, mockConverterProvider2); assertThat(chain.converterFor(EnhancedType.of(String.class))).isSameAs(mockAttributeConverter2); } @Test public void resolveMultipleProviderChain_matchFirst() { when(mockConverterProvider1.converterFor(any())).thenReturn(mockAttributeConverter1); ChainConverterProvider chain = ChainConverterProvider.create(mockConverterProvider1, mockConverterProvider2); assertThat(chain.converterFor(EnhancedType.of(String.class))).isSameAs(mockAttributeConverter1); } @Test public void equalsHashcode() { EqualsVerifier.forClass(ChainConverterProvider.class) .usingGetClass() .verify(); } }
3,984
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/internal
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/internal/converter/ConverterProviderResolverTest.java
package software.amazon.awssdk.enhanced.dynamodb.internal.converter; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.enhanced.dynamodb.AttributeConverterProvider; import software.amazon.awssdk.enhanced.dynamodb.DefaultAttributeConverterProvider; @RunWith(MockitoJUnitRunner.class) public class ConverterProviderResolverTest { @Mock private AttributeConverterProvider mockConverterProvider1; @Mock private AttributeConverterProvider mockConverterProvider2; @Test public void resolveProviders_null() { assertThat(ConverterProviderResolver.resolveProviders(null)).isNull(); } @Test public void resolveProviders_empty() { assertThat(ConverterProviderResolver.resolveProviders(emptyList())).isNull(); } @Test public void resolveProviders_singleton() { assertThat(ConverterProviderResolver.resolveProviders(singletonList(mockConverterProvider1))) .isSameAs(mockConverterProvider1); } @Test public void resolveProviders_multiple() { AttributeConverterProvider result = ConverterProviderResolver.resolveProviders( Arrays.asList(mockConverterProvider1, mockConverterProvider2)); assertThat(result).isNotNull(); assertThat(result).isInstanceOf(ChainConverterProvider.class); } @Test public void defaultProvider_returnsInstance() { AttributeConverterProvider defaultProvider = ConverterProviderResolver.defaultConverterProvider(); assertThat(defaultProvider).isNotNull(); assertThat(defaultProvider).isInstanceOf(DefaultAttributeConverterProvider.class); } }
3,985
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/internal/converter
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/internal/converter/attribute/OptionalAttributeValueConverterTest.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.internal.converter.attribute; import org.junit.jupiter.api.Test; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; public class OptionalAttributeValueConverterTest { private static final OptionalAttributeConverter<String> CONVERTER = OptionalAttributeConverter.create(StringAttributeConverter.create()); @Test public void testTransformTo_nulPropertyIsNull_doesNotThrowNPE() { AttributeValue av = AttributeValue.builder() .nul(null) .s("foo") .build(); CONVERTER.transformTo(av); } }
3,986
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/internal
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/internal/mapper/MetaTableSchemaCacheTest.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.internal.mapper; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItem; public class MetaTableSchemaCacheTest { private final MetaTableSchemaCache metaTableSchemaCache = new MetaTableSchemaCache(); @Test public void createAndGetSingleEntry() { MetaTableSchema<FakeItem> metaTableSchema = metaTableSchemaCache.getOrCreate(FakeItem.class); assertThat(metaTableSchema).isNotNull(); assertThat(metaTableSchemaCache.get(FakeItem.class)).hasValue(metaTableSchema); } @Test public void getKeyNotInMap() { assertThat(metaTableSchemaCache.get(FakeItem.class)).isNotPresent(); } @Test public void createReturnsExistingObject() { MetaTableSchema<FakeItem> metaTableSchema = metaTableSchemaCache.getOrCreate(FakeItem.class); assertThat(metaTableSchema).isNotNull(); assertThat(metaTableSchemaCache.getOrCreate(FakeItem.class)).isSameAs(metaTableSchema); } }
3,987
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/internal
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/internal/operations/TransactGetItemsOperationTest.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.internal.operations; import static java.util.Collections.emptyMap; import static java.util.Collections.singletonList; import static java.util.stream.Collectors.toList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.sameInstance; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import static software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItem.createUniqueFakeItem; import static software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItemWithSort.createUniqueFakeItemWithSort; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.IntStream; 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.Document; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClientExtension; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.Key; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItem; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItemWithSort; import software.amazon.awssdk.enhanced.dynamodb.internal.DefaultDocument; import software.amazon.awssdk.enhanced.dynamodb.model.TransactGetItemsEnhancedRequest; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.Get; import software.amazon.awssdk.services.dynamodb.model.ItemResponse; import software.amazon.awssdk.services.dynamodb.model.TransactGetItem; import software.amazon.awssdk.services.dynamodb.model.TransactGetItemsRequest; import software.amazon.awssdk.services.dynamodb.model.TransactGetItemsResponse; @RunWith(MockitoJUnitRunner.class) public class TransactGetItemsOperationTest { private static final String TABLE_NAME = "table-name"; private static final String TABLE_NAME_2 = "table-name-2"; private static final List<FakeItem> FAKE_ITEMS = IntStream.range(0, 6).mapToObj($ -> createUniqueFakeItem()).collect(toList()); private static final List<Map<String, AttributeValue>> FAKE_ITEM_MAPS = FAKE_ITEMS.stream() .map(item -> FakeItem.getTableSchema().itemToMap(item, FakeItem.getTableMetadata().primaryKeys())) .collect(toList()); private static final List<Key> FAKE_ITEM_KEYS = FAKE_ITEMS.stream().map(fakeItem -> Key.builder().partitionValue(fakeItem.getId()).build()).collect(toList()); private static final List<FakeItemWithSort> FAKESORT_ITEMS = IntStream.range(0, 6) .mapToObj($ -> createUniqueFakeItemWithSort()).collect(toList()); private static final List<Map<String, AttributeValue>> FAKESORT_ITEM_MAPS = FAKESORT_ITEMS.stream() .map(item -> FakeItemWithSort.getTableSchema() .itemToMap(item, FakeItemWithSort.getTableMetadata().primaryKeys())) .collect(toList()); private static final List<Key> FAKESORT_ITEM_KEYS = FAKESORT_ITEMS.stream() .map(fakeItemWithSort -> Key.builder() .partitionValue(fakeItemWithSort.getId()) .sortValue(fakeItemWithSort.getSort()) .build()) .collect(toList()); @Mock private DynamoDbClient mockDynamoDbClient; @Mock private DynamoDbEnhancedClientExtension mockExtension; private DynamoDbEnhancedClient enhancedClient; private DynamoDbTable<FakeItem> fakeItemMappedTable; private DynamoDbTable<FakeItemWithSort> fakeItemWithSortMappedTable; @Before public void setupMappedTables() { enhancedClient = DynamoDbEnhancedClient.builder().dynamoDbClient(mockDynamoDbClient).extensions().build(); fakeItemMappedTable = enhancedClient.table(TABLE_NAME, FakeItem.getTableSchema()); fakeItemWithSortMappedTable = enhancedClient.table(TABLE_NAME_2, FakeItemWithSort.getTableSchema()); } @Test public void generateRequest_getsFromMultipleTables_usingShortcutForm() { TransactGetItemsEnhancedRequest transactGetItemsEnhancedRequest = TransactGetItemsEnhancedRequest.builder() .addGetItem(fakeItemMappedTable, FAKE_ITEM_KEYS.get(0)) .addGetItem(fakeItemWithSortMappedTable, FAKESORT_ITEM_KEYS.get(0)) .addGetItem(fakeItemWithSortMappedTable, FAKESORT_ITEM_KEYS.get(1)) .addGetItem(fakeItemMappedTable, FAKE_ITEM_KEYS.get(1)) .build(); TransactGetItemsOperation operation = TransactGetItemsOperation.create(transactGetItemsEnhancedRequest); List<TransactGetItem> transactGetItems = Arrays.asList( TransactGetItem.builder().get(Get.builder().tableName(TABLE_NAME).key(FAKE_ITEM_MAPS.get(0)).build()).build(), TransactGetItem.builder().get(Get.builder().tableName(TABLE_NAME_2).key(FAKESORT_ITEM_MAPS.get(0)).build()).build(), TransactGetItem.builder().get(Get.builder().tableName(TABLE_NAME_2).key(FAKESORT_ITEM_MAPS.get(1)).build()).build(), TransactGetItem.builder().get(Get.builder().tableName(TABLE_NAME).key(FAKE_ITEM_MAPS.get(1)).build()).build()); TransactGetItemsRequest expectedRequest = TransactGetItemsRequest.builder() .transactItems(transactGetItems) .build(); TransactGetItemsRequest actualRequest = operation.generateRequest(null); assertThat(actualRequest, is(expectedRequest)); } @Test public void getServiceCall_makesTheRightCallAndReturnsResponse_usingKeyItemForm() { TransactGetItemsEnhancedRequest transactGetItemsEnhancedRequest = TransactGetItemsEnhancedRequest.builder() .addGetItem(fakeItemMappedTable, FAKE_ITEMS.get(0)) .build(); TransactGetItemsOperation operation = TransactGetItemsOperation.create(transactGetItemsEnhancedRequest); TransactGetItem transactGetItem = TransactGetItem.builder().get(Get.builder().tableName(TABLE_NAME).key(FAKE_ITEM_MAPS.get(0)).build()).build(); TransactGetItemsRequest transactGetItemsRequest = TransactGetItemsRequest.builder() .transactItems(singletonList(transactGetItem)) .build(); TransactGetItemsResponse expectedResponse = TransactGetItemsResponse.builder().build(); when(mockDynamoDbClient.transactGetItems(any(TransactGetItemsRequest.class))).thenReturn(expectedResponse); TransactGetItemsResponse response = operation.serviceCall(mockDynamoDbClient).apply(transactGetItemsRequest); assertThat(response, sameInstance(expectedResponse)); verify(mockDynamoDbClient).transactGetItems(transactGetItemsRequest); } @Test public void transformResponse_noExtension_returnsItemsFromDifferentTables() { TransactGetItemsOperation operation = TransactGetItemsOperation.create(emptyRequest()); List<ItemResponse> itemResponses = Arrays.asList( ItemResponse.builder().item(FAKE_ITEM_MAPS.get(0)).build(), ItemResponse.builder().item(FAKESORT_ITEM_MAPS.get(0)).build(), ItemResponse.builder().item(FAKESORT_ITEM_MAPS.get(1)).build(), ItemResponse.builder().item(FAKE_ITEM_MAPS.get(1)).build()); TransactGetItemsResponse response = TransactGetItemsResponse.builder() .responses(itemResponses) .build(); List<Document> result = operation.transformResponse(response, null); assertThat(result, contains(DefaultDocument.create(FAKE_ITEM_MAPS.get(0)), DefaultDocument.create(FAKESORT_ITEM_MAPS.get(0)), DefaultDocument.create(FAKESORT_ITEM_MAPS.get(1)), DefaultDocument.create(FAKE_ITEM_MAPS.get(1)))); } @Test public void transformResponse_doesNotInteractWithExtension() { TransactGetItemsOperation operation = TransactGetItemsOperation.create(emptyRequest()); List<ItemResponse> itemResponses = Arrays.asList( ItemResponse.builder().item(FAKE_ITEM_MAPS.get(0)).build(), ItemResponse.builder().item(FAKESORT_ITEM_MAPS.get(0)).build(), ItemResponse.builder().item(FAKESORT_ITEM_MAPS.get(1)).build(), ItemResponse.builder().item(FAKE_ITEM_MAPS.get(1)).build()); TransactGetItemsResponse response = TransactGetItemsResponse.builder() .responses(itemResponses) .build(); operation.transformResponse(response, mockExtension); verifyNoMoreInteractions(mockExtension); } @Test public void transformResponse_noExtension_returnsNullsAsNulls() { TransactGetItemsOperation operation = TransactGetItemsOperation.create(emptyRequest()); List<ItemResponse> itemResponses = Arrays.asList( ItemResponse.builder().item(FAKE_ITEM_MAPS.get(0)).build(), ItemResponse.builder().item(FAKESORT_ITEM_MAPS.get(0)).build(), null); TransactGetItemsResponse response = TransactGetItemsResponse.builder() .responses(itemResponses) .build(); List<Document> result = operation.transformResponse(response, null); assertThat(result, contains(DefaultDocument.create(FAKE_ITEM_MAPS.get(0)), DefaultDocument.create(FAKESORT_ITEM_MAPS.get(0)), null)); } @Test public void transformResponse_noExtension_returnsEmptyAsNull() { TransactGetItemsOperation operation = TransactGetItemsOperation.create(emptyRequest()); List<ItemResponse> itemResponses = Arrays.asList( ItemResponse.builder().item(FAKE_ITEM_MAPS.get(0)).build(), ItemResponse.builder().item(FAKESORT_ITEM_MAPS.get(0)).build(), ItemResponse.builder().item(emptyMap()).build()); TransactGetItemsResponse response = TransactGetItemsResponse.builder() .responses(itemResponses) .build(); List<Document> result = operation.transformResponse(response, null); assertThat(result, contains(DefaultDocument.create(FAKE_ITEM_MAPS.get(0)), DefaultDocument.create(FAKESORT_ITEM_MAPS.get(0)), DefaultDocument.create(emptyMap()))); } private static TransactGetItemsEnhancedRequest emptyRequest() { return TransactGetItemsEnhancedRequest.builder().build(); } }
3,988
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/internal
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/internal/operations/UpdateItemOperationTest.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.internal.operations; import static java.util.Collections.singletonList; import static java.util.Collections.singletonMap; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.either; import static org.hamcrest.Matchers.hasEntry; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.Matchers.sameInstance; import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItem.createUniqueFakeItem; import static software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItemWithSort.createUniqueFakeItemWithSort; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.numberValue; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.UUID; import java.util.function.Consumer; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClientExtension; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbExtensionContext; 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.extensions.ReadModification; import software.amazon.awssdk.enhanced.dynamodb.extensions.WriteModification; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItem; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItemWithSort; import software.amazon.awssdk.enhanced.dynamodb.internal.extensions.DefaultDynamoDbExtensionContext; import software.amazon.awssdk.enhanced.dynamodb.model.UpdateItemEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.update.DeleteAction; import software.amazon.awssdk.enhanced.dynamodb.update.UpdateExpression; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.ReturnConsumedCapacity; import software.amazon.awssdk.services.dynamodb.model.ReturnItemCollectionMetrics; 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 UpdateItemOperationTest { private static final String TABLE_NAME = "table-name"; private static final String OTHER_ATTRIBUTE_1_NAME = "#AMZN_MAPPED_other_attribute_1"; private static final String OTHER_ATTRIBUTE_2_NAME = "#AMZN_MAPPED_other_attribute_2"; private static final String SUBCLASS_ATTRIBUTE_NAME = "#AMZN_MAPPED_subclass_attribute"; private static final String OTHER_ATTRIBUTE_1_VALUE = ":AMZN_MAPPED_other_attribute_1"; private static final String OTHER_ATTRIBUTE_2_VALUE = ":AMZN_MAPPED_other_attribute_2"; private static final String SUBCLASS_ATTRIBUTE_VALUE = ":AMZN_MAPPED_subclass_attribute"; private static final OperationContext PRIMARY_CONTEXT = DefaultOperationContext.create(TABLE_NAME, TableMetadata.primaryIndexName()); private static final OperationContext GSI_1_CONTEXT = DefaultOperationContext.create(TABLE_NAME, "gsi_1"); private static final Expression CONDITION_EXPRESSION; private static final Expression MINIMAL_CONDITION_EXPRESSION = Expression.builder().expression("foo = bar").build(); private static final Map<String, AttributeValue> EXPRESSION_VALUES; private static final Map<String, String> EXPRESSION_NAMES; static { Map<String, String> expressionNames = new HashMap<>(); expressionNames.put("#test_field_1", "test_field_1"); expressionNames.put("#test_field_2", "test_field_2"); Map<String, AttributeValue> expressionValues = new HashMap<>(); expressionValues.put(":test_value_1", numberValue(1)); expressionValues.put(":test_value_2", numberValue(2)); CONDITION_EXPRESSION = Expression.builder() .expression("#test_field_1 = :test_value_1 OR #test_field_2 = :test_value_2") .expressionNames(Collections.unmodifiableMap(expressionNames)) .expressionValues(Collections.unmodifiableMap(expressionValues)) .build(); EXPRESSION_VALUES = new HashMap<>(); EXPRESSION_VALUES.put(OTHER_ATTRIBUTE_1_VALUE, AttributeValue.builder().s("value-1").build()); EXPRESSION_VALUES.put(OTHER_ATTRIBUTE_2_VALUE, AttributeValue.builder().s("value-2").build()); EXPRESSION_NAMES = new HashMap<>(); EXPRESSION_NAMES.put(OTHER_ATTRIBUTE_1_NAME, "other_attribute_1"); EXPRESSION_NAMES.put(OTHER_ATTRIBUTE_2_NAME, "other_attribute_2"); } @Mock private DynamoDbClient mockDynamoDbClient; @Mock private DynamoDbEnhancedClientExtension mockDynamoDbEnhancedClientExtension; @Test public void getServiceCall_makesTheRightCallAndReturnsResponse() { FakeItem item = createUniqueFakeItem(); UpdateItemOperation<FakeItem> updateItemOperation = UpdateItemOperation.create( UpdateItemEnhancedRequest.builder(FakeItem.class).item(item).build()); UpdateItemRequest updateItemRequest = UpdateItemRequest.builder().tableName(TABLE_NAME).build(); UpdateItemResponse expectedResponse = UpdateItemResponse.builder().build(); when(mockDynamoDbClient.updateItem(any(UpdateItemRequest.class))).thenReturn(expectedResponse); UpdateItemResponse response = updateItemOperation.serviceCall(mockDynamoDbClient).apply(updateItemRequest); assertThat(response, sameInstance(expectedResponse)); verify(mockDynamoDbClient).updateItem(updateItemRequest); } @Test(expected = IllegalArgumentException.class) public void generateRequest_withIndex_throwsIllegalArgumentException() { FakeItem item = createUniqueFakeItem(); UpdateItemOperation<FakeItem> updateItemOperation = UpdateItemOperation.create( UpdateItemEnhancedRequest.builder(FakeItem.class).item(item).build()); updateItemOperation.generateRequest(FakeItem.getTableSchema(), GSI_1_CONTEXT, null); } @Test public void generateRequest_nullValuesNotIgnoredByDefault() { FakeItemWithSort item = createUniqueFakeItemWithSort(); item.setOtherAttribute1("value-1"); UpdateItemOperation<FakeItemWithSort> updateItemOperation = UpdateItemOperation.create(requestFakeItemWithSort(item, b -> { })); UpdateItemRequest request = updateItemOperation.generateRequest(FakeItemWithSort.getTableSchema(), PRIMARY_CONTEXT, null); String expectedUpdateExpression = "SET " + OTHER_ATTRIBUTE_1_NAME + " = " + OTHER_ATTRIBUTE_1_VALUE + " REMOVE " + OTHER_ATTRIBUTE_2_NAME; UpdateItemRequest.Builder expectedRequestBuilder = ddbRequestBuilder(ddbKey(item.getId(), item.getSort())); expectedRequestBuilder.expressionAttributeValues(expressionValuesFor(OTHER_ATTRIBUTE_1_VALUE)); expectedRequestBuilder.expressionAttributeNames(expressionNamesFor(OTHER_ATTRIBUTE_1_NAME, OTHER_ATTRIBUTE_2_NAME)); expectedRequestBuilder.updateExpression(expectedUpdateExpression); assertThat(request, is(expectedRequestBuilder.build())); } @Test public void generateRequest_withConditionExpression() { FakeItemWithSort item = createUniqueFakeItemWithSort(); item.setOtherAttribute1("value-1"); UpdateItemOperation<FakeItemWithSort> updateItemOperation = UpdateItemOperation.create(requestFakeItemWithSort(item, b -> b.conditionExpression(CONDITION_EXPRESSION))); UpdateItemRequest request = updateItemOperation.generateRequest(FakeItemWithSort.getTableSchema(), PRIMARY_CONTEXT, null); String expectedUpdateExpression = "SET " + OTHER_ATTRIBUTE_1_NAME + " = " + OTHER_ATTRIBUTE_1_VALUE + " REMOVE " + OTHER_ATTRIBUTE_2_NAME; UpdateItemRequest.Builder expectedRequestBuilder = ddbRequestBuilder(ddbKey(item.getId(), item.getSort())); expectedRequestBuilder.expressionAttributeValues(expressionValuesFor(CONDITION_EXPRESSION.expressionValues(), OTHER_ATTRIBUTE_1_VALUE)); expectedRequestBuilder.expressionAttributeNames(expressionNamesFor(CONDITION_EXPRESSION.expressionNames(), OTHER_ATTRIBUTE_1_NAME, OTHER_ATTRIBUTE_2_NAME)); expectedRequestBuilder.updateExpression(expectedUpdateExpression); expectedRequestBuilder.conditionExpression(CONDITION_EXPRESSION.expression()); assertThat(request, is(expectedRequestBuilder.build())); } @Test public void generateRequest_withMinimalConditionExpression() { FakeItemWithSort item = createUniqueFakeItemWithSort(); item.setOtherAttribute1("value-1"); UpdateItemOperation<FakeItemWithSort> updateItemOperation = UpdateItemOperation.create(requestFakeItemWithSort(item, b -> b.conditionExpression(MINIMAL_CONDITION_EXPRESSION))); UpdateItemRequest request = updateItemOperation.generateRequest(FakeItemWithSort.getTableSchema(), PRIMARY_CONTEXT, null); assertThat(request.conditionExpression(), is(MINIMAL_CONDITION_EXPRESSION.expression())); assertThat(request.expressionAttributeNames(), is(expressionNamesFor(OTHER_ATTRIBUTE_1_NAME, OTHER_ATTRIBUTE_2_NAME))); assertThat(request.expressionAttributeValues(), is(expressionValuesFor(OTHER_ATTRIBUTE_1_VALUE))); } @Test public void generateRequest_explicitlyUnsetIgnoreNulls() { FakeItemWithSort item = createUniqueFakeItemWithSort(); item.setOtherAttribute1("value-1"); UpdateItemOperation<FakeItemWithSort> updateItemOperation = UpdateItemOperation.create(requestFakeItemWithSort(item, b-> b.ignoreNulls(false))); UpdateItemRequest request = updateItemOperation.generateRequest(FakeItemWithSort.getTableSchema(), PRIMARY_CONTEXT, null); String expectedUpdateExpression = "SET " + OTHER_ATTRIBUTE_1_NAME + " = " + OTHER_ATTRIBUTE_1_VALUE + " REMOVE " + OTHER_ATTRIBUTE_2_NAME; UpdateItemRequest.Builder expectedRequestBuilder = ddbRequestBuilder(ddbKey(item.getId(), item.getSort())); expectedRequestBuilder.expressionAttributeValues(expressionValuesFor(OTHER_ATTRIBUTE_1_VALUE)); expectedRequestBuilder.expressionAttributeNames(expressionNamesFor(OTHER_ATTRIBUTE_1_NAME, OTHER_ATTRIBUTE_2_NAME)); expectedRequestBuilder.updateExpression(expectedUpdateExpression); assertThat(request, is(expectedRequestBuilder.build())); } @Test public void generateRequest_multipleSetters() { FakeItemWithSort item = createUniqueFakeItemWithSort(); item.setOtherAttribute1("value-1"); item.setOtherAttribute2("value-2"); UpdateItemOperation<FakeItemWithSort> updateItemOperation = UpdateItemOperation.create(requestFakeItemWithSort(item, b-> b.ignoreNulls(false))); UpdateItemRequest request = updateItemOperation.generateRequest(FakeItemWithSort.getTableSchema(), PRIMARY_CONTEXT, null); UpdateItemRequest.Builder expectedRequestBuilder = ddbRequestBuilder(ddbKey(item.getId(), item.getSort())); expectedRequestBuilder.expressionAttributeValues(expressionValuesFor(OTHER_ATTRIBUTE_1_VALUE, OTHER_ATTRIBUTE_2_VALUE)); expectedRequestBuilder.expressionAttributeNames(expressionNamesFor(OTHER_ATTRIBUTE_1_NAME, OTHER_ATTRIBUTE_2_NAME)); String updateExpression1 = "SET " + OTHER_ATTRIBUTE_1_NAME + " = " + OTHER_ATTRIBUTE_1_VALUE + ", " + OTHER_ATTRIBUTE_2_NAME + " = " + OTHER_ATTRIBUTE_2_VALUE; UpdateItemRequest expectedRequest1 = expectedRequestBuilder.updateExpression(updateExpression1).build(); String updateExpression2 = "SET " + OTHER_ATTRIBUTE_2_NAME + " = " + OTHER_ATTRIBUTE_2_VALUE + ", " + OTHER_ATTRIBUTE_1_NAME + " = " + OTHER_ATTRIBUTE_1_VALUE; UpdateItemRequest expectedRequest2 = expectedRequestBuilder.updateExpression(updateExpression2).build(); assertThat(request, either(is(expectedRequest1)).or(is(expectedRequest2))); } @Test public void generateRequest_multipleDeletes() { FakeItemWithSort item = createUniqueFakeItemWithSort(); UpdateItemOperation<FakeItemWithSort> updateItemOperation = UpdateItemOperation.create(requestFakeItemWithSort(item, b-> b.ignoreNulls(false))); UpdateItemRequest request = updateItemOperation.generateRequest(FakeItemWithSort.getTableSchema(), PRIMARY_CONTEXT, null); UpdateItemRequest.Builder expectedRequestBuilder = ddbRequestBuilder(ddbKey(item.getId(), item.getSort())); expectedRequestBuilder.expressionAttributeNames(expressionNamesFor(OTHER_ATTRIBUTE_1_NAME, OTHER_ATTRIBUTE_2_NAME)); String updateExpression1 = "REMOVE " + OTHER_ATTRIBUTE_1_NAME + ", " + OTHER_ATTRIBUTE_2_NAME; UpdateItemRequest expectedRequest1 = expectedRequestBuilder.updateExpression(updateExpression1).build(); String updateExpression2 = "REMOVE " + OTHER_ATTRIBUTE_2_NAME + ", " + OTHER_ATTRIBUTE_1_NAME; UpdateItemRequest expectedRequest2 = expectedRequestBuilder.updateExpression(updateExpression2).build(); assertThat(request,either(is(expectedRequest1)).or(is(expectedRequest2))); } @Test public void generateRequest_canIgnoreNullValues() { FakeItemWithSort item = createUniqueFakeItemWithSort(); item.setOtherAttribute1("value-1"); UpdateItemOperation<FakeItemWithSort> updateItemOperation = UpdateItemOperation.create(requestFakeItemWithSort(item, b-> b.ignoreNulls(true))); UpdateItemRequest request = updateItemOperation.generateRequest(FakeItemWithSort.getTableSchema(), PRIMARY_CONTEXT, null); String expectedUpdateExpression = "SET " + OTHER_ATTRIBUTE_1_NAME + " = " + OTHER_ATTRIBUTE_1_VALUE; UpdateItemRequest.Builder expectedRequestBuilder = ddbRequestBuilder(ddbKey(item.getId(), item.getSort())); expectedRequestBuilder.expressionAttributeValues(expressionValuesFor(OTHER_ATTRIBUTE_1_VALUE)); expectedRequestBuilder.expressionAttributeNames(expressionNamesFor(OTHER_ATTRIBUTE_1_NAME)); expectedRequestBuilder.updateExpression(expectedUpdateExpression); UpdateItemRequest expectedRequest = expectedRequestBuilder.build(); assertThat(request, is(expectedRequest)); } @Test public void generateRequest_keyOnlyItem() { FakeItemWithSort item = createUniqueFakeItemWithSort(); UpdateItemOperation<FakeItemWithSort> updateItemOperation = UpdateItemOperation.create(requestFakeItemWithSort(item, b-> b.ignoreNulls(true))); UpdateItemRequest request = updateItemOperation.generateRequest(FakeItemWithSort.getTableSchema(), PRIMARY_CONTEXT, null); UpdateItemRequest expectedRequest = ddbRequestBuilder(ddbKey(item.getId(), item.getSort())).build(); assertThat(request, is(expectedRequest)); } @Test public void generateRequest_withExtension_modifiesKeyPortionOfItem() { FakeItem baseFakeItem = createUniqueFakeItem(); FakeItem fakeItem = createUniqueFakeItem(); Map<String, AttributeValue> baseMap = FakeItem.getTableSchema().itemToMap(baseFakeItem, false); Map<String, AttributeValue> fakeMap = FakeItem.getTableSchema().itemToMap(fakeItem, false); Map<String, AttributeValue> keyMap = FakeItem.getTableSchema().itemToMap(fakeItem, singletonList("id")); when(mockDynamoDbEnhancedClientExtension.beforeWrite(any(DynamoDbExtensionContext.BeforeWrite.class))) .thenReturn(WriteModification.builder().transformedItem(fakeMap).build()); UpdateItemOperation<FakeItem> updateItemOperation = UpdateItemOperation.create(UpdateItemEnhancedRequest.builder(FakeItem.class).item(baseFakeItem).build()); UpdateItemRequest request = updateItemOperation.generateRequest(FakeItem.getTableSchema(), PRIMARY_CONTEXT, mockDynamoDbEnhancedClientExtension); assertThat(request.key(), is(keyMap)); verify(mockDynamoDbEnhancedClientExtension).beforeWrite(extensionContext(baseMap, b -> b.operationName(OperationName.UPDATE_ITEM))); } @Test public void generateRequest_withExtension_transformedItemModifiesUpdateExpression() { FakeItem fakeItem = createUniqueFakeItem(); Map<String, AttributeValue> baseMap = new HashMap<>(FakeItem.getTableSchema().itemToMap(fakeItem, true)); Map<String, AttributeValue> fakeMap = new HashMap<>(baseMap); fakeMap.put("subclass_attribute", AttributeValue.builder().s("1").build()); when(mockDynamoDbEnhancedClientExtension.beforeWrite(any(DynamoDbExtensionContext.BeforeWrite.class))) .thenReturn(WriteModification.builder().transformedItem(fakeMap).build()); UpdateItemOperation<FakeItem> updateItemOperation = UpdateItemOperation.create(requestFakeItem(fakeItem, b -> b.ignoreNulls(true))); UpdateItemRequest request = updateItemOperation.generateRequest(FakeItem.getTableSchema(), PRIMARY_CONTEXT, mockDynamoDbEnhancedClientExtension); assertThat(request.updateExpression(), is("SET " + SUBCLASS_ATTRIBUTE_NAME + " = " + SUBCLASS_ATTRIBUTE_VALUE)); assertThat(request.expressionAttributeValues(), hasEntry(SUBCLASS_ATTRIBUTE_VALUE, AttributeValue.builder().s("1").build())); assertThat(request.expressionAttributeNames(), hasEntry(SUBCLASS_ATTRIBUTE_NAME, "subclass_attribute")); } @Test public void generateRequest_withExtensions_singleCondition() { FakeItem baseFakeItem = createUniqueFakeItem(); FakeItem fakeItem = createUniqueFakeItem(); Map<String, AttributeValue> fakeMap = FakeItem.getTableSchema().itemToMap(fakeItem, true); Expression condition = Expression.builder().expression("condition").expressionValues(fakeMap).build(); when(mockDynamoDbEnhancedClientExtension.beforeWrite(any(DynamoDbExtensionContext.BeforeWrite.class))) .thenReturn(WriteModification.builder().additionalConditionalExpression(condition).build()); UpdateItemOperation<FakeItem> updateItemOperation = UpdateItemOperation.create(requestFakeItem(baseFakeItem, b -> b.ignoreNulls(true))); UpdateItemRequest request = updateItemOperation.generateRequest(FakeItem.getTableSchema(), PRIMARY_CONTEXT, mockDynamoDbEnhancedClientExtension); assertThat(request.conditionExpression(), is("condition")); assertThat(request.expressionAttributeValues(), is(fakeMap)); } @Test public void generateRequest_withExtensions_singleUpdateExpression() { Map<String, AttributeValue> deleteActionMap = singletonMap(":val", AttributeValue.builder().s("s").build()); DeleteAction deleteAction = DeleteAction.builder().path("attr1") .value(":val") .expressionValues(deleteActionMap) .build(); UpdateExpression updateExpression = UpdateExpression.builder().addAction(deleteAction).build(); FakeItem item = createUniqueFakeItem(); when(mockDynamoDbEnhancedClientExtension.beforeWrite(any(DynamoDbExtensionContext.BeforeWrite.class))) .thenReturn(WriteModification.builder().updateExpression(updateExpression).build()); UpdateItemOperation<FakeItem> updateItemOperation = UpdateItemOperation.create(requestFakeItem(item, b -> b.ignoreNulls(true))); UpdateItemRequest request = updateItemOperation.generateRequest(FakeItem.getTableSchema(), PRIMARY_CONTEXT, mockDynamoDbEnhancedClientExtension); assertThat(request.updateExpression(), is("DELETE attr1 :val")); assertThat(request.expressionAttributeValues(), is(deleteActionMap)); } @Test public void generateRequest_withExtensions_conditionAndUpdateExpression() { FakeItem baseFakeItem = createUniqueFakeItem(); FakeItem fakeItem = createUniqueFakeItem(); Map<String, AttributeValue> fakeMap = FakeItem.getTableSchema().itemToMap(fakeItem, true); Expression condition = Expression.builder().expression("condition").expressionValues(fakeMap).build(); Map<String, AttributeValue> deleteActionMap = singletonMap(":val", AttributeValue.builder().s("s").build()); DeleteAction deleteAction = DeleteAction.builder().path("attr1") .value(":val") .expressionValues(deleteActionMap) .build(); UpdateExpression updateExpression = UpdateExpression.builder().addAction(deleteAction).build(); when(mockDynamoDbEnhancedClientExtension.beforeWrite(any(DynamoDbExtensionContext.BeforeWrite.class))) .thenReturn(WriteModification.builder() .additionalConditionalExpression(condition) .updateExpression(updateExpression) .build()); UpdateItemOperation<FakeItem> updateItemOperation = UpdateItemOperation.create(requestFakeItem(baseFakeItem, b -> b.ignoreNulls(true))); UpdateItemRequest request = updateItemOperation.generateRequest(FakeItem.getTableSchema(), PRIMARY_CONTEXT, mockDynamoDbEnhancedClientExtension); assertThat(request.conditionExpression(), is("condition")); assertThat(request.updateExpression(), is("DELETE attr1 :val")); assertThat(request.expressionAttributeValues(), is(Expression.joinValues(fakeMap, deleteActionMap))); } @Test public void generateRequest_withExtensions_conflictingExpressionValue_throwsRuntimeException() { FakeItem baseFakeItem = createUniqueFakeItem(); baseFakeItem.setSubclassAttribute("something"); Map<String, AttributeValue> values = singletonMap(SUBCLASS_ATTRIBUTE_VALUE, AttributeValue.builder().s("1").build()); Expression condition1 = Expression.builder().expression("condition1").expressionValues(values).build(); when(mockDynamoDbEnhancedClientExtension.beforeWrite(any(DynamoDbExtensionContext.BeforeWrite.class))) .thenReturn(WriteModification.builder().additionalConditionalExpression(condition1).build()); UpdateItemOperation<FakeItem> updateItemOperation = UpdateItemOperation.create(requestFakeItem(baseFakeItem, b -> b.ignoreNulls(true))); try { updateItemOperation.generateRequest(FakeItem.getTableSchema(), PRIMARY_CONTEXT, mockDynamoDbEnhancedClientExtension); fail("Exception should be thrown"); } catch (RuntimeException e) { assertThat(e.getMessage(), containsString("subclass_attribute")); } } @Test public void generateRequest_withExtensions_conflictingExpressionName_throwsRuntimeException() { FakeItem baseFakeItem = createUniqueFakeItem(); baseFakeItem.setSubclassAttribute("something"); Map<String, String> names = singletonMap(SUBCLASS_ATTRIBUTE_NAME, "conflict"); Expression condition1 = Expression.builder().expression("condition1").expressionNames(names).build(); when(mockDynamoDbEnhancedClientExtension.beforeWrite(any(DynamoDbExtensionContext.BeforeWrite.class))) .thenReturn(WriteModification.builder().additionalConditionalExpression(condition1).build()); UpdateItemOperation<FakeItem> updateItemOperation = UpdateItemOperation.create(requestFakeItem(baseFakeItem, b -> b.ignoreNulls(true))); try { updateItemOperation.generateRequest(FakeItem.getTableSchema(), PRIMARY_CONTEXT, mockDynamoDbEnhancedClientExtension); fail("Exception should be thrown"); } catch (RuntimeException e) { assertThat(e.getMessage(), containsString("subclass_attribute")); } } @Test public void generateRequest_withExtension_correctlyCoalescesIdenticalExpressionValues() { FakeItem baseFakeItem = createUniqueFakeItem(); baseFakeItem.setSubclassAttribute("something"); Map<String, AttributeValue> values = singletonMap(SUBCLASS_ATTRIBUTE_VALUE, AttributeValue.builder().s("something").build()); Expression condition = Expression.builder().expression("condition").expressionValues(values).build(); when(mockDynamoDbEnhancedClientExtension.beforeWrite(any(DynamoDbExtensionContext.BeforeWrite.class))) .thenReturn(WriteModification.builder().additionalConditionalExpression(condition).build()); UpdateItemOperation<FakeItem> updateItemOperation = UpdateItemOperation.create(requestFakeItem(baseFakeItem, b -> b.ignoreNulls(true))); UpdateItemRequest request = updateItemOperation.generateRequest(FakeItem.getTableSchema(), PRIMARY_CONTEXT, mockDynamoDbEnhancedClientExtension); assertThat(request.expressionAttributeValues(), is(values)); } @Test public void generateRequest_withExtension_correctlyCoalescesIdenticalExpressionNames() { FakeItem baseFakeItem = createUniqueFakeItem(); baseFakeItem.setSubclassAttribute("something"); Map<String, String> names = singletonMap(SUBCLASS_ATTRIBUTE_NAME, "subclass_attribute"); Expression condition = Expression.builder().expression("condition").expressionNames(names).build(); when(mockDynamoDbEnhancedClientExtension.beforeWrite(any(DynamoDbExtensionContext.BeforeWrite.class))) .thenReturn(WriteModification.builder().additionalConditionalExpression(condition).build()); UpdateItemOperation<FakeItem> updateItemOperation = UpdateItemOperation.create(requestFakeItem(baseFakeItem, b -> b.ignoreNulls(true))); UpdateItemRequest request = updateItemOperation.generateRequest(FakeItem.getTableSchema(), PRIMARY_CONTEXT, mockDynamoDbEnhancedClientExtension); assertThat(request.expressionAttributeNames(), is(names)); } @Test public void generateRequest_withExtension_noModifications() { FakeItem baseFakeItem = createUniqueFakeItem(); when(mockDynamoDbEnhancedClientExtension.beforeWrite(any(DynamoDbExtensionContext.BeforeWrite.class))) .thenReturn(WriteModification.builder().build()); UpdateItemOperation<FakeItem> updateItemOperation = UpdateItemOperation.create(requestFakeItem(baseFakeItem, b -> b.ignoreNulls(true))); UpdateItemRequest request = updateItemOperation.generateRequest(FakeItem.getTableSchema(), PRIMARY_CONTEXT, mockDynamoDbEnhancedClientExtension); assertThat(request.conditionExpression(), is(nullValue())); assertThat(request.expressionAttributeValues().size(), is(0)); } @Test public void generateRequest_withExtension_conditionAndModification() { FakeItem baseFakeItem = createUniqueFakeItem(); Map<String, AttributeValue> baseMap = new HashMap<>(FakeItem.getTableSchema().itemToMap(baseFakeItem, true)); Map<String, AttributeValue> fakeMap = new HashMap<>(baseMap); fakeMap.put("subclass_attribute", AttributeValue.builder().s("1").build()); Map<String, AttributeValue> conditionValues = new HashMap<>(); conditionValues.put(":condition_value", AttributeValue.builder().s("2").build()); when(mockDynamoDbEnhancedClientExtension.beforeWrite(any(DynamoDbExtensionContext.BeforeWrite.class))) .thenReturn(WriteModification.builder() .transformedItem(fakeMap) .additionalConditionalExpression(Expression.builder() .expression("condition") .expressionValues(conditionValues) .build()) .build()); UpdateItemOperation<FakeItem> updateItemOperation = UpdateItemOperation.create(requestFakeItem(baseFakeItem, b -> b.ignoreNulls(true))); UpdateItemRequest request = updateItemOperation.generateRequest(FakeItem.getTableSchema(), PRIMARY_CONTEXT, mockDynamoDbEnhancedClientExtension); assertThat(request.updateExpression(), is("SET " + SUBCLASS_ATTRIBUTE_NAME + " = " + SUBCLASS_ATTRIBUTE_VALUE)); assertThat(request.expressionAttributeValues(), hasEntry(SUBCLASS_ATTRIBUTE_VALUE, AttributeValue.builder().s("1").build())); assertThat(request.expressionAttributeValues(), hasEntry(":condition_value", AttributeValue.builder().s("2").build())); assertThat(request.expressionAttributeNames(), hasEntry(SUBCLASS_ATTRIBUTE_NAME, "subclass_attribute")); } @Test public void generateRequest_withReturnConsumedCapacity_unknownValue_generatesCorrectRequest() { FakeItem item = createUniqueFakeItem(); String returnConsumedCapacity = UUID.randomUUID().toString(); UpdateItemOperation<FakeItem> updateItemOperation = UpdateItemOperation.create(requestFakeItem(item, b -> b.ignoreNulls(true) .returnConsumedCapacity(returnConsumedCapacity))); UpdateItemRequest request = updateItemOperation.generateRequest(FakeItem.getTableSchema(), PRIMARY_CONTEXT, null); UpdateItemRequest expectedRequest = ddbRequest(ddbKey(item.getId()), b -> b.returnConsumedCapacity(returnConsumedCapacity)); assertThat(request, is(expectedRequest)); } @Test public void generateRequest_withReturnConsumedCapacity_knownValue_generatesCorrectRequest() { FakeItem item = createUniqueFakeItem(); ReturnConsumedCapacity returnConsumedCapacity = ReturnConsumedCapacity.TOTAL; UpdateItemOperation<FakeItem> updateItemOperation = UpdateItemOperation.create(requestFakeItem(item, b -> b.ignoreNulls(true) .returnConsumedCapacity(returnConsumedCapacity))); UpdateItemRequest request = updateItemOperation.generateRequest(FakeItem.getTableSchema(), PRIMARY_CONTEXT, null); UpdateItemRequest expectedRequest = ddbRequest(ddbKey(item.getId()), b -> b.returnConsumedCapacity(returnConsumedCapacity)); assertThat(request, is(expectedRequest)); } @Test public void generateRequest_withReturnItemCollectionMetrics_unknownValue_generatesCorrectRequest() { FakeItem item = createUniqueFakeItem(); String returnItemCollectionMetrics = UUID.randomUUID().toString(); UpdateItemOperation<FakeItem> updateItemOperation = UpdateItemOperation.create(requestFakeItem(item, b -> b.ignoreNulls(true) .returnItemCollectionMetrics(returnItemCollectionMetrics))); UpdateItemRequest request = updateItemOperation.generateRequest(FakeItem.getTableSchema(), PRIMARY_CONTEXT, null); UpdateItemRequest expectedRequest = ddbRequest(ddbKey(item.getId()), b -> b.returnItemCollectionMetrics(returnItemCollectionMetrics)); assertThat(request, is(expectedRequest)); } @Test public void generateRequest_withReturnItemCollectionMetrics_knownValue_generatesCorrectRequest() { FakeItem item = createUniqueFakeItem(); ReturnItemCollectionMetrics returnItemCollectionMetrics = ReturnItemCollectionMetrics.SIZE; UpdateItemOperation<FakeItem> updateItemOperation = UpdateItemOperation.create(requestFakeItem(item, b -> b.ignoreNulls(true) .returnItemCollectionMetrics(returnItemCollectionMetrics))); UpdateItemRequest request = updateItemOperation.generateRequest(FakeItem.getTableSchema(), PRIMARY_CONTEXT, null); UpdateItemRequest expectedRequest = ddbRequest(ddbKey(item.getId()), b -> b.returnItemCollectionMetrics(returnItemCollectionMetrics)); assertThat(request, is(expectedRequest)); } @Test public void transformResponse_withExtension_returnsCorrectTransformedItem() { FakeItem baseFakeItem = createUniqueFakeItem(); FakeItem fakeItem = createUniqueFakeItem(); Map<String, AttributeValue> baseFakeMap = FakeItem.getTableSchema().itemToMap(baseFakeItem, true); Map<String, AttributeValue> fakeMap = FakeItem.getTableSchema().itemToMap(fakeItem, true); when(mockDynamoDbEnhancedClientExtension.afterRead(any(DynamoDbExtensionContext.AfterRead.class))).thenReturn( ReadModification.builder().transformedItem(fakeMap).build()); FakeItem resultItem = transformResponse(baseFakeItem); assertThat(resultItem, is(fakeItem)); verify(mockDynamoDbEnhancedClientExtension).afterRead(extensionContext(baseFakeMap)); } @Test public void transformResponse_withNoOpExtension_returnsCorrectItem() { when(mockDynamoDbEnhancedClientExtension.afterRead(any(DynamoDbExtensionContext.AfterRead.class))) .thenReturn(ReadModification.builder().build()); FakeItem baseFakeItem = createUniqueFakeItem(); Map<String, AttributeValue> baseFakeMap = FakeItem.getTableSchema().itemToMap(baseFakeItem, true); FakeItem resultItem = transformResponse(baseFakeItem); assertThat(resultItem, is(baseFakeItem)); verify(mockDynamoDbEnhancedClientExtension).afterRead(extensionContext(baseFakeMap)); } @Test(expected = IllegalStateException.class) public void transformResponse_afterReadThrowsException_throwsIllegalStateException() { when(mockDynamoDbEnhancedClientExtension.afterRead(any(DynamoDbExtensionContext.AfterRead.class))) .thenThrow(RuntimeException.class); transformResponse(createUniqueFakeItem()); } private Map<String, AttributeValue> ddbKey(String partitionKey) { return singletonMap("id", AttributeValue.builder().s(partitionKey).build()); } private Map<String, AttributeValue> ddbKey(String partitionKey, String sortKey) { Map<String, AttributeValue> expectedKey = new HashMap<>(); expectedKey.put("id", AttributeValue.builder().s(partitionKey).build()); expectedKey.put("sort", AttributeValue.builder().s(sortKey).build()); return expectedKey; } private UpdateItemRequest ddbRequest(Map<String, AttributeValue> keys, Consumer<UpdateItemRequest.Builder> modify) { UpdateItemRequest.Builder builder = ddbBaseRequestBuilder(keys); modify.accept(builder); return builder.build(); } private UpdateItemRequest.Builder ddbRequestBuilder(Map<String, AttributeValue> keys) { return ddbBaseRequestBuilder(keys); } private UpdateItemRequest.Builder ddbBaseRequestBuilder(Map<String, AttributeValue> keys) { return UpdateItemRequest.builder().tableName(TABLE_NAME) .key(keys) .returnValues(ReturnValue.ALL_NEW); } private static Map<String, AttributeValue> expressionValuesFor(Map<String, AttributeValue> initValues, String... tokens) { Map<String, AttributeValue> expressionValues = new HashMap<>(initValues); expressionValues.putAll(expressionValuesFor(tokens)); return expressionValues; } private static Map<String, AttributeValue> expressionValuesFor(String... tokens) { return Stream.of(tokens).collect(Collectors.toMap(String::toString, EXPRESSION_VALUES::get)); } private static Map<String, String> expressionNamesFor(Map<String, String> initValues, String... tokens) { Map<String, String> expressionNames = new HashMap<>(initValues); expressionNames.putAll(expressionNamesFor(tokens)); return expressionNames; } private static Map<String, String> expressionNamesFor(String... tokens) { return Stream.of(tokens).collect(Collectors.toMap(String::toString, EXPRESSION_NAMES::get)); } private UpdateItemEnhancedRequest<FakeItem> requestFakeItem( FakeItem item, Consumer<UpdateItemEnhancedRequest.Builder<FakeItem>> modify) { UpdateItemEnhancedRequest.Builder<FakeItem> builder = UpdateItemEnhancedRequest.builder(FakeItem.class).item(item); modify.accept(builder); return builder.build(); } private UpdateItemEnhancedRequest<FakeItemWithSort> requestFakeItemWithSort( FakeItemWithSort item, Consumer<UpdateItemEnhancedRequest.Builder<FakeItemWithSort>> modify) { UpdateItemEnhancedRequest.Builder<FakeItemWithSort> builder = UpdateItemEnhancedRequest.builder(FakeItemWithSort.class) .item(item); modify.accept(builder); return builder.build(); } private DefaultDynamoDbExtensionContext extensionContext(Map<String, AttributeValue> fakeMap) { return extensionContext(fakeMap, b -> {}); } private DefaultDynamoDbExtensionContext extensionContext(Map<String, AttributeValue> fakeMap, Consumer<DefaultDynamoDbExtensionContext.Builder> modify) { DefaultDynamoDbExtensionContext.Builder builder = DefaultDynamoDbExtensionContext.builder() .tableMetadata(FakeItem.getTableMetadata()) .tableSchema(FakeItem.getTableSchema()) .operationContext(PRIMARY_CONTEXT) .items(fakeMap); modify.accept(builder); return builder.build(); } private FakeItem transformResponse(FakeItem item) { UpdateItemOperation<FakeItem> updateItemOperation = UpdateItemOperation.create(requestFakeItem(item, b -> b.ignoreNulls(true))); Map<String, AttributeValue> itemMap = FakeItem.getTableSchema().itemToMap(item, true); return updateItemOperation.transformResponse(UpdateItemResponse.builder().attributes(itemMap).build(), FakeItem.getTableSchema(), PRIMARY_CONTEXT, mockDynamoDbEnhancedClientExtension).attributes(); } }
3,989
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/internal
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/internal/operations/TableOperationTest.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.internal.operations; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.sameInstance; import static org.junit.Assert.assertThat; import java.util.concurrent.CompletableFuture; 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.DynamoDbEnhancedClientExtension; 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.functionaltests.models.FakeItem; import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; @RunWith(MockitoJUnitRunner.class) public class TableOperationTest { private static final String FAKE_RESULT = "fake-result"; private static final String FAKE_TABLE_NAME = "fake-table-name"; private final FakeTableOperation fakeTableOperation = new FakeTableOperation(); @Mock private DynamoDbEnhancedClientExtension mockDynamoDbEnhancedClientExtension; @Mock private DynamoDbClient mockDynamoDbClient; @Test public void executeOnPrimaryIndex_defaultImplementation_callsExecuteCorrectly() { fakeTableOperation.executeOnPrimaryIndex(FakeItem.getTableSchema(), FAKE_TABLE_NAME, mockDynamoDbEnhancedClientExtension, mockDynamoDbClient); assertThat(fakeTableOperation.lastDynamoDbClient, sameInstance(mockDynamoDbClient)); assertThat(fakeTableOperation.lastDynamoDbEnhancedClientExtension, sameInstance(mockDynamoDbEnhancedClientExtension)); assertThat(fakeTableOperation.lastTableSchema, sameInstance(FakeItem.getTableSchema())); assertThat(fakeTableOperation.lastOperationContext, is( DefaultOperationContext.create(FAKE_TABLE_NAME, TableMetadata.primaryIndexName()))); } private static class FakeTableOperation implements TableOperation<FakeItem, String, String, String> { private TableSchema<FakeItem> lastTableSchema = null; private OperationContext lastOperationContext = null; private DynamoDbEnhancedClientExtension lastDynamoDbEnhancedClientExtension = null; private DynamoDbClient lastDynamoDbClient = null; @Override public OperationName operationName() { return OperationName.NONE; } @Override public String generateRequest(TableSchema<FakeItem> tableSchema, OperationContext context, DynamoDbEnhancedClientExtension extension) { return null; } @Override public Function<String, String> serviceCall(DynamoDbClient dynamoDbClient) { return null; } @Override public Function<String, CompletableFuture<String>> asyncServiceCall(DynamoDbAsyncClient dynamoDbAsyncClient) { return null; } @Override public String transformResponse(String response, TableSchema<FakeItem> tableSchema, OperationContext context, DynamoDbEnhancedClientExtension extension) { return null; } @Override public String execute(TableSchema<FakeItem> tableSchema, OperationContext context, DynamoDbEnhancedClientExtension extension, DynamoDbClient dynamoDbClient) { lastTableSchema = tableSchema; lastOperationContext = context; lastDynamoDbEnhancedClientExtension = extension; lastDynamoDbClient = dynamoDbClient; return FAKE_RESULT; } } }
3,990
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/internal
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/internal/operations/QueryOperationConditionalTest.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.internal.operations; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasEntry; import static org.hamcrest.Matchers.is; import static software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItem.createUniqueFakeItem; import static software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItemWithSort.createUniqueFakeItemWithSort; import static software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItemWithSort.createUniqueFakeItemWithoutSort; import java.util.UUID; import org.junit.Test; 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.functionaltests.models.FakeItem; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItemWithNumericSort; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItemWithSort; import software.amazon.awssdk.enhanced.dynamodb.internal.EnhancedClientUtils; import software.amazon.awssdk.enhanced.dynamodb.model.QueryConditional; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; public class QueryOperationConditionalTest { private static final String ID_KEY = "#AMZN_MAPPED_id"; private static final String ID_VALUE = ":AMZN_MAPPED_id"; private static final String SORT_KEY = "#AMZN_MAPPED_sort"; private static final String SORT_VALUE = ":AMZN_MAPPED_sort"; private static final String SORT_OTHER_VALUE = ":AMZN_MAPPED_sort2"; private final FakeItem fakeItem = createUniqueFakeItem(); private final AttributeValue fakeItemHashValue = AttributeValue.builder().s(fakeItem.getId()).build(); private final FakeItemWithSort fakeItemWithSort = createUniqueFakeItemWithSort(); private final AttributeValue fakeItemWithSortHashValue = AttributeValue.builder().s(fakeItemWithSort.getId()).build(); private final AttributeValue fakeItemWithSortSortValue = AttributeValue.builder().s(fakeItemWithSort.getSort()).build(); private final FakeItemWithSort fakeItemWithoutSort = createUniqueFakeItemWithoutSort(); private final AttributeValue fakeItemWithoutSortHashValue = AttributeValue.builder().s(fakeItemWithoutSort.getId()).build(); @Test public void equalTo_hashOnly() { Expression expression = QueryConditional.keyEqualTo(getKey(fakeItem)).expression(FakeItem.getTableSchema(), TableMetadata.primaryIndexName()); assertThat(expression.expression(), is(ID_KEY + " = " + ID_VALUE)); assertThat(expression.expressionNames(), hasEntry(ID_KEY, "id")); assertThat(expression.expressionValues(), hasEntry(ID_VALUE, fakeItemHashValue)); } @Test(expected = IllegalArgumentException.class) public void equalTo_hashOnly_notSet_throwsIllegalArgumentException() { fakeItem.setId(null); QueryConditional.keyEqualTo(getKey(fakeItem)) .expression(FakeItem.getTableSchema(), TableMetadata.primaryIndexName()); } @Test public void equalTo_hashAndRangeKey_bothSet() { Expression expression = QueryConditional.keyEqualTo(getKey(fakeItemWithSort)) .expression(FakeItemWithSort.getTableSchema(), TableMetadata.primaryIndexName()); verifyExpression(expression, "="); } @Test(expected = IllegalArgumentException.class) public void equalTo_hashAndRangeKey_hashNotSet_throwsIllegalArgumentException() { fakeItemWithSort.setId(null); QueryConditional.keyEqualTo(getKey(fakeItemWithSort)) .expression(FakeItemWithSort.getTableSchema(), TableMetadata.primaryIndexName()); } @Test public void equalTo_hashAndRangeKey_hashOnlySet() { Expression expression = QueryConditional.keyEqualTo(getKey(fakeItemWithoutSort)) .expression(FakeItemWithSort.getTableSchema(), TableMetadata.primaryIndexName()); assertThat(expression.expression(), is(ID_KEY + " = " + ID_VALUE)); assertThat(expression.expressionNames(), hasEntry(ID_KEY, "id")); assertThat(expression.expressionValues(), hasEntry(ID_VALUE, fakeItemWithoutSortHashValue)); } @Test public void greaterThan_hashAndRangeKey_bothSet() { Expression expression = QueryConditional.sortGreaterThan(getKey(fakeItemWithSort)) .expression(FakeItemWithSort.getTableSchema(), TableMetadata.primaryIndexName()); verifyExpression(expression, ">"); } @Test(expected = IllegalArgumentException.class) public void greaterThan_hashOnly_throwsIllegalArgumentException() { QueryConditional.sortGreaterThan(getKey(fakeItem)) .expression(FakeItem.getTableSchema(), TableMetadata.primaryIndexName()); } @Test(expected = IllegalArgumentException.class) public void greaterThan_hashAndSort_onlyHashSet_throwsIllegalArgumentException() { QueryConditional.sortGreaterThan(getKey(fakeItemWithoutSort)) .expression(FakeItemWithSort.getTableSchema(), TableMetadata.primaryIndexName()); } @Test public void greaterThanOrEqualTo_hashAndRangeKey_bothSet() { Expression expression = QueryConditional.sortGreaterThanOrEqualTo(getKey(fakeItemWithSort)) .expression(FakeItemWithSort.getTableSchema(), TableMetadata.primaryIndexName()); verifyExpression(expression, ">="); } @Test(expected = IllegalArgumentException.class) public void greaterThanOrEqualTo_hashOnly_throwsIllegalArgumentException() { QueryConditional.sortGreaterThanOrEqualTo(getKey(fakeItem)) .expression(FakeItem.getTableSchema(), TableMetadata.primaryIndexName()); } @Test(expected = IllegalArgumentException.class) public void greaterThanOrEqualTo_hashAndSort_onlyHashSet_throwsIllegalArgumentException() { QueryConditional.sortGreaterThanOrEqualTo(getKey(fakeItemWithoutSort)) .expression(FakeItemWithSort.getTableSchema(), TableMetadata.primaryIndexName()); } @Test public void lessThan_hashAndRangeKey_bothSet() { Expression expression = QueryConditional.sortLessThan(getKey(fakeItemWithSort)) .expression(FakeItemWithSort.getTableSchema(), TableMetadata.primaryIndexName()); verifyExpression(expression, "<"); } @Test(expected = IllegalArgumentException.class) public void lessThan_hashOnly_throwsIllegalArgumentException() { QueryConditional.sortLessThan(getKey(fakeItem)) .expression(FakeItem.getTableSchema(), TableMetadata.primaryIndexName()); } @Test(expected = IllegalArgumentException.class) public void lessThan_hashAndSort_onlyHashSet_throwsIllegalArgumentException() { QueryConditional.sortLessThan(getKey(fakeItemWithoutSort)) .expression(FakeItemWithSort.getTableSchema(), TableMetadata.primaryIndexName()); } @Test public void lessThanOrEqualTo_hashAndRangeKey_bothSet() { Expression expression = QueryConditional.sortLessThanOrEqualTo(getKey(fakeItemWithSort)) .expression(FakeItemWithSort.getTableSchema(), TableMetadata.primaryIndexName()); verifyExpression(expression, "<="); } @Test(expected = IllegalArgumentException.class) public void lessThanOrEqualTo_hashOnly_throwsIllegalArgumentException() { QueryConditional.sortLessThanOrEqualTo(getKey(fakeItem)) .expression(FakeItem.getTableSchema(), TableMetadata.primaryIndexName()); } @Test(expected = IllegalArgumentException.class) public void lessThanOrEqualTo_hashAndSort_onlyHashSet_throwsIllegalArgumentException() { QueryConditional.sortLessThanOrEqualTo(getKey(fakeItemWithoutSort)) .expression(FakeItemWithSort.getTableSchema(), TableMetadata.primaryIndexName()); } @Test public void beginsWith_hashAndRangeKey_bothSet() { Expression expression = QueryConditional.sortBeginsWith(getKey(fakeItemWithSort)) .expression(FakeItemWithSort.getTableSchema(), TableMetadata.primaryIndexName()); String expectedExpression = String.format("%s = %s AND begins_with ( %s, %s )", ID_KEY, ID_VALUE, SORT_KEY, SORT_VALUE); assertThat(expression.expression(), is(expectedExpression)); assertThat(expression.expressionValues(), hasEntry(ID_VALUE, fakeItemWithSortHashValue)); assertThat(expression.expressionValues(), hasEntry(SORT_VALUE, fakeItemWithSortSortValue)); assertThat(expression.expressionNames(), hasEntry(ID_KEY, "id")); assertThat(expression.expressionNames(), hasEntry(SORT_KEY, "sort")); } @Test(expected = IllegalArgumentException.class) public void beginsWith_hashOnly_throwsIllegalArgumentException() { QueryConditional.sortBeginsWith(getKey(fakeItem)) .expression(FakeItem.getTableSchema(), TableMetadata.primaryIndexName()); } @Test(expected = IllegalArgumentException.class) public void beginsWith_hashAndSort_onlyHashSet_throwsIllegalArgumentException() { QueryConditional.sortBeginsWith(getKey(fakeItemWithoutSort)) .expression(FakeItemWithSort.getTableSchema(), TableMetadata.primaryIndexName()); } @Test(expected = IllegalArgumentException.class) public void beginsWith_numericRange_throwsIllegalArgumentException() { FakeItemWithNumericSort fakeItemWithNumericSort = FakeItemWithNumericSort.createUniqueFakeItemWithSort(); QueryConditional.sortBeginsWith(getKey(fakeItemWithNumericSort)).expression(FakeItemWithNumericSort.getTableSchema(), TableMetadata.primaryIndexName()); } @Test public void between_allKeysSet_stringSort() { FakeItemWithSort otherFakeItemWithSort = FakeItemWithSort.builder().id(fakeItemWithSort.getId()).sort(UUID.randomUUID().toString()).build(); AttributeValue otherFakeItemWithSortSortValue = AttributeValue.builder().s(otherFakeItemWithSort.getSort()).build(); Expression expression = QueryConditional.sortBetween(getKey(fakeItemWithSort), getKey(otherFakeItemWithSort)) .expression(FakeItemWithSort.getTableSchema(), TableMetadata.primaryIndexName()); String expectedExpression = String.format("%s = %s AND %s BETWEEN %s AND %s", ID_KEY, ID_VALUE, SORT_KEY, SORT_VALUE, SORT_OTHER_VALUE); assertThat(expression.expression(), is(expectedExpression)); assertThat(expression.expressionValues(), hasEntry(ID_VALUE, fakeItemWithSortHashValue)); assertThat(expression.expressionValues(), hasEntry(SORT_VALUE, fakeItemWithSortSortValue)); assertThat(expression.expressionValues(), hasEntry(SORT_OTHER_VALUE, otherFakeItemWithSortSortValue)); assertThat(expression.expressionNames(), hasEntry(ID_KEY, "id")); assertThat(expression.expressionNames(), hasEntry(SORT_KEY, "sort")); } @Test(expected = IllegalArgumentException.class) public void between_hashOnly_throwsIllegalArgumentException() { FakeItem otherFakeItem = createUniqueFakeItem(); QueryConditional.sortBetween(getKey(fakeItem), getKey(otherFakeItem)) .expression(FakeItem.getTableSchema(), TableMetadata.primaryIndexName()); } @Test(expected = IllegalArgumentException.class) public void between_hashAndSort_onlyFirstSortSet_throwsIllegalArgumentException() { QueryConditional.sortBetween(getKey(fakeItemWithSort), getKey(fakeItemWithoutSort)) .expression(FakeItemWithSort.getTableSchema(), TableMetadata.primaryIndexName()); } @Test(expected = IllegalArgumentException.class) public void between_hashAndSort_onlySecondSortSet_throwsIllegalArgumentException() { QueryConditional.sortBetween(getKey(fakeItemWithoutSort), getKey(fakeItemWithSort)) .expression(FakeItemWithSort.getTableSchema(), TableMetadata.primaryIndexName()); } private void verifyExpression(Expression expression, String condition) { assertThat(expression.expression(), is(ID_KEY + " = " + ID_VALUE + " AND " + SORT_KEY + " " + condition + " " + SORT_VALUE)); assertThat(expression.expressionNames(), hasEntry(ID_KEY, "id")); assertThat(expression.expressionNames(), hasEntry(SORT_KEY, "sort")); assertThat(expression.expressionValues(), hasEntry(ID_VALUE, fakeItemWithSortHashValue)); assertThat(expression.expressionValues(), hasEntry(SORT_VALUE, fakeItemWithSortSortValue)); } private Key getKey(FakeItem item) { return EnhancedClientUtils.createKeyFromItem(item, FakeItem.getTableSchema(), TableMetadata.primaryIndexName()); } private Key getKey(FakeItemWithSort item) { return EnhancedClientUtils.createKeyFromItem(item, FakeItemWithSort.getTableSchema(), TableMetadata.primaryIndexName()); } private Key getKey(FakeItemWithNumericSort item) { return EnhancedClientUtils.createKeyFromItem(item, FakeItemWithNumericSort.getTableSchema(), TableMetadata.primaryIndexName()); } }
3,991
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/internal
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/internal/operations/QueryOperationTest.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.internal.operations; import static java.util.Collections.singletonMap; import static java.util.stream.Collectors.toList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasEntry; import static org.hamcrest.Matchers.is; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItem.createUniqueFakeItem; import static software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItemWithIndices.createUniqueFakeItemWithIndices; import static software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItemWithSort.createUniqueFakeItemWithSort; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.stringValue; import static software.amazon.awssdk.enhanced.dynamodb.model.QueryConditional.keyEqualTo; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.core.async.SdkPublisher; import software.amazon.awssdk.core.pagination.sync.SdkIterable; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClientExtension; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbExtensionContext; 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.extensions.ReadModification; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItem; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItemWithIndices; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItemWithSort; import software.amazon.awssdk.enhanced.dynamodb.internal.extensions.DefaultDynamoDbExtensionContext; 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.DynamoDbAsyncClient; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.QueryRequest; import software.amazon.awssdk.services.dynamodb.model.QueryResponse; import software.amazon.awssdk.services.dynamodb.paginators.QueryIterable; import software.amazon.awssdk.services.dynamodb.paginators.QueryPublisher; @RunWith(MockitoJUnitRunner.class) public class QueryOperationTest { private static final String TABLE_NAME = "table-name"; private static final OperationContext PRIMARY_CONTEXT = DefaultOperationContext.create(TABLE_NAME, TableMetadata.primaryIndexName()); private static final OperationContext GSI_1_CONTEXT = DefaultOperationContext.create(TABLE_NAME, "gsi_1"); private final FakeItem keyItem = createUniqueFakeItem(); private final QueryOperation<FakeItem> queryOperation = QueryOperation.create(QueryEnhancedRequest.builder() .queryConditional(keyEqualTo(k -> k.partitionValue(keyItem.getId()))) .build()); @Mock private DynamoDbClient mockDynamoDbClient; @Mock private DynamoDbAsyncClient mockDynamoDbAsyncClient; @Mock private QueryConditional mockQueryConditional; @Mock private DynamoDbEnhancedClientExtension mockDynamoDbEnhancedClientExtension; @Test public void getServiceCall_makesTheRightCallAndReturnsResponse() { QueryRequest queryRequest = QueryRequest.builder().build(); QueryIterable mockQueryIterable = mock(QueryIterable.class); when(mockDynamoDbClient.queryPaginator(any(QueryRequest.class))).thenReturn(mockQueryIterable); SdkIterable<QueryResponse> response = queryOperation.serviceCall(mockDynamoDbClient).apply(queryRequest); assertThat(response, is(mockQueryIterable)); verify(mockDynamoDbClient).queryPaginator(queryRequest); } @Test public void getAsyncServiceCall_makesTheRightCallAndReturnsResponse() { QueryRequest queryRequest = QueryRequest.builder().build(); QueryPublisher mockQueryPublisher = mock(QueryPublisher.class); when(mockDynamoDbAsyncClient.queryPaginator(any(QueryRequest.class))).thenReturn(mockQueryPublisher); SdkPublisher<QueryResponse> response = queryOperation.asyncServiceCall(mockDynamoDbAsyncClient).apply(queryRequest); assertThat(response, is(mockQueryPublisher)); verify(mockDynamoDbAsyncClient).queryPaginator(queryRequest); } @Test public void generateRequest_nonDefault_usesQueryConditional() { Map<String, AttributeValue> keyItemMap = getAttributeValueMap(keyItem); Expression expression = Expression.builder().expression("test-expression").expressionValues(keyItemMap).build(); when(mockQueryConditional.expression(any(), anyString())).thenReturn(expression); QueryOperation<FakeItem> query = QueryOperation.create(QueryEnhancedRequest.builder() .queryConditional(mockQueryConditional) .build()); QueryRequest queryRequest = query.generateRequest(FakeItem.getTableSchema(), PRIMARY_CONTEXT, null); QueryRequest expectedQueryRequest = QueryRequest.builder() .tableName(TABLE_NAME) .keyConditionExpression("test-expression") .expressionAttributeValues(keyItemMap) .build(); assertThat(queryRequest, is(expectedQueryRequest)); verify(mockQueryConditional).expression(FakeItem.getTableSchema(), TableMetadata.primaryIndexName()); } @Test public void generateRequest_defaultQuery_usesEqualTo() { QueryRequest queryRequest = queryOperation.generateRequest(FakeItem.getTableSchema(), PRIMARY_CONTEXT, null); QueryRequest expectedQueryRequest = QueryRequest.builder() .tableName(TABLE_NAME) .keyConditionExpression("#AMZN_MAPPED_id = :AMZN_MAPPED_id") .expressionAttributeValues(singletonMap(":AMZN_MAPPED_id", AttributeValue.builder().s(keyItem.getId()).build())) .expressionAttributeNames(singletonMap("#AMZN_MAPPED_id", "id")) .build(); assertThat(queryRequest, is(expectedQueryRequest)); } @Test public void generateRequest_knowsHowToUseAnIndex() { FakeItemWithIndices fakeItem = createUniqueFakeItemWithIndices(); QueryOperation<FakeItemWithIndices> queryToTest = QueryOperation.create(QueryEnhancedRequest.builder() .queryConditional(keyEqualTo(k -> k.partitionValue(fakeItem.getGsiId()))) .build()); QueryRequest queryRequest = queryToTest.generateRequest(FakeItemWithIndices.getTableSchema(), GSI_1_CONTEXT, null); assertThat(queryRequest.indexName(), is("gsi_1")); } @Test public void generateRequest_ascending() { QueryOperation<FakeItem> queryToTest = QueryOperation.create(QueryEnhancedRequest.builder() .queryConditional(keyEqualTo(k -> k.partitionValue(keyItem.getId()))) .scanIndexForward(true) .build()); QueryRequest queryRequest = queryToTest.generateRequest(FakeItem.getTableSchema(), PRIMARY_CONTEXT, null); assertThat(queryRequest.scanIndexForward(), is(true)); } @Test public void generateRequest_descending() { QueryOperation<FakeItem> queryToTest = QueryOperation.create(QueryEnhancedRequest.builder() .queryConditional(keyEqualTo(k -> k.partitionValue(keyItem.getId()))) .scanIndexForward(false) .build()); QueryRequest queryRequest = queryToTest.generateRequest(FakeItem.getTableSchema(), PRIMARY_CONTEXT, null); assertThat(queryRequest.scanIndexForward(), is(false)); } @Test public void generateRequest_limit() { QueryOperation<FakeItem> queryToTest = QueryOperation.create(QueryEnhancedRequest.builder() .queryConditional(keyEqualTo(k -> k.partitionValue(keyItem.getId()))) .limit(123) .build()); QueryRequest queryRequest = queryToTest.generateRequest(FakeItem.getTableSchema(), PRIMARY_CONTEXT, null); assertThat(queryRequest.limit(), is(123)); } @Test public void generateRequest_filterExpression_withValues() { Map<String, AttributeValue> expressionValues = singletonMap(":test-key", stringValue("test-value")); Expression filterExpression = Expression.builder() .expression("test-expression") .expressionValues(expressionValues) .build(); QueryOperation<FakeItem> queryToTest = QueryOperation.create(QueryEnhancedRequest.builder() .queryConditional(keyEqualTo(k -> k.partitionValue(keyItem.getId()))) .filterExpression(filterExpression) .build()); QueryRequest queryRequest = queryToTest.generateRequest(FakeItem.getTableSchema(), PRIMARY_CONTEXT, null); assertThat(queryRequest.filterExpression(), is("test-expression")); assertThat(queryRequest.expressionAttributeValues(), hasEntry(":test-key", stringValue("test-value"))); } @Test public void generateRequest_filterExpression_withoutValues() { Expression filterExpression = Expression.builder().expression("test-expression").build(); QueryOperation<FakeItem> queryToTest = QueryOperation.create(QueryEnhancedRequest.builder() .queryConditional(keyEqualTo(k -> k.partitionValue(keyItem.getId()))) .filterExpression(filterExpression) .build()); QueryRequest queryRequest = queryToTest.generateRequest(FakeItem.getTableSchema(), PRIMARY_CONTEXT, null); assertThat(queryRequest.filterExpression(), is("test-expression")); } @Test(expected = IllegalArgumentException.class) public void generateRequest_filterExpression_withConflictingValues() { Map<String, AttributeValue> expressionValues = singletonMap(":AMZN_MAPPED_id", stringValue("test-value")); Map<String, String> expressionNames = singletonMap("#AMZN_MAPPED_id", "id"); Expression filterExpression = Expression.builder() .expression("test-expression") .expressionNames(expressionNames) .expressionValues(expressionValues) .build(); QueryOperation<FakeItem> queryToTest = QueryOperation.create(QueryEnhancedRequest.builder() .queryConditional(keyEqualTo(k -> k.partitionValue(keyItem.getId()))) .filterExpression(filterExpression) .build()); queryToTest.generateRequest(FakeItem.getTableSchema(), PRIMARY_CONTEXT, null); } @Test public void generateRequest_consistentRead() { QueryOperation<FakeItem> queryToTest = QueryOperation.create(QueryEnhancedRequest.builder() .queryConditional(keyEqualTo(k -> k.partitionValue(keyItem.getId()))) .consistentRead(true) .build()); QueryRequest queryRequest = queryToTest.generateRequest(FakeItem.getTableSchema(), PRIMARY_CONTEXT, null); assertThat(queryRequest.consistentRead(), is(true)); } @Test public void generateRequest_projectionExpression() { QueryOperation<FakeItem> queryToTest = QueryOperation.create(QueryEnhancedRequest.builder() .queryConditional(keyEqualTo(k -> k.partitionValue(keyItem.getId()))) .attributesToProject("id") .addAttributeToProject("version") .build()); QueryRequest queryRequest = queryToTest.generateRequest(FakeItem.getTableSchema(), PRIMARY_CONTEXT, null); assertThat(queryRequest.projectionExpression(), is("#AMZN_MAPPED_id,#AMZN_MAPPED_version")); assertThat(queryRequest.expressionAttributeNames().get("#AMZN_MAPPED_id"), is ("id")); assertThat(queryRequest.expressionAttributeNames().get("#AMZN_MAPPED_version"), is ("version")); } @Test public void generateRequest_hashKeyOnly_withExclusiveStartKey() { FakeItem exclusiveStartKey = createUniqueFakeItem(); QueryOperation<FakeItem> queryToTest = QueryOperation.create(QueryEnhancedRequest.builder() .queryConditional(keyEqualTo(k -> k.partitionValue(keyItem.getId()))) .exclusiveStartKey(FakeItem.getTableSchema() .itemToMap(exclusiveStartKey, FakeItem.getTableMetadata() .primaryKeys())) .build()); QueryRequest queryRequest = queryToTest.generateRequest(FakeItem.getTableSchema(), PRIMARY_CONTEXT, null); assertThat(queryRequest.exclusiveStartKey(), hasEntry("id", AttributeValue.builder().s(exclusiveStartKey.getId()).build())); } @Test public void generateRequest_secondaryIndex_exclusiveStartKeyUsesPrimaryAndSecondaryIndex() { FakeItemWithIndices exclusiveStartKey = createUniqueFakeItemWithIndices(); Set<String> keyFields = new HashSet<>(FakeItemWithIndices.getTableSchema().tableMetadata().primaryKeys()); keyFields.addAll(FakeItemWithIndices.getTableSchema().tableMetadata().indexKeys("gsi_1")); QueryOperation<FakeItemWithIndices> queryToTest = QueryOperation.create(QueryEnhancedRequest.builder() .queryConditional(keyEqualTo(k -> k.partitionValue(keyItem.getId()))) .exclusiveStartKey(FakeItemWithIndices.getTableSchema() .itemToMap(exclusiveStartKey, keyFields)) .build()); QueryRequest queryRequest = queryToTest.generateRequest(FakeItemWithIndices.getTableSchema(), GSI_1_CONTEXT, null); assertThat(queryRequest.exclusiveStartKey(), hasEntry("id", AttributeValue.builder().s(exclusiveStartKey.getId()).build())); assertThat(queryRequest.exclusiveStartKey(), hasEntry("sort", AttributeValue.builder().s(exclusiveStartKey.getSort()).build())); assertThat(queryRequest.exclusiveStartKey(), hasEntry("gsi_id", AttributeValue.builder().s(exclusiveStartKey.getGsiId()).build())); assertThat(queryRequest.exclusiveStartKey(), hasEntry("gsi_sort", AttributeValue.builder().s(exclusiveStartKey.getGsiSort()).build())); } @Test public void generateRequest_hashAndSortKey_withExclusiveStartKey() { FakeItemWithSort exclusiveStartKey = createUniqueFakeItemWithSort(); QueryOperation<FakeItemWithSort> queryToTest = QueryOperation.create(QueryEnhancedRequest.builder() .queryConditional(keyEqualTo(k -> k.partitionValue(keyItem.getId()))) .exclusiveStartKey( FakeItemWithSort.getTableSchema() .itemToMap( exclusiveStartKey, FakeItemWithSort.getTableSchema() .tableMetadata() .primaryKeys())) .build()); QueryRequest queryRequest = queryToTest.generateRequest(FakeItemWithSort.getTableSchema(), PRIMARY_CONTEXT, null); assertThat(queryRequest.exclusiveStartKey(), hasEntry("id", AttributeValue.builder().s(exclusiveStartKey.getId()).build())); assertThat(queryRequest.exclusiveStartKey(), hasEntry("sort", AttributeValue.builder().s(exclusiveStartKey.getSort()).build())); } @Test public void transformResults_multipleItems_returnsCorrectItems() { List<FakeItem> queryResultItems = generateFakeItemList(); List<Map<String, AttributeValue>> queryResultMaps = queryResultItems.stream().map(QueryOperationTest::getAttributeValueMap).collect(toList()); QueryResponse queryResponse = generateFakeQueryResults(queryResultMaps); Page<FakeItem> queryResultPage = queryOperation.transformResponse(queryResponse, FakeItem.getTableSchema(), PRIMARY_CONTEXT, null); assertThat(queryResultPage.items(), is(queryResultItems)); } @Test public void transformResults_multipleItems_setsLastEvaluatedKey() { List<FakeItem> queryResultItems = generateFakeItemList(); FakeItem lastEvaluatedKey = createUniqueFakeItem(); List<Map<String, AttributeValue>> queryResultMaps = queryResultItems.stream().map(QueryOperationTest::getAttributeValueMap).collect(toList()); QueryResponse queryResponse = generateFakeQueryResults(queryResultMaps, getAttributeValueMap(lastEvaluatedKey)); Page<FakeItem> queryResultPage = queryOperation.transformResponse(queryResponse, FakeItem.getTableSchema(), PRIMARY_CONTEXT, null); assertThat(queryResultPage.lastEvaluatedKey(), is(getAttributeValueMap(lastEvaluatedKey))); } @Test public void queryItem_withExtension_correctlyTransformsItem() { List<FakeItem> queryResultItems = generateFakeItemList(); List<FakeItem> modifiedResultItems = generateFakeItemList(); List<Map<String, AttributeValue>> queryResultMap = queryResultItems.stream().map(QueryOperationTest::getAttributeValueMap).collect(toList()); ReadModification[] readModifications = modifiedResultItems.stream() .map(QueryOperationTest::getAttributeValueMap) .map(attributeMap -> ReadModification.builder().transformedItem(attributeMap).build()) .collect(Collectors.toList()) .toArray(new ReadModification[]{}); when(mockDynamoDbEnhancedClientExtension.afterRead(any(DynamoDbExtensionContext.AfterRead.class))) .thenReturn(readModifications[0], Arrays.copyOfRange(readModifications, 1, readModifications.length)); QueryResponse queryResponse = generateFakeQueryResults(queryResultMap); Page<FakeItem> queryResultPage = queryOperation.transformResponse(queryResponse, FakeItem.getTableSchema(), PRIMARY_CONTEXT, mockDynamoDbEnhancedClientExtension); assertThat(queryResultPage.items(), is(modifiedResultItems)); InOrder inOrder = Mockito.inOrder(mockDynamoDbEnhancedClientExtension); queryResultMap.forEach( attributeMap -> inOrder.verify(mockDynamoDbEnhancedClientExtension) .afterRead( DefaultDynamoDbExtensionContext.builder() .tableMetadata(FakeItem.getTableMetadata()) .operationContext(PRIMARY_CONTEXT) .tableSchema(FakeItem.getTableSchema()) .items(attributeMap).build())); } private static QueryResponse generateFakeQueryResults(List<Map<String, AttributeValue>> queryItemMapsPage) { return QueryResponse.builder().items(queryItemMapsPage).build(); } private static QueryResponse generateFakeQueryResults(List<Map<String, AttributeValue>> queryItemMapsPage, Map<String, AttributeValue> lastEvaluatedKey) { return QueryResponse.builder().items(queryItemMapsPage).lastEvaluatedKey(lastEvaluatedKey).build(); } private static List<FakeItem> generateFakeItemList() { return IntStream.range(0, 3).mapToObj(ignored -> FakeItem.createUniqueFakeItem()).collect(toList()); } private static Map<String, AttributeValue> getAttributeValueMap(FakeItem fakeItem) { return singletonMap("id", AttributeValue.builder().s(fakeItem.getId()).build()); } }
3,992
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/internal
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/internal/operations/DescribeTableOperationTest.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.internal.operations; import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.mockito.ArgumentMatchers.same; import static org.mockito.Mockito.verify; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.enhanced.dynamodb.OperationContext; import software.amazon.awssdk.enhanced.dynamodb.TableMetadata; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItem; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItemWithIndices; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItemWithSort; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.DescribeTableRequest; @RunWith(MockitoJUnitRunner.class) public class DescribeTableOperationTest { private static final String TABLE_NAME = "table-name"; private static final OperationContext PRIMARY_CONTEXT = DefaultOperationContext.create(TABLE_NAME, TableMetadata.primaryIndexName()); private static final OperationContext GSI_1_CONTEXT = DefaultOperationContext.create(TABLE_NAME, "gsi_1"); @Mock private DynamoDbClient mockDynamoDbClient; @Test public void getServiceCall_makesTheRightCall() { DescribeTableOperation<FakeItem> operation = DescribeTableOperation.create(); DescribeTableRequest describeTableRequest = DescribeTableRequest.builder().build(); operation.serviceCall(mockDynamoDbClient).apply(describeTableRequest); verify(mockDynamoDbClient).describeTable(same(describeTableRequest)); } @Test public void generateRequest_from_DescribeTableOperation() { DescribeTableOperation<FakeItemWithSort> describeTableOperation = DescribeTableOperation.create(); DescribeTableRequest describeTableRequest = describeTableOperation .generateRequest(FakeItemWithSort.getTableSchema(), PRIMARY_CONTEXT, null); assertThat(describeTableRequest, is(describeTableRequest.builder().tableName(TABLE_NAME).build())); } @Test public void generateRequest_doesNotWorkForIndex() { DescribeTableOperation<FakeItemWithIndices> operation = DescribeTableOperation.create(); assertThatThrownBy(() -> operation.generateRequest(FakeItemWithIndices.getTableSchema(), GSI_1_CONTEXT, null)) .hasMessageContaining("cannot be executed against a secondary index"); } }
3,993
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/internal
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/internal/operations/PutItemOperationTest.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.internal.operations; import static java.util.Collections.emptyMap; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.Matchers.sameInstance; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItem.createUniqueFakeItem; 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.Map; import java.util.UUID; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClientExtension; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbExtensionContext; 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.extensions.WriteModification; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItem; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItemComposedClass; import software.amazon.awssdk.enhanced.dynamodb.internal.extensions.DefaultDynamoDbExtensionContext; import software.amazon.awssdk.enhanced.dynamodb.model.PutItemEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.TransactPutItemEnhancedRequest; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.Put; import software.amazon.awssdk.services.dynamodb.model.PutItemRequest; import software.amazon.awssdk.services.dynamodb.model.PutItemResponse; import software.amazon.awssdk.services.dynamodb.model.ReturnConsumedCapacity; import software.amazon.awssdk.services.dynamodb.model.ReturnItemCollectionMetrics; import software.amazon.awssdk.services.dynamodb.model.ReturnValue; import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem; @RunWith(MockitoJUnitRunner.class) public class PutItemOperationTest { private static final String TABLE_NAME = "table-name"; private static final OperationContext PRIMARY_CONTEXT = DefaultOperationContext.create(TABLE_NAME, TableMetadata.primaryIndexName()); private static final OperationContext GSI_1_CONTEXT = DefaultOperationContext.create(TABLE_NAME, "gsi_1"); private static final Expression CONDITION_EXPRESSION; private static final Expression CONDITION_EXPRESSION_2; private static final Expression MINIMAL_CONDITION_EXPRESSION = Expression.builder().expression("foo = bar").build(); static { Map<String, String> expressionNames = new HashMap<>(); expressionNames.put("#test_field_1", "test_field_1"); expressionNames.put("#test_field_2", "test_field_2"); Map<String, AttributeValue> expressionValues = new HashMap<>(); expressionValues.put(":test_value_1", numberValue(1)); expressionValues.put(":test_value_2", numberValue(2)); CONDITION_EXPRESSION = Expression.builder() .expression("#test_field_1 = :test_value_1 OR #test_field_2 = :test_value_2") .expressionNames(Collections.unmodifiableMap(expressionNames)) .expressionValues(Collections.unmodifiableMap(expressionValues)) .build(); } static { Map<String, String> expressionNames = new HashMap<>(); expressionNames.put("#test_field_3", "test_field_3"); expressionNames.put("#test_field_4", "test_field_4"); Map<String, AttributeValue> expressionValues = new HashMap<>(); expressionValues.put(":test_value_3", numberValue(3)); expressionValues.put(":test_value_4", numberValue(4)); CONDITION_EXPRESSION_2 = Expression.builder() .expression("#test_field_3 = :test_value_3 OR #test_field_4 = :test_value_4") .expressionNames(Collections.unmodifiableMap(expressionNames)) .expressionValues(Collections.unmodifiableMap(expressionValues)) .build(); } @Mock private DynamoDbClient mockDynamoDbClient; @Mock private DynamoDbEnhancedClientExtension mockDynamoDbEnhancedClientExtension; @Test public void getServiceCall_makesTheRightCallAndReturnsResponse() { FakeItem fakeItem = createUniqueFakeItem(); PutItemOperation<FakeItem> putItemOperation = PutItemOperation.create(PutItemEnhancedRequest.builder(FakeItem.class).item(fakeItem).build()); PutItemRequest getItemRequest = PutItemRequest.builder().tableName(TABLE_NAME).build(); PutItemResponse expectedResponse = PutItemResponse.builder().build(); when(mockDynamoDbClient.putItem(any(PutItemRequest.class))).thenReturn(expectedResponse); PutItemResponse response = putItemOperation.serviceCall(mockDynamoDbClient).apply(getItemRequest); assertThat(response, sameInstance(expectedResponse)); verify(mockDynamoDbClient).putItem(getItemRequest); } @Test(expected = IllegalArgumentException.class) public void generateRequest_withIndex_throwsIllegalArgumentException() { FakeItem fakeItem = createUniqueFakeItem(); PutItemOperation<FakeItem> putItemOperation = PutItemOperation.create(PutItemEnhancedRequest.builder(FakeItem.class).item(fakeItem).build()); putItemOperation.generateRequest(FakeItem.getTableSchema(), GSI_1_CONTEXT, null); } @Test public void generateRequest_generatesCorrectRequest() { FakeItem fakeItem = createUniqueFakeItem(); fakeItem.setSubclassAttribute("subclass-value"); PutItemOperation<FakeItem> putItemOperation = PutItemOperation.create(PutItemEnhancedRequest.builder(FakeItem.class) .item(fakeItem) .build()); PutItemRequest request = putItemOperation.generateRequest(FakeItem.getTableSchema(), PRIMARY_CONTEXT, null); Map<String, AttributeValue> expectedItemMap = new HashMap<>(); expectedItemMap.put("id", AttributeValue.builder().s(fakeItem.getId()).build()); expectedItemMap.put("subclass_attribute", AttributeValue.builder().s("subclass-value").build()); PutItemRequest expectedRequest = PutItemRequest.builder() .tableName(TABLE_NAME) .item(expectedItemMap) .build(); assertThat(request, is(expectedRequest)); } @Test public void generateRequest_withConditionExpression_generatesCorrectRequest() { FakeItem fakeItem = createUniqueFakeItem(); fakeItem.setSubclassAttribute("subclass-value"); PutItemOperation<FakeItem> putItemOperation = PutItemOperation.create(PutItemEnhancedRequest.builder(FakeItem.class) .conditionExpression(CONDITION_EXPRESSION) .item(fakeItem) .build()); PutItemRequest request = putItemOperation.generateRequest(FakeItem.getTableSchema(), PRIMARY_CONTEXT, null); Map<String, AttributeValue> expectedItemMap = new HashMap<>(); expectedItemMap.put("id", AttributeValue.builder().s(fakeItem.getId()).build()); expectedItemMap.put("subclass_attribute", AttributeValue.builder().s("subclass-value").build()); PutItemRequest expectedRequest = PutItemRequest.builder() .tableName(TABLE_NAME) .item(expectedItemMap) .conditionExpression(CONDITION_EXPRESSION.expression()) .expressionAttributeNames(CONDITION_EXPRESSION.expressionNames()) .expressionAttributeValues(CONDITION_EXPRESSION.expressionValues()) .build(); assertThat(request, is(expectedRequest)); } @Test public void generateRequest_withReturnValues_unknownValue_generatesCorrectRequest() { FakeItem fakeItem = createUniqueFakeItem(); fakeItem.setSubclassAttribute("subclass-value"); String returnValues = UUID.randomUUID().toString(); PutItemOperation<FakeItem> putItemOperation = PutItemOperation.create(PutItemEnhancedRequest.builder(FakeItem.class) .item(fakeItem) .returnValues(returnValues) .build()); PutItemRequest request = putItemOperation.generateRequest(FakeItem.getTableSchema(), PRIMARY_CONTEXT, null); Map<String, AttributeValue> expectedItemMap = new HashMap<>(); expectedItemMap.put("id", AttributeValue.builder().s(fakeItem.getId()).build()); expectedItemMap.put("subclass_attribute", AttributeValue.builder().s("subclass-value").build()); PutItemRequest expectedRequest = PutItemRequest.builder() .tableName(TABLE_NAME) .item(expectedItemMap) .returnValues(returnValues) .build(); assertThat(request, is(expectedRequest)); } @Test public void generateRequest_withReturnValues_knownValue_generatesCorrectRequest() { FakeItem fakeItem = createUniqueFakeItem(); fakeItem.setSubclassAttribute("subclass-value"); ReturnValue returnValues = ReturnValue.ALL_OLD; PutItemOperation<FakeItem> putItemOperation = PutItemOperation.create(PutItemEnhancedRequest.builder(FakeItem.class) .item(fakeItem) .returnValues(returnValues) .build()); PutItemRequest request = putItemOperation.generateRequest(FakeItem.getTableSchema(), PRIMARY_CONTEXT, null); Map<String, AttributeValue> expectedItemMap = new HashMap<>(); expectedItemMap.put("id", AttributeValue.builder().s(fakeItem.getId()).build()); expectedItemMap.put("subclass_attribute", AttributeValue.builder().s("subclass-value").build()); PutItemRequest expectedRequest = PutItemRequest.builder() .tableName(TABLE_NAME) .item(expectedItemMap) .returnValues(returnValues) .build(); assertThat(request, is(expectedRequest)); } @Test public void generateRequest_withReturnConsumedCapacity_unknownValue_generatesCorrectRequest() { FakeItem fakeItem = createUniqueFakeItem(); fakeItem.setSubclassAttribute("subclass-value"); String returnConsumedCapacity = UUID.randomUUID().toString(); PutItemOperation<FakeItem> putItemOperation = PutItemOperation.create(PutItemEnhancedRequest.builder(FakeItem.class) .item(fakeItem) .returnConsumedCapacity(returnConsumedCapacity) .build()); PutItemRequest request = putItemOperation.generateRequest(FakeItem.getTableSchema(), PRIMARY_CONTEXT, null); Map<String, AttributeValue> expectedItemMap = new HashMap<>(); expectedItemMap.put("id", AttributeValue.builder().s(fakeItem.getId()).build()); expectedItemMap.put("subclass_attribute", AttributeValue.builder().s("subclass-value").build()); PutItemRequest expectedRequest = PutItemRequest.builder() .tableName(TABLE_NAME) .item(expectedItemMap) .returnConsumedCapacity(returnConsumedCapacity) .build(); assertThat(request, is(expectedRequest)); } @Test public void generateRequest_withReturnConsumedCapacity_knownValue_generatesCorrectRequest() { FakeItem fakeItem = createUniqueFakeItem(); fakeItem.setSubclassAttribute("subclass-value"); ReturnConsumedCapacity returnConsumedCapacity = ReturnConsumedCapacity.TOTAL; PutItemOperation<FakeItem> putItemOperation = PutItemOperation.create(PutItemEnhancedRequest.builder(FakeItem.class) .item(fakeItem) .returnConsumedCapacity(returnConsumedCapacity) .build()); PutItemRequest request = putItemOperation.generateRequest(FakeItem.getTableSchema(), PRIMARY_CONTEXT, null); Map<String, AttributeValue> expectedItemMap = new HashMap<>(); expectedItemMap.put("id", AttributeValue.builder().s(fakeItem.getId()).build()); expectedItemMap.put("subclass_attribute", AttributeValue.builder().s("subclass-value").build()); PutItemRequest expectedRequest = PutItemRequest.builder() .tableName(TABLE_NAME) .item(expectedItemMap) .returnConsumedCapacity(returnConsumedCapacity) .build(); assertThat(request, is(expectedRequest)); } @Test public void generateRequest_withReturnItemCollectionMetrics_unknownValue_generatesCorrectRequest() { FakeItem fakeItem = createUniqueFakeItem(); fakeItem.setSubclassAttribute("subclass-value"); String returnItemCollectionMetrics = UUID.randomUUID().toString(); PutItemOperation<FakeItem> putItemOperation = PutItemOperation.create(PutItemEnhancedRequest.builder(FakeItem.class) .item(fakeItem) .returnItemCollectionMetrics(returnItemCollectionMetrics) .build()); PutItemRequest request = putItemOperation.generateRequest(FakeItem.getTableSchema(), PRIMARY_CONTEXT, null); Map<String, AttributeValue> expectedItemMap = new HashMap<>(); expectedItemMap.put("id", AttributeValue.builder().s(fakeItem.getId()).build()); expectedItemMap.put("subclass_attribute", AttributeValue.builder().s("subclass-value").build()); PutItemRequest expectedRequest = PutItemRequest.builder() .tableName(TABLE_NAME) .item(expectedItemMap) .returnItemCollectionMetrics(returnItemCollectionMetrics) .build(); assertThat(request, is(expectedRequest)); } @Test public void generateRequest_withReturnItemCollectionMetrics_knownValue_generatesCorrectRequest() { FakeItem fakeItem = createUniqueFakeItem(); fakeItem.setSubclassAttribute("subclass-value"); ReturnItemCollectionMetrics returnItemCollectionMetrics = ReturnItemCollectionMetrics.SIZE; PutItemOperation<FakeItem> putItemOperation = PutItemOperation.create(PutItemEnhancedRequest.builder(FakeItem.class) .item(fakeItem) .returnItemCollectionMetrics(returnItemCollectionMetrics) .build()); PutItemRequest request = putItemOperation.generateRequest(FakeItem.getTableSchema(), PRIMARY_CONTEXT, null); Map<String, AttributeValue> expectedItemMap = new HashMap<>(); expectedItemMap.put("id", AttributeValue.builder().s(fakeItem.getId()).build()); expectedItemMap.put("subclass_attribute", AttributeValue.builder().s("subclass-value").build()); PutItemRequest expectedRequest = PutItemRequest.builder() .tableName(TABLE_NAME) .item(expectedItemMap) .returnItemCollectionMetrics(returnItemCollectionMetrics) .build(); assertThat(request, is(expectedRequest)); } @Test public void generateRequest_withMinimalConditionExpression() { FakeItem fakeItem = createUniqueFakeItem(); PutItemOperation<FakeItem> putItemOperation = PutItemOperation.create(PutItemEnhancedRequest.builder(FakeItem.class) .item(fakeItem) .conditionExpression(MINIMAL_CONDITION_EXPRESSION) .build()); PutItemRequest request = putItemOperation.generateRequest(FakeItem.getTableSchema(), PRIMARY_CONTEXT, null); assertThat(request.conditionExpression(), is(MINIMAL_CONDITION_EXPRESSION.expression())); assertThat(request.expressionAttributeNames(), is(emptyMap())); assertThat(request.expressionAttributeValues(), is(emptyMap())); } @Test public void generateRequest_withConditionExpression_andExtensionWithSingleCondition() { FakeItem baseFakeItem = createUniqueFakeItem(); when(mockDynamoDbEnhancedClientExtension.beforeWrite(any(DynamoDbExtensionContext.BeforeWrite.class))) .thenReturn(WriteModification.builder().additionalConditionalExpression(CONDITION_EXPRESSION_2).build()); PutItemOperation<FakeItem> putItemOperation = PutItemOperation.create(PutItemEnhancedRequest.builder(FakeItem.class) .conditionExpression(CONDITION_EXPRESSION) .item(baseFakeItem) .build()); PutItemRequest request = putItemOperation.generateRequest(FakeItem.getTableSchema(), PRIMARY_CONTEXT, mockDynamoDbEnhancedClientExtension); Expression expectedCondition = Expression.join(CONDITION_EXPRESSION, CONDITION_EXPRESSION_2, " AND "); assertThat(request.conditionExpression(), is(expectedCondition.expression())); assertThat(request.expressionAttributeNames(), is(expectedCondition.expressionNames())); assertThat(request.expressionAttributeValues(), is(expectedCondition.expressionValues())); } @Test(expected = IllegalArgumentException.class) public void generateRequest_noPartitionKey_throwsIllegalArgumentException() { FakeItemComposedClass fakeItem = FakeItemComposedClass.builder().composedAttribute("whatever").build(); PutItemOperation<FakeItemComposedClass> putItemOperation = PutItemOperation.create(PutItemEnhancedRequest.builder(FakeItemComposedClass.class).item(fakeItem).build()); putItemOperation.generateRequest(FakeItemComposedClass.getTableSchema(), PRIMARY_CONTEXT, null); } @Test public void transformResponse_doesNotBlowUp() { FakeItem fakeItem = createUniqueFakeItem(); PutItemOperation<FakeItem> putItemOperation = PutItemOperation.create(PutItemEnhancedRequest.builder(FakeItem.class) .item(fakeItem) .build()); PutItemResponse response = PutItemResponse.builder().build(); putItemOperation.transformResponse(response, FakeItem.getTableSchema(), PRIMARY_CONTEXT, null); } @Test public void generateRequest_withExtension_modifiesItemToPut() { FakeItem baseFakeItem = createUniqueFakeItem(); FakeItem fakeItem = createUniqueFakeItem(); Map<String, AttributeValue> baseMap = FakeItem.getTableSchema().itemToMap(baseFakeItem, true); Map<String, AttributeValue> fakeMap = FakeItem.getTableSchema().itemToMap(fakeItem, true); when(mockDynamoDbEnhancedClientExtension.beforeWrite(any(DynamoDbExtensionContext.BeforeWrite.class))) .thenReturn(WriteModification.builder().transformedItem(fakeMap).build()); PutItemOperation<FakeItem> putItemOperation = PutItemOperation.create(PutItemEnhancedRequest.builder(FakeItem.class) .item(baseFakeItem) .build()); PutItemRequest request = putItemOperation.generateRequest(FakeItem.getTableSchema(), PRIMARY_CONTEXT, mockDynamoDbEnhancedClientExtension); assertThat(request.item(), is(fakeMap)); verify(mockDynamoDbEnhancedClientExtension).beforeWrite( DefaultDynamoDbExtensionContext.builder() .items(baseMap) .operationContext(PRIMARY_CONTEXT) .operationName(OperationName.PUT_ITEM) .tableSchema(FakeItem.getTableSchema()) .tableMetadata(FakeItem.getTableMetadata()).build()); } @Test public void generateRequest_withExtension_singleCondition() { FakeItem baseFakeItem = createUniqueFakeItem(); FakeItem fakeItem = createUniqueFakeItem(); Map<String, AttributeValue> fakeMap = FakeItem.getTableSchema().itemToMap(fakeItem, true); Expression condition = Expression.builder().expression("condition").expressionValues(fakeMap).build(); when(mockDynamoDbEnhancedClientExtension.beforeWrite(any(DynamoDbExtensionContext.BeforeWrite.class))) .thenReturn(WriteModification.builder().additionalConditionalExpression(condition).build()); PutItemOperation<FakeItem> putItemOperation = PutItemOperation.create(PutItemEnhancedRequest.builder(FakeItem.class) .item(baseFakeItem) .build()); PutItemRequest request = putItemOperation.generateRequest(FakeItem.getTableSchema(), PRIMARY_CONTEXT, mockDynamoDbEnhancedClientExtension); assertThat(request.conditionExpression(), is("condition")); assertThat(request.expressionAttributeValues(), is(fakeMap)); } @Test public void generateRequest_withExtension_noModifications() { FakeItem baseFakeItem = createUniqueFakeItem(); when(mockDynamoDbEnhancedClientExtension.beforeWrite(any(DynamoDbExtensionContext.BeforeWrite.class))) .thenReturn(WriteModification.builder().build()); PutItemOperation<FakeItem> putItemOperation = PutItemOperation.create(PutItemEnhancedRequest.builder(FakeItem.class) .item(baseFakeItem) .build()); PutItemRequest request = putItemOperation.generateRequest(FakeItem.getTableSchema(), PRIMARY_CONTEXT, mockDynamoDbEnhancedClientExtension); assertThat(request.conditionExpression(), is(nullValue())); assertThat(request.expressionAttributeValues().size(), is(0)); } @Test public void generateTransactWriteItem_basicRequest() { FakeItem fakeItem = createUniqueFakeItem(); Map<String, AttributeValue> fakeItemMap = FakeItem.getTableSchema().itemToMap(fakeItem, true); PutItemOperation<FakeItem> putItemOperation = spy(PutItemOperation.create(PutItemEnhancedRequest.builder(FakeItem.class) .item(fakeItem) .build())); OperationContext context = DefaultOperationContext.create(TABLE_NAME, TableMetadata.primaryIndexName()); PutItemRequest putItemRequest = PutItemRequest.builder() .tableName(TABLE_NAME) .item(fakeItemMap) .build(); doReturn(putItemRequest).when(putItemOperation).generateRequest(any(), any(), any()); TransactWriteItem actualResult = putItemOperation.generateTransactWriteItem(FakeItem.getTableSchema(), context, mockDynamoDbEnhancedClientExtension); TransactWriteItem expectedResult = TransactWriteItem.builder() .put(Put.builder() .item(fakeItemMap) .tableName(TABLE_NAME) .build()) .build(); assertThat(actualResult, is(expectedResult)); verify(putItemOperation).generateRequest(FakeItem.getTableSchema(), context, mockDynamoDbEnhancedClientExtension); } @Test public void generateTransactWriteItem_conditionalRequest() { FakeItem fakeItem = createUniqueFakeItem(); Map<String, AttributeValue> fakeItemMap = FakeItem.getTableSchema().itemToMap(fakeItem, true); PutItemOperation<FakeItem> putItemOperation = spy(PutItemOperation.create(PutItemEnhancedRequest.builder(FakeItem.class) .item(fakeItem) .build())); OperationContext context = DefaultOperationContext.create(TABLE_NAME, TableMetadata.primaryIndexName()); String conditionExpression = "condition-expression"; Map<String, AttributeValue> attributeValues = Collections.singletonMap("key", stringValue("value1")); Map<String, String> attributeNames = Collections.singletonMap("key", "value2"); PutItemRequest putItemRequest = PutItemRequest.builder() .tableName(TABLE_NAME) .item(fakeItemMap) .conditionExpression(conditionExpression) .expressionAttributeValues(attributeValues) .expressionAttributeNames(attributeNames) .build(); doReturn(putItemRequest).when(putItemOperation).generateRequest(any(), any(), any()); TransactWriteItem actualResult = putItemOperation.generateTransactWriteItem(FakeItem.getTableSchema(), context, mockDynamoDbEnhancedClientExtension); TransactWriteItem expectedResult = TransactWriteItem.builder() .put(Put.builder() .item(fakeItemMap) .tableName(TABLE_NAME) .conditionExpression(conditionExpression) .expressionAttributeNames(attributeNames) .expressionAttributeValues(attributeValues) .build()) .build(); assertThat(actualResult, is(expectedResult)); verify(putItemOperation).generateRequest(FakeItem.getTableSchema(), context, mockDynamoDbEnhancedClientExtension); } @Test public void generateTransactWriteItem_returnValuesOnConditionCheckFailure_generatesCorrectRequest() { FakeItem fakeItem = createUniqueFakeItem(); Map<String, AttributeValue> fakeItemMap = FakeItem.getTableSchema().itemToMap(fakeItem, true); String returnValues = "return-values"; PutItemOperation<FakeItem> putItemOperation = spy(PutItemOperation.create(TransactPutItemEnhancedRequest.builder(FakeItem.class) .item(fakeItem) .returnValuesOnConditionCheckFailure(returnValues) .build())); OperationContext context = DefaultOperationContext.create(TABLE_NAME, TableMetadata.primaryIndexName()); PutItemRequest putItemRequest = PutItemRequest.builder() .tableName(TABLE_NAME) .item(fakeItemMap) .build(); doReturn(putItemRequest).when(putItemOperation).generateRequest(any(), any(), any()); TransactWriteItem actualResult = putItemOperation.generateTransactWriteItem(FakeItem.getTableSchema(), context, mockDynamoDbEnhancedClientExtension); TransactWriteItem expectedResult = TransactWriteItem.builder() .put(Put.builder() .item(fakeItemMap) .tableName(TABLE_NAME) .returnValuesOnConditionCheckFailure(returnValues) .build()) .build(); assertThat(actualResult, is(expectedResult)); verify(putItemOperation).generateRequest(FakeItem.getTableSchema(), context, mockDynamoDbEnhancedClientExtension); } }
3,994
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/internal
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/internal/operations/DefaultOperationContextTest.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.internal.operations; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; import software.amazon.awssdk.enhanced.dynamodb.TableMetadata; public class DefaultOperationContextTest { @Test public void createWithTableNameAndIndexName() { DefaultOperationContext context = DefaultOperationContext.create("table_name", "index_name"); assertThat(context.tableName(), is("table_name")); assertThat(context.indexName(), is("index_name")); } @Test public void createWithTableName() { DefaultOperationContext context = DefaultOperationContext.create("table_name"); assertThat(context.tableName(), is("table_name")); assertThat(context.indexName(), Matchers.is(TableMetadata.primaryIndexName())); } }
3,995
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/internal
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/internal/operations/ConditionCheckTest.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.internal.operations; import static java.util.Collections.singletonMap; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.nullValue; import static org.mockito.Mockito.verifyNoMoreInteractions; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.stringValue; import java.util.Map; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClientExtension; import software.amazon.awssdk.enhanced.dynamodb.Expression; import software.amazon.awssdk.enhanced.dynamodb.Key; import software.amazon.awssdk.enhanced.dynamodb.OperationContext; import software.amazon.awssdk.enhanced.dynamodb.TableMetadata; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItem; import software.amazon.awssdk.enhanced.dynamodb.model.ConditionCheck; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.ReturnValuesOnConditionCheckFailure; import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem; @RunWith(MockitoJUnitRunner.class) public class ConditionCheckTest { @Mock private DynamoDbEnhancedClientExtension mockDynamoDbEnhancedClientExtension; @Test public void generateTransactWriteItem() { FakeItem fakeItem = FakeItem.createUniqueFakeItem(); Map<String, AttributeValue> keyMap = singletonMap("id", stringValue(fakeItem.getId())); String returnValues = "return-values"; Expression conditionExpression = Expression.builder() .expression("expression") .expressionNames(singletonMap("key1", "value1")) .expressionValues(singletonMap("key2", stringValue("value2"))) .build(); ConditionCheck<FakeItem> operation = ConditionCheck.builder() .key(k -> k.partitionValue(fakeItem.getId())) .conditionExpression(conditionExpression) .returnValuesOnConditionCheckFailure(returnValues) .build(); OperationContext context = DefaultOperationContext.create("table-name", TableMetadata.primaryIndexName()); TransactWriteItem result = operation.generateTransactWriteItem(FakeItem.getTableSchema(), context, mockDynamoDbEnhancedClientExtension); TransactWriteItem expectedResult = TransactWriteItem.builder() .conditionCheck( software.amazon.awssdk.services.dynamodb.model.ConditionCheck .builder() .tableName("table-name") .key(keyMap) .conditionExpression(conditionExpression.expression()) .expressionAttributeValues(conditionExpression.expressionValues()) .expressionAttributeNames(conditionExpression.expressionNames()) .returnValuesOnConditionCheckFailure(returnValues) .build()) .build(); assertThat(result, is(expectedResult)); verifyNoMoreInteractions(mockDynamoDbEnhancedClientExtension); } @Test public void builder_minimal() { ConditionCheck<Object> builtObject = ConditionCheck.builder().build(); assertThat(builtObject.conditionExpression(), is(nullValue())); assertThat(builtObject.returnValuesOnConditionCheckFailure(), is(nullValue())); assertThat(builtObject.returnValuesOnConditionCheckFailureAsString(), is(nullValue())); } @Test public void builder_maximal() { FakeItem fakeItem = FakeItem.createUniqueFakeItem(); String returnValues = "ALL_OLD"; Expression conditionExpression = Expression.builder() .expression("expression") .expressionNames(singletonMap("key1", "value1")) .expressionValues(singletonMap("key2", stringValue("value2"))) .build(); ConditionCheck<FakeItem> builtObject = ConditionCheck.builder() .key(k -> k.partitionValue(fakeItem.getId())) .conditionExpression(conditionExpression) .returnValuesOnConditionCheckFailure(returnValues) .build(); assertThat(builtObject.conditionExpression(), is(conditionExpression)); assertThat(builtObject.returnValuesOnConditionCheckFailure(), is(ReturnValuesOnConditionCheckFailure.ALL_OLD)); assertThat(builtObject.returnValuesOnConditionCheckFailureAsString(), is(returnValues)); } @Test public void equals_maximal() { FakeItem fakeItem = FakeItem.createUniqueFakeItem(); String returnValues = "ALL_OLD"; Expression conditionExpression = Expression.builder() .expression("expression") .expressionNames(singletonMap("key1", "value1")) .expressionValues(singletonMap("key2", stringValue("value2"))) .build(); ConditionCheck<FakeItem> builtObject = ConditionCheck.builder() .key(k -> k.partitionValue(fakeItem.getId())) .conditionExpression(conditionExpression) .returnValuesOnConditionCheckFailure(returnValues) .build(); ConditionCheck<Object> copiedObject = builtObject.toBuilder().build(); assertThat(builtObject, equalTo(copiedObject)); } @Test public void equals_minimal() { ConditionCheck<FakeItem> builtObject1 = ConditionCheck.builder().build(); ConditionCheck<FakeItem> builtObject2 = ConditionCheck.builder().build(); assertThat(builtObject1, equalTo(builtObject2)); } @Test public void equals_differentType() { ConditionCheck<FakeItem> builtObject1 = ConditionCheck.builder().build(); software.amazon.awssdk.services.dynamodb.model.ConditionCheck differentType = software.amazon.awssdk.services.dynamodb.model.ConditionCheck.builder().build(); assertThat(builtObject1, not(equalTo(differentType))); } @Test public void equals_self() { ConditionCheck<FakeItem> builtObject = ConditionCheck.builder().build(); assertThat(builtObject, equalTo(builtObject)); } @Test public void equals_keyNotEqual() { Key key1 = Key.builder().partitionValue("key1").build(); Key key2 = Key.builder().partitionValue("key2").build(); ConditionCheck<FakeItem> builtObject1 = ConditionCheck.builder().key(key1).build(); ConditionCheck<FakeItem> builtObject2 = ConditionCheck.builder().key(key2).build(); assertThat(builtObject1, not(equalTo(builtObject2))); } @Test public void equals_conditionExpressionNotEqual() { Expression conditionExpression1 = Expression.builder() .expression("expression1") .expressionNames(singletonMap("key1", "value1")) .expressionValues(singletonMap("key2", stringValue("value2"))) .build(); Expression conditionExpression2 = Expression.builder() .expression("expression2") .expressionNames(singletonMap("key1", "value1")) .expressionValues(singletonMap("key2", stringValue("value2"))) .build(); ConditionCheck<FakeItem> builtObject1 = ConditionCheck.builder().conditionExpression(conditionExpression1).build(); ConditionCheck<FakeItem> builtObject2 = ConditionCheck.builder().conditionExpression(conditionExpression2).build(); assertThat(builtObject1, not(equalTo(builtObject2))); } @Test public void equals_returnValuesNotEqual() { ReturnValuesOnConditionCheckFailure returnValues1 = ReturnValuesOnConditionCheckFailure.NONE; ReturnValuesOnConditionCheckFailure returnValues2 = ReturnValuesOnConditionCheckFailure.ALL_OLD; ConditionCheck<FakeItem> builtObject1 = ConditionCheck.builder().returnValuesOnConditionCheckFailure(returnValues1).build(); ConditionCheck<FakeItem> builtObject2 = ConditionCheck.builder().returnValuesOnConditionCheckFailure(returnValues2).build(); assertThat(builtObject1, not(equalTo(builtObject2))); } @Test public void hashCode_maximal() { FakeItem fakeItem = FakeItem.createUniqueFakeItem(); String returnValues = "ALL_OLD"; Expression conditionExpression = Expression.builder() .expression("expression") .expressionNames(singletonMap("key1", "value1")) .expressionValues(singletonMap("key2", stringValue("value2"))) .build(); ConditionCheck<FakeItem> builtObject = ConditionCheck.builder() .key(k -> k.partitionValue(fakeItem.getId())) .conditionExpression(conditionExpression) .returnValuesOnConditionCheckFailure(returnValues) .build(); ConditionCheck<Object> copiedObject = builtObject.toBuilder().build(); assertThat(builtObject.hashCode(), equalTo(copiedObject.hashCode())); } @Test public void hashCode_minimal() { ConditionCheck<FakeItem> builtObject1 = ConditionCheck.builder().build(); ConditionCheck<FakeItem> builtObject2 = ConditionCheck.builder().build(); assertThat(builtObject1.hashCode(), equalTo(builtObject2.hashCode())); } @Test public void builder_returnValuesOnConditionCheckFailureNewValue_enumGetterReturnsUnknownValue() { String returnValues = "new-value"; ConditionCheck<FakeItem> builtObject = ConditionCheck.builder() .returnValuesOnConditionCheckFailure(returnValues) .build(); assertThat(builtObject.returnValuesOnConditionCheckFailure(), equalTo(ReturnValuesOnConditionCheckFailure.UNKNOWN_TO_SDK_VERSION)); } @Test public void builder_returnValuesOnConditionCheckFailureNewValue_stringGetter() { String returnValues = "new-value"; ConditionCheck<FakeItem> builtObject = ConditionCheck.builder() .returnValuesOnConditionCheckFailure(returnValues) .build(); assertThat(builtObject.returnValuesOnConditionCheckFailureAsString(), is(returnValues)); } }
3,996
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/internal
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/internal/operations/CreateTableOperationTest.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.internal.operations; 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 org.hamcrest.Matchers.nullValue; import static org.hamcrest.Matchers.sameInstance; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.same; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static software.amazon.awssdk.services.dynamodb.model.KeyType.HASH; import static software.amazon.awssdk.services.dynamodb.model.KeyType.RANGE; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.hamcrest.Description; import org.hamcrest.TypeSafeMatcher; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.core.util.DefaultSdkAutoConstructList; import software.amazon.awssdk.enhanced.dynamodb.OperationContext; import software.amazon.awssdk.enhanced.dynamodb.TableMetadata; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItem; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItemWithBinaryKey; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItemWithByteBufferKey; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItemWithIndices; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItemWithNumericSort; import software.amazon.awssdk.enhanced.dynamodb.model.CreateTableEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.EnhancedGlobalSecondaryIndex; import software.amazon.awssdk.enhanced.dynamodb.model.EnhancedLocalSecondaryIndex; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition; import software.amazon.awssdk.services.dynamodb.model.BillingMode; import software.amazon.awssdk.services.dynamodb.model.CreateTableRequest; import software.amazon.awssdk.services.dynamodb.model.CreateTableResponse; import software.amazon.awssdk.services.dynamodb.model.KeySchemaElement; import software.amazon.awssdk.services.dynamodb.model.Projection; import software.amazon.awssdk.services.dynamodb.model.ProjectionType; import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughput; import software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType; import software.amazon.awssdk.services.dynamodb.model.StreamSpecification; import software.amazon.awssdk.services.dynamodb.model.StreamViewType; @RunWith(MockitoJUnitRunner.class) public class CreateTableOperationTest { private static final String TABLE_NAME = "table-name"; private static final OperationContext PRIMARY_CONTEXT = DefaultOperationContext.create(TABLE_NAME, TableMetadata.primaryIndexName()); private static final OperationContext GSI_1_CONTEXT = DefaultOperationContext.create(TABLE_NAME, "gsi_1"); private static MatchedGsi matchesGsi(software.amazon.awssdk.services.dynamodb.model.GlobalSecondaryIndex other) { return new MatchedGsi(other); } @Mock private DynamoDbClient mockDynamoDbClient; private static class MatchedGsi extends TypeSafeMatcher<software.amazon.awssdk.services.dynamodb.model.GlobalSecondaryIndex> { private final software.amazon.awssdk.services.dynamodb.model.GlobalSecondaryIndex other; private MatchedGsi(software.amazon.awssdk.services.dynamodb.model.GlobalSecondaryIndex other) { this.other = other; } @Override protected boolean matchesSafely(software.amazon.awssdk.services.dynamodb.model.GlobalSecondaryIndex globalSecondaryIndex) { if (!other.indexName().equals(globalSecondaryIndex.indexName())) { return false; } if ((other.projection() != null && !other.projection().equals(globalSecondaryIndex.projection())) || (other.projection() == null && globalSecondaryIndex.projection() != null)) { return false; } return containsInAnyOrder(other.keySchema().toArray(new KeySchemaElement[]{})) .matches(globalSecondaryIndex.keySchema()); } @Override public void describeTo(Description description) { description.appendText("a GlobalSecondaryIndex equivalent to [" + other.toString() + "]"); } } @Test public void generateRequest_withLsiAndGsi() { Projection projection1 = Projection.builder().projectionType(ProjectionType.ALL).build(); Projection projection2 = Projection.builder().projectionType(ProjectionType.KEYS_ONLY).build(); Projection projection3 = Projection.builder() .projectionType(ProjectionType.INCLUDE) .nonKeyAttributes("key1", "key2") .build(); ProvisionedThroughput provisionedThroughput1 = ProvisionedThroughput.builder() .readCapacityUnits(1L) .writeCapacityUnits(2L) .build(); ProvisionedThroughput provisionedThroughput2 = ProvisionedThroughput.builder() .readCapacityUnits(3L) .writeCapacityUnits(4L) .build(); List<EnhancedGlobalSecondaryIndex> globalSecondaryIndexList = Arrays.asList( EnhancedGlobalSecondaryIndex.builder() .indexName("gsi_1") .projection(projection1) .provisionedThroughput(provisionedThroughput1) .build(), EnhancedGlobalSecondaryIndex.builder() .indexName("gsi_2") .projection(projection2) .provisionedThroughput(provisionedThroughput2) .build()); CreateTableOperation<FakeItemWithIndices> operation = CreateTableOperation.create(CreateTableEnhancedRequest.builder() .globalSecondaryIndices(globalSecondaryIndexList) .localSecondaryIndices(Collections.singletonList( EnhancedLocalSecondaryIndex.create("lsi_1", projection3))) .build()); CreateTableRequest request = operation.generateRequest(FakeItemWithIndices.getTableSchema(), PRIMARY_CONTEXT, null); assertThat(request.tableName(), is(TABLE_NAME)); assertThat(request.keySchema(), containsInAnyOrder(KeySchemaElement.builder() .attributeName("id") .keyType(HASH) .build(), KeySchemaElement.builder() .attributeName("sort") .keyType(RANGE) .build())); software.amazon.awssdk.services.dynamodb.model.GlobalSecondaryIndex expectedGsi1 = software.amazon.awssdk.services.dynamodb.model.GlobalSecondaryIndex.builder() .indexName("gsi_1") .keySchema(KeySchemaElement.builder() .attributeName("gsi_id") .keyType(HASH) .build(), KeySchemaElement.builder() .attributeName("gsi_sort") .keyType(RANGE) .build()) .projection(projection1) .provisionedThroughput(provisionedThroughput1) .build(); software.amazon.awssdk.services.dynamodb.model.GlobalSecondaryIndex expectedGsi2 = software.amazon.awssdk.services.dynamodb.model.GlobalSecondaryIndex.builder() .indexName("gsi_2") .keySchema(KeySchemaElement.builder() .attributeName("gsi_id") .keyType(HASH) .build()) .projection(projection2) .provisionedThroughput(provisionedThroughput2) .build(); assertThat(request.globalSecondaryIndexes(), containsInAnyOrder(matchesGsi(expectedGsi1), matchesGsi(expectedGsi2))); software.amazon.awssdk.services.dynamodb.model.LocalSecondaryIndex expectedLsi = software.amazon.awssdk.services.dynamodb.model.LocalSecondaryIndex.builder() .indexName("lsi_1") .keySchema(KeySchemaElement.builder() .attributeName("id") .keyType(HASH) .build(), KeySchemaElement.builder() .attributeName("lsi_sort") .keyType(RANGE) .build()) .projection(projection3) .build(); assertThat(request.localSecondaryIndexes(), containsInAnyOrder(expectedLsi)); assertThat(request.attributeDefinitions(), containsInAnyOrder( AttributeDefinition.builder() .attributeName("id") .attributeType(ScalarAttributeType.S) .build(), AttributeDefinition.builder() .attributeName("sort") .attributeType(ScalarAttributeType.S) .build(), AttributeDefinition.builder() .attributeName("lsi_sort") .attributeType(ScalarAttributeType.S) .build(), AttributeDefinition.builder() .attributeName("gsi_id") .attributeType(ScalarAttributeType.S) .build(), AttributeDefinition.builder() .attributeName("gsi_sort") .attributeType(ScalarAttributeType.S) .build())); } @Test(expected = IllegalArgumentException.class) public void generateRequest_invalidGsi() { ProvisionedThroughput provisionedThroughput = ProvisionedThroughput.builder() .readCapacityUnits(1L) .writeCapacityUnits(1L) .build(); List<EnhancedGlobalSecondaryIndex> invalidGsiList = Collections.singletonList( EnhancedGlobalSecondaryIndex.builder() .indexName("invalid") .projection(p -> p.projectionType(ProjectionType.ALL)) .provisionedThroughput(provisionedThroughput) .build()); CreateTableOperation<FakeItem> operation = CreateTableOperation.create(CreateTableEnhancedRequest.builder().globalSecondaryIndices(invalidGsiList).build()); operation.generateRequest(FakeItem.getTableSchema(), PRIMARY_CONTEXT, null); } @Test(expected = IllegalArgumentException.class) public void generateRequest_invalidGsiAsLsiReference() { List<EnhancedLocalSecondaryIndex> invalidGsiList = Collections.singletonList( EnhancedLocalSecondaryIndex.create("gsi_1", Projection.builder().projectionType(ProjectionType.ALL).build())); CreateTableOperation<FakeItemWithIndices> operation = CreateTableOperation.create(CreateTableEnhancedRequest.builder().localSecondaryIndices(invalidGsiList).build()); operation.generateRequest(FakeItemWithIndices.getTableSchema(), PRIMARY_CONTEXT, null); } @Test public void generateRequest_validLsiAsGsiReference() { List<EnhancedGlobalSecondaryIndex> validLsiList = Collections.singletonList( EnhancedGlobalSecondaryIndex.builder() .indexName("lsi_1") .projection(p -> p.projectionType(ProjectionType.ALL)) .provisionedThroughput(p -> p.readCapacityUnits(1L).writeCapacityUnits(1L)) .build()); CreateTableOperation<FakeItemWithIndices> operation = CreateTableOperation.create(CreateTableEnhancedRequest.builder().globalSecondaryIndices(validLsiList).build()); CreateTableRequest request = operation.generateRequest(FakeItemWithIndices.getTableSchema(), PRIMARY_CONTEXT, null); assertThat(request.globalSecondaryIndexes().size(), is(1)); software.amazon.awssdk.services.dynamodb.model.GlobalSecondaryIndex globalSecondaryIndex = request.globalSecondaryIndexes().get(0); assertThat(globalSecondaryIndex.indexName(), is("lsi_1")); } @Test public void generateRequest_nonReferencedIndicesDoNotCreateExtraAttributeDefinitions() { CreateTableOperation<FakeItemWithIndices> operation = CreateTableOperation.create(CreateTableEnhancedRequest.builder().build()); CreateTableRequest request = operation.generateRequest(FakeItemWithIndices.getTableSchema(), PRIMARY_CONTEXT, null); AttributeDefinition attributeDefinition1 = AttributeDefinition.builder() .attributeName("id") .attributeType(ScalarAttributeType.S) .build(); AttributeDefinition attributeDefinition2 = AttributeDefinition.builder() .attributeName("sort") .attributeType(ScalarAttributeType.S) .build(); assertThat(request.attributeDefinitions(), containsInAnyOrder(attributeDefinition1, attributeDefinition2)); } @Test(expected = IllegalArgumentException.class) public void generateRequest_invalidLsi() { List<EnhancedLocalSecondaryIndex> invalidLsiList = Collections.singletonList( EnhancedLocalSecondaryIndex.create("invalid", Projection.builder().projectionType(ProjectionType.ALL).build())); CreateTableOperation<FakeItem> operation = CreateTableOperation.create(CreateTableEnhancedRequest.builder().localSecondaryIndices(invalidLsiList).build()); operation.generateRequest(FakeItem.getTableSchema(), PRIMARY_CONTEXT, null); } @Test public void generateRequest_withProvisionedThroughput() { ProvisionedThroughput provisionedThroughput = ProvisionedThroughput.builder() .writeCapacityUnits(1L) .readCapacityUnits(2L) .build(); CreateTableOperation<FakeItem> operation = CreateTableOperation.create( CreateTableEnhancedRequest.builder().provisionedThroughput(provisionedThroughput).build()); CreateTableRequest request = operation.generateRequest(FakeItem.getTableSchema(), PRIMARY_CONTEXT, null); assertThat(request.billingMode(), is(BillingMode.PROVISIONED)); assertThat(request.provisionedThroughput(), is(provisionedThroughput)); } @Test public void generateRequest_withNoProvisionedThroughput() { CreateTableOperation<FakeItem> operation = CreateTableOperation.create(CreateTableEnhancedRequest.builder().build()); CreateTableRequest request = operation.generateRequest(FakeItem.getTableSchema(), PRIMARY_CONTEXT, null); assertThat(request.billingMode(), is(BillingMode.PAY_PER_REQUEST)); } @Test public void generateRequest_withStreamSpecification() { StreamSpecification streamSpecification = StreamSpecification.builder() .streamEnabled(true) .streamViewType(StreamViewType.NEW_IMAGE) .build(); CreateTableOperation<FakeItem> operation = CreateTableOperation.create( CreateTableEnhancedRequest.builder().streamSpecification(streamSpecification).build()); CreateTableRequest request = operation.generateRequest(FakeItem.getTableSchema(), PRIMARY_CONTEXT, null); assertThat(request.streamSpecification(), is(streamSpecification)); } @Test public void generateRequest_withNoStreamSpecification() { CreateTableOperation<FakeItem> operation = CreateTableOperation.create(CreateTableEnhancedRequest.builder().build()); CreateTableRequest request = operation.generateRequest(FakeItem.getTableSchema(), PRIMARY_CONTEXT, null); assertThat(request.streamSpecification(), is(nullValue())); } @Test public void generateRequest_withNumericKey() { CreateTableOperation<FakeItemWithNumericSort> operation = CreateTableOperation.create(CreateTableEnhancedRequest.builder() .build()); CreateTableRequest request = operation.generateRequest(FakeItemWithNumericSort.getTableSchema(), PRIMARY_CONTEXT, null); assertThat(request.tableName(), is(TABLE_NAME)); assertThat(request.keySchema(), containsInAnyOrder(KeySchemaElement.builder() .attributeName("id") .keyType(HASH) .build(), KeySchemaElement.builder() .attributeName("sort") .keyType(RANGE) .build())); assertThat(request.globalSecondaryIndexes(), is(DefaultSdkAutoConstructList.getInstance())); assertThat(request.localSecondaryIndexes(), is(DefaultSdkAutoConstructList.getInstance())); assertThat(request.attributeDefinitions(), containsInAnyOrder( AttributeDefinition.builder() .attributeName("id") .attributeType(ScalarAttributeType.S) .build(), AttributeDefinition.builder() .attributeName("sort") .attributeType(ScalarAttributeType.N) .build())); } @Test public void generateRequest_withBinaryKey() { CreateTableOperation<FakeItemWithBinaryKey> operation = CreateTableOperation.create(CreateTableEnhancedRequest.builder() .build()); CreateTableRequest request = operation.generateRequest(FakeItemWithBinaryKey.getTableSchema(), PRIMARY_CONTEXT, null); assertThat(request.tableName(), is(TABLE_NAME)); assertThat(request.keySchema(), containsInAnyOrder(KeySchemaElement.builder() .attributeName("id") .keyType(HASH) .build())); assertThat(request.globalSecondaryIndexes(), is(empty())); assertThat(request.localSecondaryIndexes(), is(empty())); assertThat(request.attributeDefinitions(), containsInAnyOrder( AttributeDefinition.builder() .attributeName("id") .attributeType(ScalarAttributeType.B) .build())); } @Test public void generateRequest_withByteBufferKey() { CreateTableOperation<FakeItemWithByteBufferKey> operation = CreateTableOperation.create(CreateTableEnhancedRequest.builder() .build()); CreateTableRequest request = operation.generateRequest(FakeItemWithByteBufferKey.getTableSchema(), PRIMARY_CONTEXT, null); assertThat(request.tableName(), is(TABLE_NAME)); assertThat(request.keySchema(), containsInAnyOrder(KeySchemaElement.builder() .attributeName("id") .keyType(HASH) .build())); assertThat(request.globalSecondaryIndexes(), is(empty())); assertThat(request.localSecondaryIndexes(), is(empty())); assertThat(request.attributeDefinitions(), containsInAnyOrder( AttributeDefinition.builder() .attributeName("id") .attributeType(ScalarAttributeType.B) .build())); } @Test(expected = IllegalArgumentException.class) public void generateRequest_doesNotWorkForIndex() { CreateTableOperation<FakeItemWithIndices> operation = CreateTableOperation.create(CreateTableEnhancedRequest.builder() .build()); operation.generateRequest(FakeItemWithIndices.getTableSchema(), GSI_1_CONTEXT, null); } @Test public void getServiceCall_makesTheRightCallAndReturnsResponse() { CreateTableOperation<FakeItem> operation = CreateTableOperation.create(CreateTableEnhancedRequest.builder().build()); CreateTableRequest createTableRequest = CreateTableRequest.builder().build(); CreateTableResponse expectedResponse = CreateTableResponse.builder().build(); when(mockDynamoDbClient.createTable(any(CreateTableRequest.class))).thenReturn(expectedResponse); CreateTableResponse actualResponse = operation.serviceCall(mockDynamoDbClient).apply(createTableRequest); assertThat(actualResponse, sameInstance(expectedResponse)); verify(mockDynamoDbClient).createTable(same(createTableRequest)); } @Test public void transformResults_doesNothing() { CreateTableOperation<FakeItem> operation = CreateTableOperation.create(CreateTableEnhancedRequest.builder().build()); CreateTableResponse response = CreateTableResponse.builder().build(); operation.transformResponse(response, FakeItem.getTableSchema(), PRIMARY_CONTEXT, null); } }
3,997
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/internal
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/internal/operations/ScanOperationTest.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.internal.operations; import static java.util.Collections.singletonList; import static java.util.Collections.singletonMap; import static java.util.stream.Collectors.toList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasEntry; import static org.hamcrest.Matchers.is; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItem.createUniqueFakeItem; import static software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItemWithSort.createUniqueFakeItemWithSort; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.stringValue; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.core.async.SdkPublisher; import software.amazon.awssdk.core.pagination.sync.SdkIterable; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClientExtension; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbExtensionContext; 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.extensions.ReadModification; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItem; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItemWithIndices; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItemWithSort; import software.amazon.awssdk.enhanced.dynamodb.internal.extensions.DefaultDynamoDbExtensionContext; import software.amazon.awssdk.enhanced.dynamodb.model.Page; import software.amazon.awssdk.enhanced.dynamodb.model.ScanEnhancedRequest; import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.ScanRequest; import software.amazon.awssdk.services.dynamodb.model.ScanResponse; import software.amazon.awssdk.services.dynamodb.paginators.ScanIterable; import software.amazon.awssdk.services.dynamodb.paginators.ScanPublisher; @RunWith(MockitoJUnitRunner.class) public class ScanOperationTest { private static final String TABLE_NAME = "table-name"; private static final OperationContext PRIMARY_CONTEXT = DefaultOperationContext.create(TABLE_NAME, TableMetadata.primaryIndexName()); private static final OperationContext GSI_1_CONTEXT = DefaultOperationContext.create(TABLE_NAME, "gsi_1"); private final ScanOperation<FakeItem> scanOperation = ScanOperation.create(ScanEnhancedRequest.builder().build()); @Mock private DynamoDbClient mockDynamoDbClient; @Mock private DynamoDbAsyncClient mockDynamoDbAsyncClient; @Mock private DynamoDbEnhancedClientExtension mockDynamoDbEnhancedClientExtension; @Test public void getServiceCall_makesTheRightCallAndReturnsResponse() { ScanRequest scanRequest = ScanRequest.builder().build(); ScanIterable mockScanIterable = mock(ScanIterable.class); when(mockDynamoDbClient.scanPaginator(any(ScanRequest.class))).thenReturn(mockScanIterable); SdkIterable<ScanResponse> response = scanOperation.serviceCall(mockDynamoDbClient).apply(scanRequest); assertThat(response, is(mockScanIterable)); verify(mockDynamoDbClient).scanPaginator(scanRequest); } @Test public void getAsyncServiceCall_makesTheRightCallAndReturnsResponse() { ScanRequest scanRequest = ScanRequest.builder().build(); ScanPublisher mockScanPublisher = mock(ScanPublisher.class); when(mockDynamoDbAsyncClient.scanPaginator(any(ScanRequest.class))).thenReturn(mockScanPublisher); SdkPublisher<ScanResponse> response = scanOperation.asyncServiceCall(mockDynamoDbAsyncClient) .apply(scanRequest); assertThat(response, is(mockScanPublisher)); verify(mockDynamoDbAsyncClient).scanPaginator(scanRequest); } @Test public void generateRequest_defaultScan() { ScanRequest request = scanOperation.generateRequest(FakeItem.getTableSchema(), PRIMARY_CONTEXT, null); ScanRequest expectedRequest = ScanRequest.builder() .tableName(TABLE_NAME) .build(); assertThat(request, is(expectedRequest)); } @Test public void generateRequest_knowsHowToUseAnIndex() { ScanOperation<FakeItemWithIndices> operation = ScanOperation.create(ScanEnhancedRequest.builder().build()); ScanRequest scanRequest = operation.generateRequest(FakeItemWithIndices.getTableSchema(), GSI_1_CONTEXT, null); assertThat(scanRequest.indexName(), is("gsi_1")); } @Test public void generateRequest_limit() { ScanOperation<FakeItem> operation = ScanOperation.create(ScanEnhancedRequest.builder().limit(10).build()); ScanRequest request = operation.generateRequest(FakeItem.getTableSchema(), PRIMARY_CONTEXT, null); ScanRequest expectedRequest = ScanRequest.builder() .tableName(TABLE_NAME) .limit(10) .build(); assertThat(request, is(expectedRequest)); } @Test public void generateRequest_segment_totalSegments() { ScanOperation<FakeItem> operation = ScanOperation.create(ScanEnhancedRequest.builder().segment(0).totalSegments(5).build()); ScanRequest request = operation.generateRequest(FakeItem.getTableSchema(), PRIMARY_CONTEXT, null); ScanRequest expectedRequest = ScanRequest.builder() .tableName(TABLE_NAME) .segment(0) .totalSegments(5) .build(); assertThat(request, is(expectedRequest)); } @Test public void generateRequest_filterCondition_expressionAndValues() { Map<String, AttributeValue> expressionValues = singletonMap(":test-key", stringValue("test-value")); Expression filterExpression = Expression.builder().expression("test-expression").expressionValues(expressionValues).build(); ScanOperation<FakeItem> operation = ScanOperation.create(ScanEnhancedRequest.builder().filterExpression(filterExpression).build()); ScanRequest request = operation.generateRequest(FakeItem.getTableSchema(), PRIMARY_CONTEXT, null); ScanRequest expectedRequest = ScanRequest.builder() .tableName(TABLE_NAME) .filterExpression("test-expression") .expressionAttributeValues(expressionValues) .build(); assertThat(request, is(expectedRequest)); } @Test public void generateRequest_filterCondition_expressionOnly() { Expression filterExpression = Expression.builder().expression("test-expression").build(); ScanOperation<FakeItem> operation = ScanOperation.create(ScanEnhancedRequest.builder().filterExpression(filterExpression).build()); ScanRequest request = operation.generateRequest(FakeItem.getTableSchema(), PRIMARY_CONTEXT, null); ScanRequest expectedRequest = ScanRequest.builder() .tableName(TABLE_NAME) .filterExpression("test-expression") .build(); assertThat(request, is(expectedRequest)); } @Test public void generateRequest_consistentRead() { ScanOperation<FakeItem> operation = ScanOperation.create(ScanEnhancedRequest.builder().consistentRead(true).build()); ScanRequest request = operation.generateRequest(FakeItem.getTableSchema(), PRIMARY_CONTEXT, null); ScanRequest expectedRequest = ScanRequest.builder() .tableName(TABLE_NAME) .consistentRead(true) .build(); assertThat(request, is(expectedRequest)); } @Test public void generateRequest_projectionExpression() { ScanOperation<FakeItem> operation = ScanOperation.create( ScanEnhancedRequest.builder() .attributesToProject("id") .addAttributeToProject("version") .build() ); ScanRequest request = operation.generateRequest(FakeItem.getTableSchema(), PRIMARY_CONTEXT, null); Map<String, String> expectedExpressionAttributeNames = new HashMap<>(); expectedExpressionAttributeNames.put("#AMZN_MAPPED_id", "id"); expectedExpressionAttributeNames.put("#AMZN_MAPPED_version", "version"); ScanRequest expectedRequest = ScanRequest.builder() .tableName(TABLE_NAME) .projectionExpression("#AMZN_MAPPED_id,#AMZN_MAPPED_version") .expressionAttributeNames(expectedExpressionAttributeNames) .build(); assertThat(request, is(expectedRequest)); } @Test public void generateRequest_hashKeyOnly_exclusiveStartKey() { FakeItem exclusiveStartKey = createUniqueFakeItem(); Map<String, AttributeValue> keyMap = FakeItem.getTableSchema().itemToMap(exclusiveStartKey, singletonList("id")); ScanOperation<FakeItem> operation = ScanOperation.create(ScanEnhancedRequest.builder().exclusiveStartKey(keyMap).build()); ScanRequest scanRequest = operation.generateRequest(FakeItem.getTableSchema(), PRIMARY_CONTEXT, null); assertThat(scanRequest.exclusiveStartKey(), hasEntry("id", AttributeValue.builder().s(exclusiveStartKey.getId()).build())); } @Test public void generateRequest_hashAndRangeKey_exclusiveStartKey() { FakeItemWithSort exclusiveStartKey = createUniqueFakeItemWithSort(); Map<String, AttributeValue> keyMap = FakeItemWithSort.getTableSchema().itemToMap(exclusiveStartKey, FakeItemWithSort.getTableMetadata().primaryKeys()); ScanOperation<FakeItemWithSort> operation = ScanOperation.create(ScanEnhancedRequest.builder().exclusiveStartKey(keyMap).build()); ScanRequest scanRequest = operation.generateRequest(FakeItemWithSort.getTableSchema(), PRIMARY_CONTEXT, null); assertThat(scanRequest.exclusiveStartKey(), hasEntry("id", AttributeValue.builder().s(exclusiveStartKey.getId()).build())); assertThat(scanRequest.exclusiveStartKey(), hasEntry("sort", AttributeValue.builder().s(exclusiveStartKey.getSort()).build())); } @Test public void transformResults_multipleItems_returnsCorrectItems() { List<FakeItem> scanResultItems = generateFakeItemList(); List<Map<String, AttributeValue>> scanResultMaps = scanResultItems.stream().map(ScanOperationTest::getAttributeValueMap).collect(toList()); ScanResponse scanResponse = generateFakeScanResults(scanResultMaps); Page<FakeItem> scanResultPage = scanOperation.transformResponse(scanResponse, FakeItem.getTableSchema(), PRIMARY_CONTEXT, null); assertThat(scanResultPage.items(), is(scanResultItems)); } @Test public void transformResults_multipleItems_setsLastEvaluatedKey() { List<FakeItem> scanResultItems = generateFakeItemList(); FakeItem lastEvaluatedKey = createUniqueFakeItem(); List<Map<String, AttributeValue>> scanResultMaps = scanResultItems.stream().map(ScanOperationTest::getAttributeValueMap).collect(toList()); ScanResponse scanResponse = generateFakeScanResults(scanResultMaps, getAttributeValueMap(lastEvaluatedKey)); Page<FakeItem> scanResultPage = scanOperation.transformResponse(scanResponse, FakeItem.getTableSchema(), PRIMARY_CONTEXT, null); assertThat(scanResultPage.lastEvaluatedKey(), is(getAttributeValueMap(lastEvaluatedKey))); } @Test public void scanItem_withExtension_correctlyTransformsItems() { List<FakeItem> scanResultItems = generateFakeItemList(); List<FakeItem> modifiedResultItems = generateFakeItemList(); List<Map<String, AttributeValue>> scanResultMaps = scanResultItems.stream().map(ScanOperationTest::getAttributeValueMap).collect(toList()); ReadModification[] readModifications = modifiedResultItems.stream() .map(ScanOperationTest::getAttributeValueMap) .map(attributeMap -> ReadModification.builder().transformedItem(attributeMap).build()) .collect(Collectors.toList()) .toArray(new ReadModification[]{}); when(mockDynamoDbEnhancedClientExtension.afterRead(any(DynamoDbExtensionContext.AfterRead.class))) .thenReturn(readModifications[0], Arrays.copyOfRange(readModifications, 1, readModifications.length)); ScanResponse scanResponse = generateFakeScanResults(scanResultMaps); Page<FakeItem> scanResultPage = scanOperation.transformResponse(scanResponse, FakeItem.getTableSchema(), PRIMARY_CONTEXT, mockDynamoDbEnhancedClientExtension); assertThat(scanResultPage.items(), is(modifiedResultItems)); InOrder inOrder = Mockito.inOrder(mockDynamoDbEnhancedClientExtension); scanResultMaps.forEach( attributeMap -> inOrder.verify(mockDynamoDbEnhancedClientExtension).afterRead( DefaultDynamoDbExtensionContext.builder() .tableMetadata(FakeItem.getTableMetadata()) .operationContext(PRIMARY_CONTEXT) .tableSchema(FakeItem.getTableSchema()) .items(attributeMap).build())); } private static ScanResponse generateFakeScanResults(List<Map<String, AttributeValue>> scanItemMapsPage) { return ScanResponse.builder().items(scanItemMapsPage).build(); } private static ScanResponse generateFakeScanResults(List<Map<String, AttributeValue>> scanItemMapsPage, Map<String, AttributeValue> lastEvaluatedKey) { return ScanResponse.builder() .items(scanItemMapsPage) .lastEvaluatedKey(lastEvaluatedKey) .build(); } private static List<FakeItem> generateFakeItemList() { return IntStream.range(0, 3).mapToObj(ignored -> FakeItem.createUniqueFakeItem()).collect(toList()); } private static Map<String, AttributeValue> getAttributeValueMap(FakeItem fakeItem) { return singletonMap("id", AttributeValue.builder().s(fakeItem.getId()).build()); } }
3,998
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/internal
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/internal/operations/TransactWriteItemsOperationTest.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.internal.operations; import static java.util.Collections.singletonList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.sameInstance; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; 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.DynamoDbEnhancedClientExtension; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItem; import software.amazon.awssdk.enhanced.dynamodb.model.TransactWriteItemsEnhancedRequest; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.Put; import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem; import software.amazon.awssdk.services.dynamodb.model.TransactWriteItemsRequest; import software.amazon.awssdk.services.dynamodb.model.TransactWriteItemsResponse; @RunWith(MockitoJUnitRunner.class) public class TransactWriteItemsOperationTest { private static final String TABLE_NAME = "table-name"; private final FakeItem fakeItem1 = FakeItem.createUniqueFakeItem(); private final FakeItem fakeItem2 = FakeItem.createUniqueFakeItem(); private final Map<String, AttributeValue> fakeItemMap1 = FakeItem.getTableSchema().itemToMap(fakeItem1, true); private final Map<String, AttributeValue> fakeItemMap2 = FakeItem.getTableSchema().itemToMap(fakeItem2, true); @Mock private DynamoDbEnhancedClientExtension mockDynamoDbEnhancedClientExtension; @Mock private DynamoDbClient mockDynamoDbClient; private TransactWriteItem fakeTransactWriteItem1 = TransactWriteItem.builder() .put(Put.builder() .item(fakeItemMap1) .tableName(TABLE_NAME) .build()) .build(); private TransactWriteItem fakeTransactWriteItem2 = TransactWriteItem.builder() .put(Put.builder() .item(fakeItemMap2) .tableName(TABLE_NAME) .build()) .build(); private DynamoDbEnhancedClient enhancedClient; private DynamoDbTable<FakeItem> fakeItemMappedTable; @Before public void setupMappedTables() { enhancedClient = DynamoDbEnhancedClient.builder().dynamoDbClient(mockDynamoDbClient).extensions().build(); fakeItemMappedTable = enhancedClient.table(TABLE_NAME, FakeItem.getTableSchema()); } @Test public void generateRequest_singleTransaction() { TransactWriteItemsEnhancedRequest transactGetItemsEnhancedRequest = TransactWriteItemsEnhancedRequest.builder() .addPutItem(fakeItemMappedTable, fakeItem1) .build(); TransactWriteItemsOperation operation = TransactWriteItemsOperation.create(transactGetItemsEnhancedRequest); TransactWriteItemsRequest actualRequest = operation.generateRequest(mockDynamoDbEnhancedClientExtension); TransactWriteItemsRequest expectedRequest = TransactWriteItemsRequest.builder() .transactItems(fakeTransactWriteItem1) .build(); assertThat(actualRequest, is(expectedRequest)); verifyNoMoreInteractions(mockDynamoDbEnhancedClientExtension); } @Test public void generateRequest_multipleTransactions() { TransactWriteItemsEnhancedRequest transactGetItemsEnhancedRequest = TransactWriteItemsEnhancedRequest.builder() .addPutItem(fakeItemMappedTable, fakeItem1) .addPutItem(fakeItemMappedTable, fakeItem2) .build(); TransactWriteItemsOperation operation = TransactWriteItemsOperation.create(transactGetItemsEnhancedRequest); TransactWriteItemsRequest actualRequest = operation.generateRequest(mockDynamoDbEnhancedClientExtension); TransactWriteItemsRequest expectedRequest = TransactWriteItemsRequest.builder() .transactItems(fakeTransactWriteItem1, fakeTransactWriteItem2) .build(); assertThat(actualRequest, is(expectedRequest)); verifyNoMoreInteractions(mockDynamoDbEnhancedClientExtension); } @Test public void generateRequest_noTransactions() { TransactWriteItemsOperation operation = TransactWriteItemsOperation.create(emptyRequest()); TransactWriteItemsRequest actualRequest = operation.generateRequest(mockDynamoDbEnhancedClientExtension); TransactWriteItemsRequest expectedRequest = TransactWriteItemsRequest.builder().build(); assertThat(actualRequest, is(expectedRequest)); verifyNoMoreInteractions(mockDynamoDbEnhancedClientExtension); } @Test public void getServiceCall_callsServiceAndReturnsResult() { TransactWriteItemsOperation operation = TransactWriteItemsOperation.create(emptyRequest()); TransactWriteItemsRequest request = TransactWriteItemsRequest.builder() .transactItems(singletonList(fakeTransactWriteItem1)) .build(); TransactWriteItemsResponse expectedResponse = TransactWriteItemsResponse.builder() .build(); when(mockDynamoDbClient.transactWriteItems(any(TransactWriteItemsRequest.class))).thenReturn(expectedResponse); TransactWriteItemsResponse actualResponse = operation.serviceCall(mockDynamoDbClient).apply(request); assertThat(actualResponse, is(sameInstance(expectedResponse))); verify(mockDynamoDbClient).transactWriteItems(request); verifyNoMoreInteractions(mockDynamoDbEnhancedClientExtension); } @Test public void transformResponse_doesNothing() { TransactWriteItemsOperation operation = TransactWriteItemsOperation.create(emptyRequest()); TransactWriteItemsResponse response = TransactWriteItemsResponse.builder().build(); operation.transformResponse(response, mockDynamoDbEnhancedClientExtension); verifyNoMoreInteractions(mockDynamoDbEnhancedClientExtension); } private TransactWriteItemsEnhancedRequest emptyRequest() { return TransactWriteItemsEnhancedRequest.builder().build(); } }
3,999