index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/converters
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/converters/attribute/JsonItemAttributeConverterTest.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.converters.attribute; import static org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.enhanced.dynamodb.converters.attribute.ConverterTestUtils.transformFrom; import static software.amazon.awssdk.enhanced.dynamodb.converters.attribute.ConverterTestUtils.transformTo; import static software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.EnhancedAttributeValue.fromNumber; import static software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.EnhancedAttributeValue.fromString; import java.util.LinkedHashMap; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.SdkNumber; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.CharacterArrayAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.JsonItemAttributeConverter; import software.amazon.awssdk.protocols.jsoncore.JsonNode; import software.amazon.awssdk.protocols.jsoncore.internal.ArrayJsonNode; import software.amazon.awssdk.protocols.jsoncore.internal.BooleanJsonNode; import software.amazon.awssdk.protocols.jsoncore.internal.NumberJsonNode; import software.amazon.awssdk.protocols.jsoncore.internal.ObjectJsonNode; import software.amazon.awssdk.protocols.jsoncore.internal.StringJsonNode; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; class JsonItemAttributeConverterTest { @Test void jsonAttributeConverterWithString() { JsonItemAttributeConverter converter = JsonItemAttributeConverter.create(); StringJsonNode stringJsonNode = new StringJsonNode("testString"); assertThat(transformFrom(converter, stringJsonNode).s()).isEqualTo("testString"); assertThat(transformTo(converter, AttributeValue.fromS("testString"))).isEqualTo(stringJsonNode); } @Test void jsonAttributeConverterWithBoolean() { JsonItemAttributeConverter converter = JsonItemAttributeConverter.create(); BooleanJsonNode booleanJsonNode = new BooleanJsonNode(true); assertThat(transformFrom(converter, booleanJsonNode).bool()).isTrue(); assertThat(transformFrom(converter, booleanJsonNode).s()).isNull(); assertThat(transformTo(converter, AttributeValue.fromBool(true))).isEqualTo(booleanJsonNode); } @Test void jsonAttributeConverterWithNumber() { JsonItemAttributeConverter converter = JsonItemAttributeConverter.create(); NumberJsonNode numberJsonNode = new NumberJsonNode("20"); assertThat(transformFrom(converter, numberJsonNode).n()).isEqualTo("20"); assertThat(transformFrom(converter, numberJsonNode).s()).isNull(); assertThat(transformTo(converter, AttributeValue.fromN("20"))).isEqualTo(numberJsonNode); } @Test void jsonAttributeConverterWithSdkBytes() { JsonItemAttributeConverter converter = JsonItemAttributeConverter.create(); StringJsonNode sdkByteJsonNode = new StringJsonNode(SdkBytes.fromUtf8String("a").asUtf8String()); assertThat(transformFrom(converter, sdkByteJsonNode).s()).isEqualTo(SdkBytes.fromUtf8String("a").asUtf8String()); assertThat(transformFrom(converter, sdkByteJsonNode).b()).isNull(); assertThat(transformTo(converter, AttributeValue.fromB(SdkBytes.fromUtf8String("a")))).isEqualTo(new StringJsonNode("YQ==")); } @Test void jsonAttributeConverterWithSet() { JsonItemAttributeConverter converter = JsonItemAttributeConverter.create(); ArrayJsonNode arrayJsonNode = new ArrayJsonNode(Stream.of(new NumberJsonNode("10"), new NumberJsonNode("20")).collect(Collectors.toList())); assertThat(transformFrom(converter, arrayJsonNode).l()) .isEqualTo(Stream.of(AttributeValue.fromN("10"), AttributeValue.fromN("20")) .collect(Collectors.toList())); } @Test void jsonAttributeWithMap(){ Map<String, JsonNode> jsonNodeMap = new LinkedHashMap<>(); jsonNodeMap.put("key", new StringJsonNode("value")); ObjectJsonNode objectJsonNode = new ObjectJsonNode(jsonNodeMap); JsonItemAttributeConverter converter = JsonItemAttributeConverter.create(); AttributeValue convertedMap = converter.transformFrom(objectJsonNode); assertThat(convertedMap.hasM()).isTrue(); Map<String, AttributeValue> expectedMap = new LinkedHashMap<>(); expectedMap.put("key", AttributeValue.fromS("value")); assertThat(convertedMap).isEqualTo(AttributeValue.fromM(expectedMap)); } }
4,300
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/converters
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/converters/attribute/BinaryAttributeConvertersTest.java
/* * Copyright 2010-2019 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.converters.attribute; import static org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.enhanced.dynamodb.converters.attribute.ConverterTestUtils.transformFrom; import static software.amazon.awssdk.enhanced.dynamodb.converters.attribute.ConverterTestUtils.transformTo; import java.nio.ByteBuffer; import java.util.Set; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.ByteArrayAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.ByteBufferAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.EnhancedAttributeValue; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.SdkBytesAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.SetAttributeConverter; public class BinaryAttributeConvertersTest { @Test public void byteArrayAttributeConverterBehaves() { ByteArrayAttributeConverter converter = ByteArrayAttributeConverter.create(); byte[] emptyBytes = new byte[0]; byte[] bytes = "foo".getBytes(); assertThat(transformFrom(converter, bytes).b().asByteArray()).isEqualTo(bytes); assertThat(transformFrom(converter, emptyBytes).b().asByteArray()).isEqualTo(emptyBytes); assertThat(transformTo(converter, EnhancedAttributeValue.fromBytes(SdkBytes.fromUtf8String("foo")).toAttributeValue())).isEqualTo(bytes); assertThat(transformTo(converter, EnhancedAttributeValue.fromBytes(SdkBytes.fromUtf8String("")).toAttributeValue())).isEqualTo(emptyBytes); } @Test public void sdkBytesAttributeConverterBehaves() { SdkBytesAttributeConverter converter = SdkBytesAttributeConverter.create(); SdkBytes bytes = SdkBytes.fromUtf8String(""); assertThat(transformFrom(converter, bytes).b()).isSameAs(bytes); assertThat(transformTo(converter, EnhancedAttributeValue.fromBytes(bytes).toAttributeValue())).isSameAs(bytes); } @Test public void sdkBytesSetAttributeConverter_ReturnsBSType() { SetAttributeConverter<Set<SdkBytes>> bytesSet = SetAttributeConverter.setConverter(SdkBytesAttributeConverter.create()); assertThat(bytesSet.attributeValueType()).isEqualTo(AttributeValueType.BS); } @Test public void byteBufferAttributeConverterBehaves() { ByteBufferAttributeConverter converter = ByteBufferAttributeConverter.create(); assertThat(converter.attributeValueType()).isEqualTo(AttributeValueType.B); String foo = "foo"; ByteBuffer byteBuffer = ByteBuffer.wrap(foo.getBytes()); SdkBytes sdkBytes = SdkBytes.fromUtf8String(foo); assertThat(transformFrom(converter, byteBuffer).b()).isEqualTo(sdkBytes); assertThat(transformTo(converter, EnhancedAttributeValue.fromBytes(sdkBytes).toAttributeValue())).isEqualTo(byteBuffer); } }
4,301
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/converters
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/converters/attribute/LocalDateTimeAttributeConverterTest.java
/* * Copyright 2010-2019 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.converters.attribute; import static org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.enhanced.dynamodb.converters.attribute.ConverterTestUtils.assertFails; import static software.amazon.awssdk.enhanced.dynamodb.converters.attribute.ConverterTestUtils.transformFrom; import static software.amazon.awssdk.enhanced.dynamodb.converters.attribute.ConverterTestUtils.transformTo; import java.time.LocalDateTime; import org.junit.jupiter.api.Test; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.EnhancedAttributeValue; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.LocalDateTimeAttributeConverter; public class LocalDateTimeAttributeConverterTest { private static LocalDateTimeAttributeConverter converter = LocalDateTimeAttributeConverter.create(); @Test public void localDateTimeAttributeConverterMinTest() { verifyTransform(LocalDateTime.MIN, "-999999999-01-01T00:00"); } @Test public void localDateTimeAttributeConverterNormalTest() { verifyTransform(LocalDateTime.of(0, 1, 1, 0, 0, 0, 0), "0000-01-01T00:00"); } @Test public void localDateTimeAttributeConverterMaxTest() { verifyTransform(LocalDateTime.MAX, "+999999999-12-31T23:59:59.999999999"); } @Test public void localDateTimeAttributeConverterLowerBoundTest() { assertFails(() -> transformTo(converter, EnhancedAttributeValue.fromString("-9999999999-01-01T00:00") .toAttributeValue())); } @Test public void localDateTimeAttributeConverterHigherBoundTest() { assertFails(() -> transformTo(converter, EnhancedAttributeValue.fromString("9999999999-12-31T00:00:00") .toAttributeValue())); } @Test public void localDateTimeAttributeConverterExceedHigherBoundTest() { assertFails(() -> transformTo(converter, EnhancedAttributeValue.fromString("9999999999-12-32T00:00:00") .toAttributeValue())); } @Test public void localDateTimeAttributeConverterInvalidNanoSecondsTest() { assertFails(() -> transformTo(converter, EnhancedAttributeValue.fromString("0-01-01T00:00:00.9999999999") .toAttributeValue())); } @Test public void localDateTimeAttributeConverterNotAcceptInstantTest() { assertFails(() -> transformTo(converter, EnhancedAttributeValue.fromString("1988-05-21T00:12:00.000000001Z") .toAttributeValue())); } @Test public void localDateTimeAttributeConverterNotAcceptOffsetTimeTest() { assertFails(() -> transformTo(converter, EnhancedAttributeValue.fromString("1988-05-21T00:12:00+01:00") .toAttributeValue())); } @Test public void localDateTimeAttributeConverterNotAcceptZonedTimeTest() { assertFails(() -> transformTo(converter, EnhancedAttributeValue.fromString("1988-05-21T00:12:00+01:00[Europe/Paris]") .toAttributeValue())); } @Test public void localDateTimeAttributeConverterNotAcceptLocalTimeTest() { assertFails(() -> transformTo(converter, EnhancedAttributeValue.fromString("00:12:00.000000001") .toAttributeValue())); } @Test public void localDateTimeAttributeConverterNotAcceptMonthDayTest() { assertFails(() -> transformTo(converter, EnhancedAttributeValue.fromString("05-21") .toAttributeValue())); } @Test public void localDateTimeAttributeConverterAdditionallyAcceptLocalDateTest() { assertThat(transformTo(converter, EnhancedAttributeValue.fromString("1988-05-21").toAttributeValue())) .isEqualTo(LocalDateTime.of(1988, 5, 21, 0, 0, 0)); } private void verifyTransform(LocalDateTime objectToTransform, String attributeValueString) { assertThat(transformFrom(converter, objectToTransform)) .isEqualTo(EnhancedAttributeValue.fromString(attributeValueString).toAttributeValue()); assertThat(transformTo(converter, EnhancedAttributeValue.fromString(attributeValueString).toAttributeValue())) .isEqualTo(objectToTransform); } }
4,302
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/converters
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/converters/attribute/EnumAttributeConverterTest.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.converters.attribute; import org.junit.jupiter.api.Test; import software.amazon.awssdk.enhanced.dynamodb.EnumAttributeConverter; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import static org.assertj.core.api.Assertions.assertThat; public class EnumAttributeConverterTest { @Test public void transformFromDefault_returnsToString() { EnumAttributeConverter<Vehicle> vehicleConverter = EnumAttributeConverter.create(Vehicle.class); AttributeValue attribute = vehicleConverter.transformFrom(Vehicle.TRUCK); assertThat(attribute.s()).isEqualTo("TRUCK"); } @Test public void transformToDefault_returnsEnum() { EnumAttributeConverter<Vehicle> vehicleConverter = EnumAttributeConverter.create(Vehicle.class); Vehicle bike = vehicleConverter.transformTo(AttributeValue.fromS("BIKE")); assertThat(bike).isEqualTo(Vehicle.BIKE); } @Test public void transformFromDefault_returnsToString_2() { EnumAttributeConverter<Animal> animalConverter = EnumAttributeConverter.create(Animal.class); AttributeValue attribute = animalConverter.transformFrom(Animal.CAT); assertThat(attribute.s()).isEqualTo("I am a Cat!"); } @Test public void transformToDefault_returnsEnum_2() { EnumAttributeConverter<Animal> animalConverter = EnumAttributeConverter.create(Animal.class); Animal dog = animalConverter.transformTo(AttributeValue.fromS("I am a Dog!")); assertThat(dog).isEqualTo(Animal.DOG); } @Test public void transformFromWithNames_returnsName() { EnumAttributeConverter<Person> personConverter = EnumAttributeConverter.createWithNameAsKeys(Person.class); AttributeValue attribute = personConverter.transformFrom(Person.JANE); assertThat(attribute.s()).isEqualTo("JANE"); assertThat(Person.JANE.toString()).isEqualTo("I am a cool person"); } @Test public void transformToWithNames_returnsEnum() { EnumAttributeConverter<Person> personConverter = EnumAttributeConverter.createWithNameAsKeys(Person.class); Person john = personConverter.transformTo(AttributeValue.fromS("JOHN")); assertThat(Person.JOHN.toString()).isEqualTo("I am a cool person"); assertThat(john).isEqualTo(Person.JOHN); } private static enum Vehicle { CAR, BIKE, TRUCK } private static enum Animal { DOG, CAT; @Override public String toString() { switch (this) { case DOG: return "I am a Dog!"; case CAT: return "I am a Cat!"; default: return null; } } } private static enum Person { JOHN, JANE; @Override public String toString() { return "I am a cool person"; } } }
4,303
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/converters
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/converters/attribute/BooleanAttributeConvertersTest.java
/* * Copyright 2010-2019 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.converters.attribute; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static software.amazon.awssdk.enhanced.dynamodb.converters.attribute.ConverterTestUtils.assertFails; import static software.amazon.awssdk.enhanced.dynamodb.converters.attribute.ConverterTestUtils.transformFrom; import static software.amazon.awssdk.enhanced.dynamodb.converters.attribute.ConverterTestUtils.transformTo; import java.util.concurrent.atomic.AtomicBoolean; import org.junit.jupiter.api.Test; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.AtomicBooleanAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.BooleanAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.EnhancedAttributeValue; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.SetAttributeConverter; public class BooleanAttributeConvertersTest { @Test public void atomicBooleanAttributeConverterBehaves() { AtomicBooleanAttributeConverter converter = AtomicBooleanAttributeConverter.create(); assertThat(transformFrom(converter, new AtomicBoolean(true)).bool()).isEqualTo(true); assertThat(transformFrom(converter, new AtomicBoolean(false)).bool()).isEqualTo(false); assertFails(() -> transformTo(converter, EnhancedAttributeValue.fromString("FALSE").toAttributeValue())); assertFails(() -> transformTo(converter, EnhancedAttributeValue.fromString("TRUE").toAttributeValue())); assertFails(() -> transformTo(converter, EnhancedAttributeValue.fromString("0").toAttributeValue())); assertFails(() -> transformTo(converter, EnhancedAttributeValue.fromString("1").toAttributeValue())); assertFails(() -> transformTo(converter, EnhancedAttributeValue.fromString("").toAttributeValue())); assertThat(transformTo(converter, EnhancedAttributeValue.fromNumber("1").toAttributeValue())).isTrue(); assertThat(transformTo(converter, EnhancedAttributeValue.fromNumber("0").toAttributeValue())).isFalse(); assertThat(transformTo(converter, EnhancedAttributeValue.fromString("true").toAttributeValue())).isTrue(); assertThat(transformTo(converter, EnhancedAttributeValue.fromString("false").toAttributeValue())).isFalse(); assertThat(transformTo(converter, EnhancedAttributeValue.fromBoolean(true).toAttributeValue())).isTrue(); assertThat(transformTo(converter, EnhancedAttributeValue.fromBoolean(false).toAttributeValue())).isFalse(); } @Test public void booleanAttributeConverterBehaves() { BooleanAttributeConverter converter = BooleanAttributeConverter.create(); assertThat(transformFrom(converter, true).bool()).isEqualTo(true); assertThat(transformFrom(converter, false).bool()).isEqualTo(false); assertFails(() -> transformTo(converter, EnhancedAttributeValue.fromString("FALSE").toAttributeValue())); assertFails(() -> transformTo(converter, EnhancedAttributeValue.fromString("TRUE").toAttributeValue())); assertFails(() -> transformTo(converter, EnhancedAttributeValue.fromString("0").toAttributeValue())); assertFails(() -> transformTo(converter, EnhancedAttributeValue.fromString("1").toAttributeValue())); assertFails(() -> transformTo(converter, EnhancedAttributeValue.fromString("").toAttributeValue())); assertThat(transformTo(converter, EnhancedAttributeValue.fromNumber("1").toAttributeValue())).isTrue(); assertThat(transformTo(converter, EnhancedAttributeValue.fromNumber("0").toAttributeValue())).isFalse(); assertThat(transformTo(converter, EnhancedAttributeValue.fromString("true").toAttributeValue())).isTrue(); assertThat(transformTo(converter, EnhancedAttributeValue.fromString("false").toAttributeValue())).isFalse(); assertThat(transformTo(converter, EnhancedAttributeValue.fromBoolean(true).toAttributeValue())).isTrue(); assertThat(transformTo(converter, EnhancedAttributeValue.fromBoolean(false).toAttributeValue())).isFalse(); } @Test public void setOfBooleanAttributeConverter_ThrowsIllegalArgumentException() { assertThatThrownBy(() -> SetAttributeConverter.setConverter(BooleanAttributeConverter.create())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("SetAttributeConverter cannot be created") .hasMessageContaining("Boolean"); } }
4,304
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/converters
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/converters/attribute/StringAttributeConvertersTest.java
/* * Copyright 2010-2019 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.converters.attribute; import static org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.enhanced.dynamodb.converters.attribute.ConverterTestUtils.assertFails; import static software.amazon.awssdk.enhanced.dynamodb.converters.attribute.ConverterTestUtils.transformFrom; import static software.amazon.awssdk.enhanced.dynamodb.converters.attribute.ConverterTestUtils.transformTo; import static software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.EnhancedAttributeValue.fromBoolean; import static software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.EnhancedAttributeValue.fromBytes; import static software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.EnhancedAttributeValue.fromListOfAttributeValues; import static software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.EnhancedAttributeValue.fromMap; import static software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.EnhancedAttributeValue.fromNumber; import static software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.EnhancedAttributeValue.fromSetOfBytes; import static software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.EnhancedAttributeValue.fromSetOfNumbers; import static software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.EnhancedAttributeValue.fromSetOfStrings; import static software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.EnhancedAttributeValue.fromString; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import java.time.Period; import java.time.ZoneId; import java.time.ZoneOffset; import java.util.Locale; import java.util.Set; import java.util.UUID; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType; import software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.CharSequenceAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.CharacterArrayAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.CharacterAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.LocaleAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.PeriodAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.SetAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.StringAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.StringBufferAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.StringBuilderAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.UriAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.UrlAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.UuidAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.ZoneIdAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.ZoneOffsetAttributeConverter; import software.amazon.awssdk.utils.ImmutableMap; public class StringAttributeConvertersTest { @Test public void charArrayAttributeConverterBehaves() { CharacterArrayAttributeConverter converter = CharacterArrayAttributeConverter.create(); char[] emptyChars = {}; char[] chars = {'f', 'o', 'o'}; char[] numChars = {'4', '2'}; assertThat(transformFrom(converter, chars).s()).isEqualTo("foo"); assertThat(transformFrom(converter, emptyChars).s()).isEqualTo(""); assertThat(transformTo(converter, fromString(""))).isEqualTo(emptyChars); assertThat(transformTo(converter, fromString("foo"))).isEqualTo(chars); assertThat(transformTo(converter, fromNumber("42"))).isEqualTo(numChars); } @Test public void characterAttributeConverterBehaves() { CharacterAttributeConverter converter = CharacterAttributeConverter.create(); assertThat(transformFrom(converter, 'a').s()).isEqualTo("a"); assertFails(() -> transformTo(converter, fromString(""))); assertFails(() -> transformTo(converter, fromString("ab"))); assertThat(transformTo(converter, fromString("a"))).isEqualTo('a'); } @Test public void charSequenceAttributeConverterBehaves() { CharSequenceAttributeConverter converter = CharSequenceAttributeConverter.create(); CharSequence emptyChars = ""; CharSequence chars = "foo"; CharSequence numChars = "42"; assertThat(transformFrom(converter, chars).s()).isEqualTo("foo"); assertThat(transformFrom(converter, emptyChars).s()).isEqualTo(""); assertThat(transformTo(converter, fromString(""))).isEqualTo(emptyChars); assertThat(transformTo(converter, fromString("foo"))).isEqualTo(chars); assertThat(transformTo(converter, fromNumber("42"))).isEqualTo(numChars); } @Test public void periodAttributeConverterBehaves() { PeriodAttributeConverter converter = PeriodAttributeConverter.create(); assertThat(transformFrom(converter, Period.ofYears(-5)).s()).isEqualTo("P-5Y"); assertThat(transformFrom(converter, Period.ofDays(-1)).s()).isEqualTo("P-1D"); assertThat(transformFrom(converter, Period.ZERO).s()).isEqualTo("P0D"); assertThat(transformFrom(converter, Period.ofDays(1)).s()).isEqualTo("P1D"); assertThat(transformFrom(converter, Period.ofYears(5)).s()).isEqualTo("P5Y"); assertFails(() -> transformTo(converter, fromString(""))); assertFails(() -> transformTo(converter, fromString("P"))); assertThat(transformTo(converter, fromString("P-5Y"))).isEqualTo(Period.ofYears(-5)); assertThat(transformTo(converter, fromString("P-1D"))).isEqualTo(Period.ofDays(-1)); assertThat(transformTo(converter, fromString("P0D"))).isEqualTo(Period.ZERO); assertThat(transformTo(converter, fromString("P1D"))).isEqualTo(Period.ofDays(1)); assertThat(transformTo(converter, fromString("P5Y"))).isEqualTo(Period.ofYears(5)); } @Test public void stringAttributeConverterBehaves() { StringAttributeConverter converter = StringAttributeConverter.create(); String emptyChars = ""; String chars = "foo"; String numChars = "42"; assertThat(transformFrom(converter, null)).isSameAs(AttributeValues.nullAttributeValue()); assertThat(transformFrom(converter, chars).s()).isSameAs(chars); assertThat(transformFrom(converter, emptyChars).s()).isSameAs(emptyChars); assertThat(transformTo(converter, fromString(emptyChars))).isSameAs(emptyChars); assertThat(transformTo(converter, fromString(chars))).isSameAs(chars); assertThat(transformTo(converter, fromNumber(emptyChars))).isSameAs(emptyChars); assertThat(transformTo(converter, fromNumber(numChars))).isSameAs(numChars); assertThat(transformTo(converter, fromBytes(SdkBytes.fromUtf8String("foo")))).isEqualTo("Zm9v"); assertThat(transformTo(converter, fromBoolean(true))).isEqualTo("true"); assertThat(transformTo(converter, fromBoolean(false))).isEqualTo("false"); assertThat(transformTo(converter, fromMap(ImmutableMap.of("a", fromString("b").toAttributeValue(), "c", fromBytes(SdkBytes.fromUtf8String("d")).toAttributeValue())))) .isEqualTo("{a=b, c=ZA==}"); assertThat(transformTo(converter, fromListOfAttributeValues(fromString("a").toAttributeValue(), fromBytes(SdkBytes.fromUtf8String("d")).toAttributeValue()))) .isEqualTo("[a, ZA==]"); assertThat(transformTo(converter, fromSetOfStrings("a", "b"))).isEqualTo("[a, b]"); assertThat(transformTo(converter, fromSetOfBytes(SdkBytes.fromUtf8String("a"), SdkBytes.fromUtf8String("b")))) .isEqualTo("[YQ==,Yg==]"); assertThat(transformTo(converter, fromSetOfNumbers("1", "2"))).isEqualTo("[1, 2]"); } @Test public void stringBuilderAttributeConverterBehaves() { StringBuilderAttributeConverter converter = StringBuilderAttributeConverter.create(); assertThat(transformFrom(converter, new StringBuilder()).s()).isEqualTo(""); assertThat(transformFrom(converter, new StringBuilder("foo")).s()).isEqualTo("foo"); assertThat(transformFrom(converter, new StringBuilder("42")).s()).isEqualTo("42"); assertThat(transformTo(converter, fromString("")).toString()).isEqualTo(""); assertThat(transformTo(converter, fromString("foo")).toString()).isEqualTo("foo"); assertThat(transformTo(converter, fromNumber("42")).toString()).isEqualTo("42"); } @Test public void stringBufferAttributeConverterBehaves() { StringBufferAttributeConverter converter = StringBufferAttributeConverter.create(); assertThat(transformFrom(converter, new StringBuffer()).s()).isEqualTo(""); assertThat(transformFrom(converter, new StringBuffer("foo")).s()).isEqualTo("foo"); assertThat(transformFrom(converter, new StringBuffer("42")).s()).isEqualTo("42"); assertThat(transformTo(converter, fromString("")).toString()).isEqualTo(""); assertThat(transformTo(converter, fromString("foo")).toString()).isEqualTo("foo"); assertThat(transformTo(converter, fromNumber("42")).toString()).isEqualTo("42"); } @Test public void localeAttributeConverterBehaves() { LocaleAttributeConverter converter = LocaleAttributeConverter.create(); assertThat(transformFrom(converter, Locale.US).s()).isEqualTo("en-US"); assertThat(transformTo(converter, fromString("en-US"))).isEqualTo(Locale.US); } @Test public void uriAttributeConverterBehaves() { UriAttributeConverter converter = UriAttributeConverter.create(); assertThat(transformFrom(converter, URI.create("http://example.com/languages/java/")).s()) .isEqualTo("http://example.com/languages/java/"); assertThat(transformFrom(converter, URI.create("sample/a/index.html#28")).s()) .isEqualTo("sample/a/index.html#28"); assertThat(transformFrom(converter, URI.create("../../demo/b/index.html")).s()) .isEqualTo("../../demo/b/index.html"); assertThat(transformFrom(converter, URI.create("file:///~/calendar")).s()).isEqualTo("file:///~/calendar"); assertThat(transformTo(converter, fromString("http://example.com/languages/java/"))) .isEqualTo(URI.create("http://example.com/languages/java/")); assertThat(transformTo(converter, fromString("sample/a/index.html#28"))) .isEqualTo(URI.create("sample/a/index.html#28")); assertThat(transformTo(converter, fromString("../../demo/b/index.html"))) .isEqualTo(URI.create("../../demo/b/index.html")); assertThat(transformTo(converter, fromString("file:///~/calendar"))) .isEqualTo(URI.create("file:///~/calendar")); } @Test public void urlAttributeConverterBehaves() throws MalformedURLException { UrlAttributeConverter converter = UrlAttributeConverter.create(); assertThat(transformFrom(converter, new URL("http://example.com/languages/java/")).s()) .isEqualTo("http://example.com/languages/java/"); assertThat(transformTo(converter, fromString("http://example.com/languages/java/"))) .isEqualTo(new URL("http://example.com/languages/java/")); } @Test public void uuidAttributeConverterBehaves() { UuidAttributeConverter converter = UuidAttributeConverter.create(); UUID uuid = UUID.randomUUID(); assertThat(transformFrom(converter, uuid).s()).isEqualTo(uuid.toString()); assertThat(transformTo(converter, fromString(uuid.toString()))).isEqualTo(uuid); } @Test public void zoneIdAttributeConverterBehaves() { ZoneIdAttributeConverter converter = ZoneIdAttributeConverter.create(); assertThat(transformFrom(converter, ZoneId.of("UTC")).s()).isEqualTo("UTC"); assertFails(() -> transformTo(converter, fromString("XXXXXX"))); assertThat(transformTo(converter, fromString("UTC"))).isEqualTo(ZoneId.of("UTC")); } @Test public void zoneOffsetAttributeConverterBehaves() { ZoneOffsetAttributeConverter converter = ZoneOffsetAttributeConverter.create(); assertThat(transformFrom(converter, ZoneOffset.ofHoursMinutesSeconds(0, -1, -2)).s()).isEqualTo("-00:01:02"); assertThat(transformFrom(converter, ZoneOffset.ofHoursMinutesSeconds(0, 1, 2)).s()).isEqualTo("+00:01:02"); assertFails(() -> transformTo(converter, fromString("+99999:00:00"))); assertThat(transformTo(converter, fromString("-00:01:02"))) .isEqualTo(ZoneOffset.ofHoursMinutesSeconds(0, -1, -2)); assertThat(transformTo(converter, fromString("+00:01:02"))) .isEqualTo(ZoneOffset.ofHoursMinutesSeconds(0, 1, 2)); } @Test public void stringSetAttributeConverter_ReturnsSSType() { SetAttributeConverter<Set<String>> converter = SetAttributeConverter.setConverter(StringAttributeConverter.create()); assertThat(converter.attributeValueType()).isEqualTo(AttributeValueType.SS); } }
4,305
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/converters
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/converters/attribute/MonthDayAttributeConverterTest.java
package software.amazon.awssdk.enhanced.dynamodb.converters.attribute; import static org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.enhanced.dynamodb.converters.attribute.ConverterTestUtils.assertFails; import static software.amazon.awssdk.enhanced.dynamodb.converters.attribute.ConverterTestUtils.transformFrom; import static software.amazon.awssdk.enhanced.dynamodb.converters.attribute.ConverterTestUtils.transformTo; import java.time.MonthDay; import org.junit.jupiter.api.Test; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.EnhancedAttributeValue; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.MonthDayAttributeConverter; public class MonthDayAttributeConverterTest { private static MonthDayAttributeConverter converter = MonthDayAttributeConverter.create(); @Test public void MonthDayAttributeConverterMinTest() { verifyTransform(MonthDay.of(1, 1), "--01-01"); } @Test public void MonthDayAttributeConverterNormalTest() { verifyTransform(MonthDay.of(5, 21), "--05-21"); } @Test public void MonthDayAttributeConverterMaxTest() { verifyTransform(MonthDay.of(12, 31), "--12-31"); } @Test public void MonthDayAttributeConverterInvalidFormatTest() { assertFails(() -> transformTo(converter, EnhancedAttributeValue.fromString("X") .toAttributeValue())); } @Test public void MonthDayAttributeConverterInvalidDateTest() { assertFails(() -> transformTo(converter, EnhancedAttributeValue.fromString("--02-30") .toAttributeValue())); } @Test public void MonthDayAttributeConverterNotAcceptLocalDateTimeTest() { assertFails(() -> transformTo(converter, EnhancedAttributeValue.fromString("1988-05-21T00:12:00.000000001") .toAttributeValue())); } @Test public void MonthDayAttributeConverterNotAcceptInstantTest() { assertFails(() -> transformTo(converter, EnhancedAttributeValue.fromString("1988-05-21T00:12:00.000000001Z") .toAttributeValue())); } @Test public void MonthDayAttributeConverterNotAcceptOffsetTimeTest() { assertFails(() -> transformTo(converter, EnhancedAttributeValue.fromString("1988-05-21T00:12:00+01:00") .toAttributeValue())); } @Test public void MonthDayAttributeConverterNotAcceptZonedTimeTest() { assertFails(() -> transformTo(converter, EnhancedAttributeValue.fromString("1988-05-21T00:12:00+01:00[Europe/Paris]") .toAttributeValue())); } @Test public void MonthDayAttributeConverterNotAcceptLocalDateTest() { assertFails(() -> transformTo(converter, EnhancedAttributeValue.fromString("1988-05-21") .toAttributeValue())); } @Test public void MonthDayAttributeConverterNotAcceptLocalTimeTest() { assertFails(() -> transformTo(converter, EnhancedAttributeValue.fromString("00:12:00.000000001") .toAttributeValue())); } private void verifyTransform(MonthDay objectToTransform, String attributeValueString) { assertThat(transformFrom(converter, objectToTransform)) .isEqualTo(EnhancedAttributeValue.fromString(attributeValueString).toAttributeValue()); assertThat(transformTo(converter, EnhancedAttributeValue.fromString(attributeValueString).toAttributeValue())) .isEqualTo(objectToTransform); } }
4,306
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/converters
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/converters/attribute/LocalTimeAttributeConverterTest.java
package software.amazon.awssdk.enhanced.dynamodb.converters.attribute; import static org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.enhanced.dynamodb.converters.attribute.ConverterTestUtils.assertFails; import static software.amazon.awssdk.enhanced.dynamodb.converters.attribute.ConverterTestUtils.transformFrom; import static software.amazon.awssdk.enhanced.dynamodb.converters.attribute.ConverterTestUtils.transformTo; import java.time.LocalTime; import org.junit.jupiter.api.Test; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.EnhancedAttributeValue; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.LocalTimeAttributeConverter; public class LocalTimeAttributeConverterTest { private static LocalTimeAttributeConverter converter = LocalTimeAttributeConverter.create(); @Test public void LocalTimeAttributeConverterMinTest() { verifyTransform(LocalTime.MIN, "00:00"); } @Test public void LocalTimeAttributeConverterNormalTest() { verifyTransform(LocalTime.of(1, 2, 3, 4), "01:02:03.000000004"); } @Test public void LocalTimeAttributeConverterMaxTest() { verifyTransform(LocalTime.MAX, "23:59:59.999999999"); } @Test public void LocalTimeAttributeConverterInvalidFormatTest() { assertFails(() -> transformTo(converter, EnhancedAttributeValue.fromString("-1") .toAttributeValue())); } @Test public void LocalTimeAttributeConverterExceedHigherBoundTest() { assertFails(() -> transformTo(converter, EnhancedAttributeValue.fromString("24:00:00") .toAttributeValue())); } @Test public void LocalTimeAttributeConverterInvalidNanoSecondsTest() { assertFails(() -> transformTo(converter, EnhancedAttributeValue.fromString("00:00:00.9999999999") .toAttributeValue())); } @Test public void LocalTimeAttributeConverterNotAcceptLocalDateTimeTest() { assertFails(() -> transformTo(converter, EnhancedAttributeValue.fromString("1988-05-21T00:12:00.000000001") .toAttributeValue())); } @Test public void LocalTimeAttributeConverterNotAcceptInstantTest() { assertFails(() -> transformTo(converter, EnhancedAttributeValue.fromString("1988-05-21T00:12:00.000000001Z") .toAttributeValue())); } @Test public void LocalTimeAttributeConverterNotAcceptOffsetTimeTest() { assertFails(() -> transformTo(converter, EnhancedAttributeValue.fromString("1988-05-21T00:12:00+01:00") .toAttributeValue())); } @Test public void LocalTimeAttributeConverterNotAcceptZonedTimeTest() { assertFails(() -> transformTo(converter, EnhancedAttributeValue.fromString("1988-05-21T00:12:00+01:00[Europe/Paris]") .toAttributeValue())); } @Test public void LocalTimeAttributeConverterNotAcceptLocalDateTest() { assertFails(() -> transformTo(converter, EnhancedAttributeValue.fromString("1988-05-21") .toAttributeValue())); } @Test public void LocalTimeAttributeConverterNotAcceptMonthDayTest() { assertFails(() -> transformTo(converter, EnhancedAttributeValue.fromString("05-21") .toAttributeValue())); } private void verifyTransform(LocalTime objectToTransform, String attributeValueString) { assertThat(transformFrom(converter, objectToTransform)) .isEqualTo(EnhancedAttributeValue.fromString(attributeValueString).toAttributeValue()); assertThat(transformTo(converter, EnhancedAttributeValue.fromString(attributeValueString).toAttributeValue())) .isEqualTo(objectToTransform); } }
4,307
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/converters
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/converters/document/CustomIntegerAttributeConverter.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.converters.document; 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.services.dynamodb.model.AttributeValue; public 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; } }
4,308
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/converters
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/converters/document/CustomClassForDocumentAttributeConverter.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.converters.document; import java.time.Instant; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; 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.AttributeValueType; import software.amazon.awssdk.enhanced.dynamodb.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.BigDecimalAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.BooleanAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.ByteArrayAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.EnhancedAttributeValue; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.InstantAsStringAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.ListAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.LongAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.SetAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.StringAttributeConverter; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; public class CustomClassForDocumentAttributeConverter implements AttributeConverter<CustomClassForDocumentAPI> { final static Integer DEFAULT_INCREMENT = 10; @Override public AttributeValue transformFrom(CustomClassForDocumentAPI input) { if(input == null){ return null; } Map<String, AttributeValue> attributeValueMap = new LinkedHashMap<>(); // Maintain the Alphabetical Order ,so that expected json matches if(input.booleanSet() != null){ attributeValueMap.put("booleanSet", AttributeValue.fromL(input.booleanSet().stream().map(b -> AttributeValue.fromBool(b)).collect(Collectors.toList()))); } if(input.customClassList() != null){ attributeValueMap.put("customClassList", convertCustomList(input.customClassList())); } if (input.innerCustomClass() != null){ attributeValueMap.put("innerCustomClass", transformFrom(input.innerCustomClass())); } if(input.instantList() != null){ attributeValueMap.put("instantList", convertInstantList(input.instantList())); } if(input.longNumber() != null){ attributeValueMap.put("longNumber", AttributeValue.fromN(input.longNumber().toString())); } if(input.string() != null){ attributeValueMap.put("string", AttributeValue.fromS(input.string())); } if(input.stringSet() != null){ attributeValueMap.put("stringSet", AttributeValue.fromSs(input.stringSet().stream().collect(Collectors.toList()))); } if(input.bigDecimalSet() != null){ attributeValueMap.put("stringSet", AttributeValue.fromNs(input.bigDecimalSet().stream().map(b -> b.toString()).collect(Collectors.toList()))); } return EnhancedAttributeValue.fromMap(attributeValueMap).toAttributeValue(); } private static AttributeValue convertCustomList(List<CustomClassForDocumentAPI> customClassForDocumentAPIList){ List<AttributeValue> convertCustomList = customClassForDocumentAPIList.stream().map(customClassForDocumentAPI -> create().transformFrom(customClassForDocumentAPI)).collect(Collectors.toList()); return AttributeValue.fromL(convertCustomList); } private static AttributeValue convertInstantList(List<Instant> customClassForDocumentAPIList){ return ListAttributeConverter.create(InstantAsStringAttributeConverter.create()).transformFrom(customClassForDocumentAPIList); } @Override public CustomClassForDocumentAPI transformTo(AttributeValue input) { Map<String, AttributeValue> customAttr = input.m(); CustomClassForDocumentAPI.Builder builder = CustomClassForDocumentAPI.builder(); if (customAttr.get("aBoolean") != null) { builder.aBoolean(BooleanAttributeConverter.create().transformTo(customAttr.get("aBoolean"))); } if (customAttr.get("bigDecimal") != null) { builder.bigDecimal(BigDecimalAttributeConverter.create().transformTo(customAttr.get("bigDecimal"))); } if (customAttr.get("bigDecimalSet") != null) { builder.bigDecimalSet(SetAttributeConverter.setConverter(BigDecimalAttributeConverter.create()).transformTo(customAttr.get("bigDecimalSet"))); } if (customAttr.get("binarySet") != null) { builder.binarySet(SetAttributeConverter.setConverter(ByteArrayAttributeConverter.create()).transformTo(customAttr.get("binarySet"))); } if (customAttr.get("binary") != null) { builder.binary(SdkBytes.fromByteArray(ByteArrayAttributeConverter.create().transformTo(customAttr.get("binary")))); } if (customAttr.get("booleanSet") != null) { builder.booleanSet(SetAttributeConverter.setConverter(BooleanAttributeConverter.create()).transformTo(customAttr.get( "booleanSet"))); } if (customAttr.get("customClassList") != null) { builder.customClassList(ListAttributeConverter.create(create()).transformTo(customAttr.get("customClassList"))); } if (customAttr.get("instantList") != null) { builder.instantList(ListAttributeConverter.create(AttributeConverterProvider.defaultProvider().converterFor(EnhancedType.of(Instant.class))).transformTo(customAttr.get( "instantList"))); } if (customAttr.get("innerCustomClass") != null) { builder.innerCustomClass(create().transformTo(customAttr.get("innerCustomClass"))); } if (customAttr.get("longNumber") != null) { builder.longNumber(LongAttributeConverter.create().transformTo(customAttr.get("longNumber"))); } if (customAttr.get("longSet") != null) { builder.longSet(SetAttributeConverter.setConverter(LongAttributeConverter.create()).transformTo(customAttr.get( "longSet"))); } if (customAttr.get("string") != null) { builder.string(StringAttributeConverter.create().transformTo(customAttr.get("string"))); } if (customAttr.get("stringSet") != null) { builder.stringSet(SetAttributeConverter.setConverter(StringAttributeConverter.create()).transformTo(customAttr.get( "stringSet"))); } return builder.build(); } public static CustomClassForDocumentAttributeConverter create() { return new CustomClassForDocumentAttributeConverter(); } @Override public EnhancedType<CustomClassForDocumentAPI> type() { return EnhancedType.of(CustomClassForDocumentAPI.class); } @Override public AttributeValueType attributeValueType() { return AttributeValueType.M; } }
4,309
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/converters
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/converters/document/CustomClassForDocumentAPI.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.converters.document; import java.math.BigDecimal; import java.time.Instant; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import software.amazon.awssdk.core.SdkBytes; public class CustomClassForDocumentAPI { public boolean aBoolean() { return aBoolean; } public BigDecimal bigDecimal() { return bigDecimal; } public Set<BigDecimal> bigDecimalSet() { return bigDecimalSet; } public SdkBytes binary() { return binary; } public Set<byte[]> binarySet() { return binarySet; } public Set<Boolean> booleanSet() { return booleanSet; } public List<CustomClassForDocumentAPI> customClassList() { return customClassForDocumentAPIList; } public Long longNumber() { return longNumber; } public Set<Long> longSet() { return longSet; } public String string() { return string; } public Set<String> stringSet() { return stringSet; } public List<Instant> instantList() { return instantList; } public Map<String, CustomClassForDocumentAPI> customClassMap() { return customClassMap; } public CustomClassForDocumentAPI innerCustomClass() { return innerCustomClassForDocumentAPI; } private final Set<String> stringSet; private final SdkBytes binary; private final Set<byte[]> binarySet; private final boolean aBoolean; private final Set<Boolean> booleanSet; private final Long longNumber; private final Set<Long> longSet; private final BigDecimal bigDecimal; private final Set<BigDecimal> bigDecimalSet; private final List<CustomClassForDocumentAPI> customClassForDocumentAPIList; private final List<Instant> instantList; private final Map<String, CustomClassForDocumentAPI> customClassMap; private final CustomClassForDocumentAPI innerCustomClassForDocumentAPI; private final String string; public static Builder builder(){ return new Builder(); } public CustomClassForDocumentAPI(Builder builder) { this.string = builder.string; this.stringSet = builder.stringSet; this.binary = builder.binary; this.binarySet = builder.binarySet; this.aBoolean = builder.aBoolean; this.booleanSet = builder.booleanSet; this.longNumber = builder.longNumber; this.longSet = builder.longSet; this.bigDecimal = builder.bigDecimal; this.bigDecimalSet = builder.bigDecimalSet; this.customClassForDocumentAPIList = builder.customClassForDocumentAPIList; this.instantList = builder.instantList; this.customClassMap = builder.customClassMap; this.innerCustomClassForDocumentAPI = builder.innerCustomClassForDocumentAPI; } public static final class Builder { private String string; private Set<String> stringSet; private SdkBytes binary; private Set<byte []> binarySet; private boolean aBoolean; private Set<Boolean> booleanSet; private Long longNumber; private Set<Long> longSet; private BigDecimal bigDecimal; private Set<BigDecimal> bigDecimalSet; private List<CustomClassForDocumentAPI> customClassForDocumentAPIList; private List<Instant> instantList; private Map<String, CustomClassForDocumentAPI> customClassMap; private CustomClassForDocumentAPI innerCustomClassForDocumentAPI; private Builder() { } public Builder string(String string) { this.string = string; return this; } public Builder stringSet(Set<String> stringSet) { this.stringSet = stringSet; return this; } public Builder binary(SdkBytes binary) { this.binary = binary; return this; } public Builder binarySet(Set<byte[]> binarySet) { this.binarySet = binarySet; return this; } public Builder aBoolean(boolean aBoolean) { this.aBoolean = aBoolean; return this; } public Builder booleanSet(Set<Boolean> booleanSet) { this.booleanSet = booleanSet; return this; } public Builder longNumber(Long longNumber) { this.longNumber = longNumber; return this; } public Builder longSet(Set<Long> longSet) { this.longSet = longSet; return this; } public Builder bigDecimal(BigDecimal bigDecimal) { this.bigDecimal = bigDecimal; return this; } public Builder bigDecimalSet(Set<BigDecimal> bigDecimalSet) { this.bigDecimalSet = bigDecimalSet; return this; } public Builder customClassList(List<CustomClassForDocumentAPI> customClassForDocumentAPIList) { this.customClassForDocumentAPIList = customClassForDocumentAPIList; return this; } public Builder instantList(List<Instant> instantList) { this.instantList = instantList; return this; } public Builder customClassMap(Map<String, CustomClassForDocumentAPI> customClassMap) { this.customClassMap = customClassMap; return this; } public Builder innerCustomClass(CustomClassForDocumentAPI innerCustomClassForDocumentAPI) { this.innerCustomClassForDocumentAPI = innerCustomClassForDocumentAPI; return this; } public CustomClassForDocumentAPI build() { return new CustomClassForDocumentAPI(this); } } @Override public String toString() { return "CustomClassForDocumentAPI{" + "aBoolean=" + aBoolean + ", bigDecimal=" + bigDecimal + ", bigDecimalSet=" + bigDecimalSet + ", binary=" + binary + ", binarySet=" + binarySet + ", booleanSet=" + booleanSet + ", customClassForDocumentAPIList=" + customClassForDocumentAPIList + ", customClassMap=" + customClassMap + ", innerCustomClassForDocumentAPI=" + innerCustomClassForDocumentAPI + ", instantList=" + instantList + ", longNumber=" + longNumber + ", longSet=" + longSet + ", string='" + string + '\'' + ", stringSet=" + stringSet + '}'; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CustomClassForDocumentAPI that = (CustomClassForDocumentAPI) o; return aBoolean == that.aBoolean && Objects.equals(string, that.string) && Objects.equals(stringSet, that.stringSet) && Objects.equals(binary, that.binary) && Objects.equals(binarySet, that.binarySet) && Objects.equals(booleanSet, that.booleanSet) && Objects.equals(longNumber, that.longNumber) && Objects.equals(longSet, that.longSet) && (bigDecimal == null ? that.bigDecimal == null : bigDecimal.compareTo(that.bigDecimal) == 0) && Objects.equals(bigDecimalSet, that.bigDecimalSet) && Objects.equals(customClassForDocumentAPIList, that.customClassForDocumentAPIList) && Objects.equals(instantList, that.instantList) && Objects.equals(customClassMap, that.customClassMap) && Objects.equals(innerCustomClassForDocumentAPI, that.innerCustomClassForDocumentAPI); } @Override public int hashCode() { return Objects.hash(string, stringSet, binary, binarySet, aBoolean, booleanSet, longNumber, longSet, bigDecimal, bigDecimalSet, customClassForDocumentAPIList, instantList, customClassMap, innerCustomClassForDocumentAPI); } }
4,310
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/converters
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/converters/document/CustomAttributeForDocumentConverterProvider.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.converters.document; import java.util.Map; 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.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.utils.ImmutableMap; public class CustomAttributeForDocumentConverterProvider implements AttributeConverterProvider { private final Map<EnhancedType<?>, AttributeConverter<?>> converterCache = ImmutableMap.of( EnhancedType.of(CustomClassForDocumentAPI.class), new CustomClassForDocumentAttributeConverter(), EnhancedType.of(Integer.class), new CustomIntegerAttributeConverter() ); @SuppressWarnings("unchecked") @Override public <T> AttributeConverter<T> converterFor(EnhancedType<T> enhancedType) { return (AttributeConverter<T>) converterCache.get(enhancedType); } public static CustomAttributeForDocumentConverterProvider create(){ return new CustomAttributeForDocumentConverterProvider(); } }
4,311
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/document/DefaultEnhancedDocumentTest.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.document; import static org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.enhanced.dynamodb.AttributeConverterProvider.defaultProvider; import static software.amazon.awssdk.enhanced.dynamodb.document.EnhancedDocumentTestData.defaultDocBuilder; import org.junit.jupiter.api.Test; import software.amazon.awssdk.enhanced.dynamodb.internal.document.DefaultEnhancedDocument; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; class DefaultEnhancedDocumentTest { @Test void copyCreatedFromToBuilder() { DefaultEnhancedDocument originalDoc = (DefaultEnhancedDocument) defaultDocBuilder() .putString("stringKey", "stringValue") .build(); DefaultEnhancedDocument copiedDoc = (DefaultEnhancedDocument) originalDoc.toBuilder().build(); DefaultEnhancedDocument copyAndAlter = (DefaultEnhancedDocument) originalDoc.toBuilder().putString("keyOne", "valueOne").build(); assertThat(originalDoc.toMap()).isEqualTo(copiedDoc.toMap()); assertThat(originalDoc.toMap().keySet()).hasSize(1); assertThat(copyAndAlter.toMap().keySet()).hasSize(2); assertThat(copyAndAlter.getString("stringKey")).isEqualTo("stringValue"); assertThat(copyAndAlter.getString("keyOne")).isEqualTo("valueOne"); assertThat(originalDoc.toMap()).isEqualTo(copiedDoc.toMap()); } @Test void isNull_inDocumentGet() { DefaultEnhancedDocument nullDocument = (DefaultEnhancedDocument) DefaultEnhancedDocument.builder() .attributeConverterProviders(defaultProvider()) .putNull("nullDocument") .putString("nonNull", "stringValue") .build(); assertThat(nullDocument.isNull("nullDocument")).isTrue(); assertThat(nullDocument.isNull("nonNull")).isFalse(); assertThat(nullDocument.toMap()).containsEntry("nullDocument", AttributeValue.fromNul(true)); } @Test void isNull_when_putObjectWithNullAttribute() { DefaultEnhancedDocument.DefaultBuilder builder = (DefaultEnhancedDocument.DefaultBuilder) DefaultEnhancedDocument.builder().attributeConverterProviders(defaultProvider()); builder.putObject("nullAttribute", AttributeValue.fromNul(true)); DefaultEnhancedDocument document = (DefaultEnhancedDocument) builder.build(); assertThat(document.isNull("nullAttribute")).isTrue(); } }
4,312
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/document/EnhancedDocumentTestData.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.document; import static java.time.Instant.ofEpochMilli; import static software.amazon.awssdk.enhanced.dynamodb.AttributeConverterProvider.defaultProvider; import static software.amazon.awssdk.enhanced.dynamodb.document.TestData.TypeMap.typeMap; import static software.amazon.awssdk.enhanced.dynamodb.document.TestData.dataBuilder; import java.math.BigDecimal; import java.time.Instant; import java.time.LocalDate; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.ArgumentsProvider; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.SdkNumber; import software.amazon.awssdk.enhanced.dynamodb.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.converters.document.CustomAttributeForDocumentConverterProvider; import software.amazon.awssdk.enhanced.dynamodb.converters.document.CustomClassForDocumentAPI; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.ChainConverterProvider; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.StringConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.string.CharSequenceStringConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.document.DefaultEnhancedDocument; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.utils.Pair; public final class EnhancedDocumentTestData implements ArgumentsProvider { private static long FIXED_INSTANT_TIME = 1677690845038L; public static final AttributeValue NUMBER_STRING_ARRAY_ATTRIBUTES_LISTS = AttributeValue.fromL(Arrays.asList(AttributeValue.fromN("1"), AttributeValue.fromN("2"), AttributeValue.fromN("3"))); private static final EnhancedDocumentTestData INSTANCE = new EnhancedDocumentTestData(); private Map<String, TestData> testScenarioMap; private List<TestData> testDataList; public EnhancedDocumentTestData() { initializeTestData(); } public static EnhancedDocumentTestData testDataInstance() { return new EnhancedDocumentTestData(); } public static EnhancedDocument.Builder defaultDocBuilder() { EnhancedDocument.Builder defaultBuilder = DefaultEnhancedDocument.builder(); return defaultBuilder.addAttributeConverterProvider(defaultProvider()); } public static AttributeStringValueMap map() { return new AttributeStringValueMap(); } private void initializeTestData() { testDataList = new ArrayList<>(); testDataList.add(dataBuilder().scenario("nullKey") .ddbItemMap(map().withKeyValue("nullKey", AttributeValue.fromNul(true)).get()) .enhancedDocument(defaultDocBuilder() .putNull("nullKey") .build()) .json("{\"nullKey\":null}") .attributeConverterProvider(defaultProvider()) .build()); testDataList.add(dataBuilder().scenario("simpleString") .ddbItemMap(map().withKeyValue("stringKey", AttributeValue.fromS("stringValue")).get()) .enhancedDocument( ((DefaultEnhancedDocument.DefaultBuilder) DefaultEnhancedDocument.builder()).putObject("stringKey", "stringValue") .addAttributeConverterProvider(defaultProvider()).build()) .attributeConverterProvider(defaultProvider()) .json("{\"stringKey\":\"stringValue\"}") .build()); testDataList.add(dataBuilder().scenario("record") .ddbItemMap(map().withKeyValue("uniqueId", AttributeValue.fromS("id-value")) .withKeyValue("sortKey",AttributeValue.fromS("sort-value")) .withKeyValue("attributeKey", AttributeValue.fromS("one")) .withKeyValue("attributeKey2", AttributeValue.fromS("two")) .withKeyValue("attributeKey3", AttributeValue.fromS("three")).get()) .enhancedDocument( defaultDocBuilder() .putString("uniqueId","id-value") .putString("sortKey","sort-value") .putString("attributeKey","one") .putString("attributeKey2","two") .putString("attributeKey3","three") .build() ) .attributeConverterProvider(defaultProvider()) .json("{\"uniqueId\":\"id-value\",\"sortKey\":\"sort-value\",\"attributeKey\":\"one\"," + "\"attributeKey2\":\"two\",\"attributeKey3\":\"three\"}") .build()); testDataList.add(dataBuilder().scenario("differentNumberTypes") .ddbItemMap(map() .withKeyValue("numberKey", AttributeValue.fromN("10")) .withKeyValue("bigDecimalNumberKey", AttributeValue.fromN(new BigDecimal(10).toString())).get()) .enhancedDocument( defaultDocBuilder() .putNumber("numberKey", Integer.valueOf(10)) .putNumber("bigDecimalNumberKey", new BigDecimal(10)) .build()) .attributeConverterProvider(defaultProvider()) .json("{" + "\"numberKey\":10," + "\"bigDecimalNumberKey\":10" + "}") .build()); testDataList.add(dataBuilder().scenario("allSimpleTypes") .ddbItemMap(map() .withKeyValue("stringKey", AttributeValue.fromS("stringValue")) .withKeyValue("numberKey", AttributeValue.fromN("10")) .withKeyValue("boolKey", AttributeValue.fromBool(true)) .withKeyValue("nullKey", AttributeValue.fromNul(true)) .withKeyValue("numberSet", AttributeValue.fromNs(Arrays.asList("1", "2", "3"))) .withKeyValue("sdkBytesSet", AttributeValue.fromBs(Arrays.asList(SdkBytes.fromUtf8String("a") ,SdkBytes.fromUtf8String("b") ,SdkBytes.fromUtf8String("c")))) .withKeyValue("stringSet", AttributeValue.fromSs(Arrays.asList("a", "b", "c"))).get()) .enhancedDocument(defaultDocBuilder() .putString("stringKey", "stringValue") .putNumber("numberKey", 10) .putBoolean("boolKey", true) .putNull("nullKey") .putNumberSet("numberSet", Stream.of(1, 2, 3).collect(Collectors.toSet())) .putBytesSet("sdkBytesSet", Stream.of(SdkBytes.fromUtf8String("a"), SdkBytes.fromUtf8String("b"), SdkBytes.fromUtf8String("c")) .collect(Collectors.toSet())) .putStringSet("stringSet", Stream.of("a", "b", "c").collect(Collectors.toSet())) .build()) .json("{\"stringKey\":\"stringValue\",\"numberKey\":10,\"boolKey\":true,\"nullKey\":null," + "\"numberSet\":[1,2,3],\"sdkBytesSet\":[\"YQ==\",\"Yg==\",\"Yw==\"],\"stringSet\":[\"a\"," + "\"b\",\"c\"]}") .attributeConverterProvider(defaultProvider()) .build()); testDataList.add(dataBuilder().scenario("differentNumberSets") .isGeneric(false) .ddbItemMap(map() .withKeyValue("floatSet", AttributeValue.fromNs(Arrays.asList("2.0", "3.0"))) .withKeyValue("integerSet", AttributeValue.fromNs(Arrays.asList("-1", "0", "1"))) .withKeyValue("bigDecimal", AttributeValue.fromNs(Arrays.asList("1000.002", "2000.003"))) .withKeyValue("sdkNumberSet", AttributeValue.fromNs(Arrays.asList("1", "2", "3"))).get()) .enhancedDocument(defaultDocBuilder() .putNumberSet("floatSet", Stream.of( Float.parseFloat("2.0"), Float.parseFloat("3.0") ).collect(Collectors.toCollection(LinkedHashSet::new))) .putNumberSet("integerSet",Arrays.asList(-1,0, 1).stream().collect(Collectors.toCollection(LinkedHashSet::new))) .putNumberSet("bigDecimal", Stream.of(BigDecimal.valueOf(1000.002), BigDecimal.valueOf(2000.003) ).collect(Collectors.toCollection(LinkedHashSet::new))) .putNumberSet("sdkNumberSet", Stream.of(SdkNumber.fromInteger(1), SdkNumber.fromInteger(2), SdkNumber.fromInteger(3) ).collect(Collectors.toSet())) .build()) .json("{\"floatSet\": [2.0, 3.0],\"integerSet\": [-1, 0, 1],\"bigDecimal\": [1000.002, 2000.003],\"sdkNumberSet\": [1,2, 3]}") .attributeConverterProvider(defaultProvider()) .build()); testDataList.add(dataBuilder().scenario("simpleListExcludingBytes") .ddbItemMap(map() .withKeyValue("numberList", AttributeValue.fromL( Arrays.asList(AttributeValue.fromN("1"), AttributeValue.fromN("2")))) .withKeyValue("stringList", AttributeValue.fromL( Arrays.asList( AttributeValue.fromS("one"), AttributeValue.fromS("two")))).get()) .enhancedDocument( defaultDocBuilder() .putList("numberList", Arrays.asList(1,2), EnhancedType.of(Integer.class)) .putList("stringList", Arrays.asList("one","two"), EnhancedType.of(String.class)) .build() ) .typeMap(typeMap() .addAttribute("numberList", EnhancedType.of(Integer.class)) .addAttribute("stringList", EnhancedType.of(String.class))) .attributeConverterProvider(defaultProvider()) .json("{\"numberList\":[1,2],\"stringList\":[\"one\",\"two\"]}") .build()); testDataList.add(dataBuilder().scenario("customList") .ddbItemMap( map().withKeyValue("customClassForDocumentAPI", AttributeValue.fromL( Arrays.asList( AttributeValue.fromM(getAttributeValueMapForCustomClassWithPrefix(1,10, false)) , AttributeValue.fromM(getAttributeValueMapForCustomClassWithPrefix(2,200, false))))).get()) .enhancedDocument( defaultDocBuilder() .attributeConverterProviders(CustomAttributeForDocumentConverterProvider.create() ,defaultProvider()) .putList("customClassForDocumentAPI" , Arrays.asList(getCustomClassForDocumentAPIWithBaseAndOffset(1,10) ,getCustomClassForDocumentAPIWithBaseAndOffset(2,200)), EnhancedType.of(CustomClassForDocumentAPI.class)) .build() ) .typeMap(typeMap() .addAttribute("instantList", EnhancedType.of(Instant.class)) .addAttribute("customClassForDocumentAPI", EnhancedType.of(CustomClassForDocumentAPI.class))) .attributeConverterProvider(ChainConverterProvider.create(CustomAttributeForDocumentConverterProvider.create(), defaultProvider())) .json("{\"customClassForDocumentAPI\":[{\"instantList\":[\"2023-03-01T17:14:05.049Z\"," + "\"2023-03-01T17:14:05.049Z\",\"2023-03-01T17:14:05.049Z\"],\"longNumber\":11," + "\"string\":\"11\",\"stringSet\":[\"12\",\"13\",\"14\"]}," + "{\"instantList\":[\"2023-03-01T17:14:05.240Z\",\"2023-03-01T17:14:05.240Z\"," + "\"2023-03-01T17:14:05.240Z\"],\"longNumber\":202,\"string\":\"202\"," + "\"stringSet\":[\"203\",\"204\",\"205\"]}]}") .build()); testDataList.add(dataBuilder().scenario("ThreeLevelNestedList") .ddbItemMap( map().withKeyValue("threeLevelList", AttributeValue.fromL(Arrays.asList( AttributeValue.fromL(Arrays.asList( AttributeValue.fromL(Arrays.asList(AttributeValue.fromS("l1_0"), AttributeValue.fromS("l1_1"))), AttributeValue.fromL(Arrays.asList(AttributeValue.fromS("l2_0"), AttributeValue.fromS("l2_1"))) )) , AttributeValue.fromL(Arrays.asList( AttributeValue.fromL(Arrays.asList(AttributeValue.fromS("l3_0"), AttributeValue.fromS("l3_1"))), AttributeValue.fromL(Arrays.asList(AttributeValue.fromS("l4_0"), AttributeValue.fromS("l4_1"))) ))))).get() ) .enhancedDocument( defaultDocBuilder() .putList("threeLevelList" , Arrays.asList( Arrays.asList( Arrays.asList("l1_0", "l1_1"), Arrays.asList("l2_0", "l2_1") ), Arrays.asList( Arrays.asList("l3_0", "l3_1"), Arrays.asList("l4_0", "l4_1") ) ) , new EnhancedType<List<List<String>>>() { } ) .build() ) .attributeConverterProvider(defaultProvider()) .json("{\"threeLevelList\":[[[\"l1_0\",\"l1_1\"],[\"l2_0\",\"l2_1\"]],[[\"l3_0\"," + "\"l3_1\"],[\"l4_0\",\"l4_1\"]]]}") .typeMap(typeMap() .addAttribute("threeLevelList", new EnhancedType<List<List<String>>>() { })) .build()); // Test case for Nested List with Maps List<Map<String, List<String>> testDataList.add(dataBuilder().scenario("listOfMapOfListValues") .ddbItemMap( map() .withKeyValue("listOfListOfMaps", AttributeValue.fromL( Arrays.asList( AttributeValue.fromM(getStringListAttributeValueMap("a", 2, 2)), AttributeValue.fromM(getStringListAttributeValueMap("b", 1, 1)) ) ) ).get()) .enhancedDocument( defaultDocBuilder() .putList("listOfListOfMaps" , Arrays.asList( getStringListObjectMap("a", 2, 2), getStringListObjectMap("b", 1, 1) ) , new EnhancedType<Map<String, List<Integer>>>() { } ) .build() ) .json("{\"listOfListOfMaps\":[{\"key_a_1\":[1,2],\"key_a_2\":[1,2]},{\"key_b_1\":[1]}]}") .attributeConverterProvider(defaultProvider()) .typeMap(typeMap() .addAttribute("listOfListOfMaps", new EnhancedType<Map<String, List<Integer>>>() { })) .build()); testDataList.add(dataBuilder().scenario("simpleMap") .ddbItemMap( map() .withKeyValue("simpleMap", AttributeValue.fromM(getStringSimpleAttributeValueMap( "suffix", 7))) .get()) .enhancedDocument( defaultDocBuilder() .putMap("simpleMap", getStringSimpleMap("suffix", 7, CharSequenceStringConverter.create()), EnhancedType.of(CharSequence.class), EnhancedType.of(String.class)) .build() ) .attributeConverterProvider(defaultProvider()) .typeMap(typeMap() .addAttribute("simpleMap", EnhancedType.of(CharSequence.class), EnhancedType.of(String.class))) .json("{\"simpleMap\":{\"key_suffix_1\":\"1\",\"key_suffix_2\":\"2\"," + "\"key_suffix_3\":\"3\",\"key_suffix_4\":\"4\",\"key_suffix_5\":\"5\"," + "\"key_suffix_6\":\"6\",\"key_suffix_7\":\"7\"}}") .build()); testDataList.add(dataBuilder().scenario("ElementsOfCustomType") .ddbItemMap( map().withKeyValue("customMapValue", AttributeValue.fromM( map().withKeyValue("entryOne", AttributeValue.fromM(getAttributeValueMapForCustomClassWithPrefix(2, 10, false))) .get())) .get() ) .enhancedDocument( defaultDocBuilder() .attributeConverterProviders(CustomAttributeForDocumentConverterProvider.create() , defaultProvider()) .putMap("customMapValue", Stream.of(Pair.of("entryOne", customValueWithBaseAndOffset(2, 10))) .collect(Collectors.toMap(p -> CharSequenceStringConverter.create().fromString(p.left()), p -> p.right(), (oldValue, newValue) -> oldValue, LinkedHashMap::new)) , EnhancedType.of(CharSequence.class), EnhancedType.of(CustomClassForDocumentAPI.class)) .build() ) .json("{\"customMapValue\":{\"entryOne\":{\"instantList\":[\"2023-03-01T17:14:05.050Z\"," + "\"2023-03-01T17:14:05.050Z\",\"2023-03-01T17:14:05.050Z\"],\"longNumber\":12," + "\"string\":\"12\",\"stringSet\":[\"13\",\"14\",\"15\"]}}}") .typeMap(typeMap() .addAttribute("customMapValue", EnhancedType.of(CharSequence.class), EnhancedType.of(CustomClassForDocumentAPI.class))) .attributeConverterProvider(ChainConverterProvider.create(CustomAttributeForDocumentConverterProvider.create(), defaultProvider())) .build()); testDataList.add(dataBuilder().scenario("complexDocWithSdkBytesAndMapArrays_And_PutOverWritten") .ddbItemMap(map().withKeyValue("nullKey",AttributeValue.fromNul(true)).get()) .enhancedDocument( defaultDocBuilder() .putNull("nullKey") .putNumber("numberKey", 1) .putString("stringKey", "stringValue") .putList("numberList", Arrays.asList(1, 2, 3), EnhancedType.of(Integer.class)) .put("simpleDate", LocalDate.MIN, EnhancedType.of(LocalDate.class)) .putStringSet("stringSet", Stream.of("one", "two").collect(Collectors.toSet())) .putBytes("sdkByteKey", SdkBytes.fromUtf8String("a")) .putBytesSet("sdkByteSet", Stream.of(SdkBytes.fromUtf8String("a"), SdkBytes.fromUtf8String("b")).collect(Collectors.toSet())) .putNumberSet("numberSetSet", Stream.of(1, 2).collect(Collectors.toSet())) .putList("numberList", Arrays.asList(4, 5, 6), EnhancedType.of(Integer.class)) .putMap("simpleMap", mapFromSimpleKeyValue(Pair.of("78b3522c-2ab3-4162-8c5d" + "-f093fa76e68c", 3), Pair.of("4ae1f694-52ce-4cf6-8211" + "-232ccf780da8", 9)), EnhancedType.of(String.class), EnhancedType.of(Integer.class)) .putMap("mapKey", mapFromSimpleKeyValue(Pair.of("1", Arrays.asList("a", "b" , "c")), Pair.of("2", Collections.singletonList("1"))), EnhancedType.of(String.class), EnhancedType.listOf(String.class)) .build() ) .json("{\"nullKey\": null, \"numberKey\": 1, \"stringKey\":\"stringValue\", " + "\"simpleDate\":\"-999999999-01-01\",\"stringSet\": " + "[\"one\",\"two\"],\"sdkByteKey\":\"a\",\"sdkByteSet\":[\"a\",\"b\"], " + "\"numberSetSet\": [1,2], " + "\"numberList\": [4, 5, 6], " + "\"simpleMap\": {\"78b3522c-2ab3-4162-8c5d-f093fa76e68c\": 3," + "\"4ae1f694-52ce-4cf6-8211-232ccf780da8\": 9}, \"mapKey\": {\"1\":[\"a\",\"b\"," + " \"c\"],\"2\":[\"1\"]}}") .attributeConverterProvider(defaultProvider()) .isGeneric(false) .build()); testDataList.add(dataBuilder().scenario("insertUsingPutJson") .ddbItemMap( map().withKeyValue("customMapValue", AttributeValue.fromM( map().withKeyValue("entryOne", AttributeValue.fromM(getAttributeValueMapForCustomClassWithPrefix(2, 10, true))) .get())) .get() ) .enhancedDocument( defaultDocBuilder() .attributeConverterProviders(CustomAttributeForDocumentConverterProvider.create() ,defaultProvider()) .putJson("customMapValue", "{\"entryOne\": " + "{" + "\"instantList\": [\"2023-03-01T17:14:05.050Z\", \"2023-03-01T17:14:05.050Z\", \"2023-03-01T17:14:05.050Z\"], " + "\"longNumber\": 12, " + "\"string\": \"12\"" + "}" + "}") .build() ) .json("{\"customMapValue\":{\"entryOne\":{\"instantList\":[\"2023-03-01T17:14:05.050Z\"," + "\"2023-03-01T17:14:05.050Z\",\"2023-03-01T17:14:05.050Z\"],\"longNumber\":12," + "\"string\":\"12\"}}}") .typeMap(typeMap() .addAttribute("customMapValue", EnhancedType.of(CharSequence.class), EnhancedType.of(CustomClassForDocumentAPI.class))) .attributeConverterProvider(ChainConverterProvider.create(CustomAttributeForDocumentConverterProvider.create(), defaultProvider())) .build()); testDataList.add(dataBuilder().scenario("putJsonWithSimpleMapOfStrings") .ddbItemMap( map() .withKeyValue("simpleMap", AttributeValue.fromM(getStringSimpleAttributeValueMap( "suffix", 7))) .get()) .enhancedDocument( defaultDocBuilder() .putJson("simpleMap", "{\"key_suffix_1\":\"1\",\"key_suffix_2\":\"2\",\"key_suffix_3\":" + " \"3\",\"key_suffix_4\": " + "\"4\",\"key_suffix_5\":\"5\",\"key_suffix_6\":\"6\",\"key_suffix_7\":\"7\"}" ) .build() ) .attributeConverterProvider(defaultProvider()) .typeMap(typeMap() .addAttribute("simpleMap", EnhancedType.of(String.class), EnhancedType.of(String.class))) .json("{\"simpleMap\":{\"key_suffix_1\":\"1\",\"key_suffix_2\":\"2\"," + "\"key_suffix_3\":\"3\",\"key_suffix_4\":\"4\",\"key_suffix_5\":\"5\"," + "\"key_suffix_6\":\"6\",\"key_suffix_7\":\"7\"}}") .build()); // singleSdkByte SetOfSdkBytes ListOfSdkBytes and Map of SdkBytes testDataList.add(dataBuilder().scenario("bytesSet") .isGeneric(false) .ddbItemMap( map() .withKeyValue("bytes", AttributeValue.fromB(SdkBytes.fromUtf8String("HelloWorld"))) .withKeyValue("setOfBytes", AttributeValue.fromBs( Arrays.asList(SdkBytes.fromUtf8String("one"), SdkBytes.fromUtf8String("two"), SdkBytes.fromUtf8String("three")))) .withKeyValue("listOfBytes", AttributeValue.fromL( Arrays.asList(SdkBytes.fromUtf8String("i1"), SdkBytes.fromUtf8String("i2"), SdkBytes.fromUtf8String("i3")).stream().map( s -> AttributeValue.fromB(s)).collect(Collectors.toList()))) .withKeyValue("mapOfBytes", AttributeValue.fromM( Stream.of(Pair.of("k1", AttributeValue.fromB(SdkBytes.fromUtf8String("v1"))) ,Pair.of("k2", AttributeValue.fromB(SdkBytes.fromUtf8String("v2")))) .collect(Collectors.toMap(k->k.left(), r ->r.right(), (oldV, newV)-> oldV, LinkedHashMap::new) ))).get()) .enhancedDocument( defaultDocBuilder() .putBytes("bytes", SdkBytes.fromUtf8String("HelloWorld")) .putBytesSet("setOfBytes", Arrays.asList(SdkBytes.fromUtf8String("one"), SdkBytes.fromUtf8String("two"), SdkBytes.fromUtf8String("three")).stream() .collect(Collectors.toCollection(LinkedHashSet::new)) ) .putList("listOfBytes", Arrays.asList(SdkBytes.fromUtf8String("i1"), SdkBytes.fromUtf8String("i2"), SdkBytes.fromUtf8String("i3")) ,EnhancedType.of(SdkBytes.class) ) .putMap("mapOfBytes" , Stream.of(Pair.of("k1", SdkBytes.fromUtf8String("v1")) ,Pair.of("k2", SdkBytes.fromUtf8String("v2"))) .collect(Collectors.toMap(k->k.left(), r ->r.right(), (oldV, newV)-> oldV, LinkedHashMap::new) ), EnhancedType.of(String.class), EnhancedType.of(SdkBytes.class)) .build() ) .json("{\"bytes\":\"HelloWorld\",\"setOfBytes\":[\"one\",\"two\",\"three\"], " + "\"listOfBytes\":[\"i1\",\"i2\",\"i3\"],\"mapOfBytes\": {\"k1\":\"v1\"," + "\"k2\":\"v2\"}}") .attributeConverterProvider(defaultProvider()) .typeMap(typeMap() .addAttribute("listOfBytes", EnhancedType.of(SdkBytes.class)) .addAttribute("mapOfBytes", EnhancedType.of(String.class), EnhancedType.of(SdkBytes.class))) .build()); testScenarioMap = testDataList.stream().collect(Collectors.toMap(TestData::getScenario, Function.identity())); // testScenarioMap = testDataList.stream().collect(Collectors.toMap(k->k.getScenario(), Function.identity())); } public TestData dataForScenario(String scenario) { return testScenarioMap.get(scenario); } public List<TestData> getAllGenericScenarios() { return testScenarioMap.values().stream().filter(testData -> testData.isGeneric()).collect(Collectors.toList()); } public static class AttributeStringValueMap { private Map<String, AttributeValue> attributeValueMap = new LinkedHashMap<>(); public Map<String, AttributeValue> get() { return attributeValueMap; } public AttributeStringValueMap withKeyValue(String key, AttributeValue value) { attributeValueMap.put(key, value); return this; } } /** * * @param offset from base elements to differentiate the subsequent elements * @param base Start of the foest element * @param includeSets While testing FromJson, sets are excluded since Json treats sets as lists * @return Map with Key - value as String, AttributeValue> */ /** * Creates a map of attribute values for a custom class with a prefix added to each key. * * @param offset The offset from the base element to differentiate subsequent elements. * @param base The start index of the first element. * @param excludeSetsInMap Whether to exclude sets when creating the map. (Json treats sets as lists.) * @return A map with key-value pairs of String and AttributeValue. */ private static Map<String, AttributeValue> getAttributeValueMapForCustomClassWithPrefix(int offset, int base, boolean excludeSetsInMap) { Map<String, AttributeValue> map = new LinkedHashMap<>(); map.put("instantList", AttributeValue.fromL(Stream.of( ofEpochMilli(FIXED_INSTANT_TIME + base +offset) ,ofEpochMilli(FIXED_INSTANT_TIME + base + offset), ofEpochMilli(FIXED_INSTANT_TIME + base + offset)) .map(r -> AttributeValue.fromS(String.valueOf(r))).collect(Collectors.toList()))); map.put("longNumber", AttributeValue.fromN(String.valueOf(base + offset))); map.put("string", AttributeValue.fromS(String.valueOf(base + offset))); if(! excludeSetsInMap){ map.put("stringSet", AttributeValue.fromSs(Stream.of(1 + base + offset,2 + base +offset, 3 + base +offset).map(r -> String.valueOf(r)).collect(Collectors.toList()))); } return map; } private static CustomClassForDocumentAPI getCustomClassForDocumentAPIWithBaseAndOffset(int offset, int base) { return CustomClassForDocumentAPI.builder() .instantList(Stream.of( ofEpochMilli(FIXED_INSTANT_TIME + base + offset), ofEpochMilli(FIXED_INSTANT_TIME + base + offset), ofEpochMilli(FIXED_INSTANT_TIME + base + offset)) .collect(Collectors.toList())) .longNumber(Long.valueOf(base + offset)) .string(String.valueOf(base + offset)) .stringSet(Stream.of(1+ base + offset, 2 +base + offset, 3 + base + offset).map(String::valueOf).collect(Collectors.toCollection(LinkedHashSet::new))) .build(); } /** * getStringListAttributeValueMap("lvl_1", 3, 2) * { * key_lvl_1_1=AttributeValue(L=[AttributeValue(N=1), AttributeValue(N=2)]), * key_lvl_1_2=AttributeValue(L=[AttributeValue(N=1), AttributeValue(N=2)]), * key_lvl_1_3=AttributeValue(L=[AttributeValue(N=1), AttributeValue(N=2)]) * } */ private static Map<String, AttributeValue> getStringListAttributeValueMap(String suffixKey, int numberOfKeys , int nestedListLength ) { Map<String, AttributeValue> result = new LinkedHashMap<>(); IntStream.range(1, numberOfKeys + 1).forEach(n-> result.put(String.format("key_%s_%d",suffixKey,n), AttributeValue.fromL(IntStream.range(1, nestedListLength+1).mapToObj(numb -> AttributeValue.fromN(String.valueOf(numb))).collect(Collectors.toList()))) ); return result; } /** * getStringListObjectMap("lvl_1", 3, 2) * { * key_lvl_1_1=[1,2], * key_lvl_1_2=[1,2], * key_lvl_1_3=[1,2] * } */ private static Map<String, List<Integer>> getStringListObjectMap(String suffixKey, int numberOfKeys , int nestedListLength ) { Map<String, List<Integer>> result = new LinkedHashMap<>(); IntStream.range(1, numberOfKeys + 1).forEach( n-> result.put(String.format("key_%s_%d",suffixKey,n), IntStream.range(1, nestedListLength+1).mapToObj(numb -> Integer.valueOf(numb)).collect(Collectors.toList())) ); return result; } @Override public Stream<? extends Arguments> provideArguments(ExtensionContext context) throws Exception { return testDataInstance().getAllGenericScenarios().stream().map(Arguments::of); } /** * { * key_suffix_1=AttributeValue(S=1), * key_suffix_2=AttributeValue(S=2), * key_suffix_3=AttributeValue(S=3) * } */ private static Map<String, AttributeValue> getStringSimpleAttributeValueMap(String suffix, int numberOfElements) { return IntStream.range(1, numberOfElements + 1) .boxed() .collect(Collectors.toMap(n -> String.format("key_%s_%d", suffix, n), n -> AttributeValue.fromS(String.valueOf(n)) , (oldValue, newValue) -> oldValue, LinkedHashMap::new)); } private static CustomClassForDocumentAPI customValueWithBaseAndOffset(int offset, int base) { return CustomClassForDocumentAPI.builder() .instantList(Stream.of( ofEpochMilli(FIXED_INSTANT_TIME + base +offset) ,ofEpochMilli(FIXED_INSTANT_TIME + base + offset), ofEpochMilli(FIXED_INSTANT_TIME + base + offset)).collect(Collectors.toList())) .longNumber(Long.valueOf(base + offset)) .string(String.valueOf(base + offset)) .stringSet(Stream.of(1 + base + offset,2 + base +offset, 3 + base +offset).map(r -> String.valueOf(r)).collect(Collectors.toCollection(LinkedHashSet::new))) .build(); } /** * getStringSimpleMap("suffix", 2, CharSequenceStringConverter.create())) *{ * key_suffix_1=1, * key_suffix_2=2 *} */ private static <T>Map<T, String> getStringSimpleMap(String suffix, int numberOfElements, StringConverter<T> stringConverter) { return IntStream.range(1, numberOfElements + 1) .boxed() .collect(Collectors.toMap( n -> stringConverter.fromString(String.format("key_%s_%d", suffix, n)), n -> String.valueOf(n), (key, value) -> key, // merge function to handle collisions LinkedHashMap::new )); } private <T> Map<String, T> mapFromSimpleKeyValue(Pair<String, T>...keyValuePair) { return Stream.of(keyValuePair) .collect(Collectors.toMap(k ->k.left(), v ->v.right(), (oldValue, newValue) -> oldValue, LinkedHashMap::new)); } }
4,313
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/document/ParameterizedDocumentTest.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.document; import static org.assertj.core.api.Assertions.assertThat; import java.util.List; import java.util.Map; import java.util.Set; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ArgumentsSource; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.SdkNumber; import software.amazon.awssdk.enhanced.dynamodb.AttributeConverterProvider; 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.attribute.ListAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.MapAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.string.DefaultStringConverterProvider; class ParameterizedDocumentTest { @ParameterizedTest @ArgumentsSource(EnhancedDocumentTestData.class) void validate_BuilderMethodsOfDefaultDocument(TestData testData) { /** * The builder method internally creates a AttributeValueMap which is saved to the ddb, if this matches then * the document is as expected */ assertThat(testData.getEnhancedDocument().toMap()).isEqualTo(testData.getDdbItemMap()); } @ParameterizedTest @ArgumentsSource(EnhancedDocumentTestData.class) void validate_validateJsonStringAreEqual(TestData testData) { System.out.println(testData.getScenario()); /** * The builder method internally creates a AttributeValueMap which is saved to the ddb, if this matches then * the document is as expected */ assertThat(testData.getEnhancedDocument().toJson()).isEqualTo(testData.getJson()); } @ParameterizedTest @ArgumentsSource(EnhancedDocumentTestData.class) void validate_documentsCreated_fromJson(TestData testData) { /** * The builder method internally creates a AttributeValueMap which is saved to the ddb, if this matches then * the document is as expected */ assertThat(EnhancedDocument.fromJson(testData.getJson()).toJson()) .isEqualTo(testData.getEnhancedDocument().toJson()); } @ParameterizedTest @ArgumentsSource(EnhancedDocumentTestData.class) void validate_documentsCreated_fromAttributeValueMap(TestData testData) { /** * The builder method internally creates a AttributeValueMap which is saved to the ddb, if this matches then * the document is as expected */ assertThat(EnhancedDocument.fromAttributeValueMap(testData.getDdbItemMap()).toMap()) .isEqualTo(testData.getDdbItemMap()); } @ParameterizedTest @ArgumentsSource(EnhancedDocumentTestData.class) void validateGetterMethodsOfDefaultDocument(TestData testData) { EnhancedDocument enhancedDocument = testData.getEnhancedDocument(); Map<String, List<EnhancedType>> enhancedTypeMap = testData.getTypeMap().enhancedTypeMap; AttributeConverterProvider chainConverterProvider = testData.getAttributeConverterProvider(); assertThat(testData.getEnhancedDocument().toMap()).isEqualTo(testData.getDdbItemMap()); testData.getDdbItemMap().forEach((key, value) -> { EnhancedAttributeValue enhancedAttributeValue = EnhancedAttributeValue.fromAttributeValue(value); switch (enhancedAttributeValue.type()) { case NULL: assertThat(enhancedDocument.isNull(key)).isTrue(); break; case S: assertThat(enhancedAttributeValue.asString()).isEqualTo(enhancedDocument.getString(key)); assertThat(enhancedAttributeValue.asString()).isEqualTo(enhancedDocument.get(key, String.class)); assertThat(enhancedAttributeValue.asString()).isEqualTo(enhancedDocument.get(key, EnhancedType.of(String.class))); break; case N: assertThat(enhancedAttributeValue.asNumber()).isEqualTo(enhancedDocument.getNumber(key).stringValue()); assertThat(enhancedAttributeValue.asNumber()).isEqualTo(String.valueOf(enhancedDocument.get(key, SdkNumber.class))); assertThat(enhancedAttributeValue.asNumber()).isEqualTo(enhancedDocument.get(key, EnhancedType.of(SdkNumber.class)).toString()); break; case B: assertThat(enhancedAttributeValue.asBytes()).isEqualTo(enhancedDocument.getBytes(key)); assertThat(enhancedAttributeValue.asBytes()).isEqualTo(enhancedDocument.get(key, SdkBytes.class)); assertThat(enhancedAttributeValue.asBytes()).isEqualTo(enhancedDocument.get(key, EnhancedType.of(SdkBytes.class))); break; case BOOL: assertThat(enhancedAttributeValue.asBoolean()).isEqualTo(enhancedDocument.getBoolean(key)); assertThat(enhancedAttributeValue.asBoolean()).isEqualTo(enhancedDocument.get(key, Boolean.class)); assertThat(enhancedAttributeValue.asBoolean()).isEqualTo(enhancedDocument.get(key, EnhancedType.of(Boolean.class))); break; case NS: Set<SdkNumber> expectedNumber = chainConverterProvider.converterFor(EnhancedType.setOf(SdkNumber.class)).transformTo(value); assertThat(expectedNumber).isEqualTo(enhancedDocument.getNumberSet(key)); break; case SS: Set<String> stringSet = chainConverterProvider.converterFor(EnhancedType.setOf(String.class)).transformTo(value); assertThat(stringSet).isEqualTo(enhancedDocument.getStringSet(key)); break; case BS: Set<SdkBytes> sdkBytesSet = chainConverterProvider.converterFor(EnhancedType.setOf(SdkBytes.class)).transformTo(value); assertThat(sdkBytesSet).isEqualTo(enhancedDocument.getBytesSet(key)); break; case L: EnhancedType enhancedType = enhancedTypeMap.get(key).get(0); ListAttributeConverter converter = ListAttributeConverter .create(chainConverterProvider.converterFor(enhancedType)); if(converter == null){ throw new IllegalStateException("Converter not found for " + enhancedType); } assertThat(converter.transformTo(value)).isEqualTo(enhancedDocument.getList(key, enhancedType)); assertThat(enhancedDocument.getListOfUnknownType(key)).isEqualTo(value.l()); break; case M: EnhancedType keyType = enhancedTypeMap.get(key).get(0); EnhancedType valueType = enhancedTypeMap.get(key).get(1); MapAttributeConverter mapAttributeConverter = MapAttributeConverter.mapConverter( DefaultStringConverterProvider.create().converterFor(keyType), chainConverterProvider.converterFor(valueType) ); assertThat(mapAttributeConverter.transformTo(value)) .isEqualTo(enhancedDocument.getMap(key, keyType, valueType)); assertThat(enhancedDocument.getMapOfUnknownType(key)).isEqualTo(value.m()); break; default: throw new IllegalStateException("EnhancedAttributeValue type not found: " + enhancedAttributeValue.type()); } }); } }
4,314
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/document/DocumentTableSchemaTest.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.document; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; import static software.amazon.awssdk.enhanced.dynamodb.AttributeConverterProvider.defaultProvider; import static software.amazon.awssdk.enhanced.dynamodb.document.EnhancedDocumentTestData.testDataInstance; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import java.util.stream.Collectors; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ArgumentsSource; import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType; import software.amazon.awssdk.enhanced.dynamodb.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.TableMetadata; import software.amazon.awssdk.enhanced.dynamodb.converters.document.CustomAttributeForDocumentConverterProvider; import software.amazon.awssdk.enhanced.dynamodb.converters.document.CustomClassForDocumentAPI; import software.amazon.awssdk.enhanced.dynamodb.document.DocumentTableSchema; 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.internal.converter.ChainConverterProvider; import software.amazon.awssdk.enhanced.dynamodb.internal.mapper.StaticKeyAttributeMetadata; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; class DocumentTableSchemaTest { String NO_PRIMARY_KEYS_IN_METADATA = "Attempt to execute an operation that requires a primary index without defining " + "any primary key attributes in the table metadata."; @Test void converterForAttribute_APIIsNotSupported() { DocumentTableSchema documentTableSchema = DocumentTableSchema.builder().build(); assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> documentTableSchema.converterForAttribute("someKey")); } @Test void defaultBuilderWith_NoElement_CreateEmptyMetaData() { DocumentTableSchema documentTableSchema = DocumentTableSchema.builder().build(); assertThat(documentTableSchema.tableMetadata()).isNotNull(); assertThat(documentTableSchema.isAbstract()).isFalse(); //Accessing attribute for documentTableSchema when TableMetaData not supplied in the builder. assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy( () -> documentTableSchema.tableMetadata().primaryKeys()).withMessage(NO_PRIMARY_KEYS_IN_METADATA); assertThat(documentTableSchema.attributeValue(EnhancedDocument .builder() .addAttributeConverterProvider(defaultProvider()) .build(), "key")).isNull(); assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> documentTableSchema.tableMetadata().primaryKeys()); assertThat(documentTableSchema.attributeNames()).isEqualTo(Collections.emptyList()); } @Test void tableMetaData_With_BothSortAndHashKey_InTheBuilder() { DocumentTableSchema documentTableSchema = DocumentTableSchema .builder() .addIndexPartitionKey(TableMetadata.primaryIndexName(), "sampleHashKey", AttributeValueType.S) .addIndexSortKey("sort-index", "sampleSortKey", AttributeValueType.S) .build(); assertThat(documentTableSchema.attributeNames()).isEqualTo(Arrays.asList("sampleHashKey", "sampleSortKey")); assertThat(documentTableSchema.tableMetadata().keyAttributes().stream().collect(Collectors.toList())).isEqualTo( Arrays.asList(StaticKeyAttributeMetadata.create("sampleHashKey", AttributeValueType.S), StaticKeyAttributeMetadata.create("sampleSortKey", AttributeValueType.S))); } @Test void tableMetaData_WithOnly_HashKeyInTheBuilder() { DocumentTableSchema documentTableSchema = DocumentTableSchema .builder() .addIndexPartitionKey( TableMetadata.primaryIndexName(), "sampleHashKey", AttributeValueType.S) .build(); assertThat(documentTableSchema.attributeNames()).isEqualTo(Collections.singletonList("sampleHashKey")); assertThat(documentTableSchema.tableMetadata().keyAttributes().stream().collect(Collectors.toList())).isEqualTo( Collections.singletonList(StaticKeyAttributeMetadata.create("sampleHashKey", AttributeValueType.S))); } @Test void defaultConverter_IsNotCreated_When_NoConverter_IsPassedInBuilder_IgnoreNullAsFalse() { DocumentTableSchema documentTableSchema = DocumentTableSchema.builder().build(); EnhancedDocument enhancedDocument = EnhancedDocument.builder() .putNull("nullKey") .attributeConverterProviders(CustomAttributeForDocumentConverterProvider.create()) .putString("stringKey", "stringValue") .build(); assertThatIllegalStateException() .isThrownBy(() -> documentTableSchema.mapToItem(enhancedDocument.toMap(), false)) .withMessageContaining("AttributeConverter not found for class EnhancedType(java.lang.String). " + "Please add an AttributeConverterProvider for this type. If it is a default type, add the " + "DefaultAttributeConverterProvider to the builder."); } @ParameterizedTest @ArgumentsSource(EnhancedDocumentTestData.class) void validate_DocumentTableSchemaItemToMap(TestData testData) { /** * The builder method internally creates a AttributeValueMap which is saved to the ddb, if this matches then * the document is as expected */ DocumentTableSchema documentTableSchema = DocumentTableSchema.builder().build(); Assertions.assertThat( documentTableSchema.itemToMap(testData.getEnhancedDocument(), false)).isEqualTo(testData.getDdbItemMap()); } @ParameterizedTest @ArgumentsSource(EnhancedDocumentTestData.class) void validate_DocumentTableSchema_mapToItem(TestData testData) { /** * The builder method internally creates a AttributeValueMap which is saved to the ddb, if this matches then * the document is as expected */ DocumentTableSchema documentTableSchema = DocumentTableSchema.builder().build(); assertThat(documentTableSchema.mapToItem(null)).isNull(); Assertions.assertThat( documentTableSchema.mapToItem(testData.getDdbItemMap()).toMap()).isEqualTo(testData.getEnhancedDocument() .toMap()); // TODO : order mismatch ?? // // Assertions.assertThat( // documentTableSchema.mapToItem(testData.getDdbItemMap()).toJson()).isEqualTo(testData.getJson()); } @Test void enhanceTypeOf_TableSchema() { assertThat(DocumentTableSchema.builder().build().itemType()).isEqualTo(EnhancedType.of(EnhancedDocument.class)); } @Test void error_When_attributeConvertersIsOverwrittenToIncorrectConverter() { DocumentTableSchema documentTableSchema = DocumentTableSchema.builder().attributeConverterProviders(defaultProvider()) .attributeConverterProviders(ChainConverterProvider.create()).build(); TestData simpleStringData = testDataInstance().dataForScenario("simpleString"); // Lazy loading is done , thus it does not fail until we try to access some doc from enhancedDocument EnhancedDocument enhancedDocument = documentTableSchema.mapToItem(simpleStringData.getDdbItemMap(), false); assertThatIllegalStateException().isThrownBy( () -> { enhancedDocument.getString("stringKey"); }).withMessage( "AttributeConverter not found for class EnhancedType(java.lang.String). Please add an AttributeConverterProvider " + "for this type. " + "If it is a default type, add the DefaultAttributeConverterProvider to the builder."); } @Test void default_attributeConverters_isUsedFromTableSchema() { DocumentTableSchema documentTableSchema = DocumentTableSchema.builder().build(); TestData simpleStringData = testDataInstance().dataForScenario("simpleString"); EnhancedDocument enhancedDocument = documentTableSchema.mapToItem(simpleStringData.getDdbItemMap(), false); assertThat(enhancedDocument.getString("stringKey")).isEqualTo("stringValue"); } @Test void custom_attributeConverters_isUsedFromTableSchema() { DocumentTableSchema documentTableSchema = DocumentTableSchema.builder() .attributeConverterProviders(CustomAttributeForDocumentConverterProvider.create(), defaultProvider()) .build(); TestData simpleStringData = testDataInstance().dataForScenario("customList"); EnhancedDocument enhancedDocument = documentTableSchema.mapToItem(simpleStringData.getDdbItemMap(), false); assertThat(enhancedDocument.getList("customClassForDocumentAPI", EnhancedType.of(CustomClassForDocumentAPI.class)).size()).isEqualTo(2); } @ParameterizedTest @ArgumentsSource(EnhancedDocumentTestData.class) void validate_DocumentTableSchemaItemToMapWithFilter(TestData testData) { EnhancedDocument filterDocument = testData.getEnhancedDocument().toBuilder() .putString("filterOne", "str") .putBoolean("filterTwo", false) .putNumber("filterThree", 3L) .putNumber("noFilter", 10) .putNull("filterNull") .build(); Map<String, AttributeValue> filteredAttributeValueMap = new LinkedHashMap<>(); filteredAttributeValueMap.put("filterOne", AttributeValue.fromS("str")); filteredAttributeValueMap.put("filterTwo", AttributeValue.fromBool(false)); filteredAttributeValueMap.put("filterThree", AttributeValue.fromN("3")); filteredAttributeValueMap.put("filterNull", AttributeValue.fromNul(true)); DocumentTableSchema documentTableSchema = DocumentTableSchema.builder().build(); Assertions.assertThat( documentTableSchema.itemToMap(filterDocument, Arrays.asList("filterOne", "filterTwo", "filterThree","filterNull") )).isEqualTo(filteredAttributeValueMap); } @Test void validate_DocumentTableSchema_WithCustomIntegerAttributeProvider() { EnhancedDocument numberDocument = EnhancedDocument.builder() .putNumber("integerOne", 1) .putNumber("integerTen", 10) .putNull("null") .build(); Map<String, AttributeValue> resultMap = new LinkedHashMap<>(); resultMap.put("integerOne", AttributeValue.fromN("11")); resultMap.put("integerTen", AttributeValue.fromN("20")); resultMap.put("null", AttributeValue.fromNul(true)); DocumentTableSchema documentTableSchema = DocumentTableSchema.builder() .attributeConverterProviders( Collections.singletonList( CustomAttributeForDocumentConverterProvider.create())) .build(); Assertions.assertThat( documentTableSchema.itemToMap(numberDocument, true)).isEqualTo(resultMap); } }
4,315
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/document/TestData.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.document; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import software.amazon.awssdk.enhanced.dynamodb.AttributeConverterProvider; import software.amazon.awssdk.enhanced.dynamodb.EnhancedType; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; public class TestData { private EnhancedDocument enhancedDocument; private String scenario; private Map<String, AttributeValue> ddbItemMap; private TypeMap typeMap; private AttributeConverterProvider attributeConverterProvider; public String getScenario() { return scenario; } private String json; private boolean isGeneric; public static Builder dataBuilder(){ return new Builder(); } public boolean isGeneric() { return isGeneric; } public EnhancedDocument getEnhancedDocument() { return enhancedDocument; } public Map<String, AttributeValue> getDdbItemMap() { return ddbItemMap; } public TypeMap getTypeMap() { return typeMap; } public AttributeConverterProvider getAttributeConverterProvider() { return attributeConverterProvider; } public String getJson() { return json; } public TestData(Builder builder) { this.enhancedDocument = builder.enhancedDocument; this.ddbItemMap = builder.ddbItemMap; this.typeMap = builder.typeMap; this.attributeConverterProvider = builder.attributeConverterProvider; this.json = builder.json; this.isGeneric = builder.isGeneric; this.scenario = builder.scenario; } public static class Builder{ private String scenario; private Builder() { } private EnhancedDocument enhancedDocument; private boolean isGeneric = true; private Map<String, AttributeValue> ddbItemMap; private TypeMap typeMap = new TypeMap(); private AttributeConverterProvider attributeConverterProvider; private String json; public Builder enhancedDocument(EnhancedDocument enhancedDocument) { this.enhancedDocument = enhancedDocument; return this; } public Builder ddbItemMap(Map<String, AttributeValue> ddbItemMap) { this.ddbItemMap = ddbItemMap; return this; } public Builder typeMap(TypeMap typeMap) { this.typeMap = typeMap; return this; } public Builder attributeConverterProvider(AttributeConverterProvider attributeConverterProvider) { this.attributeConverterProvider = attributeConverterProvider; return this; } public Builder isGeneric(boolean isGeneric) { this.isGeneric = isGeneric; return this; } public Builder scenario(String scenario) { this.scenario = scenario; return this; } public Builder json(String json) { this.json = json; return this; } public TestData build(){ return new TestData(this); } } public static class TypeMap { private TypeMap() { } public static TypeMap typeMap(){ return new TypeMap(); } Map<String, List<EnhancedType>> enhancedTypeMap = new LinkedHashMap<>(); public Map<String, List<EnhancedType>> getEnhancedTypeMap() { return enhancedTypeMap; } public TypeMap addAttribute(String attribute, EnhancedType... enhancedType) { enhancedTypeMap.put(attribute, Arrays.asList(enhancedType)); return this; } } }
4,316
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/document/EnhancedDocumentTest.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.document; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.assertj.core.api.Assertions.assertThatNullPointerException; import static software.amazon.awssdk.enhanced.dynamodb.AttributeConverterProvider.defaultProvider; import static org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.enhanced.dynamodb.document.EnhancedDocumentTestData.testDataInstance; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import java.math.BigDecimal; import java.time.LocalDate; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.ValueSource; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.SdkNumber; import software.amazon.awssdk.enhanced.dynamodb.DefaultAttributeConverterProvider; import software.amazon.awssdk.enhanced.dynamodb.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.converters.document.CustomAttributeForDocumentConverterProvider; import software.amazon.awssdk.enhanced.dynamodb.converters.document.CustomClassForDocumentAPI; class EnhancedDocumentTest { private static Stream<Arguments> escapeDocumentStrings() { char c = 0x0a; return Stream.of( Arguments.of(String.valueOf(c), "{\"key\":\"\\n\"}") , Arguments.of("", "{\"key\":\"\"}") , Arguments.of("\"", "{\"key\":\"\\\"\"}") , Arguments.of("\\", "{\"key\":\"\\\\\"}") , Arguments.of(" ", "{\"key\":\" \"}") , Arguments.of("\t", "{\"key\":\"\\t\"}") , Arguments.of("\n", "{\"key\":\"\\n\"}") , Arguments.of("\r", "{\"key\":\"\\r\"}") , Arguments.of("\f", "{\"key\":\"\\f\"}") ); } private static Stream<Arguments> unEscapeDocumentStrings() { return Stream.of( Arguments.of("'", "{\"key\":\"'\"}"), Arguments.of("'single quote'", "{\"key\":\"'single quote'\"}") ); } @Test void enhancedDocumentGetters() { EnhancedDocument document = testDataInstance() .dataForScenario("complexDocWithSdkBytesAndMapArrays_And_PutOverWritten") .getEnhancedDocument(); // Assert assertThat(document.getString("stringKey")).isEqualTo("stringValue"); assertThat(document.getNumber("numberKey")).isEqualTo(SdkNumber.fromInteger(1)); assertThat(document.getList("numberList", EnhancedType.of(BigDecimal.class))) .containsExactly(BigDecimal.valueOf(4), BigDecimal.valueOf(5), BigDecimal.valueOf(6)); assertThat(document.getList("numberList", EnhancedType.of(SdkNumber.class))) .containsExactly(SdkNumber.fromInteger(4), SdkNumber.fromInteger(5), SdkNumber.fromInteger(6)); assertThat(document.get("simpleDate", EnhancedType.of(LocalDate.class))).isEqualTo(LocalDate.MIN); assertThat(document.getStringSet("stringSet")).containsExactly("one", "two"); assertThat(document.getBytes("sdkByteKey")).isEqualTo(SdkBytes.fromUtf8String("a")); assertThat(document.getBytesSet("sdkByteSet")) .containsExactlyInAnyOrder(SdkBytes.fromUtf8String("a"), SdkBytes.fromUtf8String("b")); assertThat(document.getNumberSet("numberSetSet")).containsExactlyInAnyOrder(SdkNumber.fromInteger(1), SdkNumber.fromInteger(2)); Map<String, BigDecimal> expectedBigDecimalMap = new LinkedHashMap<>(); expectedBigDecimalMap.put("78b3522c-2ab3-4162-8c5d-f093fa76e68c", BigDecimal.valueOf(3)); expectedBigDecimalMap.put("4ae1f694-52ce-4cf6-8211-232ccf780da8", BigDecimal.valueOf(9)); assertThat(document.getMap("simpleMap", EnhancedType.of(String.class), EnhancedType.of(BigDecimal.class))) .containsExactlyEntriesOf(expectedBigDecimalMap); Map<UUID, BigDecimal> expectedUuidBigDecimalMap = new LinkedHashMap<>(); expectedUuidBigDecimalMap.put(UUID.fromString("78b3522c-2ab3-4162-8c5d-f093fa76e68c"), BigDecimal.valueOf(3)); expectedUuidBigDecimalMap.put(UUID.fromString("4ae1f694-52ce-4cf6-8211-232ccf780da8"), BigDecimal.valueOf(9)); assertThat(document.getMap("simpleMap", EnhancedType.of(UUID.class), EnhancedType.of(BigDecimal.class))) .containsExactlyEntriesOf(expectedUuidBigDecimalMap); } @Test void enhancedDocWithNestedListAndMaps() { /** * No attributeConverters supplied, in this case it uses the {@link DefaultAttributeConverterProvider} and does not error */ EnhancedDocument simpleDoc = EnhancedDocument.builder() .attributeConverterProviders(defaultProvider()) .putString("HashKey", "abcdefg123") .putNull("nullKey") .putNumber("numberKey", 2.0) .putBytes("sdkByte", SdkBytes.fromUtf8String("a")) .putBoolean("booleanKey", true) .putJson("jsonKey", "{\"1\": [\"a\", \"b\", \"c\"],\"2\": 1}") .putStringSet("stingSet", Stream.of("a", "b", "c").collect(Collectors.toSet())) .putNumberSet("numberSet", Stream.of(1, 2, 3, 4).collect(Collectors.toSet())) .putBytesSet("sdkByteSet", Stream.of(SdkBytes.fromUtf8String("a")).collect(Collectors.toSet())) .build(); assertThat(simpleDoc.toJson()).isEqualTo("{\"HashKey\":\"abcdefg123\",\"nullKey\":null,\"numberKey\":2.0," + "\"sdkByte\":\"YQ==\",\"booleanKey\":true,\"jsonKey\":{\"1\":[\"a\",\"b\"," + "\"c\"],\"2\":1},\"stingSet\":[\"a\",\"b\",\"c\"],\"numberSet\":[1,2,3,4]," + "\"sdkByteSet\":[\"YQ==\"]}"); assertThat(simpleDoc.isPresent("HashKey")).isTrue(); // No Null pointer or doesnot exist is thrown assertThat(simpleDoc.isPresent("HashKey2")).isFalse(); assertThat(simpleDoc.getString("HashKey")).isEqualTo("abcdefg123"); assertThat(simpleDoc.isNull("nullKey")).isTrue(); assertThat(simpleDoc.getNumber("numberKey")).isEqualTo(SdkNumber.fromDouble(2.0)); assertThat(simpleDoc.getNumber("numberKey").bigDecimalValue().compareTo(BigDecimal.valueOf(2.0))).isEqualTo(0); assertThat(simpleDoc.getBytes("sdkByte")).isEqualTo(SdkBytes.fromUtf8String("a")); assertThat(simpleDoc.getBoolean("booleanKey")).isTrue(); assertThat(simpleDoc.getJson("jsonKey")).isEqualTo("{\"1\":[\"a\",\"b\",\"c\"],\"2\":1}"); assertThat(simpleDoc.getStringSet("stingSet")).isEqualTo(Stream.of("a", "b", "c").collect(Collectors.toSet())); assertThat(simpleDoc.getList("stingSet", EnhancedType.of(String.class))).isEqualTo(Stream.of("a", "b", "c").collect(Collectors.toList())); assertThat(simpleDoc.getNumberSet("numberSet") .stream().map(n -> n.intValue()).collect(Collectors.toSet())) .isEqualTo(Stream.of(1, 2, 3, 4).collect(Collectors.toSet())); assertThat(simpleDoc.getBytesSet("sdkByteSet")).isEqualTo(Stream.of(SdkBytes.fromUtf8String("a")).collect(Collectors.toSet())); // Trying to access some other Types assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() -> simpleDoc.getBoolean("sdkByteSet")) .withMessageContaining("BooleanAttributeConverter cannot convert " + "an attribute of type BS into the requested type class java.lang.Boolean"); } @Test void testNullArgsInStaticConstructor() { assertThatNullPointerException() .isThrownBy(() -> EnhancedDocument.fromAttributeValueMap(null)) .withMessage("attributeValueMap must not be null."); assertThatNullPointerException() .isThrownBy(() -> EnhancedDocument.fromJson(null)) .withMessage("json must not be null."); } @Test void accessingSetFromBuilderMethodsAsListsInDocuments() { Set<String> stringSet = Stream.of("a", "b", "c").collect(Collectors.toSet()); EnhancedDocument enhancedDocument = EnhancedDocument.builder() .addAttributeConverterProvider(defaultProvider()) .putStringSet("stringSet", stringSet) .build(); Set<String> retrievedStringSet = enhancedDocument.getStringSet("stringSet"); assertThat(retrievedStringSet).isEqualTo(stringSet); // Note that this behaviour is different in V1 , in order to remain consistent with EnhancedDDB converters List<String> retrievedStringList = enhancedDocument.getList("stringSet", EnhancedType.of(String.class)); assertThat(retrievedStringList).containsExactlyInAnyOrderElementsOf(stringSet); } @Test void builder_ResetsTheOldValues_beforeJsonSetterIsCalled() { EnhancedDocument enhancedDocument = EnhancedDocument.builder() .attributeConverterProviders(defaultProvider()) .putString("simpleKeyOriginal", "simpleValueOld") .json("{\"stringKey\": \"stringValue\"}") .putString("simpleKeyNew", "simpleValueNew") .build(); assertThat(enhancedDocument.toJson()).isEqualTo("{\"stringKey\":\"stringValue\",\"simpleKeyNew\":\"simpleValueNew\"}"); assertThat(enhancedDocument.getString("simpleKeyOriginal")).isNull(); } @Test void builder_with_NullKeys() { String EMPTY_OR_NULL_ERROR = "Attribute name must not be null or empty."; assertThatIllegalArgumentException() .isThrownBy(() -> EnhancedDocument.builder().putString(null, "Sample")) .withMessage(EMPTY_OR_NULL_ERROR); assertThatIllegalArgumentException() .isThrownBy(() -> EnhancedDocument.builder().putNull(null)) .withMessage(EMPTY_OR_NULL_ERROR); assertThatIllegalArgumentException() .isThrownBy(() -> EnhancedDocument.builder().putNumber(null, 3)) .withMessage(EMPTY_OR_NULL_ERROR); assertThatIllegalArgumentException() .isThrownBy(() -> EnhancedDocument.builder().putList(null, Arrays.asList(), EnhancedType.of(String.class))) .withMessage(EMPTY_OR_NULL_ERROR); assertThatIllegalArgumentException() .isThrownBy(() -> EnhancedDocument.builder().putBytes(null, SdkBytes.fromUtf8String("a"))) .withMessage(EMPTY_OR_NULL_ERROR); assertThatIllegalArgumentException() .isThrownBy(() -> EnhancedDocument.builder().putMap(null, new HashMap<>(), null, null)) .withMessage(EMPTY_OR_NULL_ERROR); assertThatIllegalArgumentException() .isThrownBy(() -> EnhancedDocument.builder().putStringSet(null, Stream.of("a").collect(Collectors.toSet()))) .withMessage(EMPTY_OR_NULL_ERROR); assertThatIllegalArgumentException() .isThrownBy(() -> EnhancedDocument.builder().putNumberSet(null, Stream.of(1).collect(Collectors.toSet()))) .withMessage(EMPTY_OR_NULL_ERROR); assertThatIllegalArgumentException() .isThrownBy(() -> EnhancedDocument.builder().putStringSet(null, Stream.of("a").collect(Collectors.toSet()))) .withMessage(EMPTY_OR_NULL_ERROR); assertThatIllegalArgumentException() .isThrownBy(() -> EnhancedDocument.builder().putBytesSet(null, Stream.of(SdkBytes.fromUtf8String("a")) .collect(Collectors.toSet()))) .withMessage(EMPTY_OR_NULL_ERROR); } @Test void errorWhen_NoAttributeConverter_IsProviderIsDefined() { EnhancedDocument enhancedDocument = testDataInstance().dataForScenario("simpleString") .getEnhancedDocument() .toBuilder() .attributeConverterProviders(CustomAttributeForDocumentConverterProvider.create()) .build(); EnhancedType getType = EnhancedType.of(EnhancedDocumentTestData.class); assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() -> enhancedDocument.get( "stringKey", getType )).withMessage( "AttributeConverter not found for class EnhancedType(java.lang.String). Please add an AttributeConverterProvider " + "for this type. " + "If it is a default type, add the DefaultAttributeConverterProvider to the builder."); } @Test void access_NumberAttributeFromMap() { EnhancedDocument enhancedDocument = EnhancedDocument.fromJson(testDataInstance() .dataForScenario("ElementsOfCustomType") .getJson()); assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() -> enhancedDocument.getNumber("customMapValue")) .withMessage( "software.amazon.awssdk.enhanced.dynamodb.internal.converter" + ".attribute.SdkNumberAttributeConverter cannot convert" + " an attribute of type M into the requested type class " + "software.amazon.awssdk.core.SdkNumber"); } @Test void access_CustomType_without_AttributeConverterProvider() { EnhancedDocument enhancedDocument = EnhancedDocument.fromJson(testDataInstance() .dataForScenario("ElementsOfCustomType") .getJson()); EnhancedType enhancedType = EnhancedType.of( CustomClassForDocumentAPI.class); assertThatExceptionOfType(IllegalStateException.class).isThrownBy( () -> enhancedDocument.get( "customMapValue", enhancedType)).withMessage("Converter not found for " + "EnhancedType(software.amazon.awssdk.enhanced.dynamodb.converters" + ".document.CustomClassForDocumentAPI)"); EnhancedDocument docWithCustomProvider = enhancedDocument.toBuilder().attributeConverterProviders(CustomAttributeForDocumentConverterProvider.create(), defaultProvider()).build(); assertThat(docWithCustomProvider.get("customMapValue", EnhancedType.of(CustomClassForDocumentAPI.class))).isNotNull(); } @Test void error_When_DefaultProviderIsPlacedCustomProvider() { CustomClassForDocumentAPI customObject = CustomClassForDocumentAPI.builder().string("str_one") .longNumber(26L) .aBoolean(false).build(); EnhancedDocument afterCustomClass = EnhancedDocument.builder() .attributeConverterProviders( CustomAttributeForDocumentConverterProvider.create(), defaultProvider()) .putString("direct_attr", "sample_value") .put("customObject", customObject, EnhancedType.of(CustomClassForDocumentAPI.class)) .build(); assertThat(afterCustomClass.toJson()).isEqualTo("{\"direct_attr\":\"sample_value\",\"customObject\":{\"longNumber\":26," + "\"string\":\"str_one\"}}"); EnhancedDocument enhancedDocument = EnhancedDocument.builder() .putString("direct_attr", "sample_value") .put("customObject", customObject, EnhancedType.of(CustomClassForDocumentAPI.class)).attributeConverterProviders (defaultProvider(), CustomAttributeForDocumentConverterProvider.create()) .build(); assertThatIllegalStateException().isThrownBy( () -> enhancedDocument.toJson() ).withMessage("Converter not found for " + "EnhancedType(software.amazon.awssdk.enhanced.dynamodb.converters.document.CustomClassForDocumentAPI)"); } @ParameterizedTest @ValueSource(strings = {"", " ", "\t", " ", "\n", "\r", "\f"}) void invalidKeyNames(String escapingString) { assertThatIllegalArgumentException().isThrownBy(() -> EnhancedDocument.builder() .attributeConverterProviders(defaultProvider()) .putString(escapingString, "sample") .build()) .withMessageContaining("Attribute name must not be null or empty."); } @ParameterizedTest @MethodSource("escapeDocumentStrings") void escapingTheValues(String escapingString, String expectedJson) throws JsonProcessingException { EnhancedDocument document = EnhancedDocument.builder() .attributeConverterProviders(defaultProvider()) .putString("key", escapingString) .build(); assertThat(document.toJson()).isEqualTo(expectedJson); assertThat(new ObjectMapper().readTree(document.toJson())).isNotNull(); } @ParameterizedTest @MethodSource("unEscapeDocumentStrings") void unEscapingTheValues(String escapingString, String expectedJson) throws JsonProcessingException { EnhancedDocument document = EnhancedDocument.builder() .attributeConverterProviders(defaultProvider()) .putString("key", escapingString) .build(); assertThat(document.toJson()).isEqualTo(expectedJson); assertThat(new ObjectMapper().readTree(document.toJson())).isNotNull(); } @Test void removeParameterFromDocument() { EnhancedDocument allSimpleTypes = testDataInstance().dataForScenario("allSimpleTypes").getEnhancedDocument(); assertThat(allSimpleTypes.isPresent("nullKey")).isTrue(); assertThat(allSimpleTypes.isNull("nullKey")).isTrue(); assertThat(allSimpleTypes.getNumber("numberKey").intValue()).isEqualTo(10); assertThat(allSimpleTypes.getString("stringKey")).isEqualTo("stringValue"); EnhancedDocument removedAttributesDoc = allSimpleTypes.toBuilder() .remove("nullKey") .remove("numberKey") .build(); assertThat(removedAttributesDoc.isPresent("nullKey")).isFalse(); assertThat(removedAttributesDoc.isNull("nullKey")).isFalse(); assertThat(removedAttributesDoc.isPresent("numberKey")).isFalse(); assertThat(removedAttributesDoc.getString("stringKey")).isEqualTo("stringValue"); assertThatIllegalArgumentException().isThrownBy( () -> removedAttributesDoc.toBuilder().remove("")) .withMessage("Attribute name must not be null or empty"); assertThatIllegalArgumentException().isThrownBy( () -> removedAttributesDoc.toBuilder().remove(null)) .withMessage("Attribute name must not be null or empty"); } @Test void nullValueInsertion() { final String SAMPLE_KEY = "sampleKey"; String expectedNullMessage = "Value for sampleKey must not be null. Use putNull API to insert a Null value"; EnhancedDocument.Builder builder = EnhancedDocument.builder(); assertThatNullPointerException().isThrownBy(() -> builder.putString(SAMPLE_KEY, null)).withMessage(expectedNullMessage); assertThatNullPointerException().isThrownBy(() -> builder.put(SAMPLE_KEY, null, EnhancedType.of(String.class))).withMessageContaining(expectedNullMessage); assertThatNullPointerException().isThrownBy(() -> builder.putNumber(SAMPLE_KEY, null)).withMessage(expectedNullMessage); assertThatNullPointerException().isThrownBy(() -> builder.putBytes(SAMPLE_KEY, null)).withMessage(expectedNullMessage); assertThatNullPointerException().isThrownBy(() -> builder.putStringSet(SAMPLE_KEY, null)).withMessage(expectedNullMessage); assertThatNullPointerException().isThrownBy(() -> builder.putBytesSet(SAMPLE_KEY, null)).withMessage(expectedNullMessage); assertThatNullPointerException().isThrownBy(() -> builder.putJson(SAMPLE_KEY, null)).withMessage(expectedNullMessage); assertThatNullPointerException().isThrownBy(() -> builder.putNumberSet(SAMPLE_KEY, null)).withMessage(expectedNullMessage); assertThatNullPointerException().isThrownBy(() -> builder.putMap(SAMPLE_KEY, null, EnhancedType.of(String.class), EnhancedType.of(String.class))).withMessage(expectedNullMessage); assertThatNullPointerException().isThrownBy(() -> builder.putList(SAMPLE_KEY, null, EnhancedType.of(String.class))).withMessage(expectedNullMessage); } @Test void accessingNulAttributeValue() { String NULL_KEY = "nullKey"; EnhancedDocument enhancedDocument = EnhancedDocument.builder().attributeConverterProviders(defaultProvider()).putNull(NULL_KEY).build(); Assertions.assertNull(enhancedDocument.getString(NULL_KEY)); Assertions.assertNull(enhancedDocument.getList(NULL_KEY, EnhancedType.of(String.class))); assertThat(enhancedDocument.getBoolean(NULL_KEY)).isNull(); } @Test void booleanValueRepresentation() { EnhancedDocument.Builder builder = EnhancedDocument.builder() .attributeConverterProviders(defaultProvider()); assertThat(builder.putString("boolean", "true").build().getBoolean("boolean")).isTrue(); assertThat(builder.putNumber("boolean", 1).build().getBoolean("boolean")).isTrue(); } @Test void putAndGetOfCustomTypes_with_EnhancedTypeApi() { CustomClassForDocumentAPI customObject = CustomClassForDocumentAPI.builder().string("str_one") .longNumber(26L) .aBoolean(false).build(); EnhancedDocument enhancedDocument = EnhancedDocument.builder() .attributeConverterProviders( CustomAttributeForDocumentConverterProvider.create(), defaultProvider()) .putString("direct_attr", "sample_value") .put("customObject", customObject, EnhancedType.of(CustomClassForDocumentAPI.class)) .build(); assertThat(enhancedDocument.get("customObject", EnhancedType.of(CustomClassForDocumentAPI.class))) .isEqualTo(customObject); } @Test void putAndGetOfCustomTypes_with_ClassTypes() { CustomClassForDocumentAPI customObject = CustomClassForDocumentAPI.builder().string("str_one") .longNumber(26L) .aBoolean(false).build(); EnhancedDocument enhancedDocument = EnhancedDocument.builder() .attributeConverterProviders( CustomAttributeForDocumentConverterProvider.create(), defaultProvider()) .putString("direct_attr", "sample_value") .put("customObject", customObject, CustomClassForDocumentAPI.class) .build(); assertThat(enhancedDocument.get("customObject", CustomClassForDocumentAPI.class)).isEqualTo(customObject); } @Test void error_when_usingClassGetPut_for_CollectionValues(){ assertThatIllegalArgumentException().isThrownBy( () -> EnhancedDocument.builder().put("mapKey", new HashMap(), Map.class)) .withMessage("Values of type Map are not supported by this API, please use the putMap API instead"); assertThatIllegalArgumentException().isThrownBy( () -> EnhancedDocument.builder().put("listKey", new ArrayList<>() , List.class)) .withMessage("Values of type List are not supported by this API, please use the putList API instead"); assertThatIllegalArgumentException().isThrownBy( () -> EnhancedDocument.builder().build().get("mapKey", Map.class)) .withMessage("Values of type Map are not supported by this API, please use the getMap API instead"); assertThatIllegalArgumentException().isThrownBy( () -> EnhancedDocument.builder().build().get("listKey" , List.class)) .withMessage("Values of type List are not supported by this API, please use the getList API instead"); } }
4,317
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/extensions/AtomicCounterExtensionTest.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.extensions; 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 java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import org.junit.Test; import software.amazon.awssdk.enhanced.dynamodb.OperationContext; import software.amazon.awssdk.enhanced.dynamodb.TableMetadata; import software.amazon.awssdk.enhanced.dynamodb.internal.extensions.DefaultDynamoDbExtensionContext; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.DefaultOperationContext; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.OperationName; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema; import software.amazon.awssdk.enhanced.dynamodb.update.SetAction; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; public class AtomicCounterExtensionTest { private static final String RECORD_ID = "id123"; private static final String TABLE_NAME = "table-name"; private static final OperationContext PRIMARY_CONTEXT = DefaultOperationContext.create(TABLE_NAME, TableMetadata.primaryIndexName()); private final AtomicCounterExtension atomicCounterExtension = AtomicCounterExtension.builder().build(); private static final StaticTableSchema<AtomicCounterItem> ITEM_MAPPER = StaticTableSchema.builder(AtomicCounterItem.class) .newItemSupplier(AtomicCounterItem::new) .addAttribute(String.class, a -> a.name("id") .getter(AtomicCounterItem::getId) .setter(AtomicCounterItem::setId) .addTag(primaryPartitionKey())) .addAttribute(Long.class, a -> a.name("defaultCounter") .getter(AtomicCounterItem::getDefaultCounter) .setter(AtomicCounterItem::setDefaultCounter) .addTag(atomicCounter())) .addAttribute(Long.class, a -> a.name("customCounter") .getter(AtomicCounterItem::getCustomCounter) .setter(AtomicCounterItem::setCustomCounter) .addTag(atomicCounter(5, 10))) .build(); private static final StaticTableSchema<SimpleItem> SIMPLE_ITEM_MAPPER = StaticTableSchema.builder(SimpleItem.class) .newItemSupplier(SimpleItem::new) .addAttribute(String.class, a -> a.name("id") .getter(SimpleItem::getId) .setter(SimpleItem::setId) .addTag(primaryPartitionKey())) .addAttribute(Long.class, a -> a.name("numberAttribute") .getter(SimpleItem::getNumberAttribute) .setter(SimpleItem::setNumberAttribute)) .build(); @Test public void beforeWrite_updateItemOperation_hasCounters_createsUpdateExpression() { AtomicCounterItem atomicCounterItem = new AtomicCounterItem(); atomicCounterItem.setId(RECORD_ID); Map<String, AttributeValue> items = ITEM_MAPPER.itemToMap(atomicCounterItem, true); assertThat(items).hasSize(1); WriteModification result = atomicCounterExtension.beforeWrite(DefaultDynamoDbExtensionContext.builder() .items(items) .tableMetadata(ITEM_MAPPER.tableMetadata()) .operationName(OperationName.UPDATE_ITEM) .operationContext(PRIMARY_CONTEXT).build()); Map<String, AttributeValue> transformedItem = result.transformedItem(); assertThat(transformedItem).isNotNull().hasSize(1); assertThat(transformedItem).containsEntry("id", AttributeValue.fromS(RECORD_ID)); assertThat(result.updateExpression()).isNotNull(); List<SetAction> setActions = result.updateExpression().setActions(); assertThat(setActions).hasSize(2); verifyAction(setActions, "customCounter", "5", "5"); verifyAction(setActions, "defaultCounter", "-1", "1"); } @Test public void beforeWrite_updateItemOperation_noCounters_noChanges() { SimpleItem item = new SimpleItem(); item.setId(RECORD_ID); item.setNumberAttribute(4L); Map<String, AttributeValue> items = SIMPLE_ITEM_MAPPER.itemToMap(item, true); assertThat(items).hasSize(2); WriteModification result = atomicCounterExtension.beforeWrite(DefaultDynamoDbExtensionContext.builder() .items(items) .tableMetadata(SIMPLE_ITEM_MAPPER.tableMetadata()) .operationName(OperationName.UPDATE_ITEM) .operationContext(PRIMARY_CONTEXT).build()); assertThat(result.transformedItem()).isNull(); assertThat(result.updateExpression()).isNull(); } @Test public void beforeWrite_updateItemOperation_hasCountersInItem_createsUpdateExpressionAndFilters() { AtomicCounterItem atomicCounterItem = new AtomicCounterItem(); atomicCounterItem.setId(RECORD_ID); atomicCounterItem.setCustomCounter(255L); Map<String, AttributeValue> items = ITEM_MAPPER.itemToMap(atomicCounterItem, true); assertThat(items).hasSize(2); WriteModification result = atomicCounterExtension.beforeWrite(DefaultDynamoDbExtensionContext.builder() .items(items) .tableMetadata(ITEM_MAPPER.tableMetadata()) .operationName(OperationName.UPDATE_ITEM) .operationContext(PRIMARY_CONTEXT).build()); Map<String, AttributeValue> transformedItem = result.transformedItem(); assertThat(transformedItem).isNotNull().hasSize(1); assertThat(transformedItem).containsEntry("id", AttributeValue.fromS(RECORD_ID)); assertThat(result.updateExpression()).isNotNull(); List<SetAction> setActions = result.updateExpression().setActions(); assertThat(setActions).hasSize(2); verifyAction(setActions, "customCounter", "5", "5"); verifyAction(setActions, "defaultCounter", "-1", "1"); } @Test public void beforeWrite_putItemOperation_hasCounters_createsItemTransform() { AtomicCounterItem atomicCounterItem = new AtomicCounterItem(); atomicCounterItem.setId(RECORD_ID); Map<String, AttributeValue> items = ITEM_MAPPER.itemToMap(atomicCounterItem, true); assertThat(items).hasSize(1); WriteModification result = atomicCounterExtension.beforeWrite(DefaultDynamoDbExtensionContext.builder() .items(items) .tableMetadata(ITEM_MAPPER.tableMetadata()) .operationName(OperationName.PUT_ITEM) .operationContext(PRIMARY_CONTEXT).build()); assertThat(result.transformedItem()).isNotNull(); assertThat(result.transformedItem()).hasSize(3); assertThat(result.updateExpression()).isNull(); } @Test public void beforeWrite_putItemOperation_noCounters_noChanges() { SimpleItem item = new SimpleItem(); item.setId(RECORD_ID); item.setNumberAttribute(4L); Map<String, AttributeValue> items = SIMPLE_ITEM_MAPPER.itemToMap(item, true); assertThat(items).hasSize(2); WriteModification result = atomicCounterExtension.beforeWrite(DefaultDynamoDbExtensionContext.builder() .items(items) .tableMetadata(SIMPLE_ITEM_MAPPER.tableMetadata()) .operationName(OperationName.PUT_ITEM) .operationContext(PRIMARY_CONTEXT).build()); assertThat(result.transformedItem()).isNull(); assertThat(result.updateExpression()).isNull(); } @Test public void beforeRead_doesNotTransformObject() { AtomicCounterItem atomicCounterItem = new AtomicCounterItem(); atomicCounterItem.setId(RECORD_ID); Map<String, AttributeValue> fakeItemMap = ITEM_MAPPER.itemToMap(atomicCounterItem, true); ReadModification result = atomicCounterExtension.afterRead(DefaultDynamoDbExtensionContext .builder() .items(fakeItemMap) .tableMetadata(ITEM_MAPPER.tableMetadata()) .operationContext(PRIMARY_CONTEXT).build()); assertThat(result).isEqualTo(ReadModification.builder().build()); } private void verifyAction(List<SetAction> actions, String attributeName, String expectedStart, String expectedDelta) { String expectedPath = String.format("#AMZN_MAPPED_%s", attributeName); SetAction action = actions.stream() .filter(a -> a.path().equals(expectedPath)) .findFirst() .orElseThrow(() -> new IllegalStateException("Failed to find expected action")); assertThat(action.value()).isEqualTo(String.format("if_not_exists(#AMZN_MAPPED_%1$s, :AMZN_MAPPED_%1$s_Start) + " + ":AMZN_MAPPED_%1$s_Delta", attributeName)); Map<String, String> expressionNames = Collections.singletonMap(String.format("#AMZN_MAPPED_%s", attributeName), attributeName); assertThat(action.expressionNames()).isEqualTo(expressionNames); Map<String, AttributeValue> expressionValues = new HashMap<>(); expressionValues.put(String.format(":AMZN_MAPPED_%s_Start", attributeName), AttributeValue.builder().n(expectedStart).build()); expressionValues.put(String.format(":AMZN_MAPPED_%s_Delta", attributeName), AttributeValue.builder().n(expectedDelta).build()); assertThat(action.expressionValues()).isEqualTo(expressionValues); } private static class AtomicCounterItem { private String id; private Long defaultCounter; private Long customCounter; public AtomicCounterItem() { } public String getId() { return id; } public void setId(String id) { this.id = id; } public Long getDefaultCounter() { return defaultCounter; } public void setDefaultCounter(Long defaultCounter) { this.defaultCounter = defaultCounter; } public Long getCustomCounter() { return customCounter; } public void setCustomCounter(Long customCounter) { this.customCounter = customCounter; } @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; AtomicCounterItem item = (AtomicCounterItem) o; return Objects.equals(id, item.id) && Objects.equals(defaultCounter, item.defaultCounter) && Objects.equals(customCounter, item.customCounter); } @Override public int hashCode() { return Objects.hash(super.hashCode(), id, defaultCounter, customCounter); } } private static class SimpleItem { private String id; private Long numberAttribute; public SimpleItem() { } public String getId() { return id; } public void setId(String id) { this.id = id; } public Long getNumberAttribute() { return numberAttribute; } public void setNumberAttribute(Long numberAttribute) { this.numberAttribute = numberAttribute; } @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; SimpleItem item = (SimpleItem) o; return Objects.equals(id, item.id) && Objects.equals(numberAttribute, item.numberAttribute); } @Override public int hashCode() { return Objects.hash(super.hashCode(), id, numberAttribute); } } }
4,318
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/extensions/WriteModificationTest.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.extensions; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; class WriteModificationTest { @Test void equalsHashcode() { EqualsVerifier.forClass(WriteModification.class) .withPrefabValues(AttributeValue.class, AttributeValue.builder().s("1").build(), AttributeValue.builder().s("2").build()) .verify(); } }
4,319
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/extensions/ChainExtensionTest.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.extensions; 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.nullValue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.isNotNull; import static org.mockito.Mockito.when; import static software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItem.createUniqueFakeItem; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; 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.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.functionaltests.models.FakeItem; import software.amazon.awssdk.enhanced.dynamodb.internal.extensions.ChainExtension; import software.amazon.awssdk.enhanced.dynamodb.internal.extensions.DefaultDynamoDbExtensionContext; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.DefaultOperationContext; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.OperationName; 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; @RunWith(MockitoJUnitRunner.class) public class ChainExtensionTest { private static final String TABLE_NAME = "concrete-table-name"; private static final OperationContext PRIMARY_CONTEXT = DefaultOperationContext.create(TABLE_NAME, TableMetadata.primaryIndexName()); private static final Map<String, AttributeValue> ATTRIBUTE_VALUES_1 = Collections.unmodifiableMap(Collections.singletonMap("key1", AttributeValue.builder().s("1").build())); private static final Map<String, AttributeValue> ATTRIBUTE_VALUES_2 = Collections.unmodifiableMap(Collections.singletonMap("key2", AttributeValue.builder().s("2").build())); private static final Map<String, AttributeValue> ATTRIBUTE_VALUES_3 = Collections.unmodifiableMap(Collections.singletonMap("key3", AttributeValue.builder().s("3").build())); @Mock private DynamoDbEnhancedClientExtension mockExtension1; @Mock private DynamoDbEnhancedClientExtension mockExtension2; @Mock private DynamoDbEnhancedClientExtension mockExtension3; private final List<Map<String, AttributeValue>> fakeItems = IntStream.range(0, 4) .mapToObj($ -> createUniqueFakeItem()) .map(fakeItem -> FakeItem.getTableSchema().itemToMap(fakeItem, true)) .collect(toList()); @Test public void beforeWrite_multipleExtensions_multipleModifications() { Expression expression1 = Expression.builder().expression("one").expressionValues(ATTRIBUTE_VALUES_1).build(); Expression expression2 = Expression.builder().expression("two").expressionValues(ATTRIBUTE_VALUES_2).build(); Expression expression3 = Expression.builder().expression("three").expressionValues(ATTRIBUTE_VALUES_3).build(); UpdateExpression updateExpression1 = updateExpression(removeAction("attr1")); UpdateExpression updateExpression2 = updateExpression(removeAction("attr2")); UpdateExpression updateExpression3 = updateExpression(removeAction("attr3")); ChainExtension extension = ChainExtension.create(mockExtension1, mockExtension2, mockExtension3); WriteModification writeModification1 = WriteModification.builder() .additionalConditionalExpression(expression1) .updateExpression(updateExpression1) .transformedItem(fakeItems.get(1)) .build(); WriteModification writeModification2 = WriteModification.builder() .additionalConditionalExpression(expression2) .updateExpression(updateExpression2) .transformedItem(fakeItems.get(2)) .build(); WriteModification writeModification3 = WriteModification.builder() .additionalConditionalExpression(expression3) .updateExpression(updateExpression3) .transformedItem(fakeItems.get(3)) .build(); when(mockExtension1.beforeWrite(any(DynamoDbExtensionContext.BeforeWrite.class))).thenReturn(writeModification1); when(mockExtension2.beforeWrite(any(DynamoDbExtensionContext.BeforeWrite.class))).thenReturn(writeModification2); when(mockExtension3.beforeWrite(any(DynamoDbExtensionContext.BeforeWrite.class))).thenReturn(writeModification3); WriteModification result = extension.beforeWrite(getWriteExtensionContext(0)); Map<String, AttributeValue> combinedMap = new HashMap<>(ATTRIBUTE_VALUES_1); combinedMap.putAll(ATTRIBUTE_VALUES_2); combinedMap.putAll(ATTRIBUTE_VALUES_3); Expression expectedConditionalExpression = Expression.builder().expression("((one) AND (two)) AND (three)").expressionValues(combinedMap).build(); UpdateExpression expectedUpdateExpression = updateExpression(removeAction("attr1"), removeAction("attr2"), removeAction("attr3")); assertThat(result.transformedItem(), is(fakeItems.get(3))); assertThat(result.additionalConditionalExpression(), is(expectedConditionalExpression)); assertThat(result.updateExpression(), is(expectedUpdateExpression)); InOrder inOrder = Mockito.inOrder(mockExtension1, mockExtension2, mockExtension3); inOrder.verify(mockExtension1).beforeWrite(getWriteExtensionContext(0)); inOrder.verify(mockExtension2).beforeWrite(getWriteExtensionContext(1)); inOrder.verify(mockExtension3).beforeWrite(getWriteExtensionContext(2)); inOrder.verifyNoMoreInteractions(); } @Test public void beforeWrite_multipleExtensions_doingNothing() { ChainExtension extension = ChainExtension.create(mockExtension1, mockExtension2, mockExtension3); when(mockExtension1.beforeWrite(any(DynamoDbExtensionContext.BeforeWrite.class))).thenReturn(WriteModification.builder().build()); when(mockExtension2.beforeWrite(any(DynamoDbExtensionContext.BeforeWrite.class))).thenReturn(WriteModification.builder().build()); when(mockExtension3.beforeWrite(any(DynamoDbExtensionContext.BeforeWrite.class))).thenReturn(WriteModification.builder().build()); WriteModification result = extension.beforeWrite(getWriteExtensionContext(0)); assertThat(result.additionalConditionalExpression(), is(nullValue())); assertThat(result.updateExpression(), is(nullValue())); assertThat(result.transformedItem(), is(nullValue())); InOrder inOrder = Mockito.inOrder(mockExtension1, mockExtension2, mockExtension3); inOrder.verify(mockExtension1).beforeWrite(getWriteExtensionContext(0)); inOrder.verify(mockExtension2).beforeWrite(getWriteExtensionContext(0)); inOrder.verify(mockExtension3).beforeWrite(getWriteExtensionContext(0)); inOrder.verifyNoMoreInteractions(); } @Test public void beforeWrite_multipleExtensions_singleCondition_noTransformations() { Expression conditionalExpression = Expression.builder().expression("one").expressionValues(ATTRIBUTE_VALUES_1).build(); ChainExtension extension = ChainExtension.create(mockExtension1, mockExtension2, mockExtension3); WriteModification writeModification1 = WriteModification.builder().build(); WriteModification writeModification2 = WriteModification.builder() .additionalConditionalExpression(conditionalExpression) .build(); WriteModification writeModification3 = WriteModification.builder().build(); when(mockExtension1.beforeWrite(any(DynamoDbExtensionContext.BeforeWrite.class))).thenReturn(writeModification1); when(mockExtension2.beforeWrite(any(DynamoDbExtensionContext.BeforeWrite.class))).thenReturn(writeModification2); when(mockExtension3.beforeWrite(any(DynamoDbExtensionContext.BeforeWrite.class))).thenReturn(writeModification3); WriteModification result = extension.beforeWrite(getWriteExtensionContext(0)); Expression expectedConditionalExpression = Expression.builder() .expression("one") .expressionValues(ATTRIBUTE_VALUES_1) .build(); assertThat(result.transformedItem(), is(nullValue())); assertThat(result.additionalConditionalExpression(), is(expectedConditionalExpression)); InOrder inOrder = Mockito.inOrder(mockExtension1, mockExtension2, mockExtension3); inOrder.verify(mockExtension1).beforeWrite(getWriteExtensionContext(0)); inOrder.verify(mockExtension2).beforeWrite(getWriteExtensionContext(0)); inOrder.verify(mockExtension3).beforeWrite(getWriteExtensionContext(0)); inOrder.verifyNoMoreInteractions(); } @Test public void beforeWrite_multipleExtensions_noConditions_singleTransformation() { ChainExtension extension = ChainExtension.create(mockExtension1, mockExtension2, mockExtension3); WriteModification writeModification1 = WriteModification.builder().build(); WriteModification writeModification2 = WriteModification.builder() .transformedItem(fakeItems.get(1)) .build(); WriteModification writeModification3 = WriteModification.builder().build(); when(mockExtension1.beforeWrite(any(DynamoDbExtensionContext.BeforeWrite.class))).thenReturn(writeModification1); when(mockExtension2.beforeWrite(any(DynamoDbExtensionContext.BeforeWrite.class))).thenReturn(writeModification2); when(mockExtension3.beforeWrite(any(DynamoDbExtensionContext.BeforeWrite.class))).thenReturn(writeModification3); WriteModification result = extension.beforeWrite(getWriteExtensionContext(0)); assertThat(result.transformedItem(), is(fakeItems.get(1))); assertThat(result.additionalConditionalExpression(), is(nullValue())); InOrder inOrder = Mockito.inOrder(mockExtension1, mockExtension2, mockExtension3); inOrder.verify(mockExtension1).beforeWrite(getWriteExtensionContext(0)); inOrder.verify(mockExtension2).beforeWrite(getWriteExtensionContext(0)); inOrder.verify(mockExtension3).beforeWrite(getWriteExtensionContext(1)); inOrder.verifyNoMoreInteractions(); } @Test public void beforeWrite_noExtensions() { ChainExtension extension = ChainExtension.create(); WriteModification result = extension.beforeWrite(getWriteExtensionContext(0)); assertThat(result.transformedItem(), is(nullValue())); assertThat(result.additionalConditionalExpression(), is(nullValue())); } @Test public void afterRead_multipleExtensions_multipleTransformations() { ChainExtension extension = ChainExtension.create(mockExtension1, mockExtension2, mockExtension3); ReadModification readModification1 = ReadModification.builder().transformedItem(fakeItems.get(1)).build(); ReadModification readModification2 = ReadModification.builder().transformedItem(fakeItems.get(2)).build(); ReadModification readModification3 = ReadModification.builder().transformedItem(fakeItems.get(3)).build(); when(mockExtension1.afterRead(any(DynamoDbExtensionContext.AfterRead.class))).thenReturn(readModification1); when(mockExtension2.afterRead(any(DynamoDbExtensionContext.AfterRead.class))).thenReturn(readModification2); when(mockExtension3.afterRead(any(DynamoDbExtensionContext.AfterRead.class))).thenReturn(readModification3); ReadModification result = extension.afterRead(getReadExtensionContext(0)); assertThat(result.transformedItem(), is(fakeItems.get(1))); InOrder inOrder = Mockito.inOrder(mockExtension1, mockExtension2, mockExtension3); inOrder.verify(mockExtension3).afterRead(getReadExtensionContext(0)); inOrder.verify(mockExtension2).afterRead(getReadExtensionContext(3)); inOrder.verify(mockExtension1).afterRead(getReadExtensionContext(2)); inOrder.verifyNoMoreInteractions(); } @Test public void afterRead_multipleExtensions_singleTransformation() { ChainExtension extension = ChainExtension.create(mockExtension1, mockExtension2, mockExtension3); ReadModification readModification1 = ReadModification.builder().build(); ReadModification readModification2 = ReadModification.builder().transformedItem(fakeItems.get(1)).build(); ReadModification readModification3 = ReadModification.builder().build(); when(mockExtension1.afterRead(any(DynamoDbExtensionContext.AfterRead.class))).thenReturn(readModification1); when(mockExtension2.afterRead(any(DynamoDbExtensionContext.AfterRead.class))).thenReturn(readModification2); when(mockExtension3.afterRead(any(DynamoDbExtensionContext.AfterRead.class))).thenReturn(readModification3); ReadModification result = extension.afterRead(getReadExtensionContext(0)); assertThat(result.transformedItem(), is(fakeItems.get(1))); InOrder inOrder = Mockito.inOrder(mockExtension1, mockExtension2, mockExtension3); inOrder.verify(mockExtension3).afterRead(getReadExtensionContext(0)); inOrder.verify(mockExtension2).afterRead(getReadExtensionContext(0)); inOrder.verify(mockExtension1).afterRead(getReadExtensionContext(1)); inOrder.verifyNoMoreInteractions(); } @Test public void afterRead_multipleExtensions_noTransformations() { ChainExtension extension = ChainExtension.create(mockExtension1, mockExtension2, mockExtension3); ReadModification readModification1 = ReadModification.builder().build(); ReadModification readModification2 = ReadModification.builder().build(); ReadModification readModification3 = ReadModification.builder().build(); when(mockExtension1.afterRead(any(DynamoDbExtensionContext.AfterRead.class))).thenReturn(readModification1); when(mockExtension2.afterRead(any(DynamoDbExtensionContext.AfterRead.class))).thenReturn(readModification2); when(mockExtension3.afterRead(any(DynamoDbExtensionContext.AfterRead.class))).thenReturn(readModification3); ReadModification result = extension.afterRead(getReadExtensionContext(0)); assertThat(result.transformedItem(), is(nullValue())); InOrder inOrder = Mockito.inOrder(mockExtension1, mockExtension2, mockExtension3); inOrder.verify(mockExtension3).afterRead(getReadExtensionContext(0)); inOrder.verify(mockExtension2).afterRead(getReadExtensionContext(0)); inOrder.verify(mockExtension1).afterRead(getReadExtensionContext(0)); inOrder.verifyNoMoreInteractions(); } @Test public void afterRead_noExtensions() { ChainExtension extension = ChainExtension.create(); ReadModification result = extension.afterRead(getReadExtensionContext(0)); assertThat(result.transformedItem(), is(nullValue())); } private DefaultDynamoDbExtensionContext getWriteExtensionContext(int i) { return getExtensionContext(i, OperationName.BATCH_WRITE_ITEM); } private DefaultDynamoDbExtensionContext getReadExtensionContext(int i) { return getExtensionContext(i, null); } private DefaultDynamoDbExtensionContext getExtensionContext(int i, OperationName operationName) { DefaultDynamoDbExtensionContext.Builder context = DefaultDynamoDbExtensionContext.builder() .tableMetadata(FakeItem.getTableMetadata()) .tableSchema(FakeItem.getTableSchema()) .operationContext(PRIMARY_CONTEXT) .items(fakeItems.get(i)); if (operationName != null) { context.operationName(OperationName.BATCH_WRITE_ITEM); } return context.build(); } private static RemoveAction removeAction(String attributeName) { return RemoveAction.builder() .path(keyRef(attributeName)) .putExpressionName(keyRef(attributeName), attributeName) .build(); } private static SetAction setAction(String attributeName, AttributeValue value) { return SetAction.builder() .value(valueRef(attributeName)) .putExpressionValue(valueRef(attributeName), value) .path(keyRef(attributeName)) .putExpressionName(keyRef(attributeName), attributeName) .build(); } private UpdateExpression updateExpression(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) { return "#AMZN_" + key; } private static String valueRef(String value) { return ":AMZN_" + value; } }
4,320
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/extensions/VersionedRecordExtensionTest.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.extensions; import static java.util.Collections.singletonMap; import static org.hamcrest.MatcherAssert.assertThat; 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 java.util.HashMap; import java.util.Map; import org.junit.Test; 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.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.internal.operations.DefaultOperationContext; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; public class VersionedRecordExtensionTest { private static final String TABLE_NAME = "table-name"; private static final OperationContext PRIMARY_CONTEXT = DefaultOperationContext.create(TABLE_NAME, TableMetadata.primaryIndexName()); private final VersionedRecordExtension versionedRecordExtension = VersionedRecordExtension.builder().build(); @Test public void beforeRead_doesNotTransformObject() { FakeItem fakeItem = createUniqueFakeItem(); Map<String, AttributeValue> fakeItemMap = FakeItem.getTableSchema().itemToMap(fakeItem, true); ReadModification result = versionedRecordExtension.afterRead(DefaultDynamoDbExtensionContext .builder() .items(fakeItemMap) .tableMetadata(FakeItem.getTableMetadata()) .operationContext(PRIMARY_CONTEXT).build()); assertThat(result, is(ReadModification.builder().build())); } @Test public void beforeWrite_initialVersion_expressionIsCorrect() { FakeItem fakeItem = createUniqueFakeItem(); WriteModification result = versionedRecordExtension.beforeWrite( DefaultDynamoDbExtensionContext .builder() .items(FakeItem.getTableSchema().itemToMap(fakeItem, true)) .tableMetadata(FakeItem.getTableMetadata()) .operationContext(PRIMARY_CONTEXT).build()); assertThat(result.additionalConditionalExpression(), is(Expression.builder() .expression("attribute_not_exists(#AMZN_MAPPED_version)") .expressionNames(singletonMap("#AMZN_MAPPED_version", "version")) .build())); } @Test public void beforeWrite_initialVersion_transformedItemIsCorrect() { FakeItem fakeItem = createUniqueFakeItem(); Map<String, AttributeValue> fakeItemWithInitialVersion = new HashMap<>(FakeItem.getTableSchema().itemToMap(fakeItem, true)); fakeItemWithInitialVersion.put("version", AttributeValue.builder().n("1").build()); WriteModification result = versionedRecordExtension.beforeWrite(DefaultDynamoDbExtensionContext .builder() .items(FakeItem.getTableSchema().itemToMap(fakeItem, true)) .tableMetadata(FakeItem.getTableMetadata()) .operationContext(PRIMARY_CONTEXT).build()); assertThat(result.transformedItem(), is(fakeItemWithInitialVersion)); } @Test public void beforeWrite_initialVersionDueToExplicitNull_transformedItemIsCorrect() { FakeItem fakeItem = createUniqueFakeItem(); Map<String, AttributeValue> inputMap = new HashMap<>(FakeItem.getTableSchema().itemToMap(fakeItem, true)); inputMap.put("version", AttributeValue.builder().nul(true).build()); Map<String, AttributeValue> fakeItemWithInitialVersion = new HashMap<>(FakeItem.getTableSchema().itemToMap(fakeItem, true)); fakeItemWithInitialVersion.put("version", AttributeValue.builder().n("1").build()); WriteModification result = versionedRecordExtension.beforeWrite(DefaultDynamoDbExtensionContext .builder() .items(inputMap) .tableMetadata(FakeItem.getTableMetadata()) .operationContext(PRIMARY_CONTEXT).build()); assertThat(result.transformedItem(), is(fakeItemWithInitialVersion)); } @Test public void beforeWrite_existingVersion_expressionIsCorrect() { FakeItem fakeItem = createUniqueFakeItem(); fakeItem.setVersion(13); WriteModification result = versionedRecordExtension.beforeWrite(DefaultDynamoDbExtensionContext .builder() .items(FakeItem.getTableSchema().itemToMap(fakeItem, true)) .tableMetadata(FakeItem.getTableMetadata()) .operationContext(PRIMARY_CONTEXT).build()); assertThat(result.additionalConditionalExpression(), is(Expression.builder() .expression("#AMZN_MAPPED_version = :old_version_value") .expressionNames(singletonMap("#AMZN_MAPPED_version", "version")) .expressionValues(singletonMap(":old_version_value", AttributeValue.builder().n("13").build())) .build())); } @Test public void beforeWrite_existingVersion_transformedItemIsCorrect() { FakeItem fakeItem = createUniqueFakeItem(); fakeItem.setVersion(13); Map<String, AttributeValue> fakeItemWithInitialVersion = new HashMap<>(FakeItem.getTableSchema().itemToMap(fakeItem, true)); fakeItemWithInitialVersion.put("version", AttributeValue.builder().n("14").build()); WriteModification result = versionedRecordExtension.beforeWrite(DefaultDynamoDbExtensionContext .builder() .items(FakeItem.getTableSchema().itemToMap(fakeItem, true)) .tableMetadata(FakeItem.getTableMetadata()) .operationContext(PRIMARY_CONTEXT).build()); assertThat(result.transformedItem(), is(fakeItemWithInitialVersion)); } @Test public void beforeWrite_returnsNoOpModification_ifVersionAttributeNotDefined() { FakeItemWithSort fakeItemWithSort = createUniqueFakeItemWithSort(); Map<String, AttributeValue> itemMap = new HashMap<>(FakeItemWithSort.getTableSchema().itemToMap(fakeItemWithSort, true)); WriteModification writeModification = versionedRecordExtension.beforeWrite( DefaultDynamoDbExtensionContext.builder() .items(itemMap) .operationContext(PRIMARY_CONTEXT) .tableMetadata(FakeItemWithSort.getTableMetadata()) .build()); assertThat(writeModification, is(WriteModification.builder().build())); } @Test(expected = IllegalArgumentException.class) public void beforeWrite_throwsIllegalArgumentException_ifVersionAttributeIsWrongType() { FakeItem fakeItem = createUniqueFakeItem(); Map<String, AttributeValue> fakeItemWIthBadVersion = new HashMap<>(FakeItem.getTableSchema().itemToMap(fakeItem, true)); fakeItemWIthBadVersion.put("version", AttributeValue.builder().s("14").build()); versionedRecordExtension.beforeWrite( DefaultDynamoDbExtensionContext.builder() .items(fakeItemWIthBadVersion) .operationContext(PRIMARY_CONTEXT) .tableMetadata(FakeItem.getTableMetadata()) .build()); } }
4,321
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/model/DeleteItemEnhancedResponseTest.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.model; import static org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItem.createUniqueFakeItem; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Test; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItem; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.ConsumedCapacity; import software.amazon.awssdk.services.dynamodb.model.ItemCollectionMetrics; public class DeleteItemEnhancedResponseTest { @Test public void builder_minimal() { DeleteItemEnhancedResponse<FakeItem> builtObject = DeleteItemEnhancedResponse.builder(FakeItem.class).build(); assertThat(builtObject.attributes()).isNull(); assertThat(builtObject.consumedCapacity()).isNull(); assertThat(builtObject.itemCollectionMetrics()).isNull(); } @Test public void builder_maximal() { FakeItem fakeItem = createUniqueFakeItem(); ConsumedCapacity consumedCapacity = ConsumedCapacity.builder().tableName("MyTable").build(); Map<String, AttributeValue> collectionKey = new HashMap<>(); collectionKey.put("foo", AttributeValue.builder().s("bar").build()); ItemCollectionMetrics itemCollectionMetrics = ItemCollectionMetrics.builder().itemCollectionKey(collectionKey).build(); DeleteItemEnhancedResponse<FakeItem> builtObject = DeleteItemEnhancedResponse.builder(FakeItem.class) .attributes(fakeItem) .consumedCapacity(consumedCapacity) .itemCollectionMetrics(itemCollectionMetrics) .build(); assertThat(builtObject.attributes()).isEqualTo(fakeItem); assertThat(builtObject.consumedCapacity()).isEqualTo(consumedCapacity); assertThat(builtObject.itemCollectionMetrics()).isEqualTo(itemCollectionMetrics); } @Test public void equals_self() { DeleteItemEnhancedResponse<FakeItem> builtObject = DeleteItemEnhancedResponse.builder(FakeItem.class).build(); assertThat(builtObject).isEqualTo(builtObject); } @Test public void equals_differentType() { DeleteItemEnhancedResponse<FakeItem> builtObject = DeleteItemEnhancedResponse.builder(FakeItem.class).build(); assertThat(builtObject).isNotEqualTo(new Object()); } @Test public void equals_attributesNotEqual() { FakeItem fakeItem1 = createUniqueFakeItem(); FakeItem fakeItem2 = createUniqueFakeItem(); DeleteItemEnhancedResponse<FakeItem> builtObject1 = DeleteItemEnhancedResponse.builder(FakeItem.class) .attributes(fakeItem1) .build(); DeleteItemEnhancedResponse<FakeItem> builtObject2 = DeleteItemEnhancedResponse.builder(FakeItem.class) .attributes(fakeItem2) .build(); assertThat(builtObject1).isNotEqualTo(builtObject2); } @Test public void hashCode_minimal() { DeleteItemEnhancedResponse<FakeItem> emptyResponse = DeleteItemEnhancedResponse.builder(FakeItem.class).build(); assertThat(emptyResponse.hashCode()).isEqualTo(0); } @Test public void hashCode_includesAttributes() { DeleteItemEnhancedResponse<FakeItem> emptyResponse = DeleteItemEnhancedResponse.builder(FakeItem.class).build(); FakeItem fakeItem = createUniqueFakeItem(); DeleteItemEnhancedResponse<FakeItem> containsAttributes = DeleteItemEnhancedResponse.builder(FakeItem.class) .attributes(fakeItem) .build(); assertThat(containsAttributes.hashCode()).isNotEqualTo(emptyResponse.hashCode()); } @Test public void hashCode_includesConsumedCapacity() { DeleteItemEnhancedResponse<FakeItem> emptyResponse = DeleteItemEnhancedResponse.builder(FakeItem.class).build(); ConsumedCapacity consumedCapacity = ConsumedCapacity.builder().tableName("MyTable").build(); DeleteItemEnhancedResponse<FakeItem> containsConsumedCapacity = DeleteItemEnhancedResponse.builder(FakeItem.class) .consumedCapacity(consumedCapacity) .build(); assertThat(containsConsumedCapacity.hashCode()).isNotEqualTo(emptyResponse.hashCode()); } @Test public void hashCode_includesItemCollectionMetrics() { DeleteItemEnhancedResponse<FakeItem> emptyResponse = DeleteItemEnhancedResponse.builder(FakeItem.class).build(); Map<String, AttributeValue> collectionKey = new HashMap<>(); collectionKey.put("foo", AttributeValue.builder().s("bar").build()); ItemCollectionMetrics itemCollectionMetrics = ItemCollectionMetrics.builder().itemCollectionKey(collectionKey).build(); DeleteItemEnhancedResponse<FakeItem> containsItemCollectionMetrics = DeleteItemEnhancedResponse.builder(FakeItem.class) .itemCollectionMetrics(itemCollectionMetrics) .build(); assertThat(containsItemCollectionMetrics.hashCode()).isNotEqualTo(emptyResponse.hashCode()); } }
4,322
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/model/ScanEnhancedRequestTest.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.model; import static java.util.Collections.singletonMap; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.numberValue; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.stringValue; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.enhanced.dynamodb.Expression; import software.amazon.awssdk.enhanced.dynamodb.NestedAttributeName; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; @RunWith(MockitoJUnitRunner.class) public class ScanEnhancedRequestTest { @Test public void builder_minimal() { ScanEnhancedRequest builtObject = ScanEnhancedRequest.builder().build(); assertThat(builtObject.exclusiveStartKey(), is(nullValue())); assertThat(builtObject.consistentRead(), is(nullValue())); assertThat(builtObject.filterExpression(), is(nullValue())); assertThat(builtObject.attributesToProject(), is(nullValue())); assertThat(builtObject.limit(), is(nullValue())); assertThat(builtObject.segment(), is(nullValue())); assertThat(builtObject.totalSegments(), is(nullValue())); } @Test public void builder_maximal() { Map<String, AttributeValue> exclusiveStartKey = new HashMap<>(); exclusiveStartKey.put("id", stringValue("id-value")); exclusiveStartKey.put("sort", numberValue(7)); Map<String, AttributeValue> expressionValues = singletonMap(":test-key", stringValue("test-value")); Expression filterExpression = Expression.builder() .expression("test-expression") .expressionValues(expressionValues) .build(); String[] attributesToProjectArray = {"one", "two"}; String additionalElement = "three"; List<String> attributesToProject = new ArrayList<>(Arrays.asList(attributesToProjectArray)); attributesToProject.add(additionalElement); ScanEnhancedRequest builtObject = ScanEnhancedRequest.builder() .exclusiveStartKey(exclusiveStartKey) .consistentRead(false) .filterExpression(filterExpression) .attributesToProject(attributesToProjectArray) .addAttributeToProject(additionalElement) .limit(3) .segment(0) .totalSegments(5) .build(); assertThat(builtObject.exclusiveStartKey(), is(exclusiveStartKey)); assertThat(builtObject.consistentRead(), is(false)); assertThat(builtObject.filterExpression(), is(filterExpression)); assertThat(builtObject.attributesToProject(), is(attributesToProject)); assertThat(builtObject.limit(), is(3)); assertThat(builtObject.segment(), is(0)); assertThat(builtObject.totalSegments(), is(5)); } @Test public void test_withNestedAttributeAddedFirst() { String[] attributesToProjectArray = {"one", "two"}; String additionalElement = "three"; ScanEnhancedRequest builtObject = ScanEnhancedRequest.builder() .addNestedAttributesToProject(NestedAttributeName.create("foo", "bar")) .attributesToProject(attributesToProjectArray) .addAttributeToProject(additionalElement) .build(); List<String> attributesToProject = Arrays.asList("one", "two", "three"); assertThat(builtObject.attributesToProject(), is(attributesToProject)); } @Test public void test_nestedAttributesToProjectWithNestedAttributeAddedLast() { String[] attributesToProjectArray = {"one", "two"}; String additionalElement = "three"; ScanEnhancedRequest builtObjectOne = ScanEnhancedRequest.builder() .attributesToProject(attributesToProjectArray) .addAttributeToProject(additionalElement) .addNestedAttributesToProject(NestedAttributeName.create("foo", "bar")) .build(); List<String> attributesToProjectNestedLast = Arrays.asList("one", "two", "three", "foo.bar"); assertThat(builtObjectOne.attributesToProject(), is(attributesToProjectNestedLast)); } @Test public void test_nestedAttributesToProjectWithNestedAttributeAddedInBetween() { String[] attributesToProjectArray = {"one", "two"}; String additionalElement = "three"; ScanEnhancedRequest builtObjectOne = ScanEnhancedRequest.builder() .attributesToProject(attributesToProjectArray) .addNestedAttributesToProject(NestedAttributeName.create("foo", "bar")) .addAttributeToProject(additionalElement) .build(); List<String> attributesToProjectNestedLast = Arrays.asList("one", "two", "foo.bar", "three"); assertThat(builtObjectOne.attributesToProject(), is(attributesToProjectNestedLast)); } @Test public void test_nestedAttributesToProjectOverwrite() { String[] attributesToProjectArray = {"one", "two"}; String additionalElement = "three"; String[] overwrite = { "overwrite"}; ScanEnhancedRequest builtObjectTwo = ScanEnhancedRequest.builder() .attributesToProject(attributesToProjectArray) .addAttributeToProject(additionalElement) .addNestedAttributesToProject(NestedAttributeName.create("foo", "bar")) .attributesToProject(overwrite) .build(); assertThat(builtObjectTwo.attributesToProject(), is(Arrays.asList(overwrite))); } @Test public void test_nestedAttributesNullStringElement() { String[] attributesToProjectArray = {"one", "two", null}; String additionalElement = "three"; assertThatThrownBy(() -> ScanEnhancedRequest.builder() .attributesToProject(attributesToProjectArray) .addAttributeToProject(additionalElement) .addAttributeToProject(null) .addNestedAttributesToProject(NestedAttributeName.create("foo", "bar")) .build()).isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> ScanEnhancedRequest.builder() .attributesToProject("foo", "bar", null) .build()).isInstanceOf(IllegalArgumentException.class); } @Test public void test_nestedAttributesNullNestedAttributeElement() { List<NestedAttributeName> attributeNames = new ArrayList<>(); attributeNames.add(NestedAttributeName.create("foo")); attributeNames.add(null); assertThatThrownBy(() -> ScanEnhancedRequest.builder() .addNestedAttributesToProject(attributeNames) .build()).isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> ScanEnhancedRequest.builder() .addNestedAttributesToProject(NestedAttributeName.create("foo", "bar"), null) .build()).isInstanceOf(IllegalArgumentException.class); NestedAttributeName nestedAttributeName = null; ScanEnhancedRequest.builder() .addNestedAttributeToProject(nestedAttributeName) .build(); assertThatThrownBy(() -> ScanEnhancedRequest.builder() .addNestedAttributesToProject(nestedAttributeName) .build()).isInstanceOf(IllegalArgumentException.class); } @Test public void toBuilder() { ScanEnhancedRequest builtObject = ScanEnhancedRequest.builder().exclusiveStartKey(null).build(); ScanEnhancedRequest copiedObject = builtObject.toBuilder().build(); assertThat(copiedObject, is(builtObject)); } }
4,323
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/model/UpdateItemEnhancedResponseTest.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.model; import static org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItem.createUniqueFakeItem; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Test; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItem; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.ConsumedCapacity; import software.amazon.awssdk.services.dynamodb.model.ItemCollectionMetrics; public class UpdateItemEnhancedResponseTest { @Test public void builder_minimal() { UpdateItemEnhancedResponse<FakeItem> builtObject = UpdateItemEnhancedResponse.builder(FakeItem.class).build(); assertThat(builtObject.attributes()).isNull(); assertThat(builtObject.consumedCapacity()).isNull(); assertThat(builtObject.itemCollectionMetrics()).isNull(); } @Test public void builder_maximal() { FakeItem fakeItem = createUniqueFakeItem(); ConsumedCapacity consumedCapacity = ConsumedCapacity.builder().tableName("MyTable").build(); Map<String, AttributeValue> collectionKey = new HashMap<>(); collectionKey.put("foo", AttributeValue.builder().s("bar").build()); ItemCollectionMetrics itemCollectionMetrics = ItemCollectionMetrics.builder().itemCollectionKey(collectionKey).build(); UpdateItemEnhancedResponse<FakeItem> builtObject = UpdateItemEnhancedResponse.builder(FakeItem.class) .attributes(fakeItem) .consumedCapacity(consumedCapacity) .itemCollectionMetrics(itemCollectionMetrics) .build(); assertThat(builtObject.attributes()).isEqualTo(fakeItem); assertThat(builtObject.consumedCapacity()).isEqualTo(consumedCapacity); assertThat(builtObject.itemCollectionMetrics()).isEqualTo(itemCollectionMetrics); } @Test public void equals_self() { UpdateItemEnhancedResponse<FakeItem> builtObject = UpdateItemEnhancedResponse.builder(FakeItem.class).build(); assertThat(builtObject).isEqualTo(builtObject); } @Test public void equals_differentType() { UpdateItemEnhancedResponse<FakeItem> builtObject = UpdateItemEnhancedResponse.builder(FakeItem.class).build(); assertThat(builtObject).isNotEqualTo(new Object()); } @Test public void equals_attributesNotEqual() { FakeItem fakeItem1 = createUniqueFakeItem(); FakeItem fakeItem2 = createUniqueFakeItem(); UpdateItemEnhancedResponse<FakeItem> builtObject1 = UpdateItemEnhancedResponse.builder(FakeItem.class) .attributes(fakeItem1) .build(); UpdateItemEnhancedResponse<FakeItem> builtObject2 = UpdateItemEnhancedResponse.builder(FakeItem.class) .attributes(fakeItem2) .build(); assertThat(builtObject1).isNotEqualTo(builtObject2); } @Test public void hashCode_minimal() { UpdateItemEnhancedResponse<FakeItem> emptyResponse = UpdateItemEnhancedResponse.builder(FakeItem.class).build(); assertThat(emptyResponse.hashCode()).isEqualTo(0); } @Test public void hashCode_includesAttributes() { UpdateItemEnhancedResponse<FakeItem> emptyResponse = UpdateItemEnhancedResponse.builder(FakeItem.class).build(); FakeItem fakeItem = createUniqueFakeItem(); UpdateItemEnhancedResponse<FakeItem> containsAttributes = UpdateItemEnhancedResponse.builder(FakeItem.class) .attributes(fakeItem) .build(); assertThat(containsAttributes.hashCode()).isNotEqualTo(emptyResponse.hashCode()); } @Test public void hashCode_includesConsumedCapacity() { UpdateItemEnhancedResponse<FakeItem> emptyResponse = UpdateItemEnhancedResponse.builder(FakeItem.class).build(); ConsumedCapacity consumedCapacity = ConsumedCapacity.builder().tableName("MyTable").build(); UpdateItemEnhancedResponse<FakeItem> containsConsumedCapacity = UpdateItemEnhancedResponse.builder(FakeItem.class) .consumedCapacity(consumedCapacity) .build(); assertThat(containsConsumedCapacity.hashCode()).isNotEqualTo(emptyResponse.hashCode()); } @Test public void hashCode_includesItemCollectionMetrics() { UpdateItemEnhancedResponse<FakeItem> emptyResponse = UpdateItemEnhancedResponse.builder(FakeItem.class).build(); Map<String, AttributeValue> collectionKey = new HashMap<>(); collectionKey.put("foo", AttributeValue.builder().s("bar").build()); ItemCollectionMetrics itemCollectionMetrics = ItemCollectionMetrics.builder().itemCollectionKey(collectionKey).build(); UpdateItemEnhancedResponse<FakeItem> containsItemCollectionMetrics = UpdateItemEnhancedResponse.builder(FakeItem.class) .itemCollectionMetrics(itemCollectionMetrics) .build(); assertThat(containsItemCollectionMetrics.hashCode()).isNotEqualTo(emptyResponse.hashCode()); } }
4,324
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/model/BatchWriteItemEnhancedRequestTest.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.model; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import java.util.Collections; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItem; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; @RunWith(MockitoJUnitRunner.class) public class BatchWriteItemEnhancedRequestTest { private static final String TABLE_NAME = "table-name"; @Mock private DynamoDbClient mockDynamoDbClient; private DynamoDbEnhancedClient enhancedClient; private DynamoDbTable<FakeItem> fakeItemMappedTable; @Before public void setupMappedTables() { enhancedClient = DynamoDbEnhancedClient.builder().dynamoDbClient(mockDynamoDbClient).build(); fakeItemMappedTable = enhancedClient.table(TABLE_NAME, FakeItem.getTableSchema()); } @Test public void builder_minimal() { BatchWriteItemEnhancedRequest builtObject = BatchWriteItemEnhancedRequest.builder().build(); assertThat(builtObject.writeBatches(), is(nullValue())); } @Test public void builder_maximal() { WriteBatch writeBatch = WriteBatch.builder(FakeItem.class) .mappedTableResource(fakeItemMappedTable) .addDeleteItem(r -> r.key(k -> k.partitionValue("key"))) .build(); BatchWriteItemEnhancedRequest builtObject = BatchWriteItemEnhancedRequest.builder() .writeBatches(writeBatch) .build(); assertThat(builtObject.writeBatches(), is(Collections.singletonList(writeBatch))); } @Test public void builder_add_single() { WriteBatch writeBatch = WriteBatch.builder(FakeItem.class) .mappedTableResource(fakeItemMappedTable) .addDeleteItem(r -> r.key(k -> k.partitionValue("key"))) .build(); BatchWriteItemEnhancedRequest builtObject = BatchWriteItemEnhancedRequest.builder() .addWriteBatch(writeBatch) .build(); assertThat(builtObject.writeBatches(), is(Collections.singletonList(writeBatch))); } @Test public void toBuilder() { BatchWriteItemEnhancedRequest builtObject = BatchWriteItemEnhancedRequest.builder().build(); BatchWriteItemEnhancedRequest copiedObject = builtObject.toBuilder().build(); assertThat(copiedObject, is(builtObject)); } }
4,325
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/model/PutItemEnhancedRequestTest.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.model; 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 software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItem.createUniqueFakeItem; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.stringValue; import java.util.UUID; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.enhanced.dynamodb.Expression; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItem; import software.amazon.awssdk.services.dynamodb.model.ReturnConsumedCapacity; import software.amazon.awssdk.services.dynamodb.model.ReturnItemCollectionMetrics; import software.amazon.awssdk.services.dynamodb.model.ReturnValue; @RunWith(MockitoJUnitRunner.class) public class PutItemEnhancedRequestTest { @Test public void builder_minimal() { PutItemEnhancedRequest<FakeItem> builtObject = PutItemEnhancedRequest.builder(FakeItem.class).build(); assertThat(builtObject.item(), is(nullValue())); assertThat(builtObject.conditionExpression(), is(nullValue())); assertThat(builtObject.returnValues(), is(nullValue())); assertThat(builtObject.returnValuesAsString(), is(nullValue())); assertThat(builtObject.returnConsumedCapacity(), is(nullValue())); assertThat(builtObject.returnConsumedCapacityAsString(), is(nullValue())); assertThat(builtObject.returnItemCollectionMetrics(), is(nullValue())); assertThat(builtObject.returnItemCollectionMetricsAsString(), is(nullValue())); } @Test public void builder_maximal() { FakeItem fakeItem = createUniqueFakeItem(); Expression conditionExpression = Expression.builder() .expression("#key = :value OR #key1 = :value1") .putExpressionName("#key", "attribute") .putExpressionName("#key1", "attribute3") .putExpressionValue(":value", stringValue("wrong")) .putExpressionValue(":value1", stringValue("three")) .build(); ReturnValue returnValues = ReturnValue.ALL_OLD; ReturnConsumedCapacity returnConsumedCapacity = ReturnConsumedCapacity.INDEXES; ReturnItemCollectionMetrics returnItemCollectionMetrics = ReturnItemCollectionMetrics.SIZE; PutItemEnhancedRequest<FakeItem> builtObject = PutItemEnhancedRequest.builder(FakeItem.class) .item(fakeItem) .conditionExpression(conditionExpression) .returnValues(returnValues) .returnConsumedCapacity(returnConsumedCapacity) .returnItemCollectionMetrics(returnItemCollectionMetrics) .build(); assertThat(builtObject.item(), is(fakeItem)); assertThat(builtObject.conditionExpression(), is(conditionExpression)); assertThat(builtObject.returnValues(), is(returnValues)); assertThat(builtObject.returnValuesAsString(), is(returnValues.toString())); assertThat(builtObject.returnConsumedCapacity(), is(returnConsumedCapacity)); assertThat(builtObject.returnConsumedCapacityAsString(), is(returnConsumedCapacity.toString())); assertThat(builtObject.returnItemCollectionMetrics(), is(returnItemCollectionMetrics)); assertThat(builtObject.returnItemCollectionMetricsAsString(), is(returnItemCollectionMetrics.toString())); } @Test public void toBuilder() { FakeItem fakeItem = createUniqueFakeItem(); Expression conditionExpression = Expression.builder() .expression("#key = :value OR #key1 = :value1") .putExpressionName("#key", "attribute") .putExpressionName("#key1", "attribute3") .putExpressionValue(":value", stringValue("wrong")) .putExpressionValue(":value1", stringValue("three")) .build(); ReturnValue returnValues = ReturnValue.ALL_OLD; ReturnConsumedCapacity returnConsumedCapacity = ReturnConsumedCapacity.INDEXES; ReturnItemCollectionMetrics returnItemCollectionMetrics = ReturnItemCollectionMetrics.SIZE; PutItemEnhancedRequest<FakeItem> builtObject = PutItemEnhancedRequest.builder(FakeItem.class) .item(fakeItem) .conditionExpression(conditionExpression) .returnValues(returnValues) .returnConsumedCapacity(returnConsumedCapacity) .returnItemCollectionMetrics(returnItemCollectionMetrics) .build(); PutItemEnhancedRequest<FakeItem> copiedObject = builtObject.toBuilder().build(); assertThat(copiedObject, is(builtObject)); } @Test public void equals_itemNotEqual() { FakeItem item1 = createUniqueFakeItem(); FakeItem item2 = createUniqueFakeItem(); PutItemEnhancedRequest<FakeItem> builtObject1 = PutItemEnhancedRequest.builder(FakeItem.class) .item(item1) .build(); PutItemEnhancedRequest<FakeItem> builtObject2 = PutItemEnhancedRequest.builder(FakeItem.class) .item(item2) .build(); assertThat(builtObject1, not(equalTo(builtObject2))); } @Test public void equals_conditionExpressionNotEqual() { Expression conditionExpression1 = Expression.builder() .expression("#key = :value OR #key1 = :value1") .putExpressionName("#key", "attribute") .putExpressionName("#key1", "attribute3") .putExpressionValue(":value", stringValue("wrong")) .putExpressionValue(":value1", stringValue("three")) .build(); Expression conditionExpression2 = Expression.builder() .expression("#key = :value AND #key1 = :value1") .putExpressionName("#key", "attribute") .putExpressionName("#key1", "attribute3") .putExpressionValue(":value", stringValue("wrong")) .putExpressionValue(":value1", stringValue("three")) .build(); PutItemEnhancedRequest<FakeItem> builtObject1 = PutItemEnhancedRequest.builder(FakeItem.class) .conditionExpression(conditionExpression1) .build(); PutItemEnhancedRequest<FakeItem> builtObject2 = PutItemEnhancedRequest.builder(FakeItem.class) .conditionExpression(conditionExpression2) .build(); assertThat(builtObject1, not(equalTo(builtObject2))); } @Test public void equals_returnValuesNotEqual() { PutItemEnhancedRequest<FakeItem> builtObject1 = PutItemEnhancedRequest.builder(FakeItem.class) .returnValues("return1") .build(); PutItemEnhancedRequest<FakeItem> builtObject2 = PutItemEnhancedRequest.builder(FakeItem.class) .returnValues("return2") .build(); assertThat(builtObject1, not(equalTo(builtObject2))); } @Test public void equals_returnConsumedCapacityNotEqual() { PutItemEnhancedRequest<FakeItem> builtObject1 = PutItemEnhancedRequest.builder(FakeItem.class) .returnConsumedCapacity("return1") .build(); PutItemEnhancedRequest<FakeItem> builtObject2 = PutItemEnhancedRequest.builder(FakeItem.class) .returnConsumedCapacity("return2") .build(); assertThat(builtObject1, not(equalTo(builtObject2))); } @Test public void equals_returnItemCollectionMetricsNotEqual() { PutItemEnhancedRequest<FakeItem> builtObject1 = PutItemEnhancedRequest.builder(FakeItem.class) .returnItemCollectionMetrics("return1") .build(); PutItemEnhancedRequest<FakeItem> builtObject2 = PutItemEnhancedRequest.builder(FakeItem.class) .returnItemCollectionMetrics("return2") .build(); assertThat(builtObject1, not(equalTo(builtObject2))); } @Test public void hashCode_minimal() { PutItemEnhancedRequest<FakeItem> emptyRequest = PutItemEnhancedRequest.builder(FakeItem.class).build(); assertThat(emptyRequest.hashCode(), equalTo(0)); } @Test public void hashCode_includesItem() { PutItemEnhancedRequest<FakeItem> emptyRequest = PutItemEnhancedRequest.builder(FakeItem.class).build(); PutItemEnhancedRequest<FakeItem> containsItem = PutItemEnhancedRequest.builder(FakeItem.class) .item(createUniqueFakeItem()) .build(); assertThat(containsItem.hashCode(), not(equalTo(emptyRequest.hashCode()))); } @Test public void hashCode_includesConditionExpression() { PutItemEnhancedRequest<FakeItem> emptyRequest = PutItemEnhancedRequest.builder(FakeItem.class).build(); Expression conditionExpression = Expression.builder() .expression("#key = :value OR #key1 = :value1") .putExpressionName("#key", "attribute") .putExpressionName("#key1", "attribute3") .putExpressionValue(":value", stringValue("wrong")) .putExpressionValue(":value1", stringValue("three")) .build(); PutItemEnhancedRequest<FakeItem> containsExpression = PutItemEnhancedRequest.builder(FakeItem.class) .conditionExpression(conditionExpression) .build(); assertThat(containsExpression.hashCode(), not(equalTo(emptyRequest.hashCode()))); } @Test public void hashCode_includesReturnValues() { PutItemEnhancedRequest<FakeItem> emptyRequest = PutItemEnhancedRequest.builder(FakeItem.class).build(); PutItemEnhancedRequest<FakeItem> containsReturnValues = PutItemEnhancedRequest.builder(FakeItem.class) .returnValues("return") .build(); assertThat(containsReturnValues.hashCode(), not(equalTo(emptyRequest.hashCode()))); } @Test public void hashCode_includesReturnConsumedCapacity() { PutItemEnhancedRequest<FakeItem> emptyRequest = PutItemEnhancedRequest.builder(FakeItem.class).build(); PutItemEnhancedRequest<FakeItem> containsReturnConsumedCapacity = PutItemEnhancedRequest.builder(FakeItem.class) .returnConsumedCapacity("return") .build(); assertThat(containsReturnConsumedCapacity.hashCode(), not(equalTo(emptyRequest.hashCode()))); } @Test public void hashCode_includesReturnItemCollectionMetrics() { PutItemEnhancedRequest<FakeItem> emptyRequest = PutItemEnhancedRequest.builder(FakeItem.class).build(); PutItemEnhancedRequest<FakeItem> cotnainsReturnItemCollectionMetrics = PutItemEnhancedRequest.builder(FakeItem.class) .returnItemCollectionMetrics("return") .build(); assertThat(cotnainsReturnItemCollectionMetrics.hashCode(), not(equalTo(emptyRequest.hashCode()))); } @Test public void builder_returnValueEnumSetter_paramNull_NoNpe() { PutItemEnhancedRequest.builder(FakeItem.class).returnValues((ReturnValue) null).build(); } @Test public void returnValues_newValue_returnsUnknownToSdkVersion() { String newReturnValue = UUID.randomUUID().toString(); PutItemEnhancedRequest<FakeItem> builtObject = PutItemEnhancedRequest.builder(FakeItem.class) .returnValues(newReturnValue) .build(); assertThat(builtObject.returnValues(), equalTo(ReturnValue.UNKNOWN_TO_SDK_VERSION)); } @Test public void returnValues_newValue_stringGetter_returnsValue() { String newReturnValue = UUID.randomUUID().toString(); PutItemEnhancedRequest<FakeItem> builtObject = PutItemEnhancedRequest.builder(FakeItem.class) .returnValues(newReturnValue) .build(); assertThat(builtObject.returnValuesAsString(), equalTo(newReturnValue)); } @Test public void builder_returnConsumedCapacityEnumSetter_paramNull_NoNpe() { PutItemEnhancedRequest.builder(FakeItem.class).returnConsumedCapacity((ReturnConsumedCapacity) null).build(); } @Test public void returnConsumedCapacity_newValue_returnsUnknownToSdkVersion() { String newReturnCapacity = UUID.randomUUID().toString(); PutItemEnhancedRequest<FakeItem> builtObject = PutItemEnhancedRequest.builder(FakeItem.class) .returnConsumedCapacity(newReturnCapacity) .build(); assertThat(builtObject.returnConsumedCapacity(), equalTo(ReturnConsumedCapacity.UNKNOWN_TO_SDK_VERSION)); } @Test public void returnConsumedCapacity_newValue_stringGetter_returnsValue() { String newReturnCapacity = UUID.randomUUID().toString(); PutItemEnhancedRequest<FakeItem> builtObject = PutItemEnhancedRequest.builder(FakeItem.class) .returnConsumedCapacity(newReturnCapacity) .build(); assertThat(builtObject.returnConsumedCapacityAsString(), equalTo(newReturnCapacity)); } @Test public void builder_returnItemCollectionMetricsEnumSetter_paramNull_NoNpe() { PutItemEnhancedRequest.builder(FakeItem.class).returnItemCollectionMetrics((ReturnItemCollectionMetrics) null).build(); } @Test public void returnItemCollectionMetrics_newValue_returnsUnknownToSdkVersion() { String newReturnItemCollectionMetrics = UUID.randomUUID().toString(); PutItemEnhancedRequest<FakeItem> builtObject = PutItemEnhancedRequest.builder(FakeItem.class) .returnItemCollectionMetrics(newReturnItemCollectionMetrics) .build(); assertThat(builtObject.returnItemCollectionMetrics(), equalTo(ReturnItemCollectionMetrics.UNKNOWN_TO_SDK_VERSION)); } @Test public void returnItemCollectionMetrics_newValue_stringGetter_returnsValue() { String newReturnItemCollectionMetrics = UUID.randomUUID().toString(); PutItemEnhancedRequest<FakeItem> builtObject = PutItemEnhancedRequest.builder(FakeItem.class) .returnItemCollectionMetrics(newReturnItemCollectionMetrics) .build(); assertThat(builtObject.returnItemCollectionMetricsAsString(), equalTo(newReturnItemCollectionMetrics)); } }
4,326
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/model/ReadBatchTest.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.model; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItem.createUniqueFakeItem; import java.util.Collections; import java.util.Map; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItem; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; @RunWith(MockitoJUnitRunner.class) public class ReadBatchTest { private static final String TABLE_NAME = "table-name"; @Mock private DynamoDbClient mockDynamoDbClient; private DynamoDbEnhancedClient enhancedClient; private DynamoDbTable<FakeItem> fakeItemMappedTable; @Before public void setupMappedTables() { enhancedClient = DynamoDbEnhancedClient.builder().dynamoDbClient(mockDynamoDbClient).build(); fakeItemMappedTable = enhancedClient.table(TABLE_NAME, FakeItem.getTableSchema()); } @Test public void builder_minimal() { ReadBatch builtObject = ReadBatch.builder(FakeItem.class).build(); assertThat(builtObject.tableName(), is(nullValue())); assertThat(builtObject.keysAndAttributes(), is(nullValue())); } @Test public void builder_maximal_consumer_style() { FakeItem fakeItem = createUniqueFakeItem(); ReadBatch builtObject = ReadBatch.builder(FakeItem.class) .mappedTableResource(fakeItemMappedTable) .addGetItem(r -> r.key(k -> k.partitionValue(fakeItem.getId()))) .build(); Map<String, AttributeValue> fakeItemMap = FakeItem.getTableSchema().itemToMap(fakeItem, FakeItem.getTableMetadata().primaryKeys()); assertThat(builtObject.tableName(), is(TABLE_NAME)); assertThat(builtObject.keysAndAttributes().keys(), containsInAnyOrder(Collections.singletonList(fakeItemMap).toArray())); } @Test public void builder_maximal_builder_style() { FakeItem fakeItem = createUniqueFakeItem(); GetItemEnhancedRequest getItem = GetItemEnhancedRequest.builder() .key(k -> k.partitionValue(fakeItem.getId())) .build(); ReadBatch builtObject = ReadBatch.builder(FakeItem.class) .mappedTableResource(fakeItemMappedTable) .addGetItem(getItem) .build(); Map<String, AttributeValue> fakeItemMap = FakeItem.getTableSchema().itemToMap(fakeItem, FakeItem.getTableMetadata().primaryKeys()); assertThat(builtObject.tableName(), is(TABLE_NAME)); assertThat(builtObject.keysAndAttributes().keys(), containsInAnyOrder(Collections.singletonList(fakeItemMap).toArray())); } @Test public void builder_key_from_item_missing_mapped_table_resource_error_message() { FakeItem fakeItem = createUniqueFakeItem(); ReadBatch.Builder<FakeItem> builder = ReadBatch.builder(FakeItem.class); assertThatThrownBy(() -> builder.addGetItem(fakeItem)) .isInstanceOf(NullPointerException.class) .hasMessage("A mappedTableResource is required to derive a key from the given keyItem"); } @Test public void builder_missing_mapped_table_resource_error_message() { ReadBatch.Builder<FakeItem> builder = ReadBatch.builder(FakeItem.class); assertThatThrownBy(() -> builder.addGetItem(GetItemEnhancedRequest.builder().build()).build()) .isInstanceOf(NullPointerException.class) .hasMessage("A mappedTableResource (table) is required when generating the read requests for ReadBatch"); } }
4,327
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/model/GetItemEnhancedRequestTest.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.model; 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 java.util.UUID; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.enhanced.dynamodb.Key; import software.amazon.awssdk.services.dynamodb.model.ReturnConsumedCapacity; @RunWith(MockitoJUnitRunner.class) public class GetItemEnhancedRequestTest { @Test public void builder_minimal() { GetItemEnhancedRequest builtObject = GetItemEnhancedRequest.builder().build(); assertThat(builtObject.key(), is(nullValue())); assertThat(builtObject.consistentRead(), is(nullValue())); assertThat(builtObject.returnConsumedCapacityAsString(), is(nullValue())); assertThat(builtObject.returnConsumedCapacity(), is(nullValue())); } @Test public void builder_maximal() { Key key = Key.builder().partitionValue("key").build(); GetItemEnhancedRequest builtObject = GetItemEnhancedRequest.builder() .key(key) .consistentRead(true) .returnConsumedCapacity(ReturnConsumedCapacity.TOTAL) .build(); assertThat(builtObject.key(), is(key)); assertThat(builtObject.consistentRead(), is(true)); assertThat(builtObject.returnConsumedCapacityAsString(), equalTo(ReturnConsumedCapacity.TOTAL.toString())); assertThat(builtObject.returnConsumedCapacity(), equalTo(ReturnConsumedCapacity.TOTAL)); } @Test public void test_equalsAndHashCode_when_returnConsumedCapacityIsDifferent() { Key key = Key.builder().partitionValue("key").build(); GetItemEnhancedRequest builtObject1 = GetItemEnhancedRequest.builder() .key(key) .returnConsumedCapacity(ReturnConsumedCapacity.TOTAL) .build(); GetItemEnhancedRequest builtObject2 = GetItemEnhancedRequest.builder() .key(key) .returnConsumedCapacity(ReturnConsumedCapacity.INDEXES) .build(); assertThat(builtObject1, not(equalTo(builtObject2))); assertThat(builtObject1.hashCode(), not(equalTo(builtObject2.hashCode()))); } @Test public void test_equalsAndHashCode_when_keyIsDifferent() { GetItemEnhancedRequest builtObject1 = GetItemEnhancedRequest.builder() .key(k -> k.partitionValue("key1")) .returnConsumedCapacity(ReturnConsumedCapacity.TOTAL) .build(); GetItemEnhancedRequest builtObject2 = GetItemEnhancedRequest.builder() .key(k -> k.partitionValue("key2")) .returnConsumedCapacity(ReturnConsumedCapacity.TOTAL) .build(); assertThat(builtObject1, not(equalTo(builtObject2))); assertThat(builtObject1.hashCode(), not(equalTo(builtObject2.hashCode()))); } @Test public void test_equalsAndHashCode_when_allValuesAreSame() { Key key = Key.builder().partitionValue("key").build(); GetItemEnhancedRequest builtObject1 = GetItemEnhancedRequest.builder() .key(key) .returnConsumedCapacity(ReturnConsumedCapacity.INDEXES) .consistentRead(true) .build(); GetItemEnhancedRequest builtObject2 = GetItemEnhancedRequest.builder() .key(key) .returnConsumedCapacity(ReturnConsumedCapacity.INDEXES) .consistentRead(true) .build(); assertThat(builtObject1, equalTo(builtObject2)); assertThat(builtObject1.hashCode(), equalTo(builtObject2.hashCode())); } @Test public void test_hashCode_includes_returnConsumedCapacity() { GetItemEnhancedRequest emptyRequest = GetItemEnhancedRequest.builder().build(); GetItemEnhancedRequest requestWithCC1 = GetItemEnhancedRequest.builder() .returnConsumedCapacity(ReturnConsumedCapacity.INDEXES) .build(); GetItemEnhancedRequest requestWithCC2 = GetItemEnhancedRequest.builder() .returnConsumedCapacity(ReturnConsumedCapacity.TOTAL) .build(); // Assert hashCode is different when returnConsumedCapacity is non-null, and all other fields are same assertThat(emptyRequest.hashCode(), not(equalTo(requestWithCC1.hashCode()))); // Assert hashCode is different when returnConsumedCapacity is different, and all other fields are same assertThat(requestWithCC1.hashCode(), not(equalTo(requestWithCC2.hashCode()))); } @Test public void test_returnConsumedCapacity_unknownToSdkVersion() { String newValue = UUID.randomUUID().toString(); GetItemEnhancedRequest request = GetItemEnhancedRequest.builder().returnConsumedCapacity(newValue).build(); // Assert that string getter returns the same value assertThat(request.returnConsumedCapacityAsString(), equalTo(newValue)); // Assert that new value resolves to correct enum value assertThat(request.returnConsumedCapacity(), equalTo(ReturnConsumedCapacity.UNKNOWN_TO_SDK_VERSION)); } @Test public void toBuilder() { Key key = Key.builder().partitionValue("key").build(); GetItemEnhancedRequest builtObject = GetItemEnhancedRequest.builder() .key(key) .returnConsumedCapacity(ReturnConsumedCapacity.TOTAL) .build(); GetItemEnhancedRequest copiedObject = builtObject.toBuilder().build(); assertThat(copiedObject, is(builtObject)); } }
4,328
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/model/TransactUpdateItemEnhancedRequestTest.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.model; 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 software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItem.createUniqueFakeItem; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.stringValue; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.enhanced.dynamodb.Expression; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItem; import software.amazon.awssdk.services.dynamodb.model.ReturnValuesOnConditionCheckFailure; @RunWith(MockitoJUnitRunner.class) public class TransactUpdateItemEnhancedRequestTest { @Test public void builder_minimal() { TransactUpdateItemEnhancedRequest<FakeItem> builtObject = TransactUpdateItemEnhancedRequest.builder(FakeItem.class).build(); assertThat(builtObject.item(), is(nullValue())); assertThat(builtObject.ignoreNulls(), is(nullValue())); assertThat(builtObject.conditionExpression(), is(nullValue())); assertThat(builtObject.returnValuesOnConditionCheckFailure(), is(nullValue())); } @Test public void builder_maximal() { FakeItem fakeItem = createUniqueFakeItem(); Expression conditionExpression = Expression.builder() .expression("#key = :value OR #key1 = :value1") .putExpressionName("#key", "attribute") .putExpressionName("#key1", "attribute3") .putExpressionValue(":value", stringValue("wrong")) .putExpressionValue(":value1", stringValue("three")) .build(); ReturnValuesOnConditionCheckFailure returnValues = ReturnValuesOnConditionCheckFailure.ALL_OLD; TransactUpdateItemEnhancedRequest<FakeItem> builtObject = TransactUpdateItemEnhancedRequest.builder(FakeItem.class) .item(fakeItem) .ignoreNulls(true) .conditionExpression(conditionExpression) .returnValuesOnConditionCheckFailure(returnValues) .build(); assertThat(builtObject.item(), is(fakeItem)); assertThat(builtObject.ignoreNulls(), is(true)); assertThat(builtObject.conditionExpression(), is(conditionExpression)); assertThat(builtObject.returnValuesOnConditionCheckFailure(), is(returnValues)); } @Test public void equals_maximal() { FakeItem fakeItem = createUniqueFakeItem(); Expression conditionExpression = Expression.builder() .expression("#key = :value OR #key1 = :value1") .putExpressionName("#key", "attribute") .putExpressionName("#key1", "attribute3") .putExpressionValue(":value", stringValue("wrong")) .putExpressionValue(":value1", stringValue("three")) .build(); ReturnValuesOnConditionCheckFailure returnValues = ReturnValuesOnConditionCheckFailure.ALL_OLD; TransactUpdateItemEnhancedRequest<FakeItem> builtObject = TransactUpdateItemEnhancedRequest.builder(FakeItem.class) .item(fakeItem) .ignoreNulls(true) .conditionExpression(conditionExpression) .returnValuesOnConditionCheckFailure(returnValues) .build(); TransactUpdateItemEnhancedRequest<FakeItem> copiedObject = builtObject.toBuilder().build(); assertThat(builtObject, equalTo(copiedObject)); } @Test public void equals_minimal() { TransactUpdateItemEnhancedRequest<FakeItem> builtObject1 = TransactUpdateItemEnhancedRequest.builder(FakeItem.class).build(); TransactUpdateItemEnhancedRequest<FakeItem> builtObject2 = TransactUpdateItemEnhancedRequest.builder(FakeItem.class).build(); assertThat(builtObject1, equalTo(builtObject2)); } @Test public void equals_differentType() { TransactUpdateItemEnhancedRequest<FakeItem> builtObject = TransactUpdateItemEnhancedRequest.builder(FakeItem.class).build(); UpdateItemEnhancedRequest<FakeItem> differentType = UpdateItemEnhancedRequest.builder(FakeItem.class).build(); assertThat(builtObject, not(equalTo(differentType))); } @Test public void equals_self() { TransactUpdateItemEnhancedRequest<FakeItem> builtObject = TransactUpdateItemEnhancedRequest.builder(FakeItem.class).build(); assertThat(builtObject, equalTo(builtObject)); } @Test public void equals_itemNotEqual() { FakeItem fakeItem1 = createUniqueFakeItem(); FakeItem fakeItem2 = createUniqueFakeItem(); TransactUpdateItemEnhancedRequest<FakeItem> builtObject1 = TransactUpdateItemEnhancedRequest.builder(FakeItem.class).item(fakeItem1).build(); TransactUpdateItemEnhancedRequest<FakeItem> builtObject2 = TransactUpdateItemEnhancedRequest.builder(FakeItem.class).item(fakeItem2).build(); assertThat(builtObject1, not(equalTo(builtObject2))); } @Test public void equals_conditionExpressionNotEqual() { Expression conditionExpression1 = Expression.builder() .expression("#key = :value OR #key1 = :value1") .putExpressionName("#key", "attribute") .putExpressionName("#key1", "attribute3") .putExpressionValue(":value", stringValue("wrong")) .putExpressionValue(":value1", stringValue("three")) .build(); Expression conditionExpression2 = Expression.builder() .expression("#key = :value AND #key1 = :value1") .putExpressionName("#key", "attribute") .putExpressionName("#key1", "attribute3") .putExpressionValue(":value", stringValue("wrong")) .putExpressionValue(":value1", stringValue("three")) .build(); TransactUpdateItemEnhancedRequest<FakeItem> builtObject1 = TransactUpdateItemEnhancedRequest.builder(FakeItem.class).conditionExpression(conditionExpression1).build(); TransactUpdateItemEnhancedRequest<FakeItem> builtObject2 = TransactUpdateItemEnhancedRequest.builder(FakeItem.class).conditionExpression(conditionExpression2).build(); assertThat(builtObject1, not(equalTo(builtObject2))); } @Test public void equals_ignoreNullsNotEqual() { TransactUpdateItemEnhancedRequest<FakeItem> builtObject1 = TransactUpdateItemEnhancedRequest.builder(FakeItem.class).ignoreNulls(true).build(); TransactUpdateItemEnhancedRequest<FakeItem> builtObject2 = TransactUpdateItemEnhancedRequest.builder(FakeItem.class).ignoreNulls(false).build(); assertThat(builtObject1, not(equalTo(builtObject2))); } @Test public void equals_returnValuesNotEqual() { ReturnValuesOnConditionCheckFailure returnValues1 = ReturnValuesOnConditionCheckFailure.NONE; ReturnValuesOnConditionCheckFailure returnValues2 = ReturnValuesOnConditionCheckFailure.ALL_OLD; TransactUpdateItemEnhancedRequest<FakeItem> builtObject1 = TransactUpdateItemEnhancedRequest.builder(FakeItem.class) .returnValuesOnConditionCheckFailure(returnValues1) .build(); TransactUpdateItemEnhancedRequest<FakeItem> builtObject2 = TransactUpdateItemEnhancedRequest.builder(FakeItem.class) .returnValuesOnConditionCheckFailure(returnValues2) .build(); assertThat(builtObject1, not(equalTo(builtObject2))); } @Test public void hashCode_maximal() { FakeItem fakeItem = createUniqueFakeItem(); Expression conditionExpression = Expression.builder() .expression("#key = :value OR #key1 = :value1") .putExpressionName("#key", "attribute") .putExpressionName("#key1", "attribute3") .putExpressionValue(":value", stringValue("wrong")) .putExpressionValue(":value1", stringValue("three")) .build(); ReturnValuesOnConditionCheckFailure returnValues = ReturnValuesOnConditionCheckFailure.ALL_OLD; TransactUpdateItemEnhancedRequest<FakeItem> builtObject = TransactUpdateItemEnhancedRequest.builder(FakeItem.class) .item(fakeItem) .ignoreNulls(true) .conditionExpression(conditionExpression) .returnValuesOnConditionCheckFailure(returnValues) .build(); TransactUpdateItemEnhancedRequest<FakeItem> copiedObject = builtObject.toBuilder().build(); assertThat(builtObject.hashCode(), equalTo(copiedObject.hashCode())); } @Test public void hashCode_minimal() { TransactUpdateItemEnhancedRequest<FakeItem> builtObject1 = TransactUpdateItemEnhancedRequest.builder(FakeItem.class).build(); TransactUpdateItemEnhancedRequest<FakeItem> builtObject2 = TransactUpdateItemEnhancedRequest.builder(FakeItem.class).build(); assertThat(builtObject1.hashCode(), equalTo(builtObject2.hashCode())); } @Test public void toBuilder() { FakeItem fakeItem = createUniqueFakeItem(); Expression conditionExpression = Expression.builder() .expression("#key = :value OR #key1 = :value1") .putExpressionName("#key", "attribute") .putExpressionName("#key1", "attribute3") .putExpressionValue(":value", stringValue("wrong")) .putExpressionValue(":value1", stringValue("three")) .build(); ReturnValuesOnConditionCheckFailure returnValues = ReturnValuesOnConditionCheckFailure.ALL_OLD; TransactUpdateItemEnhancedRequest<FakeItem> builtObject = TransactUpdateItemEnhancedRequest.builder(FakeItem.class) .item(fakeItem) .ignoreNulls(true) .conditionExpression(conditionExpression) .returnValuesOnConditionCheckFailure(returnValues) .build(); TransactUpdateItemEnhancedRequest<FakeItem> copiedObject = builtObject.toBuilder().build(); assertThat(copiedObject, is(builtObject)); } @Test public void builder_returnValuesOnConditionCheckFailureSetterNull_noNpe() { TransactUpdateItemEnhancedRequest<FakeItem> builtObject = TransactUpdateItemEnhancedRequest.builder(FakeItem.class) .item(createUniqueFakeItem()) .returnValuesOnConditionCheckFailure((ReturnValuesOnConditionCheckFailure) null) .build(); assertThat(builtObject.returnValuesOnConditionCheckFailure(), is(nullValue())); assertThat(builtObject.returnValuesOnConditionCheckFailureAsString(), is(nullValue())); } @Test public void builder_returnValuesOnConditionCheckFailureNewValue_enumGetterReturnsUnknownValue() { String returnValues = "new-value"; TransactUpdateItemEnhancedRequest<FakeItem> builtObject = TransactUpdateItemEnhancedRequest.builder(FakeItem.class) .returnValuesOnConditionCheckFailure(returnValues) .build(); assertThat(builtObject.returnValuesOnConditionCheckFailure(), equalTo(ReturnValuesOnConditionCheckFailure.UNKNOWN_TO_SDK_VERSION)); } @Test public void builder_returnValuesOnConditionCheckFailureNewValue_stringGetter() { String returnValues = "new-value"; TransactUpdateItemEnhancedRequest<FakeItem> builtObject = TransactUpdateItemEnhancedRequest.builder(FakeItem.class) .returnValuesOnConditionCheckFailure(returnValues) .build(); assertThat(builtObject.returnValuesOnConditionCheckFailureAsString(), is(returnValues)); } }
4,329
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/model/BatchGetItemEnhancedRequestTest.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.model; 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 java.util.Collections; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItem; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.ConsumedCapacity; import software.amazon.awssdk.services.dynamodb.model.ReturnConsumedCapacity; @RunWith(MockitoJUnitRunner.class) public class BatchGetItemEnhancedRequestTest { private static final String TABLE_NAME = "table-name"; @Mock private DynamoDbClient mockDynamoDbClient; private DynamoDbEnhancedClient enhancedClient; private DynamoDbTable<FakeItem> fakeItemMappedTable; @Before public void setupMappedTables() { enhancedClient = DynamoDbEnhancedClient.builder().dynamoDbClient(mockDynamoDbClient).build(); fakeItemMappedTable = enhancedClient.table(TABLE_NAME, FakeItem.getTableSchema()); } @Test public void builder_minimal() { BatchGetItemEnhancedRequest builtObject = BatchGetItemEnhancedRequest.builder().build(); assertThat(builtObject.readBatches(), is(nullValue())); assertThat(builtObject.returnConsumedCapacity(), is(nullValue())); assertThat(builtObject.returnConsumedCapacityAsString(), is(nullValue())); } @Test public void builder_maximal() { ReadBatch readBatch = ReadBatch.builder(FakeItem.class) .mappedTableResource(fakeItemMappedTable) .addGetItem(r -> r.key(k -> k.partitionValue("key"))) .build(); BatchGetItemEnhancedRequest builtObject = BatchGetItemEnhancedRequest.builder() .readBatches(readBatch) .returnConsumedCapacity(ReturnConsumedCapacity.TOTAL) .build(); assertThat(builtObject.readBatches(), is(Collections.singletonList(readBatch))); assertThat(builtObject.returnConsumedCapacity(), equalTo(ReturnConsumedCapacity.TOTAL)); assertThat(builtObject.returnConsumedCapacityAsString(), equalTo(ReturnConsumedCapacity.TOTAL.toString())); } @Test public void builder_add_single() { ReadBatch readBatch = ReadBatch.builder(FakeItem.class) .mappedTableResource(fakeItemMappedTable) .addGetItem(r -> r.key(k -> k.partitionValue("key"))) .build(); BatchGetItemEnhancedRequest builtObject = BatchGetItemEnhancedRequest.builder() .addReadBatch(readBatch) .build(); assertThat(builtObject.readBatches(), is(Collections.singletonList(readBatch))); } @Test public void toBuilder() { BatchGetItemEnhancedRequest builtObject = BatchGetItemEnhancedRequest.builder().build(); BatchGetItemEnhancedRequest copiedObject = builtObject.toBuilder().build(); assertThat(copiedObject, is(builtObject)); assertThat(copiedObject.hashCode(), equalTo(builtObject.hashCode())); } @Test public void toBuilder_maximal() { ReadBatch readBatch = ReadBatch.builder(FakeItem.class) .mappedTableResource(fakeItemMappedTable) .addGetItem(r -> r.key(k -> k.partitionValue("key"))) .build(); BatchGetItemEnhancedRequest builtObject = BatchGetItemEnhancedRequest.builder() .readBatches(readBatch) .returnConsumedCapacity(ReturnConsumedCapacity.TOTAL) .build(); BatchGetItemEnhancedRequest copiedObject = builtObject.toBuilder().build(); assertThat(copiedObject, is(builtObject)); assertThat(copiedObject.hashCode(), equalTo(builtObject.hashCode())); } @Test public void hashCode_includes_readBatches() { BatchGetItemEnhancedRequest request1 = BatchGetItemEnhancedRequest.builder().build(); ReadBatch readBatch = ReadBatch.builder(FakeItem.class) .mappedTableResource(fakeItemMappedTable) .addGetItem(r -> r.key(k -> k.partitionValue("key"))) .build(); BatchGetItemEnhancedRequest request2 = BatchGetItemEnhancedRequest.builder() .readBatches(readBatch) .build(); assertThat(request1, not(equalTo(request2))); assertThat(request1.hashCode(), not(equalTo(request2))); } @Test public void hashCode_includes_consumedCapacity() { BatchGetItemEnhancedRequest request1 = BatchGetItemEnhancedRequest.builder().build(); BatchGetItemEnhancedRequest request2 = BatchGetItemEnhancedRequest.builder() .returnConsumedCapacity(ReturnConsumedCapacity.INDEXES) .build(); assertThat(request1, not(equalTo(request2))); assertThat(request1.hashCode(), not(equalTo(request2))); } @Test public void returnConsumedCapacity_unknownToSdkVersion() { BatchGetItemEnhancedRequest builtObject = BatchGetItemEnhancedRequest.builder() .returnConsumedCapacity("abcdefg") .build(); assertThat(builtObject.returnConsumedCapacity(), is(ReturnConsumedCapacity.UNKNOWN_TO_SDK_VERSION)); assertThat(builtObject.returnConsumedCapacityAsString(), equalTo("abcdefg")); } }
4,330
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/model/GetItemEnhancedResponseTest.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.model; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItem.createUniqueFakeItem; import org.assertj.core.api.Assertions; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItem; import software.amazon.awssdk.services.dynamodb.model.ConsumedCapacity; @RunWith(MockitoJUnitRunner.class) public class GetItemEnhancedResponseTest { @Test public void builder_minimal() { GetItemEnhancedResponse<FakeItem> response = GetItemEnhancedResponse.<FakeItem>builder().build(); assertThat(response.attributes(), is(nullValue())); assertThat(response.consumedCapacity(), is(nullValue())); } @Test public void builder_maximal() { FakeItem item = createUniqueFakeItem(); ConsumedCapacity consumedCapacity = ConsumedCapacity.builder() .capacityUnits(10.0) .build(); GetItemEnhancedResponse<FakeItem> response = GetItemEnhancedResponse.<FakeItem>builder() .attributes(item) .consumedCapacity(consumedCapacity) .build(); assertThat(response.attributes(), is(item)); assertThat(response.consumedCapacity(), is(consumedCapacity)); } @Test public void equals_self() { GetItemEnhancedResponse<FakeItem> builtObject1 = GetItemEnhancedResponse.<FakeItem>builder().build(); assertThat(builtObject1, equalTo(builtObject1)); ConsumedCapacity consumedCapacity = ConsumedCapacity.builder() .capacityUnits(10.0) .build(); GetItemEnhancedResponse<FakeItem> builtObject2 = GetItemEnhancedResponse.<FakeItem>builder() .attributes(createUniqueFakeItem()) .consumedCapacity(consumedCapacity) .build(); assertThat(builtObject2, equalTo(builtObject2)); } @Test public void equals_differentType() { GetItemEnhancedResponse<FakeItem> response = GetItemEnhancedResponse.<FakeItem>builder().build(); assertThat(response, not(equalTo(new Object()))); } @Test public void equals_attributesNotEqual() { FakeItem fakeItem1 = createUniqueFakeItem(); FakeItem fakeItem2 = createUniqueFakeItem(); GetItemEnhancedResponse<FakeItem> builtObject1 = GetItemEnhancedResponse.<FakeItem>builder() .attributes(fakeItem1) .build(); GetItemEnhancedResponse<FakeItem> builtObject2 = GetItemEnhancedResponse.<FakeItem>builder() .attributes(fakeItem2) .build(); Assertions.assertThat(builtObject1).isNotEqualTo(builtObject2); } @Test public void hashCode_minimal() { GetItemEnhancedResponse<FakeItem> response = GetItemEnhancedResponse.<FakeItem>builder().build(); assertThat(response.hashCode(), equalTo(0)); } @Test public void hashCode_includesAttributes() { GetItemEnhancedResponse<FakeItem> builtObject1 = GetItemEnhancedResponse.<FakeItem>builder().build(); GetItemEnhancedResponse<FakeItem> builtObject2 = GetItemEnhancedResponse.<FakeItem>builder() .attributes(createUniqueFakeItem()) .build(); assertThat(builtObject1.hashCode(), not(equalTo(builtObject2.hashCode()))); } @Test public void hashCode_includesConsumedCapacity() { GetItemEnhancedResponse<FakeItem> builtObject1 = GetItemEnhancedResponse.<FakeItem>builder().build(); ConsumedCapacity consumedCapacity = ConsumedCapacity.builder().capacityUnits(12.5).build(); GetItemEnhancedResponse<FakeItem> builtObject2 = GetItemEnhancedResponse.<FakeItem>builder() .consumedCapacity(consumedCapacity) .build(); assertThat(builtObject1.hashCode(), not(equalTo(builtObject2.hashCode()))); } }
4,331
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/model/TransactPutItemEnhancedRequestTest.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.model; 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 software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItem.createUniqueFakeItem; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.stringValue; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.enhanced.dynamodb.Expression; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItem; import software.amazon.awssdk.services.dynamodb.model.ReturnValuesOnConditionCheckFailure; @RunWith(MockitoJUnitRunner.class) public class TransactPutItemEnhancedRequestTest { @Test public void builder_minimal() { TransactPutItemEnhancedRequest<FakeItem> builtObject = TransactPutItemEnhancedRequest.builder(FakeItem.class).build(); assertThat(builtObject.item(), is(nullValue())); assertThat(builtObject.conditionExpression(), is(nullValue())); assertThat(builtObject.returnValuesOnConditionCheckFailure(), is(nullValue())); } @Test public void builder_maximal() { FakeItem fakeItem = createUniqueFakeItem(); Expression conditionExpression = Expression.builder() .expression("#key = :value OR #key1 = :value1") .putExpressionName("#key", "attribute") .putExpressionName("#key1", "attribute3") .putExpressionValue(":value", stringValue("wrong")) .putExpressionValue(":value1", stringValue("three")) .build(); ReturnValuesOnConditionCheckFailure returnValues = ReturnValuesOnConditionCheckFailure.ALL_OLD; TransactPutItemEnhancedRequest<FakeItem> builtObject = TransactPutItemEnhancedRequest.builder(FakeItem.class) .item(fakeItem) .conditionExpression(conditionExpression) .returnValuesOnConditionCheckFailure(returnValues) .build(); assertThat(builtObject.item(), is(fakeItem)); assertThat(builtObject.conditionExpression(), is(conditionExpression)); assertThat(builtObject.returnValuesOnConditionCheckFailure(), is(returnValues)); } @Test public void equals_maximal() { FakeItem fakeItem = createUniqueFakeItem(); Expression conditionExpression = Expression.builder() .expression("#key = :value OR #key1 = :value1") .putExpressionName("#key", "attribute") .putExpressionName("#key1", "attribute3") .putExpressionValue(":value", stringValue("wrong")) .putExpressionValue(":value1", stringValue("three")) .build(); ReturnValuesOnConditionCheckFailure returnValues = ReturnValuesOnConditionCheckFailure.ALL_OLD; TransactPutItemEnhancedRequest<FakeItem> builtObject = TransactPutItemEnhancedRequest.builder(FakeItem.class) .item(fakeItem) .conditionExpression(conditionExpression) .returnValuesOnConditionCheckFailure(returnValues) .build(); TransactPutItemEnhancedRequest<FakeItem> copiedObject = builtObject.toBuilder().build(); assertThat(builtObject, equalTo(copiedObject)); } @Test public void equals_minimal() { TransactPutItemEnhancedRequest<FakeItem> builtObject1 = TransactPutItemEnhancedRequest.builder(FakeItem.class).build(); TransactPutItemEnhancedRequest<FakeItem> builtObject2 = TransactPutItemEnhancedRequest.builder(FakeItem.class).build(); assertThat(builtObject1, equalTo(builtObject2)); } @Test public void equals_differentType() { TransactPutItemEnhancedRequest<FakeItem> builtObject = TransactPutItemEnhancedRequest.builder(FakeItem.class).build(); PutItemEnhancedRequest<FakeItem> differentType = PutItemEnhancedRequest.builder(FakeItem.class).build(); assertThat(builtObject, not(equalTo(differentType))); } @Test public void equals_self() { TransactPutItemEnhancedRequest<FakeItem> builtObject = TransactPutItemEnhancedRequest.builder(FakeItem.class).build(); assertThat(builtObject, equalTo(builtObject)); } @Test public void equals_itemNotEqual() { FakeItem fakeItem = createUniqueFakeItem(); FakeItem fakeItem2 = createUniqueFakeItem(); TransactPutItemEnhancedRequest<FakeItem> builtObject1 = TransactPutItemEnhancedRequest.builder(FakeItem.class) .item(fakeItem) .build(); TransactPutItemEnhancedRequest<FakeItem> builtObject2 = TransactPutItemEnhancedRequest.builder(FakeItem.class) .item(fakeItem2) .build(); assertThat(builtObject1, not(equalTo(builtObject2))); } @Test public void equals_conditionExpressNotEqual() { Expression conditionExpression1 = Expression.builder() .expression("#key = :value OR #key1 = :value1") .putExpressionName("#key", "attribute") .putExpressionName("#key1", "attribute3") .putExpressionValue(":value", stringValue("wrong")) .putExpressionValue(":value1", stringValue("three")) .build(); Expression conditionExpression2 = Expression.builder() .expression("#key = :value AND #key1 = :value1") .putExpressionName("#key", "attribute") .putExpressionName("#key1", "attribute3") .putExpressionValue(":value", stringValue("wrong")) .putExpressionValue(":value1", stringValue("three")) .build(); TransactPutItemEnhancedRequest<FakeItem> builtObject1 = TransactPutItemEnhancedRequest.builder(FakeItem.class) .conditionExpression(conditionExpression1) .build(); TransactPutItemEnhancedRequest<FakeItem> builtObject2 = TransactPutItemEnhancedRequest.builder(FakeItem.class) .conditionExpression(conditionExpression2) .build(); assertThat(builtObject1, not(equalTo(builtObject2))); } @Test public void equals_returnValuesOnConditionCheckFailureNotEqual() { ReturnValuesOnConditionCheckFailure returnValues1 = ReturnValuesOnConditionCheckFailure.ALL_OLD; ReturnValuesOnConditionCheckFailure returnValues2 = ReturnValuesOnConditionCheckFailure.NONE; TransactPutItemEnhancedRequest<FakeItem> builtObject1 = TransactPutItemEnhancedRequest.builder(FakeItem.class) .returnValuesOnConditionCheckFailure(returnValues1) .build(); TransactPutItemEnhancedRequest<FakeItem> builtObject2 = TransactPutItemEnhancedRequest.builder(FakeItem.class) .returnValuesOnConditionCheckFailure(returnValues2) .build(); assertThat(builtObject1, not(equalTo(builtObject2))); } @Test public void hashCode_maximal() { FakeItem fakeItem = createUniqueFakeItem(); Expression conditionExpression = Expression.builder() .expression("#key = :value OR #key1 = :value1") .putExpressionName("#key", "attribute") .putExpressionName("#key1", "attribute3") .putExpressionValue(":value", stringValue("wrong")) .putExpressionValue(":value1", stringValue("three")) .build(); ReturnValuesOnConditionCheckFailure returnValues = ReturnValuesOnConditionCheckFailure.ALL_OLD; TransactPutItemEnhancedRequest<FakeItem> builtObject = TransactPutItemEnhancedRequest.builder(FakeItem.class) .item(fakeItem) .conditionExpression(conditionExpression) .returnValuesOnConditionCheckFailure(returnValues) .build(); TransactPutItemEnhancedRequest<FakeItem> copiedObject = builtObject.toBuilder().build(); assertThat(builtObject.hashCode(), equalTo(copiedObject.hashCode())); } @Test public void hashCode_minimal() { TransactPutItemEnhancedRequest<FakeItem> builtObject1 = TransactPutItemEnhancedRequest.builder(FakeItem.class).build(); TransactPutItemEnhancedRequest<FakeItem> builtObject2 = TransactPutItemEnhancedRequest.builder(FakeItem.class).build(); assertThat(builtObject1.hashCode(), equalTo(builtObject2.hashCode())); } @Test public void toBuilder() { FakeItem fakeItem = createUniqueFakeItem(); Expression conditionExpression = Expression.builder() .expression("#key = :value OR #key1 = :value1") .putExpressionName("#key", "attribute") .putExpressionName("#key1", "attribute3") .putExpressionValue(":value", stringValue("wrong")) .putExpressionValue(":value1", stringValue("three")) .build(); ReturnValuesOnConditionCheckFailure returnValues = ReturnValuesOnConditionCheckFailure.ALL_OLD; TransactPutItemEnhancedRequest<FakeItem> builtObject = TransactPutItemEnhancedRequest.builder(FakeItem.class) .item(fakeItem) .conditionExpression(conditionExpression) .returnValuesOnConditionCheckFailure(returnValues) .build(); TransactPutItemEnhancedRequest<FakeItem> copiedObject = builtObject.toBuilder().build(); assertThat(copiedObject, is(builtObject)); } @Test public void builder_returnValuesOnConditionCheckFailureNull_noNpe() { ReturnValuesOnConditionCheckFailure returnValues = null; TransactPutItemEnhancedRequest<FakeItem> builtObject = TransactPutItemEnhancedRequest.builder(FakeItem.class) .returnValuesOnConditionCheckFailure(returnValues) .build(); assertThat(builtObject.returnValuesOnConditionCheckFailure(), is(nullValue())); assertThat(builtObject.returnValuesOnConditionCheckFailureAsString(), is(nullValue())); } @Test public void builder_returnValuesOnConditionCheckFailureNewValue_enumGetterReturnsUnknownValue() { String returnValues = "new-value"; TransactPutItemEnhancedRequest<FakeItem> builtObject = TransactPutItemEnhancedRequest.builder(FakeItem.class) .returnValuesOnConditionCheckFailure(returnValues) .build(); assertThat(builtObject.returnValuesOnConditionCheckFailure(), equalTo(ReturnValuesOnConditionCheckFailure.UNKNOWN_TO_SDK_VERSION)); } @Test public void builder_returnValuesOnConditionCheckFailureNewValue_stringGetter() { String returnValues = "new-value"; TransactPutItemEnhancedRequest<FakeItem> builtObject = TransactPutItemEnhancedRequest.builder(FakeItem.class) .returnValuesOnConditionCheckFailure(returnValues) .build(); assertThat(builtObject.returnValuesOnConditionCheckFailureAsString(), is(returnValues)); } }
4,332
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/model/UpdateItemEnhancedRequestTest.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.model; 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 software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItem.createUniqueFakeItem; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.stringValue; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.enhanced.dynamodb.Expression; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItem; import software.amazon.awssdk.services.dynamodb.model.ReturnConsumedCapacity; import software.amazon.awssdk.services.dynamodb.model.ReturnItemCollectionMetrics; @RunWith(MockitoJUnitRunner.class) public class UpdateItemEnhancedRequestTest { @Test public void builder_minimal() { UpdateItemEnhancedRequest<FakeItem> builtObject = UpdateItemEnhancedRequest.builder(FakeItem.class).build(); assertThat(builtObject.item(), is(nullValue())); assertThat(builtObject.ignoreNulls(), is(nullValue())); assertThat(builtObject.conditionExpression(), is(nullValue())); assertThat(builtObject.returnConsumedCapacity(), is(nullValue())); assertThat(builtObject.returnConsumedCapacityAsString(), is(nullValue())); assertThat(builtObject.returnItemCollectionMetrics(), is(nullValue())); assertThat(builtObject.returnItemCollectionMetricsAsString(), is(nullValue())); } @Test public void builder_maximal() { FakeItem fakeItem = createUniqueFakeItem(); Expression conditionExpression = Expression.builder() .expression("#key = :value OR #key1 = :value1") .putExpressionName("#key", "attribute") .putExpressionName("#key1", "attribute3") .putExpressionValue(":value", stringValue("wrong")) .putExpressionValue(":value1", stringValue("three")) .build(); ReturnConsumedCapacity returnConsumedCapacity = ReturnConsumedCapacity.TOTAL; ReturnItemCollectionMetrics returnItemCollectionMetrics = ReturnItemCollectionMetrics.SIZE; UpdateItemEnhancedRequest<FakeItem> builtObject = UpdateItemEnhancedRequest.builder(FakeItem.class) .item(fakeItem) .ignoreNulls(true) .conditionExpression(conditionExpression) .returnConsumedCapacity(returnConsumedCapacity) .returnItemCollectionMetrics(returnItemCollectionMetrics) .build(); assertThat(builtObject.item(), is(fakeItem)); assertThat(builtObject.ignoreNulls(), is(true)); assertThat(builtObject.conditionExpression(), is(conditionExpression)); assertThat(builtObject.returnConsumedCapacity(), is(returnConsumedCapacity)); assertThat(builtObject.returnConsumedCapacityAsString(), is(returnConsumedCapacity.toString())); assertThat(builtObject.returnItemCollectionMetrics(), is(returnItemCollectionMetrics)); assertThat(builtObject.returnItemCollectionMetricsAsString(), is(returnItemCollectionMetrics.toString())); } @Test public void toBuilder() { FakeItem fakeItem = createUniqueFakeItem(); Expression conditionExpression = Expression.builder() .expression("#key = :value OR #key1 = :value1") .putExpressionName("#key", "attribute") .putExpressionName("#key1", "attribute3") .putExpressionValue(":value", stringValue("wrong")) .putExpressionValue(":value1", stringValue("three")) .build(); ReturnConsumedCapacity returnConsumedCapacity = ReturnConsumedCapacity.TOTAL; ReturnItemCollectionMetrics returnItemCollectionMetrics = ReturnItemCollectionMetrics.SIZE; UpdateItemEnhancedRequest<FakeItem> builtObject = UpdateItemEnhancedRequest.builder(FakeItem.class) .item(fakeItem) .ignoreNulls(true) .conditionExpression(conditionExpression) .returnConsumedCapacity(returnConsumedCapacity) .returnItemCollectionMetrics(returnItemCollectionMetrics) .build(); UpdateItemEnhancedRequest<FakeItem> copiedObject = builtObject.toBuilder().build(); assertThat(copiedObject, is(builtObject)); } @Test public void equals_self() { UpdateItemEnhancedRequest<FakeItem> builtObject = UpdateItemEnhancedRequest.builder(FakeItem.class).build(); assertThat(builtObject, equalTo(builtObject)); } @Test public void equals_differentType() { UpdateItemEnhancedRequest<FakeItem> builtObject = UpdateItemEnhancedRequest.builder(FakeItem.class).build(); assertThat(builtObject, not(equalTo(new Object()))); } @Test public void equals_itemNotEqual() { FakeItem fakeItem1 = createUniqueFakeItem(); FakeItem fakeItem2 = createUniqueFakeItem(); UpdateItemEnhancedRequest<FakeItem> builtObject1 = UpdateItemEnhancedRequest.builder(FakeItem.class) .item(fakeItem1) .build(); UpdateItemEnhancedRequest<FakeItem> builtObject2 = UpdateItemEnhancedRequest.builder(FakeItem.class) .item(fakeItem2) .build(); assertThat(builtObject1, not(equalTo(builtObject2))); } @Test public void equals_ignoreNullsNotEqual() { UpdateItemEnhancedRequest<FakeItem> builtObject1 = UpdateItemEnhancedRequest.builder(FakeItem.class) .ignoreNulls(true) .build(); UpdateItemEnhancedRequest<FakeItem> builtObject2 = UpdateItemEnhancedRequest.builder(FakeItem.class) .ignoreNulls(false) .build(); assertThat(builtObject1, not(equalTo(builtObject2))); } @Test public void equals_conditionExpressionNotEqual() { Expression conditionExpression1 = Expression.builder() .expression("#key = :value OR #key1 = :value1") .putExpressionName("#key", "attribute") .putExpressionName("#key1", "attribute3") .putExpressionValue(":value", stringValue("wrong")) .putExpressionValue(":value1", stringValue("three")) .build(); Expression conditionExpression2 = Expression.builder() .expression("#key = :value AND #key1 = :value1") .putExpressionName("#key", "attribute") .putExpressionName("#key1", "attribute3") .putExpressionValue(":value", stringValue("wrong")) .putExpressionValue(":value1", stringValue("three")) .build(); UpdateItemEnhancedRequest<FakeItem> builtObject1 = UpdateItemEnhancedRequest.builder(FakeItem.class) .conditionExpression(conditionExpression1) .build(); UpdateItemEnhancedRequest<FakeItem> builtObject2 = UpdateItemEnhancedRequest.builder(FakeItem.class) .conditionExpression(conditionExpression2) .build(); assertThat(builtObject1, not(equalTo(builtObject2))); } @Test public void equals_returnConsumedCapacityNotEqual() { UpdateItemEnhancedRequest<FakeItem> builtObject1 = UpdateItemEnhancedRequest.builder(FakeItem.class) .returnConsumedCapacity("return1") .build(); UpdateItemEnhancedRequest<FakeItem> builtObject2 = UpdateItemEnhancedRequest.builder(FakeItem.class) .returnConsumedCapacity("return2") .build(); assertThat(builtObject1, not(equalTo(builtObject2))); } @Test public void equals_returnItemCollectionMetricsNotEqual() { UpdateItemEnhancedRequest<FakeItem> builtObject1 = UpdateItemEnhancedRequest.builder(FakeItem.class) .returnItemCollectionMetrics("return1") .build(); UpdateItemEnhancedRequest<FakeItem> builtObject2 = UpdateItemEnhancedRequest.builder(FakeItem.class) .returnItemCollectionMetrics("return2") .build(); assertThat(builtObject1, not(equalTo(builtObject2))); } @Test public void hashCode_minimal() { UpdateItemEnhancedRequest<FakeItem> emptyRequest = UpdateItemEnhancedRequest.builder(FakeItem.class).build(); assertThat(emptyRequest.hashCode(), equalTo(0)); } @Test public void hashCode_includesItem() { UpdateItemEnhancedRequest<FakeItem> emptyRequest = UpdateItemEnhancedRequest.builder(FakeItem.class).build(); UpdateItemEnhancedRequest<FakeItem> containsItem = UpdateItemEnhancedRequest.builder(FakeItem.class) .item(createUniqueFakeItem()) .build(); assertThat(containsItem.hashCode(), not(equalTo(emptyRequest.hashCode()))); } @Test public void hashCode_includesIgnoreNulls() { UpdateItemEnhancedRequest<FakeItem> emptyRequest = UpdateItemEnhancedRequest.builder(FakeItem.class).build(); UpdateItemEnhancedRequest<FakeItem> containsItem = UpdateItemEnhancedRequest.builder(FakeItem.class) .ignoreNulls(true) .build(); assertThat(containsItem.hashCode(), not(equalTo(emptyRequest.hashCode()))); } @Test public void hashCode_includesConditionExpression() { UpdateItemEnhancedRequest<FakeItem> emptyRequest = UpdateItemEnhancedRequest.builder(FakeItem.class).build(); Expression conditionExpression = Expression.builder() .expression("#key = :value OR #key1 = :value1") .putExpressionName("#key", "attribute") .putExpressionName("#key1", "attribute3") .putExpressionValue(":value", stringValue("wrong")) .putExpressionValue(":value1", stringValue("three")) .build(); UpdateItemEnhancedRequest<FakeItem> containsExpression = UpdateItemEnhancedRequest.builder(FakeItem.class) .conditionExpression(conditionExpression) .build(); assertThat(containsExpression.hashCode(), not(equalTo(emptyRequest.hashCode()))); } @Test public void hashCode_includesReturnConsumedCapacity() { UpdateItemEnhancedRequest<FakeItem> emptyRequest = UpdateItemEnhancedRequest.builder(FakeItem.class).build(); UpdateItemEnhancedRequest<FakeItem> containsItem = UpdateItemEnhancedRequest.builder(FakeItem.class) .returnConsumedCapacity("return1") .build(); assertThat(containsItem.hashCode(), not(equalTo(emptyRequest.hashCode()))); } @Test public void hashCode_includesReturnItemCollectionMetrics() { UpdateItemEnhancedRequest<FakeItem> emptyRequest = UpdateItemEnhancedRequest.builder(FakeItem.class).build(); UpdateItemEnhancedRequest<FakeItem> containsItem = UpdateItemEnhancedRequest.builder(FakeItem.class) .returnItemCollectionMetrics("return1") .build(); assertThat(containsItem.hashCode(), not(equalTo(emptyRequest.hashCode()))); } }
4,333
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/model/WriteBatchTest.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.model; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItem.createUniqueFakeItem; import java.util.Map; import org.assertj.core.api.ThrowableAssert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.Key; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItem; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.DeleteRequest; import software.amazon.awssdk.services.dynamodb.model.PutRequest; import software.amazon.awssdk.services.dynamodb.model.WriteRequest; @RunWith(MockitoJUnitRunner.class) public class WriteBatchTest { private static final String TABLE_NAME = "table-name"; @Mock private DynamoDbClient mockDynamoDbClient; 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 builder_minimal() { WriteBatch builtObject = WriteBatch.builder(FakeItem.class).build(); assertThat(builtObject.tableName(), is(nullValue())); assertThat(builtObject.writeRequests(), is(nullValue())); } @Test public void builder_maximal_consumer_style() { FakeItem fakeItem = createUniqueFakeItem(); WriteBatch builtObject = WriteBatch.builder(FakeItem.class) .mappedTableResource(fakeItemMappedTable) .addPutItem(r -> r.item(fakeItem)) .addDeleteItem(r -> r.key(k -> k.partitionValue(fakeItem.getId()))) .build(); Map<String, AttributeValue> fakeItemMap = FakeItem.getTableSchema().itemToMap(fakeItem, FakeItem.getTableMetadata().primaryKeys()); assertThat(builtObject.tableName(), is(TABLE_NAME)); assertThat(builtObject.writeRequests(), containsInAnyOrder(putRequest(fakeItemMap), deleteRequest(fakeItemMap))); } @Test public void builder_maximal_builder_style() { FakeItem fakeItem = createUniqueFakeItem(); PutItemEnhancedRequest<FakeItem> putItem = PutItemEnhancedRequest.builder(FakeItem.class).item(fakeItem).build(); DeleteItemEnhancedRequest deleteItem = DeleteItemEnhancedRequest.builder() .key(k -> k.partitionValue(fakeItem.getId())) .build(); WriteBatch builtObject = WriteBatch.builder(FakeItem.class) .mappedTableResource(fakeItemMappedTable) .addPutItem(putItem) .addDeleteItem(deleteItem) .build(); Map<String, AttributeValue> fakeItemMap = FakeItem.getTableSchema().itemToMap(fakeItem, FakeItem.getTableMetadata().primaryKeys()); assertThat(builtObject.tableName(), is(TABLE_NAME)); assertThat(builtObject.writeRequests(), containsInAnyOrder(putRequest(fakeItemMap), deleteRequest(fakeItemMap))); } @Test public void builder_missing_mapped_table_resource_error_message() { FakeItem fakeItem = createUniqueFakeItem(); PutItemEnhancedRequest<FakeItem> putItemRequest = PutItemEnhancedRequest.builder(FakeItem.class).item(fakeItem).build(); Key partitionKey = Key.builder().partitionValue(fakeItem.getId()).build(); DeleteItemEnhancedRequest deleteItemRequest = DeleteItemEnhancedRequest.builder() .key(partitionKey) .build(); WriteBatch.Builder<FakeItem> builder = WriteBatch.builder(FakeItem.class); String errorMesageAfterBuild = "A mappedTableResource (table) is required when generating the write requests for " + "WriteBatch"; assertThrowsMappedTableResourceNullException(() -> builder.addPutItem(putItemRequest).build(), errorMesageAfterBuild); assertThrowsMappedTableResourceNullException(() -> builder.addPutItem(fakeItem).build(), errorMesageAfterBuild); assertThrowsMappedTableResourceNullException(() -> builder.addPutItem(r -> r.item(fakeItem)).build(), errorMesageAfterBuild); assertThrowsMappedTableResourceNullException(() -> builder.addDeleteItem(r -> r.key(partitionKey)).build(), errorMesageAfterBuild); assertThrowsMappedTableResourceNullException(() -> builder.addDeleteItem(deleteItemRequest).build(), errorMesageAfterBuild); String errorMessageDeleteKeyFromItem = "A mappedTableResource is required to derive a key from the given keyItem"; assertThrowsMappedTableResourceNullException(() -> builder.addDeleteItem(fakeItem).build(), errorMessageDeleteKeyFromItem); } private static void assertThrowsMappedTableResourceNullException(ThrowableAssert.ThrowingCallable runnable, String message) { assertThatThrownBy(runnable).isInstanceOf(NullPointerException.class).hasMessage(message); } private static WriteRequest putRequest(Map<String, AttributeValue> itemMap) { return WriteRequest.builder().putRequest(PutRequest.builder().item(itemMap).build()).build(); } private static WriteRequest deleteRequest(Map<String, AttributeValue> itemMap) { return WriteRequest.builder().deleteRequest(DeleteRequest.builder().key(itemMap).build()).build(); } }
4,334
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/model/TransactDeleteItemEnhancedRequestTest.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.model; 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 software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.stringValue; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.enhanced.dynamodb.Expression; import software.amazon.awssdk.enhanced.dynamodb.Key; import software.amazon.awssdk.services.dynamodb.model.ReturnValuesOnConditionCheckFailure; @RunWith(MockitoJUnitRunner.class) public class TransactDeleteItemEnhancedRequestTest { @Test public void builder_minimal() { TransactDeleteItemEnhancedRequest builtObject = TransactDeleteItemEnhancedRequest.builder().build(); assertThat(builtObject.key(), is(nullValue())); assertThat(builtObject.conditionExpression(), is(nullValue())); assertThat(builtObject.returnValuesOnConditionCheckFailure(), is(nullValue())); } @Test public void builder_maximal() { Key key = Key.builder().partitionValue("key").build(); Expression conditionExpression = Expression.builder() .expression("#key = :value OR #key1 = :value1") .putExpressionName("#key", "attribute") .putExpressionName("#key1", "attribute3") .putExpressionValue(":value", stringValue("wrong")) .putExpressionValue(":value1", stringValue("three")) .build(); ReturnValuesOnConditionCheckFailure returnValues = ReturnValuesOnConditionCheckFailure.ALL_OLD; TransactDeleteItemEnhancedRequest builtObject = TransactDeleteItemEnhancedRequest.builder() .key(key) .conditionExpression(conditionExpression) .returnValuesOnConditionCheckFailure(returnValues) .build(); assertThat(builtObject.key(), is(key)); assertThat(builtObject.conditionExpression(), is(conditionExpression)); assertThat(builtObject.returnValuesOnConditionCheckFailure(), is(returnValues)); } @Test public void equals_maximal() { Key key = Key.builder().partitionValue("key").build(); Expression conditionExpression = Expression.builder() .expression("#key = :value OR #key1 = :value1") .putExpressionName("#key", "attribute") .putExpressionName("#key1", "attribute3") .putExpressionValue(":value", stringValue("wrong")) .putExpressionValue(":value1", stringValue("three")) .build(); ReturnValuesOnConditionCheckFailure returnValues = ReturnValuesOnConditionCheckFailure.ALL_OLD; TransactDeleteItemEnhancedRequest builtObject = TransactDeleteItemEnhancedRequest.builder() .key(key) .conditionExpression(conditionExpression) .returnValuesOnConditionCheckFailure(returnValues) .build(); TransactDeleteItemEnhancedRequest copiedObject = builtObject.toBuilder().build(); assertThat(builtObject, equalTo(copiedObject)); } @Test public void equals_minimal() { TransactDeleteItemEnhancedRequest builtObject1 = TransactDeleteItemEnhancedRequest.builder().build(); TransactDeleteItemEnhancedRequest builtObject2 = TransactDeleteItemEnhancedRequest.builder().build(); assertThat(builtObject1, equalTo(builtObject2)); } @Test public void equals_differentType() { TransactDeleteItemEnhancedRequest builtObject = TransactDeleteItemEnhancedRequest.builder().build(); DeleteItemEnhancedRequest differentType = DeleteItemEnhancedRequest.builder().build(); assertThat(builtObject, not(equalTo(differentType))); } @Test public void equals_self() { TransactDeleteItemEnhancedRequest builtObject = TransactDeleteItemEnhancedRequest.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(); TransactDeleteItemEnhancedRequest builtObject1 = TransactDeleteItemEnhancedRequest.builder().key(key1).build(); TransactDeleteItemEnhancedRequest builtObject2 = TransactDeleteItemEnhancedRequest.builder().key(key2).build(); assertThat(builtObject1, not(equalTo(builtObject2))); } @Test public void equals_conditionExpressionNotEqual() { Expression conditionExpression1 = Expression.builder() .expression("#key = :value OR #key1 = :value1") .putExpressionName("#key", "attribute") .putExpressionName("#key1", "attribute3") .putExpressionValue(":value", stringValue("wrong")) .putExpressionValue(":value1", stringValue("three")) .build(); Expression conditionExpression2 = Expression.builder() .expression("#key = :value AND #key1 = :value1") .putExpressionName("#key", "attribute") .putExpressionName("#key1", "attribute3") .putExpressionValue(":value", stringValue("wrong")) .putExpressionValue(":value1", stringValue("three")) .build(); TransactDeleteItemEnhancedRequest builtObject1 = TransactDeleteItemEnhancedRequest.builder().conditionExpression(conditionExpression1).build(); TransactDeleteItemEnhancedRequest builtObject2 = TransactDeleteItemEnhancedRequest.builder().conditionExpression(conditionExpression2).build(); assertThat(builtObject1, not(equalTo(builtObject2))); } @Test public void equal_returnValuesNotEqual() { ReturnValuesOnConditionCheckFailure returnValues1 = ReturnValuesOnConditionCheckFailure.ALL_OLD; ReturnValuesOnConditionCheckFailure returnValues2 = ReturnValuesOnConditionCheckFailure.NONE; TransactDeleteItemEnhancedRequest builtObject1 = TransactDeleteItemEnhancedRequest.builder().returnValuesOnConditionCheckFailure(returnValues1).build(); TransactDeleteItemEnhancedRequest builtObject2 = TransactDeleteItemEnhancedRequest.builder().returnValuesOnConditionCheckFailure(returnValues2).build(); assertThat(builtObject1, not(equalTo(builtObject2))); } @Test public void hashCode_maximal() { Key key = Key.builder().partitionValue("key").build(); Expression conditionExpression = Expression.builder() .expression("#key = :value OR #key1 = :value1") .putExpressionName("#key", "attribute") .putExpressionName("#key1", "attribute3") .putExpressionValue(":value", stringValue("wrong")) .putExpressionValue(":value1", stringValue("three")) .build(); ReturnValuesOnConditionCheckFailure returnValues = ReturnValuesOnConditionCheckFailure.ALL_OLD; TransactDeleteItemEnhancedRequest builtObject = TransactDeleteItemEnhancedRequest.builder() .key(key) .conditionExpression(conditionExpression) .returnValuesOnConditionCheckFailure(returnValues) .build(); TransactDeleteItemEnhancedRequest copiedObject = builtObject.toBuilder().build(); assertThat(builtObject.hashCode(), equalTo(copiedObject.hashCode())); } @Test public void hashCode_minimal() { TransactDeleteItemEnhancedRequest builtObject1 = TransactDeleteItemEnhancedRequest.builder().build(); TransactDeleteItemEnhancedRequest builtObject2 = TransactDeleteItemEnhancedRequest.builder().build(); assertThat(builtObject1.hashCode(), equalTo(builtObject2.hashCode())); } @Test public void toBuilder() { Key key = Key.builder().partitionValue("key").build(); ReturnValuesOnConditionCheckFailure returnValues = ReturnValuesOnConditionCheckFailure.ALL_OLD; TransactDeleteItemEnhancedRequest builtObject = TransactDeleteItemEnhancedRequest.builder() .key(key) .returnValuesOnConditionCheckFailure(returnValues) .build(); TransactDeleteItemEnhancedRequest copiedObject = builtObject.toBuilder().build(); assertThat(copiedObject, is(builtObject)); } @Test public void builder_returnValuesOnConditionCheckFailureSetterNull_noNpe() { TransactDeleteItemEnhancedRequest builtObject = TransactDeleteItemEnhancedRequest.builder() .returnValuesOnConditionCheckFailure((ReturnValuesOnConditionCheckFailure) null) .build(); assertThat(builtObject.returnValuesOnConditionCheckFailure(), is(nullValue())); } @Test public void builder_returnValuesOnConditionCheckFailureSetterString() { String returnValues = "new-value"; TransactDeleteItemEnhancedRequest builtObject = TransactDeleteItemEnhancedRequest.builder() .returnValuesOnConditionCheckFailure(returnValues) .build(); assertThat(builtObject.returnValuesOnConditionCheckFailureAsString(), is(returnValues)); } }
4,335
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/model/QueryEnhancedRequestTest.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.model; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.enhanced.dynamodb.Expression; import software.amazon.awssdk.enhanced.dynamodb.NestedAttributeName; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import java.util.*; import static java.util.Collections.singletonMap; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.numberValue; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.stringValue; import static software.amazon.awssdk.enhanced.dynamodb.model.QueryConditional.keyEqualTo; @RunWith(MockitoJUnitRunner.class) public class QueryEnhancedRequestTest { @Test public void builder_minimal() { QueryEnhancedRequest builtObject = QueryEnhancedRequest.builder().build(); assertThat(builtObject.exclusiveStartKey(), is(nullValue())); assertThat(builtObject.consistentRead(), is(nullValue())); assertThat(builtObject.filterExpression(), is(nullValue())); assertThat(builtObject.limit(), is(nullValue())); assertThat(builtObject.queryConditional(), is(nullValue())); assertThat(builtObject.scanIndexForward(), is(nullValue())); assertThat(builtObject.attributesToProject(), is(nullValue())); } @Test public void builder_maximal() { Map<String, AttributeValue> exclusiveStartKey = new HashMap<>(); exclusiveStartKey.put("id", stringValue("id-value")); exclusiveStartKey.put("sort", numberValue(7)); Map<String, AttributeValue> expressionValues = singletonMap(":test-key", stringValue("test-value")); Expression filterExpression = Expression.builder() .expression("test-expression") .expressionValues(expressionValues) .build(); QueryConditional queryConditional = keyEqualTo(k -> k.partitionValue("id-value")); String[] attributesToProjectArray = {"one", "two"}; String additionalElement = "three"; List<String> attributesToProject = new ArrayList<>(Arrays.asList(attributesToProjectArray)); attributesToProject.add(additionalElement); QueryEnhancedRequest builtObject = QueryEnhancedRequest.builder() .exclusiveStartKey(exclusiveStartKey) .consistentRead(false) .filterExpression(filterExpression) .limit(3) .queryConditional(queryConditional) .scanIndexForward(true) .attributesToProject(attributesToProjectArray) .addAttributeToProject(additionalElement) .build(); assertThat(builtObject.exclusiveStartKey(), is(exclusiveStartKey)); assertThat(builtObject.consistentRead(), is(false)); assertThat(builtObject.filterExpression(), is(filterExpression)); assertThat(builtObject.limit(), is(3)); assertThat(builtObject.queryConditional(), is(queryConditional)); assertThat(builtObject.scanIndexForward(), is(true)); assertThat(builtObject.attributesToProject(), is(attributesToProject)); } @Test public void test_withNestedAttributeAddedFirstAndThenAttributesToProject() { String[] attributesToProjectArray = {"one", "two"}; String additionalElement = "three"; QueryEnhancedRequest builtObject = QueryEnhancedRequest.builder() .addNestedAttributesToProject(NestedAttributeName.create("foo", "bar")) .attributesToProject(attributesToProjectArray) .addAttributeToProject(additionalElement) .build(); List<String> attributesToProject = Arrays.asList("one", "two", "three"); assertThat(builtObject.attributesToProject(), is(attributesToProject)); } @Test public void test_nestedAttributesToProjectWithNestedAttributeAddedLast() { String[] attributesToProjectArray = {"one", "two"}; String additionalElement = "three"; QueryEnhancedRequest builtObjectOne = QueryEnhancedRequest.builder() .attributesToProject(attributesToProjectArray) .addAttributeToProject(additionalElement) .addNestedAttributesToProject(NestedAttributeName.create("foo", "bar")) .build(); List<String> attributesToProjectNestedLast = Arrays.asList("one", "two", "three", "foo.bar"); assertThat(builtObjectOne.attributesToProject(), is(attributesToProjectNestedLast)); } @Test public void test_nestedAttributesToProjectWithNestedAttributeAddedInBetween() { String[] attributesToProjectArray = {"one", "two"}; String additionalElement = "three"; QueryEnhancedRequest builtObjectOne = QueryEnhancedRequest.builder() .attributesToProject(attributesToProjectArray) .addNestedAttributesToProject(NestedAttributeName.create("foo", "bar")) .addAttributeToProject(additionalElement) .build(); List<String> attributesToProjectNestedLast = Arrays.asList("one", "two", "foo.bar", "three"); assertThat(builtObjectOne.attributesToProject(), is(attributesToProjectNestedLast)); } @Test public void test_nestedAttributesToProjectOverwrite() { String[] attributesToProjectArray = {"one", "two"}; String additionalElement = "three"; String[] overwrite = { "overwrite"}; QueryEnhancedRequest builtObjectTwo = QueryEnhancedRequest.builder() .attributesToProject(attributesToProjectArray) .addAttributeToProject(additionalElement) .addNestedAttributesToProject(NestedAttributeName.create("foo", "bar")) .attributesToProject(overwrite) .build(); assertThat(builtObjectTwo.attributesToProject(), is(Arrays.asList(overwrite))); } @Test public void test_nestedAttributesNullNestedAttributeElement() { List<NestedAttributeName> attributeNames = new ArrayList<>(); attributeNames.add(NestedAttributeName.create("foo")); attributeNames.add(null); assertThatThrownBy(() -> QueryEnhancedRequest.builder() .addNestedAttributesToProject(attributeNames) .build()).isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> QueryEnhancedRequest.builder() .addNestedAttributesToProject(NestedAttributeName.create("foo", "bar"), null) .build()).isInstanceOf(IllegalArgumentException.class); NestedAttributeName nestedAttributeName = null; QueryEnhancedRequest.builder() .addNestedAttributeToProject(nestedAttributeName) .build(); assertThatThrownBy(() -> QueryEnhancedRequest.builder() .addNestedAttributesToProject(nestedAttributeName) .build()).isInstanceOf(IllegalArgumentException.class); } @Test public void toBuilder() { QueryEnhancedRequest builtObject = QueryEnhancedRequest.builder().build(); QueryEnhancedRequest copiedObject = builtObject.toBuilder().build(); assertThat(copiedObject, is(builtObject)); } }
4,336
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/model/DeleteItemEnhancedRequestTest.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.model; 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 software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.stringValue; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.enhanced.dynamodb.Expression; import software.amazon.awssdk.enhanced.dynamodb.Key; import software.amazon.awssdk.services.dynamodb.model.ReturnConsumedCapacity; import software.amazon.awssdk.services.dynamodb.model.ReturnItemCollectionMetrics; @RunWith(MockitoJUnitRunner.class) public class DeleteItemEnhancedRequestTest { @Test public void builder_minimal() { DeleteItemEnhancedRequest builtObject = DeleteItemEnhancedRequest.builder().build(); assertThat(builtObject.key(), is(nullValue())); assertThat(builtObject.conditionExpression(), is(nullValue())); assertThat(builtObject.returnConsumedCapacity(), is(nullValue())); assertThat(builtObject.returnConsumedCapacityAsString(), is(nullValue())); assertThat(builtObject.returnItemCollectionMetrics(), is(nullValue())); assertThat(builtObject.returnItemCollectionMetricsAsString(), is(nullValue())); } @Test public void builder_maximal() { Key key = Key.builder().partitionValue("key").build(); Expression conditionExpression = Expression.builder() .expression("#key = :value OR #key1 = :value1") .putExpressionName("#key", "attribute") .putExpressionName("#key1", "attribute3") .putExpressionValue(":value", stringValue("wrong")) .putExpressionValue(":value1", stringValue("three")) .build(); ReturnConsumedCapacity returnConsumedCapacity = ReturnConsumedCapacity.TOTAL; ReturnItemCollectionMetrics returnItemCollectionMetrics = ReturnItemCollectionMetrics.SIZE; DeleteItemEnhancedRequest builtObject = DeleteItemEnhancedRequest.builder() .key(key) .conditionExpression(conditionExpression) .returnConsumedCapacity(returnConsumedCapacity) .returnItemCollectionMetrics(returnItemCollectionMetrics) .build(); assertThat(builtObject.key(), is(key)); assertThat(builtObject.conditionExpression(), is(conditionExpression)); assertThat(builtObject.returnConsumedCapacity(), is(returnConsumedCapacity)); assertThat(builtObject.returnConsumedCapacityAsString(), is(returnConsumedCapacity.toString())); assertThat(builtObject.returnItemCollectionMetrics(), is(returnItemCollectionMetrics)); assertThat(builtObject.returnItemCollectionMetricsAsString(), is(returnItemCollectionMetrics.toString())); } @Test public void toBuilder() { Key key = Key.builder().partitionValue("key").build(); Expression conditionExpression = Expression.builder() .expression("#key = :value OR #key1 = :value1") .putExpressionName("#key", "attribute") .putExpressionName("#key1", "attribute3") .putExpressionValue(":value", stringValue("wrong")) .putExpressionValue(":value1", stringValue("three")) .build(); ReturnConsumedCapacity returnConsumedCapacity = ReturnConsumedCapacity.TOTAL; ReturnItemCollectionMetrics returnItemCollectionMetrics = ReturnItemCollectionMetrics.SIZE; DeleteItemEnhancedRequest builtObject = DeleteItemEnhancedRequest.builder() .key(key) .conditionExpression(conditionExpression) .returnConsumedCapacity(returnConsumedCapacity) .returnItemCollectionMetrics(returnItemCollectionMetrics) .build(); DeleteItemEnhancedRequest copiedObject = builtObject.toBuilder().build(); assertThat(copiedObject, is(builtObject)); } @Test public void equals_keyNotEqual() { Key key1 = Key.builder().partitionValue("key1").build(); Key key2 = Key.builder().partitionValue("key2").build(); DeleteItemEnhancedRequest builtObject1 = DeleteItemEnhancedRequest.builder().key(key1).build(); DeleteItemEnhancedRequest builtObject2 = DeleteItemEnhancedRequest.builder().key(key2).build(); assertThat(builtObject1, not(equalTo(builtObject2))); } @Test public void equals_conditionExpressionNotEqual() { Expression conditionExpression1 = Expression.builder() .expression("#key = :value OR #key1 = :value1") .putExpressionName("#key", "attribute") .putExpressionName("#key1", "attribute3") .putExpressionValue(":value", stringValue("wrong")) .putExpressionValue(":value1", stringValue("three")) .build(); Expression conditionExpression2 = Expression.builder() .expression("#key = :value AND #key1 = :value1") .putExpressionName("#key", "attribute") .putExpressionName("#key1", "attribute3") .putExpressionValue(":value", stringValue("wrong")) .putExpressionValue(":value1", stringValue("three")) .build(); DeleteItemEnhancedRequest builtObject1 = DeleteItemEnhancedRequest.builder() .conditionExpression(conditionExpression1) .build(); DeleteItemEnhancedRequest builtObject2 = DeleteItemEnhancedRequest.builder() .conditionExpression(conditionExpression2) .build(); assertThat(builtObject1, not(equalTo(builtObject2))); } @Test public void equals_returnConsumedCapacityNotEqual() { ReturnConsumedCapacity returnConsumedCapacity1 = ReturnConsumedCapacity.TOTAL; ReturnConsumedCapacity returnConsumedCapacity2 = ReturnConsumedCapacity.NONE; DeleteItemEnhancedRequest builtObject1 = DeleteItemEnhancedRequest.builder() .returnConsumedCapacity(returnConsumedCapacity1) .build(); DeleteItemEnhancedRequest builtObject2 = DeleteItemEnhancedRequest.builder() .returnConsumedCapacity(returnConsumedCapacity2) .build(); assertThat(builtObject1, not(equalTo(builtObject2))); } @Test public void equals_returnItemCollectionMetricsNotEqual() { ReturnItemCollectionMetrics returnItemCollectionMetrics1 = ReturnItemCollectionMetrics.SIZE; ReturnItemCollectionMetrics returnItemCollectionMetrics2 = ReturnItemCollectionMetrics.NONE; DeleteItemEnhancedRequest builtObject1 = DeleteItemEnhancedRequest.builder() .returnItemCollectionMetrics(returnItemCollectionMetrics1) .build(); DeleteItemEnhancedRequest builtObject2 = DeleteItemEnhancedRequest.builder() .returnItemCollectionMetrics(returnItemCollectionMetrics2) .build(); assertThat(builtObject1, not(equalTo(builtObject2))); } @Test public void hashCode_minimal() { DeleteItemEnhancedRequest emptyRequest = DeleteItemEnhancedRequest.builder().build(); assertThat(emptyRequest.hashCode(), equalTo(0)); } @Test public void hashCode_includesKey() { DeleteItemEnhancedRequest emptyRequest = DeleteItemEnhancedRequest.builder().build(); Key key = Key.builder().partitionValue("key").build(); DeleteItemEnhancedRequest containsKey = DeleteItemEnhancedRequest.builder().key(key).build(); assertThat(containsKey.hashCode(), not(equalTo(emptyRequest.hashCode()))); } @Test public void hashCode_includesConditionExpression() { DeleteItemEnhancedRequest emptyRequest = DeleteItemEnhancedRequest.builder().build(); Expression conditionExpression = Expression.builder() .expression("#key = :value OR #key1 = :value1") .putExpressionName("#key", "attribute") .putExpressionName("#key1", "attribute3") .putExpressionValue(":value", stringValue("wrong")) .putExpressionValue(":value1", stringValue("three")) .build(); DeleteItemEnhancedRequest containsKey = DeleteItemEnhancedRequest.builder() .conditionExpression(conditionExpression) .build(); assertThat(containsKey.hashCode(), not(equalTo(emptyRequest.hashCode()))); } @Test public void hashCode_includesReturnConsumedCapacity() { DeleteItemEnhancedRequest emptyRequest = DeleteItemEnhancedRequest.builder().build(); ReturnConsumedCapacity returnConsumedCapacity = ReturnConsumedCapacity.TOTAL; DeleteItemEnhancedRequest containsKey = DeleteItemEnhancedRequest.builder() .returnConsumedCapacity(returnConsumedCapacity) .build(); assertThat(containsKey.hashCode(), not(equalTo(emptyRequest.hashCode()))); } @Test public void hashCode_includesReturnItemCollectionMetrics() { DeleteItemEnhancedRequest emptyRequest = DeleteItemEnhancedRequest.builder().build(); ReturnItemCollectionMetrics returnItemCollectionMetrics = ReturnItemCollectionMetrics.SIZE; DeleteItemEnhancedRequest containsKey = DeleteItemEnhancedRequest.builder() .returnItemCollectionMetrics(returnItemCollectionMetrics) .build(); assertThat(containsKey.hashCode(), not(equalTo(emptyRequest.hashCode()))); } }
4,337
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/model/CreateTableEnhancedRequestTest.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.model; import static java.util.Arrays.asList; import static java.util.function.Predicate.isEqual; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import java.util.Collections; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.services.dynamodb.model.LocalSecondaryIndex; import software.amazon.awssdk.services.dynamodb.model.Projection; import software.amazon.awssdk.services.dynamodb.model.ProjectionType; import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughput; @RunWith(MockitoJUnitRunner.class) public class CreateTableEnhancedRequestTest { @Test public void builder_minimal() { CreateTableEnhancedRequest builtObject = CreateTableEnhancedRequest.builder().build(); assertThat(builtObject.globalSecondaryIndices(), is(nullValue())); assertThat(builtObject.localSecondaryIndices(), is(nullValue())); assertThat(builtObject.provisionedThroughput(), is(nullValue())); } @Test public void builder_maximal() { EnhancedGlobalSecondaryIndex globalSecondaryIndex = EnhancedGlobalSecondaryIndex.builder() .indexName("gsi_1") .projection(p -> p.projectionType(ProjectionType.ALL)) .provisionedThroughput(getDefaultProvisionedThroughput()) .build(); EnhancedLocalSecondaryIndex localSecondaryIndex = EnhancedLocalSecondaryIndex.create( "lsi", Projection.builder().projectionType(ProjectionType.ALL).build()); CreateTableEnhancedRequest builtObject = CreateTableEnhancedRequest.builder() .globalSecondaryIndices(globalSecondaryIndex) .localSecondaryIndices(localSecondaryIndex) .provisionedThroughput(getDefaultProvisionedThroughput()) .build(); assertThat(builtObject.globalSecondaryIndices(), is(Collections.singletonList(globalSecondaryIndex))); assertThat(builtObject.localSecondaryIndices(), is(Collections.singletonList(localSecondaryIndex))); assertThat(builtObject.provisionedThroughput(), is(getDefaultProvisionedThroughput())); } @Test public void builder_consumerBuilder() { CreateTableEnhancedRequest builtObject = CreateTableEnhancedRequest.builder() .globalSecondaryIndices(gsi -> gsi.indexName("x"), gsi -> gsi.indexName("y")) .localSecondaryIndices(lsi -> lsi.indexName("x"), lsi -> lsi.indexName("y")) .provisionedThroughput(p -> p.readCapacityUnits(10L)) .build(); assertThat(builtObject.globalSecondaryIndices(), equalTo(asList(EnhancedGlobalSecondaryIndex.builder().indexName("x").build(), EnhancedGlobalSecondaryIndex.builder().indexName("y").build()))); assertThat(builtObject.localSecondaryIndices(), equalTo(asList(EnhancedLocalSecondaryIndex.builder().indexName("x").build(), EnhancedLocalSecondaryIndex.builder().indexName("y").build()))); assertThat(builtObject.provisionedThroughput(), equalTo(ProvisionedThroughput.builder().readCapacityUnits(10L).build())); } @Test public void toBuilder() { CreateTableEnhancedRequest builtObject = CreateTableEnhancedRequest.builder() .provisionedThroughput(getDefaultProvisionedThroughput()) .build(); CreateTableEnhancedRequest copiedObject = builtObject.toBuilder().build(); assertThat(copiedObject, is(builtObject)); } private ProvisionedThroughput getDefaultProvisionedThroughput() { return ProvisionedThroughput.builder() .writeCapacityUnits(1L) .readCapacityUnits(2L) .build(); } }
4,338
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/model/TransactWriteItemsEnhancedRequestTest.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.model; import static java.util.Collections.singletonMap; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertEquals; import static software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItem.createUniqueFakeItem; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.stringValue; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.UUID; 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.Expression; import software.amazon.awssdk.enhanced.dynamodb.Key; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItem; import software.amazon.awssdk.enhanced.dynamodb.internal.client.ExtensionResolver; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.TransactWriteItemsOperation; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.Delete; import software.amazon.awssdk.services.dynamodb.model.Put; import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem; import software.amazon.awssdk.services.dynamodb.model.TransactWriteItemsRequest; @RunWith(MockitoJUnitRunner.class) public class TransactWriteItemsEnhancedRequestTest { private static final String TABLE_NAME = "table-name"; @Mock private DynamoDbClient mockDynamoDbClient; 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 builder_minimal() { TransactWriteItemsEnhancedRequest builtObject = TransactWriteItemsEnhancedRequest.builder().build(); assertThat(builtObject.transactWriteItems(), is(nullValue())); } @Test public void builder_maximal_consumer_style() { FakeItem fakeItem = createUniqueFakeItem(); Expression conditionExpression = Expression.builder() .expression("#attribute = :attribute") .expressionValues(singletonMap(":attribute", stringValue("0"))) .expressionNames(singletonMap("#attribute", "attribute")) .build(); TransactWriteItemsEnhancedRequest builtObject = TransactWriteItemsEnhancedRequest.builder() .addPutItem(fakeItemMappedTable, fakeItem) .addDeleteItem(fakeItemMappedTable, fakeItem) .addUpdateItem(fakeItemMappedTable, fakeItem) .addConditionCheck(fakeItemMappedTable, r -> r.key(k -> k.partitionValue(fakeItem.getId())) .conditionExpression(conditionExpression)) .build(); assertThat(builtObject.transactWriteItems().size(), is(4)); assertThat(builtObject.transactWriteItems().get(0), is(getTransactWriteItems(fakeItem).get(0))); assertThat(builtObject.transactWriteItems().get(1), is(getTransactWriteItems(fakeItem).get(1))); assertThat(builtObject.transactWriteItems().get(2).update(), is(notNullValue())); assertThat(builtObject.transactWriteItems().get(2).update().key().get("id").s(), is(fakeItem.getId())); assertThat(builtObject.transactWriteItems().get(3).conditionCheck(), is(notNullValue())); assertThat(builtObject.transactWriteItems().get(3).conditionCheck().key().get("id").s(), is(fakeItem.getId())); } @Test public void builder_maximal_shortcut_style() { FakeItem fakeItem = createUniqueFakeItem(); Expression conditionExpression = Expression.builder() .expression("#attribute = :attribute") .expressionValues(singletonMap(":attribute", stringValue("0"))) .expressionNames(singletonMap("#attribute", "attribute")) .build(); TransactWriteItemsEnhancedRequest builtObject = TransactWriteItemsEnhancedRequest.builder() .addPutItem(fakeItemMappedTable, fakeItem) .addDeleteItem(fakeItemMappedTable, Key.builder().partitionValue(fakeItem.getId()).build()) .addUpdateItem(fakeItemMappedTable, fakeItem) .addConditionCheck(fakeItemMappedTable, r -> r.key(k -> k.partitionValue(fakeItem.getId())) .conditionExpression(conditionExpression)) .build(); assertThat(builtObject.transactWriteItems().size(), is(4)); assertThat(builtObject.transactWriteItems().get(0), is(getTransactWriteItems(fakeItem).get(0))); assertThat(builtObject.transactWriteItems().get(1), is(getTransactWriteItems(fakeItem).get(1))); assertThat(builtObject.transactWriteItems().get(2).update(), is(notNullValue())); assertThat(builtObject.transactWriteItems().get(2).update().key().get("id").s(), is(fakeItem.getId())); assertThat(builtObject.transactWriteItems().get(3).conditionCheck(), is(notNullValue())); assertThat(builtObject.transactWriteItems().get(3).conditionCheck().key().get("id").s(), is(fakeItem.getId())); } @Test public void builder_maximal_builder_style() { FakeItem fakeItem = createUniqueFakeItem(); PutItemEnhancedRequest<FakeItem> putItem = PutItemEnhancedRequest.builder(FakeItem.class).item(fakeItem).build(); DeleteItemEnhancedRequest deleteItem = DeleteItemEnhancedRequest.builder() .key(k -> k.partitionValue(fakeItem.getId())) .build(); UpdateItemEnhancedRequest<FakeItem> updateItem = UpdateItemEnhancedRequest.builder(FakeItem.class) .item(fakeItem).build(); Expression conditionExpression = Expression.builder() .expression("#attribute = :attribute") .expressionValues(singletonMap(":attribute", stringValue("0"))) .expressionNames(singletonMap("#attribute", "attribute")) .build(); ConditionCheck<FakeItem> conditionCheck = ConditionCheck.builder() .key(k -> k.partitionValue(fakeItem.getId())) .conditionExpression(conditionExpression) .build(); TransactWriteItemsEnhancedRequest builtObject = TransactWriteItemsEnhancedRequest.builder() .addPutItem(fakeItemMappedTable, putItem) .addDeleteItem(fakeItemMappedTable, deleteItem) .addUpdateItem(fakeItemMappedTable, updateItem) .addConditionCheck(fakeItemMappedTable, conditionCheck) .build(); assertThat(builtObject.transactWriteItems().size(), is(4)); assertThat(builtObject.transactWriteItems().get(0), is(getTransactWriteItems(fakeItem).get(0))); assertThat(builtObject.transactWriteItems().get(1), is(getTransactWriteItems(fakeItem).get(1))); assertThat(builtObject.transactWriteItems().get(2).update(), is(notNullValue())); assertThat(builtObject.transactWriteItems().get(2).update().key().get("id").s(), is(fakeItem.getId())); assertThat(builtObject.transactWriteItems().get(3).conditionCheck(), is(notNullValue())); assertThat(builtObject.transactWriteItems().get(3).conditionCheck().key().get("id").s(), is(fakeItem.getId())); } @Test public void builder_passRequestToken_shouldWork() { String token = UUID.randomUUID().toString(); TransactWriteItemsEnhancedRequest enhancedRequest = TransactWriteItemsEnhancedRequest.builder() .clientRequestToken(token) .build(); DynamoDbEnhancedClientExtension extension = ExtensionResolver.resolveExtensions(ExtensionResolver.defaultExtensions()); TransactWriteItemsRequest request = TransactWriteItemsOperation.create(enhancedRequest).generateRequest(extension); assertEquals(token, request.clientRequestToken()); } private List<TransactWriteItem> getTransactWriteItems(FakeItem fakeItem) { final Map<String, AttributeValue> fakeItemMap = FakeItem.getTableSchema().itemToMap(fakeItem, true); TransactWriteItem putWriteItem = TransactWriteItem.builder() .put(Put.builder() .item(fakeItemMap) .tableName(TABLE_NAME) .build()) .build(); TransactWriteItem deleteWriteItem = TransactWriteItem.builder() .delete(Delete.builder() .key(fakeItemMap) .tableName(TABLE_NAME) .build()) .build(); return Arrays.asList(putWriteItem, deleteWriteItem); } }
4,339
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/model/PageTest.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.model; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.singletonMap; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; class PageTest { @Test public void nullToStringIsCorrect() { assertThat(Page.create(null)).hasToString("Page()"); } @Test public void emptyToStringIsCorrect() { assertThat(Page.create(emptyList())).hasToString("Page(items=[])"); } @Test public void fullToStringIsCorrect() { assertThat(Page.create(asList("foo", "bar"), singletonMap("foo", AttributeValue.builder().s("bar").build()))) .hasToString("Page(lastEvaluatedKey={foo=AttributeValue(S=bar)}, items=[foo, bar])"); } }
4,340
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/model/TransactGetItemsEnhancedRequestTest.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.model; 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.functionaltests.models.FakeItem.createUniqueFakeItem; import java.util.Arrays; import java.util.List; import java.util.Map; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItem; 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.TransactGetItem; @RunWith(MockitoJUnitRunner.class) public class TransactGetItemsEnhancedRequestTest { private static final String TABLE_NAME = "table-name"; @Mock private DynamoDbClient mockDynamoDbClient; private DynamoDbEnhancedClient enhancedClient; private DynamoDbTable<FakeItem> fakeItemMappedTable; @Before public void setupMappedTables() { enhancedClient = DynamoDbEnhancedClient.builder().dynamoDbClient(mockDynamoDbClient).build(); fakeItemMappedTable = enhancedClient.table(TABLE_NAME, FakeItem.getTableSchema()); } @Test public void builder_minimal() { TransactGetItemsEnhancedRequest builtObject = TransactGetItemsEnhancedRequest.builder().build(); assertThat(builtObject.transactGetItems(), is(nullValue())); } @Test public void builder_maximal_consumer_style() { FakeItem fakeItem = createUniqueFakeItem(); TransactGetItemsEnhancedRequest builtObject = TransactGetItemsEnhancedRequest.builder() .addGetItem(fakeItemMappedTable, fakeItem) .addGetItem(fakeItemMappedTable, fakeItem) .build(); assertThat(builtObject.transactGetItems(), is(getTransactGetItems(fakeItem))); } @Test public void builder_maximal_builder_style() { FakeItem fakeItem = createUniqueFakeItem(); GetItemEnhancedRequest getItem = GetItemEnhancedRequest.builder() .key(k -> k.partitionValue(fakeItem.getId())) .build(); TransactGetItemsEnhancedRequest builtObject = TransactGetItemsEnhancedRequest.builder() .addGetItem(fakeItemMappedTable, getItem) .addGetItem(fakeItemMappedTable, getItem) .build(); assertThat(builtObject.transactGetItems(), is(getTransactGetItems(fakeItem))); } private List<TransactGetItem> getTransactGetItems(FakeItem fakeItem) { final Map<String, AttributeValue> fakeItemMap = FakeItem.getTableSchema().itemToMap(fakeItem, true); TransactGetItem getItem = TransactGetItem.builder() .get(Get.builder() .key(fakeItemMap) .tableName(TABLE_NAME) .build()) .build(); return Arrays.asList(getItem, getItem); } }
4,341
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/model/PutItemEnhancedResponseTest.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.model; import static org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItem.createUniqueFakeItem; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Test; import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItem; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.ConsumedCapacity; import software.amazon.awssdk.services.dynamodb.model.ItemCollectionMetrics; public class PutItemEnhancedResponseTest { @Test public void builder_minimal() { PutItemEnhancedResponse<FakeItem> builtObject = PutItemEnhancedResponse.builder(FakeItem.class).build(); assertThat(builtObject.attributes()).isNull(); assertThat(builtObject.consumedCapacity()).isNull(); assertThat(builtObject.itemCollectionMetrics()).isNull(); } @Test public void builder_maximal() { FakeItem fakeItem = createUniqueFakeItem(); ConsumedCapacity consumedCapacity = ConsumedCapacity.builder().tableName("MyTable").build(); Map<String, AttributeValue> collectionKey = new HashMap<>(); collectionKey.put("foo", AttributeValue.builder().s("bar").build()); ItemCollectionMetrics itemCollectionMetrics = ItemCollectionMetrics.builder().itemCollectionKey(collectionKey).build(); PutItemEnhancedResponse<FakeItem> builtObject = PutItemEnhancedResponse.builder(FakeItem.class) .attributes(fakeItem) .consumedCapacity(consumedCapacity) .itemCollectionMetrics(itemCollectionMetrics) .build(); assertThat(builtObject.attributes()).isEqualTo(fakeItem); assertThat(builtObject.consumedCapacity()).isEqualTo(consumedCapacity); assertThat(builtObject.itemCollectionMetrics()).isEqualTo(itemCollectionMetrics); } @Test public void equals_self() { PutItemEnhancedResponse<FakeItem> builtObject = PutItemEnhancedResponse.builder(FakeItem.class).build(); assertThat(builtObject).isEqualTo(builtObject); } @Test public void equals_differentType() { PutItemEnhancedResponse<FakeItem> builtObject = PutItemEnhancedResponse.builder(FakeItem.class).build(); assertThat(builtObject).isNotEqualTo(new Object()); } @Test public void equals_attributesNotEqual() { FakeItem fakeItem1 = createUniqueFakeItem(); FakeItem fakeItem2 = createUniqueFakeItem(); PutItemEnhancedResponse<FakeItem> builtObject1 = PutItemEnhancedResponse.builder(FakeItem.class) .attributes(fakeItem1) .build(); PutItemEnhancedResponse<FakeItem> builtObject2 = PutItemEnhancedResponse.builder(FakeItem.class) .attributes(fakeItem2) .build(); assertThat(builtObject1).isNotEqualTo(builtObject2); } @Test public void hashCode_minimal() { PutItemEnhancedResponse<FakeItem> emptyResponse = PutItemEnhancedResponse.builder(FakeItem.class).build(); assertThat(emptyResponse.hashCode()).isEqualTo(0); } @Test public void hashCode_includesAttributes() { PutItemEnhancedResponse<FakeItem> emptyResponse = PutItemEnhancedResponse.builder(FakeItem.class).build(); FakeItem fakeItem = createUniqueFakeItem(); PutItemEnhancedResponse<FakeItem> containsAttributes = PutItemEnhancedResponse.builder(FakeItem.class) .attributes(fakeItem) .build(); assertThat(containsAttributes.hashCode()).isNotEqualTo(emptyResponse.hashCode()); } @Test public void hashCode_includesConsumedCapacity() { PutItemEnhancedResponse<FakeItem> emptyResponse = PutItemEnhancedResponse.builder(FakeItem.class).build(); ConsumedCapacity consumedCapacity = ConsumedCapacity.builder().tableName("MyTable").build(); PutItemEnhancedResponse<FakeItem> containsConsumedCapacity = PutItemEnhancedResponse.builder(FakeItem.class) .consumedCapacity(consumedCapacity) .build(); assertThat(containsConsumedCapacity.hashCode()).isNotEqualTo(emptyResponse.hashCode()); } @Test public void hashCode_includesItemCollectionMetrics() { PutItemEnhancedResponse<FakeItem> emptyResponse = PutItemEnhancedResponse.builder(FakeItem.class).build(); Map<String, AttributeValue> collectionKey = new HashMap<>(); collectionKey.put("foo", AttributeValue.builder().s("bar").build()); ItemCollectionMetrics itemCollectionMetrics = ItemCollectionMetrics.builder().itemCollectionKey(collectionKey).build(); PutItemEnhancedResponse<FakeItem> containsItemCollectionMetrics = PutItemEnhancedResponse.builder(FakeItem.class) .itemCollectionMetrics(itemCollectionMetrics) .build(); assertThat(containsItemCollectionMetrics.hashCode()).isNotEqualTo(emptyResponse.hashCode()); } }
4,342
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/model/DescribeTableEnhancedResponseTest.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.model; import static org.assertj.core.api.Assertions.assertThatThrownBy; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; public class DescribeTableEnhancedResponseTest { @Test public void responseNull_shouldThrowException() { assertThatThrownBy(() -> DescribeTableEnhancedResponse.builder().build()) .isInstanceOf(NullPointerException.class) .hasMessageContaining("response must not be null"); } @Test public void equalsHashcode() { EqualsVerifier.forClass(DescribeTableEnhancedResponse.class) .withNonnullFields("response") .verify(); } }
4,343
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/mocktests/BatchGetTestUtils.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.mocktests; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import com.github.tomakehurst.wiremock.stubbing.Scenario; public class BatchGetTestUtils { private BatchGetTestUtils() { } static final String RESPONSE_WITHOUT_UNPROCESSED_KEYS = "{\"Responses\":{\"table\":[{\"id\":{\"N\":\"1\"}," + "\"value\":{\"N\":\"2\"}},{\"id\":{\"N\":\"2\"}," + "\"value\":{\"N\":\"0\"}},{\"id\":{\"N\":\"0\"}," + "\"value\":{\"N\":\"0\"}}]},\"UnprocessedKeys\":{}}"; static final String RESPONSE_WITH_UNPROCESSED_KEYS = "{\"Responses\":{\"table\":[{\"id\":{\"N\":\"1\"}," + "\"value\":{\"N\":\"2\"}},{\"id\":{\"N\":\"0\"}," + "\"value\":{\"N\":\"0\"}}]},\"UnprocessedKeys\":{\"table" + "\": {\"Keys\": [{\"id\": {\"N\": \"2\"}}]}}}"; static final String RESPONSE_WITH_UNPROCESSED_KEYS_PROCESSED = "{\"Responses\":{\"table\":[{\"id\":{\"N\":\"2\"}," + "\"value\":{\"N\":\"0\"}}]},\"UnprocessedKeys\":{}}"; static void stubSuccessfulResponse() { stubFor(post(anyUrl()) .willReturn(aResponse().withStatus(200).withBody(RESPONSE_WITHOUT_UNPROCESSED_KEYS))); } static void stubResponseWithUnprocessedKeys() { stubFor(post(anyUrl()) .inScenario("unprocessed keys") .whenScenarioStateIs(Scenario.STARTED) .willSetStateTo("first attempt") .willReturn(aResponse().withStatus(200) .withBody(RESPONSE_WITH_UNPROCESSED_KEYS))); stubFor(post(anyUrl()) .inScenario("unprocessed keys") .whenScenarioStateIs("first attempt") .willSetStateTo("second attempt") .willReturn(aResponse().withStatus(200) .withBody(RESPONSE_WITH_UNPROCESSED_KEYS_PROCESSED))); } static final class Record { private int id; Integer getId() { return id; } Record setId(Integer id) { this.id = id; return this; } } }
4,344
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/mocktests/AsyncBatchGetItemTest.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.mocktests; import static org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.enhanced.dynamodb.functionaltests.LocalDynamoDbAsyncTestBase.drainPublisher; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey; import static software.amazon.awssdk.enhanced.dynamodb.mocktests.BatchGetTestUtils.stubResponseWithUnprocessedKeys; import static software.amazon.awssdk.enhanced.dynamodb.mocktests.BatchGetTestUtils.stubSuccessfulResponse; import com.github.tomakehurst.wiremock.junit.WireMockRule; import java.net.URI; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.core.async.SdkPublisher; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbAsyncTable; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedAsyncClient; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema; import software.amazon.awssdk.enhanced.dynamodb.mocktests.BatchGetTestUtils.Record; import software.amazon.awssdk.enhanced.dynamodb.model.BatchGetResultPage; import software.amazon.awssdk.enhanced.dynamodb.model.BatchGetResultPagePublisher; import software.amazon.awssdk.enhanced.dynamodb.model.ReadBatch; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient; public class AsyncBatchGetItemTest { private DynamoDbEnhancedAsyncClient enhancedClient; private DynamoDbAsyncTable<Record> table; @Rule public WireMockRule wireMock = new WireMockRule(0); @Before public void setup() { DynamoDbAsyncClient dynamoDbClient = DynamoDbAsyncClient.builder() .region(Region.US_WEST_2) .credentialsProvider(() -> AwsBasicCredentials.create("foo", "bar")) .endpointOverride(URI.create("http://localhost:" + wireMock.port())) .endpointDiscoveryEnabled(false) .build(); enhancedClient = DynamoDbEnhancedAsyncClient.builder() .dynamoDbClient(dynamoDbClient) .build(); StaticTableSchema<Record> tableSchema = StaticTableSchema.builder(Record.class) .newItemSupplier(Record::new) .addAttribute(Integer.class, a -> a.name("id") .getter(Record::getId) .setter(Record::setId) .tags(primaryPartitionKey())) .build(); table = enhancedClient.table("table", tableSchema); } @After public void cleanup() { wireMock.resetAll(); } @Test public void successfulResponseWithoutUnprocessedKeys_NoNextPage() { stubSuccessfulResponse(); SdkPublisher<BatchGetResultPage> publisher = enhancedClient.batchGetItem(r -> r.readBatches( ReadBatch.builder(Record.class) .mappedTableResource(table) .build())); List<BatchGetResultPage> batchGetResultPages = drainPublisher(publisher, 1); assertThat(batchGetResultPages.size()).isEqualTo(1); assertThat(batchGetResultPages.get(0).resultsForTable(table).size()).isEqualTo(3); } @Test public void successfulResponseWithoutUnprocessedKeys_viaFlattenedItems_NoNextPage() { stubSuccessfulResponse(); BatchGetResultPagePublisher publisher = enhancedClient.batchGetItem(r -> r.readBatches( ReadBatch.builder(Record.class) .mappedTableResource(table) .build())); List<Record> records = drainPublisher(publisher.resultsForTable(table), 3); assertThat(records.size()).isEqualTo(3); } @Test public void responseWithUnprocessedKeys_iteratePage_shouldFetchUnprocessedKeys() throws InterruptedException { stubResponseWithUnprocessedKeys(); SdkPublisher<BatchGetResultPage> publisher = enhancedClient.batchGetItem(r -> r.readBatches( ReadBatch.builder(Record.class) .mappedTableResource(table) .build())); List<BatchGetResultPage> batchGetResultPages = drainPublisher(publisher, 2); assertThat(batchGetResultPages.size()).isEqualTo(2); assertThat(batchGetResultPages.get(0).resultsForTable(table).size()).isEqualTo(2); assertThat(batchGetResultPages.get(1).resultsForTable(table).size()).isEqualTo(1); assertThat(batchGetResultPages.size()).isEqualTo(2); } @Test public void responseWithUnprocessedKeys_iterateItems_shouldFetchUnprocessedKeys() throws InterruptedException { stubResponseWithUnprocessedKeys(); BatchGetResultPagePublisher publisher = enhancedClient.batchGetItem(r -> r.readBatches( ReadBatch.builder(Record.class) .mappedTableResource(table) .build())); List<Record> records = drainPublisher(publisher.resultsForTable(table), 3); assertThat(records.size()).isEqualTo(3); } }
4,345
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/mocktests/BatchGetItemTest.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.mocktests; import static org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey; import static software.amazon.awssdk.enhanced.dynamodb.mocktests.BatchGetTestUtils.stubResponseWithUnprocessedKeys; import static software.amazon.awssdk.enhanced.dynamodb.mocktests.BatchGetTestUtils.stubSuccessfulResponse; import com.github.tomakehurst.wiremock.junit.WireMockRule; import java.net.URI; import java.util.Iterator; import java.util.List; import java.util.stream.Collectors; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.core.pagination.sync.SdkIterable; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema; import software.amazon.awssdk.enhanced.dynamodb.mocktests.BatchGetTestUtils.Record; import software.amazon.awssdk.enhanced.dynamodb.model.BatchGetResultPage; import software.amazon.awssdk.enhanced.dynamodb.model.BatchGetResultPageIterable; import software.amazon.awssdk.enhanced.dynamodb.model.ReadBatch; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; public class BatchGetItemTest { private DynamoDbEnhancedClient enhancedClient; private DynamoDbTable<Record> table; @Rule public WireMockRule wireMock = new WireMockRule(0); @Before public void setup() { DynamoDbClient dynamoDbClient = DynamoDbClient.builder() .region(Region.US_WEST_2) .credentialsProvider(() -> AwsBasicCredentials.create("foo", "bar")) .endpointOverride(URI.create("http://localhost:" + wireMock.port())) .endpointDiscoveryEnabled(false) .build(); enhancedClient = DynamoDbEnhancedClient.builder() .dynamoDbClient(dynamoDbClient) .build(); StaticTableSchema<Record> tableSchema = StaticTableSchema.builder(Record.class) .newItemSupplier(Record::new) .addAttribute(Integer.class, a -> a.name("id") .getter(Record::getId) .setter(Record::setId) .tags(primaryPartitionKey())) .build(); table = enhancedClient.table("table", tableSchema); } @Test public void successfulResponseWithoutUnprocessedKeys_NoNextPage() { stubSuccessfulResponse(); SdkIterable<BatchGetResultPage> batchGetResultPages = enhancedClient.batchGetItem(r -> r.readBatches( ReadBatch.builder(Record.class) .mappedTableResource(table) .addGetItem(i -> i.key(k -> k.partitionValue(0))) .build())); List<BatchGetResultPage> pages = batchGetResultPages.stream().collect(Collectors.toList()); assertThat(pages.size()).isEqualTo(1); } @Test public void successfulResponseWithoutUnprocessedKeys_NoNextPage_viaFlattenedItems() { stubSuccessfulResponse(); BatchGetResultPageIterable batchGetResultPages = enhancedClient.batchGetItem(r -> r.readBatches( ReadBatch.builder(Record.class) .mappedTableResource(table) .addGetItem(i -> i.key(k -> k.partitionValue(0))) .build())); assertThat(batchGetResultPages.resultsForTable(table)).hasSize(3); } @Test public void responseWithUnprocessedKeys_iteratePage_shouldFetchUnprocessedKeys() { stubResponseWithUnprocessedKeys(); SdkIterable<BatchGetResultPage> batchGetResultPages = enhancedClient.batchGetItem(r -> r.readBatches( ReadBatch.builder(Record.class) .mappedTableResource(table) .addGetItem(i -> i.key(k -> k.partitionValue("1"))) .build())); Iterator<BatchGetResultPage> iterator = batchGetResultPages.iterator(); BatchGetResultPage firstPage = iterator.next(); List<Record> resultsForTable = firstPage.resultsForTable(table); assertThat(resultsForTable.size()).isEqualTo(2); BatchGetResultPage secondPage = iterator.next(); assertThat(secondPage.resultsForTable(table).size()).isEqualTo(1); assertThat(iterator).isExhausted(); } @Test public void responseWithUnprocessedKeys_iterateItems_shouldFetchUnprocessedKeys() { stubResponseWithUnprocessedKeys(); BatchGetResultPageIterable batchGetResultPages = enhancedClient.batchGetItem(r -> r.readBatches( ReadBatch.builder(Record.class) .mappedTableResource(table) .addGetItem(i -> i.key(k -> k.partitionValue("1"))) .build())); SdkIterable<Record> results = batchGetResultPages.resultsForTable(table); assertThat(results.stream().count()).isEqualTo(3); } }
4,346
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/it/java/software/amazon/awssdk/enhanced
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/it/java/software/amazon/awssdk/enhanced/dynamodb/ScanQueryIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.numberValue; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.stringValue; import static software.amazon.awssdk.enhanced.dynamodb.model.QueryConditional.sortBetween; import static software.amazon.awssdk.enhanced.dynamodb.model.QueryConditional.sortGreaterThan; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; 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.enhanced.dynamodb.model.Record; 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.ConsumedCapacity; import software.amazon.awssdk.services.dynamodb.model.ReturnConsumedCapacity; public class ScanQueryIntegrationTest extends DynamoDbEnhancedIntegrationTestBase { private static final String TABLE_NAME = createTestTableName(); private static DynamoDbClient dynamoDbClient; private static DynamoDbEnhancedClient enhancedClient; private static DynamoDbTable<Record> mappedTable; @BeforeClass public static void setup() { dynamoDbClient = createDynamoDbClient(); enhancedClient = DynamoDbEnhancedClient.builder().dynamoDbClient(dynamoDbClient).build(); mappedTable = enhancedClient.table(TABLE_NAME, TABLE_SCHEMA); mappedTable.createTable(); dynamoDbClient.waiter().waitUntilTableExists(r -> r.tableName(TABLE_NAME)); } @AfterClass public static void teardown() { try { dynamoDbClient.deleteTable(r -> r.tableName(TABLE_NAME)); } finally { dynamoDbClient.close(); } } private void insertRecords() { RECORDS.forEach(record -> mappedTable.putItem(r -> r.item(record))); } @Test public void scan_withoutReturnConsumedCapacity_checksPageCount() { insertRecords(); Iterator<Page<Record>> results = mappedTable.scan(ScanEnhancedRequest.builder().limit(5).build()) .iterator(); Page<Record> page1 = results.next(); assertThat(results.hasNext(), is(true)); Page<Record> page2 = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page1.items(), is(RECORDS.subList(0, 5))); assertThat(page1.consumedCapacity(), is(nullValue())); assertThat(page1.lastEvaluatedKey(), is(getKeyMap(4))); assertThat(page1.count(), equalTo(5)); assertThat(page1.scannedCount(), equalTo(5)); assertThat(page2.items(), is(RECORDS.subList(5, 9))); assertThat(page2.lastEvaluatedKey(), is(nullValue())); assertThat(page2.count(), equalTo(4)); assertThat(page2.scannedCount(), equalTo(4)); } @Test public void scan_withReturnConsumedCapacityAndDifferentReadConsistency_checksConsumedCapacity() { insertRecords(); Iterator<Page<Record>> eventualConsistencyResult = mappedTable.scan(ScanEnhancedRequest.builder().returnConsumedCapacity(ReturnConsumedCapacity.TOTAL).build()) .iterator(); Page<Record> page = eventualConsistencyResult.next(); assertThat(eventualConsistencyResult.hasNext(), is(false)); ConsumedCapacity eventualConsumedCapacity = page.consumedCapacity(); assertThat(eventualConsumedCapacity, is(notNullValue())); Iterator<Page<Record>> strongConsistencyResult = mappedTable.scan(ScanEnhancedRequest.builder().returnConsumedCapacity(ReturnConsumedCapacity.TOTAL).build()) .iterator(); page = strongConsistencyResult.next(); assertThat(strongConsistencyResult.hasNext(), is(false)); ConsumedCapacity strongConsumedCapacity = page.consumedCapacity(); assertThat(strongConsumedCapacity, is(notNullValue())); assertThat(strongConsumedCapacity.capacityUnits(), is(greaterThanOrEqualTo(eventualConsumedCapacity.capacityUnits()))); } @Test public void query_withoutReturnConsumedCapacity_checksPageCount() { insertRecords(); Iterator<Page<Record>> results = mappedTable.query(QueryEnhancedRequest.builder() .queryConditional(sortBetween(k-> k.partitionValue("id-value").sortValue(2), k-> k.partitionValue("id-value").sortValue(6))) .limit(3) .build()) .iterator(); Page<Record> page1 = results.next(); assertThat(results.hasNext(), is(true)); Page<Record> page2 = results.next(); assertThat(results.hasNext(), is(false)); assertThat(page1.items(), is(RECORDS.subList(2, 5))); assertThat(page1.consumedCapacity(), is(nullValue())); assertThat(page1.lastEvaluatedKey(), is(getKeyMap(4))); assertThat(page1.count(), equalTo(3)); assertThat(page1.scannedCount(), equalTo(3)); assertThat(page2.items(), is(RECORDS.subList(5, 7))); assertThat(page2.lastEvaluatedKey(), is(nullValue())); assertThat(page2.count(), equalTo(2)); assertThat(page2.scannedCount(), equalTo(2)); } @Test public void query_withReturnConsumedCapacityAndDifferentReadConsistency_checksConsumedCapacity() { insertRecords(); Iterator<Page<Record>> eventualConsistencyResult = mappedTable.query(QueryEnhancedRequest.builder() .queryConditional(sortGreaterThan(k -> k.partitionValue("id-value").sortValue(3))) .returnConsumedCapacity(ReturnConsumedCapacity.TOTAL) .build()) .iterator(); Page<Record> page = eventualConsistencyResult.next(); assertThat(eventualConsistencyResult.hasNext(), is(false)); ConsumedCapacity eventualConsumedCapacity = page.consumedCapacity(); assertThat(eventualConsumedCapacity, is(notNullValue())); Iterator<Page<Record>> strongConsistencyResult = mappedTable.query(QueryEnhancedRequest.builder() .queryConditional(sortGreaterThan(k -> k.partitionValue("id-value").sortValue(3))) .returnConsumedCapacity(ReturnConsumedCapacity.TOTAL) .build()) .iterator(); page = strongConsistencyResult.next(); assertThat(strongConsistencyResult.hasNext(), is(false)); ConsumedCapacity strongConsumedCapacity = page.consumedCapacity(); assertThat(strongConsumedCapacity, is(notNullValue())); assertThat(strongConsumedCapacity.capacityUnits(), is(greaterThanOrEqualTo(eventualConsumedCapacity.capacityUnits()))); } private Map<String, AttributeValue> getKeyMap(int sort) { Map<String, AttributeValue> result = new HashMap<>(); result.put("id", stringValue(RECORDS.get(sort).getId())); result.put("sort", numberValue(RECORDS.get(sort).getSort())); return Collections.unmodifiableMap(result); } }
4,347
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/it/java/software/amazon/awssdk/enhanced
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/it/java/software/amazon/awssdk/enhanced/dynamodb/AsyncCrudWithResponseIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb; import static org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.secondaryPartitionKey; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.secondarySortKey; import org.assertj.core.data.Offset; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import software.amazon.awssdk.enhanced.dynamodb.model.DeleteItemEnhancedResponse; import software.amazon.awssdk.enhanced.dynamodb.model.EnhancedLocalSecondaryIndex; import software.amazon.awssdk.enhanced.dynamodb.model.GetItemEnhancedResponse; import software.amazon.awssdk.enhanced.dynamodb.model.PutItemEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.PutItemEnhancedResponse; import software.amazon.awssdk.enhanced.dynamodb.model.Record; import software.amazon.awssdk.enhanced.dynamodb.model.UpdateItemEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.UpdateItemEnhancedResponse; import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient; import software.amazon.awssdk.services.dynamodb.model.ConsumedCapacity; import software.amazon.awssdk.services.dynamodb.model.Projection; import software.amazon.awssdk.services.dynamodb.model.ProjectionType; import software.amazon.awssdk.services.dynamodb.model.ReturnConsumedCapacity; import software.amazon.awssdk.services.dynamodb.model.ReturnItemCollectionMetrics; public class AsyncCrudWithResponseIntegrationTest extends DynamoDbEnhancedIntegrationTestBase { private static final String TABLE_NAME = createTestTableName(); private static final EnhancedLocalSecondaryIndex LOCAL_SECONDARY_INDEX = EnhancedLocalSecondaryIndex.builder() .indexName("index1") .projection(Projection.builder() .projectionType(ProjectionType.ALL) .build()) .build(); private static DynamoDbAsyncClient dynamoDbClient; private static DynamoDbEnhancedAsyncClient enhancedClient; private static DynamoDbAsyncTable<Record> mappedTable; @BeforeClass public static void setup() { dynamoDbClient = createAsyncDynamoDbClient(); enhancedClient = DynamoDbEnhancedAsyncClient.builder().dynamoDbClient(dynamoDbClient).build(); mappedTable = enhancedClient.table(TABLE_NAME, TABLE_SCHEMA); mappedTable.createTable(r -> r.localSecondaryIndices(LOCAL_SECONDARY_INDEX)).join(); dynamoDbClient.waiter().waitUntilTableExists(r -> r.tableName(TABLE_NAME)).join(); } @AfterClass public static void teardown() { try { dynamoDbClient.deleteTable(r -> r.tableName(TABLE_NAME)).join(); } finally { dynamoDbClient.close(); } } @Test public void putItem_returnItemCollectionMetrics_set_itemCollectionMetricsNull() { Record record = new Record().setId("1").setSort(10); PutItemEnhancedRequest<Record> request = PutItemEnhancedRequest.builder(Record.class) .item(record) .build(); PutItemEnhancedResponse<Record> response = mappedTable.putItemWithResponse(request).join(); assertThat(response.itemCollectionMetrics()).isNull(); } @Test public void putItem_returnItemCollectionMetrics_set_itemCollectionMetricsNotNull() { Record record = new Record().setId("1").setSort(10); PutItemEnhancedRequest<Record> request = PutItemEnhancedRequest.builder(Record.class) .item(record) .returnItemCollectionMetrics(ReturnItemCollectionMetrics.SIZE) .build(); PutItemEnhancedResponse<Record> response = mappedTable.putItemWithResponse(request).join(); assertThat(response.itemCollectionMetrics()).isNotNull(); } @Test public void updateItem_returnItemCollectionMetrics_set_itemCollectionMetricsNull() { Record record = new Record().setId("1").setSort(10); UpdateItemEnhancedRequest<Record> request = UpdateItemEnhancedRequest.builder(Record.class) .item(record) .build(); UpdateItemEnhancedResponse<Record> response = mappedTable.updateItemWithResponse(request).join(); assertThat(response.itemCollectionMetrics()).isNull(); } @Test public void updateItem_returnItemCollectionMetrics_set_itemCollectionMetricsNotNull() { Record record = new Record().setId("1").setSort(10); UpdateItemEnhancedRequest<Record> request = UpdateItemEnhancedRequest.builder(Record.class) .item(record) .returnItemCollectionMetrics(ReturnItemCollectionMetrics.SIZE) .build(); UpdateItemEnhancedResponse<Record> response = mappedTable.updateItemWithResponse(request).join(); assertThat(response.itemCollectionMetrics()).isNotNull(); } @Test public void deleteItem_returnConsumedCapacity_unset_consumedCapacityNull() { Key key = Key.builder().partitionValue("1").sortValue(10).build(); DeleteItemEnhancedResponse<Record> response = mappedTable.deleteItemWithResponse(r -> r.key(key)).join(); assertThat(response.consumedCapacity()).isNull(); } @Test public void deleteItem_returnConsumedCapacity_set_consumedCapacityNotNull() { Key key = Key.builder().partitionValue("1").sortValue(10).build(); DeleteItemEnhancedResponse<Record> response = mappedTable.deleteItemWithResponse(r -> r.key(key).returnConsumedCapacity(ReturnConsumedCapacity.TOTAL)).join(); assertThat(response.consumedCapacity()).isNotNull(); } @Test public void delete_returnItemCollectionMetrics_set_itemCollectionMetricsNotNull() { Key key = Key.builder().partitionValue("1").sortValue(10).build(); DeleteItemEnhancedResponse<Record> response = mappedTable.deleteItemWithResponse(r -> r.key(key).returnItemCollectionMetrics(ReturnItemCollectionMetrics.SIZE)) .join(); assertThat(response.itemCollectionMetrics()).isNotNull(); } @Test public void getItem_withoutReturnConsumedCapacity() { Record record = new Record().setId("101").setSort(102).setStringAttribute(getStringAttrValue(80_000)); Key key = Key.builder() .partitionValue(record.getId()) .sortValue(record.getSort()) .build(); GetItemEnhancedResponse<Record> response = mappedTable.getItemWithResponse(req -> req.key(key)).join(); assertThat(response.consumedCapacity()).isNull(); } }
4,348
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/it/java/software/amazon/awssdk/enhanced
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/it/java/software/amazon/awssdk/enhanced/dynamodb/DynamoDbEnhancedIntegrationTestBase.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primarySortKey; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.secondaryPartitionKey; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.secondarySortKey; import java.util.Arrays; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; import java.util.stream.IntStream; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema; import software.amazon.awssdk.enhanced.dynamodb.model.Record; import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.testutils.service.AwsIntegrationTestBase; public abstract class DynamoDbEnhancedIntegrationTestBase extends AwsIntegrationTestBase { protected static String createTestTableName() { return UUID.randomUUID() + "-ddb-enhanced-integ-test"; } protected static DynamoDbClient createDynamoDbClient() { return DynamoDbClient.builder() .credentialsProvider(getCredentialsProvider()) .build(); } protected static DynamoDbAsyncClient createAsyncDynamoDbClient() { return DynamoDbAsyncClient.builder() .credentialsProvider(getCredentialsProvider()) .build(); } protected static final TableSchema<Record> TABLE_SCHEMA = StaticTableSchema.builder(Record.class) .newItemSupplier(Record::new) .addAttribute(String.class, a -> a.name("id") .getter(Record::getId) .setter(Record::setId) .tags(primaryPartitionKey(), secondaryPartitionKey("index1"))) .addAttribute(Integer.class, a -> a.name("sort") .getter(Record::getSort) .setter(Record::setSort) .tags(primarySortKey(), secondarySortKey("index1"))) .addAttribute(Integer.class, a -> a.name("value") .getter(Record::getValue) .setter(Record::setValue)) .addAttribute(String.class, a -> a.name("gsi_id") .getter(Record::getGsiId) .setter(Record::setGsiId) .tags(secondaryPartitionKey("gsi_keys_only"))) .addAttribute(Integer.class, a -> a.name("gsi_sort") .getter(Record::getGsiSort) .setter(Record::setGsiSort) .tags(secondarySortKey("gsi_keys_only"))) .addAttribute(String.class, a -> a.name("stringAttribute") .getter(Record::getStringAttribute) .setter(Record::setStringAttribute)) .build(); protected static final List<Record> RECORDS = IntStream.range(0, 9) .mapToObj(i -> new Record() .setId("id-value") .setSort(i) .setValue(i) .setStringAttribute(getStringAttrValue(10 * 1024)) .setGsiId("gsi-id-value") .setGsiSort(i)) .collect(Collectors.toList()); protected static final List<Record> KEYS_ONLY_RECORDS = RECORDS.stream() .map(record -> new Record() .setId(record.getId()) .setSort(record.getSort()) .setGsiId(record.getGsiId()) .setGsiSort(record.getGsiSort())) .collect(Collectors.toList()); protected static String getStringAttrValue(int numChars) { char[] chars = new char[numChars]; Arrays.fill(chars, 'a'); return new String(chars); } }
4,349
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/it/java/software/amazon/awssdk/enhanced
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/it/java/software/amazon/awssdk/enhanced/dynamodb/CrudWithResponseIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb; import static org.assertj.core.api.Assertions.assertThat; import org.assertj.core.data.Offset; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import software.amazon.awssdk.enhanced.dynamodb.model.DeleteItemEnhancedResponse; import software.amazon.awssdk.enhanced.dynamodb.model.EnhancedLocalSecondaryIndex; import software.amazon.awssdk.enhanced.dynamodb.model.GetItemEnhancedResponse; import software.amazon.awssdk.enhanced.dynamodb.model.PutItemEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.PutItemEnhancedResponse; import software.amazon.awssdk.enhanced.dynamodb.model.Record; import software.amazon.awssdk.enhanced.dynamodb.model.UpdateItemEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.UpdateItemEnhancedResponse; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.ConsumedCapacity; import software.amazon.awssdk.services.dynamodb.model.Projection; import software.amazon.awssdk.services.dynamodb.model.ProjectionType; import software.amazon.awssdk.services.dynamodb.model.ReturnConsumedCapacity; import software.amazon.awssdk.services.dynamodb.model.ReturnItemCollectionMetrics; public class CrudWithResponseIntegrationTest extends DynamoDbEnhancedIntegrationTestBase { private static final String TABLE_NAME = createTestTableName(); private static final EnhancedLocalSecondaryIndex LOCAL_SECONDARY_INDEX = EnhancedLocalSecondaryIndex.builder() .indexName("index1") .projection(Projection.builder() .projectionType(ProjectionType.ALL) .build()) .build(); private static DynamoDbClient dynamoDbClient; private static DynamoDbEnhancedClient enhancedClient; private static DynamoDbTable<Record> mappedTable; @BeforeClass public static void setup() { dynamoDbClient = createDynamoDbClient(); enhancedClient = DynamoDbEnhancedClient.builder().dynamoDbClient(dynamoDbClient).build(); mappedTable = enhancedClient.table(TABLE_NAME, TABLE_SCHEMA); mappedTable.createTable(r -> r.localSecondaryIndices(LOCAL_SECONDARY_INDEX)); dynamoDbClient.waiter().waitUntilTableExists(r -> r.tableName(TABLE_NAME)); } @AfterClass public static void teardown() { try { dynamoDbClient.deleteTable(r -> r.tableName(TABLE_NAME)); } finally { dynamoDbClient.close(); } } @Test public void putItem_set_requestedMetadataNull() { Record record = new Record().setId("1").setSort(10); PutItemEnhancedResponse<Record> response = mappedTable.putItemWithResponse(r -> r.item(record)); assertThat(response.itemCollectionMetrics()).isNull(); assertThat(response.consumedCapacity()).isNull(); } @Test public void putItem_set_requestedMetadataNotNull() { Record record = new Record().setId("1").setSort(10); PutItemEnhancedRequest<Record> request = PutItemEnhancedRequest.builder(Record.class) .item(record) .returnItemCollectionMetrics(ReturnItemCollectionMetrics.SIZE) .returnConsumedCapacity(ReturnConsumedCapacity.TOTAL) .build(); PutItemEnhancedResponse<Record> response = mappedTable.putItemWithResponse(request); assertThat(response.itemCollectionMetrics()).isNotNull(); assertThat(response.consumedCapacity()).isNotNull(); assertThat(response.consumedCapacity().capacityUnits()).isNotNull(); } @Test public void updateItem_set_requestedMetadataNull() { Record record = new Record().setId("1").setSort(10); UpdateItemEnhancedResponse<Record> response = mappedTable.updateItemWithResponse(r -> r.item(record)); assertThat(response.itemCollectionMetrics()).isNull(); assertThat(response.consumedCapacity()).isNull(); } @Test public void updateItem_set_itemCollectionMetricsNotNull() { Record record = new Record().setId("1").setSort(10); UpdateItemEnhancedRequest<Record> request = UpdateItemEnhancedRequest.builder(Record.class) .item(record) .returnItemCollectionMetrics(ReturnItemCollectionMetrics.SIZE) .returnConsumedCapacity(ReturnConsumedCapacity.TOTAL) .build(); UpdateItemEnhancedResponse<Record> response = mappedTable.updateItemWithResponse(request); assertThat(response.itemCollectionMetrics()).isNotNull(); assertThat(response.consumedCapacity()).isNotNull(); assertThat(response.consumedCapacity().capacityUnits()).isNotNull(); } @Test public void deleteItem__unset_consumedCapacityNull() { Key key = Key.builder().partitionValue("1").sortValue(10).build(); DeleteItemEnhancedResponse<Record> response = mappedTable.deleteItemWithResponse(r -> r.key(key)); assertThat(response.consumedCapacity()).isNull(); } @Test public void deleteItem__set_consumedCapacityNotNull() { Key key = Key.builder().partitionValue("1").sortValue(10).build(); DeleteItemEnhancedResponse<Record> response = mappedTable.deleteItemWithResponse(r -> r.key(key) .returnItemCollectionMetrics(ReturnItemCollectionMetrics.SIZE) .returnConsumedCapacity(ReturnConsumedCapacity.TOTAL)); assertThat(response.consumedCapacity()).isNotNull(); } @Test public void getItem_set_requestedMetadataNull() { Record record = new Record().setId("101").setSort(102).setStringAttribute(getStringAttrValue(80_000)); Key key = Key.builder() .partitionValue(record.getId()) .sortValue(record.getSort()) .build(); mappedTable.putItem(record); GetItemEnhancedResponse<Record> response = mappedTable.getItemWithResponse(req -> req.key(key)); assertThat(response.consumedCapacity()).isNull(); } @Test public void getItem_set_eventualConsistent() { Record record = new Record().setId("101").setSort(102).setStringAttribute(getStringAttrValue(80 * 1024)); Key key = Key.builder() .partitionValue(record.getId()) .sortValue(record.getSort()) .build(); mappedTable.putItem(record); GetItemEnhancedResponse<Record> response = mappedTable.getItemWithResponse( req -> req.key(key).returnConsumedCapacity(ReturnConsumedCapacity.TOTAL) ); ConsumedCapacity consumedCapacity = response.consumedCapacity(); assertThat(consumedCapacity).isNotNull(); // An eventually consistent read request of an item up to 4 KB requires one-half read request unit. assertThat(consumedCapacity.capacityUnits()).isCloseTo(10.0, Offset.offset(1.0)); } @Test public void getItem_set_stronglyConsistent() { Record record = new Record().setId("101").setSort(102).setStringAttribute(getStringAttrValue(80 * 1024)); Key key = Key.builder() .partitionValue(record.getId()) .sortValue(record.getSort()) .build(); mappedTable.putItem(record); GetItemEnhancedResponse<Record> response = mappedTable.getItemWithResponse( req -> req.key(key).returnConsumedCapacity(ReturnConsumedCapacity.TOTAL).consistentRead(true) ); ConsumedCapacity consumedCapacity = response.consumedCapacity(); assertThat(consumedCapacity).isNotNull(); // A strongly consistent read request of an item up to 4 KB requires one read request unit. assertThat(consumedCapacity.capacityUnits()).isCloseTo(20.0, Offset.offset(1.0)); } }
4,350
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/it/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/it/java/software/amazon/awssdk/enhanced/dynamodb/model/Record.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.model; import java.util.Objects; public class Record { private String id; private Integer sort; private Integer value; private String gsiId; private Integer gsiSort; private String stringAttribute; public String getId() { return id; } public Record setId(String id) { this.id = id; return this; } public Integer getSort() { return sort; } public Record setSort(Integer sort) { this.sort = sort; return this; } public Integer getValue() { return value; } public Record setValue(Integer value) { this.value = value; return this; } public String getGsiId() { return gsiId; } public Record setGsiId(String gsiId) { this.gsiId = gsiId; return this; } public Integer getGsiSort() { return gsiSort; } public Record setGsiSort(Integer gsiSort) { this.gsiSort = gsiSort; return this; } public String getStringAttribute() { return stringAttribute; } public Record setStringAttribute(String stringAttribute) { this.stringAttribute = stringAttribute; return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Record record = (Record) o; return Objects.equals(id, record.id) && Objects.equals(sort, record.sort) && Objects.equals(value, record.value) && Objects.equals(gsiId, record.gsiId) && Objects.equals(stringAttribute, record.stringAttribute) && Objects.equals(gsiSort, record.gsiSort); } @Override public int hashCode() { return Objects.hash(id, sort, value, gsiId, gsiSort, stringAttribute); } }
4,351
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/EnumAttributeConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import java.util.function.Function; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.utils.Validate; /** * A converter between an {@link Enum} and {@link AttributeValue}. * * <p> * This stores values in DynamoDB as a string. * * <p> * Use EnumAttributeConverter::create in order to use Enum::toString as the enum identifier * * <p> * Use EnumAttributeConverter::createWithNameAsKeys in order to use Enum::name as the enum identifier * * <p> * This can be created via {@link #create(Class)}. */ @SdkPublicApi public final class EnumAttributeConverter<T extends Enum<T>> implements AttributeConverter<T> { private final Class<T> enumClass; private final Map<String, T> enumValueMap; private final Function<T, String> keyExtractor; private EnumAttributeConverter(Class<T> enumClass, Function<T, String> keyExtractor) { this.enumClass = enumClass; this.keyExtractor = keyExtractor; Map<String, T> mutableEnumValueMap = new LinkedHashMap<>(); Arrays.stream(enumClass.getEnumConstants()) .forEach(enumConstant -> mutableEnumValueMap.put(keyExtractor.apply(enumConstant), enumConstant)); this.enumValueMap = Collections.unmodifiableMap(mutableEnumValueMap); } /** * Creates an EnumAttributeConverter for an {@link Enum}. * * <p> * Uses Enum::toString as the enum identifier. * * @param enumClass The enum class to be used * @return an EnumAttributeConverter * @param <T> the enum subclass */ public static <T extends Enum<T>> EnumAttributeConverter<T> create(Class<T> enumClass) { return new EnumAttributeConverter<>(enumClass, Enum::toString); } /** * Creates an EnumAttributeConverter for an {@link Enum}. * * <p> * Uses Enum::name as the enum identifier. * * @param enumClass The enum class to be used * @return an EnumAttributeConverter * @param <T> the enum subclass */ public static <T extends Enum<T>> EnumAttributeConverter<T> createWithNameAsKeys(Class<T> enumClass) { return new EnumAttributeConverter<>(enumClass, Enum::name); } /** * Returns the proper {@link AttributeValue} for the given enum type. * * @param input the enum type to be converted * @return AttributeValue */ @Override public AttributeValue transformFrom(T input) { return AttributeValue.builder().s(keyExtractor.apply(input)).build(); } /** * Returns the proper enum type for the given {@link AttributeValue} input. * * @param input the AttributeValue to be converted * @return an enum type */ @Override public T transformTo(AttributeValue input) { Validate.isTrue(input.s() != null, "Cannot convert non-string value to enum."); T returnValue = enumValueMap.get(input.s()); if (returnValue == null) { throw new IllegalArgumentException(String.format("Unable to convert string value '%s' to enum type '%s'", input.s(), enumClass)); } return returnValue; } /** * Returns the {@link EnhancedType} of the converter. * * @return EnhancedType */ @Override public EnhancedType<T> type() { return EnhancedType.of(enumClass); } /** * Returns the {@link AttributeValueType} of the converter. * * @return AttributeValueType */ @Override public AttributeValueType attributeValueType() { return AttributeValueType.S; } }
4,352
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/DynamoDbEnhancedClient.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb; import java.util.List; import java.util.function.Consumer; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.core.pagination.sync.SdkIterable; import software.amazon.awssdk.enhanced.dynamodb.internal.client.DefaultDynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.model.BatchGetItemEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.BatchGetResultPage; import software.amazon.awssdk.enhanced.dynamodb.model.BatchGetResultPageIterable; import software.amazon.awssdk.enhanced.dynamodb.model.BatchWriteItemEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.BatchWriteResult; import software.amazon.awssdk.enhanced.dynamodb.model.ConditionCheck; import software.amazon.awssdk.enhanced.dynamodb.model.DeleteItemEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.GetItemEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.PutItemEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.TransactGetItemsEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.TransactWriteItemsEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.UpdateItemEnhancedRequest; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.BatchGetItemRequest; /** * Synchronous interface for running commands against a DynamoDb database. * <p> * By default, all command methods throw an {@link UnsupportedOperationException} to prevent interface extensions from breaking * implementing classes. */ @SdkPublicApi @ThreadSafe public interface DynamoDbEnhancedClient extends DynamoDbEnhancedResource { /** * Returns a mapped table that can be used to execute commands that work with mapped items against that table. * * @param tableName The name of the physical table persisted by DynamoDb. * @param tableSchema A {@link TableSchema} that maps the table to a modelled object. * @return A {@link DynamoDbTable} object that can be used to execute table operations against. * @param <T> The modelled object type being mapped to this table. */ <T> DynamoDbTable<T> table(String tableName, TableSchema<T> tableSchema); /** * Retrieves items from one or more tables by their primary keys, see {@link Key}. BatchGetItem is a composite operation * where the request contains one batch of {@link GetItemEnhancedRequest} per targeted table. * The operation makes several calls to the database; each time you iterate over the result to retrieve a page, * a call is made for the items on that page. * <p> * The additional configuration parameters that the enhanced client supports are defined * in the {@link BatchGetItemEnhancedRequest}. * <p> * <b>Partial results</b>. A single call to DynamoDb has restraints on how much data can be retrieved. * If those limits are exceeded, the call yields a partial result. This may also be the case if * provisional throughput is exceeded or there is an internal DynamoDb processing failure. The operation automatically * retries any unprocessed keys returned from DynamoDb in subsequent calls for pages. * <p> * This operation calls the low-level {@link DynamoDbClient#batchGetItemPaginator} operation. Consult the BatchGetItem * documentation for further details and constraints as well as current limits of data retrieval. * <p> * Example: * <pre> * {@code * * BatchGetResultPageIterable batchResults = enhancedClient.batchGetItem( * BatchGetItemEnhancedRequest.builder() * .readBatches(ReadBatch.builder(FirstItem.class) * .mappedTableResource(firstItemTable) * .addGetItem(GetItemEnhancedRequest.builder().key(key1).build()) * .addGetItem(GetItemEnhancedRequest.builder().key(key2).build()) * .build(), * ReadBatch.builder(SecondItem.class) * .mappedTableResource(secondItemTable) * .addGetItem(GetItemEnhancedRequest.builder().key(key3).build()) * .build()) * .build()); * } * </pre> * * <p> * The result can be accessed either through iterable {@link BatchGetResultPage}s or flattened results belonging to the * supplied table across all pages. * * <p> * 1) Iterating through pages * <pre> * {@code * batchResults.forEach(page -> { * page.resultsForTable(firstItemTable).forEach(item -> System.out.println(item)); * page.resultsForTable(secondItemTable).forEach(item -> System.out.println(item)); * }); * } * </pre> * * <p> * 2) Iterating through results across all pages * <pre> * {@code * results.resultsForTable(firstItemTable).forEach(item -> System.out.println(item)); * results.resultsForTable(secondItemTable).forEach(item -> System.out.println(item)); * } * </pre> * * @param request A {@link BatchGetItemEnhancedRequest} containing keys grouped by tables. * @return an iterator of type {@link SdkIterable} with paginated results of type {@link BatchGetResultPage}. * @see #batchGetItem(Consumer) * @see DynamoDbClient#batchGetItemPaginator */ default BatchGetResultPageIterable batchGetItem(BatchGetItemEnhancedRequest request) { throw new UnsupportedOperationException(); } /** * Retrieves items from one or more tables by their primary keys, see {@link Key}. BatchGetItem is a composite operation * where the request contains one batch of {@link GetItemEnhancedRequest} per targeted table. * The operation makes several calls to the database; each time you iterate over the result to retrieve a page, * a call is made for the items on that page. * <p> * <b>Note:</b> This is a convenience method that creates an instance of the request builder avoiding the need to create one * manually via {@link BatchGetItemEnhancedRequest#builder()}. * <p> * Example: * <pre> * {@code * * BatchGetResultPageIterable batchResults = enhancedClient.batchGetItem(r -> r.addReadBatches( * ReadBatch.builder(FirstItem.class) * .mappedTableResource(firstItemTable) * .addGetItem(i -> i.key(key1)) * .addGetItem(i -> i.key(key2)) * .build(), * ReadBatch.builder(SecondItem.class) * .mappedTableResource(secondItemTable) * .addGetItem(i -> i.key(key3)) * .build())); * } * </pre> * * @param requestConsumer a {@link Consumer} of {@link BatchGetItemEnhancedRequest.Builder} containing keys grouped by tables. * @return an iterator of type {@link SdkIterable} with paginated results of type {@link BatchGetResultPage}. * @see #batchGetItem(BatchGetItemEnhancedRequest) * @see DynamoDbClient#batchGetItemPaginator(BatchGetItemRequest) */ default BatchGetResultPageIterable batchGetItem(Consumer<BatchGetItemEnhancedRequest.Builder> requestConsumer) { throw new UnsupportedOperationException(); } /** * Puts and/or deletes multiple items in one or more tables. BatchWriteItem is a composite operation where the request * contains one batch of (a mix of) {@link PutItemEnhancedRequest} and {@link DeleteItemEnhancedRequest} per targeted table. * <p> * The additional configuration parameters that the enhanced client supports are defined * in the {@link BatchWriteItemEnhancedRequest}. * <p> * A single call to BatchWriteItem has the same limit of items as the low-level DynamoDB API BatchWriteItem operation, * considering all items across all WriteBatches. * <p> * <b>Note: </b> BatchWriteItem cannot update items. Instead, use the individual updateItem operation * {@link DynamoDbTable#updateItem(UpdateItemEnhancedRequest)}. * <p> * <b>Partial updates</b><br>Each delete or put call is atomic, but the operation as a whole is not. * If individual operations fail due to exceeded provisional throughput internal DynamoDb processing failures, * the failed requests can be retrieved through the result, see {@link BatchWriteResult}. * <p> * There are some conditions that cause the whole batch operation to fail. These include non-existing tables, erroneously * defined primary key attributes, attempting to put and delete the same item as well as referring more than once to the same * hash and range (sort) key. * <p> * This operation calls the low-level DynamoDB API BatchWriteItem operation. Consult the BatchWriteItem documentation for * further details and constraints, current limits of data to write and/or delete, how to handle partial updates and retries * and under which conditions the operation will fail. * <p> * Example: * <pre> * {@code * * BatchWriteResult batchResult = enhancedClient.batchWriteItem( * BatchWriteItemEnhancedRequest.builder() * .writeBatches(WriteBatch.builder(FirstItem.class) * .mappedTableResource(firstItemTable) * .addPutItem(PutItemEnhancedRequest.builder().item(item1).build()) * .addDeleteItem(DeleteItemEnhancedRequest.builder() * .key(key2) * .build()) * .build(), * WriteBatch.builder(SecondItem.class) * .mappedTableResource(secondItemTable) * .addPutItem(PutItemEnhancedRequest.builder().item(item3).build()) * .build()) * .build()); * } * </pre> * * @param request A {@link BatchWriteItemEnhancedRequest} containing keys and items grouped by tables. * @return a {@link BatchWriteResult} containing any unprocessed requests. */ default BatchWriteResult batchWriteItem(BatchWriteItemEnhancedRequest request) { throw new UnsupportedOperationException(); } /** * Puts and/or deletes multiple items in one or more tables. BatchWriteItem is a composite operation where the request * contains one batch of (a mix of) {@link PutItemEnhancedRequest} and {@link DeleteItemEnhancedRequest} per targeted table. * <p> * The additional configuration parameters that the enhanced client supports are defined * in the {@link BatchWriteItemEnhancedRequest}. * <p> * A single call to BatchWriteItem has the same limit of items as the low-level DynamoDB API BatchWriteItem operation, * considering all items across all WriteBatches. * <p> * <b>Note: </b> BatchWriteItem cannot update items. Instead, use the individual updateItem operation * {@link DynamoDbTable#updateItem(UpdateItemEnhancedRequest)}. * <p> * <b>Partial updates</b><br>Each delete or put call is atomic, but the operation as a whole is not. * If individual operations fail due to exceeded provisional throughput internal DynamoDb processing failures, * the failed requests can be retrieved through the result, see {@link BatchWriteResult}. * <p> * There are some conditions that cause the whole batch operation to fail. These include non-existing tables, erroneously * defined primary key attributes, attempting to put and delete the same item as well as referring more than once to the same * hash and range (sort) key. * <p> * This operation calls the low-level DynamoDB API BatchWriteItem operation. Consult the BatchWriteItem documentation for * further details and constraints, current limits of data to write and/or delete, how to handle partial updates and retries * and under which conditions the operation will fail. * <p> * <b>Note:</b> This is a convenience method that creates an instance of the request builder avoiding the need to create one * manually via {@link BatchWriteItemEnhancedRequest#builder()}. * <p> * Example: * <pre> * {@code * * BatchWriteResult batchResult = enhancedClient.batchWriteItem(r -> r.writeBatches( * WriteBatch.builder(FirstItem.class) * .mappedTableResource(firstItemTable) * .addPutItem(i -> i.item(item1)) * .addDeleteItem(i -> i.key(key2)) * .build(), * WriteBatch.builder(SecondItem.class) * .mappedTableResource(secondItemTable) * .addPutItem(i -> i.item(item3)) * .build())); * } * </pre> * * @param requestConsumer a {@link Consumer} of {@link BatchWriteItemEnhancedRequest} containing keys and items grouped by * tables. * @return a {@link BatchWriteResult} containing any unprocessed requests. */ default BatchWriteResult batchWriteItem(Consumer<BatchWriteItemEnhancedRequest.Builder> requestConsumer) { throw new UnsupportedOperationException(); } /** * Retrieves multiple items from one or more tables in a single atomic transaction. TransactGetItem is a composite operation * where the request contains a set of get requests, each containing a table reference and a * {@link GetItemEnhancedRequest}. The list of results correspond to the ordering of the request definitions; for example * the third addGetItem() call on the request builder will match the third result (index 2) of the result. * <p> * The additional configuration parameters that the enhanced client supports are defined * in the {@link TransactGetItemsEnhancedRequest}. * <p> * DynamoDb will reject a call to TransactGetItems if the call exceeds limits such as provisioned throughput or allowed size * of items, if the request contains errors or if there are conflicting operations accessing the same item, for instance * updating and reading at the same time. * <p> * This operation calls the low-level DynamoDB API TransactGetItems operation. Consult the TransactGetItems documentation for * further details and constraints. * <p> * Examples: * <pre> * {@code * * List<TransactGetResultPage> results = enhancedClient.transactGetItems( * TransactGetItemsEnhancedRequest.builder() * .addGetItem(firstItemTable, GetItemEnhancedRequest.builder().key(key1).build()) * .addGetItem(firstItemTable, GetItemEnhancedRequest.builder().key(key2).build()) * .addGetItem(firstItemTable, GetItemEnhancedRequest.builder().key(key3).build()) * .addGetItem(secondItemTable, GetItemEnhancedRequest.builder().key(key4).build()) * .build()); * MyItem item = results.get(3).getItem(secondItemTable); * } * </pre> * See {@link DynamoDbClient#transactGetItems(Consumer)} to learn more about {@code TransactGetItems}. * * @param request A {@link TransactGetItemsEnhancedRequest} containing keys with table references. * @return a list of {@link Document} with the results. */ default List<Document> transactGetItems(TransactGetItemsEnhancedRequest request) { throw new UnsupportedOperationException(); } /** * Retrieves multiple items from one or more tables in a single atomic transaction. TransactGetItem is a composite operation * where the request contains a set of get requests, each containing a table reference and a * {@link GetItemEnhancedRequest}. The list of results correspond to the ordering of the request definitions; for example * the third addGetItem() call on the request builder will match the third result (index 2) of the result. * <p> * The additional configuration parameters that the enhanced client supports are defined * in the {@link TransactGetItemsEnhancedRequest}. * <p> * DynamoDb will reject a call to TransactGetItems if the call exceeds limits such as provisioned throughput or allowed size * of items, if the request contains errors or if there are conflicting operations accessing the same item, for instance * updating and reading at the same time. * <p> * This operation calls the low-level DynamoDB API TransactGetItems operation. Consult the TransactGetItems documentation for * further details and constraints. * <p> * <b>Note:</b> This is a convenience method that creates an instance of the request builder avoiding the need to create one * manually via {@link TransactGetItemsEnhancedRequest#builder()}. * <p> * Examples: * <pre> * {@code * * List<TransactGetResultPage> results = enhancedClient.transactGetItems( * r -> r.addGetItem(firstItemTable, i -> i.key(k -> k.partitionValue(0))) * .addGetItem(firstItemTable, i -> i.key(k -> k.partitionValue(1))) * .addGetItem(firstItemTable, i -> i.key(k -> k.partitionValue(2))) * .addGetItem(secondItemTable, i -> i.key(k -> k.partitionValue(0)))); * MyItem item = results.get(3).getItem(secondItemTable); * } * </pre> * <p> * See {@link DynamoDbClient#transactGetItems(Consumer)} to learn more about {@code TransactGetItems}. * * @param requestConsumer a {@link Consumer} of {@link TransactGetItemsEnhancedRequest} containing keys with table references. * @return a list of {@link Document} with the results. * */ default List<Document> transactGetItems(Consumer<TransactGetItemsEnhancedRequest.Builder> requestConsumer) { throw new UnsupportedOperationException(); } /** * Writes and/or modifies multiple items from one or more tables in a single atomic transaction. TransactGetItem is a * composite operation where the request contains a set of action requests, each containing a table reference and * one of the following requests: * <ul> * <li>Condition check of item - {@link ConditionCheck}</li> * <li>Delete item - {@link DeleteItemEnhancedRequest}</li> * <li>Put item - {@link PutItemEnhancedRequest}</li> * <li>Update item - {@link UpdateItemEnhancedRequest}</li> * </ul> * <p> * The additional configuration parameters that the enhanced client supports are defined * in the {@link TransactWriteItemsEnhancedRequest}. * <p> * DynamoDb will reject a call to TransactWriteItems if the call exceeds limits such as provisioned throughput or allowed size * of items, if the request contains errors or if there are conflicting operations accessing the same item. If the request * contains condition checks that aren't met, this will also cause rejection. * <p> * This operation calls the low-level DynamoDB API TransactWriteItems operation. Consult the TransactWriteItems documentation * for further details and constraints, current limits of data to write and/or delete and under which conditions the operation * will fail. * <p> * Example: * <pre> * {@code * * result = enhancedClient.transactWriteItems( * TransactWriteItemsEnhancedRequest.builder() * .addPutItem(firstItemTable, PutItemEnhancedRequest.builder().item(item1).build()) * .addDeleteItem(firstItemTable, DeleteItemEnhancedRequest.builder().key(key2).build()) * .addConditionCheck(firstItemTable, * ConditionCheck.builder() * .key(key3) * .conditionExpression(conditionExpression) * .build()) * .addUpdateItem(secondItemTable, * UpdateItemEnhancedRequest.builder().item(item4).build()) * .build()); * } * </pre> * See {@link DynamoDbClient#transactWriteItems(Consumer)} to learn more about {@code TransactWriteItems}. * * @param request A {@link BatchWriteItemEnhancedRequest} containing keys grouped by tables. */ default Void transactWriteItems(TransactWriteItemsEnhancedRequest request) { throw new UnsupportedOperationException(); } /** * Writes and/or modifies multiple items from one or more tables in a single atomic transaction. TransactGetItem is a * composite operation where the request contains a set of action requests, each containing a table reference and * one of the following requests: * <ul> * <li>Condition check of item - {@link ConditionCheck}</li> * <li>Delete item - {@link DeleteItemEnhancedRequest}</li> * <li>Put item - {@link PutItemEnhancedRequest}</li> * <li>Update item - {@link UpdateItemEnhancedRequest}</li> * </ul> * <p> * The additional configuration parameters that the enhanced client supports are defined * in the {@link TransactWriteItemsEnhancedRequest}. * <p> * DynamoDb will reject a call to TransactWriteItems if the call exceeds limits such as provisioned throughput or allowed size * of items, if the request contains errors or if there are conflicting operations accessing the same item. If the request * contains condition checks that aren't met, this will also cause rejection. * <p> * This operation calls the low-level DynamoDB API TransactWriteItems operation. Consult the TransactWriteItems documentation * for further details and constraints, current limits of data to write and/or delete and under which conditions the operation * will fail. * <p> * <b>Note:</b> This is a convenience method that creates an instance of the request builder avoiding the need to create one * manually via {@link TransactWriteItemsEnhancedRequest#builder()}. * <p> * Example: * <pre> * {@code * * result = enhancedClient.transactWriteItems(r -> r.addPutItem(firstItemTable, i -> i.item(item1)) * .addDeleteItem(firstItemTable, i -> i.key(k -> k.partitionValue(2))) * .addConditionCheck(firstItemTable, * i -> i.key(key3).conditionExpression(conditionExpression)) * .addUpdateItem(secondItemTable, i -> i.item(item4))); * } * </pre> * See {@link DynamoDbClient#transactWriteItems(Consumer)} to learn more about {@code TransactWriteItems}. * * @param requestConsumer a {@link Consumer} of {@link TransactWriteItemsEnhancedRequest} containing keys and items grouped * by tables. */ default Void transactWriteItems(Consumer<TransactWriteItemsEnhancedRequest.Builder> requestConsumer) { throw new UnsupportedOperationException(); } /** * Creates a default builder for {@link DynamoDbEnhancedClient}. */ static Builder builder() { return DefaultDynamoDbEnhancedClient.builder(); } /** * Creates a {@link DynamoDbEnhancedClient} with a default {@link DynamoDbClient} */ static DynamoDbEnhancedClient create() { return builder().build(); } /** * The builder definition for a {@link DynamoDbEnhancedClient}. */ @NotThreadSafe interface Builder extends DynamoDbEnhancedResource.Builder { /** * The regular low-level SDK client to use with the enhanced client. * @param dynamoDbClient an initialized {@link DynamoDbClient} */ Builder dynamoDbClient(DynamoDbClient dynamoDbClient); @Override Builder extensions(DynamoDbEnhancedClientExtension... dynamoDbEnhancedClientExtensions); @Override Builder extensions(List<DynamoDbEnhancedClientExtension> dynamoDbEnhancedClientExtensions); /** * Builds an enhanced client based on the settings supplied to this builder * @return An initialized {@link DynamoDbEnhancedClient} */ DynamoDbEnhancedClient build(); } }
4,353
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/DynamoDbEnhancedClientExtension.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.enhanced.dynamodb.extensions.ReadModification; import software.amazon.awssdk.enhanced.dynamodb.extensions.WriteModification; /** * Interface for extending the DynamoDb Enhanced client. Two hooks are provided, one that is called just before a record * is written to the database, and one called just after a record is read from the database. This gives the extension the * opportunity to act as an invisible layer between the application and the database and transform the data accordingly. * <p> * Multiple extensions can be used with the enhanced client, but the order in which they are loaded is important. For * instance one extension may overwrite the value of an attribute that another extension then includes in a checksum * calculation. */ @SdkPublicApi @ThreadSafe public interface DynamoDbEnhancedClientExtension { /** * This hook is called just before an operation is going to write data to the database. The extension that * implements this method can choose to transform the item itself, or add a condition to the write operation * or both. * * @param context The {@link DynamoDbExtensionContext.BeforeWrite} context containing the state of the execution. * @return A {@link WriteModification} object that can alter the behavior of the write operation. */ default WriteModification beforeWrite(DynamoDbExtensionContext.BeforeWrite context) { return WriteModification.builder().build(); } /** * This hook is called just after an operation that has read data from the database. The extension that * implements this method can choose to transform the item, and then it is the transformed item that will be * mapped back to the application instead of the item that was actually read from the database. * * @param context The {@link DynamoDbExtensionContext.AfterRead} context containing the state of the execution. * @return A {@link ReadModification} object that can alter the results of a read operation. */ default ReadModification afterRead(DynamoDbExtensionContext.AfterRead context) { return ReadModification.builder().build(); } }
4,354
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/MappedTableResource.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; /** * Interface for a resource object that is part of either a {@link DynamoDbTable} or {@link DynamoDbAsyncTable}. This * part of the interface is common between both of those higher order interfaces and has methods to access the * metadata associated with the mapped entity, such as the schema and the table name, but knows nothing about how to * actually execute operations against it. * * @param <T> The type of the modelled object. */ @SdkPublicApi @ThreadSafe public interface MappedTableResource<T> { /** * Gets the {@link DynamoDbEnhancedClientExtension} associated with this mapped resource. * @return The {@link DynamoDbEnhancedClientExtension} associated with this mapped resource. */ DynamoDbEnhancedClientExtension mapperExtension(); /** * Gets the {@link TableSchema} object that this mapped table was built with. * @return The {@link TableSchema} object for this mapped table. */ TableSchema<T> tableSchema(); /** * Gets the physical table name that operations performed by this object will be executed against. * @return The physical table name. */ String tableName(); /** * Creates a {@link Key} object from a modelled item. This key can be used in query conditionals and get * operations to locate a specific record. * @param item The item to extract the key fields from. * @return A key that has been initialized with the index values extracted from the modelled object. */ Key keyFrom(T item); }
4,355
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/EnhancedType.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb; import static java.util.stream.Collectors.toList; import java.lang.reflect.GenericArrayType; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.lang.reflect.WildcardType; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Deque; import java.util.List; import java.util.Map; import java.util.NavigableMap; import java.util.NavigableSet; import java.util.Optional; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import java.util.concurrent.ConcurrentMap; import java.util.function.Consumer; import java.util.stream.Collectors; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.enhanced.dynamodb.internal.mapper.DefaultParameterizedType; import software.amazon.awssdk.utils.Validate; /** * Similar to {@link Class}, this represents a specific raw class type. Unlike {@code Class}, this allows representing type * parameters that would usually be erased. * * @see #EnhancedType() * @see #of(Class) * @see #listOf(Class) * @see #mapOf(Class, Class) */ @SdkPublicApi @ThreadSafe @Immutable public class EnhancedType<T> { private final boolean isWildcard; private final Class<T> rawClass; private final List<EnhancedType<?>> rawClassParameters; private final TableSchema<T> tableSchema; private final EnhancedTypeDocumentConfiguration documentConfiguration; /** * Create a type token, capturing the generic type arguments of the token as {@link Class}es. * * <p> * <b>This must be called from an anonymous subclass.</b> For example, * {@code new EnhancedType<Iterable<String>>()&#123;&#125;} (note the extra {}) for a {@code EnhancedType<Iterable<String>>}. */ protected EnhancedType() { this(null); } private EnhancedType(Type type, EnhancedTypeDocumentConfiguration documentConfiguration) { if (type == null) { type = captureGenericTypeArguments(); } if (type instanceof WildcardType) { this.isWildcard = true; this.rawClass = null; this.rawClassParameters = null; this.tableSchema = null; } else { this.isWildcard = false; this.rawClass = validateAndConvert(type); this.rawClassParameters = loadTypeParameters(type); this.tableSchema = null; } this.documentConfiguration = documentConfiguration; } private EnhancedType(Type type) { this(type, null); } private EnhancedType(Class<?> rawClass, List<EnhancedType<?>> rawClassParameters, TableSchema<T> tableSchema) { this(rawClass, rawClassParameters, tableSchema, null); } private EnhancedType(Class<?> rawClass, List<EnhancedType<?>> rawClassParameters, TableSchema<T> tableSchema, EnhancedTypeDocumentConfiguration documentConfiguration) { // This is only used internally, so we can make sure this cast is safe via testing. this.rawClass = (Class<T>) rawClass; this.isWildcard = false; this.rawClassParameters = rawClassParameters; this.tableSchema = tableSchema; this.documentConfiguration = documentConfiguration; } /** * Create a type token for the provided non-parameterized class. * * <p> * Reasons this call may fail with a {@link RuntimeException}: * <ol> * <li>If the provided type is null.</li> * </ol> */ public static <T> EnhancedType<T> of(Class<T> type) { return new EnhancedType<>(type); } /** * Create a type token for the provided non-parameterized class. * * <p> * Reasons this call may fail with a {@link RuntimeException}: * <ol> * <li>If the provided type is null.</li> * </ol> */ public static EnhancedType<?> of(Type type) { return new EnhancedType<>(type); } /** * Create a type token for a optional, with the provided value type class. * * <p> * Reasons this call may fail with a {@link RuntimeException}: * <ol> * <li>If the provided type is null.</li> * </ol> */ public static <T> EnhancedType<Optional<T>> optionalOf(Class<T> valueType) { return new EnhancedType<>(DefaultParameterizedType.parameterizedType(Optional.class, valueType)); } /** * Create a type token for a list, with the provided value type class. * * <p> * Reasons this call may fail with a {@link RuntimeException}: * <ol> * <li>If the provided type is null.</li> * </ol> */ public static <T> EnhancedType<List<T>> listOf(Class<T> valueType) { return new EnhancedType<>(DefaultParameterizedType.parameterizedType(List.class, valueType)); } /** * Create a type token for a list, with the provided value type class. * * <p> * Reasons this call may fail with a {@link RuntimeException}: * <ol> * <li>If the provided type is null.</li> * </ol> */ public static <T> EnhancedType<List<T>> listOf(EnhancedType<T> valueType) { return new EnhancedType<>(List.class, Arrays.asList(valueType), null); } /** * Create a type token for a set, with the provided value type class. * * <p> * Reasons this call may fail with a {@link RuntimeException}: * <ol> * <li>If the provided type is null.</li> * </ol> */ public static <T> EnhancedType<Set<T>> setOf(Class<T> valueType) { return new EnhancedType<>(DefaultParameterizedType.parameterizedType(Set.class, valueType)); } /** * Create a type token for a set, with the provided value type class. * * <p> * Reasons this call may fail with a {@link RuntimeException}: * <ol> * <li>If the provided type is null.</li> * </ol> */ public static <T> EnhancedType<Set<T>> setOf(EnhancedType<T> valueType) { return new EnhancedType<>(Set.class, Arrays.asList(valueType), null); } /** * Create a type token for a sorted set, with the provided value type class. * * <p> * Reasons this call may fail with a {@link RuntimeException}: * <ol> * <li>If the provided type is null.</li> * </ol> */ public static <T> EnhancedType<SortedSet<T>> sortedSetOf(Class<T> valueType) { return new EnhancedType<>(DefaultParameterizedType.parameterizedType(SortedSet.class, valueType)); } /** * Create a type token for a sorted set, with the provided value type class. * * <p> * Reasons this call may fail with a {@link RuntimeException}: * <ol> * <li>If the provided type is null.</li> * </ol> */ public static <T> EnhancedType<SortedSet<T>> sortedSetOf(EnhancedType<T> valueType) { return new EnhancedType<>(SortedSet.class, Arrays.asList(valueType), null); } /** * Create a type token for a deque, with the provided value type class. * * <p> * Reasons this call may fail with a {@link RuntimeException}: * <ol> * <li>If the provided type is null.</li> * </ol> */ public static <T> EnhancedType<Deque<T>> dequeOf(Class<T> valueType) { return new EnhancedType<>(DefaultParameterizedType.parameterizedType(Deque.class, valueType)); } /** * Create a type token for a deque, with the provided value type token. * * <p> * Reasons this call may fail with a {@link RuntimeException}: * <ol> * <li>If the provided type is null.</li> * </ol> */ public static <T> EnhancedType<Deque<T>> dequeOf(EnhancedType<T> valueType) { return new EnhancedType<>(Deque.class, Arrays.asList(valueType), null); } /** * Create a type token for a navigable set, with the provided value type class. * * <p> * Reasons this call may fail with a {@link RuntimeException}: * <ol> * <li>If the provided type is null.</li> * </ol> */ public static <T> EnhancedType<NavigableSet<T>> navigableSetOf(Class<T> valueType) { return new EnhancedType<>(DefaultParameterizedType.parameterizedType(NavigableSet.class, valueType)); } /** * Create a type token for a navigable set, with the provided value type token. * * <p> * Reasons this call may fail with a {@link RuntimeException}: * <ol> * <li>If the provided type is null.</li> * </ol> */ public static <T> EnhancedType<NavigableSet<T>> navigableSetOf(EnhancedType<T> valueType) { return new EnhancedType<>(NavigableSet.class, Arrays.asList(valueType), null); } /** * Create a type token for a collection, with the provided value type class. * * <p> * Reasons this call may fail with a {@link RuntimeException}: * <ol> * <li>If the provided type is null.</li> * </ol> */ public static <T> EnhancedType<Collection<T>> collectionOf(Class<T> valueType) { return new EnhancedType<>(DefaultParameterizedType.parameterizedType(Collection.class, valueType)); } /** * Create a type token for a collection, with the provided value type token. * * <p> * Reasons this call may fail with a {@link RuntimeException}: * <ol> * <li>If the provided type is null.</li> * </ol> */ public static <T> EnhancedType<Collection<T>> collectionOf(EnhancedType<T> valueType) { return new EnhancedType<>(Collection.class, Arrays.asList(valueType), null); } /** * Create a type token for a map, with the provided key and value type classes. * * <p> * Reasons this call may fail with a {@link RuntimeException}: * <ol> * <li>If the provided types are null.</li> * </ol> */ public static <T, U> EnhancedType<Map<T, U>> mapOf(Class<T> keyType, Class<U> valueType) { return new EnhancedType<>(DefaultParameterizedType.parameterizedType(Map.class, keyType, valueType)); } /** * Create a type token for a map, with the provided key and value type classes. * * <p> * Reasons this call may fail with a {@link RuntimeException}: * <ol> * <li>If the provided types are null.</li> * </ol> */ public static <T, U> EnhancedType<Map<T, U>> mapOf(EnhancedType<T> keyType, EnhancedType<U> valueType) { return new EnhancedType<>(Map.class, Arrays.asList(keyType, valueType), null); } /** * Create a type token for a sorted map, with the provided key and value type classes. * * <p> * Reasons this call may fail with a {@link RuntimeException}: * <ol> * <li>If the provided types are null.</li> * </ol> */ public static <T, U> EnhancedType<SortedMap<T, U>> sortedMapOf(Class<T> keyType, Class<U> valueType) { return new EnhancedType<>(DefaultParameterizedType.parameterizedType(SortedMap.class, keyType, valueType)); } /** * Create a type token for a sorted map, with the provided key and value type classes. * * <p> * Reasons this call may fail with a {@link RuntimeException}: * <ol> * <li>If the provided types are null.</li> * </ol> */ public static <T, U> EnhancedType<SortedMap<T, U>> sortedMapOf(EnhancedType<T> keyType, EnhancedType<U> valueType) { return new EnhancedType<>(SortedMap.class, Arrays.asList(keyType, valueType), null); } /** * Create a type token for a concurrent map, with the provided key and value type classes. * * <p> * Reasons this call may fail with a {@link RuntimeException}: * <ol> * <li>If the provided types are null.</li> * </ol> */ public static <T, U> EnhancedType<ConcurrentMap<T, U>> concurrentMapOf(Class<T> keyType, Class<U> valueType) { return new EnhancedType<>(DefaultParameterizedType.parameterizedType(ConcurrentMap.class, keyType, valueType)); } /** * Create a type token for a concurrent map, with the provided key and value type classes. * * <p> * Reasons this call may fail with a {@link RuntimeException}: * <ol> * <li>If the provided types are null.</li> * </ol> */ public static <T, U> EnhancedType<ConcurrentMap<T, U>> concurrentMapOf(EnhancedType<T> keyType, EnhancedType<U> valueType) { return new EnhancedType<>(ConcurrentMap.class, Arrays.asList(keyType, valueType), null); } /** * Create a type token for a navigable map, with the provided key and value type classes. * * <p> * Reasons this call may fail with a {@link RuntimeException}: * <ol> * <li>If the provided types are null.</li> * </ol> */ public static <T, U> EnhancedType<NavigableMap<T, U>> navigableMapOf(Class<T> keyType, Class<U> valueType) { return new EnhancedType<>(DefaultParameterizedType.parameterizedType(NavigableMap.class, keyType, valueType)); } /** * Create a type token for a navigable map, with the provided key and value type classes. * * <p> * Reasons this call may fail with a {@link RuntimeException}: * <ol> * <li>If the provided types are null.</li> * </ol> */ public static <T, U> EnhancedType<NavigableMap<T, U>> navigableMapOf(EnhancedType<T> keyType, EnhancedType<U> valueType) { return new EnhancedType<>(NavigableMap.class, Arrays.asList(keyType, valueType), null); } /** * Create a type token that represents a document that is specified by the provided {@link TableSchema}. * * @param documentClass The Class representing the modeled document. * @param documentTableSchema A TableSchema that describes the properties of the document. * @return a new {@link EnhancedType} representing the provided document. */ public static <T> EnhancedType<T> documentOf(Class<T> documentClass, TableSchema<T> documentTableSchema) { return new EnhancedType<>(documentClass, null, documentTableSchema); } /** * Create a type token that represents a document that is specified by the provided {@link TableSchema}. * * @param documentClass The Class representing the modeled document. * @param documentTableSchema A TableSchema that describes the properties of the document. * @param enhancedTypeConfiguration the configuration for this enhanced type * @return a new {@link EnhancedType} representing the provided document. */ public static <T> EnhancedType<T> documentOf(Class<T> documentClass, TableSchema<T> documentTableSchema, Consumer<EnhancedTypeDocumentConfiguration.Builder> enhancedTypeConfiguration) { EnhancedTypeDocumentConfiguration.Builder builder = EnhancedTypeDocumentConfiguration.builder(); enhancedTypeConfiguration.accept(builder); return new EnhancedType<>(documentClass, null, documentTableSchema, builder.build()); } private static Type validateIsSupportedType(Type type) { Validate.validState(type != null, "Type must not be null."); Validate.validState(!(type instanceof GenericArrayType), "Array type %s is not supported. Use java.util.List instead of arrays.", type); Validate.validState(!(type instanceof TypeVariable), "Type variable type %s is not supported.", type); if (type instanceof WildcardType) { WildcardType wildcardType = (WildcardType) type; Validate.validState(wildcardType.getUpperBounds().length == 1 && wildcardType.getUpperBounds()[0] == Object.class, "Non-Object wildcard type upper bounds are not supported."); Validate.validState(wildcardType.getLowerBounds().length == 0, "Wildcard type lower bounds are not supported."); } return type; } /** * Returns whether or not the type this {@link EnhancedType} was created with is a wildcard type. */ public boolean isWildcard() { return isWildcard; } /** * Retrieve the {@link Class} object that this type token represents. * * e.g. For {@code EnhancedType<String>}, this would return {@code String.class}. */ public Class<T> rawClass() { Validate.isTrue(!isWildcard, "A wildcard type is not expected here."); return rawClass; } /** * Retrieve the {@link TableSchema} for a modeled document. This is used for * converting nested documents within a schema. */ public Optional<TableSchema<T>> tableSchema() { return Optional.ofNullable(tableSchema); } /** * Retrieve the {@link Class} objects of any type parameters for the class that this type token represents. * * <p> * e.g. For {@code EnhancedType<List<String>>}, this would return {@code String.class}, and {@link #rawClass()} would * return {@code List.class}. * * <p> * If there are no type parameters, this will return an empty list. */ public List<EnhancedType<?>> rawClassParameters() { Validate.isTrue(!isWildcard, "A wildcard type is not expected here."); return rawClassParameters; } /** * Retrieve the optional {@link EnhancedTypeDocumentConfiguration} for this EnhancedType */ public Optional<EnhancedTypeDocumentConfiguration> documentConfiguration() { return Optional.ofNullable(documentConfiguration); } private Type captureGenericTypeArguments() { Type superclass = getClass().getGenericSuperclass(); ParameterizedType parameterizedSuperclass = Validate.isInstanceOf(ParameterizedType.class, superclass, "%s isn't parameterized", superclass); return parameterizedSuperclass.getActualTypeArguments()[0]; } private Class<T> validateAndConvert(Type type) { validateIsSupportedType(type); if (type instanceof Class) { return (Class<T>) type; } else if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; return validateAndConvert(parameterizedType.getRawType()); } else { throw new IllegalStateException("Unsupported type: " + type); } } private List<EnhancedType<?>> loadTypeParameters(Type type) { if (!(type instanceof ParameterizedType)) { return Collections.emptyList(); } ParameterizedType parameterizedType = (ParameterizedType) type; return Collections.unmodifiableList( Arrays.stream(parameterizedType.getActualTypeArguments()) .peek(t -> Validate.validState(t != null, "Invalid type argument.")) .map(EnhancedType::new) .collect(toList())); } private StringBuilder innerToString() { StringBuilder result = new StringBuilder(); result.append(rawClass.getTypeName()); if (null != rawClassParameters && !rawClassParameters.isEmpty()) { result.append("<"); result.append(rawClassParameters.stream().map(EnhancedType::innerToString).collect(Collectors.joining(", "))); result.append(">"); } return result; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof EnhancedType)) { return false; } EnhancedType<?> enhancedType = (EnhancedType<?>) o; if (isWildcard != enhancedType.isWildcard) { return false; } if (!rawClass.equals(enhancedType.rawClass)) { return false; } if (rawClassParameters != null ? !rawClassParameters.equals(enhancedType.rawClassParameters) : enhancedType.rawClassParameters != null) { return false; } if (documentConfiguration != null ? !documentConfiguration.equals(enhancedType.documentConfiguration) : enhancedType.documentConfiguration != null) { return false; } return tableSchema != null ? tableSchema.equals(enhancedType.tableSchema) : enhancedType.tableSchema == null; } @Override public int hashCode() { int result = (isWildcard ? 1 : 0); result = 31 * result + rawClass.hashCode(); result = 31 * result + (rawClassParameters != null ? rawClassParameters.hashCode() : 0); result = 31 * result + (tableSchema != null ? tableSchema.hashCode() : 0); result = 31 * result + (documentConfiguration != null ? documentConfiguration.hashCode() : 0); return result; } @Override public String toString() { return "EnhancedType(" + innerToString() + ")"; } }
4,356
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/DynamoDbTable.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb; import java.util.function.Consumer; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.core.pagination.sync.SdkIterable; import software.amazon.awssdk.enhanced.dynamodb.model.CreateTableEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.DeleteItemEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.DeleteItemEnhancedResponse; import software.amazon.awssdk.enhanced.dynamodb.model.DescribeTableEnhancedResponse; import software.amazon.awssdk.enhanced.dynamodb.model.GetItemEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.GetItemEnhancedResponse; import software.amazon.awssdk.enhanced.dynamodb.model.Page; import software.amazon.awssdk.enhanced.dynamodb.model.PageIterable; import software.amazon.awssdk.enhanced.dynamodb.model.PutItemEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.PutItemEnhancedResponse; import software.amazon.awssdk.enhanced.dynamodb.model.QueryConditional; import software.amazon.awssdk.enhanced.dynamodb.model.QueryEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.ScanEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.UpdateItemEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.UpdateItemEnhancedResponse; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.ConsumedCapacity; import software.amazon.awssdk.services.dynamodb.model.DescribeTableRequest; import software.amazon.awssdk.services.dynamodb.waiters.DynamoDbWaiter; /** * Synchronous interface for running commands against an object that is linked to a specific DynamoDb table resource * and therefore knows how to map records from that table into a modelled object. * <p> * By default, all command methods throw an {@link UnsupportedOperationException} to prevent interface extensions from * breaking implementing classes. * <p> * @param <T> The type of the modelled object. */ @SdkPublicApi @ThreadSafe public interface DynamoDbTable<T> extends MappedTableResource<T> { /** * Returns a mapped index that can be used to execute commands against a secondary index belonging to the table * being mapped by this object. Note that only a subset of the commands that work against a table will work * against a secondary index. * * @param indexName The name of the secondary index to build the command interface for. * @return A {@link DynamoDbIndex} object that can be used to execute database commands against. */ DynamoDbIndex<T> index(String indexName); /** * Creates a new table in DynamoDb with the name and schema already defined for this DynamoDbTable * together with additional parameters specified in the supplied request object, {@link CreateTableEnhancedRequest}. * <p> * Use {@link DynamoDbEnhancedClient#table(String, TableSchema)} to define the mapped table resource. * <p> * This operation calls the low-level DynamoDB API CreateTable operation. Note that this is an asynchronous * operation and that the table may not immediately be available for writes and reads. You can use * {@link DynamoDbWaiter#waitUntilTableExists(DescribeTableRequest)} to wait for the resource to be ready. * <p> * Example: * <pre> * {@code * * ProvisionedThroughput provisionedThroughput = ProvisionedThroughput.builder() * .readCapacityUnits(50L) * .writeCapacityUnits(50L) * .build(); * mappedTable.createTable(CreateTableEnhancedRequest.builder() * .provisionedThroughput(provisionedThroughput) * .build()); * * dynamoDbClient.waiter().waitUntilTableExists(b -> b.tableName(tableName)); * } * </pre> * * @param request A {@link CreateTableEnhancedRequest} containing optional parameters for table creation. */ default void createTable(CreateTableEnhancedRequest request) { throw new UnsupportedOperationException(); } /** * Creates a new table in DynamoDb with the name and schema already defined for this DynamoDbTable * together with additional parameters specified in the supplied request object, {@link CreateTableEnhancedRequest}. * <p> * Use {@link DynamoDbEnhancedClient#table(String, TableSchema)} to define the mapped table resource. * <p> * This operation calls the low-level DynamoDB API CreateTable operation. Note that this is an asynchronous * operation and that the table may not immediately be available for writes and reads. You can use * {@link DynamoDbWaiter#waitUntilTableExists(DescribeTableRequest)} to wait for the resource to be ready. * <p> * <b>Note:</b> This is a convenience method that creates an instance of the request builder avoiding the need to * create one manually via {@link CreateTableEnhancedRequest#builder()}. * <p> * Example: * <pre> * {@code * * ProvisionedThroughput provisionedThroughput = ProvisionedThroughput.builder() * .readCapacityUnits(50L) * .writeCapacityUnits(50L) * .build(); * mappedTable.createTable(r -> r.provisionedThroughput(provisionedThroughput)); * dynamoDbClient.waiter().waitUntilTableExists(b -> b.tableName(tableName)); * } * </pre> * * @param requestConsumer A {@link Consumer} of {@link CreateTableEnhancedRequest.Builder} containing optional * parameters for table creation. */ default void createTable(Consumer<CreateTableEnhancedRequest.Builder> requestConsumer) { throw new UnsupportedOperationException(); } /** * Creates a new table in DynamoDb with the name and schema already defined for this DynamoDbTable. * <p> * Use {@link DynamoDbEnhancedClient#table(String, TableSchema)} to define the mapped table resource. * <p> * This operation calls the low-level DynamoDB API CreateTable operation. Note that this is an asynchronous * operation and that the table may not immediately be available for writes and reads. You can use * {@link DynamoDbWaiter#waitUntilTableExists(DescribeTableRequest)} to wait for the resource to be ready. * <p> * Example: * <pre> * {@code * * mappedTable.createTable(); * dynamoDbClient.waiter().waitUntilTableExists(b -> b.tableName(tableName)); * } * </pre> * */ default void createTable() { throw new UnsupportedOperationException(); } /** * Deletes a single item from the mapped table using a supplied primary {@link Key}. * <p> * The additional configuration parameters that the enhanced client supports are defined * in the {@link DeleteItemEnhancedRequest}. * <p> * This operation calls the low-level DynamoDB API DeleteItem operation. Consult the DeleteItem documentation for * further details and constraints. * <p> * Example: * <pre> * {@code * * MyItem previouslyPersistedItem = mappedTable.delete(DeleteItemEnhancedRequest.builder().key(key).build()); * } * </pre> * * @param request A {@link DeleteItemEnhancedRequest} with key and optional directives for deleting an item from the * table. * @return The item that was persisted in the database before it was deleted. */ default T deleteItem(DeleteItemEnhancedRequest request) { throw new UnsupportedOperationException(); } /** * Deletes a single item from the mapped table using a supplied primary {@link Key}. * <p> * The additional configuration parameters that the enhanced client supports are defined * in the {@link DeleteItemEnhancedRequest}. * <p> * This operation calls the low-level DynamoDB API DeleteItem operation. Consult the DeleteItem documentation for * further details and constraints. * <p> * <b>Note:</b> This is a convenience method that creates an instance of the request builder avoiding the need to * create one manually via {@link DeleteItemEnhancedRequest#builder()}. * <p> * Example: * <pre> * {@code * * MyItem previouslyPersistedItem = mappedTable.delete(r -> r.key(key)); * } * </pre> * * @param requestConsumer A {@link Consumer} of {@link DeleteItemEnhancedRequest} with key and * optional directives for deleting an item from the table. * @return The item that was persisted in the database before it was deleted. */ default T deleteItem(Consumer<DeleteItemEnhancedRequest.Builder> requestConsumer) { throw new UnsupportedOperationException(); } /** * Deletes a single item from the mapped table using a supplied primary {@link Key}. * <p> * This operation calls the low-level DynamoDB API DeleteItem operation. Consult the DeleteItem documentation for * further details and constraints. * <p> * Example: * <pre> * {@code * * MyItem previouslyPersistedItem = mappedTable.delete(key); * } * </pre> * * @param key A {@link Key} that will be used to match a specific record to delete from the database table. * @return The item that was persisted in the database before it was deleted. */ default T deleteItem(Key key) { throw new UnsupportedOperationException(); } /** * Deletes a single item from the mapped table using just the key of a supplied modelled 'key item' object. * <p> * This operation calls the low-level DynamoDB API DeleteItem operation. Consult the DeleteItem documentation for * further details and constraints. * <p> * Example: * <pre> * {@code * * MyItem previouslyPersistedItem = mappedTable.deleteItem(keyItem); * } * </pre> * * @param keyItem A modelled item with the primary key fields set that will be used to match a specific record to * delete from the database table. * @return The item that was persisted in the database before it was deleted. */ default T deleteItem(T keyItem) { throw new UnsupportedOperationException(); } /** * Deletes a single item from the mapped table using a supplied primary {@link Key}. * <p> * The additional configuration parameters that the enhanced client supports are defined * in the {@link DeleteItemEnhancedRequest}. * <p> * This operation calls the low-level DynamoDB API DeleteItem operation. Consult the DeleteItem documentation for * further details and constraints. Unlike {@link #deleteItem(DeleteItemEnhancedRequest)}, this returns a response object, * allowing the user to retrieve additional information from DynamoDB related to the API call, such as * {@link ConsumedCapacity} if specified on the request. * <p> * Example: * <pre> * {@code * * DeleteItemEnhancedRequest request = DeleteItemEnhancedRequest.builder().key(key).build(); * DeleteItemEnhancedResponse<MyItem> response = mappedTable.deleteItemWithResponse(request); * } * </pre> * * @param request A {@link DeleteItemEnhancedRequest} with key and optional directives for deleting an item from the * table. * @return The response returned by DynamoDB. */ default DeleteItemEnhancedResponse<T> deleteItemWithResponse(DeleteItemEnhancedRequest request) { throw new UnsupportedOperationException(); } /** * Deletes a single item from the mapped table using a supplied primary {@link Key}. * <p> * The additional configuration parameters that the enhanced client supports are defined * in the {@link DeleteItemEnhancedRequest}. * <p> * This operation calls the low-level DynamoDB API DeleteItem operation. Consult the DeleteItem documentation for * further details and constraints. Unlike {@link #deleteItem(Consumer)}, this returns a response object, allowing the user to * retrieve additional information from DynamoDB related to the API call, such as {@link ConsumedCapacity} if specified on * the request. * <p> * <b>Note:</b> This is a convenience method that creates an instance of the request builder avoiding the need to * create one manually via {@link DeleteItemEnhancedRequest#builder()}. * <p> * Example: * <pre> * {@code * * DeleteItemEnhancedResponse<MyItem> response = mappedTable.deleteWithResponse(r -> r.key(key)); * } * </pre> * * @param requestConsumer A {@link Consumer} of {@link DeleteItemEnhancedRequest} with key and * optional directives for deleting an item from the table. * @return The response returned by DynamoDB. */ default DeleteItemEnhancedResponse<T> deleteItemWithResponse(Consumer<DeleteItemEnhancedRequest.Builder> requestConsumer) { throw new UnsupportedOperationException(); } /** * Retrieves a single item from the mapped table using a supplied primary {@link Key}. * <p> * The additional configuration parameters that the enhanced client supports are defined * in the {@link GetItemEnhancedRequest}. * <p> * This operation calls the low-level DynamoDB API GetItem operation. Consult the GetItem documentation for * further details and constraints. * <p> * Example: * <pre> * {@code * * MyItem item = mappedTable.getItem(GetItemEnhancedRequest.builder().key(key).build()); * } * </pre> * * @param request A {@link GetItemEnhancedRequest} with key and optional directives for retrieving an item from the * table. * @return The retrieved item */ default T getItem(GetItemEnhancedRequest request) { throw new UnsupportedOperationException(); } /** * Retrieves a single item from the mapped table using a supplied primary {@link Key}. * <p> * The additional configuration parameters that the enhanced client supports are defined * in the {@link GetItemEnhancedRequest}. * <p> * This operation calls the low-level DynamoDB API GetItem operation. Consult the GetItem documentation for * further details and constraints. * <p> * <b>Note:</b> This is a convenience method that creates an instance of the request builder avoiding the need to * create one manually via {@link GetItemEnhancedRequest#builder()}. * <p> * Example: * <pre> * {@code * * MyItem item = mappedTable.getItem(r -> r.key(key)); * } * </pre> * * @param requestConsumer A {@link Consumer} of {@link GetItemEnhancedRequest.Builder} with key and optional * directives for retrieving an item from the table. * @return The retrieved item */ default T getItem(Consumer<GetItemEnhancedRequest.Builder> requestConsumer) { throw new UnsupportedOperationException(); } /** * Retrieves a single item from the mapped table using a supplied primary {@link Key}. * <p> * This operation calls the low-level DynamoDB API GetItem operation. Consult the GetItem documentation for * further details and constraints. * <p> * Example: * <pre> * {@code * * MyItem item = mappedTable.getItem(key); * } * </pre> * * @param key A {@link Key} that will be used to match a specific record to retrieve from the database table. * @return The retrieved item */ default T getItem(Key key) { throw new UnsupportedOperationException(); } /** * Retrieves a single item from the mapped table using just the key of a supplied modelled 'key item'. * <p> * This operation calls the low-level DynamoDB API GetItem operation. Consult the GetItem documentation for * further details and constraints. * <p> * Example: * <pre> * {@code * * MyItem item = mappedTable.getItem(keyItem); * } * </pre> * * @param keyItem A modelled item with the primary key fields set that will be used to match a specific record to * retrieve from the database table. * @return The retrieved item */ default T getItem(T keyItem) { throw new UnsupportedOperationException(); } /** * Retrieves a single item from the mapped table using a supplied primary {@link Key}. This is similar to * {@link #getItem(GetItemEnhancedRequest)} but returns {@link GetItemEnhancedResponse} for additional information. * * <p> * The additional configuration parameters that the enhanced client supports are defined * in the {@link GetItemEnhancedRequest}. * <p> * This operation calls the low-level DynamoDB API GetItem operation. Consult the GetItem documentation for * further details and constraints. * <p> * Example: * <pre> * {@code * * MyItem item = mappedTable.getItemWithResponse(GetItemEnhancedRequest.builder().key(key).build()); * } * </pre> * * @param request A {@link GetItemEnhancedRequest} with key and optional directives for retrieving an item from the * table. * @return The retrieved item */ default GetItemEnhancedResponse<T> getItemWithResponse(GetItemEnhancedRequest request) { throw new UnsupportedOperationException(); } /** * Retrieves a single item from the mapped table using a supplied primary {@link Key}. This is similar to * {@link #getItem(Consumer<GetItemEnhancedRequest.Builder>)} but returns {@link GetItemEnhancedResponse} for additional * information. * * <p> * The additional configuration parameters that the enhanced client supports are defined * in the {@link GetItemEnhancedRequest}. * <p> * This operation calls the low-level DynamoDB API GetItem operation. Consult the GetItem documentation for * further details and constraints. * <p> * <b>Note:</b> This is a convenience method that creates an instance of the request builder avoiding the need to * create one manually via {@link GetItemEnhancedRequest#builder()}. * <p> * Example: * <pre> * {@code * * MyItem item = mappedTable.getItemWithResponse(r -> r.key(key)); * } * </pre> * * @param requestConsumer A {@link Consumer} of {@link GetItemEnhancedRequest.Builder} with key and optional * directives for retrieving an item from the table. * @return The retrieved item */ default GetItemEnhancedResponse<T> getItemWithResponse(Consumer<GetItemEnhancedRequest.Builder> requestConsumer) { throw new UnsupportedOperationException(); } /** * Executes a query against the primary index of the table using a {@link QueryConditional} expression to retrieve a * list of items matching the given conditions. * <p> * The result can be accessed either through iterable {@link Page}s or {@link Page#items()} directly. If you are iterating * the pages, the result is accessed through iterable pages (see {@link Page}) in an interactive way; each time a * result page is retrieved, a query call is made to DynamoDb to get those entries. If no matches are found, * the resulting iterator will contain an empty page. Results are sorted by sort key value in ascending order by default; * this behavior can be overridden in the {@link QueryEnhancedRequest}. * <p> * The additional configuration parameters that the enhanced client supports are defined * in the {@link QueryEnhancedRequest}. * <p> * This operation calls the low-level DynamoDB API Query operation. Consult the Query documentation for * further details and constraints. * <p> * Example: * <p> * 1) Iterating through pages * * <pre> * {@code * QueryConditional queryConditional = QueryConditional.keyEqualTo(Key.builder().partitionValue("id-value").build()); * PageIterable<MyItem> results = table.query(QueryEnhancedRequest.builder() * .queryConditional(queryConditional) * .build()); * results.stream().forEach(p -> p.items().forEach(item -> System.out.println(item))) * } * </pre> * * 2) Iterating through items * * <pre> * {@code * results.items().stream().forEach(item -> System.out.println(item)); * } * </pre> * * @see #query(QueryConditional) * @see #query(Consumer) * @see DynamoDbClient#queryPaginator * @param request A {@link QueryEnhancedRequest} defining the query conditions and how * to handle the results. * @return an iterator of type {@link SdkIterable} with paginated results (see {@link Page}). */ default PageIterable<T> query(QueryEnhancedRequest request) { throw new UnsupportedOperationException(); } /** * This is a convenience method that creates an instance of the request builder avoiding the need to create one * manually via {@link QueryEnhancedRequest#builder()}. * <p> * Example: * <pre> * {@code * * PageIterable<MyItem> results = * mappedTable.query(r -> r.queryConditional(QueryConditional.keyEqualTo(k -> k.partitionValue("id-value")))); * } * </pre> * @see #query(QueryEnhancedRequest) * @see #query(QueryConditional) * @param requestConsumer A {@link Consumer} of {@link QueryEnhancedRequest} defining the query conditions and how to * handle the results. * @return an iterator of type {@link SdkIterable} with paginated results (see {@link Page}). */ default PageIterable<T> query(Consumer<QueryEnhancedRequest.Builder> requestConsumer) { throw new UnsupportedOperationException(); } /** * Executes a query against the primary index of the table using a {@link QueryConditional} expression to retrieve a * list of items matching the given conditions. * <p> * Example: * <pre> * {@code * * PageIterable<MyItem> results = * mappedTable.query(QueryConditional.keyEqualTo(Key.builder().partitionValue("id-value").build())); * } * </pre> * * @see #query(QueryEnhancedRequest) * @see #query(Consumer) * @see DynamoDbClient#queryPaginator * @param queryConditional A {@link QueryConditional} defining the matching criteria for records to be queried. * @return an iterator of type {@link SdkIterable} with paginated results (see {@link Page}). */ default PageIterable<T> query(QueryConditional queryConditional) { throw new UnsupportedOperationException(); } /** * Puts a single item in the mapped table. If the table contains an item with the same primary key, it will be * replaced with this item. * <p> * The additional configuration parameters that the enhanced client supports are defined * in the {@link PutItemEnhancedRequest}. * <p> * This operation calls the low-level DynamoDB API PutItem operation. Consult the PutItem documentation for * further details and constraints. * <p> * Example: * <pre> * {@code * * mappedTable.putItem(PutItemEnhancedRequest.builder(MyItem.class).item(item).build()); * } * </pre> * * @param request A {@link PutItemEnhancedRequest} that includes the item to enter into * the table, its class and optional directives. */ default void putItem(PutItemEnhancedRequest<T> request) { throw new UnsupportedOperationException(); } /** * Puts a single item in the mapped table. If the table contains an item with the same primary key, it will be * replaced with this item. * <p> * The additional configuration parameters that the enhanced client supports are defined * in the {@link PutItemEnhancedRequest}. * <p> * This operation calls the low-level DynamoDB API PutItem operation. Consult the PutItem documentation for * further details and constraints. * <p> * Example: * <pre> * {@code * * mappedTable.putItem(r -> r.item(item)); * } * </pre> * * @param requestConsumer A {@link Consumer} of {@link PutItemEnhancedRequest.Builder} that includes the item * to enter into the table, its class and optional directives. */ default void putItem(Consumer<PutItemEnhancedRequest.Builder<T>> requestConsumer) { throw new UnsupportedOperationException(); } /** * Puts a single item in the mapped table. If the table contains an item with the same primary key, it will be * replaced with this item. * <p> * This operation calls the low-level DynamoDB API PutItem operation. Consult the PutItem documentation for * further details and constraints. * <p> * Example: * <pre> * {@code * * mappedTable.putItem(item); * } * </pre> * * @param item the modelled item to be inserted into or overwritten in the database table. */ default void putItem(T item) { throw new UnsupportedOperationException(); } /** * Puts a single item in the mapped table. If the table contains an item with the same primary key, it will be * replaced with this item. This is similar to {@link #putItem(PutItemEnhancedRequest)} but returns * {@link PutItemEnhancedResponse} for additional information. * <p> * The additional configuration parameters that the enhanced client supports are defined * in the {@link PutItemEnhancedRequest}. * <p> * This operation calls the low-level DynamoDB API PutItem operation. Consult the PutItem documentation for * further details and constraints. * <p> * Example: * <pre> * {@code * * mappedTable.putItem(PutItemEnhancedRequest.builder(MyItem.class).item(item).build()); * } * </pre> * * @param request A {@link PutItemEnhancedRequest} that includes the item to enter into * the table, its class and optional directives. * * @return The response returned by DynamoDB. */ default PutItemEnhancedResponse<T> putItemWithResponse(PutItemEnhancedRequest<T> request) { throw new UnsupportedOperationException(); } /** * Puts a single item in the mapped table. If the table contains an item with the same primary key, it will be * replaced with this item. This is similar to {@link #putItem(PutItemEnhancedRequest)} but returns * {@link PutItemEnhancedResponse} for additional information. * <p> * The additional configuration parameters that the enhanced client supports are defined * in the {@link PutItemEnhancedRequest}. * <p> * This operation calls the low-level DynamoDB API PutItem operation. Consult the PutItem documentation for * further details and constraints. * <p> * Example: * <pre> * {@code * * mappedTable.putItem(PutItemEnhancedRequest.builder(MyItem.class).item(item).build()); * } * </pre> * * @param requestConsumer A {@link Consumer} of {@link PutItemEnhancedRequest.Builder} that includes the item * to enter into the table, its class and optional directives. * * @return The response returned by DynamoDB. */ default PutItemEnhancedResponse<T> putItemWithResponse(Consumer<PutItemEnhancedRequest.Builder<T>> requestConsumer) { throw new UnsupportedOperationException(); } /** * Scans the table and retrieves all items. * <p> * The result can be accessed either through iterable {@link Page}s or items across all pages directly. Each time a * result page is retrieved, a query call is made to DynamoDb to get those entries. If no matches are found, * the resulting iterator will contain an empty page. * <p> * The additional configuration parameters that the enhanced client supports are defined * in the {@link ScanEnhancedRequest}. * <p> * Example: * <p> * 1) Iterating through pages * <pre> * {@code * * PageIterable<MyItem> results = mappedTable.scan(ScanEnhancedRequest.builder().consistentRead(true).build()); * results.stream().forEach(p -> p.items().forEach(item -> System.out.println(item))) * } * </pre> * * <p> * 2) Iterating through items * <pre> * {@code * * PageIterable<MyItem> results = mappedTable.scan(ScanEnhancedRequest.builder().consistentRead(true).build()); * results.items().stream().forEach(item -> System.out.println(item)); * } * </pre> * * @see #scan(Consumer) * @see #scan() * @see DynamoDbClient#scanPaginator * @param request A {@link ScanEnhancedRequest} defining how to handle the results. * @return an iterator of type {@link SdkIterable} with paginated results (see {@link Page}). */ default PageIterable<T> scan(ScanEnhancedRequest request) { throw new UnsupportedOperationException(); } /** * This is a convenience method that creates an instance of the request builder avoiding the need to create one * manually via {@link ScanEnhancedRequest#builder()}. * * <p> * Example: * <pre> * {@code * * PageIterable<MyItem> results = mappedTable.scan(r -> r.limit(5)); * } * </pre> * * @see #scan(ScanEnhancedRequest) * @see #scan() * @param requestConsumer A {@link Consumer} of {@link ScanEnhancedRequest} defining the query conditions and how to * handle the results. * @return an iterator of type {@link SdkIterable} with paginated results (see {@link Page}). */ default PageIterable<T> scan(Consumer<ScanEnhancedRequest.Builder> requestConsumer) { throw new UnsupportedOperationException(); } /** * Scans the table and retrieves all items using default settings. * <p> * The result can be accessed either through iterable {@link Page}s or items across all pages directly. Each time a * result page is retrieved, a query call is made to DynamoDb to get those entries. If no matches are found, * the resulting iterator will contain an empty page. * <p> * Example: * <pre> * {@code * * PageIterable<MyItem> results = mappedTable.scan(); * } * </pre> * * @see #scan(ScanEnhancedRequest) * @see #scan(Consumer) * @see DynamoDbClient#scanPaginator * @return an iterator of type {@link SdkIterable} with paginated results (see {@link Page}). */ default PageIterable<T> scan() { throw new UnsupportedOperationException(); } /** * Updates an item in the mapped table, or adds it if it doesn't exist. * <p> * The additional configuration parameters that the enhanced client supports are defined * in the {@link UpdateItemEnhancedRequest}. * <p> * This operation calls the low-level DynamoDB API UpdateItem operation. Consult the UpdateItem documentation for * further details and constraints. * <p> * Example: * <pre> * {@code * * MyItem item = mappedTable.updateItem(UpdateItemEnhancedRequest.builder(MyItem.class).item(item).build()); * } * </pre> * * @param request A {@link UpdateItemEnhancedRequest} that includes the item to be updated, * its class and optional directives. * @return The updated item */ default T updateItem(UpdateItemEnhancedRequest<T> request) { throw new UnsupportedOperationException(); } /** * Updates an item in the mapped table, or adds it if it doesn't exist. * <p> * The additional configuration parameters that the enhanced client supports are defined * in the {@link UpdateItemEnhancedRequest}. * <p> * This operation calls the low-level DynamoDB API UpdateItem operation. Consult the UpdateItem documentation for * further details and constraints. * <p> * Example: * <pre> * {@code * * MyItem item = mappedTable.updateItem(r -> r.item(item)); * } * </pre> * * @param requestConsumer A {@link Consumer} of {@link UpdateItemEnhancedRequest.Builder} that includes the item * to be updated, its class and optional directives. * @return The updated item */ default T updateItem(Consumer<UpdateItemEnhancedRequest.Builder<T>> requestConsumer) { throw new UnsupportedOperationException(); } /** * Updates an item in the mapped table, or adds it if it doesn't exist. * <p> * This operation calls the low-level DynamoDB API UpdateItem operation. Consult the UpdateItem documentation for * further details and constraints. * <p> * Example: * <pre> * {@code * * MyItem item = mappedTable.updateItem(item); * } * </pre> * * @param item the modelled item to be inserted into or updated in the database table. * @return The updated item */ default T updateItem(T item) { throw new UnsupportedOperationException(); } /** * Updates an item in the mapped table, or adds it if it doesn't exist. This is similar to * {@link #updateItem(UpdateItemEnhancedRequest)}} but returns {@link UpdateItemEnhancedResponse} for additional information. * <p> * This operation calls the low-level DynamoDB API UpdateItem operation. Consult the UpdateItem documentation for * further details and constraints. * <p> * Example: * <pre> * {@code * UpdateItemEnhancedRequest<MyItem> request = UpdateItemEnhancedRequest.builder(MyItem.class).item(myItem).build(); * UpdateItemEnhancedResponse<MyItem> response = mappedTable.updateItemWithResponse(request); * } * </pre> * <p> * * * @param request the modelled item to be inserted into or updated in the database table. * @return The response returned by DynamoDB. */ default UpdateItemEnhancedResponse<T> updateItemWithResponse(UpdateItemEnhancedRequest<T> request) { throw new UnsupportedOperationException(); } /** * Updates an item in the mapped table, or adds it if it doesn't exist. This is similar to * {@link #updateItem(Consumer)} but returns {@link UpdateItemEnhancedResponse} for additional information. * <p> * This operation calls the low-level DynamoDB API UpdateItem operation. Consult the UpdateItem documentation for * further details and constraints. * <p> * Example: * <pre> * {@code * * UpdateItemEnhancedResponse<MyItem> response = mappedTable.updateItemWithResponse(r ->r.item(myItem)); * } * </pre> * <p> * * * @param requestConsumer A {@link Consumer} of {@link UpdateItemEnhancedRequest.Builder} that includes the item * * to be updated, its class and optional directives. * @return The response from DynamoDB. */ default UpdateItemEnhancedResponse<T> updateItemWithResponse(Consumer<UpdateItemEnhancedRequest.Builder<T>> requestConsumer) { throw new UnsupportedOperationException(); } /** * Deletes a table in DynamoDb with the name and schema already defined for this DynamoDbTable. * <p> * Use {@link DynamoDbEnhancedClient#table(String, TableSchema)} to define the mapped table resource. * <p> * This operation calls the low-level DynamoDB API DeleteTable operation. * Note that this is an asynchronous operation and that the table may not immediately be deleted. You can use * {@link DynamoDbWaiter#waitUntilTableNotExists} * in the underlying client. * <p> * Example: * <pre> * {@code * * mappedTable.deleteTable(); * } * </pre> * */ default void deleteTable() { throw new UnsupportedOperationException(); } /** * Describes a table in DynamoDb with the name defined for this {@link DynamoDbTable}. * This operation calls the low-level DynamoDB API DescribeTable operation, * see {@link DynamoDbClient#describeTable(DescribeTableRequest)} * <p> * Example: * <pre> * {@code * * DescribeTableEnhancedResponse response = mappedTable.describeTable(); * } * </pre> * */ default DescribeTableEnhancedResponse describeTable() { throw new UnsupportedOperationException(); } }
4,357
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/DynamoDbAsyncIndex.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb; import java.util.function.Consumer; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.core.async.SdkPublisher; 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.enhanced.dynamodb.model.ScanEnhancedRequest; /** * Asynchronous interface for running commands against an object that is linked to a specific DynamoDb secondary index * and knows how to map records from the table that index is linked to into a modelled object. * <p> * By default, all command methods throw an {@link UnsupportedOperationException} to prevent interface extensions from breaking * implementing classes. * * @param <T> The type of the modelled object. */ @SdkPublicApi @ThreadSafe public interface DynamoDbAsyncIndex<T> { /** * Executes a query against a secondary index using a {@link QueryConditional} expression to retrieve a list of * items matching the given conditions. * <p> * The result is accessed through iterable pages (see {@link Page}) in an interactive way; each time a * result page is retrieved, a query call is made to DynamoDb to get those entries. If no matches are found, * the resulting iterator will contain an empty page. Results are sorted by sort key value in * ascending order by default; this behavior can be overridden in the {@link QueryEnhancedRequest}. * <p> * The additional configuration parameters that the enhanced client supports are defined * in the {@link QueryEnhancedRequest}. * <p> * This operation calls the low-level DynamoDB API Query operation. Consult the Query documentation for * further details and constraints. * <p> * Example: * <pre> * {@code * * QueryConditional queryConditional = QueryConditional.keyEqualTo(Key.builder().partitionValue("id-value").build()); * SdkPublisher<Page<MyItem>> publisher = mappedIndex.query(QueryEnhancedRequest.builder() * .queryConditional(queryConditional) * .build()); * } * </pre> * * @param request A {@link QueryEnhancedRequest} defining the query conditions and how * to handle the results. * @return a publisher {@link SdkPublisher} with paginated results (see {@link Page}). */ default SdkPublisher<Page<T>> query(QueryEnhancedRequest request) { throw new UnsupportedOperationException(); } /** * Executes a query against a secondary index using a {@link QueryConditional} expression to retrieve a list of * items matching the given conditions. * <p> * The result is accessed through iterable pages (see {@link Page}) in an interactive way; each time a * result page is retrieved, a query call is made to DynamoDb to get those entries. If no matches are found, * the resulting iterator will contain an empty page. Results are sorted by sort key value in * ascending order by default; this behavior can be overridden in the {@link QueryEnhancedRequest}. * <p> * The additional configuration parameters that the enhanced client supports are defined * in the {@link QueryEnhancedRequest}. * <p> * This operation calls the low-level DynamoDB API Query operation. Consult the Query documentation for * further details and constraints. * <p> * <b>Note:</b> This is a convenience method that creates an instance of the request builder avoiding the need to create one * manually via {@link QueryEnhancedRequest#builder()}. * <p> * Example: * <pre> * {@code * * SdkPublisher<Page<MyItem>> publisher = * mappedIndex.query(r -> r.queryConditional(QueryConditional.keyEqualTo(k -> k.partitionValue("id-value")))); * } * </pre> * * @param requestConsumer A {@link Consumer} of {@link QueryEnhancedRequest} defining the query conditions and how to * handle the results. * @return a publisher {@link SdkPublisher} with paginated results (see {@link Page}). */ default SdkPublisher<Page<T>> query(Consumer<QueryEnhancedRequest.Builder> requestConsumer) { throw new UnsupportedOperationException(); } /** * Executes a query against the secondary index of the table using a {@link QueryConditional} expression to retrieve * a list of items matching the given conditions. * <p> * The result is accessed through iterable pages (see {@link Page}) in an interactive way; each time a * result page is retrieved, a query call is made to DynamoDb to get those entries. If no matches are found, * the resulting iterator will contain an empty page. Results are sorted by sort key value in * ascending order. * <p> * This operation calls the low-level DynamoDB API Query operation. Consult the Query documentation for * further details and constraints. * <p> * Example: * <pre> * {@code * * SdkPublisher<Page<MyItem>> results = * mappedIndex.query(QueryConditional.keyEqualTo(Key.builder().partitionValue("id-value").build())); * } * </pre> * * @param queryConditional A {@link QueryConditional} defining the matching criteria for records to be queried. * @return a publisher {@link SdkPublisher} with paginated results (see {@link Page}). */ default SdkPublisher<Page<T>> query(QueryConditional queryConditional) { throw new UnsupportedOperationException(); } /** * Scans the table against a secondary index and retrieves all items. * <p> * The result is accessed through iterable pages (see {@link Page}) in an interactive way; each time a * result page is retrieved, a scan call is made to DynamoDb to get those entries. If no matches are found, * the resulting iterator will contain an empty page. * <p> * The additional configuration parameters that the enhanced client supports are defined * in the {@link ScanEnhancedRequest}. * <p> * Example: * <pre> * {@code * * SdkPublisher<Page<MyItem>> publisher = mappedTable.scan(ScanEnhancedRequest.builder().consistentRead(true).build()); * } * </pre> * * @param request A {@link ScanEnhancedRequest} defining how to handle the results. * @return a publisher {@link SdkPublisher} with paginated results (see {@link Page}). */ default SdkPublisher<Page<T>> scan(ScanEnhancedRequest request) { throw new UnsupportedOperationException(); } /** * Scans the table against a secondary index and retrieves all items. * <p> * The result is accessed through iterable pages (see {@link Page}) in an interactive way; each time a * result page is retrieved, a scan call is made to DynamoDb to get those entries. If no matches are found, * the resulting iterator will contain an empty page. * <p> * The additional configuration parameters that the enhanced client supports are defined * in the {@link ScanEnhancedRequest}. * <p> * <b>Note:</b> This is a convenience method that creates an instance of the request builder avoiding the need to create one * manually via {@link ScanEnhancedRequest#builder()}. * <p> * Example: * <pre> * {@code * * SdkPublisher<Page<MyItem>> publisher = mappedTable.scan(r -> r.limit(5)); * } * </pre> * * @param requestConsumer A {@link Consumer} of {@link ScanEnhancedRequest} defining the query conditions and how to * handle the results. * @return a publisher {@link SdkPublisher} with paginated results (see {@link Page}). */ default SdkPublisher<Page<T>> scan(Consumer<ScanEnhancedRequest.Builder> requestConsumer) { throw new UnsupportedOperationException(); } /** * Scans the table against a secondary index and retrieves all items using default settings. * <p> * The result is accessed through iterable pages (see {@link Page}) in an interactive way; each time a * result page is retrieved, a scan call is made to DynamoDb to get those entries. If no matches are found, * the resulting iterator will contain an empty page. * <p> * Example: * <pre> * {@code * * SdkPublisher<Page<MyItem>> publisher = mappedTable.scan(); * } * </pre> * * @return a publisher {@link SdkPublisher} with paginated results (see {@link Page}). */ default SdkPublisher<Page<T>> scan() { throw new UnsupportedOperationException(); } /** * Gets the {@link DynamoDbEnhancedClientExtension} associated with this mapped resource. * @return The {@link DynamoDbEnhancedClientExtension} associated with this mapped resource. */ DynamoDbEnhancedClientExtension mapperExtension(); /** * Gets the {@link TableSchema} object that this mapped table was built with. * @return The {@link TableSchema} object for this mapped table. */ TableSchema<T> tableSchema(); /** * Gets the physical table name that operations performed by this object will be executed against. * @return The physical table name. */ String tableName(); /** * Gets the physical secondary index name that operations performed by this object will be executed against. * @return The physical secondary index name. */ String indexName(); /** * Creates a {@link Key} object from a modelled item. This key can be used in query conditionals and get * operations to locate a specific record. * @param item The item to extract the key fields from. * @return A key that has been initialized with the index values extracted from the modelled object. */ Key keyFrom(T item); }
4,358
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/DynamoDbAsyncTable.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.enhanced.dynamodb.model.CreateTableEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.DeleteItemEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.DeleteItemEnhancedResponse; import software.amazon.awssdk.enhanced.dynamodb.model.DescribeTableEnhancedResponse; import software.amazon.awssdk.enhanced.dynamodb.model.GetItemEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.GetItemEnhancedResponse; import software.amazon.awssdk.enhanced.dynamodb.model.Page; import software.amazon.awssdk.enhanced.dynamodb.model.PagePublisher; import software.amazon.awssdk.enhanced.dynamodb.model.PutItemEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.PutItemEnhancedResponse; import software.amazon.awssdk.enhanced.dynamodb.model.QueryConditional; import software.amazon.awssdk.enhanced.dynamodb.model.QueryEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.ScanEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.UpdateItemEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.UpdateItemEnhancedResponse; import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient; import software.amazon.awssdk.services.dynamodb.model.ConsumedCapacity; import software.amazon.awssdk.services.dynamodb.model.DescribeTableRequest; import software.amazon.awssdk.services.dynamodb.waiters.DynamoDbAsyncWaiter; /** * Asynchronous interface for running commands against an object that is linked to a specific DynamoDb table resource * and therefore knows how to map records from that table into a modelled object. * <p> * By default, all command methods throw an {@link UnsupportedOperationException} to prevent interface extensions from breaking * implementing classes. * * @param <T> The type of the modelled object. */ @SdkPublicApi @ThreadSafe public interface DynamoDbAsyncTable<T> extends MappedTableResource<T> { /** * Returns a mapped index that can be used to execute commands against a secondary index belonging to the table * being mapped by this object. Note that only a subset of the commands that work against a table will work * against a secondary index. * * @param indexName The name of the secondary index to build the command interface for. * @return An {@link DynamoDbAsyncIndex} object that can be used to execute database commands against. */ DynamoDbAsyncIndex<T> index(String indexName); /** * Creates a new table in DynamoDb with the name and schema already defined for this DynamoDbTable * together with additional parameters specified in the supplied request object, {@link CreateTableEnhancedRequest}. * <p> * Use {@link DynamoDbEnhancedClient#table(String, TableSchema)} to define the mapped table resource. * <p> * This operation calls the low-level DynamoDB API CreateTable operation. Note that this is an asynchronous operation and that * the table may not immediately be available for writes and reads. * You can use {@link DynamoDbAsyncWaiter#waitUntilTableExists(DescribeTableRequest)} to wait for the resource to be ready. * <p> * Example: * <pre> * {@code * * ProvisionedThroughput provisionedThroughput = ProvisionedThroughput.builder() * .readCapacityUnits(50L) * .writeCapacityUnits(50L) * .build(); * mappedTable.createTable(CreateTableEnhancedRequest.builder() * .provisionedThroughput(provisionedThroughput) * .build()) * .join(); * asyncClient.waiter().waitUntilTableExists(b -> b.tableName(tableName)).join(); * } * </pre> * * @param request A {@link CreateTableEnhancedRequest} containing optional parameters for table creation. * @return a {@link CompletableFuture} of {@link Void}. */ default CompletableFuture<Void> createTable(CreateTableEnhancedRequest request) { throw new UnsupportedOperationException(); } /** * Creates a new table in DynamoDb with the name and schema already defined for this DynamoDbTable * together with additional parameters specified in the supplied request object, {@link CreateTableEnhancedRequest}. * <p> * Use {@link DynamoDbEnhancedClient#table(String, TableSchema)} to define the mapped table resource. * <p> * This operation calls the low-level DynamoDB API CreateTable operation. Note that this is an asynchronous operation and that * the table may not immediately be available for writes and reads. You can use * {@link DynamoDbAsyncWaiter#waitUntilTableExists(DescribeTableRequest)} to wait for the resource to be ready. * <p> * <b>Note:</b> This is a convenience method that creates an instance of the request builder avoiding the need to create one * manually via {@link CreateTableEnhancedRequest#builder()}. * <p> * Example: * <pre> * {@code * * ProvisionedThroughput provisionedThroughput = ProvisionedThroughput.builder() * .readCapacityUnits(50L) * .writeCapacityUnits(50L) * .build(); * mappedTable.createTable(r -> r.provisionedThroughput(provisionedThroughput)).join(); * asyncClient.waiter().waitUntilTableExists(b -> b.tableName(tableName)).join(); * } * </pre> * * @param requestConsumer A {@link Consumer} of {@link CreateTableEnhancedRequest.Builder} containing optional parameters * for table creation. * @return a {@link CompletableFuture} of {@link Void}. */ default CompletableFuture<Void> createTable(Consumer<CreateTableEnhancedRequest.Builder> requestConsumer) { throw new UnsupportedOperationException(); } /** * Creates a new table in DynamoDb with the name and schema already defined for this DynamoDbTable. * <p> * Use {@link DynamoDbEnhancedClient#table(String, TableSchema)} to define the mapped table resource. * <p> * This operation calls the low-level DynamoDB API CreateTable operation. Note that this is an asynchronous operation and that * the table may not immediately be available for writes and reads. You can use * {@link DynamoDbAsyncWaiter#waitUntilTableExists(DescribeTableRequest)} to wait for the resource to be ready. * <p> * Example: * <pre> * {@code * * mappedTable.createTable().join(); * asyncClient.waiter().waitUntilTableExists(b -> b.tableName(tableName)).join(); * } * </pre> * * @return a {@link CompletableFuture} of {@link Void}. */ default CompletableFuture<Void> createTable() { throw new UnsupportedOperationException(); } /** * Deletes a single item from the mapped table using a supplied primary {@link Key}. * <p> * The additional configuration parameters that the enhanced client supports are defined * in the {@link DeleteItemEnhancedRequest}. * <p> * This operation calls the low-level DynamoDB API DeleteItem operation. Consult the DeleteItem documentation for * further details and constraints. * <p> * Example: * <pre> * {@code * * MyItem previouslyPersistedItem = mappedTable.delete(DeleteItemEnhancedRequest.builder().key(key).build()).join(); * } * </pre> * * @param request A {@link DeleteItemEnhancedRequest} with key and optional directives for deleting an item from the table. * @return a {@link CompletableFuture} of the item that was persisted in the database before it was deleted. */ default CompletableFuture<T> deleteItem(DeleteItemEnhancedRequest request) { throw new UnsupportedOperationException(); } /** * Deletes a single item from the mapped table using a supplied primary {@link Key}. * <p> * The additional configuration parameters that the enhanced client supports are defined * in the {@link DeleteItemEnhancedRequest}. * <p> * This operation calls the low-level DynamoDB API DeleteItem operation. Consult the DeleteItem documentation for * further details and constraints. * <p> * <b>Note:</b> This is a convenience method that creates an instance of the request builder avoiding the need to create one * manually via {@link DeleteItemEnhancedRequest#builder()}. * <p> * Example: * <pre> * {@code * * MyItem previouslyPersistedItem = mappedTable.delete(r -> r.key(key)).join(); * } * </pre> * * @param requestConsumer A {@link Consumer} of {@link DeleteItemEnhancedRequest} with key and * optional directives for deleting an item from the table. * @return a {@link CompletableFuture} of the item that was persisted in the database before it was deleted. */ default CompletableFuture<T> deleteItem(Consumer<DeleteItemEnhancedRequest.Builder> requestConsumer) { throw new UnsupportedOperationException(); } /** * Deletes a single item from the mapped table using a supplied primary {@link Key}. * <p> * This operation calls the low-level DynamoDB API DeleteItem operation. Consult the DeleteItem documentation for * further details and constraints. * <p> * Example: * <pre> * {@code * * MyItem previouslyPersistedItem = mappedTable.delete(key).join; * } * </pre> * * @param key A {@link Key} that will be used to match a specific record to delete from the database table. * @return a {@link CompletableFuture} of the item that was persisted in the database before it was deleted. */ default CompletableFuture<T> deleteItem(Key key) { throw new UnsupportedOperationException(); } /** * Deletes a single item from the mapped table using just the key of a supplied modelled 'key item' object. * <p> * This operation calls the low-level DynamoDB API DeleteItem operation. Consult the DeleteItem documentation for * further details and constraints. * <p> * Example: * <pre> * {@code * * MyItem previouslyPersistedItem = mappedTable.deleteItem(keyItem).join(); * } * </pre> * * @param keyItem A modelled item with the primary key fields set that will be used to match a specific record to * delete from the database table. * @return a {@link CompletableFuture} of the item that was persisted in the database before it was deleted. */ default CompletableFuture<T> deleteItem(T keyItem) { throw new UnsupportedOperationException(); } /** * Deletes a single item from the mapped table using a supplied primary {@link Key}. * <p> * The additional configuration parameters that the enhanced client supports are defined * in the {@link DeleteItemEnhancedRequest}. * <p> * This operation calls the low-level DynamoDB API DeleteItem operation. Consult the DeleteItem documentation for * further details and constraints. Unlike {@link #deleteItem(DeleteItemEnhancedRequest)}, this returns a response object, * allowing the user to retrieve additional information from DynamoDB related to the API call, such as * {@link ConsumedCapacity} if specified on the request. * <p> * Example: * <pre> * {@code * * DeleteItemEnhancedRequest request = DeleteItemEnhancedRequest.builder().key(key).build(); * DeleteItemEnhancedResponse<MyItem> response = mappedTable.deleteItemWithResponse(request).join(); * } * </pre> * * @param request A {@link DeleteItemEnhancedRequest} with key and optional directives for deleting an item from the * table. * @return A {@code CompletableFuture} containing the response returned by DynamoDB. */ default CompletableFuture<DeleteItemEnhancedResponse<T>> deleteItemWithResponse(DeleteItemEnhancedRequest request) { throw new UnsupportedOperationException(); } /** * Deletes a single item from the mapped table using a supplied primary {@link Key}. * <p> * The additional configuration parameters that the enhanced client supports are defined * in the {@link DeleteItemEnhancedRequest}. * <p> * This operation calls the low-level DynamoDB API DeleteItem operation. Consult the DeleteItem documentation for * further details and constraints. Unlike {@link #deleteItem(Consumer)}, this returns a response object, allowing the user to * retrieve additional information from DynamoDB related to the API call, such as {@link ConsumedCapacity} if specified on * the request. * <p> * <b>Note:</b> This is a convenience method that creates an instance of the request builder avoiding the need to * create one manually via {@link DeleteItemEnhancedRequest#builder()}. * <p> * Example: * <pre> * {@code * * DeleteItemEnhancedResponse<MyItem> response = mappedTable.deleteWithResponse(r -> r.key(key)).join(); * } * </pre> * * @param requestConsumer A {@link Consumer} of {@link DeleteItemEnhancedRequest} with key and * optional directives for deleting an item from the table. * @return A {@code CompletableFuture} containing the response returned by DynamoDB. */ default CompletableFuture<DeleteItemEnhancedResponse<T>> deleteItemWithResponse( Consumer<DeleteItemEnhancedRequest.Builder> requestConsumer) { throw new UnsupportedOperationException(); } /** * Retrieves a single item from the mapped table using a supplied primary {@link Key}. * <p> * The additional configuration parameters that the enhanced client supports are defined * in the {@link GetItemEnhancedRequest}. * <p> * This operation calls the low-level DynamoDB API GetItem operation. Consult the GetItem documentation for * further details and constraints. * <p> * Example: * <pre> * {@code * * MyItem item = mappedTable.getItem(GetItemEnhancedRequest.builder().key(key).build()).join(); * } * </pre> * * @param request A {@link GetItemEnhancedRequest} with key and optional directives for retrieving an item from the table. * @return a {@link CompletableFuture} of the item that was persisted in the database before it was deleted. */ default CompletableFuture<T> getItem(GetItemEnhancedRequest request) { throw new UnsupportedOperationException(); } /** * Retrieves a single item from the mapped table using a supplied primary {@link Key}. * <p> * The additional configuration parameters that the enhanced client supports are defined * in the {@link GetItemEnhancedRequest}. * <p> * This operation calls the low-level DynamoDB API GetItem operation. Consult the GetItem documentation for * further details and constraints. * <p> * <b>Note:</b> This is a convenience method that creates an instance of the request builder avoiding the need to create one * manually via {@link GetItemEnhancedRequest#builder()}. * <p> * Example: * <pre> * {@code * * MyItem item = mappedTable.getItem(r -> r.key(key)).join(); * } * </pre> * * @param requestConsumer A {@link Consumer} of {@link GetItemEnhancedRequest.Builder} with key and optional directives * for retrieving an item from the table. * @return a {@link CompletableFuture} of the retrieved item */ default CompletableFuture<T> getItem(Consumer<GetItemEnhancedRequest.Builder> requestConsumer) { throw new UnsupportedOperationException(); } /** * Retrieves a single item from the mapped table using a supplied primary {@link Key}. * <p> * This operation calls the low-level DynamoDB API GetItem operation. Consult the GetItem documentation for * further details and constraints. * <p> * Example: * <pre> * {@code * * MyItem item = mappedTable.getItem(key).join(); * } * </pre> * * @param key A {@link Key} that will be used to match a specific record to retrieve from the database table. * @return a {@link CompletableFuture} of the retrieved item */ default CompletableFuture<T> getItem(Key key) { throw new UnsupportedOperationException(); } /** * Retrieves a single item from the mapped table using just the key of a supplied modelled 'key item'. * <p> * This operation calls the low-level DynamoDB API GetItem operation. Consult the GetItem documentation for * further details and constraints. * <p> * Example: * <pre> * {@code * * MyItem item = mappedTable.getItem(keyItem).join(); * } * </pre> * * @param keyItem A modelled item with the primary key fields set that will be used to match a specific record to * retrieve from the database table. * @return a {@link CompletableFuture} of the retrieved item */ default CompletableFuture<T> getItem(T keyItem) { throw new UnsupportedOperationException(); } /** * Retrieves a single item from the mapped table using a supplied primary {@link Key}. This is similar to * {@link #getItem(GetItemEnhancedRequest)} but returns {@link GetItemEnhancedResponse} for * additional information. * * <p> * The additional configuration parameters that the enhanced client supports are defined * in the {@link GetItemEnhancedRequest}. * <p> * This operation calls the low-level DynamoDB API GetItem operation. Consult the GetItem documentation for * further details and constraints. * <p> * Example: * <pre> * {@code * * MyItem item = mappedTable.getItemWithResponse(GetItemEnhancedRequest.builder().key(key).build()).join(); * } * </pre> * * @param request A {@link GetItemEnhancedRequest} with key and optional directives for retrieving an item from the table. * @return a {@link CompletableFuture} of the item that was persisted in the database before it was deleted. */ default CompletableFuture<GetItemEnhancedResponse<T>> getItemWithResponse(GetItemEnhancedRequest request) { throw new UnsupportedOperationException(); } /** * Retrieves a single item from the mapped table using a supplied primary {@link Key}. This is similar to * {@link #getItem(Consumer<GetItemEnhancedRequest.Builder>)} but returns {@link GetItemEnhancedResponse} for * additional information. * * <p> * The additional configuration parameters that the enhanced client supports are defined * in the {@link GetItemEnhancedRequest}. * <p> * This operation calls the low-level DynamoDB API GetItem operation. Consult the GetItem documentation for * further details and constraints. * <p> * <b>Note:</b> This is a convenience method that creates an instance of the request builder avoiding the need to create one * manually via {@link GetItemEnhancedRequest#builder()}. * <p> * Example: * <pre> * {@code * * MyItem item = mappedTable.getItemWithResponse(r -> r.key(key)).join(); * } * </pre> * * @param requestConsumer A {@link Consumer} of {@link GetItemEnhancedRequest.Builder} with key and optional directives * for retrieving an item from the table. * @return a {@link CompletableFuture} of the retrieved item */ default CompletableFuture<GetItemEnhancedResponse<T>> getItemWithResponse( Consumer<GetItemEnhancedRequest.Builder> requestConsumer) { throw new UnsupportedOperationException(); } /** * Executes a query against the primary index of the table using a {@link QueryConditional} expression to retrieve a list of * items matching the given conditions. * <p> * The return type is a custom publisher that can be subscribed to request a stream of {@link Page}s or * a stream of items across all pages. Results are sorted by sort key value in * ascending order by default; this behavior can be overridden in the {@link QueryEnhancedRequest}. * <p> * The additional configuration parameters that the enhanced client supports are defined * in the {@link QueryEnhancedRequest}. * <p> * This operation calls the low-level DynamoDB API Query operation. Consult the Query documentation * {@link DynamoDbAsyncClient#queryPaginator} for further details and constraints. * <p> * Example: * <p> * 1) Subscribing to {@link Page}s * <pre> * {@code * * QueryConditional queryConditional = QueryConditional.keyEqualTo(Key.builder().partitionValue("id-value").build()); * PagePublisher<MyItem> publisher = mappedTable.query(QueryEnhancedRequest.builder() * .queryConditional(queryConditional) * .build()); * publisher.subscribe(page -> page.items().forEach(item -> System.out.println(item))); * } * </pre> * <p> * 2) Subscribing to items across all pages * <pre> * {@code * * QueryConditional queryConditional = QueryConditional.keyEqualTo(Key.builder().partitionValue("id-value").build()); * PagePublisher<MyItem> publisher = mappedTable.query(QueryEnhancedRequest.builder() * .queryConditional(queryConditional) * .build()) * .items(); * publisher.items().subscribe(item -> System.out.println(item)); * } * </pre> * * @see #query(Consumer) * @see #query(QueryConditional) * @see DynamoDbAsyncClient#queryPaginator * @param request A {@link QueryEnhancedRequest} defining the query conditions and how * to handle the results. * @return a publisher {@link PagePublisher} with paginated results (see {@link Page}). */ default PagePublisher<T> query(QueryEnhancedRequest request) { throw new UnsupportedOperationException(); } /** * Executes a query against the primary index of the table using a {@link QueryConditional} expression to retrieve a list of * items matching the given conditions. * <p> * <b>Note:</b> This is a convenience method that creates an instance of the request builder avoiding the need to create one * manually via {@link QueryEnhancedRequest#builder()}. * <p> * Example: * <pre> * {@code * * PagePublisher<MyItem> publisher = * mappedTable.query(r -> r.queryConditional(QueryConditional.keyEqualTo(k -> k.partitionValue("id-value")))); * } * </pre> * * @see #query(QueryEnhancedRequest) * @see #query(QueryConditional) * @see DynamoDbAsyncClient#queryPaginator * @param requestConsumer A {@link Consumer} of {@link QueryEnhancedRequest} defining the query conditions and how to * handle the results. * @return a publisher {@link PagePublisher} with paginated results (see {@link Page}). */ default PagePublisher<T> query(Consumer<QueryEnhancedRequest.Builder> requestConsumer) { throw new UnsupportedOperationException(); } /** * Executes a query against the primary index of the table using a {@link QueryConditional} expression to retrieve a * list of items matching the given conditions. * <p> * The result is accessed through iterable pages (see {@link Page}) in an interactive way; each time a * result page is retrieved, a query call is made to DynamoDb to get those entries. If no matches are found, * the resulting iterator will contain an empty page. Results are sorted by sort key value in * ascending order. * <p> * This operation calls the low-level DynamoDB API Query operation. Consult the Query documentation for * further details and constraints. * <p> * Example: * <pre> * {@code * * PagePublisher<MyItem> results = * mappedTable.query(QueryConditional.keyEqualTo(Key.builder().partitionValue("id-value").build())); * } * </pre> * * @see #query(QueryEnhancedRequest) * @see #query(Consumer) * @see DynamoDbAsyncClient#queryPaginator * @param queryConditional A {@link QueryConditional} defining the matching criteria for records to be queried. * @return a publisher {@link PagePublisher} with paginated results (see {@link Page}). */ default PagePublisher<T> query(QueryConditional queryConditional) { throw new UnsupportedOperationException(); } /** * Puts a single item in the mapped table. If the table contains an item with the same primary key, it will be replaced with * this item. * <p> * The additional configuration parameters that the enhanced client supports are defined * in the {@link PutItemEnhancedRequest}. * <p> * This operation calls the low-level DynamoDB API PutItem operation. Consult the PutItem documentation for * further details and constraints. * <p> * Example: * <pre> * {@code * * mappedTable.putItem(PutItemEnhancedRequest.builder(MyItem.class).item(item).build()).join(); * } * </pre> * * @param request A {@link PutItemEnhancedRequest} that includes the item to enter into * the table, its class and optional directives. * @return a {@link CompletableFuture} that returns no results which will complete when the operation is done. */ default CompletableFuture<Void> putItem(PutItemEnhancedRequest<T> request) { throw new UnsupportedOperationException(); } /** * Puts a single item in the mapped table. If the table contains an item with the same primary key, it will be replaced with * this item. * <p> * The additional configuration parameters that the enhanced client supports are defined * in the {@link PutItemEnhancedRequest}. * <p> * This operation calls the low-level DynamoDB API PutItem operation. Consult the PutItem documentation for * further details and constraints. * <p> * Example: * <pre> * {@code * * mappedTable.putItem(r -> r.item(item)).join(); * } * </pre> * * @param requestConsumer A {@link Consumer} of {@link PutItemEnhancedRequest.Builder} that includes the item * to enter into the table, its class and optional directives. * @return a {@link CompletableFuture} that returns no results which will complete when the operation is done. */ default CompletableFuture<Void> putItem(Consumer<PutItemEnhancedRequest.Builder<T>> requestConsumer) { throw new UnsupportedOperationException(); } /** * Puts a single item in the mapped table. If the table contains an item with the same primary key, it will be * replaced with this item. * <p> * This operation calls the low-level DynamoDB API PutItem operation. Consult the PutItem documentation for * further details and constraints. * <p> * Example: * <pre> * {@code * * mappedTable.putItem(item); * } * </pre> * * @param item the modelled item to be inserted into or overwritten in the database table. * @return a {@link CompletableFuture} that returns no results which will complete when the operation is done. */ default CompletableFuture<Void> putItem(T item) { throw new UnsupportedOperationException(); } /** * Puts a single item in the mapped table. If the table contains an item with the same primary key, it will be * replaced with this item. This is similar to {@link #putItem(PutItemEnhancedRequest)} but returns * {@link PutItemEnhancedResponse} for additional information. * <p> * The additional configuration parameters that the enhanced client supports are defined * in the {@link PutItemEnhancedRequest}. * <p> * This operation calls the low-level DynamoDB API PutItem operation. Consult the PutItem documentation for * further details and constraints. * <p> * Example: * <pre> * {@code * * mappedTable.putItem(PutItemEnhancedRequest.builder(MyItem.class).item(item).build()); * } * </pre> * * @param request A {@link PutItemEnhancedRequest} that includes the item to enter into * the table, its class and optional directives. * * @return A {@link CompletableFuture} that contains the response returned by DynamoDB. */ default CompletableFuture<PutItemEnhancedResponse<T>> putItemWithResponse(PutItemEnhancedRequest<T> request) { throw new UnsupportedOperationException(); } /** * Puts a single item in the mapped table. If the table contains an item with the same primary key, it will be * replaced with this item. This is similar to {@link #putItem(PutItemEnhancedRequest)} but returns * {@link PutItemEnhancedResponse} for additional information. * <p> * The additional configuration parameters that the enhanced client supports are defined * in the {@link PutItemEnhancedRequest}. * <p> * This operation calls the low-level DynamoDB API PutItem operation. Consult the PutItem documentation for * further details and constraints. * <p> * Example: * <pre> * {@code * * mappedTable.putItem(PutItemEnhancedRequest.builder(MyItem.class).item(item).build()); * } * </pre> * * @param requestConsumer A {@link Consumer} of {@link PutItemEnhancedRequest.Builder} that includes the item * to enter into the table, its class and optional directives. * * @return A {@link CompletableFuture} that contains the response returned by DynamoDB. */ default CompletableFuture<PutItemEnhancedResponse<T>> putItemWithResponse( Consumer<PutItemEnhancedRequest.Builder<T>> requestConsumer) { throw new UnsupportedOperationException(); } /** * Scans the table and retrieves all items. * <p> * The return type is a custom publisher that can be subscribed to request a stream of {@link Page}s or * a stream of flattened items across all pages. Each time a result page is retrieved, a scan call is made * to DynamoDb to get those entries. If no matches are found, the resulting iterator will contain an empty page. * * <p> * The additional configuration parameters that the enhanced client supports are defined * in the {@link ScanEnhancedRequest}. * <p> * Example: * <p> * 1) Subscribing to {@link Page}s * <pre> * {@code * * PagePublisher<MyItem> publisher = mappedTable.scan(ScanEnhancedRequest.builder().consistentRead(true).build()); * publisher.subscribe(page -> page.items().forEach(item -> System.out.println(item))); * } * </pre> * * <p> * 2) Subscribing to items across all pages. * <pre> * {@code * * PagePublisher<MyItem> publisher = mappedTable.scan(ScanEnhancedRequest.builder().consistentRead(true).build()); * publisher.items().subscribe(item -> System.out.println(item)); * } * </pre> * * @see #scan(Consumer) * @see #scan() * @see DynamoDbAsyncClient#scanPaginator * @param request A {@link ScanEnhancedRequest} defining how to handle the results. * @return a publisher {@link PagePublisher} with paginated results (see {@link Page}). */ default PagePublisher<T> scan(ScanEnhancedRequest request) { throw new UnsupportedOperationException(); } /** * Scans the table and retrieves all items. * <p> * Example: * <pre> * {@code * * PagePublisher<MyItem> publisher = mappedTable.scan(r -> r.limit(5)); * } * </pre> * * @see #scan(ScanEnhancedRequest) * @see #scan() * @see DynamoDbAsyncClient#scanPaginator * @param requestConsumer A {@link Consumer} of {@link ScanEnhancedRequest} defining the query conditions and how to * handle the results. * @return a publisher {@link PagePublisher} with paginated results (see {@link Page}). */ default PagePublisher<T> scan(Consumer<ScanEnhancedRequest.Builder> requestConsumer) { throw new UnsupportedOperationException(); } /** * Scans the table and retrieves all items using default settings. * * Example: * <pre> * {@code * * PagePublisher<MyItem> publisher = mappedTable.scan(); * } * </pre> * @see #scan(ScanEnhancedRequest) * @see #scan(Consumer) * @see DynamoDbAsyncClient#scanPaginator * @return a publisher {@link PagePublisher} with paginated results (see {@link Page}). */ default PagePublisher<T> scan() { throw new UnsupportedOperationException(); } /** * Updates an item in the mapped table, or adds it if it doesn't exist. * <p> * The additional configuration parameters that the enhanced client supports are defined * in the {@link UpdateItemEnhancedRequest}. * <p> * This operation calls the low-level DynamoDB API UpdateItem operation. Consult the UpdateItem documentation for * further details and constraints. * <p> * Example: * <pre> * {@code * * MyItem item = mappedTable.updateItem(UpdateItemEnhancedRequest.builder(MyItem.class).item(item).build()).join(); * } * </pre> * * @param request A {@link UpdateItemEnhancedRequest} that includes the item to be updated, * its class and optional directives. * @return a {@link CompletableFuture} of the updated item */ default CompletableFuture<T> updateItem(UpdateItemEnhancedRequest<T> request) { throw new UnsupportedOperationException(); } /** * Updates an item in the mapped table, or adds it if it doesn't exist. * <p> * The additional configuration parameters that the enhanced client supports are defined * in the {@link UpdateItemEnhancedRequest}. * <p> * This operation calls the low-level DynamoDB API UpdateItem operation. Consult the UpdateItem documentation for * further details and constraints. * <p> * Example: * <pre> * {@code * * MyItem item = mappedTable.updateItem(r -> r.item(item)).join(); * } * </pre> * * @param requestConsumer A {@link Consumer} of {@link UpdateItemEnhancedRequest.Builder} that includes the item * to be updated, its class and optional directives. * @return a {@link CompletableFuture} of the updated item */ default CompletableFuture<T> updateItem(Consumer<UpdateItemEnhancedRequest.Builder<T>> requestConsumer) { throw new UnsupportedOperationException(); } /** * Updates an item in the mapped table, or adds it if it doesn't exist. * <p> * This operation calls the low-level DynamoDB API UpdateItem operation. Consult the UpdateItem documentation for * further details and constraints. * <p> * Example: * <pre> * {@code * * MyItem item = mappedTable.updateItem(item).join(); * } * </pre> * * @param item the modelled item to be inserted into or updated in the database table. * @return a {@link CompletableFuture} of the updated item */ default CompletableFuture<T> updateItem(T item) { throw new UnsupportedOperationException(); } /** * Updates an item in the mapped table, or adds it if it doesn't exist. This is similar to * {@link #updateItem(UpdateItemEnhancedRequest)}} but returns {@link UpdateItemEnhancedResponse} for additional information. * <p> * This operation calls the low-level DynamoDB API UpdateItem operation. Consult the UpdateItem documentation for * further details and constraints. * <p> * Example: * <pre> * {@code * UpdateItemEnhancedRequest<MyItem> request = UpdateItemEnhancedRequest.builder(MyItem.class).item(myItem).build(); * UpdateItemEnhancedResponse<MyItem> response = mappedTable.updateItemWithResponse(request).join(); * } * </pre> * <p> * * * @param request the modelled item to be inserted into or updated in the database table. * @return A {@link CompletableFuture} containing the response from DynamoDB. */ default CompletableFuture<UpdateItemEnhancedResponse<T>> updateItemWithResponse(UpdateItemEnhancedRequest<T> request) { throw new UnsupportedOperationException(); } /** * Updates an item in the mapped table, or adds it if it doesn't exist. This is similar to * {@link #updateItem(Consumer)} but returns {@link UpdateItemEnhancedResponse} for additional information. * <p> * This operation calls the low-level DynamoDB API UpdateItem operation. Consult the UpdateItem documentation for * further details and constraints. * <p> * Example: * <pre> * {@code * * UpdateItemEnhancedResponse<MyItem> response = mappedTable.updateItemWithResponse(r ->r.item(myItem)).join(); * } * </pre> * <p> * * * @param requestConsumer A {@link Consumer} of {@link UpdateItemEnhancedRequest.Builder} that includes the item * * to be updated, its class and optional directives. * @return A {@link CompletableFuture} containing the response from DynamoDB. */ default CompletableFuture<UpdateItemEnhancedResponse<T>> updateItemWithResponse( Consumer<UpdateItemEnhancedRequest.Builder<T>> requestConsumer) { throw new UnsupportedOperationException(); } /** * Deletes a table in DynamoDb with the name and schema already defined for this DynamoDbTable. * <p> * Use {@link DynamoDbEnhancedClient#table(String, TableSchema)} to define the mapped table resource. * <p> * This operation calls the low-level DynamoDB API DeleteTable operation. * Note that this is an asynchronous operation and that the table may not immediately deleted. You can use * {@link software.amazon.awssdk.services.dynamodb.waiters.DynamoDbAsyncWaiter#waitUntilTableNotExists} * in the underlying client. * <p> * Example: * <pre> * {@code * * mappedTable.deleteTable().join(); * } * </pre> * * @return a {@link CompletableFuture} of {@link Void}. */ default CompletableFuture<Void> deleteTable() { throw new UnsupportedOperationException(); } /** * Describes a table in DynamoDb with the name defined for this {@link DynamoDbAsyncTable). * This operation calls the low-level DynamoDB API DescribeTable operation, * see {@link DynamoDbAsyncClient#describeTable(DescribeTableRequest)} * * <p> * Example: * <pre> * {@code * * DescribeTableEnhancedResponse response = mappedTable.describeTable().join(); * } * </pre> */ default CompletableFuture<DescribeTableEnhancedResponse> describeTable() { throw new UnsupportedOperationException(); } }
4,359
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/TableMetadata.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb; import java.util.Collection; import java.util.Map; import java.util.Optional; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType; /** * Interface for an object the stores structural information about a DynamoDb table. */ @SdkPublicApi @ThreadSafe public interface TableMetadata { /** * Returns the attribute name of the partition key for an index. * * @param indexName The name of the index. * @return The attribute name representing the partition key for this index. * @throws IllegalArgumentException if the index does not exist in the metadata or does not have a partition key * associated with it.. */ String indexPartitionKey(String indexName); /** * Returns the attribute name of the sort key for an index. * * @param indexName The name of the index. * @return Optional of the attribute name representing the sort key for this index; empty if the index does not * have a sort key. */ Optional<String> indexSortKey(String indexName); /** * Returns a custom metadata object. These objects are used by extensions to the library, therefore the type of * object stored is flexible and does not need to be known by the interface. * * @param key A unique key for the metadata object. This namespace is shared by all extensions, so it is * recommended best practice to qualify it with the name of your extension. * @param objectClass The java class that the object will be cast to before returning. An exception will be * thrown if the stored object cannot be cast to this class. * @param <T> The flexible type for the object being returned. The compiler will typically infer this. * @return An optional containing custom metadata object or empty if the object was not found. */ <T> Optional<T> customMetadataObject(String key, Class<? extends T> objectClass); /** * Returns all the names of attributes associated with the keys of a specified index. * * @param indexName The name of the index. * @return A collection of all key attribute names for that index. */ Collection<String> indexKeys(String indexName); /** * Returns all the names of attributes associated with any index (primary or secondary) known for this table. * Additionally any additional attributes that are deemed to be 'key-like' in how they should be treated will * also be returned. An example of a 'key-like' attribute that is not actually a key is one tagged as a 'version' * attribute when using the versioned record extension. * * @return A collection of all key attribute names for the table. * * @deprecated Use {@link #keyAttributes()} instead. */ @Deprecated Collection<String> allKeys(); /** * Returns metadata about all the known indices for this table. * @return A collection of {@link IndexMetadata} containing information about the indices. */ Collection<IndexMetadata> indices(); /** * Returns all custom metadata for this table. These entries are used by extensions to the library, therefore the * value type of each metadata object stored in the map is not known and is provided as {@link Object}. * <p> * This method should not be used to inspect individual custom metadata objects, instead use * {@link TableMetadata#customMetadataObject(String, Class)} ()} as that will perform a type-safety check on the * retrieved object. * @return A map of all the custom metadata for this table. */ Map<String, Object> customMetadata(); /** * Returns metadata about all the known 'key' attributes for this table, such as primary and secondary index keys, * or any other attribute that forms part of the structure of the table. * @return A collection of {@link KeyAttributeMetadata} containing information about the keys. */ Collection<KeyAttributeMetadata> keyAttributes(); /** * Returns the DynamoDb scalar attribute type associated with a key attribute if one is applicable. * @param keyAttribute The key attribute name to return the scalar attribute type of. * @return Optional {@link ScalarAttributeType} of the attribute, or empty if attribute is a non-scalar type. * @throws IllegalArgumentException if the keyAttribute is not found. */ Optional<ScalarAttributeType> scalarAttributeType(String keyAttribute); /** * Returns the attribute name used as the primary partition key for the table. * * @return The primary partition key attribute name. * @throws IllegalArgumentException if the primary partition key is not known. */ default String primaryPartitionKey() { return indexPartitionKey(primaryIndexName()); } /** * Returns the attribute name used as the primary sort key for the table. * * @return An optional of the primary sort key attribute name; empty if this key is not known. */ default Optional<String> primarySortKey() { return indexSortKey(primaryIndexName()); } /** * Returns the names of the attributes that make up the primary key for the table. * * @return A collection of attribute names that make up the primary key for the table. */ default Collection<String> primaryKeys() { return indexKeys(primaryIndexName()); } /** * Returns an arbitrary constant that should be used as the primary index name. This pattern creates a * common abstraction and simplifies the implementation of operations that also work on secondary indices such as * scan() and query(). * * @return An arbitrary constant that internally represents the primary index name. */ static String primaryIndexName() { // Must include illegal symbols that cannot be used by a real index. // This value is arbitrary and ephemeral but could end up being serialized with TableMetadata through the // actions of a client, so it should not be altered unless absolutely necessary. return "$PRIMARY_INDEX"; } }
4,360
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/IndexMetadata.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb; import java.util.Optional; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; /** * A metadata class that stores information about an index */ @SdkPublicApi @ThreadSafe public interface IndexMetadata { /** * The name of the index */ String name(); /** * The partition key for the index; if there is one. */ Optional<KeyAttributeMetadata> partitionKey(); /** * The sort key for the index; if there is one. */ Optional<KeyAttributeMetadata> sortKey(); }
4,361
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/DynamoDbIndex.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb; import java.util.function.Consumer; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.core.pagination.sync.SdkIterable; 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.enhanced.dynamodb.model.ScanEnhancedRequest; /** * Synchronous interface for running commands against an object that is linked to a specific DynamoDb secondary index * and knows how to map records from the table that index is linked to into a modelled object. * <p> * By default, all command methods throw an {@link UnsupportedOperationException} to prevent interface extensions from breaking * implementing classes. * * @param <T> The type of the modelled object. */ @SdkPublicApi @ThreadSafe public interface DynamoDbIndex<T> { /** * Executes a query against a secondary index using a {@link QueryConditional} expression to retrieve a list of * items matching the given conditions. * <p> * The result is accessed through iterable pages (see {@link Page}) in an interactive way; each time a * result page is retrieved, a query call is made to DynamoDb to get those entries. If no matches are found, * the resulting iterator will contain an empty page. Results are sorted by sort key value in * ascending order by default; this behavior can be overridden in the {@link QueryEnhancedRequest}. * <p> * The additional configuration parameters that the enhanced client supports are defined * in the {@link QueryEnhancedRequest}. * <p> * This operation calls the low-level DynamoDB API Query operation. Consult the Query documentation for * further details and constraints. * <p> * Example: * <pre> * {@code * * QueryConditional queryConditional = QueryConditional.keyEqualTo(Key.builder().partitionValue("id-value").build()); * Iterator<Page<MyItem>> results = mappedIndex.query(QueryEnhancedRequest.builder() * .queryConditional(queryConditional) * .build()); * } * </pre> * * @param request A {@link QueryEnhancedRequest} defining the query conditions and how * to handle the results. * @return an iterator of type {@link SdkIterable} with paginated results (see {@link Page}). */ default SdkIterable<Page<T>> query(QueryEnhancedRequest request) { throw new UnsupportedOperationException(); } /** * Executes a query against a secondary index using a {@link QueryConditional} expression to retrieve a list of * items matching the given conditions. * <p> * The result is accessed through iterable pages (see {@link Page}) in an interactive way; each time a * result page is retrieved, a query call is made to DynamoDb to get those entries. If no matches are found, * the resulting iterator will contain an empty page. Results are sorted by sort key value in * ascending order by default; this behavior can be overridden in the {@link QueryEnhancedRequest}. * <p> * The additional configuration parameters that the enhanced client supports are defined * in the {@link QueryEnhancedRequest}. * <p> * This operation calls the low-level DynamoDB API Query operation. Consult the Query documentation for * further details and constraints. * <p> * <b>Note:</b> This is a convenience method that creates an instance of the request builder avoiding the need to create one * manually via {@link QueryEnhancedRequest#builder()}. * <p> * Example: * <pre> * {@code * * Iterator<Page<MyItem>> results = * mappedIndex.query(r -> r.queryConditional(QueryConditional.keyEqualTo(k -> k.partitionValue("id-value")))); * } * </pre> * * @param requestConsumer A {@link Consumer} of {@link QueryEnhancedRequest} defining the query conditions and how to * handle the results. * @return an iterator of type {@link SdkIterable} with paginated results (see {@link Page}). */ default SdkIterable<Page<T>> query(Consumer<QueryEnhancedRequest.Builder> requestConsumer) { throw new UnsupportedOperationException(); } /** * Executes a query against the secondary index of the table using a {@link QueryConditional} expression to retrieve * a list of items matching the given conditions. * <p> * The result is accessed through iterable pages (see {@link Page}) in an interactive way; each time a * result page is retrieved, a query call is made to DynamoDb to get those entries. If no matches are found, * the resulting iterator will contain an empty page. Results are sorted by sort key value in * ascending order. * <p> * This operation calls the low-level DynamoDB API Query operation. Consult the Query documentation for * further details and constraints. * <p> * Example: * <pre> * {@code * * Iterator<Page<MyItem>> results = * mappedIndex.query(QueryConditional.keyEqualTo(Key.builder().partitionValue("id-value").build())); * } * </pre> * * @param queryConditional A {@link QueryConditional} defining the matching criteria for records to be queried. * @return an iterator of type {@link SdkIterable} with paginated results (see {@link Page}). */ default SdkIterable<Page<T>> query(QueryConditional queryConditional) { throw new UnsupportedOperationException(); } /** * Scans the table against a secondary index and retrieves all items. * <p> * The result is accessed through iterable pages (see {@link Page}) in an interactive way; each time a * result page is retrieved, a scan call is made to DynamoDb to get those entries. If no matches are found, * the resulting iterator will contain an empty page. * <p> * The additional configuration parameters that the enhanced client supports are defined * in the {@link ScanEnhancedRequest}. * <p> * Example: * <pre> * {@code * * Iterator<Page<MyItem>> results = mappedTable.scan(ScanEnhancedRequest.builder().consistentRead(true).build()); * } * </pre> * * @param request A {@link ScanEnhancedRequest} defining how to handle the results. * @return an iterator of type {@link SdkIterable} with paginated results (see {@link Page}). */ default SdkIterable<Page<T>> scan(ScanEnhancedRequest request) { throw new UnsupportedOperationException(); } /** * Scans the table against a secondary index and retrieves all items. * <p> * The result is accessed through iterable pages (see {@link Page}) in an interactive way; each time a * result page is retrieved, a scan call is made to DynamoDb to get those entries. If no matches are found, * the resulting iterator will contain an empty page. * <p> * The additional configuration parameters that the enhanced client supports are defined * in the {@link ScanEnhancedRequest}. * <p> * <b>Note:</b> This is a convenience method that creates an instance of the request builder avoiding the need to create one * manually via {@link ScanEnhancedRequest#builder()}. * <p> * Example: * <pre> * {@code * * Iterator<Page<MyItem>> results = mappedTable.scan(r -> r.limit(5)); * } * </pre> * * @param requestConsumer A {@link Consumer} of {@link ScanEnhancedRequest} defining the query conditions and how to * handle the results. * @return an iterator of type {@link SdkIterable} with paginated results (see {@link Page}). */ default SdkIterable<Page<T>> scan(Consumer<ScanEnhancedRequest.Builder> requestConsumer) { throw new UnsupportedOperationException(); } /** * Scans the table against a secondary index and retrieves all items using default settings. * <p> * The result is accessed through iterable pages (see {@link Page}) in an interactive way; each time a * result page is retrieved, a scan call is made to DynamoDb to get those entries. If no matches are found, * the resulting iterator will contain an empty page. * <p> * Example: * <pre> * {@code * * Iterator<Page<MyItem>> results = mappedTable.scan(); * } * </pre> * * @return an iterator of type {@link SdkIterable} with paginated results (see {@link Page}). */ default SdkIterable<Page<T>> scan() { throw new UnsupportedOperationException(); } /** * Gets the {@link DynamoDbEnhancedClientExtension} associated with this mapped resource. * @return The {@link DynamoDbEnhancedClientExtension} associated with this mapped resource. */ DynamoDbEnhancedClientExtension mapperExtension(); /** * Gets the {@link TableSchema} object that this mapped table was built with. * @return The {@link TableSchema} object for this mapped table. */ TableSchema<T> tableSchema(); /** * Gets the physical table name that operations performed by this object will be executed against. * @return The physical table name. */ String tableName(); /** * Gets the physical secondary index name that operations performed by this object will be executed against. * @return The physical secondary index name. */ String indexName(); /** * Creates a {@link Key} object from a modelled item. This key can be used in query conditionals and get * operations to locate a specific record. * @param item The item to extract the key fields from. * @return A key that has been initialized with the index values extracted from the modelled object. */ Key keyFrom(T item); }
4,362
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/DynamoDbExtensionContext.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb; import java.util.Map; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.OperationName; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * A wrapper for the immutable context objects that are visible to the {@link DynamoDbEnhancedClientExtension}s. */ @SdkPublicApi @ThreadSafe public final class DynamoDbExtensionContext { private DynamoDbExtensionContext() { } @SdkPublicApi @ThreadSafe public interface Context { /** * @return The {@link AttributeValue} map of the items that is about to be written or has just been read. */ Map<String, AttributeValue> items(); /** * @return The context under which the operation to be modified is taking place. */ OperationContext operationContext(); /** * @return A {@link TableMetadata} object describing the structure of the modelled table. */ TableMetadata tableMetadata(); /** * @return A {@link TableSchema} object describing the structure of the modelled table. */ default TableSchema<?> tableSchema() { throw new UnsupportedOperationException(); } } /** * The state of the execution when the {@link DynamoDbEnhancedClientExtension#beforeWrite} method is invoked. */ @SdkPublicApi @ThreadSafe public interface BeforeWrite extends Context { /** * @return The context under which the operation to be modified is taking place. */ OperationName operationName(); } /** * The state of the execution when the {@link DynamoDbEnhancedClientExtension#afterRead} method is invoked. */ @SdkPublicApi @ThreadSafe public interface AfterRead extends Context { } }
4,363
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/Document.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; /** * A document representing a table item in the form of a map containing attributes and values. * <p> * Use the {@link #getItem(MappedTableResource)} method to transform the collection of attributes into a typed item. */ @SdkPublicApi @ThreadSafe public interface Document { /** * Get the table item associated with the table schema in the mapped table resource. * * @param mappedTableResource the mapped table resource this item was retrieved from * @param <T> the type of items in the mapped table resource * @return the item constructed from the document */ <T> T getItem(MappedTableResource<T> mappedTableResource); }
4,364
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/EnhancedTypeDocumentConfiguration.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * Configuration for {@link EnhancedType} of document type */ @SdkPublicApi @ThreadSafe public final class EnhancedTypeDocumentConfiguration implements ToCopyableBuilder<EnhancedTypeDocumentConfiguration.Builder, EnhancedTypeDocumentConfiguration> { private final boolean preserveEmptyObject; private final boolean ignoreNulls; public EnhancedTypeDocumentConfiguration(Builder builder) { this.preserveEmptyObject = builder.preserveEmptyObject != null && builder.preserveEmptyObject; this.ignoreNulls = builder.ignoreNulls != null && builder.ignoreNulls; } /** * @return whether to initialize the associated {@link EnhancedType} as empty class when * mapping it to a Java object */ public boolean preserveEmptyObject() { return preserveEmptyObject; } /** * @return whether to ignore attributes with null values in the associated {@link EnhancedType}. */ public boolean ignoreNulls() { return ignoreNulls; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } EnhancedTypeDocumentConfiguration that = (EnhancedTypeDocumentConfiguration) o; if (preserveEmptyObject != that.preserveEmptyObject) { return false; } return ignoreNulls == that.ignoreNulls; } @Override public int hashCode() { int result = (preserveEmptyObject ? 1 : 0); result = 31 * result + (ignoreNulls ? 1 : 0); return result; } @Override public Builder toBuilder() { return builder().preserveEmptyObject(preserveEmptyObject).ignoreNulls(ignoreNulls); } public static Builder builder() { return new Builder(); } @NotThreadSafe public static final class Builder implements CopyableBuilder<Builder, EnhancedTypeDocumentConfiguration> { private Boolean preserveEmptyObject; private Boolean ignoreNulls; private Builder() { } /** * Specifies whether to initialize the associated {@link EnhancedType} as empty class when * mapping it to a Java object. By default, the value is false */ public Builder preserveEmptyObject(Boolean preserveEmptyObject) { this.preserveEmptyObject = preserveEmptyObject; return this; } /** * Specifies whether to ignore attributes with null values in the associated {@link EnhancedType}. * By default, the value is false */ public Builder ignoreNulls(Boolean ignoreNulls) { this.ignoreNulls = ignoreNulls; return this; } @Override public EnhancedTypeDocumentConfiguration build() { return new EnhancedTypeDocumentConfiguration(this); } } }
4,365
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/OperationContext.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; /** * A context object that is associated with a specific operation and identifies the resources that the operation is * meant to operate on. * <p> * This context is passed to and can be read by extension hooks (see {@link DynamoDbEnhancedClientExtension}). */ @SdkPublicApi @ThreadSafe public interface OperationContext { /** * The name of the table being operated on */ String tableName(); /** * The name of the index within the table being operated on. If it is the primary index, then this value will be * set to the constant {@link TableMetadata#primaryIndexName()}. */ String indexName(); }
4,366
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/Expression.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb; import java.util.Collections; import java.util.HashMap; import java.util.Map; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * High-level representation of a DynamoDB 'expression' that can be used in various situations where the API requires * or accepts an expression. In addition various convenience methods are provided to help manipulate expressions. * <p> * At a minimum, an expression must contain a string that is the expression itself. * <p> * Optionally, attribute names can be substituted with tokens using the '#name_token' syntax; also attribute values can * be substituted with tokens using the ':value_token' syntax. If tokens are used in the expression then the values or * names associated with those tokens must be explicitly added to the expressionValues and expressionNames maps * respectively that are also stored on this object. * <p> * Example:- * {@code * Expression myExpression = Expression.builder() * .expression("#a = :b") * .putExpressionName("#a", "myAttribute") * .putExpressionValue(":b", myAttributeValue) * .build(); * } */ @SdkPublicApi @ThreadSafe public final class Expression { private final String expression; private final Map<String, AttributeValue> expressionValues; private final Map<String, String> expressionNames; private Expression(String expression, Map<String, AttributeValue> expressionValues, Map<String, String> expressionNames) { this.expression = expression; this.expressionValues = expressionValues; this.expressionNames = expressionNames; } /** * Constructs a new expression builder. * @return a new expression builder. */ public static Builder builder() { return new Builder(); } /** * Coalesces two complete expressions into a single expression. The expression string will be joined using the * supplied join token, and the ExpressionNames and ExpressionValues maps will be merged. * @param expression1 The first expression to coalesce * @param expression2 The second expression to coalesce * @param joinToken The join token to be used to join the expression strings (e.g.: 'AND', 'OR') * @return The coalesced expression * @throws IllegalArgumentException if a conflict occurs when merging ExpressionNames or ExpressionValues */ public static Expression join(Expression expression1, Expression expression2, String joinToken) { if (expression1 == null) { return expression2; } if (expression2 == null) { return expression1; } return Expression.builder() .expression(joinExpressions(expression1.expression, expression2.expression, joinToken)) .expressionValues(joinValues(expression1.expressionValues(), expression2.expressionValues())) .expressionNames(joinNames(expression1.expressionNames(), expression2.expressionNames())) .build(); } /** * Coalesces two expression strings into a single expression string. The expression string will be joined using the * supplied join token. * @param expression1 The first expression string to coalesce * @param expression2 The second expression string to coalesce * @param joinToken The join token to be used to join the expression strings (e.g.: 'AND', 'OR) * @return The coalesced expression */ public static String joinExpressions(String expression1, String expression2, String joinToken) { if (expression1 == null) { return expression2; } if (expression2 == null) { return expression1; } return "(" + expression1 + ")" + joinToken + "(" + expression2 + ")"; } /** * Coalesces two ExpressionValues maps into a single ExpressionValues map. The ExpressionValues map is an optional * component of an expression. * @param expressionValues1 The first ExpressionValues map * @param expressionValues2 The second ExpressionValues map * @return The coalesced ExpressionValues map * @throws IllegalArgumentException if a conflict occurs when merging ExpressionValues */ public static Map<String, AttributeValue> joinValues(Map<String, AttributeValue> expressionValues1, Map<String, AttributeValue> expressionValues2) { if (expressionValues1 == null) { return expressionValues2; } if (expressionValues2 == null) { return expressionValues1; } Map<String, AttributeValue> result = new HashMap<>(expressionValues1); expressionValues2.forEach((key, value) -> { AttributeValue oldValue = result.put(key, value); if (oldValue != null && !oldValue.equals(value)) { throw new IllegalArgumentException( String.format("Attempt to coalesce two expressions with conflicting expression values. " + "Expression value key = '%s'", key)); } }); return Collections.unmodifiableMap(result); } /** * Coalesces two ExpressionNames maps into a single ExpressionNames map. The ExpressionNames map is an optional * component of an expression. * @param expressionNames1 The first ExpressionNames map * @param expressionNames2 The second ExpressionNames map * @return The coalesced ExpressionNames map * @throws IllegalArgumentException if a conflict occurs when merging ExpressionNames */ public static Map<String, String> joinNames(Map<String, String> expressionNames1, Map<String, String> expressionNames2) { if (expressionNames1 == null || expressionNames1.isEmpty()) { return expressionNames2; } if (expressionNames2 == null || expressionNames2.isEmpty()) { return expressionNames1; } Map<String, String> result = new HashMap<>(expressionNames1); expressionNames2.forEach((key, value) -> { String oldValue = result.put(key, value); if (oldValue != null && !oldValue.equals(value)) { throw new IllegalArgumentException( String.format("Attempt to coalesce two expressions with conflicting expression names. " + "Expression name key = '%s'", key)); } }); return Collections.unmodifiableMap(result); } public String expression() { return expression; } public Map<String, AttributeValue> expressionValues() { return expressionValues; } public Map<String, String> expressionNames() { return expressionNames; } /** * Coalesces two complete expressions into a single expression joined by an 'AND'. * * @see #join(Expression, Expression, String) */ public Expression and(Expression expression) { return join(this, expression, " AND "); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Expression that = (Expression) o; if (expression != null ? ! expression.equals(that.expression) : that.expression != null) { return false; } if (expressionValues != null ? ! expressionValues.equals(that.expressionValues) : that.expressionValues != null) { return false; } return expressionNames != null ? expressionNames.equals(that.expressionNames) : that.expressionNames == null; } @Override public int hashCode() { int result = expression != null ? expression.hashCode() : 0; result = 31 * result + (expressionValues != null ? expressionValues.hashCode() : 0); result = 31 * result + (expressionNames != null ? expressionNames.hashCode() : 0); return result; } /** * A builder for {@link Expression} */ @NotThreadSafe public static final class Builder { private String expression; private Map<String, AttributeValue> expressionValues; private Map<String, String> expressionNames; private Builder() { } /** * The expression string */ public Builder expression(String expression) { this.expression = expression; return this; } /** * The optional 'expression values' token map */ public Builder expressionValues(Map<String, AttributeValue> expressionValues) { this.expressionValues = expressionValues == null ? null : new HashMap<>(expressionValues); return this; } /** * Adds a single element to the optional 'expression values' token map */ public Builder putExpressionValue(String key, AttributeValue value) { if (this.expressionValues == null) { this.expressionValues = new HashMap<>(); } this.expressionValues.put(key, value); return this; } /** * The optional 'expression names' token map */ public Builder expressionNames(Map<String, String> expressionNames) { this.expressionNames = expressionNames == null ? null : new HashMap<>(expressionNames); return this; } /** * Adds a single element to the optional 'expression names' token map */ public Builder putExpressionName(String key, String value) { if (this.expressionNames == null) { this.expressionNames = new HashMap<>(); } this.expressionNames.put(key, value); return this; } /** * Builds an {@link Expression} based on the values stored in this builder */ public Expression build() { return new Expression(expression, expressionValues == null ? null : Collections.unmodifiableMap(expressionValues), expressionNames == null ? null : Collections.unmodifiableMap(expressionNames)); } } }
4,367
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/KeyAttributeMetadata.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; /** * A metadata class that stores information about a key attribute */ @SdkPublicApi @ThreadSafe public interface KeyAttributeMetadata { /** * The name of the key attribute */ String name(); /** * The DynamoDB type of the key attribute */ AttributeValueType attributeValueType(); }
4,368
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/AttributeConverterProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.ConverterProviderResolver; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * Interface for determining the {@link AttributeConverter} to use for * converting a given {@link EnhancedType}. */ @SdkPublicApi @ThreadSafe public interface AttributeConverterProvider { /** * Finds a {@link AttributeConverter} for converting an object with a type * specified by a {@link EnhancedType} to a {@link AttributeValue} and back. * * @param enhancedType The type of the object to be converted * @return {@link AttributeConverter} for converting the given type. */ <T> AttributeConverter<T> converterFor(EnhancedType<T> enhancedType); /** * Returns a default implementation of AttributeConverterProvider with all * standard Java type converters included. */ static AttributeConverterProvider defaultProvider() { return ConverterProviderResolver.defaultConverterProvider(); } }
4,369
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/DefaultAttributeConverterProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.PrimitiveConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.StringConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.StringConverterProvider; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.AtomicBooleanAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.AtomicIntegerAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.AtomicLongAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.BigDecimalAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.BigIntegerAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.BooleanAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.ByteArrayAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.ByteAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.ByteBufferAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.CharSequenceAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.CharacterArrayAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.CharacterAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.DocumentAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.DoubleAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.DurationAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.FloatAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.InstantAsStringAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.IntegerAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.ListAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.LocalDateAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.LocalDateTimeAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.LocalTimeAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.LocaleAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.LongAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.MapAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.MonthDayAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.OffsetDateTimeAsStringAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.OptionalDoubleAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.OptionalIntAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.OptionalLongAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.PeriodAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.SdkBytesAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.SdkNumberAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.SetAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.ShortAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.StringAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.StringBufferAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.StringBuilderAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.UriAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.UrlAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.UuidAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.ZoneIdAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.ZoneOffsetAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.ZonedDateTimeAsStringAttributeConverter; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Validate; /** * This class is the default attribute converter provider in the DDB Enhanced library. When instantiated * using the constructor {@link #DefaultAttributeConverterProvider()} or the {@link #create()} method, it's loaded * with the currently supported attribute converters in the library. * <p> * Given an input, the method {@link #converterFor(EnhancedType)} will identify a converter that can convert the * specific Java type and invoke it. If a converter cannot be found, it will invoke a "parent" converter, * which would be expected to be able to convert the value (or throw an exception). */ @SdkPublicApi @ThreadSafe @Immutable public final class DefaultAttributeConverterProvider implements AttributeConverterProvider { private static final DefaultAttributeConverterProvider INSTANCE = getDefaultBuilder().build(); private static final Logger log = Logger.loggerFor(DefaultAttributeConverterProvider.class); private final ConcurrentHashMap<EnhancedType<?>, AttributeConverter<?>> converterCache = new ConcurrentHashMap<>(); private DefaultAttributeConverterProvider(Builder builder) { // Converters are used in the REVERSE order of how they were added to the builder. for (int i = builder.converters.size() - 1; i >= 0; i--) { AttributeConverter<?> converter = builder.converters.get(i); converterCache.put(converter.type(), converter); if (converter instanceof PrimitiveConverter) { PrimitiveConverter<?> primitiveConverter = (PrimitiveConverter<?>) converter; converterCache.put(primitiveConverter.primitiveType(), converter); } } } /** * Returns an attribute converter provider with all default converters set. */ public DefaultAttributeConverterProvider() { this(getDefaultBuilder()); } /** * Returns an attribute converter provider with all default converters set. */ public static DefaultAttributeConverterProvider create() { return INSTANCE; } /** * Equivalent to {@code builder(EnhancedType.of(Object.class))}. */ public static Builder builder() { return new Builder(); } /** * Find a converter that matches the provided type. If one cannot be found, throw an exception. */ @Override public <T> AttributeConverter<T> converterFor(EnhancedType<T> type) { return findConverter(type).orElseThrow(() -> new IllegalStateException("Converter not found for " + type)); } /** * Find a converter that matches the provided type. If one cannot be found, return empty. */ @SuppressWarnings("unchecked") private <T> Optional<AttributeConverter<T>> findConverter(EnhancedType<T> type) { Optional<AttributeConverter<T>> converter = findConverterInternal(type); if (converter.isPresent()) { log.debug(() -> "Converter for " + type + ": " + converter.get().getClass().getTypeName()); } else { log.debug(() -> "No converter available for " + type); } return converter; } private <T> Optional<AttributeConverter<T>> findConverterInternal(EnhancedType<T> type) { AttributeConverter<T> converter = (AttributeConverter<T>) converterCache.get(type); if (converter != null) { return Optional.of(converter); } if (type.rawClass().isAssignableFrom(Map.class)) { converter = createMapConverter(type); } else if (type.rawClass().isAssignableFrom(Set.class)) { converter = createSetConverter(type); } else if (type.rawClass().isAssignableFrom(List.class)) { EnhancedType<T> innerType = (EnhancedType<T>) type.rawClassParameters().get(0); AttributeConverter<?> innerConverter = findConverter(innerType) .orElseThrow(() -> new IllegalStateException("Converter not found for " + type)); return Optional.of((AttributeConverter<T>) ListAttributeConverter.create(innerConverter)); } else if (type.rawClass().isEnum()) { return Optional.of(EnumAttributeConverter.create(((EnhancedType<? extends Enum>) type).rawClass())); } if (type.tableSchema().isPresent()) { converter = DocumentAttributeConverter.create(type.tableSchema().get(), type); } if (converter != null && shouldCache(type.rawClass())) { this.converterCache.put(type, converter); } return Optional.ofNullable(converter); } private boolean shouldCache(Class<?> type) { // Do not cache anonymous classes, to prevent memory leaks. return !type.isAnonymousClass(); } @SuppressWarnings("unchecked") private <T> AttributeConverter<T> createMapConverter(EnhancedType<T> type) { EnhancedType<?> keyType = type.rawClassParameters().get(0); EnhancedType<T> valueType = (EnhancedType<T>) type.rawClassParameters().get(1); StringConverter<?> keyConverter = StringConverterProvider.defaultProvider().converterFor(keyType); AttributeConverter<?> valueConverter = findConverter(valueType) .orElseThrow(() -> new IllegalStateException("Converter not found for " + type)); return (AttributeConverter<T>) MapAttributeConverter.mapConverter(keyConverter, valueConverter); } @SuppressWarnings("unchecked") private <T> AttributeConverter<T> createSetConverter(EnhancedType<T> type) { EnhancedType<T> innerType = (EnhancedType<T>) type.rawClassParameters().get(0); AttributeConverter<?> innerConverter = findConverter(innerType) .orElseThrow(() -> new IllegalStateException("Converter not found for " + type)); return (AttributeConverter<T>) SetAttributeConverter.setConverter(innerConverter); } private static Builder getDefaultBuilder() { return DefaultAttributeConverterProvider.builder() .addConverter(AtomicBooleanAttributeConverter.create()) .addConverter(AtomicIntegerAttributeConverter.create()) .addConverter(AtomicLongAttributeConverter.create()) .addConverter(BigDecimalAttributeConverter.create()) .addConverter(BigIntegerAttributeConverter.create()) .addConverter(BooleanAttributeConverter.create()) .addConverter(ByteArrayAttributeConverter.create()) .addConverter(ByteBufferAttributeConverter.create()) .addConverter(ByteAttributeConverter.create()) .addConverter(CharacterArrayAttributeConverter.create()) .addConverter(CharacterAttributeConverter.create()) .addConverter(CharSequenceAttributeConverter.create()) .addConverter(DoubleAttributeConverter.create()) .addConverter(DurationAttributeConverter.create()) .addConverter(FloatAttributeConverter.create()) .addConverter(InstantAsStringAttributeConverter.create()) .addConverter(IntegerAttributeConverter.create()) .addConverter(LocalDateAttributeConverter.create()) .addConverter(LocalDateTimeAttributeConverter.create()) .addConverter(LocaleAttributeConverter.create()) .addConverter(LocalTimeAttributeConverter.create()) .addConverter(LongAttributeConverter.create()) .addConverter(MonthDayAttributeConverter.create()) .addConverter(OffsetDateTimeAsStringAttributeConverter.create()) .addConverter(OptionalDoubleAttributeConverter.create()) .addConverter(OptionalIntAttributeConverter.create()) .addConverter(OptionalLongAttributeConverter.create()) .addConverter(PeriodAttributeConverter.create()) .addConverter(SdkBytesAttributeConverter.create()) .addConverter(ShortAttributeConverter.create()) .addConverter(StringAttributeConverter.create()) .addConverter(StringBufferAttributeConverter.create()) .addConverter(StringBuilderAttributeConverter.create()) .addConverter(UriAttributeConverter.create()) .addConverter(UrlAttributeConverter.create()) .addConverter(UuidAttributeConverter.create()) .addConverter(ZonedDateTimeAsStringAttributeConverter.create()) .addConverter(ZoneIdAttributeConverter.create()) .addConverter(ZoneOffsetAttributeConverter.create()) .addConverter(SdkNumberAttributeConverter.create()); } /** * A builder for configuring and creating {@link DefaultAttributeConverterProvider}s. */ @NotThreadSafe public static class Builder { private List<AttributeConverter<?>> converters = new ArrayList<>(); private Builder() { } public Builder addConverter(AttributeConverter<?> converter) { Validate.paramNotNull(converter, "converter"); this.converters.add(converter); return this; } public DefaultAttributeConverterProvider build() { return new DefaultAttributeConverterProvider(this); } } }
4,370
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/TableSchema.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb; import java.util.Collection; import java.util.List; import java.util.Map; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.enhanced.dynamodb.document.DocumentTableSchema; import software.amazon.awssdk.enhanced.dynamodb.document.EnhancedDocument; import software.amazon.awssdk.enhanced.dynamodb.mapper.BeanTableSchema; import software.amazon.awssdk.enhanced.dynamodb.mapper.ImmutableTableSchema; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticImmutableTableSchema; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbImmutable; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPreserveEmptyObject; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * Interface for a mapper that is capable of mapping a modelled Java object into a map of {@link AttributeValue} that is * understood by the DynamoDb low-level SDK and back again. This object is also expected to know about the * structure of the table it is modelling, which is stored in a {@link TableMetadata} object. * * @param <T> The type of model object that is being mapped to records in the DynamoDb table. */ @SdkPublicApi @ThreadSafe public interface TableSchema<T> { /** * Returns a builder for the {@link StaticTableSchema} implementation of this interface which allows all attributes, * tags and table structure to be directly declared in the builder. * * @param itemClass The class of the item this {@link TableSchema} will map records to. * @param <T> The type of the item this {@link TableSchema} will map records to. * @return A newly initialized {@link StaticTableSchema.Builder}. */ static <T> StaticTableSchema.Builder<T> builder(Class<T> itemClass) { return StaticTableSchema.builder(itemClass); } /** * Returns a builder for the {@link StaticTableSchema} implementation of this interface which allows all attributes, * tags and table structure to be directly declared in the builder. * * @param itemType The {@link EnhancedType} of the item this {@link TableSchema} will map records to. * @param <T> The type of the item this {@link TableSchema} will map records to. * @return A newly initialized {@link StaticTableSchema.Builder}. */ static <T> StaticTableSchema.Builder<T> builder(EnhancedType<T> itemType) { return StaticTableSchema.builder(itemType); } /** * Returns a builder for the {@link StaticImmutableTableSchema} implementation of this interface which allows all * attributes, tags and table structure to be directly declared in the builder. * * @param immutableItemClass The class of the immutable item this {@link TableSchema} will map records to. * @param immutableBuilderClass The class that can be used to construct immutable items this {@link TableSchema} * maps records to. * @param <T> The type of the immutable item this {@link TableSchema} will map records to. * @param <B> The type of the builder used by this {@link TableSchema} to construct immutable items with. * @return A newly initialized {@link StaticImmutableTableSchema.Builder} */ static <T, B> StaticImmutableTableSchema.Builder<T, B> builder(Class<T> immutableItemClass, Class<B> immutableBuilderClass) { return StaticImmutableTableSchema.builder(immutableItemClass, immutableBuilderClass); } /** * Returns a builder for the {@link StaticImmutableTableSchema} implementation of this interface which allows all * attributes, tags and table structure to be directly declared in the builder. * * @param immutableItemType The {@link EnhancedType} of the immutable item this {@link TableSchema} will map records to. * @param immutableBuilderType The {@link EnhancedType} of the class that can be used to construct immutable items this * {@link TableSchema} maps records to. * @param <T> The type of the immutable item this {@link TableSchema} will map records to. * @param <B> The type of the builder used by this {@link TableSchema} to construct immutable items with. * @return A newly initialized {@link StaticImmutableTableSchema.Builder} */ static <T, B> StaticImmutableTableSchema.Builder<T, B> builder(EnhancedType<T> immutableItemType, EnhancedType<B> immutableBuilderType) { return StaticImmutableTableSchema.builder(immutableItemType, immutableBuilderType); } /** * Scans a bean class that has been annotated with DynamoDb bean annotations and then returns a * {@link BeanTableSchema} implementation of this interface that can map records to and from items of that bean * class. * * <p> * It's recommended to only create a {@link BeanTableSchema} once for a single bean class, usually at application start up, * because it's a moderately expensive operation. * * @param beanClass The bean class this {@link TableSchema} will map records to. * @param <T> The type of the item this {@link TableSchema} will map records to. * @return An initialized {@link BeanTableSchema}. */ static <T> BeanTableSchema<T> fromBean(Class<T> beanClass) { return BeanTableSchema.create(beanClass); } /** * Provides interfaces to interact with DynamoDB tables as {@link EnhancedDocument} where the complete Schema of the table is * not required. * * @return A {@link DocumentTableSchema.Builder} for instantiating DocumentTableSchema. */ static DocumentTableSchema.Builder documentSchemaBuilder() { return DocumentTableSchema.builder(); } /** * Scans an immutable class that has been annotated with DynamoDb immutable annotations and then returns a * {@link ImmutableTableSchema} implementation of this interface that can map records to and from items of that * immutable class. * * <p> * It's recommended to only create an {@link ImmutableTableSchema} once for a single immutable class, usually at application * start up, because it's a moderately expensive operation. * * @param immutableClass The immutable class this {@link TableSchema} will map records to. * @param <T> The type of the item this {@link TableSchema} will map records to. * @return An initialized {@link ImmutableTableSchema}. */ static <T> ImmutableTableSchema<T> fromImmutableClass(Class<T> immutableClass) { return ImmutableTableSchema.create(immutableClass); } /** * Scans a class that has been annotated with DynamoDb enhanced client annotations and then returns an appropriate * {@link TableSchema} implementation that can map records to and from items of that class. Currently supported * top level annotations (see documentation on those classes for more information on how to use them): * {@link DynamoDbBean}, {@link DynamoDbImmutable}. * * <p> * It's recommended to only invoke this operation once for a single class, usually at application start up, * because it's a moderately expensive operation. * * <p> * If this table schema is not behaving as you expect, enable debug logging for * {@code software.amazon.awssdk.enhanced.dynamodb.beans}. * * @param annotatedClass A class that has been annotated with DynamoDb enhanced client annotations. * @param <T> The type of the item this {@link TableSchema} will map records to. * @return An initialized {@link TableSchema} */ static <T> TableSchema<T> fromClass(Class<T> annotatedClass) { if (annotatedClass.getAnnotation(DynamoDbImmutable.class) != null) { return fromImmutableClass(annotatedClass); } if (annotatedClass.getAnnotation(DynamoDbBean.class) != null) { return fromBean(annotatedClass); } throw new IllegalArgumentException("Class does not appear to be a valid DynamoDb annotated class. [class = " + "\"" + annotatedClass + "\"]"); } /** * Takes a raw DynamoDb SDK representation of a record in a table and maps it to a Java object. A new object is * created to fulfil this operation. * <p> * If attributes are missing from the map, that will not cause an error, however if attributes are found in the * map which the mapper does not know how to map, an exception will be thrown. * * <p> * If all attribute values in the attributeMap are null, null will be returned. Use {@link #mapToItem(Map, boolean)} * instead if you need to preserve empty object. * * <p> * API Implementors Note: * <p> * {@link #mapToItem(Map, boolean)} must be implemented if {@code preserveEmptyObject} behavior is desired. * * @param attributeMap A map of String to {@link AttributeValue} that contains all the raw attributes to map. * @return A new instance of a Java object with all the attributes mapped onto it. * @throws IllegalArgumentException if any attributes in the map could not be mapped onto the new model object. * @see #mapToItem(Map, boolean) */ T mapToItem(Map<String, AttributeValue> attributeMap); /** * Takes a raw DynamoDb SDK representation of a record in a table and maps it to a Java object. A new object is * created to fulfil this operation. * <p> * If attributes are missing from the map, that will not cause an error, however if attributes are found in the * map which the mapper does not know how to map, an exception will be thrown. * * <p> * In the scenario where all attribute values in the map are null, it will return null if {@code preserveEmptyObject} * is true. If it's false, an empty object will be returned. * * <p> * Note that {@code preserveEmptyObject} only applies to the top level Java object, if it has nested "empty" objects, they * will be mapped as null. You can use {@link DynamoDbPreserveEmptyObject} to configure this behavior for nested objects. * * <p> * API Implementors Note: * <p> * This method must be implemented if {@code preserveEmptyObject} behavior is to be supported * * @param attributeMap A map of String to {@link AttributeValue} that contains all the raw attributes to map. * @param preserveEmptyObject whether to initialize this Java object as empty class if all fields are null * @return A new instance of a Java object with all the attributes mapped onto it. * @throws IllegalArgumentException if any attributes in the map could not be mapped onto the new model object. * @throws UnsupportedOperationException if {@code preserveEmptyObject} is not supported in the implementation * @see #mapToItem(Map) */ default T mapToItem(Map<String, AttributeValue> attributeMap, boolean preserveEmptyObject) { if (preserveEmptyObject) { throw new UnsupportedOperationException("preserveEmptyObject is not supported. You can set preserveEmptyObject to " + "false to continue to call this operation. If you wish to enable " + "preserveEmptyObject, please reach out to the maintainers of the " + "implementation class for assistance."); } return mapToItem(attributeMap); } /** * Takes a modelled object and converts it into a raw map of {@link AttributeValue} that the DynamoDb low-level * SDK can work with. * * @param item The modelled Java object to convert into a map of attributes. * @param ignoreNulls If set to true; any null values in the Java object will not be added to the output map. * If set to false; null values in the Java object will be added as {@link AttributeValue} of * type 'nul' to the output map. * @return A map of String to {@link AttributeValue} representing all the modelled attributes in the model object. */ Map<String, AttributeValue> itemToMap(T item, boolean ignoreNulls); /** * Takes a modelled object and extracts a specific set of attributes which are then returned as a map of * {@link AttributeValue} that the DynamoDb low-level SDK can work with. This method is typically used to extract * just the key attributes of a modelled item and will not ignore nulls on the modelled object. * * @param item The modelled Java object to extract the map of attributes from. * @param attributes A collection of attribute names to extract into the output map. * @return A map of String to {@link AttributeValue} representing the requested modelled attributes in the model * object. */ Map<String, AttributeValue> itemToMap(T item, Collection<String> attributes); /** * Returns a single attribute value from the modelled object. * * @param item The modelled Java object to extract the attribute from. * @param attributeName The attribute name describing which attribute to extract. * @return A single {@link AttributeValue} representing the requested modelled attribute in the model object or * null if the attribute has not been set with a value in the modelled object. */ AttributeValue attributeValue(T item, String attributeName); /** * Returns the object that describes the structure of the table being modelled by the mapper. This includes * information such as the table name, index keys and attribute tags. * @return A {@link TableMetadata} object that contains structural information about the table being modelled. */ TableMetadata tableMetadata(); /** * Returns the {@link EnhancedType} that represents the 'Type' of the Java object this table schema object maps to * and from. * @return The {@link EnhancedType} of the modelled item this TableSchema maps to. */ EnhancedType<T> itemType(); /** * Returns a complete list of attribute names that are mapped by this {@link TableSchema} */ List<String> attributeNames(); /** * A boolean value that represents whether this {@link TableSchema} is abstract which means that it cannot be used * to directly create records as it is lacking required structural elements to map to a table, such as a primary * key, but can be referred to and embedded by other schemata. * * @return true if it is abstract, and therefore cannot be used directly to create records but can be referred to * by other schemata, and false if it is concrete and may be used to map records directly. */ boolean isAbstract(); /** * {@link AttributeConverter} that is applied to the given key. * * @param key Attribute of the modelled item. * @return AttributeConverter defined for the given attribute key. */ default AttributeConverter<T> converterForAttribute(Object key) { throw new UnsupportedOperationException(); } }
4,371
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/DynamoDbEnhancedResource.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb; import java.util.List; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; /** * Shared interface components for {@link DynamoDbEnhancedClient} and {@link DynamoDbEnhancedAsyncClient}. Any common * methods implemented by both of those classes or their builders are declared here. */ @SdkPublicApi @ThreadSafe public interface DynamoDbEnhancedResource { /** * Shared interface components for the builders of {@link DynamoDbEnhancedClient} and * {@link DynamoDbEnhancedAsyncClient} */ @NotThreadSafe interface Builder { /** * Specifies the extensions to load with the enhanced client. The extensions will be loaded in the strict order * they are supplied here. Calling this method will override any bundled extensions that are loaded by default, * namely the {@link software.amazon.awssdk.enhanced.dynamodb.extensions.VersionedRecordExtension}, so this * extension must be included in the supplied list otherwise it will not be loaded. Providing an empty list here * will cause no extensions to get loaded, effectively dropping the default ones. * * @param dynamoDbEnhancedClientExtensions a list of extensions to load with the enhanced client */ Builder extensions(DynamoDbEnhancedClientExtension... dynamoDbEnhancedClientExtensions); /** * Specifies the extensions to load with the enhanced client. The extensions will be loaded in the strict order * they are supplied here. Calling this method will override any bundled extensions that are loaded by default, * namely the {@link software.amazon.awssdk.enhanced.dynamodb.extensions.VersionedRecordExtension}, so this * extension must be included in the supplied list otherwise it will not be loaded. Providing an empty list here * will cause no extensions to get loaded, effectively dropping the default ones. * * @param dynamoDbEnhancedClientExtensions a list of extensions to load with the enhanced client */ Builder extensions(List<DynamoDbEnhancedClientExtension> dynamoDbEnhancedClientExtensions); } }
4,372
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/Key.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.nullAttributeValue; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Optional; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.utils.Validate; /** * An object that represents a key that can be used to either identify a specific record or form part of a query * conditional. Keys are literal and hence not typed, and can be re-used in commands for different modelled types if * the literal values are to be the same. * <p> * A key will always have a single partition key value associated with it, and optionally will have a sort key value. * The names of the keys themselves are not part of this object. */ @SdkPublicApi @ThreadSafe public final class Key { private final AttributeValue partitionValue; private final AttributeValue sortValue; private Key(Builder builder) { Validate.isTrue(builder.partitionValue != null && !builder.partitionValue.equals(nullAttributeValue()), "partitionValue should not be null"); this.partitionValue = builder.partitionValue; this.sortValue = builder.sortValue; } /** * Returns a new builder that can be used to construct an instance of this class. * @return A newly initialized {@link Builder} object. */ public static Builder builder() { return new Builder(); } /** * Return a map of the key elements that can be passed directly to DynamoDb. * @param tableSchema A tableschema to determine the key attribute names from. * @param index The name of the index to use when determining the key attribute names. * @return A map of attribute names to {@link AttributeValue}. */ public Map<String, AttributeValue> keyMap(TableSchema<?> tableSchema, String index) { Map<String, AttributeValue> keyMap = new HashMap<>(); keyMap.put(tableSchema.tableMetadata().indexPartitionKey(index), partitionValue); if (sortValue != null) { keyMap.put(tableSchema.tableMetadata().indexSortKey(index).orElseThrow( () -> new IllegalArgumentException("A sort key value was supplied for an index that does not support " + "one. Index: " + index)), sortValue); } return Collections.unmodifiableMap(keyMap); } /** * Get the literal value of the partition key stored in this object. * @return An {@link AttributeValue} representing the literal value of the partition key. */ public AttributeValue partitionKeyValue() { return partitionValue; } /** * Get the literal value of the sort key stored in this object if available. * @return An optional {@link AttributeValue} representing the literal value of the sort key, or empty if there * is no sort key value in this Key. */ public Optional<AttributeValue> sortKeyValue() { return Optional.ofNullable(sortValue); } /** * Return a map of the key elements that form the primary key of a table that can be passed directly to DynamoDb. * @param tableSchema A tableschema to determine the key attribute names from. * @return A map of attribute names to {@link AttributeValue}. */ public Map<String, AttributeValue> primaryKeyMap(TableSchema<?> tableSchema) { return keyMap(tableSchema, TableMetadata.primaryIndexName()); } /** * Converts an existing key into a builder object that can be used to modify its values and then create a new key. * @return A {@link Builder} initialized with the values of this key. */ public Builder toBuilder() { return new Builder().partitionValue(this.partitionValue).sortValue(this.sortValue); } /** * Builder for {@link Key} */ @NotThreadSafe public static final class Builder { private AttributeValue partitionValue; private AttributeValue sortValue; private Builder() { } /** * Value to be used for the partition key * @param partitionValue partition key value */ public Builder partitionValue(AttributeValue partitionValue) { this.partitionValue = partitionValue; return this; } /** * String value to be used for the partition key. The string will be converted into an AttributeValue of type S. * @param partitionValue partition key value */ public Builder partitionValue(String partitionValue) { this.partitionValue = AttributeValues.stringValue(partitionValue); return this; } /** * Numeric value to be used for the partition key. The number will be converted into an AttributeValue of type N. * @param partitionValue partition key value */ public Builder partitionValue(Number partitionValue) { this.partitionValue = AttributeValues.numberValue(partitionValue); return this; } /** * Binary value to be used for the partition key. The input will be converted into an AttributeValue of type B. * @param partitionValue the bytes to be used for the binary key value. */ public Builder partitionValue(SdkBytes partitionValue) { this.partitionValue = AttributeValues.binaryValue(partitionValue); return this; } /** * Value to be used for the sort key * @param sortValue sort key value */ public Builder sortValue(AttributeValue sortValue) { this.sortValue = sortValue; return this; } /** * String value to be used for the sort key. The string will be converted into an AttributeValue of type S. * @param sortValue sort key value */ public Builder sortValue(String sortValue) { this.sortValue = AttributeValues.stringValue(sortValue); return this; } /** * Numeric value to be used for the sort key. The number will be converted into an AttributeValue of type N. * @param sortValue sort key value */ public Builder sortValue(Number sortValue) { this.sortValue = AttributeValues.numberValue(sortValue); return this; } /** * Binary value to be used for the sort key. The input will be converted into an AttributeValue of type B. * @param sortValue the bytes to be used for the binary key value. */ public Builder sortValue(SdkBytes sortValue) { this.sortValue = AttributeValues.binaryValue(sortValue); return this; } /** * Construct a {@link Key} from this builder. */ public Key build() { return new Key(this); } } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Key key = (Key) o; if (partitionValue != null ? ! partitionValue.equals(key.partitionValue) : key.partitionValue != null) { return false; } return sortValue != null ? sortValue.equals(key.sortValue) : key.sortValue == null; } @Override public int hashCode() { int result = partitionValue != null ? partitionValue.hashCode() : 0; result = 31 * result + (sortValue != null ? sortValue.hashCode() : 0); return result; } }
4,373
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/NestedAttributeName.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.enhanced.dynamodb.model.QueryEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.ScanEnhancedRequest; import software.amazon.awssdk.utils.Validate; /** * A high-level representation of a DynamoDB nested attribute name that can be used in various situations where the API requires * or accepts a nested attribute name. The nested attributes are represented by a list of strings where each element * corresponds to a nesting level. A simple (top-level) attribute name can be represented by creating an instance with a * single string element. * <p> * NestedAttributeName is used directly in {@link QueryEnhancedRequest#nestedAttributesToProject()} * and {@link ScanEnhancedRequest#nestedAttributesToProject()}, and indirectly by * {@link QueryEnhancedRequest#attributesToProject()} and {@link ScanEnhancedRequest#attributesToProject()}. * <p> * Examples of creating NestedAttributeNames: * <ul> * <li>Simple attribute {@code Level0} can be created as {@code NestedAttributeName.create("Level0")}</li> * <li>Nested attribute {@code Level0.Level1} can be created as {@code NestedAttributeName.create("Level0", "Level1")}</li> * <li>Nested attribute {@code Level0.Level-2} can be created as {@code NestedAttributeName.create("Level0", "Level-2")}</li> * <li>List item 0 of {@code ListAttribute} can be created as {@code NestedAttributeName.create("ListAttribute[0]")} * </li> * </ul> */ @SdkPublicApi @ThreadSafe public final class NestedAttributeName { private final List<String> elements; private NestedAttributeName(List<String> nestedAttributeNames) { Validate.validState(nestedAttributeNames != null, "nestedAttributeNames must not be null."); Validate.notEmpty(nestedAttributeNames, "nestedAttributeNames must not be empty"); Validate.noNullElements(nestedAttributeNames, "nestedAttributeNames must not contain null values"); this.elements = Collections.unmodifiableList(nestedAttributeNames); } /** * Creates a NestedAttributeName with a single element, which is effectively just a simple attribute name without nesting. * <p> * <b>Example:</b>create("foo") will create NestedAttributeName corresponding to Attribute foo. * * @param element Attribute Name. Single String represents just a simple attribute name without nesting. * @return NestedAttributeName with attribute name as specified element. */ public static NestedAttributeName create(String element) { return new Builder().addElement(element).build(); } /** * Creates a NestedAttributeName from a list of elements that compose the full path of the nested attribute. * <p> * <b>Example:</b>create("foo", "bar") will create NestedAttributeName which represents foo.bar nested attribute. * * @param elements Nested Attribute Names. Each of strings in varargs represent the nested attribute name * at subsequent levels. * @return NestedAttributeName with Nested attribute name set as specified in elements var args. */ public static NestedAttributeName create(String... elements) { return new Builder().elements(elements).build(); } /** * Creates a NestedAttributeName from a list of elements that compose the full path of the nested attribute. * <p> * <b>Example:</b>create(Arrays.asList("foo", "bar")) will create NestedAttributeName * which represents foo.bar nested attribute. * * @param elements List of Nested Attribute Names. Each of strings in List represent the nested attribute name * at subsequent levels. * @return NestedAttributeName with Nested attribute name set as specified in elements Collections. */ public static NestedAttributeName create(List<String> elements) { return new Builder().elements(elements).build(); } /** * Create a builder that can be used to create a {@link NestedAttributeName}. */ public static Builder builder() { return new Builder(); } /** * Gets elements of NestedAttributeName in the form of List. Each element in the list corresponds * to the subsequent Nested Attribute name. * * @return List of nested attributes, each entry in the list represent one level of nesting. * Example, A Two level Attribute name foo.bar will be represented as ["foo", "bar"] */ public List<String> elements() { return elements; } /** * Returns a builder initialized with all existing values on the request object. */ public Builder toBuilder() { return builder().elements(elements); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } NestedAttributeName that = (NestedAttributeName) o; return elements != null ? elements.equals(that.elements) : that.elements == null; } @Override public int hashCode() { return elements != null ? elements.hashCode() : 0; } @Override public String toString() { return elements == null ? "" : elements.stream().collect(Collectors.joining(".")); } /** * A builder for {@link NestedAttributeName}. */ @NotThreadSafe public static class Builder { private List<String> elements = null; private Builder() { } /** * Adds a single element of NestedAttributeName. * Subsequent calls to this method can add attribute Names at subsequent nesting levels. * <p> * <b>Example:</b>builder().addElement("foo").addElement("bar") will add elements in NestedAttributeName * which represent a Nested Attribute Name foo.bar * * @param element Attribute Name. * @return Returns a reference to this object so that method calls can be chained together. */ public Builder addElement(String element) { if (elements == null) { elements = new ArrayList<>(); } elements.add(element); return this; } /** * Adds a single element of NestedAttributeName. * Subsequent calls to this method will append the new elements to the end of the existing chain of elements * creating new levels of nesting. * <p> * <b>Example:</b>builder().addElements("foo","bar") will add elements in NestedAttributeName * which represent a Nested Attribute Name foo.bar * * @param elements Nested Attribute Names. Each of strings in varargs represent the nested attribute name * at subsequent levels. * @return Returns a reference to this object so that method calls can be chained together. */ public Builder addElements(String... elements) { if (this.elements == null) { this.elements = new ArrayList<>(); } this.elements.addAll(Arrays.asList(elements)); return this; } /** * Adds a List of elements to NestedAttributeName. * Subsequent calls to this method will append the new elements to the end of the existing chain of elements * creating new levels of nesting. * <p> * <b>Example:</b>builder().addElements(Arrays.asList("foo","bar")) will add elements in NestedAttributeName * to represent a Nested Attribute Name foo.bar * * @param elements List of Strings where each string corresponds to subsequent nesting attribute name. * @return Returns a reference to this object so that method calls can be chained together. */ public Builder addElements(List<String> elements) { if (this.elements == null) { this.elements = new ArrayList<>(); } this.elements.addAll(elements); return this; } /** * Set elements of NestedAttributeName with list of Strings. Will overwrite any existing elements stored by this builder. * <p> * <b>Example:</b>builder().elements("foo","bar") will set the elements in NestedAttributeName * to represent a nested attribute name of 'foo.bar' * * @param elements a list of strings that correspond to the elements in a nested attribute name. * @return Returns a reference to this object so that method calls can be chained together. */ public Builder elements(String... elements) { this.elements = new ArrayList<>(Arrays.asList(elements)); return this; } /** * Sets the elements that compose a nested attribute name. Will overwrite any existing elements stored by this builder. * <p> * <b>Example:</b>builder().elements(Arrays.asList("foo","bar")) will add elements in NestedAttributeName * which represent a Nested Attribute Name foo.bar * * @param elements a list of strings that correspond to the elements in a nested attribute name. * @return Returns a reference to this object so that method calls can be chained together. */ public Builder elements(List<String> elements) { this.elements = new ArrayList<>(elements); return this; } public NestedAttributeName build() { return new NestedAttributeName(elements); } } }
4,374
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/DynamoDbEnhancedAsyncClient.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.core.async.SdkPublisher; import software.amazon.awssdk.enhanced.dynamodb.internal.client.DefaultDynamoDbEnhancedAsyncClient; import software.amazon.awssdk.enhanced.dynamodb.model.BatchGetItemEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.BatchGetResultPage; import software.amazon.awssdk.enhanced.dynamodb.model.BatchGetResultPagePublisher; import software.amazon.awssdk.enhanced.dynamodb.model.BatchWriteItemEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.BatchWriteResult; import software.amazon.awssdk.enhanced.dynamodb.model.ConditionCheck; import software.amazon.awssdk.enhanced.dynamodb.model.DeleteItemEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.GetItemEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.PutItemEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.TransactGetItemsEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.TransactWriteItemsEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.UpdateItemEnhancedRequest; import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient; /** * Asynchronous interface for running commands against a DynamoDb database. * <p> * By default, all command methods throw an {@link UnsupportedOperationException} to prevent interface extensions from breaking * implementing classes. */ @SdkPublicApi @ThreadSafe public interface DynamoDbEnhancedAsyncClient extends DynamoDbEnhancedResource { /** * Returns a mapped table that can be used to execute commands that work with mapped items against that table. * * @param tableName The name of the physical table persisted by DynamoDb. * @param tableSchema A {@link TableSchema} that maps the table to a modelled object. * @return A {@link DynamoDbAsyncTable} object that can be used to execute table operations against. * @param <T> THe modelled object type being mapped to this table. */ <T> DynamoDbAsyncTable<T> table(String tableName, TableSchema<T> tableSchema); /** * Retrieves items from one or more tables by their primary keys, see {@link Key}. BatchGetItem is a composite operation * where the request contains one batch of {@link GetItemEnhancedRequest} per targeted table. * The operation makes several calls to the database; each time you iterate over the result to retrieve a page, * a call is made for the items on that page. * <p> * The additional configuration parameters that the enhanced client supports are defined * in the {@link BatchGetItemEnhancedRequest}. * <p> * <b>Partial results</b>. A single call to DynamoDb has restraints on how much data can be retrieved. * If those limits are exceeded, the call yields a partial result. This may also be the case if * provisional throughput is exceeded or there is an internal DynamoDb processing failure. The operation automatically * retries any unprocessed keys returned from DynamoDb in subsequent calls for pages. * <p> * This operation calls the low-level {@link DynamoDbAsyncClient#batchGetItemPaginator} operation. Consult the * BatchGetItem documentation for further details and constraints as well as current limits of data retrieval. * <p> * Example: * <pre> * {@code * * BatchGetResultPagePublisher publisher = enhancedClient.batchGetItem( * BatchGetItemEnhancedRequest.builder() * .readBatches(ReadBatch.builder(FirstItem.class) * .mappedTableResource(firstItemTable) * .addGetItem(GetItemEnhancedRequest.builder().key(key1).build()) * .addGetItem(GetItemEnhancedRequest.builder().key(key2).build()) * .build(), * ReadBatch.builder(SecondItem.class) * .mappedTableResource(secondItemTable) * .addGetItem(GetItemEnhancedRequest.builder().key(key3).build()) * .build()) * .build()); * } * </pre> * * <p> * The returned {@link BatchGetResultPagePublisher} can be subscribed to request a stream of {@link BatchGetResultPage}s * or a stream of flattened results belonging to the supplied table across all pages. * * <p> * 1) Subscribing to {@link BatchGetResultPage}s * <pre> * {@code * publisher.subscribe(page -> { * page.resultsForTable(firstItemTable).forEach(item -> System.out.println(item)); * page.resultsForTable(secondItemTable).forEach(item -> System.out.println(item)); * }); * } * </pre> * * <p> * 2) Subscribing to results across all pages * <pre> * {@code * publisher.resultsForTable(firstItemTable).subscribe(item -> System.out.println(item)); * publisher.resultsForTable(secondItemTable).subscribe(item -> System.out.println(item)); * } * </pre> * @see #batchGetItem(Consumer) * @see DynamoDbAsyncClient#batchGetItemPaginator * @param request A {@link BatchGetItemEnhancedRequest} containing keys grouped by tables. * @return a publisher {@link SdkPublisher} with paginated results of type {@link BatchGetResultPage}. */ default BatchGetResultPagePublisher batchGetItem(BatchGetItemEnhancedRequest request) { throw new UnsupportedOperationException(); } /** * Retrieves items from one or more tables by their primary keys, see {@link Key}. BatchGetItem is a composite operation * where the request contains one batch of {@link GetItemEnhancedRequest} per targeted table. * The operation makes several calls to the database; each time you iterate over the result to retrieve a page, * a call is made for the items on that page. * <p> * <b>Note:</b> This is a convenience method that creates an instance of the request builder avoiding the need to create one * manually via {@link BatchGetItemEnhancedRequest#builder()}. * <p> * Example: * <pre> * {@code * * BatchGetResultPagePublisher batchResults = enhancedClient.batchGetItem(r -> r.addReadBatches( * ReadBatch.builder(FirstItem.class) * .mappedTableResource(firstItemTable) * .addGetItem(i -> i.key(key1)) * .addGetItem(i -> i.key(key2)) * .build(), * ReadBatch.builder(SecondItem.class) * .mappedTableResource(secondItemTable) * .addGetItem(i -> i.key(key3)) * .build())); * } * </pre> * * @see #batchGetItem(BatchGetItemEnhancedRequest) * @see DynamoDbAsyncClient#batchGetItem * @param requestConsumer a {@link Consumer} of {@link BatchGetItemEnhancedRequest.Builder} containing keys grouped by tables. * @return a publisher {@link SdkPublisher} with paginated results of type {@link BatchGetResultPage}. */ default BatchGetResultPagePublisher batchGetItem(Consumer<BatchGetItemEnhancedRequest.Builder> requestConsumer) { throw new UnsupportedOperationException(); } /** * Puts and/or deletes multiple items in one or more tables. BatchWriteItem is a composite operation where the request * contains one batch of (a mix of) {@link PutItemEnhancedRequest} and {@link DeleteItemEnhancedRequest} per targeted table. * <p> * The additional configuration parameters that the enhanced client supports are defined * in the {@link BatchWriteItemEnhancedRequest}. * <p> * <b>Note: </b> BatchWriteItem cannot update items. Instead, use the individual updateItem operation * {@link DynamoDbAsyncTable#updateItem(UpdateItemEnhancedRequest)}. * <p> * <b>Partial updates</b><br>Each delete or put call is atomic, but the operation as a whole is not. * If individual operations fail due to exceeded provisional throughput internal DynamoDb processing failures, * the failed requests can be retrieved through the result, see {@link BatchWriteResult}. * <p> * There are some conditions that cause the whole batch operation to fail. These include non-existing tables, erroneously * defined primary key attributes, attempting to put and delete the same item as well as referring more than once to the same * hash and range (sort) key. * <p> * This operation calls the low-level DynamoDB API BatchWriteItem operation. Consult the BatchWriteItem documentation for * further details and constraints, current limits of data to write and/or delete, how to handle partial updates and retries * and under which conditions the operation will fail. * <p> * Example: * <pre> * {@code * * BatchWriteResult batchResult = enhancedClient.batchWriteItem( * BatchWriteItemEnhancedRequest.builder() * .writeBatches(WriteBatch.builder(FirstItem.class) * .mappedTableResource(firstItemTable) * .addPutItem(PutItemEnhancedRequest.builder().item(item1).build()) * .addDeleteItem(DeleteItemEnhancedRequest.builder() * .key(key2) * .build()) * .build(), * WriteBatch.builder(SecondItem.class) * .mappedTableResource(secondItemTable) * .addPutItem(PutItemEnhancedRequest.builder().item(item3).build()) * .build()) * .build()).join(); * } * </pre> * * @param request A {@link BatchWriteItemEnhancedRequest} containing keys and items grouped by tables. * @return a {@link CompletableFuture} of {@link BatchWriteResult}, containing any unprocessed requests. */ default CompletableFuture<BatchWriteResult> batchWriteItem(BatchWriteItemEnhancedRequest request) { throw new UnsupportedOperationException(); } /** * Puts and/or deletes multiple items in one or more tables. BatchWriteItem is a composite operation where the request * contains one batch of (a mix of) {@link PutItemEnhancedRequest} and {@link DeleteItemEnhancedRequest} per targeted table. * <p> * The additional configuration parameters that the enhanced client supports are defined * in the {@link BatchWriteItemEnhancedRequest}. * <p> * <b>Note: </b> BatchWriteItem cannot update items. Instead, use the individual updateItem operation * {@link DynamoDbAsyncTable#updateItem}}. * <p> * <b>Partial updates</b><br>Each delete or put call is atomic, but the operation as a whole is not. * If individual operations fail due to exceeded provisional throughput internal DynamoDb processing failures, * the failed requests can be retrieved through the result, see {@link BatchWriteResult}. * <p> * There are some conditions that cause the whole batch operation to fail. These include non-existing tables, erroneously * defined primary key attributes, attempting to put and delete the same item as well as referring more than once to the same * hash and range (sort) key. * <p> * This operation calls the low-level DynamoDB API BatchWriteItem operation. Consult the BatchWriteItem documentation for * further details and constraints, current limits of data to write and/or delete, how to handle partial updates and retries * and under which conditions the operation will fail. * <p> * <b>Note:</b> This is a convenience method that creates an instance of the request builder avoiding the need to create one * manually via {@link BatchWriteItemEnhancedRequest#builder()}. * <p> * Example: * <pre> * {@code * * BatchWriteResult batchResult = enhancedClient.batchWriteItem(r -> r.writeBatches( * WriteBatch.builder(FirstItem.class) * .mappedTableResource(firstItemTable) * .addPutItem(i -> i.item(item1)) * .addDeleteItem(i -> i.key(key2)) * .build(), * WriteBatch.builder(SecondItem.class) * .mappedTableResource(secondItemTable) * .addPutItem(i -> i.item(item3)) * .build())).join(); * } * </pre> * * @param requestConsumer a {@link Consumer} of {@link BatchWriteItemEnhancedRequest} containing keys and items grouped by * tables. * @return a {@link CompletableFuture} of {@link BatchWriteResult}, containing any unprocessed requests. */ default CompletableFuture<BatchWriteResult> batchWriteItem(Consumer<BatchWriteItemEnhancedRequest.Builder> requestConsumer) { throw new UnsupportedOperationException(); } /** * Retrieves multiple items from one or more tables in a single atomic transaction. TransactGetItem is a composite operation * where the request contains a set of get requests, each containing a table reference and a * {@link GetItemEnhancedRequest}. * <p> * The additional configuration parameters that the enhanced client supports are defined * in the {@link TransactGetItemsEnhancedRequest}. * <p> * DynamoDb will reject a call to TransactGetItems if the call exceeds limits such as provisioned throughput or allowed size * of items, if the request contains errors or if there are conflicting operations accessing the same item, for instance * updating and reading at the same time. * <p> * This operation calls the low-level DynamoDB API TransactGetItems operation. Consult the TransactGetItems documentation for * further details and constraints. * <p> * Examples: * <pre> * {@code * * List<TransactGetResultPage> results = enhancedClient.transactGetItems( * TransactGetItemsEnhancedRequest.builder() * .addGetItem(firstItemTable, GetItemEnhancedRequest.builder().key(key1).build()) * .addGetItem(firstItemTable, GetItemEnhancedRequest.builder().key(key2).build()) * .addGetItem(firstItemTable, GetItemEnhancedRequest.builder().key(key3).build()) * .addGetItem(secondItemTable, GetItemEnhancedRequest.builder().key(key4).build()) * .build()).join(); * } * </pre> * * @param request A {@link TransactGetItemsEnhancedRequest} containing keys with table references. * @return a {@link CompletableFuture} containing a list of {@link Document} with the results. */ default CompletableFuture<List<Document>> transactGetItems(TransactGetItemsEnhancedRequest request) { throw new UnsupportedOperationException(); } /** * Retrieves multiple items from one or more tables in a single atomic transaction. TransactGetItem is a composite operation * where the request contains a set of get requests, each containing a table reference and a * {@link GetItemEnhancedRequest}. * <p> * The additional configuration parameters that the enhanced client supports are defined * in the {@link TransactGetItemsEnhancedRequest}. * <p> * DynamoDb will reject a call to TransactGetItems if the call exceeds limits such as provisioned throughput or allowed size * of items, if the request contains errors or if there are conflicting operations accessing the same item, for instance * updating and reading at the same time. * <p> * This operation calls the low-level DynamoDB API TransactGetItems operation. Consult the TransactGetItems documentation for * further details and constraints. * <p> * <b>Note:</b> This is a convenience method that creates an instance of the request builder avoiding the need to create one * manually via {@link TransactGetItemsEnhancedRequest#builder()}. * <p> * Examples: * <pre> * {@code * * List<TransactGetResultPage> results = = enhancedClient.transactGetItems( * r -> r.addGetItem(firstItemTable, i -> i.key(k -> k.partitionValue(0))) * .addGetItem(firstItemTable, i -> i.key(k -> k.partitionValue(1))) * .addGetItem(firstItemTable, i -> i.key(k -> k.partitionValue(2))) * .addGetItem(secondItemTable, i -> i.key(k -> k.partitionValue(0)))).join(); * } * </pre> * * @param requestConsumer a {@link Consumer} of {@link TransactGetItemsEnhancedRequest} containing keys with table references. * @return a {@link CompletableFuture} containing a list of {@link Document} with the results. */ default CompletableFuture<List<Document>> transactGetItems( Consumer<TransactGetItemsEnhancedRequest.Builder> requestConsumer) { throw new UnsupportedOperationException(); } /** * Writes and/or modifies multiple items from one or more tables in a single atomic transaction. TransactGetItem is a * composite operation where the request contains a set of action requests, each containing a table reference and * one of the following requests: * <ul> * <li>Condition check of item - {@link ConditionCheck}</li> * <li>Delete item - {@link DeleteItemEnhancedRequest}</li> * <li>Put item - {@link PutItemEnhancedRequest}</li> * <li>Update item - {@link UpdateItemEnhancedRequest}</li> * </ul> * <p> * The additional configuration parameters that the enhanced client supports are defined * in the {@link TransactWriteItemsEnhancedRequest}. * <p> * DynamoDb will reject a call to TransactWriteItems if the call exceeds limits such as provisioned throughput or allowed size * of items, if the request contains errors or if there are conflicting operations accessing the same item. If the request * contains condition checks that aren't met, this will also cause rejection. * <p> * This operation calls the low-level DynamoDB API TransactWriteItems operation. Consult the TransactWriteItems documentation * for further details and constraints, current limits of data to write and/or delete and under which conditions the operation * will fail. * <p> * Example: * <pre> * {@code * * enhancedClient.transactWriteItems( * TransactWriteItemsEnhancedRequest.builder() * .addPutItem(firstItemTable, PutItemEnhancedRequest.builder().item(item1).build()) * .addDeleteItem(firstItemTable, DeleteItemEnhancedRequest.builder().key(key2).build()) * .addConditionCheck(firstItemTable, * ConditionCheck.builder() * .key(key3) * .conditionExpression(conditionExpression) * .build()) * .addUpdateItem(secondItemTable, * UpdateItemEnhancedRequest.builder().item(item4).build()) * .build()).join(); * } * </pre> * * @param request A {@link BatchWriteItemEnhancedRequest} containing keys grouped by tables. * @return a {@link CompletableFuture} of {@link Void}. */ default CompletableFuture<Void> transactWriteItems(TransactWriteItemsEnhancedRequest request) { throw new UnsupportedOperationException(); } /** * Writes and/or modifies multiple items from one or more tables in a single atomic transaction. TransactGetItem is a * composite operation where the request contains a set of action requests, each containing a table reference and * one of the following requests: * <ul> * <li>Condition check of item - {@link ConditionCheck}</li> * <li>Delete item - {@link DeleteItemEnhancedRequest}</li> * <li>Put item - {@link PutItemEnhancedRequest}</li> * <li>Update item - {@link UpdateItemEnhancedRequest}</li> * </ul> * <p> * The additional configuration parameters that the enhanced client supports are defined * in the {@link TransactWriteItemsEnhancedRequest}. * <p> * DynamoDb will reject a call to TransactWriteItems if the call exceeds limits such as provisioned throughput or allowed size * of items, if the request contains errors or if there are conflicting operations accessing the same item. If the request * contains condition checks that aren't met, this will also cause rejection. * <p> * This operation calls the low-level DynamoDB API TransactWriteItems operation. Consult the TransactWriteItems documentation * for further details and constraints, current limits of data to write and/or delete and under which conditions the operation * will fail. * <p> * <b>Note:</b> This is a convenience method that creates an instance of the request builder avoiding the need to create one * manually via {@link TransactWriteItemsEnhancedRequest#builder()}. * <p> * Example: * <pre> * {@code * * enhancedClient.transactWriteItems(r -> r.addPutItem(firstItemTable, i -> i.item(item1)) * .addDeleteItem(firstItemTable, i -> i.key(k -> k.partitionValue(2))) * .addConditionCheck(firstItemTable, i -> i.key(key3) * .conditionExpression(conditionExpression)) * .addUpdateItem(secondItemTable, i -> i.item(item4))).join(); * } * </pre> * * @param requestConsumer a {@link Consumer} of {@link TransactWriteItemsEnhancedRequest} containing keys and items grouped by * tables. * @return a {@link CompletableFuture} of {@link Void}. */ default CompletableFuture<Void> transactWriteItems(Consumer<TransactWriteItemsEnhancedRequest.Builder> requestConsumer) { throw new UnsupportedOperationException(); } /** * Creates a default builder for {@link DynamoDbEnhancedAsyncClient}. */ static DynamoDbEnhancedAsyncClient.Builder builder() { return DefaultDynamoDbEnhancedAsyncClient.builder(); } /** * Creates a {@link DynamoDbEnhancedClient} with a default {@link DynamoDbAsyncClient} */ static DynamoDbEnhancedAsyncClient create() { return builder().build(); } /** * The builder definition for a {@link DynamoDbEnhancedAsyncClient}. */ @NotThreadSafe interface Builder extends DynamoDbEnhancedResource.Builder { /** * The regular low-level SDK client to use with the enhanced client. * @param dynamoDbClient an initialized {@link DynamoDbAsyncClient} */ Builder dynamoDbClient(DynamoDbAsyncClient dynamoDbClient); @Override Builder extensions(DynamoDbEnhancedClientExtension... dynamoDbEnhancedClientExtensions); @Override Builder extensions(List<DynamoDbEnhancedClientExtension> dynamoDbEnhancedClientExtensions); /** * Builds an enhanced client based on the settings supplied to this builder * @return An initialized {@link DynamoDbEnhancedAsyncClient} */ DynamoDbEnhancedAsyncClient build(); } }
4,375
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/AttributeConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb; import java.time.Instant; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.InstantAsStringAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.StringAttributeConverter; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * Converts between a specific Java type and an {@link AttributeValue}. * * <p> * Examples: * <ul> * <li>The {@link StringAttributeConverter} converts a {@link String} into a DynamoDB string * ({@link software.amazon.awssdk.services.dynamodb.model.AttributeValue#s()}).</li> * <li>The {@link InstantAsStringAttributeConverter} converts an {@link Instant} into a DynamoDB string * ({@link software.amazon.awssdk.services.dynamodb.model.AttributeValue#s()}).</li> * </ul> */ @SdkPublicApi @ThreadSafe public interface AttributeConverter<T> { /** * Convert the provided Java object into an {@link AttributeValue}. This will raise a {@link RuntimeException} if the * conversion fails, or the input is null. * * <p> * Example: * <pre> * {@code * InstantAsStringAttributeConverter converter = InstantAsStringAttributeConverter.create(); * assertEquals(converter.transformFrom(Instant.EPOCH), * EnhancedAttributeValue.fromString("1970-01-01T00:00:00Z").toAttributeValue()); * } * </pre> */ AttributeValue transformFrom(T input); /** * Convert the provided {@link AttributeValue} into a Java object. This will raise a {@link RuntimeException} if the * conversion fails, or the input is null. * * <p> * <pre> * Example: * {@code * InstantAsStringAttributeConverter converter = InstantAsStringAttributeConverter.create(); * assertEquals(converter.transformTo(EnhancedAttributeValue.fromString("1970-01-01T00:00:00Z").toAttributeValue()), * Instant.EPOCH); * } * </pre> */ T transformTo(AttributeValue input); /** * The type supported by this converter. */ EnhancedType<T> type(); /** * The {@link AttributeValueType} that a converter stores and reads values * from DynamoDB via the {@link AttributeValue} class. */ AttributeValueType attributeValueType(); }
4,376
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/AttributeValueType.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType; @SdkPublicApi @ThreadSafe public enum AttributeValueType { B(ScalarAttributeType.B), // binary BOOL, // boolean BS, // binary set L, // list M, // documentMap N(ScalarAttributeType.N), // number NS, // number set S(ScalarAttributeType.S), // string SS, // string set NULL; // null private final ScalarAttributeType scalarAttributeType; AttributeValueType() { this.scalarAttributeType = null; } AttributeValueType(ScalarAttributeType scalarAttributeType) { this.scalarAttributeType = scalarAttributeType; } public ScalarAttributeType scalarAttributeType() { return scalarAttributeType; } }
4,377
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/update/AddAction.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.update; import java.util.Collections; import java.util.HashMap; import java.util.Map; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * A representation of a single {@link UpdateExpression} ADD action. * <p> * At a minimum, this action must contain a path string referencing the attribute that should be acted upon and a value string * referencing the value to be added to the attribute. The value should be substituted with tokens using the * ':value_token' syntax and values associated with the token must be explicitly added to the expressionValues map. * Consult the DynamoDB UpdateExpression documentation for details on this action. * <p> * Optionally, attribute names can be substituted with tokens using the '#name_token' syntax. If tokens are used in the * expression then the names associated with those tokens must be explicitly added to the expressionNames map * that is also stored on this object. * <p> * Example:- * <pre> * {@code * AddUpdateAction addAction = AddUpdateAction.builder() * .path("#a") * .value(":b") * .putExpressionName("#a", "attributeA") * .putExpressionValue(":b", myAttributeValue) * .build(); * } * </pre> */ @SdkPublicApi public final class AddAction implements UpdateAction, ToCopyableBuilder<AddAction.Builder, AddAction> { private final String path; private final String value; private final Map<String, String> expressionNames; private final Map<String, AttributeValue> expressionValues; private AddAction(Builder builder) { this.path = Validate.paramNotNull(builder.path, "path"); this.value = Validate.paramNotNull(builder.value, "value"); this.expressionValues = wrapSecure(Validate.paramNotNull(builder.expressionValues, "expressionValues")); this.expressionNames = wrapSecure(builder.expressionNames != null ? builder.expressionNames : new HashMap<>()); } private static <T, U> Map<T, U> wrapSecure(Map<T, U> map) { return Collections.unmodifiableMap(new HashMap<>(map)); } /** * Constructs a new builder for {@link AddAction}. * * @return a new builder. */ public static Builder builder() { return new Builder(); } @Override public Builder toBuilder() { return builder().path(path) .value(value) .expressionNames(expressionNames) .expressionValues(expressionValues); } public String path() { return path; } public String value() { return value; } public Map<String, String> expressionNames() { return expressionNames; } public Map<String, AttributeValue> expressionValues() { return expressionValues; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } AddAction that = (AddAction) o; if (path != null ? ! path.equals(that.path) : that.path != null) { return false; } if (value != null ? ! value.equals(that.value) : that.value != null) { return false; } if (expressionValues != null ? ! expressionValues.equals(that.expressionValues) : that.expressionValues != null) { return false; } return expressionNames != null ? expressionNames.equals(that.expressionNames) : that.expressionNames == null; } @Override public int hashCode() { int result = path != null ? path.hashCode() : 0; result = 31 * result + (value != null ? value.hashCode() : 0); result = 31 * result + (expressionValues != null ? expressionValues.hashCode() : 0); result = 31 * result + (expressionNames != null ? expressionNames.hashCode() : 0); return result; } /** * A builder for {@link AddAction} */ public static final class Builder implements CopyableBuilder<Builder, AddAction> { private String path; private String value; private Map<String, String> expressionNames; private Map<String, AttributeValue> expressionValues; private Builder() { } /** * A string expression representing the attribute to be acted upon */ public Builder path(String path) { this.path = path; return this; } /** * A string expression representing the value used in the action. The value must be represented as an * expression attribute value token. */ public Builder value(String value) { this.value = value; return this; } /** * Sets the 'expression values' token map that maps from value references (expression attribute values) to * DynamoDB AttributeValues, overriding any existing values. * The value reference should always start with ':' (colon). * * @see #putExpressionValue(String, AttributeValue) */ public Builder expressionValues(Map<String, AttributeValue> expressionValues) { this.expressionValues = expressionValues == null ? null : new HashMap<>(expressionValues); return this; } /** * Adds a single element to the 'expression values' token map. * * @see #expressionValues(Map) */ public Builder putExpressionValue(String key, AttributeValue value) { if (this.expressionValues == null) { this.expressionValues = new HashMap<>(); } this.expressionValues.put(key, value); return this; } /** * Sets the optional 'expression names' token map, overriding any existing values. Use if the attribute * references in the path expression are token ('expression attribute names') prepended with the * '#' (pound) sign. It should map from token name to real attribute name. * * @see #putExpressionName(String, String) */ public Builder expressionNames(Map<String, String> expressionNames) { this.expressionNames = expressionNames == null ? null : new HashMap<>(expressionNames); return this; } /** * Adds a single element to the optional 'expression names' token map. * * @see #expressionNames(Map) */ public Builder putExpressionName(String key, String value) { if (this.expressionNames == null) { this.expressionNames = new HashMap<>(); } this.expressionNames.put(key, value); return this; } /** * Builds an {@link AddAction} based on the values stored in this builder. */ public AddAction build() { return new AddAction(this); } } }
4,378
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/update/SetAction.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.update; import java.util.Collections; import java.util.HashMap; import java.util.Map; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * A representation of a single {@link UpdateExpression} SET action. * <p> * At a minimum, this action must contain a path string referencing the attribute that should be acted upon and a value string * referencing the value to set or change. * <p> * The value string may contain just an operand, or operands combined with '+' or '-'. Furthermore, an operand can be a * reference to a specific value or a function. All references to values should be substituted with tokens using the * ':value_token' syntax and values associated with the token must be explicitly added to the expressionValues map. * Consult the DynamoDB UpdateExpression documentation for details on this action. * <p> * Optionally, attribute names can be substituted with tokens using the '#name_token' syntax. If tokens are used in the * expression then the names associated with those tokens must be explicitly added to the expressionNames map * that is also stored on this object. * <p> * Example:- * <pre> * {@code * //Simply setting the value of 'attributeA' to 'myAttributeValue' * SetUpdateAction setAction1 = SetUpdateAction.builder() * .path("#a") * .value(":b") * .putExpressionName("#a", "attributeA") * .putExpressionValue(":b", myAttributeValue) * .build(); * * //Increasing the value of 'attributeA' with 'delta' if it already exists, otherwise sets it to 'startValue' * SetUpdateAction setAction2 = SetUpdateAction.builder() * .path("#a") * .value("if_not_exists(#a, :startValue) + :delta") * .putExpressionName("#a", "attributeA") * .putExpressionValue(":delta", myNumericAttributeValue1) * .putExpressionValue(":startValue", myNumericAttributeValue2) * .build(); * } * </pre> */ @SdkPublicApi public final class SetAction implements UpdateAction, ToCopyableBuilder<SetAction.Builder, SetAction> { private final String path; private final String value; private final Map<String, String> expressionNames; private final Map<String, AttributeValue> expressionValues; private SetAction(Builder builder) { this.path = Validate.paramNotNull(builder.path, "path"); this.value = Validate.paramNotNull(builder.value, "value"); this.expressionValues = wrapSecure(Validate.paramNotNull(builder.expressionValues, "expressionValues")); this.expressionNames = wrapSecure(builder.expressionNames != null ? builder.expressionNames : new HashMap<>()); } private static <T, U> Map<T, U> wrapSecure(Map<T, U> map) { return Collections.unmodifiableMap(new HashMap<>(map)); } /** * Constructs a new builder for {@link SetAction}. * * @return a new builder. */ public static Builder builder() { return new Builder(); } @Override public Builder toBuilder() { return builder().path(path) .value(value) .expressionNames(expressionNames) .expressionValues(expressionValues); } public String path() { return path; } public String value() { return value; } public Map<String, String> expressionNames() { return expressionNames; } public Map<String, AttributeValue> expressionValues() { return expressionValues; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SetAction that = (SetAction) o; if (path != null ? ! path.equals(that.path) : that.path != null) { return false; } if (value != null ? ! value.equals(that.value) : that.value != null) { return false; } if (expressionValues != null ? ! expressionValues.equals(that.expressionValues) : that.expressionValues != null) { return false; } return expressionNames != null ? expressionNames.equals(that.expressionNames) : that.expressionNames == null; } @Override public int hashCode() { int result = path != null ? path.hashCode() : 0; result = 31 * result + (value != null ? value.hashCode() : 0); result = 31 * result + (expressionValues != null ? expressionValues.hashCode() : 0); result = 31 * result + (expressionNames != null ? expressionNames.hashCode() : 0); return result; } /** * A builder for {@link SetAction} */ public static final class Builder implements CopyableBuilder<Builder, SetAction> { private String path; private String value; private Map<String, String> expressionNames; private Map<String, AttributeValue> expressionValues; private Builder() { } /** * A string expression representing the attribute to be acted upon */ public Builder path(String path) { this.path = path; return this; } /** * A string expression representing the value used in the action. The value must be represented as an * expression attribute value token. */ public Builder value(String value) { this.value = value; return this; } /** * Sets the 'expression values' token map that maps from value references (expression attribute values) to * DynamoDB AttributeValues, overriding any existing values. * The value reference should always start with ':' (colon). * * @see #putExpressionValue(String, AttributeValue) */ public Builder expressionValues(Map<String, AttributeValue> expressionValues) { this.expressionValues = expressionValues == null ? null : new HashMap<>(expressionValues); return this; } /** * Adds a single element to the 'expression values' token map. * * @see #expressionValues(Map) */ public Builder putExpressionValue(String key, AttributeValue value) { if (this.expressionValues == null) { this.expressionValues = new HashMap<>(); } this.expressionValues.put(key, value); return this; } /** * Sets the optional 'expression names' token map, overriding any existing values. Use if the attribute * references in the path expression are token ('expression attribute names') prepended with the * '#' (pound) sign. It should map from token name to real attribute name. * * @see #putExpressionName(String, String) */ public Builder expressionNames(Map<String, String> expressionNames) { this.expressionNames = expressionNames == null ? null : new HashMap<>(expressionNames); return this; } /** * Adds a single element to the optional 'expression names' token map. * * @see #expressionNames(Map) */ public Builder putExpressionName(String key, String value) { if (this.expressionNames == null) { this.expressionNames = new HashMap<>(); } this.expressionNames.put(key, value); return this; } /** * Builds an {@link SetAction} based on the values stored in this builder. */ public SetAction build() { return new SetAction(this); } } }
4,379
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/update/RemoveAction.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.update; import java.util.Collections; import java.util.HashMap; import java.util.Map; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * A representation of a single {@link UpdateExpression} REMOVE action. * <p> * At a minimum, this action must contain a path string referencing the attribute that should be removed when applying this * action. Consult the DynamoDB UpdateExpression documentation for details on this action. * <p> * Optionally, attribute names can be substituted with tokens using the '#name_token' syntax. If tokens are used in the * expression then the names associated with those tokens must be explicitly added to the expressionNames map * that is also stored on this object. * <p> * Example:- * <pre> * {@code * RemoveUpdateAction removeAction = RemoveUpdateAction.builder() * .path("#a") * .putExpressionName("#a", "attributeA") * .build(); * } * </pre> */ @SdkPublicApi public final class RemoveAction implements UpdateAction, ToCopyableBuilder<RemoveAction.Builder, RemoveAction> { private final String path; private final Map<String, String> expressionNames; private RemoveAction(Builder builder) { this.path = Validate.paramNotNull(builder.path, "path"); this.expressionNames = wrapSecure(builder.expressionNames != null ? builder.expressionNames : new HashMap<>()); } private static <T, U> Map<T, U> wrapSecure(Map<T, U> map) { return Collections.unmodifiableMap(new HashMap<>(map)); } /** * Constructs a new builder for {@link RemoveAction}. * * @return a new builder. */ public static Builder builder() { return new Builder(); } @Override public Builder toBuilder() { return builder().path(path) .expressionNames(expressionNames); } public String path() { return path; } public Map<String, String> expressionNames() { return expressionNames; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } RemoveAction that = (RemoveAction) o; if (path != null ? ! path.equals(that.path) : that.path != null) { return false; } return expressionNames != null ? expressionNames.equals(that.expressionNames) : that.expressionNames == null; } @Override public int hashCode() { int result = path != null ? path.hashCode() : 0; result = 31 * result + (expressionNames != null ? expressionNames.hashCode() : 0); return result; } /** * A builder for {@link RemoveAction} */ public static final class Builder implements CopyableBuilder<Builder, RemoveAction> { private String path; private Map<String, String> expressionNames; private Builder() { } /** * A string expression representing the attribute to remove */ public Builder path(String path) { this.path = path; return this; } /** * Sets the optional 'expression names' token map, overriding any existing values. Use if the attribute * references in the path expression are token ('expression attribute names') prepended with the * '#' (pound) sign. It should map from token name to real attribute name. * * @see #putExpressionName(String, String) */ public Builder expressionNames(Map<String, String> expressionNames) { this.expressionNames = expressionNames == null ? null : new HashMap<>(expressionNames); return this; } /** * Adds a single element to the optional 'expression names' token map. * * @see #expressionNames(Map) */ public Builder putExpressionName(String key, String value) { if (this.expressionNames == null) { this.expressionNames = new HashMap<>(); } this.expressionNames.put(key, value); return this; } /** * Builds an {@link RemoveAction} based on the values stored in this builder. */ public RemoveAction build() { return new RemoveAction(this); } } }
4,380
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/update/DeleteAction.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.update; import java.util.Collections; import java.util.HashMap; import java.util.Map; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * A representation of a single {@link UpdateExpression} DELETE action. * <p> * At a minimum, this action must contain a path string referencing the attribute that should be acted upon and a value string * referencing the value (subset) to be removed from the attribute. The value should be substituted with tokens using the * ':value_token' syntax and values associated with the token must be explicitly added to the expressionValues map. * Consult the DynamoDB UpdateExpression documentation for details on this action. * <p> * Optionally, attribute names can be substituted with tokens using the '#name_token' syntax. If tokens are used in the * expression then the names associated with those tokens must be explicitly added to the expressionNames map * that is also stored on this object. * <p> * Example:- * <pre> * {@code * DeleteUpdateAction deleteAction = DeleteUpdateAction.builder() * .path("#a") * .value(":b") * .putExpressionName("#a", "attributeA") * .putExpressionValue(":b", myAttributeValue) * .build(); * } * </pre> */ @SdkPublicApi public final class DeleteAction implements UpdateAction, ToCopyableBuilder<DeleteAction.Builder, DeleteAction> { private final String path; private final String value; private final Map<String, String> expressionNames; private final Map<String, AttributeValue> expressionValues; private DeleteAction(Builder builder) { this.path = Validate.paramNotNull(builder.path, "path"); this.value = Validate.paramNotNull(builder.value, "value"); this.expressionValues = wrapSecure(Validate.paramNotNull(builder.expressionValues, "expressionValues")); this.expressionNames = wrapSecure(builder.expressionNames != null ? builder.expressionNames : new HashMap<>()); } private static <T, U> Map<T, U> wrapSecure(Map<T, U> map) { return Collections.unmodifiableMap(new HashMap<>(map)); } /** * Constructs a new builder for {@link DeleteAction}. * * @return a new builder. */ public static Builder builder() { return new Builder(); } @Override public Builder toBuilder() { return builder().path(path) .value(value) .expressionNames(expressionNames) .expressionValues(expressionValues); } public String path() { return path; } public String value() { return value; } public Map<String, String> expressionNames() { return expressionNames; } public Map<String, AttributeValue> expressionValues() { return expressionValues; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DeleteAction that = (DeleteAction) o; if (path != null ? ! path.equals(that.path) : that.path != null) { return false; } if (value != null ? ! value.equals(that.value) : that.value != null) { return false; } if (expressionValues != null ? ! expressionValues.equals(that.expressionValues) : that.expressionValues != null) { return false; } return expressionNames != null ? expressionNames.equals(that.expressionNames) : that.expressionNames == null; } @Override public int hashCode() { int result = path != null ? path.hashCode() : 0; result = 31 * result + (value != null ? value.hashCode() : 0); result = 31 * result + (expressionValues != null ? expressionValues.hashCode() : 0); result = 31 * result + (expressionNames != null ? expressionNames.hashCode() : 0); return result; } /** * A builder for {@link DeleteAction} */ public static final class Builder implements CopyableBuilder<Builder, DeleteAction> { private String path; private String value; private Map<String, String> expressionNames; private Map<String, AttributeValue> expressionValues; private Builder() { } /** * A string expression representing the attribute to be acted upon */ public Builder path(String path) { this.path = path; return this; } /** * A string expression representing the value used in the action. The value must be represented as an * expression attribute value token. */ public Builder value(String value) { this.value = value; return this; } /** * Sets the 'expression values' token map that maps from value references (expression attribute values) to * DynamoDB AttributeValues, overriding any existing values. * The value reference should always start with ':' (colon). * * @see #putExpressionValue(String, AttributeValue) */ public Builder expressionValues(Map<String, AttributeValue> expressionValues) { this.expressionValues = expressionValues == null ? null : new HashMap<>(expressionValues); return this; } /** * Adds a single element to the 'expression values' token map. * * @see #expressionValues(Map) */ public Builder putExpressionValue(String key, AttributeValue value) { if (this.expressionValues == null) { this.expressionValues = new HashMap<>(); } this.expressionValues.put(key, value); return this; } /** * Sets the optional 'expression names' token map, overriding any existing values. Use if the attribute * references in the path expression are token ('expression attribute names') prepended with the * '#' (pound) sign. It should map from token name to real attribute name. * * @see #putExpressionName(String, String) */ public Builder expressionNames(Map<String, String> expressionNames) { this.expressionNames = expressionNames == null ? null : new HashMap<>(expressionNames); return this; } /** * Adds a single element to the optional 'expression names' token map. * * @see #expressionNames(Map) */ public Builder putExpressionName(String key, String value) { if (this.expressionNames == null) { this.expressionNames = new HashMap<>(); } this.expressionNames.put(key, value); return this; } /** * Builds an {@link DeleteAction} based on the values stored in this builder. */ public DeleteAction build() { return new DeleteAction(this); } } }
4,381
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/update/UpdateExpression.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.update; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import software.amazon.awssdk.annotations.SdkPublicApi; /** * Contains sets of {@link UpdateAction} that represent the four DynamoDB update actions: SET, ADD, REMOVE and DELETE. * <p> * Use this class to build an immutable UpdateExpression with one or more UpdateAction. An UpdateExpression may be merged * with another. When two UpdateExpression are merged, the actions of each group of UpdateAction, should they exist, are * combined; all SET actions from each expression are concatenated, all REMOVE actions etc. * <p> * DynamoDb Enhanced will convert the UpdateExpression to a format readable by DynamoDb, * <p> * Example:- * <pre> * {@code * RemoveUpdateAction removeAction = ... * SetUpdateAction setAction = ... * UpdateExpression.builder() * .addAction(removeAction) * .addAction(setAction) * .build(); * } * </pre> * * See respective subtype of {@link UpdateAction}, for example {@link SetAction}, for details on creating that action. */ @SdkPublicApi public final class UpdateExpression { private final List<RemoveAction> removeActions; private final List<SetAction> setActions; private final List<DeleteAction> deleteActions; private final List<AddAction> addActions; private UpdateExpression(Builder builder) { this.removeActions = builder.removeActions; this.setActions = builder.setActions; this.deleteActions = builder.deleteActions; this.addActions = builder.addActions; } /** * Constructs a new builder for {@link UpdateExpression}. * * @return a new builder. */ public static Builder builder() { return new Builder(); } public List<RemoveAction> removeActions() { return Collections.unmodifiableList(new ArrayList<>(removeActions)); } public List<SetAction> setActions() { return Collections.unmodifiableList(new ArrayList<>(setActions)); } public List<DeleteAction> deleteActions() { return Collections.unmodifiableList(new ArrayList<>(deleteActions)); } public List<AddAction> addActions() { return Collections.unmodifiableList(new ArrayList<>(addActions)); } /** * Merges two UpdateExpression, returning a new */ public static UpdateExpression mergeExpressions(UpdateExpression expression1, UpdateExpression expression2) { if (expression1 == null) { return expression2; } if (expression2 == null) { return expression1; } Builder builder = builder(); builder.removeActions = Stream.concat(expression1.removeActions.stream(), expression2.removeActions.stream()).collect(Collectors.toList()); builder.setActions = Stream.concat(expression1.setActions.stream(), expression2.setActions.stream()).collect(Collectors.toList()); builder.deleteActions = Stream.concat(expression1.deleteActions.stream(), expression2.deleteActions.stream()).collect(Collectors.toList()); builder.addActions = Stream.concat(expression1.addActions.stream(), expression2.addActions.stream()).collect(Collectors.toList()); return builder.build(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } UpdateExpression that = (UpdateExpression) o; if (removeActions != null ? ! removeActions.equals(that.removeActions) : that.removeActions != null) { return false; } if (setActions != null ? ! setActions.equals(that.setActions) : that.setActions != null) { return false; } if (deleteActions != null ? ! deleteActions.equals(that.deleteActions) : that.deleteActions != null) { return false; } return addActions != null ? addActions.equals(that.addActions) : that.addActions == null; } @Override public int hashCode() { int result = removeActions != null ? removeActions.hashCode() : 0; result = 31 * result + (setActions != null ? setActions.hashCode() : 0); result = 31 * result + (deleteActions != null ? deleteActions.hashCode() : 0); result = 31 * result + (addActions != null ? addActions.hashCode() : 0); return result; } /** * A builder for {@link UpdateExpression} */ public static final class Builder { private List<RemoveAction> removeActions = new ArrayList<>(); private List<SetAction> setActions = new ArrayList<>(); private List<DeleteAction> deleteActions = new ArrayList<>(); private List<AddAction> addActions = new ArrayList<>(); private Builder() { } /** * Add an action of type {@link RemoveAction} */ public Builder addAction(RemoveAction action) { removeActions.add(action); return this; } /** * Add an action of type {@link SetAction} */ public Builder addAction(SetAction action) { setActions.add(action); return this; } /** * Add an action of type {@link DeleteAction} */ public Builder addAction(DeleteAction action) { deleteActions.add(action); return this; } /** * Add an action of type {@link AddAction} */ public Builder addAction(AddAction action) { addActions.add(action); return this; } /** * Adds a list of {@link UpdateAction} of any subtype to the builder, overwriting any previous values. */ public Builder actions(List<? extends UpdateAction> actions) { replaceActions(actions); return this; } /** * Adds a list of {@link UpdateAction} of any subtype to the builder, overwriting any previous values. */ public Builder actions(UpdateAction... actions) { actions(Arrays.asList(actions)); return this; } /** * Builds an {@link UpdateExpression} based on the values stored in this builder. */ public UpdateExpression build() { return new UpdateExpression(this); } private void replaceActions(List<? extends UpdateAction> actions) { if (actions != null) { this.removeActions = new ArrayList<>(); this.setActions = new ArrayList<>(); this.deleteActions = new ArrayList<>(); this.addActions = new ArrayList<>(); actions.forEach(this::assignAction); } } private void assignAction(UpdateAction action) { if (action instanceof RemoveAction) { addAction((RemoveAction) action); } else if (action instanceof SetAction) { addAction((SetAction) action); } else if (action instanceof DeleteAction) { addAction((DeleteAction) action); } else if (action instanceof AddAction) { addAction((AddAction) action); } else { throw new IllegalArgumentException( String.format("Do not recognize UpdateAction: %s", action.getClass())); } } } }
4,382
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/update/UpdateAction.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.update; import software.amazon.awssdk.annotations.SdkPublicApi; /** * An update action represents a part of an {@link UpdateExpression} */ @SdkPublicApi public interface UpdateAction { }
4,383
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper/StaticImmutableTableSchema.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.unmodifiableMap; import static software.amazon.awssdk.enhanced.dynamodb.internal.EnhancedClientUtils.isNullAttributeValue; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Stream; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.enhanced.dynamodb.AttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.AttributeConverterProvider; import software.amazon.awssdk.enhanced.dynamodb.DefaultAttributeConverterProvider; import software.amazon.awssdk.enhanced.dynamodb.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.ConverterProviderResolver; import software.amazon.awssdk.enhanced.dynamodb.internal.mapper.ResolvedImmutableAttribute; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * Implementation of {@link TableSchema} that builds a schema for immutable data objects based on directly declared * attributes. Just like {@link StaticTableSchema} which is the equivalent implementation for mutable objects, this is * the most direct, and thus fastest, implementation of {@link TableSchema}. * <p> * Example using a fictional 'Customer' immutable data item class that has an inner builder class named 'Builder':- * {@code * static final TableSchema<Customer> CUSTOMER_TABLE_SCHEMA = * StaticImmutableTableSchema.builder(Customer.class, Customer.Builder.class) * .newItemBuilder(Customer::builder, Customer.Builder::build) * .addAttribute(String.class, a -> a.name("account_id") * .getter(Customer::accountId) * .setter(Customer.Builder::accountId) * .tags(primaryPartitionKey())) * .addAttribute(Integer.class, a -> a.name("sub_id") * .getter(Customer::subId) * .setter(Customer.Builder::subId) * .tags(primarySortKey())) * .addAttribute(String.class, a -> a.name("name") * .getter(Customer::name) * .setter(Customer.Builder::name) * .tags(secondaryPartitionKey("customers_by_name"))) * .addAttribute(Instant.class, a -> a.name("created_date") * .getter(Customer::createdDate) * .setter(Customer.Builder::createdDate) * .tags(secondarySortKey("customers_by_date"), * secondarySortKey("customers_by_name"))) * .build(); * } */ @SdkPublicApi @ThreadSafe public final class StaticImmutableTableSchema<T, B> implements TableSchema<T> { private final List<ResolvedImmutableAttribute<T, B>> attributeMappers; private final Supplier<B> newBuilderSupplier; private final Function<B, T> buildItemFunction; private final Map<String, ResolvedImmutableAttribute<T, B>> indexedMappers; private final StaticTableMetadata tableMetadata; private final EnhancedType<T> itemType; private final AttributeConverterProvider attributeConverterProvider; private final Map<String, FlattenedMapper<T, B, ?>> indexedFlattenedMappers; private final List<String> attributeNames; private static class FlattenedMapper<T, B, T1> { private final Function<T, T1> otherItemGetter; private final BiConsumer<B, T1> otherItemSetter; private final TableSchema<T1> otherItemTableSchema; private FlattenedMapper(Function<T, T1> otherItemGetter, BiConsumer<B, T1> otherItemSetter, TableSchema<T1> otherItemTableSchema) { this.otherItemGetter = otherItemGetter; this.otherItemSetter = otherItemSetter; this.otherItemTableSchema = otherItemTableSchema; } public TableSchema<T1> getOtherItemTableSchema() { return otherItemTableSchema; } private B mapToItem(B thisBuilder, Supplier<B> thisBuilderConstructor, Map<String, AttributeValue> attributeValues) { T1 otherItem = this.otherItemTableSchema.mapToItem(attributeValues); if (otherItem != null) { if (thisBuilder == null) { thisBuilder = thisBuilderConstructor.get(); } this.otherItemSetter.accept(thisBuilder, otherItem); } return thisBuilder; } private Map<String, AttributeValue> itemToMap(T item, boolean ignoreNulls) { T1 otherItem = this.otherItemGetter.apply(item); if (otherItem == null) { return Collections.emptyMap(); } return this.otherItemTableSchema.itemToMap(otherItem, ignoreNulls); } private AttributeValue attributeValue(T item, String attributeName) { T1 otherItem = this.otherItemGetter.apply(item); if (otherItem == null) { return null; } AttributeValue attributeValue = this.otherItemTableSchema.attributeValue(otherItem, attributeName); return isNullAttributeValue(attributeValue) ? null : attributeValue; } } private StaticImmutableTableSchema(Builder<T, B> builder) { StaticTableMetadata.Builder tableMetadataBuilder = StaticTableMetadata.builder(); this.attributeConverterProvider = ConverterProviderResolver.resolveProviders(builder.attributeConverterProviders); // Resolve declared attributes and find converters for them Stream<ResolvedImmutableAttribute<T, B>> attributesStream = builder.attributes == null ? Stream.empty() : builder.attributes.stream().map(a -> a.resolve(this.attributeConverterProvider)); // Merge resolved declared attributes List<ResolvedImmutableAttribute<T, B>> mutableAttributeMappers = new ArrayList<>(); Map<String, ResolvedImmutableAttribute<T, B>> mutableIndexedMappers = new HashMap<>(); Set<String> mutableAttributeNames = new LinkedHashSet<>(); Stream.concat(attributesStream, builder.additionalAttributes.stream()).forEach( resolvedAttribute -> { String attributeName = resolvedAttribute.attributeName(); if (mutableAttributeNames.contains(attributeName)) { throw new IllegalArgumentException( "Attempt to add an attribute to a mapper that already has one with the same name. " + "[Attribute name: " + attributeName + "]"); } mutableAttributeNames.add(attributeName); mutableAttributeMappers.add(resolvedAttribute); mutableIndexedMappers.put(attributeName, resolvedAttribute); // Merge in metadata associated with attribute tableMetadataBuilder.mergeWith(resolvedAttribute.tableMetadata()); } ); Map<String, FlattenedMapper<T, B, ?>> mutableFlattenedMappers = new HashMap<>(); builder.flattenedMappers.forEach( flattenedMapper -> { flattenedMapper.otherItemTableSchema.attributeNames().forEach( attributeName -> { if (mutableAttributeNames.contains(attributeName)) { throw new IllegalArgumentException( "Attempt to add an attribute to a mapper that already has one with the same name. " + "[Attribute name: " + attributeName + "]"); } mutableAttributeNames.add(attributeName); mutableFlattenedMappers.put(attributeName, flattenedMapper); } ); tableMetadataBuilder.mergeWith(flattenedMapper.getOtherItemTableSchema().tableMetadata()); } ); // Apply table-tags to table metadata if (builder.tags != null) { builder.tags.forEach(staticTableTag -> staticTableTag.modifyMetadata().accept(tableMetadataBuilder)); } this.attributeMappers = Collections.unmodifiableList(mutableAttributeMappers); this.indexedMappers = Collections.unmodifiableMap(mutableIndexedMappers); this.attributeNames = Collections.unmodifiableList(new ArrayList<>(mutableAttributeNames)); this.indexedFlattenedMappers = Collections.unmodifiableMap(mutableFlattenedMappers); this.newBuilderSupplier = builder.newBuilderSupplier; this.buildItemFunction = builder.buildItemFunction; this.tableMetadata = tableMetadataBuilder.build(); this.itemType = builder.itemType; } /** * Creates a builder for a {@link StaticImmutableTableSchema} typed to specific immutable data item class. * @param itemClass The immutable data item class object that the {@link StaticImmutableTableSchema} is to map to. * @param builderClass The builder class object that can be used to construct instances of the immutable data item. * @return A newly initialized builder */ public static <T, B> Builder<T, B> builder(Class<T> itemClass, Class<B> builderClass) { return new Builder<>(EnhancedType.of(itemClass), EnhancedType.of(builderClass)); } /** * Creates a builder for a {@link StaticImmutableTableSchema} typed to specific immutable data item class. * @param itemType The {@link EnhancedType} of the immutable data item class object that the * {@link StaticImmutableTableSchema} is to map to. * @param builderType The builder {@link EnhancedType} that can be used to construct instances of the immutable data item. * @return A newly initialized builder */ public static <T, B> Builder<T, B> builder(EnhancedType<T> itemType, EnhancedType<B> builderType) { return new Builder<>(itemType, builderType); } /** * Builder for a {@link StaticImmutableTableSchema} * @param <T> The immutable data item class object that the {@link StaticImmutableTableSchema} is to map to. * @param <B> The builder class object that can be used to construct instances of the immutable data item. */ @NotThreadSafe public static final class Builder<T, B> { private final EnhancedType<T> itemType; private final EnhancedType<B> builderType; private final List<ResolvedImmutableAttribute<T, B>> additionalAttributes = new ArrayList<>(); private final List<FlattenedMapper<T, B, ?>> flattenedMappers = new ArrayList<>(); private List<ImmutableAttribute<T, B, ?>> attributes; private Supplier<B> newBuilderSupplier; private Function<B, T> buildItemFunction; private List<StaticTableTag> tags; private List<AttributeConverterProvider> attributeConverterProviders = Collections.singletonList(ConverterProviderResolver.defaultConverterProvider()); private Builder(EnhancedType<T> itemType, EnhancedType<B> builderType) { this.itemType = itemType; this.builderType = builderType; } /** * Methods used to construct a new instance of the immutable data object. * @param newBuilderMethod A method to create a new builder for the immutable data object. * @param buildMethod A method on the builder to build a new instance of the immutable data object. */ public Builder<T, B> newItemBuilder(Supplier<B> newBuilderMethod, Function<B, T> buildMethod) { this.newBuilderSupplier = newBuilderMethod; this.buildItemFunction = buildMethod; return this; } /** * A list of attributes that can be mapped between the data item object and the database record that are to * be associated with the schema. Will overwrite any existing attributes. */ @SafeVarargs public final Builder<T, B> attributes(ImmutableAttribute<T, B, ?>... immutableAttributes) { this.attributes = Arrays.asList(immutableAttributes); return this; } /** * A list of attributes that can be mapped between the data item object and the database record that are to * be associated with the schema. Will overwrite any existing attributes. */ public Builder<T, B> attributes(Collection<ImmutableAttribute<T, B, ?>> immutableAttributes) { this.attributes = new ArrayList<>(immutableAttributes); return this; } /** * Adds a single attribute to the table schema that can be mapped between the data item object and the database * record. */ public <R> Builder<T, B> addAttribute(EnhancedType<R> attributeType, Consumer<ImmutableAttribute.Builder<T, B, R>> immutableAttribute) { ImmutableAttribute.Builder<T, B, R> builder = ImmutableAttribute.builder(itemType, builderType, attributeType); immutableAttribute.accept(builder); return addAttribute(builder.build()); } /** * Adds a single attribute to the table schema that can be mapped between the data item object and the database * record. */ public <R> Builder<T, B> addAttribute(Class<R> attributeClass, Consumer<ImmutableAttribute.Builder<T, B, R>> immutableAttribute) { return addAttribute(EnhancedType.of(attributeClass), immutableAttribute); } /** * Adds a single attribute to the table schema that can be mapped between the data item object and the database * record. */ public Builder<T, B> addAttribute(ImmutableAttribute<T, B, ?> immutableAttribute) { if (this.attributes == null) { this.attributes = new ArrayList<>(); } this.attributes.add(immutableAttribute); return this; } /** * Associate one or more {@link StaticTableTag} with this schema. See documentation on the tags themselves to * understand what each one does. This method will overwrite any existing table tags. */ public Builder<T, B> tags(StaticTableTag... staticTableTags) { this.tags = Arrays.asList(staticTableTags); return this; } /** * Associate one or more {@link StaticTableTag} with this schema. See documentation on the tags themselves to * understand what each one does. This method will overwrite any existing table tags. */ public Builder<T, B> tags(Collection<StaticTableTag> staticTableTags) { this.tags = new ArrayList<>(staticTableTags); return this; } /** * Associates a {@link StaticTableTag} with this schema. See documentation on the tags themselves to understand * what each one does. This method will add the tag to the list of existing table tags. */ public Builder<T, B> addTag(StaticTableTag staticTableTag) { if (this.tags == null) { this.tags = new ArrayList<>(); } this.tags.add(staticTableTag); return this; } /** * Flattens all the attributes defined in another {@link TableSchema} into the database record this schema * maps to. Functions to get and set an object that the flattened schema maps to is required. */ public <T1> Builder<T, B> flatten(TableSchema<T1> otherTableSchema, Function<T, T1> otherItemGetter, BiConsumer<B, T1> otherItemSetter) { if (otherTableSchema.isAbstract()) { throw new IllegalArgumentException("Cannot flatten an abstract TableSchema. You must supply a concrete " + "TableSchema that is able to create items"); } FlattenedMapper<T, B, T1> flattenedMapper = new FlattenedMapper<>(otherItemGetter, otherItemSetter, otherTableSchema); this.flattenedMappers.add(flattenedMapper); return this; } /** * Extends the {@link StaticImmutableTableSchema} of a super-class, effectively rolling all the attributes modelled by * the super-class into the {@link StaticImmutableTableSchema} of the sub-class. The extended immutable table schema * must be using a builder class that is also a super-class of the builder being used for the current immutable * table schema. */ public Builder<T, B> extend(StaticImmutableTableSchema<? super T, ? super B> superTableSchema) { Stream<ResolvedImmutableAttribute<T, B>> attributeStream = upcastingTransformForAttributes(superTableSchema.attributeMappers); attributeStream.forEach(this.additionalAttributes::add); return this; } /** * Specifies the {@link AttributeConverterProvider}s to use with the table schema. * The list of attribute converter providers must provide {@link AttributeConverter}s for all types used * in the schema. The attribute converter providers will be loaded in the strict order they are supplied here. * <p> * Calling this method will override the default attribute converter provider * {@link DefaultAttributeConverterProvider}, which provides standard converters for most primitive * and common Java types, so that provider must included in the supplied list if it is to be * used. Providing an empty list here will cause no providers to get loaded. * <p> * Adding one custom attribute converter provider and using the default as fallback: * {@code * builder.attributeConverterProviders(customAttributeConverter, AttributeConverterProvider.defaultProvider()) * } * * @param attributeConverterProviders a list of attribute converter providers to use with the table schema */ public Builder<T, B> attributeConverterProviders(AttributeConverterProvider... attributeConverterProviders) { this.attributeConverterProviders = Arrays.asList(attributeConverterProviders); return this; } /** * Specifies the {@link AttributeConverterProvider}s to use with the table schema. * The list of attribute converter providers must provide {@link AttributeConverter}s for all types used * in the schema. The attribute converter providers will be loaded in the strict order they are supplied here. * <p> * Calling this method will override the default attribute converter provider * {@link DefaultAttributeConverterProvider}, which provides standard converters * for most primitive and common Java types, so that provider must included in the supplied list if it is to be * used. Providing an empty list here will cause no providers to get loaded. * <p> * Adding one custom attribute converter provider and using the default as fallback: * {@code * List<AttributeConverterProvider> providers = new ArrayList<>( * customAttributeConverter, * AttributeConverterProvider.defaultProvider()); * builder.attributeConverterProviders(providers); * } * * @param attributeConverterProviders a list of attribute converter providers to use with the table schema */ public Builder<T, B> attributeConverterProviders(List<AttributeConverterProvider> attributeConverterProviders) { this.attributeConverterProviders = new ArrayList<>(attributeConverterProviders); return this; } /** * Builds a {@link StaticImmutableTableSchema} based on the values this builder has been configured with */ public StaticImmutableTableSchema<T, B> build() { return new StaticImmutableTableSchema<>(this); } private static <T extends T1, T1, B extends B1, B1> Stream<ResolvedImmutableAttribute<T, B>> upcastingTransformForAttributes(Collection<ResolvedImmutableAttribute<T1, B1>> superAttributes) { return superAttributes.stream().map(attribute -> attribute.transform(x -> x, x -> x)); } } @Override public StaticTableMetadata tableMetadata() { return tableMetadata; } @Override public T mapToItem(Map<String, AttributeValue> attributeMap, boolean preserveEmptyObject) { B builder = null; // Instantiate the builder right now if preserveEmtpyBean is true, otherwise lazily instantiate the builder once // we have an attribute to write if (preserveEmptyObject) { builder = constructNewBuilder(); } Map<FlattenedMapper<T, B, ?>, Map<String, AttributeValue>> flattenedAttributeValuesMap = new LinkedHashMap<>(); for (Map.Entry<String, AttributeValue> entry : attributeMap.entrySet()) { String key = entry.getKey(); AttributeValue value = entry.getValue(); if (!isNullAttributeValue(value)) { ResolvedImmutableAttribute<T, B> attributeMapper = indexedMappers.get(key); if (attributeMapper != null) { if (builder == null) { builder = constructNewBuilder(); } attributeMapper.updateItemMethod().accept(builder, value); } else { FlattenedMapper<T, B, ?> flattenedMapper = this.indexedFlattenedMappers.get(key); if (flattenedMapper != null) { Map<String, AttributeValue> flattenedAttributeValues = flattenedAttributeValuesMap.get(flattenedMapper); if (flattenedAttributeValues == null) { flattenedAttributeValues = new HashMap<>(); } flattenedAttributeValues.put(key, value); flattenedAttributeValuesMap.put(flattenedMapper, flattenedAttributeValues); } } } } for (Map.Entry<FlattenedMapper<T, B, ?>, Map<String, AttributeValue>> entry : flattenedAttributeValuesMap.entrySet()) { builder = entry.getKey().mapToItem(builder, this::constructNewBuilder, entry.getValue()); } return builder == null ? null : buildItemFunction.apply(builder); } @Override public T mapToItem(Map<String, AttributeValue> attributeMap) { return mapToItem(attributeMap, false); } @Override public Map<String, AttributeValue> itemToMap(T item, boolean ignoreNulls) { Map<String, AttributeValue> attributeValueMap = new HashMap<>(); attributeMappers.forEach(attributeMapper -> { String attributeKey = attributeMapper.attributeName(); AttributeValue attributeValue = attributeMapper.attributeGetterMethod().apply(item); if (!ignoreNulls || !isNullAttributeValue(attributeValue)) { attributeValueMap.put(attributeKey, attributeValue); } }); indexedFlattenedMappers.forEach((name, flattenedMapper) -> { attributeValueMap.putAll(flattenedMapper.itemToMap(item, ignoreNulls)); }); return unmodifiableMap(attributeValueMap); } @Override public Map<String, AttributeValue> itemToMap(T item, Collection<String> attributes) { Map<String, AttributeValue> attributeValueMap = new HashMap<>(); attributes.forEach(key -> { AttributeValue attributeValue = attributeValue(item, key); if (attributeValue == null || !isNullAttributeValue(attributeValue)) { attributeValueMap.put(key, attributeValue); } }); return unmodifiableMap(attributeValueMap); } @Override public AttributeValue attributeValue(T item, String key) { ResolvedImmutableAttribute<T, B> attributeMapper = indexedMappers.get(key); if (attributeMapper == null) { FlattenedMapper<T, B, ?> flattenedMapper = indexedFlattenedMappers.get(key); if (flattenedMapper == null) { throw new IllegalArgumentException(String.format("TableSchema does not know how to retrieve requested " + "attribute '%s' from mapped object.", key)); } return flattenedMapper.attributeValue(item, key); } AttributeValue attributeValue = attributeMapper.attributeGetterMethod().apply(item); return isNullAttributeValue(attributeValue) ? null : attributeValue; } @Override public EnhancedType<T> itemType() { return this.itemType; } @Override public List<String> attributeNames() { return this.attributeNames; } @Override public boolean isAbstract() { return this.buildItemFunction == null; } /** * The table schema {@link AttributeConverterProvider}. * @see Builder#attributeConverterProvider */ public AttributeConverterProvider attributeConverterProvider() { return this.attributeConverterProvider; } private B constructNewBuilder() { if (newBuilderSupplier == null) { throw new UnsupportedOperationException("An abstract TableSchema cannot be used to map a database record " + "to a concrete object. Add a 'newItemBuilder' to the " + "TableSchema to give it the ability to create mapped objects."); } return newBuilderSupplier.get(); } @Override public AttributeConverter<T> converterForAttribute(Object key) { ResolvedImmutableAttribute<T, B> resolvedImmutableAttribute = indexedMappers.get(key); if (resolvedImmutableAttribute != null) { return resolvedImmutableAttribute.attributeConverter(); } // If no resolvedAttribute is found look through flattened attributes FlattenedMapper<T, B, ?> flattenedMapper = indexedFlattenedMappers.get(key); if (flattenedMapper != null) { return (AttributeConverter) flattenedMapper.getOtherItemTableSchema().converterForAttribute(key); } return null; } }
4,384
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper/StaticAttributeTag.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 java.util.function.Consumer; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType; import software.amazon.awssdk.enhanced.dynamodb.EnhancedType; /** * Interface for a tag that can be applied to any {@link StaticAttribute}. When a tagged attribute is added to a * {@link software.amazon.awssdk.enhanced.dynamodb.TableSchema}, the table metadata stored on the schema will be updated * by calling the {@link #modifyMetadata(String, AttributeValueType)} method for every tag associated with the * attribute. * <p> * Common implementations of this interface that can be used to declare indices in your schema can be found in * {@link StaticAttributeTags}. */ @SdkPublicApi @ThreadSafe public interface StaticAttributeTag { /** * A function that modifies an existing {@link StaticTableSchema.Builder} when this tag is applied to a specific * attribute. This will be used by the {@link StaticTableSchema} to capture all the metadata associated with * tagged attributes when constructing the table schema. * * @param attributeName The name of the attribute this tag has been applied to. * @param attributeValueType The type of the attribute this tag has been applied to. This can be used for * validation, for instance if you have an attribute tag that should only be associated * with a string. * @return a consumer that modifies an existing {@link StaticTableSchema.Builder}. */ Consumer<StaticTableMetadata.Builder> modifyMetadata(String attributeName, AttributeValueType attributeValueType); /** * Function that validates the Converted return type is suitable for the extension. * @param <R> the class that the value of this attribute converts to. * @param attributeName The name of the attribute this tag has been applied to. * @param enhancedType The type of the object to be converted * @param attributeValueType Attribute Value type of the attribute. */ default <R> void validateType(String attributeName, EnhancedType<R> enhancedType, AttributeValueType attributeValueType) { } }
4,385
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper/ImmutableTableSchema.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 software.amazon.awssdk.enhanced.dynamodb.internal.DynamoDbEnhancedLogger.BEAN_LOGGER; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.WeakHashMap; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.enhanced.dynamodb.AttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.AttributeConverterProvider; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.EnhancedTypeDocumentConfiguration; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.internal.AttributeConfiguration; import software.amazon.awssdk.enhanced.dynamodb.internal.immutable.ImmutableInfo; import software.amazon.awssdk.enhanced.dynamodb.internal.immutable.ImmutableIntrospector; import software.amazon.awssdk.enhanced.dynamodb.internal.immutable.ImmutablePropertyDescriptor; import software.amazon.awssdk.enhanced.dynamodb.internal.mapper.BeanAttributeGetter; import software.amazon.awssdk.enhanced.dynamodb.internal.mapper.BeanAttributeSetter; import software.amazon.awssdk.enhanced.dynamodb.internal.mapper.MetaTableSchema; import software.amazon.awssdk.enhanced.dynamodb.internal.mapper.MetaTableSchemaCache; import software.amazon.awssdk.enhanced.dynamodb.internal.mapper.ObjectConstructor; import software.amazon.awssdk.enhanced.dynamodb.internal.mapper.ObjectGetterMethod; import software.amazon.awssdk.enhanced.dynamodb.internal.mapper.StaticGetterMethod; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.BeanTableSchemaAttributeTag; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbAttribute; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbConvertedBy; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbFlatten; 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.DynamoDbPreserveEmptyObject; /** * Implementation of {@link TableSchema} that builds a table schema based on properties and annotations of an immutable * class with an associated builder class. Example: * <pre> * <code> * {@literal @}DynamoDbImmutable(builder = Customer.Builder.class) * public class Customer { * {@literal @}DynamoDbPartitionKey * public String accountId() { ... } * * {@literal @}DynamoDbSortKey * public int subId() { ... } * * // Defines a GSI (customers_by_name) with a partition key of 'name' * {@literal @}DynamoDbSecondaryPartitionKey(indexNames = "customers_by_name") * public String name() { ... } * * // Defines an LSI (customers_by_date) with a sort key of 'createdDate' and also declares the * // same attribute as a sort key for the GSI named 'customers_by_name' * {@literal @}DynamoDbSecondarySortKey(indexNames = {"customers_by_date", "customers_by_name"}) * public Instant createdDate() { ... } * * // Not required to be an inner-class, but builders often are * public static final class Builder { * public Builder accountId(String accountId) { ... }; * public Builder subId(int subId) { ... }; * public Builder name(String name) { ... }; * public Builder createdDate(Instant createdDate) { ... }; * * public Customer build() { ... }; * } * } * </pre> * * Creating an {@link ImmutableTableSchema} is a moderately expensive operation, and should be performed sparingly. This is * usually done once at application startup. * * If this table schema is not behaving as you expect, enable debug logging for 'software.amazon.awssdk.enhanced.dynamodb.beans'. * * @param <T> The type of object that this {@link TableSchema} maps to. */ @SdkPublicApi @ThreadSafe public final class ImmutableTableSchema<T> extends WrappedTableSchema<T, StaticImmutableTableSchema<T, ?>> { private static final String ATTRIBUTE_TAG_STATIC_SUPPLIER_NAME = "attributeTagFor"; private static final Map<Class<?>, ImmutableTableSchema<?>> IMMUTABLE_TABLE_SCHEMA_CACHE = Collections.synchronizedMap(new WeakHashMap<>()); private ImmutableTableSchema(StaticImmutableTableSchema<T, ?> wrappedTableSchema) { super(wrappedTableSchema); } /** * Scans an immutable class and builds an {@link ImmutableTableSchema} from it that can be used with the * {@link DynamoDbEnhancedClient}. * * Creating an {@link ImmutableTableSchema} is a moderately expensive operation, and should be performed sparingly. This is * usually done once at application startup. * * @param immutableClass The annotated immutable class to build the table schema from. * @param <T> The immutable class type. * @return An initialized {@link ImmutableTableSchema} */ @SuppressWarnings("unchecked") public static <T> ImmutableTableSchema<T> create(Class<T> immutableClass) { return (ImmutableTableSchema<T>) IMMUTABLE_TABLE_SCHEMA_CACHE.computeIfAbsent( immutableClass, clz -> create(clz, new MetaTableSchemaCache())); } private static <T> ImmutableTableSchema<T> create(Class<T> immutableClass, MetaTableSchemaCache metaTableSchemaCache) { debugLog(immutableClass, () -> "Creating immutable schema"); // Fetch or create a new reference to this yet-to-be-created TableSchema in the cache MetaTableSchema<T> metaTableSchema = metaTableSchemaCache.getOrCreate(immutableClass); ImmutableTableSchema<T> newTableSchema = new ImmutableTableSchema<>(createStaticImmutableTableSchema(immutableClass, metaTableSchemaCache)); metaTableSchema.initialize(newTableSchema); return newTableSchema; } // Called when creating an immutable TableSchema recursively. Utilizes the MetaTableSchema cache to stop infinite // recursion static <T> TableSchema<T> recursiveCreate(Class<T> immutableClass, MetaTableSchemaCache metaTableSchemaCache) { Optional<MetaTableSchema<T>> metaTableSchema = metaTableSchemaCache.get(immutableClass); // If we get a cache hit... if (metaTableSchema.isPresent()) { // Either: use the cached concrete TableSchema if we have one if (metaTableSchema.get().isInitialized()) { return metaTableSchema.get().concreteTableSchema(); } // Or: return the uninitialized MetaTableSchema as this must be a recursive reference and it will be // initialized later as the chain completes return metaTableSchema.get(); } // Otherwise: cache doesn't know about this class; create a new one from scratch return create(immutableClass, metaTableSchemaCache); } private static <T> StaticImmutableTableSchema<T, ?> createStaticImmutableTableSchema( Class<T> immutableClass, MetaTableSchemaCache metaTableSchemaCache) { ImmutableInfo<T> immutableInfo = ImmutableIntrospector.getImmutableInfo(immutableClass); Class<?> builderClass = immutableInfo.builderClass(); return createStaticImmutableTableSchema(immutableClass, builderClass, immutableInfo, metaTableSchemaCache); } private static <T, B> StaticImmutableTableSchema<T, B> createStaticImmutableTableSchema( Class<T> immutableClass, Class<B> builderClass, ImmutableInfo<T> immutableInfo, MetaTableSchemaCache metaTableSchemaCache) { Supplier<B> newBuilderSupplier = newObjectSupplier(immutableInfo, builderClass); Function<B, T> buildFunction = ObjectGetterMethod.create(builderClass, immutableInfo.buildMethod()); StaticImmutableTableSchema.Builder<T, B> builder = StaticImmutableTableSchema.builder(immutableClass, builderClass) .newItemBuilder(newBuilderSupplier, buildFunction); builder.attributeConverterProviders( createConverterProvidersFromAnnotation(immutableClass, immutableClass.getAnnotation(DynamoDbImmutable.class))); List<ImmutableAttribute<T, B, ?>> attributes = new ArrayList<>(); immutableInfo.propertyDescriptors() .forEach(propertyDescriptor -> { DynamoDbFlatten dynamoDbFlatten = getPropertyAnnotation(propertyDescriptor, DynamoDbFlatten.class); if (dynamoDbFlatten != null) { builder.flatten(TableSchema.fromClass(propertyDescriptor.getter().getReturnType()), getterForProperty(propertyDescriptor, immutableClass), setterForProperty(propertyDescriptor, builderClass)); } else { AttributeConfiguration beanAttributeConfiguration = resolveAttributeConfiguration(propertyDescriptor); ImmutableAttribute.Builder<T, B, ?> attributeBuilder = immutableAttributeBuilder(propertyDescriptor, immutableClass, builderClass, metaTableSchemaCache, beanAttributeConfiguration); Optional<AttributeConverter> attributeConverter = createAttributeConverterFromAnnotation(propertyDescriptor); attributeConverter.ifPresent(attributeBuilder::attributeConverter); addTagsToAttribute(attributeBuilder, propertyDescriptor); attributes.add(attributeBuilder.build()); } }); builder.attributes(attributes); return builder.build(); } private static List<AttributeConverterProvider> createConverterProvidersFromAnnotation(Class<?> immutableClass, DynamoDbImmutable dynamoDbImmutable) { Class<? extends AttributeConverterProvider>[] providerClasses = dynamoDbImmutable.converterProviders(); return Arrays.stream(providerClasses) .peek(c -> debugLog(immutableClass, () -> "Adding Converter: " + c.getTypeName())) .map(c -> (AttributeConverterProvider) newObjectSupplierForClass(c).get()) .collect(Collectors.toList()); } private static <T, B> ImmutableAttribute.Builder<T, B, ?> immutableAttributeBuilder( ImmutablePropertyDescriptor propertyDescriptor, Class<T> immutableClass, Class<B> builderClass, MetaTableSchemaCache metaTableSchemaCache, AttributeConfiguration beanAttributeConfiguration) { Type propertyType = propertyDescriptor.getter().getGenericReturnType(); EnhancedType<?> propertyTypeToken = convertTypeToEnhancedType(propertyType, metaTableSchemaCache, beanAttributeConfiguration); return ImmutableAttribute.builder(immutableClass, builderClass, propertyTypeToken) .name(attributeNameForProperty(propertyDescriptor)) .getter(getterForProperty(propertyDescriptor, immutableClass)) .setter(setterForProperty(propertyDescriptor, builderClass)); } /** * Converts a {@link Type} to an {@link EnhancedType}. Usually {@link EnhancedType#of} is capable of doing this all * by itself, but for the ImmutableTableSchema we want to detect if a parameterized class is being passed without a * converter that is actually another annotated class in which case we want to capture its schema and add it to the * EnhancedType. Unfortunately this means we have to duplicate some of the recursive Type parsing that * EnhancedClient otherwise does all by itself. */ @SuppressWarnings("unchecked") private static EnhancedType<?> convertTypeToEnhancedType(Type type, MetaTableSchemaCache metaTableSchemaCache, AttributeConfiguration attributeConfiguration) { Class<?> clazz = null; if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; Type rawType = parameterizedType.getRawType(); if (List.class.equals(rawType)) { EnhancedType<?> enhancedType = convertTypeToEnhancedType(parameterizedType.getActualTypeArguments()[0], metaTableSchemaCache, attributeConfiguration); return EnhancedType.listOf(enhancedType); } if (Map.class.equals(rawType)) { EnhancedType<?> enhancedType = convertTypeToEnhancedType(parameterizedType.getActualTypeArguments()[1], metaTableSchemaCache, attributeConfiguration); return EnhancedType.mapOf(EnhancedType.of(parameterizedType.getActualTypeArguments()[0]), enhancedType); } if (rawType instanceof Class) { clazz = (Class<?>) rawType; } } else if (type instanceof Class) { clazz = (Class<?>) type; } if (clazz != null) { Consumer<EnhancedTypeDocumentConfiguration.Builder> attrConfiguration = b -> b.preserveEmptyObject(attributeConfiguration.preserveEmptyObject()) .ignoreNulls(attributeConfiguration.ignoreNulls()); if (clazz.getAnnotation(DynamoDbImmutable.class) != null) { return EnhancedType.documentOf( (Class<Object>) clazz, (TableSchema<Object>) ImmutableTableSchema.recursiveCreate(clazz, metaTableSchemaCache), attrConfiguration); } else if (clazz.getAnnotation(DynamoDbBean.class) != null) { return EnhancedType.documentOf( (Class<Object>) clazz, (TableSchema<Object>) BeanTableSchema.recursiveCreate(clazz, metaTableSchemaCache), attrConfiguration); } } return EnhancedType.of(type); } private static Optional<AttributeConverter> createAttributeConverterFromAnnotation( ImmutablePropertyDescriptor propertyDescriptor) { DynamoDbConvertedBy attributeConverterBean = getPropertyAnnotation(propertyDescriptor, DynamoDbConvertedBy.class); Optional<Class<?>> optionalClass = Optional.ofNullable(attributeConverterBean) .map(DynamoDbConvertedBy::value); return optionalClass.map(clazz -> (AttributeConverter) newObjectSupplierForClass(clazz).get()); } /** * This method scans all the annotations on a property and looks for a meta-annotation of * {@link BeanTableSchemaAttributeTag}. If the meta-annotation is found, it attempts to create * an annotation tag based on a standard named static method * of the class that tag has been annotated with passing in the original property annotation as an argument. */ private static void addTagsToAttribute(ImmutableAttribute.Builder<?, ?, ?> attributeBuilder, ImmutablePropertyDescriptor propertyDescriptor) { propertyAnnotations(propertyDescriptor).forEach(annotation -> { BeanTableSchemaAttributeTag beanTableSchemaAttributeTag = annotation.annotationType().getAnnotation(BeanTableSchemaAttributeTag.class); if (beanTableSchemaAttributeTag != null) { Class<?> tagClass = beanTableSchemaAttributeTag.value(); Method tagMethod; try { tagMethod = tagClass.getDeclaredMethod(ATTRIBUTE_TAG_STATIC_SUPPLIER_NAME, annotation.annotationType()); } catch (NoSuchMethodException e) { throw new RuntimeException( String.format("Could not find a static method named '%s' on class '%s' that returns " + "an AttributeTag for annotation '%s'", ATTRIBUTE_TAG_STATIC_SUPPLIER_NAME, tagClass, annotation.annotationType()), e); } if (!Modifier.isStatic(tagMethod.getModifiers())) { throw new RuntimeException( String.format("Could not find a static method named '%s' on class '%s' that returns " + "an AttributeTag for annotation '%s'", ATTRIBUTE_TAG_STATIC_SUPPLIER_NAME, tagClass, annotation.annotationType())); } StaticAttributeTag staticAttributeTag; try { staticAttributeTag = (StaticAttributeTag) tagMethod.invoke(null, annotation); } catch (IllegalAccessException | InvocationTargetException e) { throw new RuntimeException( String.format("Could not invoke method to create AttributeTag for annotation '%s' on class " + "'%s'.", annotation.annotationType(), tagClass), e); } attributeBuilder.addTag(staticAttributeTag); } }); } private static <T, R> Supplier<R> newObjectSupplier(ImmutableInfo<T> immutableInfo, Class<R> builderClass) { if (immutableInfo.staticBuilderMethod().isPresent()) { return StaticGetterMethod.create(immutableInfo.staticBuilderMethod().get()); } return newObjectSupplierForClass(builderClass); } private static <R> Supplier<R> newObjectSupplierForClass(Class<R> clazz) { try { Constructor<R> constructor = clazz.getConstructor(); debugLog(clazz, () -> "Constructor: " + constructor); return ObjectConstructor.create(clazz, constructor); } catch (NoSuchMethodException e) { throw new IllegalArgumentException( String.format("Builder class '%s' appears to have no default constructor thus cannot be used with " + "the ImmutableTableSchema", clazz), e); } } private static <T, R> Function<T, R> getterForProperty(ImmutablePropertyDescriptor propertyDescriptor, Class<T> immutableClass) { Method readMethod = propertyDescriptor.getter(); debugLog(immutableClass, () -> "Property " + propertyDescriptor.name() + " read method: " + readMethod); return BeanAttributeGetter.create(immutableClass, readMethod); } private static <T, R> BiConsumer<T, R> setterForProperty(ImmutablePropertyDescriptor propertyDescriptor, Class<T> builderClass) { Method writeMethod = propertyDescriptor.setter(); debugLog(builderClass, () -> "Property " + propertyDescriptor.name() + " write method: " + writeMethod); return BeanAttributeSetter.create(builderClass, writeMethod); } private static String attributeNameForProperty(ImmutablePropertyDescriptor propertyDescriptor) { DynamoDbAttribute dynamoDbAttribute = getPropertyAnnotation(propertyDescriptor, DynamoDbAttribute.class); if (dynamoDbAttribute != null) { return dynamoDbAttribute.value(); } return propertyDescriptor.name(); } private static <R extends Annotation> R getPropertyAnnotation(ImmutablePropertyDescriptor propertyDescriptor, Class<R> annotationType) { R getterAnnotation = propertyDescriptor.getter().getAnnotation(annotationType); R setterAnnotation = propertyDescriptor.setter().getAnnotation(annotationType); if (getterAnnotation != null) { return getterAnnotation; } return setterAnnotation; } private static List<? extends Annotation> propertyAnnotations(ImmutablePropertyDescriptor propertyDescriptor) { return Stream.concat(Arrays.stream(propertyDescriptor.getter().getAnnotations()), Arrays.stream(propertyDescriptor.setter().getAnnotations())) .collect(Collectors.toList()); } private static AttributeConfiguration resolveAttributeConfiguration(ImmutablePropertyDescriptor propertyDescriptor) { boolean shouldPreserveEmptyObject = getPropertyAnnotation(propertyDescriptor, DynamoDbPreserveEmptyObject.class) != null; boolean ignoreNulls = getPropertyAnnotation(propertyDescriptor, DynamoDbIgnoreNulls.class) != null; return AttributeConfiguration.builder() .preserveEmptyObject(shouldPreserveEmptyObject) .ignoreNulls(ignoreNulls) .build(); } private static void debugLog(Class<?> beanClass, Supplier<String> logMessage) { BEAN_LOGGER.debug(() -> beanClass.getTypeName() + " - " + logMessage.get()); } }
4,386
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper/ImmutableAttribute.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 java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.function.BiConsumer; import java.util.function.Function; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; 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.utils.Validate; /** * A class that represents an attribute on an mapped immutable item. A {@link StaticImmutableTableSchema} composes * multiple attributes that map to a common immutable item class. * <p> * The recommended way to use this class is by calling * {@link software.amazon.awssdk.enhanced.dynamodb.TableSchema#builder(Class, Class)}. * Example: * {@code * TableSchema.builder(Customer.class, Customer.Builder.class) * .addAttribute(String.class, * a -> a.name("customer_name").getter(Customer::name).setter(Customer.Builder::name)) * // ... * .build(); * } * <p> * It's also possible to construct this class on its own using the static builder. Example: * {@code * ImmutableAttribute<Customer, Customer.Builder, ?> customerNameAttribute = * ImmutableAttribute.builder(Customer.class, Customer.Builder.class, String.class) * .name("customer_name") * .getter(Customer::name) * .setter(Customer.Builder::name) * .build(); * } * @param <T> the class of the immutable item this attribute maps into. * @param <B> the class of the builder for the immutable item this attribute maps into. * @param <R> the class that the value of this attribute converts to. */ @SdkPublicApi @ThreadSafe public final class ImmutableAttribute<T, B, R> { private final String name; private final Function<T, R> getter; private final BiConsumer<B, R> setter; private final Collection<StaticAttributeTag> tags; private final EnhancedType<R> type; private final AttributeConverter<R> attributeConverter; private ImmutableAttribute(Builder<T, B, R> builder) { this.name = Validate.paramNotNull(builder.name, "name"); this.getter = Validate.paramNotNull(builder.getter, "getter"); this.setter = Validate.paramNotNull(builder.setter, "setter"); this.tags = builder.tags == null ? Collections.emptyList() : Collections.unmodifiableCollection(builder.tags); this.type = Validate.paramNotNull(builder.type, "type"); this.attributeConverter = builder.attributeConverter; } /** * Constructs a new builder for this class using supplied types. * @param itemClass The class of the immutable item that this attribute composes. * @param builderClass The class of the builder for the immutable item that this attribute composes. * @param attributeType A {@link EnhancedType} that represents the type of the value this attribute stores. * @return A new typed builder for an attribute. */ public static <T, B, R> Builder<T, B, R> builder(Class<T> itemClass, Class<B> builderClass, EnhancedType<R> attributeType) { return new Builder<>(attributeType); } /** * Constructs a new builder for this class using supplied types. * @param itemType The {@link EnhancedType} of the immutable item that this attribute composes. * @param builderType The {@link EnhancedType} of the builder for the immutable item that this attribute composes. * @param attributeType A {@link EnhancedType} that represents the type of the value this attribute stores. * @return A new typed builder for an attribute. */ public static <T, B, R> Builder<T, B, R> builder(EnhancedType<T> itemType, EnhancedType<B> builderType, EnhancedType<R> attributeType) { return new Builder<>(attributeType); } /** * Constructs a new builder for this class using supplied types. * @param itemClass The class of the item that this attribute composes. * @param builderClass The class of the builder for the immutable item that this attribute composes. * @param attributeClass A class that represents the type of the value this attribute stores. * @return A new typed builder for an attribute. */ public static <T, B, R> Builder<T, B, R> builder(Class<T> itemClass, Class<B> builderClass, Class<R> attributeClass) { return new Builder<>(EnhancedType.of(attributeClass)); } /** * The name of this attribute */ public String name() { return this.name; } /** * A function that can get the value of this attribute from a modelled immutable item it composes. */ public Function<T, R> getter() { return this.getter; } /** * A function that can set the value of this attribute on a builder for the immutable modelled item it composes. */ public BiConsumer<B, R> setter() { return this.setter; } /** * A collection of {@link StaticAttributeTag} associated with this attribute. */ public Collection<StaticAttributeTag> tags() { return this.tags; } /** * A {@link EnhancedType} that represents the type of the value this attribute stores. */ public EnhancedType<R> type() { return this.type; } /** * A custom {@link AttributeConverter} that will be used to convert this attribute. * If no custom converter was provided, the value will be null. * @see Builder#attributeConverter */ public AttributeConverter<R> attributeConverter() { return this.attributeConverter; } /** * Converts an instance of this class to a {@link Builder} that can be used to modify and reconstruct it. */ public Builder<T, B, R> toBuilder() { return new Builder<T, B, R>(this.type).name(this.name) .getter(this.getter) .setter(this.setter) .tags(this.tags) .attributeConverter(this.attributeConverter); } ResolvedImmutableAttribute<T, B> resolve(AttributeConverterProvider attributeConverterProvider) { return ResolvedImmutableAttribute.create(this, converterFrom(attributeConverterProvider)); } private AttributeConverter<R> converterFrom(AttributeConverterProvider attributeConverterProvider) { return (attributeConverter != null) ? attributeConverter : attributeConverterProvider.converterFor(type); } /** * A typed builder for {@link ImmutableAttribute}. * @param <T> the class of the item this attribute maps into. * @param <R> the class that the value of this attribute converts to. */ @NotThreadSafe public static final class Builder<T, B, R> { private final EnhancedType<R> type; private String name; private Function<T, R> getter; private BiConsumer<B, R> setter; private List<StaticAttributeTag> tags; private AttributeConverter<R> attributeConverter; private Builder(EnhancedType<R> type) { this.type = type; } /** * The name of this attribute */ public Builder<T, B, R> name(String name) { this.name = name; return this; } /** * A function that can get the value of this attribute from a modelled item it composes. */ public Builder<T, B, R> getter(Function<T, R> getter) { this.getter = getter; return this; } /** * A function that can set the value of this attribute on a modelled item it composes. */ public Builder<T, B, R> setter(BiConsumer<B, R> setter) { this.setter = setter; return this; } /** * A collection of {@link StaticAttributeTag} associated with this attribute. Overwrites any existing tags. */ public Builder<T, B, R> tags(Collection<StaticAttributeTag> tags) { this.tags = new ArrayList<>(tags); return this; } /** * A collection of {@link StaticAttributeTag} associated with this attribute. Overwrites any existing tags. */ public Builder<T, B, R> tags(StaticAttributeTag... tags) { this.tags = Arrays.asList(tags); return this; } /** * Associates a single {@link StaticAttributeTag} with this attribute. Adds to any existing tags. */ public Builder<T, B, R> addTag(StaticAttributeTag tag) { if (this.tags == null) { this.tags = new ArrayList<>(); } this.tags.add(tag); return this; } /** * An {@link AttributeConverter} for the attribute type ({@link EnhancedType}), that can convert this attribute. * It takes precedence over any converter for this type provided by the table schema * {@link AttributeConverterProvider}. */ public Builder<T, B, R> attributeConverter(AttributeConverter<R> attributeConverter) { this.attributeConverter = attributeConverter; return this; } /** * Builds a {@link StaticAttributeTag} from the values stored in this builder. */ public ImmutableAttribute<T, B, R> build() { return new ImmutableAttribute<>(this); } } }
4,387
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper/StaticTableSchema.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 java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.enhanced.dynamodb.AttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.AttributeConverterProvider; import software.amazon.awssdk.enhanced.dynamodb.DefaultAttributeConverterProvider; import software.amazon.awssdk.enhanced.dynamodb.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; /** * Implementation of {@link TableSchema} that builds a schema based on directly declared attributes and methods to * get and set those attributes. Just like {@link StaticImmutableTableSchema} which is the equivalent implementation for * immutable objects, this is the most direct, and thus fastest, implementation of {@link TableSchema}. * <p> * Example using a fictional 'Customer' data item class:- * <pre>{@code * static final TableSchema<Customer> CUSTOMER_TABLE_SCHEMA = * StaticTableSchema.builder(Customer.class) * .newItemSupplier(Customer::new) * .addAttribute(String.class, a -> a.name("account_id") * .getter(Customer::getAccountId) * .setter(Customer::setAccountId) * .tags(primaryPartitionKey())) * .addAttribute(Integer.class, a -> a.name("sub_id") * .getter(Customer::getSubId) * .setter(Customer::setSubId) * .tags(primarySortKey())) * .addAttribute(String.class, a -> a.name("name") * .getter(Customer::getName) * .setter(Customer::setName) * .tags(secondaryPartitionKey("customers_by_name"))) * .addAttribute(Instant.class, a -> a.name("created_date") * .getter(Customer::getCreatedDate) * .setter(Customer::setCreatedDate) * .tags(secondarySortKey("customers_by_date"), * secondarySortKey("customers_by_name"))) * .build(); * }</pre> */ @SdkPublicApi @ThreadSafe public final class StaticTableSchema<T> extends WrappedTableSchema<T, StaticImmutableTableSchema<T, T>> { private StaticTableSchema(Builder<T> builder) { super(builder.delegateBuilder.build()); } /** * Creates a builder for a {@link StaticTableSchema} typed to specific data item class. * @param itemClass The data item class object that the {@link StaticTableSchema} is to map to. * @return A newly initialized builder */ public static <T> Builder<T> builder(Class<T> itemClass) { return new Builder<>(EnhancedType.of(itemClass)); } /** * Creates a builder for a {@link StaticTableSchema} typed to specific data item class. * @param itemType The {@link EnhancedType} of the data item class object that the {@link StaticTableSchema} is to map to. * @return A newly initialized builder */ public static <T> Builder<T> builder(EnhancedType<T> itemType) { return new Builder<>(itemType); } /** * Builder for a {@link StaticTableSchema} * @param <T> The data item type that the {@link StaticTableSchema} this builder will build is to map to. */ @NotThreadSafe public static final class Builder<T> { private final StaticImmutableTableSchema.Builder<T, T> delegateBuilder; private final EnhancedType<T> itemType; private Builder(EnhancedType<T> itemType) { this.delegateBuilder = StaticImmutableTableSchema.builder(itemType, itemType); this.itemType = itemType; } /** * A function that can be used to create new instances of the data item class. */ public Builder<T> newItemSupplier(Supplier<T> newItemSupplier) { this.delegateBuilder.newItemBuilder(newItemSupplier, Function.identity()); return this; } /** * A list of attributes that can be mapped between the data item object and the database record that are to * be associated with the schema. Will overwrite any existing attributes. */ @SafeVarargs public final Builder<T> attributes(StaticAttribute<T, ?>... staticAttributes) { this.delegateBuilder.attributes(Arrays.stream(staticAttributes) .map(StaticAttribute::toImmutableAttribute) .collect(Collectors.toList())); return this; } /** * A list of attributes that can be mapped between the data item object and the database record that are to * be associated with the schema. Will overwrite any existing attributes. */ public Builder<T> attributes(Collection<StaticAttribute<T, ?>> staticAttributes) { this.delegateBuilder.attributes(staticAttributes.stream() .map(StaticAttribute::toImmutableAttribute) .collect(Collectors.toList())); return this; } /** * Adds a single attribute to the table schema that can be mapped between the data item object and the database * record. */ public <R> Builder<T> addAttribute(EnhancedType<R> attributeType, Consumer<StaticAttribute.Builder<T, R>> staticAttribute) { StaticAttribute.Builder<T, R> builder = StaticAttribute.builder(itemType, attributeType); staticAttribute.accept(builder); this.delegateBuilder.addAttribute(builder.build().toImmutableAttribute()); return this; } /** * Adds a single attribute to the table schema that can be mapped between the data item object and the database * record. */ public <R> Builder<T> addAttribute(Class<R> attributeClass, Consumer<StaticAttribute.Builder<T, R>> staticAttribute) { StaticAttribute.Builder<T, R> builder = StaticAttribute.builder(itemType, EnhancedType.of(attributeClass)); staticAttribute.accept(builder); this.delegateBuilder.addAttribute(builder.build().toImmutableAttribute()); return this; } /** * Adds a single attribute to the table schema that can be mapped between the data item object and the database * record. */ public Builder<T> addAttribute(StaticAttribute<T, ?> staticAttribute) { this.delegateBuilder.addAttribute(staticAttribute.toImmutableAttribute()); return this; } /** * Flattens all the attributes defined in another {@link StaticTableSchema} into the database record this schema * maps to. Functions to get and set an object that the flattened schema maps to is required. */ public <R> Builder<T> flatten(TableSchema<R> otherTableSchema, Function<T, R> otherItemGetter, BiConsumer<T, R> otherItemSetter) { this.delegateBuilder.flatten(otherTableSchema, otherItemGetter, otherItemSetter); return this; } /** * Extends the {@link StaticTableSchema} of a super-class, effectively rolling all the attributes modelled by * the super-class into the {@link StaticTableSchema} of the sub-class. */ public Builder<T> extend(StaticTableSchema<? super T> superTableSchema) { this.delegateBuilder.extend(superTableSchema.toImmutableTableSchema()); return this; } /** * Associate one or more {@link StaticTableTag} with this schema. See documentation on the tags themselves to * understand what each one does. This method will overwrite any existing table tags. */ public Builder<T> tags(StaticTableTag... staticTableTags) { this.delegateBuilder.tags(staticTableTags); return this; } /** * Associate one or more {@link StaticTableTag} with this schema. See documentation on the tags themselves to * understand what each one does. This method will overwrite any existing table tags. */ public Builder<T> tags(Collection<StaticTableTag> staticTableTags) { this.delegateBuilder.tags(staticTableTags); return this; } /** * Associates a {@link StaticTableTag} with this schema. See documentation on the tags themselves to understand * what each one does. This method will add the tag to the list of existing table tags. */ public Builder<T> addTag(StaticTableTag staticTableTag) { this.delegateBuilder.addTag(staticTableTag); return this; } /** * Specifies the {@link AttributeConverterProvider}s to use with the table schema. * The list of attribute converter providers must provide {@link AttributeConverter}s for all types used * in the schema. The attribute converter providers will be loaded in the strict order they are supplied here. * <p> * Calling this method will override the default attribute converter provider * {@link DefaultAttributeConverterProvider}, which provides standard converters for most primitive * and common Java types, so that provider must included in the supplied list if it is to be * used. Providing an empty list here will cause no providers to get loaded. * <p> * Adding one custom attribute converter provider and using the default as fallback: * {@code * builder.attributeConverterProviders(customAttributeConverter, AttributeConverterProvider.defaultProvider()) * } * * @param attributeConverterProviders a list of attribute converter providers to use with the table schema */ public Builder<T> attributeConverterProviders(AttributeConverterProvider... attributeConverterProviders) { this.delegateBuilder.attributeConverterProviders(attributeConverterProviders); return this; } /** * Specifies the {@link AttributeConverterProvider}s to use with the table schema. * The list of attribute converter providers must provide {@link AttributeConverter}s for all types used * in the schema. The attribute converter providers will be loaded in the strict order they are supplied here. * <p> * Calling this method will override the default attribute converter provider * {@link DefaultAttributeConverterProvider}, which provides standard converters * for most primitive and common Java types, so that provider must included in the supplied list if it is to be * used. Providing an empty list here will cause no providers to get loaded. * <p> * Adding one custom attribute converter provider and using the default as fallback: * {@code * List<AttributeConverterProvider> providers = new ArrayList<>( * customAttributeConverter, * AttributeConverterProvider.defaultProvider()); * builder.attributeConverterProviders(providers); * } * * @param attributeConverterProviders a list of attribute converter providers to use with the table schema */ public Builder<T> attributeConverterProviders(List<AttributeConverterProvider> attributeConverterProviders) { this.delegateBuilder.attributeConverterProviders(attributeConverterProviders); return this; } /** * Builds a {@link StaticTableSchema} based on the values this builder has been configured with */ public StaticTableSchema<T> build() { return new StaticTableSchema<>(this); } } private StaticImmutableTableSchema<T, T> toImmutableTableSchema() { return delegateTableSchema(); } /** * The table schema {@link AttributeConverterProvider}. * @see Builder#attributeConverterProvider */ public AttributeConverterProvider attributeConverterProvider() { return delegateTableSchema().attributeConverterProvider(); } }
4,388
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper/StaticTableTag.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 java.util.function.Consumer; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; /** * Interface for a tag that can be applied to any {@link StaticTableSchema}. When the table schema is instantiated, * the table metadata stored on the schema will be updated by calling the {@link #modifyMetadata()} method for every tag * associated with the table. */ @SdkPublicApi @ThreadSafe public interface StaticTableTag { /** * A function that modifies an existing {@link StaticTableSchema.Builder} when this tag is applied to a table. This * will be used by the {@link StaticTableSchema} to capture all the metadata associated with tags that have been * applied to the table. * * @return a consumer that modifies an existing {@link StaticTableSchema.Builder}. */ Consumer<StaticTableMetadata.Builder> modifyMetadata(); }
4,389
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper/StaticTableMetadata.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 java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType; import software.amazon.awssdk.enhanced.dynamodb.IndexMetadata; import software.amazon.awssdk.enhanced.dynamodb.KeyAttributeMetadata; import software.amazon.awssdk.enhanced.dynamodb.TableMetadata; import software.amazon.awssdk.enhanced.dynamodb.internal.mapper.StaticIndexMetadata; import software.amazon.awssdk.enhanced.dynamodb.internal.mapper.StaticKeyAttributeMetadata; import software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType; /** * Implementation of {@link TableMetadata} that can be constructed directly using literal values for metadata objects. * This implementation is used by {@link StaticTableSchema} and associated interfaces such as {@link StaticAttributeTag} * and {@link StaticTableTag} which permit manipulation of the table metadata. */ @SdkPublicApi @ThreadSafe public final class StaticTableMetadata implements TableMetadata { private final Map<String, Object> customMetadata; private final Map<String, IndexMetadata> indexByNameMap; private final Map<String, KeyAttributeMetadata> keyAttributes; private StaticTableMetadata(Builder builder) { this.customMetadata = Collections.unmodifiableMap(builder.customMetadata); this.indexByNameMap = Collections.unmodifiableMap(builder.indexByNameMap); this.keyAttributes = Collections.unmodifiableMap(builder.keyAttributes); } /** * Create a new builder for this class * @return A newly initialized {@link Builder} for building a {@link StaticTableMetadata} object. */ public static Builder builder() { return new Builder(); } @Override public <T> Optional<T> customMetadataObject(String key, Class<? extends T> objectClass) { Object genericObject = customMetadata.get(key); if (genericObject == null) { return Optional.empty(); } if (!objectClass.isAssignableFrom(genericObject.getClass())) { throw new IllegalArgumentException("Attempt to retrieve a custom metadata object as a type that is not " + "assignable for that object. Custom metadata key: " + key + "; " + "requested object class: " + objectClass.getCanonicalName() + "; " + "found object class: " + genericObject.getClass().getCanonicalName()); } return Optional.of(objectClass.cast(genericObject)); } @Override public String indexPartitionKey(String indexName) { IndexMetadata index = getIndex(indexName); if (!index.partitionKey().isPresent()) { if (!TableMetadata.primaryIndexName().equals(indexName) && index.sortKey().isPresent()) { // Local secondary index, use primary partition key return primaryPartitionKey(); } throw new IllegalArgumentException("Attempt to execute an operation against an index that requires a " + "partition key without assigning a partition key to that index. " + "Index name: " + indexName); } return index.partitionKey().get().name(); } @Override public Optional<String> indexSortKey(String indexName) { IndexMetadata index = getIndex(indexName); return index.sortKey().map(KeyAttributeMetadata::name); } @Override public Collection<String> indexKeys(String indexName) { IndexMetadata index = getIndex(indexName); if (index.sortKey().isPresent()) { if (!TableMetadata.primaryIndexName().equals(indexName) && !index.partitionKey().isPresent()) { // Local secondary index, use primary index for partition key return Collections.unmodifiableList(Arrays.asList(primaryPartitionKey(), index.sortKey().get().name())); } return Collections.unmodifiableList(Arrays.asList(index.partitionKey().get().name(), index.sortKey().get().name())); } else { return Collections.singletonList(index.partitionKey().get().name()); } } @Override public Collection<String> allKeys() { return this.keyAttributes.keySet(); } @Override public Collection<IndexMetadata> indices() { return indexByNameMap.values(); } @Override public Map<String, Object> customMetadata() { return this.customMetadata; } @Override public Collection<KeyAttributeMetadata> keyAttributes() { return this.keyAttributes.values(); } private IndexMetadata getIndex(String indexName) { IndexMetadata index = indexByNameMap.get(indexName); if (index == null) { if (TableMetadata.primaryIndexName().equals(indexName)) { throw new IllegalArgumentException("Attempt to execute an operation that requires a primary index " + "without defining any primary key attributes in the table " + "metadata."); } else { throw new IllegalArgumentException("Attempt to execute an operation that requires a secondary index " + "without defining the index attributes in the table metadata. " + "Index name: " + indexName); } } return index; } @Override public Optional<ScalarAttributeType> scalarAttributeType(String keyAttribute) { KeyAttributeMetadata key = this.keyAttributes.get(keyAttribute); if (key == null) { throw new IllegalArgumentException("Key attribute '" + keyAttribute + "' not found in table metadata."); } return Optional.ofNullable(key.attributeValueType().scalarAttributeType()); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } StaticTableMetadata that = (StaticTableMetadata) o; if (customMetadata != null ? ! customMetadata.equals(that.customMetadata) : that.customMetadata != null) { return false; } if (indexByNameMap != null ? ! indexByNameMap.equals(that.indexByNameMap) : that.indexByNameMap != null) { return false; } return keyAttributes != null ? keyAttributes.equals(that.keyAttributes) : that.keyAttributes == null; } @Override public int hashCode() { int result = customMetadata != null ? customMetadata.hashCode() : 0; result = 31 * result + (indexByNameMap != null ? indexByNameMap.hashCode() : 0); result = 31 * result + (keyAttributes != null ? keyAttributes.hashCode() : 0); return result; } /** * Builder for {@link StaticTableMetadata} */ @NotThreadSafe public static class Builder { private final Map<String, Object> customMetadata = new LinkedHashMap<>(); private final Map<String, IndexMetadata> indexByNameMap = new LinkedHashMap<>(); private final Map<String, KeyAttributeMetadata> keyAttributes = new LinkedHashMap<>(); private Builder() { } /** * Builds an immutable instance of {@link StaticTableMetadata} from the values supplied to the builder. */ public StaticTableMetadata build() { return new StaticTableMetadata(this); } /** * Adds a single custom object to the metadata, keyed by a string. Attempting to add a metadata object with a * key that matches one that has already been added will cause an exception to be thrown. * @param key a string key that will be used to retrieve the custom metadata * @param object an object that will be stored in the custom metadata map * @throws IllegalArgumentException if the custom metadata map already contains an entry with the same key */ public Builder addCustomMetadataObject(String key, Object object) { if (customMetadata.containsKey(key)) { throw new IllegalArgumentException("Attempt to set a custom metadata object that has already been set. " + "Custom metadata object key: " + key); } customMetadata.put(key, object); return this; } /** * Adds collection of custom objects to the custom metadata, keyed by a string. * If a collection is already present then it will append the newly added collection to the existing collection. * * @param key a string key that will be used to retrieve the custom metadata * @param objects Collection of objects that will be stored in the custom metadata map */ public Builder addCustomMetadataObject(String key, Collection<Object> objects) { Object collectionInMetadata = customMetadata.get(key); Object customObjectToPut = collectionInMetadata != null ? Stream.concat(((Collection<Object>) collectionInMetadata).stream(), objects.stream()).collect(Collectors.toSet()) : objects; customMetadata.put(key, customObjectToPut); return this; } /** * Adds map of custom objects to the custom metadata, keyed by a string. * If a map is already present then it will merge the new map with the existing map. * * @param key a string key that will be used to retrieve the custom metadata * @param objectMap Map of objects that will be stored in the custom metadata map */ public Builder addCustomMetadataObject(String key, Map<Object, Object> objectMap) { Object collectionInMetadata = customMetadata.get(key); Object customObjectToPut = collectionInMetadata != null ? Stream.concat(((Map<Object, Object>) collectionInMetadata).entrySet().stream(), objectMap.entrySet().stream()) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)) : objectMap; customMetadata.put(key, customObjectToPut); return this; } /** * Adds information about a partition key associated with a specific index. * @param indexName the name of the index to associate the partition key with * @param attributeName the name of the attribute that represents the partition key * @param attributeValueType the {@link AttributeValueType} of the partition key * @throws IllegalArgumentException if a partition key has already been defined for this index */ public Builder addIndexPartitionKey(String indexName, String attributeName, AttributeValueType attributeValueType) { IndexMetadata index = indexByNameMap.get(indexName); if (index != null && index.partitionKey().isPresent()) { throw new IllegalArgumentException("Attempt to set an index partition key that conflicts with an " + "existing index partition key of the same name and index. Index " + "name: " + indexName + "; attribute name: " + attributeName); } KeyAttributeMetadata partitionKey = StaticKeyAttributeMetadata.create(attributeName, attributeValueType); indexByNameMap.put(indexName, StaticIndexMetadata.builderFrom(index).name(indexName).partitionKey(partitionKey).build()); markAttributeAsKey(attributeName, attributeValueType); return this; } /** * Adds information about a sort key associated with a specific index. * @param indexName the name of the index to associate the sort key with * @param attributeName the name of the attribute that represents the sort key * @param attributeValueType the {@link AttributeValueType} of the sort key * @throws IllegalArgumentException if a sort key has already been defined for this index */ public Builder addIndexSortKey(String indexName, String attributeName, AttributeValueType attributeValueType) { IndexMetadata index = indexByNameMap.get(indexName); if (index != null && index.sortKey().isPresent()) { throw new IllegalArgumentException("Attempt to set an index sort key that conflicts with an existing" + " index sort key of the same name and index. Index name: " + indexName + "; attribute name: " + attributeName); } KeyAttributeMetadata sortKey = StaticKeyAttributeMetadata.create(attributeName, attributeValueType); indexByNameMap.put(indexName, StaticIndexMetadata.builderFrom(index).name(indexName).sortKey(sortKey).build()); markAttributeAsKey(attributeName, attributeValueType); return this; } /** * Declares a 'key-like' attribute that is not an actual DynamoDB key. These pseudo-keys can then be recognized * by extensions and treated appropriately, often being protected from manipulations as those would alter the * meaning of the record. One example usage of this is a 'versioned record attribute': although the version is * not part of the primary key of the record, it effectively serves as such. * @param attributeName the name of the attribute to mark as a pseudo-key * @param attributeValueType the {@link AttributeValueType} of the pseudo-key */ public Builder markAttributeAsKey(String attributeName, AttributeValueType attributeValueType) { KeyAttributeMetadata existing = keyAttributes.get(attributeName); if (existing != null && existing.attributeValueType() != attributeValueType) { throw new IllegalArgumentException("Attempt to mark an attribute as a key with a different " + "AttributeValueType than one that has already been recorded."); } if (existing == null) { keyAttributes.put(attributeName, StaticKeyAttributeMetadata.create(attributeName, attributeValueType)); } return this; } /** * Package-private method to merge the contents of a constructed {@link TableMetadata} into this builder. */ Builder mergeWith(TableMetadata other) { other.indices().forEach( index -> { index.partitionKey().ifPresent( partitionKey -> addIndexPartitionKey(index.name(), partitionKey.name(), partitionKey.attributeValueType())); index.sortKey().ifPresent( sortKey -> addIndexSortKey(index.name(), sortKey.name(), sortKey.attributeValueType()) ); }); other.customMetadata().forEach(this::mergeCustomMetaDataObject); other.keyAttributes().forEach(keyAttribute -> markAttributeAsKey(keyAttribute.name(), keyAttribute.attributeValueType())); return this; } private void mergeCustomMetaDataObject(String key, Object object) { if (object instanceof Collection) { this.addCustomMetadataObject(key, (Collection<Object>) object); } else if (object instanceof Map) { this.addCustomMetadataObject(key, (Map<Object, Object>) object); } else { this.addCustomMetadataObject(key, object); } } } }
4,390
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper/BeanTableSchema.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 software.amazon.awssdk.enhanced.dynamodb.internal.DynamoDbEnhancedLogger.BEAN_LOGGER; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.beans.Transient; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.WeakHashMap; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.enhanced.dynamodb.AttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.AttributeConverterProvider; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.EnhancedTypeDocumentConfiguration; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.internal.AttributeConfiguration; import software.amazon.awssdk.enhanced.dynamodb.internal.mapper.BeanAttributeGetter; import software.amazon.awssdk.enhanced.dynamodb.internal.mapper.BeanAttributeSetter; import software.amazon.awssdk.enhanced.dynamodb.internal.mapper.MetaTableSchema; import software.amazon.awssdk.enhanced.dynamodb.internal.mapper.MetaTableSchemaCache; import software.amazon.awssdk.enhanced.dynamodb.internal.mapper.ObjectConstructor; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.BeanTableSchemaAttributeTag; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbAttribute; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbConvertedBy; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbFlatten; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbIgnore; 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.DynamoDbPreserveEmptyObject; /** * Implementation of {@link TableSchema} that builds a table schema based on properties and annotations of a bean * class. Example: * <pre> * <code> * {@literal @}DynamoDbBean * public class Customer { * private String accountId; * private int subId; // primitive types are supported * private String name; * private Instant createdDate; * * {@literal @}DynamoDbPartitionKey * public String getAccountId() { return this.accountId; } * public void setAccountId(String accountId) { this.accountId = accountId; } * * {@literal @}DynamoDbSortKey * public int getSubId() { return this.subId; } * public void setSubId(int subId) { this.subId = subId; } * * // Defines a GSI (customers_by_name) with a partition key of 'name' * {@literal @}DynamoDbSecondaryPartitionKey(indexNames = "customers_by_name") * public String getName() { return this.name; } * public void setName(String name) { this.name = name; } * * // Defines an LSI (customers_by_date) with a sort key of 'createdDate' and also declares the * // same attribute as a sort key for the GSI named 'customers_by_name' * {@literal @}DynamoDbSecondarySortKey(indexNames = {"customers_by_date", "customers_by_name"}) * public Instant getCreatedDate() { return this.createdDate; } * public void setCreatedDate(Instant createdDate) { this.createdDate = createdDate; } * } * * </pre> * * Creating an {@link BeanTableSchema} is a moderately expensive operation, and should be performed sparingly. This is * usually done once at application startup. * * If this table schema is not behaving as you expect, enable debug logging for 'software.amazon.awssdk.enhanced.dynamodb.beans'. * * @param <T> The type of object that this {@link TableSchema} maps to. */ @SdkPublicApi @ThreadSafe public final class BeanTableSchema<T> extends WrappedTableSchema<T, StaticTableSchema<T>> { private static final Map<Class<?>, BeanTableSchema<?>> BEAN_TABLE_SCHEMA_CACHE = Collections.synchronizedMap(new WeakHashMap<>()); private static final String ATTRIBUTE_TAG_STATIC_SUPPLIER_NAME = "attributeTagFor"; private BeanTableSchema(StaticTableSchema<T> staticTableSchema) { super(staticTableSchema); } /** * Scans a bean class and builds a {@link BeanTableSchema} from it that can be used with the * {@link DynamoDbEnhancedClient}. * * <p> * It's recommended to only create a {@link BeanTableSchema} once for a single bean class, usually at application start up, * because it's a moderately expensive operation. * * @param beanClass The bean class to build the table schema from. * @param <T> The bean class type. * @return An initialized {@link BeanTableSchema} */ @SuppressWarnings("unchecked") public static <T> BeanTableSchema<T> create(Class<T> beanClass) { return (BeanTableSchema<T>) BEAN_TABLE_SCHEMA_CACHE.computeIfAbsent(beanClass, clz -> create(clz, new MetaTableSchemaCache())); } private static <T> BeanTableSchema<T> create(Class<T> beanClass, MetaTableSchemaCache metaTableSchemaCache) { debugLog(beanClass, () -> "Creating bean schema"); // Fetch or create a new reference to this yet-to-be-created TableSchema in the cache MetaTableSchema<T> metaTableSchema = metaTableSchemaCache.getOrCreate(beanClass); BeanTableSchema<T> newTableSchema = new BeanTableSchema<>(createStaticTableSchema(beanClass, metaTableSchemaCache)); metaTableSchema.initialize(newTableSchema); return newTableSchema; } // Called when creating an immutable TableSchema recursively. Utilizes the MetaTableSchema cache to stop infinite // recursion static <T> TableSchema<T> recursiveCreate(Class<T> beanClass, MetaTableSchemaCache metaTableSchemaCache) { Optional<MetaTableSchema<T>> metaTableSchema = metaTableSchemaCache.get(beanClass); // If we get a cache hit... if (metaTableSchema.isPresent()) { // Either: use the cached concrete TableSchema if we have one if (metaTableSchema.get().isInitialized()) { return metaTableSchema.get().concreteTableSchema(); } // Or: return the uninitialized MetaTableSchema as this must be a recursive reference and it will be // initialized later as the chain completes return metaTableSchema.get(); } // Otherwise: cache doesn't know about this class; create a new one from scratch return create(beanClass); } private static <T> StaticTableSchema<T> createStaticTableSchema(Class<T> beanClass, MetaTableSchemaCache metaTableSchemaCache) { DynamoDbBean dynamoDbBean = beanClass.getAnnotation(DynamoDbBean.class); if (dynamoDbBean == null) { throw new IllegalArgumentException("A DynamoDb bean class must be annotated with @DynamoDbBean, but " + beanClass.getTypeName() + " was not."); } BeanInfo beanInfo; try { beanInfo = Introspector.getBeanInfo(beanClass); } catch (IntrospectionException e) { throw new IllegalArgumentException(e); } Supplier<T> newObjectSupplier = newObjectSupplierForClass(beanClass); StaticTableSchema.Builder<T> builder = StaticTableSchema.builder(beanClass) .newItemSupplier(newObjectSupplier); builder.attributeConverterProviders(createConverterProvidersFromAnnotation(beanClass, dynamoDbBean)); List<StaticAttribute<T, ?>> attributes = new ArrayList<>(); Arrays.stream(beanInfo.getPropertyDescriptors()) .filter(p -> isMappableProperty(beanClass, p)) .forEach(propertyDescriptor -> { DynamoDbFlatten dynamoDbFlatten = getPropertyAnnotation(propertyDescriptor, DynamoDbFlatten.class); if (dynamoDbFlatten != null) { builder.flatten(TableSchema.fromClass(propertyDescriptor.getReadMethod().getReturnType()), getterForProperty(propertyDescriptor, beanClass), setterForProperty(propertyDescriptor, beanClass)); } else { AttributeConfiguration attributeConfiguration = resolveAttributeConfiguration(propertyDescriptor); StaticAttribute.Builder<T, ?> attributeBuilder = staticAttributeBuilder(propertyDescriptor, beanClass, metaTableSchemaCache, attributeConfiguration); Optional<AttributeConverter> attributeConverter = createAttributeConverterFromAnnotation(propertyDescriptor); attributeConverter.ifPresent(attributeBuilder::attributeConverter); addTagsToAttribute(attributeBuilder, propertyDescriptor); attributes.add(attributeBuilder.build()); } }); builder.attributes(attributes); return builder.build(); } private static AttributeConfiguration resolveAttributeConfiguration(PropertyDescriptor propertyDescriptor) { boolean shouldPreserveEmptyObject = getPropertyAnnotation(propertyDescriptor, DynamoDbPreserveEmptyObject.class) != null; boolean shouldIgnoreNulls = getPropertyAnnotation(propertyDescriptor, DynamoDbIgnoreNulls.class) != null; return AttributeConfiguration.builder() .preserveEmptyObject(shouldPreserveEmptyObject) .ignoreNulls(shouldIgnoreNulls) .build(); } private static List<AttributeConverterProvider> createConverterProvidersFromAnnotation(Class<?> beanClass, DynamoDbBean dynamoDbBean) { Class<? extends AttributeConverterProvider>[] providerClasses = dynamoDbBean.converterProviders(); return Arrays.stream(providerClasses) .peek(c -> debugLog(beanClass, () -> "Adding Converter: " + c.getTypeName())) .map(c -> (AttributeConverterProvider) newObjectSupplierForClass(c).get()) .collect(Collectors.toList()); } private static <T> StaticAttribute.Builder<T, ?> staticAttributeBuilder(PropertyDescriptor propertyDescriptor, Class<T> beanClass, MetaTableSchemaCache metaTableSchemaCache, AttributeConfiguration attributeConfiguration) { Type propertyType = propertyDescriptor.getReadMethod().getGenericReturnType(); EnhancedType<?> propertyTypeToken = convertTypeToEnhancedType(propertyType, metaTableSchemaCache, attributeConfiguration); return StaticAttribute.builder(beanClass, propertyTypeToken) .name(attributeNameForProperty(propertyDescriptor)) .getter(getterForProperty(propertyDescriptor, beanClass)) .setter(setterForProperty(propertyDescriptor, beanClass)); } /** * Converts a {@link Type} to an {@link EnhancedType}. Usually {@link EnhancedType#of} is capable of doing this all * by itself, but for the BeanTableSchema we want to detect if a parameterized class is being passed without a * converter that is actually another annotated class in which case we want to capture its schema and add it to the * EnhancedType. Unfortunately this means we have to duplicate some of the recursive Type parsing that * EnhancedClient otherwise does all by itself. */ @SuppressWarnings("unchecked") private static EnhancedType<?> convertTypeToEnhancedType(Type type, MetaTableSchemaCache metaTableSchemaCache, AttributeConfiguration attributeConfiguration) { Class<?> clazz = null; if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; Type rawType = parameterizedType.getRawType(); if (List.class.equals(rawType)) { EnhancedType<?> enhancedType = convertTypeToEnhancedType(parameterizedType.getActualTypeArguments()[0], metaTableSchemaCache, attributeConfiguration); return EnhancedType.listOf(enhancedType); } if (Map.class.equals(rawType)) { EnhancedType<?> enhancedType = convertTypeToEnhancedType(parameterizedType.getActualTypeArguments()[1], metaTableSchemaCache, attributeConfiguration); return EnhancedType.mapOf(EnhancedType.of(parameterizedType.getActualTypeArguments()[0]), enhancedType); } if (rawType instanceof Class) { clazz = (Class<?>) rawType; } } else if (type instanceof Class) { clazz = (Class<?>) type; } if (clazz != null) { Consumer<EnhancedTypeDocumentConfiguration.Builder> attrConfiguration = b -> b.preserveEmptyObject(attributeConfiguration.preserveEmptyObject()) .ignoreNulls(attributeConfiguration.ignoreNulls()); if (clazz.getAnnotation(DynamoDbImmutable.class) != null) { return EnhancedType.documentOf( (Class<Object>) clazz, (TableSchema<Object>) ImmutableTableSchema.recursiveCreate(clazz, metaTableSchemaCache), attrConfiguration); } else if (clazz.getAnnotation(DynamoDbBean.class) != null) { return EnhancedType.documentOf( (Class<Object>) clazz, (TableSchema<Object>) BeanTableSchema.recursiveCreate(clazz, metaTableSchemaCache), attrConfiguration); } } return EnhancedType.of(type); } private static Optional<AttributeConverter> createAttributeConverterFromAnnotation( PropertyDescriptor propertyDescriptor) { DynamoDbConvertedBy attributeConverterBean = getPropertyAnnotation(propertyDescriptor, DynamoDbConvertedBy.class); Optional<Class<?>> optionalClass = Optional.ofNullable(attributeConverterBean) .map(DynamoDbConvertedBy::value); return optionalClass.map(clazz -> (AttributeConverter) newObjectSupplierForClass(clazz).get()); } /** * This method scans all the annotations on a property and looks for a meta-annotation of * {@link BeanTableSchemaAttributeTag}. If the meta-annotation is found, it attempts to create * an annotation tag based on a standard named static method * of the class that tag has been annotated with passing in the original property annotation as an argument. */ private static void addTagsToAttribute(StaticAttribute.Builder<?, ?> attributeBuilder, PropertyDescriptor propertyDescriptor) { propertyAnnotations(propertyDescriptor).forEach(annotation -> { BeanTableSchemaAttributeTag beanTableSchemaAttributeTag = annotation.annotationType().getAnnotation(BeanTableSchemaAttributeTag.class); if (beanTableSchemaAttributeTag != null) { Class<?> tagClass = beanTableSchemaAttributeTag.value(); Method tagMethod; try { tagMethod = tagClass.getDeclaredMethod(ATTRIBUTE_TAG_STATIC_SUPPLIER_NAME, annotation.annotationType()); } catch (NoSuchMethodException e) { throw new RuntimeException( String.format("Could not find a static method named '%s' on class '%s' that returns " + "an AttributeTag for annotation '%s'", ATTRIBUTE_TAG_STATIC_SUPPLIER_NAME, tagClass, annotation.annotationType()), e); } if (!Modifier.isStatic(tagMethod.getModifiers())) { throw new RuntimeException( String.format("Could not find a static method named '%s' on class '%s' that returns " + "an AttributeTag for annotation '%s'", ATTRIBUTE_TAG_STATIC_SUPPLIER_NAME, tagClass, annotation.annotationType())); } StaticAttributeTag staticAttributeTag; try { staticAttributeTag = (StaticAttributeTag) tagMethod.invoke(null, annotation); } catch (IllegalAccessException | InvocationTargetException e) { throw new RuntimeException( String.format("Could not invoke method to create AttributeTag for annotation '%s' on class " + "'%s'.", annotation.annotationType(), tagClass), e); } attributeBuilder.addTag(staticAttributeTag); } }); } private static <R> Supplier<R> newObjectSupplierForClass(Class<R> clazz) { try { Constructor<R> constructor = clazz.getConstructor(); debugLog(clazz, () -> "Constructor: " + constructor); return ObjectConstructor.create(clazz, constructor); } catch (NoSuchMethodException e) { throw new IllegalArgumentException( String.format("Class '%s' appears to have no default constructor thus cannot be used with the " + "BeanTableSchema", clazz), e); } } private static <T, R> Function<T, R> getterForProperty(PropertyDescriptor propertyDescriptor, Class<T> beanClass) { Method readMethod = propertyDescriptor.getReadMethod(); debugLog(beanClass, () -> "Property " + propertyDescriptor.getDisplayName() + " read method: " + readMethod); return BeanAttributeGetter.create(beanClass, readMethod); } private static <T, R> BiConsumer<T, R> setterForProperty(PropertyDescriptor propertyDescriptor, Class<T> beanClass) { Method writeMethod = propertyDescriptor.getWriteMethod(); debugLog(beanClass, () -> "Property " + propertyDescriptor.getDisplayName() + " write method: " + writeMethod); return BeanAttributeSetter.create(beanClass, writeMethod); } private static String attributeNameForProperty(PropertyDescriptor propertyDescriptor) { DynamoDbAttribute dynamoDbAttribute = getPropertyAnnotation(propertyDescriptor, DynamoDbAttribute.class); if (dynamoDbAttribute != null) { return dynamoDbAttribute.value(); } return propertyDescriptor.getName(); } private static boolean isMappableProperty(Class<?> beanClass, PropertyDescriptor propertyDescriptor) { if (propertyDescriptor.getReadMethod() == null) { debugLog(beanClass, () -> "Ignoring bean property " + propertyDescriptor.getDisplayName() + " because it has no " + "read (get/is) method."); return false; } if (propertyDescriptor.getWriteMethod() == null) { debugLog(beanClass, () -> "Ignoring bean property " + propertyDescriptor.getDisplayName() + " because it has no " + "write (set) method."); return false; } if (getPropertyAnnotation(propertyDescriptor, DynamoDbIgnore.class) != null || getPropertyAnnotation(propertyDescriptor, Transient.class) != null) { debugLog(beanClass, () -> "Ignoring bean property " + propertyDescriptor.getDisplayName() + " because it has " + "@DynamoDbIgnore or @Transient."); return false; } return true; } private static <R extends Annotation> R getPropertyAnnotation(PropertyDescriptor propertyDescriptor, Class<R> annotationType) { R getterAnnotation = propertyDescriptor.getReadMethod().getAnnotation(annotationType); R setterAnnotation = propertyDescriptor.getWriteMethod().getAnnotation(annotationType); if (getterAnnotation != null) { return getterAnnotation; } // TODO: It's a common mistake that superclasses might have annotations that the child classes do not inherit, but the // customer expects them to be inherited. We should either allow inheriting those annotations, allow specifying an // annotation to inherit them, or log when this situation happens. return setterAnnotation; } private static List<? extends Annotation> propertyAnnotations(PropertyDescriptor propertyDescriptor) { return Stream.concat(Arrays.stream(propertyDescriptor.getReadMethod().getAnnotations()), Arrays.stream(propertyDescriptor.getWriteMethod().getAnnotations())) .collect(Collectors.toList()); } private static void debugLog(Class<?> beanClass, Supplier<String> logMessage) { BEAN_LOGGER.debug(() -> beanClass.getTypeName() + " - " + logMessage.get()); } }
4,391
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper/UpdateBehavior.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 software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; /** * Update behaviors that can be applied to individual attributes. This behavior will only apply to 'update' operations * such as UpdateItem, and not 'put' operations such as PutItem. * <p> * If an update behavior is not specified for an attribute, the default behavior of {@link #WRITE_ALWAYS} will be * applied. */ @SdkPublicApi @ThreadSafe public enum UpdateBehavior { /** * Always overwrite with the new value if one is provided, or remove any existing value if a null value is * provided and 'ignoreNulls' is set to false. * <p> * This is the default behavior applied to all attributes unless otherwise specified. */ WRITE_ALWAYS, /** * Write the new value if there is no existing value in the persisted record or a new record is being written, * otherwise leave the existing value. * <p> * IMPORTANT: If a null value is provided and 'ignoreNulls' is set to false, the attribute * will always be removed from the persisted record as DynamoDb does not support conditional removal with this * method. */ WRITE_IF_NOT_EXISTS }
4,392
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper/StaticAttributeTags.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 java.util.Collection; import java.util.function.BiConsumer; import java.util.function.Consumer; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType; import software.amazon.awssdk.enhanced.dynamodb.TableMetadata; import software.amazon.awssdk.enhanced.dynamodb.internal.extensions.AtomicCounterTag; import software.amazon.awssdk.enhanced.dynamodb.internal.mapper.UpdateBehaviorTag; /** * Common implementations of {@link StaticAttributeTag}. These tags can be used to mark your attributes as having certain * characteristics or features, such as primary or secondary keys in your {@link StaticTableSchema} definitions. */ @SdkPublicApi @ThreadSafe public final class StaticAttributeTags { private static final StaticAttributeTag PRIMARY_PARTITION_KEY_SINGLETON = new KeyAttributeTag((tableMetadataBuilder, attribute) -> tableMetadataBuilder.addIndexPartitionKey(TableMetadata.primaryIndexName(), attribute.getAttributeName(), attribute.getAttributeValueType())); private static final StaticAttributeTag PRIMARY_SORT_KEY_SINGLETON = new KeyAttributeTag((tableMetadataBuilder, attribute) -> tableMetadataBuilder.addIndexSortKey(TableMetadata.primaryIndexName(), attribute.getAttributeName(), attribute.getAttributeValueType())); private StaticAttributeTags() { } /** * Marks an attribute as being the primary partition key of the table it participates in. Only one attribute can * be marked this way in a given table schema. */ public static StaticAttributeTag primaryPartitionKey() { return PRIMARY_PARTITION_KEY_SINGLETON; } /** * Marks an attribute as being the primary sort key of the table it participates in. Only one attribute can be * marked this way in a given table schema. */ public static StaticAttributeTag primarySortKey() { return PRIMARY_SORT_KEY_SINGLETON; } /** * Marks an attribute as being a partition key for a secondary index. * @param indexName The name of the index this key participates in. */ public static StaticAttributeTag secondaryPartitionKey(String indexName) { return new KeyAttributeTag((tableMetadataBuilder, attribute) -> tableMetadataBuilder.addIndexPartitionKey(indexName, attribute.getAttributeName(), attribute.getAttributeValueType())); } /** * Marks an attribute as being a partition key for multiple secondary indices. * @param indexNames The names of the indices this key participates in. */ public static StaticAttributeTag secondaryPartitionKey(Collection<String> indexNames) { return new KeyAttributeTag( (tableMetadataBuilder, attribute) -> indexNames.forEach( indexName -> tableMetadataBuilder.addIndexPartitionKey(indexName, attribute.getAttributeName(), attribute.getAttributeValueType()))); } /** * Marks an attribute as being a sort key for a secondary index. * @param indexName The name of the index this key participates in. */ public static StaticAttributeTag secondarySortKey(String indexName) { return new KeyAttributeTag((tableMetadataBuilder, attribute) -> tableMetadataBuilder.addIndexSortKey(indexName, attribute.getAttributeName(), attribute.getAttributeValueType())); } /** * Marks an attribute as being a sort key for multiple secondary indices. * @param indexNames The names of the indices this key participates in. */ public static StaticAttributeTag secondarySortKey(Collection<String> indexNames) { return new KeyAttributeTag( (tableMetadataBuilder, attribute) -> indexNames.forEach( indexName -> tableMetadataBuilder.addIndexSortKey(indexName, attribute.getAttributeName(), attribute.getAttributeValueType()))); } /** * Specifies the behavior when this attribute is updated as part of an 'update' operation such as UpdateItem. See * documentation of {@link UpdateBehavior} for details on the different behaviors supported and the default * behavior. * @param updateBehavior The {@link UpdateBehavior} to be applied to this attribute */ public static StaticAttributeTag updateBehavior(UpdateBehavior updateBehavior) { return UpdateBehaviorTag.fromUpdateBehavior(updateBehavior); } /** * Used to explicitly designate an attribute to be an auto-generated counter updated unconditionally in DynamoDB. * By supplying a negative integer delta value, the attribute works as a decreasing counter. * * @param delta The value to increment (positive) or decrement (negative) the counter with for each update. * @param startValue The starting value of the counter. */ public static StaticAttributeTag atomicCounter(long delta, long startValue) { return AtomicCounterTag.fromValues(delta, startValue); } /** * Used to explicitly designate an attribute to be a default auto-generated, increasing counter updated unconditionally in * DynamoDB. The counter will have 0 as its first written value and increment with 1 for each subsequent calls to updateItem. * */ public static StaticAttributeTag atomicCounter() { return AtomicCounterTag.create(); } private static class KeyAttributeTag implements StaticAttributeTag { private final BiConsumer<StaticTableMetadata.Builder, AttributeAndType> tableMetadataKeySetter; private KeyAttributeTag(BiConsumer<StaticTableMetadata.Builder, AttributeAndType> tableMetadataKeySetter) { this.tableMetadataKeySetter = tableMetadataKeySetter; } @Override public Consumer<StaticTableMetadata.Builder> modifyMetadata(String attributeName, AttributeValueType attributeValueType) { return metadata -> { if (attributeValueType.scalarAttributeType() == null) { throw new IllegalArgumentException( String.format("Attribute '%s' of type %s is not a suitable type to be used as a key.", attributeName, attributeValueType.name())); } tableMetadataKeySetter.accept(metadata, new AttributeAndType(attributeName, attributeValueType)); }; } } private static class AttributeAndType { private final String attributeName; private final AttributeValueType attributeValueType; private AttributeAndType(String attributeName, AttributeValueType attributeValueType) { this.attributeName = attributeName; this.attributeValueType = attributeValueType; } private String getAttributeName() { return attributeName; } private AttributeValueType getAttributeValueType() { return attributeValueType; } } }
4,393
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper/StaticAttribute.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 java.util.Collection; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Function; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.enhanced.dynamodb.AttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.AttributeConverterProvider; import software.amazon.awssdk.enhanced.dynamodb.EnhancedType; /** * A class that represents an attribute that can be read from and written to an mapped item. A {@link StaticTableSchema} * composes multiple attributes that map to a common item class. * <p> * The recommended way to use this class is by calling {@link StaticTableSchema.Builder#addAttribute(Class, Consumer)}. * Example: * <pre>{@code * StaticTableSchema.builder() * .addAttribute(String.class, * a -> a.name("customer_name").getter(Customer::getName).setter(Customer::setName)) * // ... * .build(); * }</pre> * <p> * It's also possible to construct this class on its own using the static builder. Example: * <pre>{@code * StaticAttribute<Customer, ?> customerNameAttribute = * StaticAttribute.builder(Customer.class, String.class) * .name("customer_name") * .getter(Customer::getName) * .setter(Customer::setName) * .build(); * } * </pre> * @param <T> the class of the item this attribute maps into. * @param <R> the class that the value of this attribute converts to. */ @SdkPublicApi @ThreadSafe public final class StaticAttribute<T, R> { private final ImmutableAttribute<T, T, R> delegateAttribute; private StaticAttribute(Builder<T, R> builder) { this.delegateAttribute = builder.delegateBuilder.build(); } /** * Constructs a new builder for this class using supplied types. * @param itemClass The class of the item that this attribute composes. * @param attributeType A {@link EnhancedType} that represents the type of the value this attribute stores. * @return A new typed builder for an attribute. */ public static <T, R> Builder<T, R> builder(Class<T> itemClass, EnhancedType<R> attributeType) { return new Builder<>(EnhancedType.of(itemClass), attributeType); } /** * Constructs a new builder for this class using supplied types. * @param itemType The {@link EnhancedType} of the item that this attribute composes. * @param attributeType A {@link EnhancedType} that represents the type of the value this attribute stores. * @return A new typed builder for an attribute. */ public static <T, R> Builder<T, R> builder(EnhancedType<T> itemType, EnhancedType<R> attributeType) { return new Builder<>(itemType, attributeType); } /** * Constructs a new builder for this class using supplied types. * @param itemClass The class of the item that this attribute composes. * @param attributeClass A class that represents the type of the value this attribute stores. * @return A new typed builder for an attribute. */ public static <T, R> Builder<T, R> builder(Class<T> itemClass, Class<R> attributeClass) { return new Builder<>(EnhancedType.of(itemClass), EnhancedType.of(attributeClass)); } /** * The name of this attribute */ public String name() { return this.delegateAttribute.name(); } /** * A function that can get the value of this attribute from a modelled item it composes. */ public Function<T, R> getter() { return this.delegateAttribute.getter(); } /** * A function that can set the value of this attribute on a modelled item it composes. */ public BiConsumer<T, R> setter() { return this.delegateAttribute.setter(); } /** * A collection of {@link StaticAttributeTag} associated with this attribute. */ public Collection<StaticAttributeTag> tags() { return this.delegateAttribute.tags(); } /** * A {@link EnhancedType} that represents the type of the value this attribute stores. */ public EnhancedType<R> type() { return this.delegateAttribute.type(); } /** * A custom {@link AttributeConverter} that will be used to convert this attribute. * If no custom converter was provided, the value will be null. * @see Builder#attributeConverter */ public AttributeConverter<R> attributeConverter() { return this.delegateAttribute.attributeConverter(); } /** * Converts an instance of this class to a {@link Builder} that can be used to modify and reconstruct it. */ public Builder<T, R> toBuilder() { return new Builder<>(this.delegateAttribute.toBuilder()); } ImmutableAttribute<T, T, R> toImmutableAttribute() { return this.delegateAttribute; } /** * A typed builder for {@link StaticAttribute}. * @param <T> the class of the item this attribute maps into. * @param <R> the class that the value of this attribute converts to. */ @NotThreadSafe public static final class Builder<T, R> { private final ImmutableAttribute.Builder<T, T, R> delegateBuilder; private Builder(EnhancedType<T> itemType, EnhancedType<R> type) { this.delegateBuilder = ImmutableAttribute.builder(itemType, itemType, type); } private Builder(ImmutableAttribute.Builder<T, T, R> delegateBuilder) { this.delegateBuilder = delegateBuilder; } /** * The name of this attribute */ public Builder<T, R> name(String name) { this.delegateBuilder.name(name); return this; } /** * A function that can get the value of this attribute from a modelled item it composes. */ public Builder<T, R> getter(Function<T, R> getter) { this.delegateBuilder.getter(getter); return this; } /** * A function that can set the value of this attribute on a modelled item it composes. */ public Builder<T, R> setter(BiConsumer<T, R> setter) { this.delegateBuilder.setter(setter); return this; } /** * A collection of {@link StaticAttributeTag} associated with this attribute. Overwrites any existing tags. */ public Builder<T, R> tags(Collection<StaticAttributeTag> tags) { this.delegateBuilder.tags(tags); return this; } /** * A collection of {@link StaticAttributeTag} associated with this attribute. Overwrites any existing tags. */ public Builder<T, R> tags(StaticAttributeTag... tags) { this.delegateBuilder.tags(tags); return this; } /** * Associates a single {@link StaticAttributeTag} with this attribute. Adds to any existing tags. */ public Builder<T, R> addTag(StaticAttributeTag tag) { this.delegateBuilder.addTag(tag); return this; } /** * An {@link AttributeConverter} for the attribute type ({@link EnhancedType}), that can convert this attribute. * It takes precedence over any converter for this type provided by the table schema * {@link AttributeConverterProvider}. */ public Builder<T, R> attributeConverter(AttributeConverter<R> attributeConverter) { this.delegateBuilder.attributeConverter(attributeConverter); return this; } /** * Builds a {@link StaticAttributeTag} from the values stored in this builder. */ public StaticAttribute<T, R> build() { return new StaticAttribute<>(this); } } }
4,394
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper/WrappedTableSchema.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 java.util.Collection; import java.util.List; import java.util.Map; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.enhanced.dynamodb.AttributeConverter; 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.services.dynamodb.model.AttributeValue; /** * Base class for any {@link TableSchema} implementation that wraps and acts as a different {@link TableSchema} * implementation. * @param <T> The parameterized type of the {@link TableSchema} being proxied. * @param <R> The actual type of the {@link TableSchema} being proxied. */ @SdkPublicApi @ThreadSafe public abstract class WrappedTableSchema<T, R extends TableSchema<T>> implements TableSchema<T> { private final R delegateTableSchema; /** * Standard constructor. * @param delegateTableSchema An instance of {@link TableSchema} to be wrapped and proxied by this class. */ protected WrappedTableSchema(R delegateTableSchema) { this.delegateTableSchema = delegateTableSchema; } /** * The delegate table schema that is wrapped and proxied by this class. */ protected R delegateTableSchema() { return this.delegateTableSchema; } @Override public T mapToItem(Map<String, AttributeValue> attributeMap) { return this.delegateTableSchema.mapToItem(attributeMap); } @Override public T mapToItem(Map<String, AttributeValue> attributeMap, boolean preserveEmptyObject) { return this.delegateTableSchema.mapToItem(attributeMap, preserveEmptyObject); } @Override public Map<String, AttributeValue> itemToMap(T item, boolean ignoreNulls) { return this.delegateTableSchema.itemToMap(item, ignoreNulls); } @Override public Map<String, AttributeValue> itemToMap(T item, Collection<String> attributes) { return this.delegateTableSchema.itemToMap(item, attributes); } @Override public AttributeValue attributeValue(T item, String attributeName) { return this.delegateTableSchema.attributeValue(item, attributeName); } @Override public TableMetadata tableMetadata() { return this.delegateTableSchema.tableMetadata(); } @Override public EnhancedType<T> itemType() { return this.delegateTableSchema.itemType(); } @Override public List<String> attributeNames() { return this.delegateTableSchema.attributeNames(); } @Override public boolean isAbstract() { return this.delegateTableSchema.isAbstract(); } @Override public AttributeConverter<T> converterForAttribute(Object key) { return this.delegateTableSchema.converterForAttribute(key); } }
4,395
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper/annotations/DynamoDbSortKey.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.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.enhanced.dynamodb.internal.mapper.BeanTableSchemaAttributeTags; /** * Denotes this attribute as being the optional primary sort key of the DynamoDb table. This attribute must map to a * DynamoDb scalar type (string, number or binary) to be valid. * * Example using {@link DynamoDbSortKey}: * <pre> * {@code * @DynamoDbBean * public class Customer { * private String accountId; * private int subId; * * @DynamoDbPartitionKey * public String getAccountId() { * return this.accountId; * } * * public void setAccountId(String accountId) { * this.accountId = accountId; * } * * @DynamoDbSortKey * public int getSubId() { * return this.subId; * } * public void setSubId(int subId) { * this.subId = subId; * } * } * } * </pre> */ @SdkPublicApi @Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @BeanTableSchemaAttributeTag(BeanTableSchemaAttributeTags.class) public @interface DynamoDbSortKey { }
4,396
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper/annotations/DynamoDbBean.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.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.enhanced.dynamodb.AttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.AttributeConverterProvider; import software.amazon.awssdk.enhanced.dynamodb.DefaultAttributeConverterProvider; import software.amazon.awssdk.enhanced.dynamodb.mapper.BeanTableSchema; /** * Class level annotation that identifies this class as being a DynamoDb mappable entity. Any class used to initialize * a {@link BeanTableSchema} must have this annotation. If a class is used as an attribute type within another * annotated DynamoDb class, either as a document or flattened with the {@link DynamoDbFlatten} annotation, it will also * require this annotation to work automatically without an explicit {@link AttributeConverter}. * <p> * <b>Attribute Converter Providers</b><br> * Using {@link AttributeConverterProvider}s is optional and, if used, the supplied provider supersedes the default * converter provided by the table schema. * <p> * Note: * <ul> * <li>The converter(s) must provide {@link AttributeConverter}s for all types used in the schema. </li> * <li>The table schema DefaultAttributeConverterProvider provides standard converters for most primitive * and common Java types. Use custom AttributeConverterProviders when you have specific needs for type conversion * that the defaults do not cover.</li> * <li>If you provide a list of attribute converter providers, you can add DefaultAttributeConverterProvider * to the end of the list to fall back on the defaults.</li> * <li>Providing an empty list {} will cause no providers to get loaded.</li> * </ul> * * Example using attribute converter providers with one custom provider and the default provider: * <pre> * {@code * (converterProviders = {CustomAttributeConverter.class, DefaultAttributeConverterProvider.class}); * } * </pre> * <p> * Example using {@link DynamoDbBean}: * <pre> * {@code * @DynamoDbBean * public class Customer { * private String id; * private Instant createdOn; * * @DynamoDbPartitionKey * public String getId() { * return this.id; * } * * public void setId(String id) { * this.id = id; * } * * public Instant getCreatedOn() { * return this.createdOn; * } * public void setCreatedOn(Instant createdOn) { * this.createdOn = createdOn; * } * } * } * </pre> */ @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @SdkPublicApi public @interface DynamoDbBean { Class<? extends AttributeConverterProvider>[] converterProviders() default { DefaultAttributeConverterProvider.class }; }
4,397
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper/annotations/DynamoDbSecondarySortKey.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.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.enhanced.dynamodb.internal.mapper.BeanTableSchemaAttributeTags; /** * Denotes an optional sort key for a global or local secondary index. * * <p>You must also specify at least one index name. For global secondary indices, this must match an index name specified in * a {@link DynamoDbSecondaryPartitionKey}. Any index names specified that do not have an associated * {@link DynamoDbSecondaryPartitionKey} are treated as local secondary indexes. * * <p>The index name will be used if a table is created from this bean. For data-oriented operations like reads and writes, this * name does not need to match the service-side name of the index. */ @SdkPublicApi @Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @BeanTableSchemaAttributeTag(BeanTableSchemaAttributeTags.class) public @interface DynamoDbSecondarySortKey { /** * The names of one or more local or global secondary indices that this sort key should participate in. * * <p>For global secondary indices, this must match an index name specified in a {@link DynamoDbSecondaryPartitionKey}. Any * index names specified that do not have an associated {@link DynamoDbSecondaryPartitionKey} are treated as local * secondary indexes. */ String[] indexNames(); }
4,398
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper/annotations/DynamoDbFlatten.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.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import software.amazon.awssdk.annotations.SdkPublicApi; /** * This annotation is used to flatten all the attributes of a separate DynamoDb bean that is stored in the current bean * object and add them as top level attributes to the record that is read and written to the database. The target bean * to flatten must be specified as part of this annotation. */ @Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @SdkPublicApi public @interface DynamoDbFlatten { /** * @deprecated This is no longer used, the class type of the attribute will be used instead. */ @Deprecated Class<?> dynamoDbBeanClass() default Object.class; }
4,399