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/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/converter | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/converter/string/ZonedDateTimeStringConverter.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.converter.string;
import java.time.ZonedDateTime;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.enhanced.dynamodb.EnhancedType;
import software.amazon.awssdk.enhanced.dynamodb.internal.converter.StringConverter;
/**
* A converter between {@link ZonedDateTime} and {@link String}.
*/
@SdkInternalApi
@ThreadSafe
@Immutable
public class ZonedDateTimeStringConverter implements StringConverter<ZonedDateTime> {
private ZonedDateTimeStringConverter() {
}
public static ZonedDateTimeStringConverter create() {
return new ZonedDateTimeStringConverter();
}
@Override
public EnhancedType<ZonedDateTime> type() {
return EnhancedType.of(ZonedDateTime.class);
}
@Override
public ZonedDateTime fromString(String string) {
return ZonedDateTime.parse(string);
}
}
| 4,500 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/converter | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/converter/string/BigIntegerStringConverter.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.converter.string;
import java.math.BigInteger;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.enhanced.dynamodb.EnhancedType;
import software.amazon.awssdk.enhanced.dynamodb.internal.converter.StringConverter;
/**
* A converter between {@link BigInteger} and {@link String}.
*
* <p>
* This converts values using {@link BigInteger#toString()} and {@link BigInteger#BigInteger(String)}.
*/
@SdkInternalApi
@ThreadSafe
@Immutable
public class BigIntegerStringConverter implements StringConverter<BigInteger> {
private BigIntegerStringConverter() {
}
public static BigIntegerStringConverter create() {
return new BigIntegerStringConverter();
}
@Override
public EnhancedType<BigInteger> type() {
return EnhancedType.of(BigInteger.class);
}
@Override
public BigInteger fromString(String string) {
return new BigInteger(string);
}
}
| 4,501 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/converter | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/converter/string/ByteArrayStringConverter.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.converter.string;
import java.math.BigInteger;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.enhanced.dynamodb.EnhancedType;
import software.amazon.awssdk.enhanced.dynamodb.internal.converter.StringConverter;
import software.amazon.awssdk.utils.BinaryUtils;
/**
* A converter between {@link BigInteger} and {@link String}.
*
* <p>
* This converts bytes to a base 64 string.
*/
@SdkInternalApi
@ThreadSafe
@Immutable
public class ByteArrayStringConverter implements StringConverter<byte[]> {
private ByteArrayStringConverter() {
}
public static ByteArrayStringConverter create() {
return new ByteArrayStringConverter();
}
@Override
public EnhancedType<byte[]> type() {
return EnhancedType.of(byte[].class);
}
@Override
public String toString(byte[] object) {
return BinaryUtils.toBase64(object);
}
@Override
public byte[] fromString(String string) {
return BinaryUtils.fromBase64(string);
}
}
| 4,502 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/converter | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/converter/string/UriStringConverter.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.converter.string;
import java.net.URI;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.enhanced.dynamodb.EnhancedType;
import software.amazon.awssdk.enhanced.dynamodb.internal.converter.StringConverter;
/**
* A converter between {@link URI} and {@link String}.
*/
@SdkInternalApi
@ThreadSafe
@Immutable
public class UriStringConverter implements StringConverter<URI> {
private UriStringConverter() {
}
public static UriStringConverter create() {
return new UriStringConverter();
}
@Override
public EnhancedType<URI> type() {
return EnhancedType.of(URI.class);
}
@Override
public URI fromString(String string) {
return URI.create(string);
}
}
| 4,503 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/converter | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/converter/string/AtomicLongStringConverter.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.converter.string;
import java.util.concurrent.atomic.AtomicLong;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.enhanced.dynamodb.EnhancedType;
import software.amazon.awssdk.enhanced.dynamodb.internal.converter.StringConverter;
/**
* A converter between {@link AtomicLong} and {@link String}.
*
* <p>
* This converts values using {@link LongStringConverter}.
*/
@SdkInternalApi
@ThreadSafe
@Immutable
public class AtomicLongStringConverter implements StringConverter<AtomicLong> {
private static LongStringConverter LONG_CONVERTER = LongStringConverter.create();
private AtomicLongStringConverter() {
}
public static AtomicLongStringConverter create() {
return new AtomicLongStringConverter();
}
@Override
public EnhancedType<AtomicLong> type() {
return EnhancedType.of(AtomicLong.class);
}
@Override
public String toString(AtomicLong object) {
return LONG_CONVERTER.toString(object.get());
}
@Override
public AtomicLong fromString(String string) {
return new AtomicLong(LONG_CONVERTER.fromString(string));
}
}
| 4,504 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/converter | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/converter/string/ShortStringConverter.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.converter.string;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.enhanced.dynamodb.EnhancedType;
import software.amazon.awssdk.enhanced.dynamodb.internal.converter.PrimitiveConverter;
import software.amazon.awssdk.enhanced.dynamodb.internal.converter.StringConverter;
/**
* A converter between {@link Short} and {@link String}.
*/
@SdkInternalApi
@ThreadSafe
@Immutable
public class ShortStringConverter implements StringConverter<Short>, PrimitiveConverter<Short> {
private ShortStringConverter() {
}
public static ShortStringConverter create() {
return new ShortStringConverter();
}
@Override
public EnhancedType<Short> type() {
return EnhancedType.of(Short.class);
}
@Override
public EnhancedType<Short> primitiveType() {
return EnhancedType.of(short.class);
}
@Override
public Short fromString(String string) {
return Short.valueOf(string);
}
}
| 4,505 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/converter | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/converter/string/InstantStringConverter.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.converter.string;
import java.time.Instant;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.enhanced.dynamodb.EnhancedType;
import software.amazon.awssdk.enhanced.dynamodb.internal.converter.StringConverter;
/**
* A converter between {@link Instant} and {@link String}.
*/
@SdkInternalApi
@ThreadSafe
@Immutable
public class InstantStringConverter implements StringConverter<Instant> {
private InstantStringConverter() {
}
public static InstantStringConverter create() {
return new InstantStringConverter();
}
@Override
public EnhancedType<Instant> type() {
return EnhancedType.of(Instant.class);
}
@Override
public Instant fromString(String string) {
return Instant.parse(string);
}
}
| 4,506 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/converter | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/converter/string/CharacterArrayStringConverter.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.converter.string;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.enhanced.dynamodb.EnhancedType;
import software.amazon.awssdk.enhanced.dynamodb.internal.converter.StringConverter;
/**
* A converter between {@code char[]} and {@link String}.
*
* <p>
* This converts values using {@link String#String(char[])} and {@link String#toCharArray()}.
*/
@SdkInternalApi
@ThreadSafe
@Immutable
public class CharacterArrayStringConverter implements StringConverter<char[]> {
private CharacterArrayStringConverter() {
}
public static CharacterArrayStringConverter create() {
return new CharacterArrayStringConverter();
}
@Override
public EnhancedType<char[]> type() {
return EnhancedType.of(char[].class);
}
@Override
public String toString(char[] object) {
return new String(object);
}
@Override
public char[] fromString(String string) {
return string.toCharArray();
}
}
| 4,507 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/converter | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/converter/string/OptionalLongStringConverter.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.converter.string;
import java.util.OptionalLong;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.enhanced.dynamodb.EnhancedType;
import software.amazon.awssdk.enhanced.dynamodb.internal.converter.StringConverter;
/**
* A converter between {@link OptionalLong} and {@link String}.
*/
@SdkInternalApi
@ThreadSafe
@Immutable
public class OptionalLongStringConverter implements StringConverter<OptionalLong> {
private static LongStringConverter LONG_CONVERTER = LongStringConverter.create();
private OptionalLongStringConverter() {
}
public static OptionalLongStringConverter create() {
return new OptionalLongStringConverter();
}
@Override
public EnhancedType<OptionalLong> type() {
return EnhancedType.of(OptionalLong.class);
}
@Override
public String toString(OptionalLong object) {
if (!object.isPresent()) {
return null;
}
return LONG_CONVERTER.toString(object.getAsLong());
}
@Override
public OptionalLong fromString(String string) {
if (string == null) {
return OptionalLong.empty();
}
return OptionalLong.of(LONG_CONVERTER.fromString(string));
}
}
| 4,508 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/converter | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/converter/string/OptionalDoubleStringConverter.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.converter.string;
import java.util.OptionalDouble;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.enhanced.dynamodb.EnhancedType;
import software.amazon.awssdk.enhanced.dynamodb.internal.converter.StringConverter;
/**
* A converter between {@link OptionalDouble} and {@link String}.
*/
@SdkInternalApi
@ThreadSafe
@Immutable
public class OptionalDoubleStringConverter implements StringConverter<OptionalDouble> {
private static DoubleStringConverter DOUBLE_CONVERTER = DoubleStringConverter.create();
private OptionalDoubleStringConverter() {
}
public static OptionalDoubleStringConverter create() {
return new OptionalDoubleStringConverter();
}
@Override
public EnhancedType<OptionalDouble> type() {
return EnhancedType.of(OptionalDouble.class);
}
@Override
public String toString(OptionalDouble object) {
if (!object.isPresent()) {
return null;
}
return DOUBLE_CONVERTER.toString(object.getAsDouble());
}
@Override
public OptionalDouble fromString(String string) {
if (string == null) {
return OptionalDouble.empty();
}
return OptionalDouble.of(DOUBLE_CONVERTER.fromString(string));
}
}
| 4,509 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/converter | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/converter/string/AtomicIntegerStringConverter.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.converter.string;
import java.util.concurrent.atomic.AtomicInteger;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.enhanced.dynamodb.EnhancedType;
import software.amazon.awssdk.enhanced.dynamodb.internal.converter.StringConverter;
/**
* A converter between {@link AtomicInteger} and {@link String}.
*
* <p>
* This converts values using {@link IntegerStringConverter}.
*/
@SdkInternalApi
@ThreadSafe
@Immutable
public class AtomicIntegerStringConverter implements StringConverter<AtomicInteger> {
private static IntegerStringConverter INTEGER_CONVERTER = IntegerStringConverter.create();
private AtomicIntegerStringConverter() {
}
public static AtomicIntegerStringConverter create() {
return new AtomicIntegerStringConverter();
}
@Override
public EnhancedType<AtomicInteger> type() {
return EnhancedType.of(AtomicInteger.class);
}
@Override
public String toString(AtomicInteger object) {
return INTEGER_CONVERTER.toString(object.get());
}
@Override
public AtomicInteger fromString(String string) {
return new AtomicInteger(INTEGER_CONVERTER.fromString(string));
}
}
| 4,510 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/converter | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/converter/string/OffsetTimeStringConverter.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.converter.string;
import java.time.OffsetTime;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.enhanced.dynamodb.EnhancedType;
import software.amazon.awssdk.enhanced.dynamodb.internal.converter.StringConverter;
/**
* A converter between {@link OffsetTime} and {@link String}.
*/
@SdkInternalApi
@ThreadSafe
@Immutable
public class OffsetTimeStringConverter implements StringConverter<OffsetTime> {
private OffsetTimeStringConverter() {
}
public static OffsetTimeStringConverter create() {
return new OffsetTimeStringConverter();
}
@Override
public EnhancedType<OffsetTime> type() {
return EnhancedType.of(OffsetTime.class);
}
@Override
public OffsetTime fromString(String string) {
return OffsetTime.parse(string);
}
}
| 4,511 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/converter | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/converter/string/StringBufferStringConverter.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.converter.string;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.enhanced.dynamodb.EnhancedType;
import software.amazon.awssdk.enhanced.dynamodb.internal.converter.StringConverter;
/**
* A converter between {@link StringBuffer} and {@link String}.
*/
@SdkInternalApi
@ThreadSafe
@Immutable
public class StringBufferStringConverter implements StringConverter<StringBuffer> {
private StringBufferStringConverter() {
}
public static StringBufferStringConverter create() {
return new StringBufferStringConverter();
}
@Override
public EnhancedType<StringBuffer> type() {
return EnhancedType.of(StringBuffer.class);
}
@Override
public StringBuffer fromString(String string) {
return new StringBuffer(string);
}
}
| 4,512 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/converter | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/converter/string/UrlStringConverter.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.converter.string;
import java.net.MalformedURLException;
import java.net.URL;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.enhanced.dynamodb.EnhancedType;
import software.amazon.awssdk.enhanced.dynamodb.internal.converter.StringConverter;
/**
* A converter between {@link URL} and {@link String}.
*/
@SdkInternalApi
@ThreadSafe
@Immutable
public class UrlStringConverter implements StringConverter<URL> {
private UrlStringConverter() {
}
public static UrlStringConverter create() {
return new UrlStringConverter();
}
@Override
public EnhancedType<URL> type() {
return EnhancedType.of(URL.class);
}
@Override
public URL fromString(String string) {
try {
return new URL(string);
} catch (MalformedURLException e) {
throw new IllegalArgumentException("URL format was incorrect: " + string, e);
}
}
}
| 4,513 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/converter | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/converter/string/BooleanStringConverter.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.converter.string;
import java.math.BigInteger;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.enhanced.dynamodb.EnhancedType;
import software.amazon.awssdk.enhanced.dynamodb.internal.converter.PrimitiveConverter;
import software.amazon.awssdk.enhanced.dynamodb.internal.converter.StringConverter;
/**
* A converter between {@link BigInteger} and {@link String}.
*
* <p>
* This converts values to strings using {@link Boolean#toString()}. This converts the literal string values "true" and "false"
* to a boolean. Any other string values will result in an exception.
*/
@SdkInternalApi
@ThreadSafe
@Immutable
public class BooleanStringConverter implements StringConverter<Boolean>, PrimitiveConverter<Boolean> {
private BooleanStringConverter() {
}
public static BooleanStringConverter create() {
return new BooleanStringConverter();
}
@Override
public EnhancedType<Boolean> type() {
return EnhancedType.of(Boolean.class);
}
@Override
public EnhancedType<Boolean> primitiveType() {
return EnhancedType.of(boolean.class);
}
@Override
public Boolean fromString(String string) {
switch (string) {
case "true": return true;
case "false": return false;
default: throw new IllegalArgumentException("Boolean string was not 'true' or 'false': " + string);
}
}
}
| 4,514 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/converter | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/converter/string/CharacterStringConverter.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.converter.string;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.enhanced.dynamodb.EnhancedType;
import software.amazon.awssdk.enhanced.dynamodb.internal.converter.PrimitiveConverter;
import software.amazon.awssdk.enhanced.dynamodb.internal.converter.StringConverter;
import software.amazon.awssdk.utils.Validate;
/**
* A converter between {@link Character} and {@link String}.
*
* <p>
* This converts values using {@link Character#toString()} and {@link String#charAt(int)}. If the string value is longer
* than 1 character, an exception will be raised.
*/
@SdkInternalApi
@ThreadSafe
@Immutable
public class CharacterStringConverter implements StringConverter<Character>, PrimitiveConverter<Character> {
private CharacterStringConverter() {
}
public static CharacterStringConverter create() {
return new CharacterStringConverter();
}
@Override
public EnhancedType<Character> type() {
return EnhancedType.of(Character.class);
}
@Override
public EnhancedType<Character> primitiveType() {
return EnhancedType.of(char.class);
}
@Override
public Character fromString(String string) {
Validate.isTrue(string.length() == 1, "Character string was not of length 1: %s", string);
return string.charAt(0);
}
}
| 4,515 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/converter | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/converter/string/YearMonthStringConverter.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.converter.string;
import java.time.YearMonth;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.enhanced.dynamodb.EnhancedType;
import software.amazon.awssdk.enhanced.dynamodb.internal.converter.StringConverter;
/**
* A converter between {@link YearMonth} and {@link String}.
*/
@SdkInternalApi
@ThreadSafe
@Immutable
public class YearMonthStringConverter implements StringConverter<YearMonth> {
private YearMonthStringConverter() {
}
public static YearMonthStringConverter create() {
return new YearMonthStringConverter();
}
@Override
public EnhancedType<YearMonth> type() {
return EnhancedType.of(YearMonth.class);
}
@Override
public YearMonth fromString(String string) {
return YearMonth.parse(string);
}
}
| 4,516 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/converter | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/converter/string/ZoneOffsetStringConverter.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.converter.string;
import java.time.ZoneOffset;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.enhanced.dynamodb.EnhancedType;
import software.amazon.awssdk.enhanced.dynamodb.internal.converter.StringConverter;
/**
* A converter between {@link ZoneOffset} and {@link String}.
*/
@SdkInternalApi
@ThreadSafe
@Immutable
public class ZoneOffsetStringConverter implements StringConverter<ZoneOffset> {
private ZoneOffsetStringConverter() {
}
public static ZoneOffsetStringConverter create() {
return new ZoneOffsetStringConverter();
}
@Override
public EnhancedType<ZoneOffset> type() {
return EnhancedType.of(ZoneOffset.class);
}
@Override
public ZoneOffset fromString(String string) {
return ZoneOffset.of(string);
}
}
| 4,517 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/converter | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/converter/string/StringBuilderStringConverter.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.converter.string;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.enhanced.dynamodb.EnhancedType;
import software.amazon.awssdk.enhanced.dynamodb.internal.converter.StringConverter;
/**
* A converter between {@link StringBuilder} and {@link String}.
*/
@SdkInternalApi
@ThreadSafe
@Immutable
public class StringBuilderStringConverter implements StringConverter<StringBuilder> {
private StringBuilderStringConverter() {
}
public static StringBuilderStringConverter create() {
return new StringBuilderStringConverter();
}
@Override
public EnhancedType<StringBuilder> type() {
return EnhancedType.of(StringBuilder.class);
}
@Override
public StringBuilder fromString(String string) {
return new StringBuilder(string);
}
}
| 4,518 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/converter | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/converter/string/FloatStringConverter.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.converter.string;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.enhanced.dynamodb.EnhancedType;
import software.amazon.awssdk.enhanced.dynamodb.internal.converter.PrimitiveConverter;
import software.amazon.awssdk.enhanced.dynamodb.internal.converter.StringConverter;
/**
* A converter between {@link Float} and {@link String}.
*/
@SdkInternalApi
@ThreadSafe
@Immutable
public class FloatStringConverter implements StringConverter<Float>, PrimitiveConverter<Float> {
private FloatStringConverter() {
}
public static FloatStringConverter create() {
return new FloatStringConverter();
}
@Override
public EnhancedType<Float> type() {
return EnhancedType.of(Float.class);
}
@Override
public EnhancedType<Float> primitiveType() {
return EnhancedType.of(float.class);
}
@Override
public Float fromString(String string) {
return Float.valueOf(string);
}
}
| 4,519 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/converter | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/converter/string/LocalTimeStringConverter.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.converter.string;
import java.time.LocalTime;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.enhanced.dynamodb.EnhancedType;
import software.amazon.awssdk.enhanced.dynamodb.internal.converter.StringConverter;
/**
* A converter between {@link LocalTime} and {@link String}.
*/
@SdkInternalApi
@ThreadSafe
@Immutable
public class LocalTimeStringConverter implements StringConverter<LocalTime> {
private LocalTimeStringConverter() {
}
public static LocalTimeStringConverter create() {
return new LocalTimeStringConverter();
}
@Override
public EnhancedType<LocalTime> type() {
return EnhancedType.of(LocalTime.class);
}
@Override
public LocalTime fromString(String string) {
return LocalTime.parse(string);
}
}
| 4,520 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/converter | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/converter/string/LocalDateStringConverter.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.converter.string;
import java.time.LocalDate;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.enhanced.dynamodb.EnhancedType;
import software.amazon.awssdk.enhanced.dynamodb.internal.converter.StringConverter;
/**
* A converter between {@link LocalDate} and {@link String}.
*/
@SdkInternalApi
@ThreadSafe
@Immutable
public class LocalDateStringConverter implements StringConverter<LocalDate> {
private LocalDateStringConverter() {
}
public static LocalDateStringConverter create() {
return new LocalDateStringConverter();
}
@Override
public EnhancedType<LocalDate> type() {
return EnhancedType.of(LocalDate.class);
}
@Override
public LocalDate fromString(String string) {
return LocalDate.parse(string);
}
}
| 4,521 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/converter | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/converter/string/LocalDateTimeStringConverter.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.converter.string;
import java.time.LocalDateTime;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.enhanced.dynamodb.EnhancedType;
import software.amazon.awssdk.enhanced.dynamodb.internal.converter.StringConverter;
/**
* A converter between {@link LocalDateTime} and {@link String}.
*/
@SdkInternalApi
@ThreadSafe
@Immutable
public class LocalDateTimeStringConverter implements StringConverter<LocalDateTime> {
private LocalDateTimeStringConverter() {
}
public static LocalDateTimeStringConverter create() {
return new LocalDateTimeStringConverter();
}
@Override
public EnhancedType<LocalDateTime> type() {
return EnhancedType.of(LocalDateTime.class);
}
@Override
public LocalDateTime fromString(String string) {
return LocalDateTime.parse(string);
}
}
| 4,522 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/converter | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/converter/string/IntegerStringConverter.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.converter.string;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.enhanced.dynamodb.EnhancedType;
import software.amazon.awssdk.enhanced.dynamodb.internal.converter.PrimitiveConverter;
import software.amazon.awssdk.enhanced.dynamodb.internal.converter.StringConverter;
/**
* A converter between {@link Integer} and {@link String}.
*/
@SdkInternalApi
@ThreadSafe
@Immutable
public class IntegerStringConverter implements StringConverter<Integer>, PrimitiveConverter<Integer> {
private IntegerStringConverter() {
}
public static IntegerStringConverter create() {
return new IntegerStringConverter();
}
@Override
public EnhancedType<Integer> type() {
return EnhancedType.of(Integer.class);
}
@Override
public EnhancedType<Integer> primitiveType() {
return EnhancedType.of(int.class);
}
@Override
public Integer fromString(String string) {
return Integer.valueOf(string);
}
}
| 4,523 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/converter | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/converter/string/PeriodStringConverter.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.converter.string;
import java.time.Period;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.enhanced.dynamodb.EnhancedType;
import software.amazon.awssdk.enhanced.dynamodb.internal.converter.StringConverter;
/**
* A converter between {@link Period} and {@link String}.
*/
@SdkInternalApi
@ThreadSafe
@Immutable
public class PeriodStringConverter implements StringConverter<Period> {
private PeriodStringConverter() {
}
public static PeriodStringConverter create() {
return new PeriodStringConverter();
}
@Override
public EnhancedType<Period> type() {
return EnhancedType.of(Period.class);
}
@Override
public Period fromString(String string) {
return Period.parse(string);
}
}
| 4,524 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/converter | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/converter/string/ZoneIdStringConverter.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.converter.string;
import java.time.ZoneId;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.enhanced.dynamodb.EnhancedType;
import software.amazon.awssdk.enhanced.dynamodb.internal.converter.StringConverter;
/**
* A converter between {@link ZoneId} and {@link String}.
*/
@SdkInternalApi
@ThreadSafe
@Immutable
public class ZoneIdStringConverter implements StringConverter<ZoneId> {
private ZoneIdStringConverter() {
}
public static ZoneIdStringConverter create() {
return new ZoneIdStringConverter();
}
@Override
public EnhancedType<ZoneId> type() {
return EnhancedType.of(ZoneId.class);
}
@Override
public ZoneId fromString(String string) {
return ZoneId.of(string);
}
}
| 4,525 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/converter | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/converter/string/LongStringConverter.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.converter.string;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.enhanced.dynamodb.EnhancedType;
import software.amazon.awssdk.enhanced.dynamodb.internal.converter.PrimitiveConverter;
import software.amazon.awssdk.enhanced.dynamodb.internal.converter.StringConverter;
/**
* A converter between {@link Long} and {@link String}.
*/
@SdkInternalApi
@ThreadSafe
@Immutable
public class LongStringConverter implements StringConverter<Long>, PrimitiveConverter<Long> {
private LongStringConverter() {
}
public static LongStringConverter create() {
return new LongStringConverter();
}
@Override
public EnhancedType<Long> type() {
return EnhancedType.of(Long.class);
}
@Override
public EnhancedType<Long> primitiveType() {
return EnhancedType.of(long.class);
}
@Override
public Long fromString(String string) {
return Long.valueOf(string);
}
}
| 4,526 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/mapper/MetaTableSchemaCache.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.mapper;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* A cache that can store lazily initialized MetaTableSchema objects used by the TableSchema creation classes to
* facilitate self-referencing recursive builds.
*/
@SdkInternalApi
@SuppressWarnings("unchecked")
public class MetaTableSchemaCache {
private final Map<Class<?>, MetaTableSchema<?>> cacheMap = new HashMap<>();
public <T> MetaTableSchema<T> getOrCreate(Class<T> mappedClass) {
return (MetaTableSchema<T>) cacheMap().computeIfAbsent(
mappedClass, ignored -> MetaTableSchema.create(mappedClass));
}
public <T> Optional<MetaTableSchema<T>> get(Class<T> mappedClass) {
return Optional.ofNullable((MetaTableSchema<T>) cacheMap().get(mappedClass));
}
private Map<Class<?>, MetaTableSchema<?>> cacheMap() {
return this.cacheMap;
}
}
| 4,527 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/mapper/DefaultParameterizedType.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.mapper;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.utils.Validate;
/**
* An implementation of {@link ParameterizedType} that guarantees its raw type is always a {@link Class}.
*/
@SdkInternalApi
@ThreadSafe
public final class DefaultParameterizedType implements ParameterizedType {
private final Class<?> rawType;
private final Type[] arguments;
private DefaultParameterizedType(Class<?> rawType, Type... arguments) {
Validate.notEmpty(arguments, "Arguments must not be empty.");
Validate.noNullElements(arguments, "Arguments cannot contain null values.");
this.rawType = Validate.paramNotNull(rawType, "rawType");
this.arguments = arguments;
}
public static ParameterizedType parameterizedType(Class<?> rawType, Type... arguments) {
return new DefaultParameterizedType(rawType, arguments);
}
@Override
public Class<?> getRawType() {
return rawType;
}
@Override
public Type[] getActualTypeArguments() {
return arguments.clone();
}
@Override
public Type getOwnerType() {
return null;
}
}
| 4,528 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/mapper/BeanAttributeGetter.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.mapper;
import java.lang.reflect.Method;
import java.util.function.Function;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.utils.Validate;
@FunctionalInterface
@SdkInternalApi
@SuppressWarnings("unchecked")
public interface BeanAttributeGetter<BeanT, GetterT> extends Function<BeanT, GetterT> {
static <BeanT, GetterT> BeanAttributeGetter<BeanT, GetterT> create(Class<BeanT> beanClass, Method getter) {
Validate.isTrue(getter.getParameterCount() == 0,
"%s.%s has parameters, despite being named like a getter.",
beanClass, getter.getName());
return LambdaToMethodBridgeBuilder.create(BeanAttributeGetter.class)
.lambdaMethodName("apply")
.runtimeLambdaSignature(Object.class, Object.class)
.compileTimeLambdaSignature(getter.getReturnType(), beanClass)
.targetMethod(getter)
.build();
}
}
| 4,529 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/mapper/MetaTableSchema.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.mapper;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import software.amazon.awssdk.annotations.SdkInternalApi;
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;
/**
* An implementation of {@link TableSchema} that can be instantiated as an uninitialized reference and then lazily
* initialized later with a concrete {@link TableSchema} at which point it will behave as the real object.
* <p>
* This allows an immutable {@link TableSchema} to be declared and used in a self-referential recursive way within its
* builder/definition path. Any attempt to use the {@link MetaTableSchema} as a concrete {@link TableSchema} before
* calling {@link #initialize(TableSchema)} will cause an exception to be thrown.
*/
@SdkInternalApi
public class MetaTableSchema<T> implements TableSchema<T> {
private TableSchema<T> concreteTableSchema;
private MetaTableSchema() {
}
public static <T> MetaTableSchema<T> create(Class<T> itemClass) {
return new MetaTableSchema<>();
}
@Override
public T mapToItem(Map<String, AttributeValue> attributeMap) {
return concreteTableSchema().mapToItem(attributeMap);
}
@Override
public Map<String, AttributeValue> itemToMap(T item, boolean ignoreNulls) {
return concreteTableSchema().itemToMap(item, ignoreNulls);
}
@Override
public Map<String, AttributeValue> itemToMap(T item, Collection<String> attributes) {
return concreteTableSchema().itemToMap(item, attributes);
}
@Override
public AttributeValue attributeValue(T item, String attributeName) {
return concreteTableSchema().attributeValue(item, attributeName);
}
@Override
public TableMetadata tableMetadata() {
return concreteTableSchema().tableMetadata();
}
@Override
public EnhancedType<T> itemType() {
return concreteTableSchema().itemType();
}
@Override
public List<String> attributeNames() {
return concreteTableSchema().attributeNames();
}
@Override
public boolean isAbstract() {
return concreteTableSchema().isAbstract();
}
@Override
public AttributeConverter<T> converterForAttribute(Object key) {
return concreteTableSchema.converterForAttribute(key);
}
public void initialize(TableSchema<T> realTableSchema) {
if (this.concreteTableSchema != null) {
throw new IllegalStateException("A MetaTableSchema can only be initialized with a concrete TableSchema " +
"instance once.");
}
this.concreteTableSchema = realTableSchema;
}
public TableSchema<T> concreteTableSchema() {
if (this.concreteTableSchema == null) {
throw new IllegalStateException("A MetaTableSchema must be initialized with a concrete TableSchema " +
"instance by calling 'initialize' before it can be used as a " +
"TableSchema itself");
}
return this.concreteTableSchema;
}
public boolean isInitialized() {
return this.concreteTableSchema != null;
}
}
| 4,530 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/mapper/ObjectConstructor.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.mapper;
import java.lang.reflect.Constructor;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.utils.Validate;
@FunctionalInterface
@SdkInternalApi
@SuppressWarnings("unchecked")
public interface ObjectConstructor<BeanT> extends Supplier<BeanT> {
static <BeanT> ObjectConstructor<BeanT> create(Class<BeanT> beanClass, Constructor<BeanT> noArgsConstructor) {
Validate.isTrue(noArgsConstructor.getParameterCount() == 0,
"%s has no default constructor.",
beanClass);
return LambdaToMethodBridgeBuilder.create(ObjectConstructor.class)
.lambdaMethodName("get")
.runtimeLambdaSignature(Object.class)
.compileTimeLambdaSignature(beanClass)
.targetMethod(noArgsConstructor)
.build();
}
}
| 4,531 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/mapper/ObjectGetterMethod.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.mapper;
import java.lang.reflect.Method;
import java.util.function.Function;
import software.amazon.awssdk.annotations.SdkInternalApi;
@FunctionalInterface
@SdkInternalApi
@SuppressWarnings("unchecked")
public interface ObjectGetterMethod<BeanT, GetterT> extends Function<BeanT, GetterT> {
static <BeanT, GetterT> ObjectGetterMethod<BeanT, GetterT> create(Class<BeanT> beanClass, Method buildMethod) {
return LambdaToMethodBridgeBuilder.create(ObjectGetterMethod.class)
.lambdaMethodName("apply")
.runtimeLambdaSignature(Object.class, Object.class)
.compileTimeLambdaSignature(buildMethod.getReturnType(), beanClass)
.targetMethod(buildMethod)
.build();
}
}
| 4,532 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/mapper/AtomicCounter.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.mapper;
import java.util.Objects;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.enhanced.dynamodb.AttributeConverter;
import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.LongAttributeConverter;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
@SdkInternalApi
public final class AtomicCounter {
public static final String KEY_PREFIX = "_";
private static final String DELTA_ATTRIBUTE_NAME = KEY_PREFIX + "Delta";
private static final String STARTVALUE_ATTRIBUTE_NAME = KEY_PREFIX + "Start";
private final CounterAttribute delta;
private final CounterAttribute startValue;
private AtomicCounter(Builder builder) {
this.delta = new CounterAttribute(builder.delta, DELTA_ATTRIBUTE_NAME);
this.startValue = new CounterAttribute(builder.startValue, STARTVALUE_ATTRIBUTE_NAME);
}
public static Builder builder() {
return new Builder();
}
public CounterAttribute delta() {
return delta;
}
public CounterAttribute startValue() {
return startValue;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AtomicCounter that = (AtomicCounter) o;
if (!Objects.equals(delta, that.delta)) {
return false;
}
return Objects.equals(startValue, that.startValue);
}
@Override
public int hashCode() {
int result = Objects.hashCode(delta);
result = 31 * result + Objects.hashCode(startValue);
return result;
}
public static final class Builder {
private Long delta;
private Long startValue;
private Builder() {
}
public Builder delta(Long delta) {
this.delta = delta;
return this;
}
public Builder startValue(Long startValue) {
this.startValue = startValue;
return this;
}
public AtomicCounter build() {
return new AtomicCounter(this);
}
}
public static class CounterAttribute {
private static final AttributeConverter<Long> CONVERTER = LongAttributeConverter.create();
private final Long value;
private final String name;
CounterAttribute(Long value, String name) {
this.value = value;
this.name = name;
}
public Long value() {
return value;
}
public String name() {
return name;
}
public static AttributeValue resolvedValue(Long value) {
return CONVERTER.transformFrom(value);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CounterAttribute that = (CounterAttribute) o;
if (!Objects.equals(value, that.value)) {
return false;
}
return Objects.equals(name, that.name);
}
@Override
public int hashCode() {
int result = Objects.hashCode(value);
result = 31 * result + Objects.hashCode(name);
return result;
}
}
}
| 4,533 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/mapper/LambdaToMethodBridgeBuilder.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.mapper;
import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely;
import java.lang.invoke.LambdaMetafactory;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.utils.Either;
@SdkInternalApi
public class LambdaToMethodBridgeBuilder<T> {
private static final MethodHandles.Lookup LOOKUP = MethodHandles.lookup();
private final Class<T> lambdaType;
private String lambdaMethodName;
private Class<?> postEraseLambdaReturnType;
private Class<?>[] postEraseLambdaParameters;
private Class<?> preEraseLambdaReturnType;
private Class<?>[] preEraseLambdaParameters;
private Either<Method, Constructor<?>> targetMethod;
private LambdaToMethodBridgeBuilder(Class<T> lambdaType) {
this.lambdaType = lambdaType;
}
public static <T> LambdaToMethodBridgeBuilder<T> create(Class<T> lambdaType) {
return new LambdaToMethodBridgeBuilder<>(lambdaType);
}
public LambdaToMethodBridgeBuilder<T> lambdaMethodName(String lambdaMethodName) {
this.lambdaMethodName = lambdaMethodName;
return this;
}
public LambdaToMethodBridgeBuilder<T> runtimeLambdaSignature(Class<?> returnType, Class<?>... parameters) {
this.postEraseLambdaReturnType = returnType;
this.postEraseLambdaParameters = parameters.clone();
return this;
}
public LambdaToMethodBridgeBuilder<T> compileTimeLambdaSignature(Class<?> returnType, Class<?>... parameters) {
this.preEraseLambdaReturnType = returnType;
this.preEraseLambdaParameters = parameters.clone();
return this;
}
public LambdaToMethodBridgeBuilder<T> targetMethod(Method method) {
this.targetMethod = Either.left(method);
return this;
}
public LambdaToMethodBridgeBuilder<T> targetMethod(Constructor<?> method) {
this.targetMethod = Either.right(method);
return this;
}
public T build() {
try {
MethodHandle targetMethodHandle = targetMethod.map(
m -> invokeSafely(() -> LOOKUP.unreflect(m)),
c -> invokeSafely(() -> LOOKUP.unreflectConstructor(c)));
return lambdaType.cast(
LambdaMetafactory.metafactory(LOOKUP,
lambdaMethodName,
MethodType.methodType(lambdaType),
MethodType.methodType(postEraseLambdaReturnType, postEraseLambdaParameters),
targetMethodHandle,
MethodType.methodType(preEraseLambdaReturnType, preEraseLambdaParameters))
.getTarget()
.invoke());
} catch (Throwable e) {
throw new IllegalArgumentException("Failed to generate method handle.", e);
}
}
}
| 4,534 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/mapper/BeanAttributeSetter.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.mapper;
import java.lang.reflect.Method;
import java.util.function.BiConsumer;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.internal.ReflectionUtils;
@FunctionalInterface
@SdkInternalApi
public interface BeanAttributeSetter<BeanT, GetterT> extends BiConsumer<BeanT, GetterT> {
@SuppressWarnings("unchecked")
static <BeanT, SetterT> BeanAttributeSetter<BeanT, SetterT> create(Class<BeanT> beanClass, Method setter) {
Validate.isTrue(setter.getParameterCount() == 1,
"%s.%s doesn't have just 1 parameter, despite being named like a setter.",
beanClass, setter.getName());
Class<?> setterInputClass = setter.getParameters()[0].getType();
Class<?> boxedInputClass = ReflectionUtils.getWrappedClass(setterInputClass);
return LambdaToMethodBridgeBuilder.create(BeanAttributeSetter.class)
.lambdaMethodName("accept")
.runtimeLambdaSignature(void.class, Object.class, Object.class)
.compileTimeLambdaSignature(void.class, beanClass, boxedInputClass)
.targetMethod(setter)
.build();
}
}
| 4,535 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/mapper/StaticGetterMethod.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.mapper;
import java.lang.reflect.Method;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkInternalApi;
@FunctionalInterface
@SdkInternalApi
@SuppressWarnings("unchecked")
public interface StaticGetterMethod<GetterT> extends Supplier<GetterT> {
static <GetterT> StaticGetterMethod<GetterT> create(Method buildMethod) {
return LambdaToMethodBridgeBuilder.create(StaticGetterMethod.class)
.lambdaMethodName("get")
.runtimeLambdaSignature(Object.class)
.compileTimeLambdaSignature(buildMethod.getReturnType())
.targetMethod(buildMethod)
.build();
}
}
| 4,536 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/mapper/AttributeType.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.mapper;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
@SdkInternalApi
public interface AttributeType<T> {
AttributeValue objectToAttributeValue(T object);
T attributeValueToObject(AttributeValue attributeValue);
AttributeValueType attributeValueType();
}
| 4,537 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/mapper/StaticIndexMetadata.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.mapper;
import java.util.Optional;
import software.amazon.awssdk.annotations.NotThreadSafe;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.enhanced.dynamodb.IndexMetadata;
import software.amazon.awssdk.enhanced.dynamodb.KeyAttributeMetadata;
@SdkInternalApi
public class StaticIndexMetadata implements IndexMetadata {
private final String name;
private final KeyAttributeMetadata partitionKey;
private final KeyAttributeMetadata sortKey;
private StaticIndexMetadata(Builder b) {
this.name = b.name;
this.partitionKey = b.partitionKey;
this.sortKey = b.sortKey;
}
public static Builder builder() {
return new Builder();
}
public static Builder builderFrom(IndexMetadata index) {
return index == null ? builder() : builder().name(index.name())
.partitionKey(index.partitionKey().orElse(null))
.sortKey(index.sortKey().orElse(null));
}
@Override
public String name() {
return this.name;
}
@Override
public Optional<KeyAttributeMetadata> partitionKey() {
return Optional.ofNullable(this.partitionKey);
}
@Override
public Optional<KeyAttributeMetadata> sortKey() {
return Optional.ofNullable(this.sortKey);
}
@NotThreadSafe
public static class Builder {
private String name;
private KeyAttributeMetadata partitionKey;
private KeyAttributeMetadata sortKey;
private Builder() {
}
public Builder name(String name) {
this.name = name;
return this;
}
public Builder partitionKey(KeyAttributeMetadata partitionKey) {
this.partitionKey = partitionKey;
return this;
}
public Builder sortKey(KeyAttributeMetadata sortKey) {
this.sortKey = sortKey;
return this;
}
public StaticIndexMetadata build() {
return new StaticIndexMetadata(this);
}
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
StaticIndexMetadata that = (StaticIndexMetadata) o;
if (name != null ? !name.equals(that.name) : that.name != null) {
return false;
}
if (partitionKey != null ? !partitionKey.equals(that.partitionKey) : that.partitionKey != null) {
return false;
}
return sortKey != null ? sortKey.equals(that.sortKey) : that.sortKey == null;
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + (partitionKey != null ? partitionKey.hashCode() : 0);
result = 31 * result + (sortKey != null ? sortKey.hashCode() : 0);
return result;
}
}
| 4,538 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/mapper/StaticKeyAttributeMetadata.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.mapper;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType;
import software.amazon.awssdk.enhanced.dynamodb.KeyAttributeMetadata;
@SdkInternalApi
public class StaticKeyAttributeMetadata implements KeyAttributeMetadata {
private final String name;
private final AttributeValueType attributeValueType;
private StaticKeyAttributeMetadata(String name, AttributeValueType attributeValueType) {
this.name = name;
this.attributeValueType = attributeValueType;
}
public static StaticKeyAttributeMetadata create(String name, AttributeValueType attributeValueType) {
return new StaticKeyAttributeMetadata(name, attributeValueType);
}
@Override
public String name() {
return this.name;
}
@Override
public AttributeValueType attributeValueType() {
return this.attributeValueType;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
StaticKeyAttributeMetadata staticKey = (StaticKeyAttributeMetadata) o;
if (name != null ? !name.equals(staticKey.name) : staticKey.name != null) {
return false;
}
return attributeValueType == staticKey.attributeValueType;
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + (attributeValueType != null ? attributeValueType.hashCode() : 0);
return result;
}
}
| 4,539 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/mapper/ResolvedImmutableAttribute.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.mapper;
import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.nullAttributeValue;
import static software.amazon.awssdk.enhanced.dynamodb.internal.EnhancedClientUtils.isNullAttributeValue;
import java.util.function.BiConsumer;
import java.util.function.Function;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.enhanced.dynamodb.AttributeConverter;
import software.amazon.awssdk.enhanced.dynamodb.mapper.ImmutableAttribute;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableMetadata;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
@SdkInternalApi
public final class ResolvedImmutableAttribute<T, B> {
private final String attributeName;
private final Function<T, AttributeValue> getAttributeMethod;
private final BiConsumer<B, AttributeValue> updateBuilderMethod;
private final StaticTableMetadata tableMetadata;
private final AttributeConverter attributeConverter;
private ResolvedImmutableAttribute(String attributeName,
Function<T, AttributeValue> getAttributeMethod,
BiConsumer<B, AttributeValue> updateBuilderMethod,
StaticTableMetadata tableMetadata,
AttributeConverter attributeConverter) {
this.attributeName = attributeName;
this.getAttributeMethod = getAttributeMethod;
this.updateBuilderMethod = updateBuilderMethod;
this.tableMetadata = tableMetadata;
this.attributeConverter = attributeConverter;
}
public static <T, B, R> ResolvedImmutableAttribute<T, B> create(ImmutableAttribute<T, B, R> immutableAttribute,
AttributeConverter<R> attributeConverter) {
AttributeType<R> attributeType = StaticAttributeType.create(attributeConverter);
Function<T, AttributeValue> getAttributeValueWithTransform = item -> {
R value = immutableAttribute.getter().apply(item);
return value == null ? nullAttributeValue() : attributeType.objectToAttributeValue(value);
};
// When setting a value on the java object, do not explicitly set nulls as this can cause an NPE to be thrown
// if the target attribute type is a primitive.
BiConsumer<B, AttributeValue> updateBuilderWithTransform =
(builder, attributeValue) -> {
// If the attributeValue is null, do not attempt to marshal
if (isNullAttributeValue(attributeValue)) {
return;
}
R value = attributeType.attributeValueToObject(attributeValue);
if (value != null) {
immutableAttribute.setter().accept(builder, value);
}
};
StaticTableMetadata.Builder tableMetadataBuilder = StaticTableMetadata.builder();
immutableAttribute.tags().forEach(tag -> {
tag.validateType(immutableAttribute.name(), immutableAttribute.type(),
attributeType.attributeValueType());
tag.modifyMetadata(immutableAttribute.name(), attributeType.attributeValueType()).accept(tableMetadataBuilder);
});
return new ResolvedImmutableAttribute<>(immutableAttribute.name(),
getAttributeValueWithTransform,
updateBuilderWithTransform,
tableMetadataBuilder.build(),
attributeConverter);
}
public <T1, B1> ResolvedImmutableAttribute<T1, B1> transform(
Function<T1, T> transformItem,
Function<B1, B> transformBuilder) {
return new ResolvedImmutableAttribute<>(
attributeName,
item -> {
T otherItem = transformItem.apply(item);
// If the containing object is null don't attempt to read attributes from it
return otherItem == null ?
nullAttributeValue() : getAttributeMethod.apply(otherItem);
},
(item, value) -> updateBuilderMethod.accept(transformBuilder.apply(item), value),
tableMetadata, attributeConverter);
}
public String attributeName() {
return attributeName;
}
public Function<T, AttributeValue> attributeGetterMethod() {
return getAttributeMethod;
}
public BiConsumer<B, AttributeValue> updateItemMethod() {
return updateBuilderMethod;
}
public StaticTableMetadata tableMetadata() {
return tableMetadata;
}
public AttributeConverter attributeConverter() {
return attributeConverter;
}
}
| 4,540 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/mapper/UpdateBehaviorTag.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.mapper;
import java.util.function.Consumer;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType;
import software.amazon.awssdk.enhanced.dynamodb.TableMetadata;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTag;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableMetadata;
import software.amazon.awssdk.enhanced.dynamodb.mapper.UpdateBehavior;
@SdkInternalApi
public class UpdateBehaviorTag implements StaticAttributeTag {
private static final String CUSTOM_METADATA_KEY_PREFIX = "UpdateBehavior:";
private static final UpdateBehavior DEFAULT_UPDATE_BEHAVIOR = UpdateBehavior.WRITE_ALWAYS;
private static final UpdateBehaviorTag WRITE_ALWAYS_TAG = new UpdateBehaviorTag(UpdateBehavior.WRITE_ALWAYS);
private static final UpdateBehaviorTag WRITE_IF_NOT_EXISTS_TAG =
new UpdateBehaviorTag(UpdateBehavior.WRITE_IF_NOT_EXISTS);
private final UpdateBehavior updateBehavior;
private UpdateBehaviorTag(UpdateBehavior updateBehavior) {
this.updateBehavior = updateBehavior;
}
public static UpdateBehaviorTag fromUpdateBehavior(UpdateBehavior updateBehavior) {
switch (updateBehavior) {
case WRITE_ALWAYS:
return WRITE_ALWAYS_TAG;
case WRITE_IF_NOT_EXISTS:
return WRITE_IF_NOT_EXISTS_TAG;
default:
throw new IllegalArgumentException("Update behavior '" + updateBehavior + "' not supported");
}
}
public static UpdateBehavior resolveForAttribute(String attributeName, TableMetadata tableMetadata) {
String metadataKey = CUSTOM_METADATA_KEY_PREFIX + attributeName;
return tableMetadata.customMetadataObject(metadataKey, UpdateBehavior.class).orElse(DEFAULT_UPDATE_BEHAVIOR);
}
@Override
public Consumer<StaticTableMetadata.Builder> modifyMetadata(String attributeName,
AttributeValueType attributeValueType) {
return metadata ->
metadata.addCustomMetadataObject(CUSTOM_METADATA_KEY_PREFIX + attributeName, this.updateBehavior);
}
}
| 4,541 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/mapper/StaticAttributeType.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.mapper;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.enhanced.dynamodb.AttributeConverter;
import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
@SdkInternalApi
public final class StaticAttributeType<T> implements AttributeType<T> {
private final AttributeConverter<T> attributeConverter;
private final AttributeValueType attributeValueType;
private StaticAttributeType(AttributeConverter<T> attributeConverter) {
this.attributeConverter = attributeConverter;
this.attributeValueType = attributeConverter.attributeValueType();
}
public static <T> AttributeType<T> create(
AttributeConverter<T> attributeConverter) {
return new StaticAttributeType<>(attributeConverter);
}
@Override
public AttributeValue objectToAttributeValue(T object) {
return this.attributeConverter.transformFrom(object);
}
@Override
public T attributeValueToObject(AttributeValue attributeValue) {
return this.attributeConverter.transformTo(attributeValue);
}
@Override
public AttributeValueType attributeValueType() {
return attributeValueType;
}
}
| 4,542 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/mapper/BeanTableSchemaAttributeTags.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.mapper;
import java.util.Arrays;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.enhanced.dynamodb.extensions.annotations.DynamoDbAtomicCounter;
import software.amazon.awssdk.enhanced.dynamodb.mapper.BeanTableSchema;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTag;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.BeanTableSchemaAttributeTag;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbSecondaryPartitionKey;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbSecondarySortKey;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbSortKey;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbUpdateBehavior;
/**
* Static provider class for core {@link BeanTableSchema} attribute tags. Each of the implemented annotations has a
* corresponding reference to this class in a
* {@link BeanTableSchemaAttributeTag}
* meta-annotation.
*/
@SdkInternalApi
public final class BeanTableSchemaAttributeTags {
private BeanTableSchemaAttributeTags() {
}
public static StaticAttributeTag attributeTagFor(DynamoDbPartitionKey annotation) {
return StaticAttributeTags.primaryPartitionKey();
}
public static StaticAttributeTag attributeTagFor(DynamoDbSortKey annotation) {
return StaticAttributeTags.primarySortKey();
}
public static StaticAttributeTag attributeTagFor(DynamoDbSecondaryPartitionKey annotation) {
return StaticAttributeTags.secondaryPartitionKey(Arrays.asList(annotation.indexNames()));
}
public static StaticAttributeTag attributeTagFor(DynamoDbSecondarySortKey annotation) {
return StaticAttributeTags.secondarySortKey(Arrays.asList(annotation.indexNames()));
}
public static StaticAttributeTag attributeTagFor(DynamoDbUpdateBehavior annotation) {
return StaticAttributeTags.updateBehavior(annotation.value());
}
public static StaticAttributeTag attributeTagFor(DynamoDbAtomicCounter annotation) {
return StaticAttributeTags.atomicCounter(annotation.delta(), annotation.startValue());
}
}
| 4,543 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/document/DefaultEnhancedDocument.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.document;
import static java.util.Collections.unmodifiableList;
import static java.util.Collections.unmodifiableMap;
import static software.amazon.awssdk.enhanced.dynamodb.internal.document.JsonStringFormatHelper.addEscapeCharacters;
import static software.amazon.awssdk.enhanced.dynamodb.internal.document.JsonStringFormatHelper.stringValue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.core.SdkNumber;
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.document.EnhancedDocument;
import software.amazon.awssdk.enhanced.dynamodb.internal.converter.ChainConverterProvider;
import software.amazon.awssdk.enhanced.dynamodb.internal.converter.StringConverterProvider;
import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.JsonItemAttributeConverter;
import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.ListAttributeConverter;
import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.MapAttributeConverter;
import software.amazon.awssdk.protocols.jsoncore.JsonNode;
import software.amazon.awssdk.protocols.jsoncore.JsonNodeParser;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.utils.Lazy;
import software.amazon.awssdk.utils.StringUtils;
import software.amazon.awssdk.utils.Validate;
/**
* Default implementation of {@link EnhancedDocument} used by the SDK to create Enhanced Documents. Attributes are initially saved
* as a String-Object Map when documents are created using the builder. Conversion to an AttributeValueMap is done lazily when
* values are accessed. When the document is retrieved from DynamoDB, the AttributeValueMap is internally saved as the attribute
* value map. Custom objects or collections are saved in the enhancedTypeMap to preserve the generic class information. Note that
* no default ConverterProviders are assigned, so ConverterProviders must be passed in the builder when creating enhanced
* documents.
*/
@Immutable
@SdkInternalApi
public class DefaultEnhancedDocument implements EnhancedDocument {
private static final Lazy<IllegalStateException> NULL_SET_ERROR = new Lazy<>(
() -> new IllegalStateException("Set must not have null values."));
private static final JsonItemAttributeConverter JSON_ATTRIBUTE_CONVERTER = JsonItemAttributeConverter.create();
private static final String VALIDATE_TYPE_ERROR = "Values of type %s are not supported by this API, please use the "
+ "%s%s API instead";
private static final AttributeValue NULL_ATTRIBUTE_VALUE = AttributeValue.fromNul(true);
private final Map<String, Object> nonAttributeValueMap;
private final Map<String, EnhancedType> enhancedTypeMap;
private final List<AttributeConverterProvider> attributeConverterProviders;
private final ChainConverterProvider attributeConverterChain;
private final Lazy<Map<String, AttributeValue>> attributeValueMap = new Lazy<>(this::initializeAttributeValueMap);
public DefaultEnhancedDocument(DefaultBuilder builder) {
this.nonAttributeValueMap = unmodifiableMap(new LinkedHashMap<>(builder.nonAttributeValueMap));
this.attributeConverterProviders = unmodifiableList(new ArrayList<>(builder.attributeConverterProviders));
this.attributeConverterChain = ChainConverterProvider.create(attributeConverterProviders);
this.enhancedTypeMap = unmodifiableMap(builder.enhancedTypeMap);
}
public static Builder builder() {
return new DefaultBuilder();
}
public static <T> AttributeConverter<T> converterForClass(EnhancedType<T> type,
ChainConverterProvider chainConverterProvider) {
if (type.rawClass().isAssignableFrom(List.class)) {
return (AttributeConverter<T>) ListAttributeConverter
.create(converterForClass(type.rawClassParameters().get(0), chainConverterProvider));
}
if (type.rawClass().isAssignableFrom(Map.class)) {
return (AttributeConverter<T>) MapAttributeConverter.mapConverter(
StringConverterProvider.defaultProvider().converterFor(type.rawClassParameters().get(0)),
converterForClass(type.rawClassParameters().get(1), chainConverterProvider));
}
return Optional.ofNullable(chainConverterProvider.converterFor(type))
.orElseThrow(() -> new IllegalStateException(
"AttributeConverter not found for class " + type
+ ". Please add an AttributeConverterProvider for this type. If it is a default type, add the "
+ "DefaultAttributeConverterProvider to the builder."));
}
@Override
public Builder toBuilder() {
return new DefaultBuilder(this);
}
@Override
public List<AttributeConverterProvider> attributeConverterProviders() {
return attributeConverterProviders;
}
@Override
public boolean isNull(String attributeName) {
if (!isPresent(attributeName)) {
return false;
}
Object attributeValue = nonAttributeValueMap.get(attributeName);
return attributeValue == null || NULL_ATTRIBUTE_VALUE.equals(attributeValue);
}
@Override
public boolean isPresent(String attributeName) {
return nonAttributeValueMap.containsKey(attributeName);
}
@Override
public <T> T get(String attributeName, EnhancedType<T> type) {
AttributeValue attributeValue = attributeValueMap.getValue().get(attributeName);
if (attributeValue == null) {
return null;
}
return fromAttributeValue(attributeValue, type);
}
@Override
public String getString(String attributeName) {
return get(attributeName, String.class);
}
@Override
public SdkNumber getNumber(String attributeName) {
return get(attributeName, SdkNumber.class);
}
@Override
public <T> T get(String attributeName, Class<T> clazz) {
checkAndValidateClass(clazz, false);
return get(attributeName, EnhancedType.of(clazz));
}
@Override
public SdkBytes getBytes(String attributeName) {
return get(attributeName, SdkBytes.class);
}
@Override
public Set<String> getStringSet(String attributeName) {
return get(attributeName, EnhancedType.setOf(String.class));
}
@Override
public Set<SdkNumber> getNumberSet(String attributeName) {
return get(attributeName, EnhancedType.setOf(SdkNumber.class));
}
@Override
public Set<SdkBytes> getBytesSet(String attributeName) {
return get(attributeName, EnhancedType.setOf(SdkBytes.class));
}
@Override
public <T> List<T> getList(String attributeName, EnhancedType<T> type) {
return get(attributeName, EnhancedType.listOf(type));
}
@Override
public <K, V> Map<K, V> getMap(String attributeName, EnhancedType<K> keyType, EnhancedType<V> valueType) {
return get(attributeName, EnhancedType.mapOf(keyType, valueType));
}
@Override
public String getJson(String attributeName) {
AttributeValue attributeValue = attributeValueMap.getValue().get(attributeName);
if (attributeValue == null) {
return null;
}
return stringValue(JSON_ATTRIBUTE_CONVERTER.transformTo(attributeValue));
}
@Override
public Boolean getBoolean(String attributeName) {
return get(attributeName, Boolean.class);
}
@Override
public List<AttributeValue> getListOfUnknownType(String attributeName) {
AttributeValue attributeValue = attributeValueMap.getValue().get(attributeName);
if (attributeValue == null) {
return null;
}
if (!attributeValue.hasL()) {
throw new IllegalStateException("Cannot get a List from attribute value of Type " + attributeValue.type());
}
return attributeValue.l();
}
@Override
public Map<String, AttributeValue> getMapOfUnknownType(String attributeName) {
AttributeValue attributeValue = attributeValueMap.getValue().get(attributeName);
if (attributeValue == null) {
return null;
}
if (!attributeValue.hasM()) {
throw new IllegalStateException("Cannot get a Map from attribute value of Type " + attributeValue.type());
}
return attributeValue.m();
}
@Override
public String toJson() {
if (nonAttributeValueMap.isEmpty()) {
return "{}";
}
return attributeValueMap.getValue().entrySet().stream()
.map(entry -> "\""
+ addEscapeCharacters(entry.getKey())
+ "\":"
+ stringValue(JSON_ATTRIBUTE_CONVERTER.transformTo(entry.getValue())))
.collect(Collectors.joining(",", "{", "}"));
}
@Override
public Map<String, AttributeValue> toMap() {
return attributeValueMap.getValue();
}
private Map<String, AttributeValue> initializeAttributeValueMap() {
Map<String, AttributeValue> result = new LinkedHashMap<>(this.nonAttributeValueMap.size());
this.nonAttributeValueMap.forEach((k, v) -> {
if (v == null) {
result.put(k, NULL_ATTRIBUTE_VALUE);
} else {
result.put(k, toAttributeValue(v, enhancedTypeMap.getOrDefault(k, EnhancedType.of(v.getClass()))));
}
});
return result;
}
private <T> AttributeValue toAttributeValue(T value, EnhancedType<T> enhancedType) {
if (value instanceof AttributeValue) {
return (AttributeValue) value;
}
return converterForClass(enhancedType, attributeConverterChain).transformFrom(value);
}
private <T> T fromAttributeValue(AttributeValue attributeValue, EnhancedType<T> type) {
if (type.rawClass().equals(AttributeValue.class)) {
return (T) attributeValue;
}
return converterForClass(type, attributeConverterChain).transformTo(attributeValue);
}
public static class DefaultBuilder implements EnhancedDocument.Builder {
Map<String, Object> nonAttributeValueMap = new LinkedHashMap<>();
Map<String, EnhancedType> enhancedTypeMap = new HashMap<>();
List<AttributeConverterProvider> attributeConverterProviders = new ArrayList<>();
private DefaultBuilder() {
}
public DefaultBuilder(DefaultEnhancedDocument enhancedDocument) {
this.nonAttributeValueMap = new LinkedHashMap<>(enhancedDocument.nonAttributeValueMap);
this.attributeConverterProviders = new ArrayList<>(enhancedDocument.attributeConverterProviders);
this.enhancedTypeMap = new HashMap<>(enhancedDocument.enhancedTypeMap);
}
public Builder putObject(String attributeName, Object value) {
putObject(attributeName, value, false);
return this;
}
private Builder putObject(String attributeName, Object value, boolean ignoreNullValue) {
if (!ignoreNullValue) {
checkInvalidAttribute(attributeName, value);
} else {
validateAttributeName(attributeName);
}
enhancedTypeMap.remove(attributeName);
nonAttributeValueMap.remove(attributeName);
nonAttributeValueMap.put(attributeName, value);
return this;
}
@Override
public Builder putString(String attributeName, String value) {
return putObject(attributeName, value);
}
@Override
public Builder putNumber(String attributeName, Number value) {
return putObject(attributeName, value);
}
@Override
public Builder putBytes(String attributeName, SdkBytes value) {
return putObject(attributeName, value);
}
@Override
public Builder putBoolean(String attributeName, boolean value) {
return putObject(attributeName, Boolean.valueOf(value));
}
@Override
public Builder putNull(String attributeName) {
return putObject(attributeName, null, true);
}
@Override
public Builder putStringSet(String attributeName, Set<String> values) {
checkInvalidAttribute(attributeName, values);
if (values.stream().anyMatch(Objects::isNull)) {
throw NULL_SET_ERROR.getValue();
}
return put(attributeName, values, EnhancedType.setOf(String.class));
}
@Override
public Builder putNumberSet(String attributeName, Set<Number> values) {
checkInvalidAttribute(attributeName, values);
Set<SdkNumber> sdkNumberSet =
values.stream().map(number -> {
if (number == null) {
throw NULL_SET_ERROR.getValue();
}
return SdkNumber.fromString(number.toString());
}).collect(Collectors.toCollection(LinkedHashSet::new));
return put(attributeName, sdkNumberSet, EnhancedType.setOf(SdkNumber.class));
}
@Override
public Builder putBytesSet(String attributeName, Set<SdkBytes> values) {
checkInvalidAttribute(attributeName, values);
if (values.stream().anyMatch(Objects::isNull)) {
throw NULL_SET_ERROR.getValue();
}
return put(attributeName, values, EnhancedType.setOf(SdkBytes.class));
}
@Override
public <T> Builder putList(String attributeName, List<T> value, EnhancedType<T> type) {
checkInvalidAttribute(attributeName, value);
Validate.paramNotNull(type, "type");
return put(attributeName, value, EnhancedType.listOf(type));
}
@Override
public <T> Builder put(String attributeName, T value, EnhancedType<T> type) {
checkInvalidAttribute(attributeName, value);
Validate.notNull(attributeName, "attributeName cannot be null.");
enhancedTypeMap.put(attributeName, type);
nonAttributeValueMap.remove(attributeName);
nonAttributeValueMap.put(attributeName, value);
return this;
}
@Override
public <T> Builder put(String attributeName, T value, Class<T> type) {
checkAndValidateClass(type, true);
put(attributeName, value, EnhancedType.of(type));
return this;
}
@Override
public <K, V> Builder putMap(String attributeName, Map<K, V> value, EnhancedType<K> keyType,
EnhancedType<V> valueType) {
checkInvalidAttribute(attributeName, value);
Validate.notNull(attributeName, "attributeName cannot be null.");
Validate.paramNotNull(keyType, "keyType");
Validate.paramNotNull(valueType, "valueType");
return put(attributeName, value, EnhancedType.mapOf(keyType, valueType));
}
@Override
public Builder putJson(String attributeName, String json) {
checkInvalidAttribute(attributeName, json);
return putObject(attributeName, getAttributeValueFromJson(json));
}
@Override
public Builder remove(String attributeName) {
Validate.isTrue(!StringUtils.isEmpty(attributeName), "Attribute name must not be null or empty");
nonAttributeValueMap.remove(attributeName);
return this;
}
@Override
public Builder addAttributeConverterProvider(AttributeConverterProvider attributeConverterProvider) {
Validate.paramNotNull(attributeConverterProvider, "attributeConverterProvider");
attributeConverterProviders.add(attributeConverterProvider);
return this;
}
@Override
public Builder attributeConverterProviders(List<AttributeConverterProvider> attributeConverterProviders) {
Validate.paramNotNull(attributeConverterProviders, "attributeConverterProviders");
this.attributeConverterProviders.clear();
this.attributeConverterProviders.addAll(attributeConverterProviders);
return this;
}
@Override
public Builder attributeConverterProviders(AttributeConverterProvider... attributeConverterProviders) {
Validate.paramNotNull(attributeConverterProviders, "attributeConverterProviders");
return attributeConverterProviders(Arrays.asList(attributeConverterProviders));
}
@Override
public Builder json(String json) {
Validate.paramNotNull(json, "json");
AttributeValue attributeValue = getAttributeValueFromJson(json);
if (attributeValue != null && attributeValue.hasM()) {
nonAttributeValueMap = new LinkedHashMap<>(attributeValue.m());
}
return this;
}
@Override
public Builder attributeValueMap(Map<String, AttributeValue> attributeValueMap) {
Validate.paramNotNull(attributeConverterProviders, "attributeValueMap");
nonAttributeValueMap.clear();
attributeValueMap.forEach(this::putObject);
return this;
}
@Override
public EnhancedDocument build() {
return new DefaultEnhancedDocument(this);
}
private static AttributeValue getAttributeValueFromJson(String json) {
JsonNodeParser build = JsonNodeParser.builder().build();
JsonNode jsonNode = build.parse(json);
if (jsonNode == null) {
throw new IllegalArgumentException("Could not parse argument json " + json);
}
return JSON_ATTRIBUTE_CONVERTER.transformFrom(jsonNode);
}
private static void checkInvalidAttribute(String attributeName, Object value) {
validateAttributeName(attributeName);
Validate.notNull(value, "Value for %s must not be null. Use putNull API to insert a Null value", attributeName);
}
private static void validateAttributeName(String attributeName) {
Validate.isTrue(attributeName != null && !attributeName.trim().isEmpty(),
"Attribute name must not be null or empty.");
}
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DefaultEnhancedDocument that = (DefaultEnhancedDocument) o;
return nonAttributeValueMap.equals(that.nonAttributeValueMap) && Objects.equals(enhancedTypeMap, that.enhancedTypeMap)
&& Objects.equals(attributeValueMap, that.attributeValueMap) && Objects.equals(attributeConverterProviders,
that.attributeConverterProviders)
&& attributeConverterChain.equals(that.attributeConverterChain);
}
@Override
public int hashCode() {
int result = nonAttributeValueMap != null ? nonAttributeValueMap.hashCode() : 0;
result = 31 * result + (attributeConverterProviders != null ? attributeConverterProviders.hashCode() : 0);
return result;
}
private static void checkAndValidateClass(Class<?> type, boolean isPut) {
Validate.paramNotNull(type, "type");
Validate.isTrue(!type.isAssignableFrom(List.class),
String.format(VALIDATE_TYPE_ERROR, "List", isPut ? "put" : "get", "List"));
Validate.isTrue(!type.isAssignableFrom(Map.class),
String.format(VALIDATE_TYPE_ERROR, "Map", isPut ? "put" : "get", "Map"));
}
} | 4,544 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/document/JsonStringFormatHelper.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.document;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.protocols.jsoncore.JsonNode;
@SdkInternalApi
public final class JsonStringFormatHelper {
private JsonStringFormatHelper() {
}
/**
* Helper function to convert a JsonNode to Json String representation
*
* @param jsonNode The JsonNode that needs to be converted to Json String.
* @return Json String of Json Node.
*/
public static String stringValue(JsonNode jsonNode) {
if (jsonNode.isArray()) {
return StreamSupport.stream(jsonNode.asArray().spliterator(), false)
.map(JsonStringFormatHelper::stringValue)
.collect(Collectors.joining(",", "[", "]"));
}
if (jsonNode.isObject()) {
return mapToString(jsonNode);
}
return jsonNode.isString() ? "\"" + addEscapeCharacters(jsonNode.text()) + "\"" : jsonNode.toString();
}
/**
* Escapes characters for a give given string
*
* @param input Input string
* @return String with escaped characters.
*/
public static String addEscapeCharacters(String input) {
StringBuilder output = new StringBuilder();
for (int i = 0; i < input.length(); i++) {
char ch = input.charAt(i);
switch (ch) {
case '\\':
output.append("\\\\"); // escape backslash with a backslash
break;
case '\n':
output.append("\\n"); // newline character
break;
case '\r':
output.append("\\r"); // carriage return character
break;
case '\t':
output.append("\\t"); // tab character
break;
case '\f':
output.append("\\f"); // form feed
break;
case '\"':
output.append("\\\""); // double-quote character
break;
default:
output.append(ch);
break;
}
}
return output.toString();
}
private static String mapToString(JsonNode jsonNode) {
Map<String, JsonNode> value = jsonNode.asObject();
if (value.isEmpty()) {
return "{}";
}
StringBuilder output = new StringBuilder();
output.append("{");
value.forEach((k, v) -> output.append("\"").append(k).append("\":")
.append(stringValue(v)).append(","));
output.setCharAt(output.length() - 1, '}');
return output.toString();
}
}
| 4,545 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/operations/ScanOperation.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.operations;
import java.util.Map;
import java.util.function.Function;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.async.SdkPublisher;
import software.amazon.awssdk.core.pagination.sync.SdkIterable;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClientExtension;
import software.amazon.awssdk.enhanced.dynamodb.Expression;
import software.amazon.awssdk.enhanced.dynamodb.OperationContext;
import software.amazon.awssdk.enhanced.dynamodb.TableMetadata;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.internal.EnhancedClientUtils;
import software.amazon.awssdk.enhanced.dynamodb.internal.ProjectionExpression;
import software.amazon.awssdk.enhanced.dynamodb.model.Page;
import software.amazon.awssdk.enhanced.dynamodb.model.ScanEnhancedRequest;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.ScanRequest;
import software.amazon.awssdk.services.dynamodb.model.ScanResponse;
@SdkInternalApi
public class ScanOperation<T> implements PaginatedTableOperation<T, ScanRequest, ScanResponse>,
PaginatedIndexOperation<T, ScanRequest, ScanResponse> {
private final ScanEnhancedRequest request;
private ScanOperation(ScanEnhancedRequest request) {
this.request = request;
}
public static <T> ScanOperation<T> create(ScanEnhancedRequest request) {
return new ScanOperation<>(request);
}
@Override
public OperationName operationName() {
return OperationName.SCAN;
}
@Override
public ScanRequest generateRequest(TableSchema<T> tableSchema,
OperationContext operationContext,
DynamoDbEnhancedClientExtension extension) {
Map<String, AttributeValue> expressionValues = null;
Map<String, String> expressionNames = null;
if (this.request.filterExpression() != null) {
expressionValues = this.request.filterExpression().expressionValues();
expressionNames = this.request.filterExpression().expressionNames();
}
String projectionExpressionAsString = null;
if (this.request.attributesToProject() != null) {
ProjectionExpression attributesToProject = ProjectionExpression.create(this.request.nestedAttributesToProject());
projectionExpressionAsString = attributesToProject.projectionExpressionAsString().orElse(null);
expressionNames = Expression.joinNames(expressionNames, attributesToProject.expressionAttributeNames());
}
ScanRequest.Builder scanRequest = ScanRequest.builder()
.tableName(operationContext.tableName())
.limit(this.request.limit())
.segment(this.request.segment())
.totalSegments(this.request.totalSegments())
.exclusiveStartKey(this.request.exclusiveStartKey())
.consistentRead(this.request.consistentRead())
.returnConsumedCapacity(this.request.returnConsumedCapacity())
.expressionAttributeValues(expressionValues)
.expressionAttributeNames(expressionNames)
.projectionExpression(projectionExpressionAsString);
if (!TableMetadata.primaryIndexName().equals(operationContext.indexName())) {
scanRequest = scanRequest.indexName(operationContext.indexName());
}
if (this.request.filterExpression() != null) {
scanRequest = scanRequest.filterExpression(this.request.filterExpression().expression());
}
return scanRequest.build();
}
@Override
public Page<T> transformResponse(ScanResponse response,
TableSchema<T> tableSchema,
OperationContext context,
DynamoDbEnhancedClientExtension dynamoDbEnhancedClientExtension) {
return EnhancedClientUtils.readAndTransformPaginatedItems(response,
tableSchema,
context,
dynamoDbEnhancedClientExtension,
ScanResponse::items,
ScanResponse::lastEvaluatedKey,
ScanResponse::count,
ScanResponse::scannedCount,
ScanResponse::consumedCapacity);
}
@Override
public Function<ScanRequest, SdkIterable<ScanResponse>> serviceCall(DynamoDbClient dynamoDbClient) {
return dynamoDbClient::scanPaginator;
}
@Override
public Function<ScanRequest, SdkPublisher<ScanResponse>> asyncServiceCall(DynamoDbAsyncClient dynamoDbAsyncClient) {
return dynamoDbAsyncClient::scanPaginator;
}
}
| 4,546 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/operations/TransactableWriteOperation.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.operations;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClientExtension;
import software.amazon.awssdk.enhanced.dynamodb.OperationContext;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
@SdkInternalApi
public interface TransactableWriteOperation<T> {
TransactWriteItem generateTransactWriteItem(TableSchema<T> tableSchema,
OperationContext operationContext,
DynamoDbEnhancedClientExtension dynamoDbEnhancedClientExtension);
}
| 4,547 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/operations/PutItemOperation.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.operations;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClientExtension;
import software.amazon.awssdk.enhanced.dynamodb.Expression;
import software.amazon.awssdk.enhanced.dynamodb.OperationContext;
import software.amazon.awssdk.enhanced.dynamodb.TableMetadata;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.extensions.WriteModification;
import software.amazon.awssdk.enhanced.dynamodb.internal.EnhancedClientUtils;
import software.amazon.awssdk.enhanced.dynamodb.internal.extensions.DefaultDynamoDbExtensionContext;
import software.amazon.awssdk.enhanced.dynamodb.model.PutItemEnhancedRequest;
import software.amazon.awssdk.enhanced.dynamodb.model.PutItemEnhancedResponse;
import software.amazon.awssdk.enhanced.dynamodb.model.TransactPutItemEnhancedRequest;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.Put;
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
import software.amazon.awssdk.services.dynamodb.model.PutItemResponse;
import software.amazon.awssdk.services.dynamodb.model.PutRequest;
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
import software.amazon.awssdk.services.dynamodb.model.WriteRequest;
import software.amazon.awssdk.utils.Either;
@SdkInternalApi
public class PutItemOperation<T>
implements BatchableWriteOperation<T>,
TransactableWriteOperation<T>,
TableOperation<T, PutItemRequest, PutItemResponse, PutItemEnhancedResponse<T>> {
private final Either<PutItemEnhancedRequest<T>, TransactPutItemEnhancedRequest<T>> request;
private PutItemOperation(PutItemEnhancedRequest<T> request) {
this.request = Either.left(request);
}
private PutItemOperation(TransactPutItemEnhancedRequest<T> request) {
this.request = Either.right(request);
}
public static <T> PutItemOperation<T> create(PutItemEnhancedRequest<T> request) {
return new PutItemOperation<>(request);
}
public static <T> PutItemOperation<T> create(TransactPutItemEnhancedRequest<T> request) {
return new PutItemOperation<>(request);
}
@Override
public OperationName operationName() {
return OperationName.PUT_ITEM;
}
@Override
public PutItemRequest generateRequest(TableSchema<T> tableSchema,
OperationContext operationContext,
DynamoDbEnhancedClientExtension extension) {
if (!TableMetadata.primaryIndexName().equals(operationContext.indexName())) {
throw new IllegalArgumentException("PutItem cannot be executed against a secondary index.");
}
TableMetadata tableMetadata = tableSchema.tableMetadata();
// Fail fast if required primary partition key does not exist and avoid the call to DynamoDb
tableMetadata.primaryPartitionKey();
boolean alwaysIgnoreNulls = true;
T item = request.map(PutItemEnhancedRequest::item, TransactPutItemEnhancedRequest::item);
Map<String, AttributeValue> itemMap = tableSchema.itemToMap(item, alwaysIgnoreNulls);
WriteModification transformation =
extension != null ? extension.beforeWrite(
DefaultDynamoDbExtensionContext.builder()
.items(itemMap)
.operationContext(operationContext)
.tableMetadata(tableMetadata)
.tableSchema(tableSchema)
.operationName(operationName())
.build())
: null;
if (transformation != null && transformation.transformedItem() != null) {
itemMap = transformation.transformedItem();
}
PutItemRequest.Builder requestBuilder = PutItemRequest.builder()
.tableName(operationContext.tableName())
.item(itemMap);
if (request.left().isPresent()) {
requestBuilder = addPlainPutItemParameters(requestBuilder, request.left().get());
}
requestBuilder = addExpressionsIfExist(requestBuilder, transformation);
return requestBuilder.build();
}
@Override
public PutItemEnhancedResponse<T> transformResponse(PutItemResponse response,
TableSchema<T> tableSchema,
OperationContext operationContext,
DynamoDbEnhancedClientExtension extension) {
T attributes = null;
if (response.hasAttributes()) {
attributes = EnhancedClientUtils.readAndTransformSingleItem(response.attributes(), tableSchema, operationContext,
extension);
}
return PutItemEnhancedResponse.<T>builder(null)
.attributes(attributes)
.consumedCapacity(response.consumedCapacity())
.itemCollectionMetrics(response.itemCollectionMetrics())
.build();
}
@Override
public Function<PutItemRequest, PutItemResponse> serviceCall(DynamoDbClient dynamoDbClient) {
return dynamoDbClient::putItem;
}
@Override
public Function<PutItemRequest, CompletableFuture<PutItemResponse>> asyncServiceCall(
DynamoDbAsyncClient dynamoDbAsyncClient) {
return dynamoDbAsyncClient::putItem;
}
@Override
public WriteRequest generateWriteRequest(TableSchema<T> tableSchema,
OperationContext operationContext,
DynamoDbEnhancedClientExtension extension) {
PutItemRequest putItemRequest = generateRequest(tableSchema, operationContext, extension);
if (putItemRequest.conditionExpression() != null) {
throw new IllegalArgumentException("A mapper extension inserted a conditionExpression in a PutItem "
+ "request as part of a BatchWriteItemRequest. This is not supported by "
+ "DynamoDb. An extension known to do this is the "
+ "VersionedRecordExtension which is loaded by default unless overridden. "
+ "To fix this use a table schema that does not "
+ "have a versioned attribute in it or do not load the offending extension.");
}
return WriteRequest.builder().putRequest(PutRequest.builder().item(putItemRequest.item()).build()).build();
}
@Override
public TransactWriteItem generateTransactWriteItem(TableSchema<T> tableSchema,
OperationContext operationContext,
DynamoDbEnhancedClientExtension dynamoDbEnhancedClientExtension) {
PutItemRequest putItemRequest = generateRequest(tableSchema, operationContext, dynamoDbEnhancedClientExtension);
Put.Builder builder = Put.builder()
.item(putItemRequest.item())
.tableName(putItemRequest.tableName())
.conditionExpression(putItemRequest.conditionExpression())
.expressionAttributeValues(putItemRequest.expressionAttributeValues())
.expressionAttributeNames(putItemRequest.expressionAttributeNames());
request.right()
.map(TransactPutItemEnhancedRequest::returnValuesOnConditionCheckFailureAsString)
.ifPresent(builder::returnValuesOnConditionCheckFailure);
return TransactWriteItem.builder()
.put(builder.build())
.build();
}
private PutItemRequest.Builder addExpressionsIfExist(PutItemRequest.Builder requestBuilder,
WriteModification transformation) {
Expression originalConditionExpression = request.map(r -> Optional.ofNullable(r.conditionExpression()),
r -> Optional.ofNullable(r.conditionExpression()))
.orElse(null);
Expression mergedConditionExpression;
if (transformation != null && transformation.additionalConditionalExpression() != null) {
mergedConditionExpression = Expression.join(originalConditionExpression,
transformation.additionalConditionalExpression(), " AND ");
} else {
mergedConditionExpression = originalConditionExpression;
}
if (mergedConditionExpression != null) {
requestBuilder = requestBuilder.conditionExpression(mergedConditionExpression.expression());
// Avoiding adding empty collections that the low level SDK will propagate to DynamoDb where it causes error.
if (mergedConditionExpression.expressionValues() != null && !mergedConditionExpression.expressionValues().isEmpty()) {
requestBuilder = requestBuilder.expressionAttributeValues(mergedConditionExpression.expressionValues());
}
if (mergedConditionExpression.expressionNames() != null && !mergedConditionExpression.expressionNames().isEmpty()) {
requestBuilder = requestBuilder.expressionAttributeNames(mergedConditionExpression.expressionNames());
}
}
return requestBuilder;
}
private PutItemRequest.Builder addPlainPutItemParameters(PutItemRequest.Builder requestBuilder,
PutItemEnhancedRequest<?> enhancedRequest) {
requestBuilder = requestBuilder.returnValues(enhancedRequest.returnValuesAsString());
requestBuilder = requestBuilder.returnConsumedCapacity(enhancedRequest.returnConsumedCapacityAsString());
requestBuilder = requestBuilder.returnItemCollectionMetrics(enhancedRequest.returnItemCollectionMetricsAsString());
return requestBuilder;
}
}
| 4,548 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/operations/PaginatedTableOperation.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.operations;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClientExtension;
import software.amazon.awssdk.enhanced.dynamodb.OperationContext;
import software.amazon.awssdk.enhanced.dynamodb.TableMetadata;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.model.PageIterable;
import software.amazon.awssdk.enhanced.dynamodb.model.PagePublisher;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
/**
* Interface for an operation that can be executed against a mapped database table and is expected to return a
* paginated list of results. These operations will be executed against the primary index of the table. Typically,
* each page of results that is served will automatically perform an additional service call to DynamoDb to retrieve
* the next set of results.
* <p>
* A concrete implementation of this interface should also implement {@link PaginatedIndexOperation} with the same
* types if the operation supports being executed against both the primary index and secondary indices.
*
* @param <ItemT> The modelled object that this table maps records to.
* @param <RequestT> The type of the request object for the DynamoDb call in the low level {@link DynamoDbClient}.
* @param <ResponseT> The type of the response object for the DynamoDb call in the low level {@link DynamoDbClient}.
*/
@SdkInternalApi
public interface PaginatedTableOperation<ItemT, RequestT, ResponseT>
extends PaginatedOperation<ItemT, RequestT, ResponseT> {
/**
* Default implementation of a complete synchronous execution of this operation against the primary index. It will
* construct a context based on the given table name and then call execute() on the {@link PaginatedOperation}
* interface to perform the operation.
*
* @param tableSchema A {@link TableSchema} that maps the table to a modelled object.
* @param tableName The physical name of the table to execute the operation against.
* @param dynamoDbClient A {@link DynamoDbClient} to make the call against.
* @param extension A {@link DynamoDbEnhancedClientExtension} that may modify the request or result of this operation. A
* null value here will result in no modifications.
* @return A high level result object as specified by the implementation of this operation.
*/
default PageIterable<ItemT> executeOnPrimaryIndex(TableSchema<ItemT> tableSchema,
String tableName,
DynamoDbEnhancedClientExtension extension,
DynamoDbClient dynamoDbClient) {
OperationContext context = DefaultOperationContext.create(tableName, TableMetadata.primaryIndexName());
return execute(tableSchema, context, extension, dynamoDbClient);
}
/**
* Default implementation of a complete non-blocking asynchronous execution of this operation against the primary
* index. It will construct a context based on the given table name and then call executeAsync() on the
* {@link PaginatedOperation} interface to perform the operation.
*
* @param tableSchema A {@link TableSchema} that maps the table to a modelled object.
* @param tableName The physical name of the table to execute the operation against.
* @param dynamoDbAsyncClient A {@link DynamoDbAsyncClient} to make the call against.
* @param extension A {@link DynamoDbEnhancedClientExtension} that may modify the request or result of this operation. A
* null value here will result in no modifications.
* @return A high level result object as specified by the implementation of this operation.
*/
default PagePublisher<ItemT> executeOnPrimaryIndexAsync(TableSchema<ItemT> tableSchema,
String tableName,
DynamoDbEnhancedClientExtension extension,
DynamoDbAsyncClient dynamoDbAsyncClient) {
OperationContext context = DefaultOperationContext.create(tableName, TableMetadata.primaryIndexName());
return executeAsync(tableSchema, context, extension, dynamoDbAsyncClient);
}
/**
* The type, or name, of the operation.
*/
OperationName operationName();
}
| 4,549 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/operations/PaginatedOperation.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.operations;
import java.util.function.Function;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.async.SdkPublisher;
import software.amazon.awssdk.core.pagination.sync.SdkIterable;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbAsyncIndex;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbAsyncTable;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClientExtension;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbIndex;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable;
import software.amazon.awssdk.enhanced.dynamodb.OperationContext;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.internal.TransformIterable;
import software.amazon.awssdk.enhanced.dynamodb.model.Page;
import software.amazon.awssdk.enhanced.dynamodb.model.PageIterable;
import software.amazon.awssdk.enhanced.dynamodb.model.PagePublisher;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
/**
* Common interface for an operation that can be executed in a synchronous or non-blocking asynchronous fashion
* against a mapped database table and is expected to return a paginated list of results. These operations can be made
* against either the primary index of a table or a secondary index, although some implementations of this interface
* do not support secondary indices and will throw an exception when executed against one. Typically, each page of
* results that is served will automatically perform an additional service call to DynamoDb to retrieve the next set
* of results.
* <p>
* This interface is extended by {@link PaginatedTableOperation} and {@link PaginatedIndexOperation} which contain
* implementations of the behavior to actually execute the operation in the context of a table or secondary index and
* are used by {@link DynamoDbTable} or {@link DynamoDbAsyncTable} and {@link DynamoDbIndex} or {@link DynamoDbAsyncIndex}
* respectively. By sharing this common interface operations are able to re-use code regardless of whether they are
* executed in the context of a primary or secondary index or whether they are being executed in a synchronous or
* non-blocking asynchronous fashion.
*
* @param <ItemT> The modelled object that this table maps records to.
* @param <RequestT> The type of the request object for the DynamoDb call in the low level {@link DynamoDbClient} or
* {@link DynamoDbAsyncClient}.
* @param <ResponseT> The type of the response object for the DynamoDb call in the low level {@link DynamoDbClient}
* or {@link DynamoDbAsyncClient}.
*/
@SdkInternalApi
public interface PaginatedOperation<ItemT, RequestT, ResponseT> {
/**
* This method generates the request that needs to be sent to a low level {@link DynamoDbClient}.
* @param tableSchema A {@link TableSchema} that maps the table to a modelled object.
* @param context An object containing the context, or target, of the command execution.
* @param extension A {@link DynamoDbEnhancedClientExtension} that may modify the request of this operation. A null
* value here will result in no modifications.
* @return A request that can be used as an argument to a {@link DynamoDbClient} call to perform the operation.
*/
RequestT generateRequest(TableSchema<ItemT> tableSchema, OperationContext context,
DynamoDbEnhancedClientExtension extension);
/**
* Provides a function for making the low level synchronous SDK call to DynamoDb.
* @param dynamoDbClient A low level {@link DynamoDbClient} to make the call against.
* @return A function that calls a paginated DynamoDb operation with a provided request object and returns the
* response object.
*/
Function<RequestT, SdkIterable<ResponseT>> serviceCall(DynamoDbClient dynamoDbClient);
/**
* Provides a function for making the low level non-blocking asynchronous SDK call to DynamoDb.
* @param dynamoDbAsyncClient A low level {@link DynamoDbAsyncClient} to make the call against.
* @return A function that calls a paginated DynamoDb operation with a provided request object and returns the
* response object.
*/
Function<RequestT, SdkPublisher<ResponseT>> asyncServiceCall(DynamoDbAsyncClient dynamoDbAsyncClient);
/**
* Takes the response object returned by the actual DynamoDb call and maps it into a higher level abstracted
* result object.
* @param response The response object returned by the DynamoDb call for this operation.
* @param tableSchema A {@link TableSchema} that maps the table to a modelled object.
* @param context An object containing the context, or target, of the command execution.
* @param dynamoDbEnhancedClientExtension A {@link DynamoDbEnhancedClientExtension} that may modify the result of
* this operation. A null value here will result in no modifications.
* @return A high level result object as specified by the implementation of this operation.
*/
Page<ItemT> transformResponse(ResponseT response,
TableSchema<ItemT> tableSchema,
OperationContext context,
DynamoDbEnhancedClientExtension dynamoDbEnhancedClientExtension);
/**
* Default implementation of a complete synchronous execution of this operation against either the primary or a
* secondary index.
* <p>
* It performs three steps:
* <ol>
* <li> Call {@link #generateRequest} to get the request object.</li>
* <li> Call {@link #asyncServiceCall} and call it using the request object generated in the previous step.</li>
* <li> Wraps the {@link SdkIterable} that was returned by the previous step with a transformation that turns each
* object returned to a high level result.</li>
* </ol>
*
* @param tableSchema A {@link TableSchema} that maps the table to a modelled object.
* @param context An object containing the context, or target, of the command execution.
* @param dynamoDbClient A {@link DynamoDbClient} to make the call against.
* @param extension A {@link DynamoDbEnhancedClientExtension} that may modify the request or result of this
* operation. A null value here will result in no modifications.
* @return A high level result object as specified by the implementation of this operation.
*/
default PageIterable<ItemT> execute(TableSchema<ItemT> tableSchema,
OperationContext context,
DynamoDbEnhancedClientExtension extension,
DynamoDbClient dynamoDbClient) {
RequestT request = generateRequest(tableSchema, context, extension);
SdkIterable<ResponseT> response = serviceCall(dynamoDbClient).apply(request);
SdkIterable<Page<ItemT>> pageIterables =
TransformIterable.of(response, r -> transformResponse(r, tableSchema, context, extension));
return PageIterable.create(pageIterables);
}
/**
* Default implementation of a complete non-blocking asynchronous execution of this operation against either the
* primary or a secondary index.
* <p>
* It performs three steps:
* <ol>
* <li> Call {@link #generateRequest} to get the request object.
* <li> Call {@link #asyncServiceCall} and call it using the request object generated in the previous step.
* <li> Wraps the {@link SdkPublisher} returned by the SDK in a new one that calls transformResponse() to
* convert the response objects published to a high level result.
* </ol>
*
* @param tableSchema A {@link TableSchema} that maps the table to a modelled object.
* @param context An object containing the context, or target, of the command execution.
* @param dynamoDbAsyncClient A {@link DynamoDbAsyncClient} to make the call against.
* @param extension A {@link DynamoDbEnhancedClientExtension} that may modify the request or result of this
* operation. A null value here will result in no modifications.
* @return An {@link SdkPublisher} that will publish pages of the high level result object as specified by the
* implementation of this operation.
*/
default PagePublisher<ItemT> executeAsync(TableSchema<ItemT> tableSchema,
OperationContext context,
DynamoDbEnhancedClientExtension extension,
DynamoDbAsyncClient dynamoDbAsyncClient) {
RequestT request = generateRequest(tableSchema, context, extension);
SdkPublisher<ResponseT> response = asyncServiceCall(dynamoDbAsyncClient).apply(request);
return PagePublisher.create(response.map(r -> transformResponse(r, tableSchema, context, extension)));
}
}
| 4,550 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/operations/CreateTableOperation.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.operations;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import java.util.stream.Collectors;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClientExtension;
import software.amazon.awssdk.enhanced.dynamodb.OperationContext;
import software.amazon.awssdk.enhanced.dynamodb.TableMetadata;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.model.CreateTableEnhancedRequest;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition;
import software.amazon.awssdk.services.dynamodb.model.BillingMode;
import software.amazon.awssdk.services.dynamodb.model.CreateTableRequest;
import software.amazon.awssdk.services.dynamodb.model.CreateTableResponse;
import software.amazon.awssdk.services.dynamodb.model.KeySchemaElement;
import software.amazon.awssdk.services.dynamodb.model.KeyType;
@SdkInternalApi
public class CreateTableOperation<T> implements TableOperation<T, CreateTableRequest, CreateTableResponse, Void> {
private final CreateTableEnhancedRequest request;
private CreateTableOperation(CreateTableEnhancedRequest request) {
this.request = request;
}
public static <T> CreateTableOperation<T> create(CreateTableEnhancedRequest request) {
return new CreateTableOperation<>(request);
}
@Override
public OperationName operationName() {
return OperationName.CREATE_TABLE;
}
@Override
public CreateTableRequest generateRequest(TableSchema<T> tableSchema,
OperationContext operationContext,
DynamoDbEnhancedClientExtension extension) {
if (!TableMetadata.primaryIndexName().equals(operationContext.indexName())) {
throw new IllegalArgumentException("PutItem cannot be executed against a secondary index.");
}
String primaryPartitionKey = tableSchema.tableMetadata().primaryPartitionKey();
Optional<String> primarySortKey = tableSchema.tableMetadata().primarySortKey();
Set<String> dedupedIndexKeys = new HashSet<>();
dedupedIndexKeys.add(primaryPartitionKey);
primarySortKey.ifPresent(dedupedIndexKeys::add);
List<software.amazon.awssdk.services.dynamodb.model.GlobalSecondaryIndex> sdkGlobalSecondaryIndices = null;
List<software.amazon.awssdk.services.dynamodb.model.LocalSecondaryIndex> sdkLocalSecondaryIndices = null;
if (this.request.globalSecondaryIndices() != null && !this.request.globalSecondaryIndices().isEmpty()) {
sdkGlobalSecondaryIndices =
this.request.globalSecondaryIndices().stream().map(gsi -> {
String indexPartitionKey = tableSchema.tableMetadata().indexPartitionKey(gsi.indexName());
Optional<String> indexSortKey = tableSchema.tableMetadata().indexSortKey(gsi.indexName());
dedupedIndexKeys.add(indexPartitionKey);
indexSortKey.ifPresent(dedupedIndexKeys::add);
return software.amazon.awssdk.services.dynamodb.model.GlobalSecondaryIndex
.builder()
.indexName(gsi.indexName())
.keySchema(generateKeySchema(indexPartitionKey, indexSortKey.orElse(null)))
.projection(gsi.projection())
.provisionedThroughput(gsi.provisionedThroughput())
.build();
}).collect(Collectors.toList());
}
if (this.request.localSecondaryIndices() != null && !this.request.localSecondaryIndices().isEmpty()) {
sdkLocalSecondaryIndices =
this.request.localSecondaryIndices().stream().map(lsi -> {
Optional<String> indexSortKey = tableSchema.tableMetadata().indexSortKey(lsi.indexName());
indexSortKey.ifPresent(dedupedIndexKeys::add);
if (!primaryPartitionKey.equals(
tableSchema.tableMetadata().indexPartitionKey(lsi.indexName()))) {
throw new IllegalArgumentException("Attempt to create a local secondary index with a partition "
+ "key that is not the primary partition key. Index name: "
+ lsi.indexName());
}
return software.amazon.awssdk.services.dynamodb.model.LocalSecondaryIndex
.builder()
.indexName(lsi.indexName())
.keySchema(generateKeySchema(primaryPartitionKey, indexSortKey.orElse(null)))
.projection(lsi.projection())
.build();
}).collect(Collectors.toList());
}
List<AttributeDefinition> attributeDefinitions =
dedupedIndexKeys.stream()
.map(attribute ->
AttributeDefinition.builder()
.attributeName(attribute)
.attributeType(tableSchema
.tableMetadata().scalarAttributeType(attribute)
.orElseThrow(() ->
new IllegalArgumentException(
"Could not map the key attribute '" + attribute +
"' to a valid scalar type.")))
.build())
.collect(Collectors.toList());
BillingMode billingMode = this.request.provisionedThroughput() == null ?
BillingMode.PAY_PER_REQUEST :
BillingMode.PROVISIONED;
return CreateTableRequest.builder()
.tableName(operationContext.tableName())
.keySchema(generateKeySchema(primaryPartitionKey, primarySortKey.orElse(null)))
.globalSecondaryIndexes(sdkGlobalSecondaryIndices)
.localSecondaryIndexes(sdkLocalSecondaryIndices)
.attributeDefinitions(attributeDefinitions)
.billingMode(billingMode)
.provisionedThroughput(this.request.provisionedThroughput())
.streamSpecification(this.request.streamSpecification())
.build();
}
@Override
public Function<CreateTableRequest, CreateTableResponse> serviceCall(DynamoDbClient dynamoDbClient) {
return dynamoDbClient::createTable;
}
@Override
public Function<CreateTableRequest, CompletableFuture<CreateTableResponse>> asyncServiceCall(
DynamoDbAsyncClient dynamoDbAsyncClient) {
return dynamoDbAsyncClient::createTable;
}
@Override
public Void transformResponse(CreateTableResponse response,
TableSchema<T> tableSchema,
OperationContext operationContext,
DynamoDbEnhancedClientExtension extension) {
// This operation does not return results
return null;
}
private static Collection<KeySchemaElement> generateKeySchema(String partitionKey, String sortKey) {
if (sortKey == null) {
return generateKeySchema(partitionKey);
}
return Collections.unmodifiableList(Arrays.asList(KeySchemaElement.builder()
.attributeName(partitionKey)
.keyType(KeyType.HASH)
.build(),
KeySchemaElement.builder()
.attributeName(sortKey)
.keyType(KeyType.RANGE)
.build()));
}
private static Collection<KeySchemaElement> generateKeySchema(String partitionKey) {
return Collections.singletonList(KeySchemaElement.builder()
.attributeName(partitionKey)
.keyType(KeyType.HASH)
.build());
}
}
| 4,551 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/operations/DeleteTableOperation.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.operations;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClientExtension;
import software.amazon.awssdk.enhanced.dynamodb.OperationContext;
import software.amazon.awssdk.enhanced.dynamodb.TableMetadata;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest;
import software.amazon.awssdk.services.dynamodb.model.DeleteTableResponse;
@SdkInternalApi
public class DeleteTableOperation<T> implements TableOperation<T, DeleteTableRequest, DeleteTableResponse, Void> {
public static <T> DeleteTableOperation<T> create() {
return new DeleteTableOperation<>();
}
@Override
public OperationName operationName() {
return OperationName.DELETE_ITEM;
}
@Override
public DeleteTableRequest generateRequest(TableSchema<T> tableSchema,
OperationContext operationContext,
DynamoDbEnhancedClientExtension extension) {
if (!TableMetadata.primaryIndexName().equals(operationContext.indexName())) {
throw new IllegalArgumentException("DeleteTable cannot be executed against a secondary index.");
}
return DeleteTableRequest.builder()
.tableName(operationContext.tableName())
.build();
}
@Override
public Function<DeleteTableRequest, DeleteTableResponse> serviceCall(DynamoDbClient dynamoDbClient) {
return dynamoDbClient::deleteTable;
}
@Override
public Function<DeleteTableRequest, CompletableFuture<DeleteTableResponse>> asyncServiceCall(
DynamoDbAsyncClient dynamoDbAsyncClient) {
return dynamoDbAsyncClient::deleteTable;
}
@Override
public Void transformResponse(DeleteTableResponse response,
TableSchema<T> tableSchema,
OperationContext operationContext,
DynamoDbEnhancedClientExtension extension) {
// This operation does not return results
return null;
}
}
| 4,552 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/operations/BatchWriteItemOperation.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.operations;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClientExtension;
import software.amazon.awssdk.enhanced.dynamodb.model.BatchWriteItemEnhancedRequest;
import software.amazon.awssdk.enhanced.dynamodb.model.BatchWriteResult;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.BatchWriteItemRequest;
import software.amazon.awssdk.services.dynamodb.model.BatchWriteItemResponse;
import software.amazon.awssdk.services.dynamodb.model.WriteRequest;
import software.amazon.awssdk.utils.CollectionUtils;
@SdkInternalApi
public class BatchWriteItemOperation
implements DatabaseOperation<BatchWriteItemRequest, BatchWriteItemResponse, BatchWriteResult> {
private final BatchWriteItemEnhancedRequest request;
private BatchWriteItemOperation(BatchWriteItemEnhancedRequest request) {
this.request = request;
}
public static BatchWriteItemOperation create(BatchWriteItemEnhancedRequest request) {
return new BatchWriteItemOperation(request);
}
@Override
public OperationName operationName() {
return OperationName.BATCH_WRITE_ITEM;
}
@Override
public BatchWriteItemRequest generateRequest(DynamoDbEnhancedClientExtension extension) {
Map<String, List<WriteRequest>> allRequestItems = new HashMap<>();
request.writeBatches().forEach(writeBatch -> {
Collection<WriteRequest> writeRequestsForTable = allRequestItems.computeIfAbsent(
writeBatch.tableName(),
ignored -> new ArrayList<>());
writeRequestsForTable.addAll(writeBatch.writeRequests());
});
return BatchWriteItemRequest.builder()
.requestItems(
Collections.unmodifiableMap(CollectionUtils.deepCopyMap(allRequestItems)))
.build();
}
@Override
public BatchWriteResult transformResponse(BatchWriteItemResponse response,
DynamoDbEnhancedClientExtension extension) {
return BatchWriteResult.builder().unprocessedRequests(response.unprocessedItems()).build();
}
@Override
public Function<BatchWriteItemRequest, BatchWriteItemResponse> serviceCall(DynamoDbClient dynamoDbClient) {
return dynamoDbClient::batchWriteItem;
}
@Override
public Function<BatchWriteItemRequest, CompletableFuture<BatchWriteItemResponse>> asyncServiceCall(
DynamoDbAsyncClient dynamoDbAsyncClient) {
return dynamoDbAsyncClient::batchWriteItem;
}
}
| 4,553 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/operations/BatchableWriteOperation.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.operations;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClientExtension;
import software.amazon.awssdk.enhanced.dynamodb.OperationContext;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.services.dynamodb.model.WriteRequest;
@SdkInternalApi
public interface BatchableWriteOperation<T> {
WriteRequest generateWriteRequest(TableSchema<T> tableSchema,
OperationContext context,
DynamoDbEnhancedClientExtension extension);
}
| 4,554 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/operations/DescribeTableOperation.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.operations;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClientExtension;
import software.amazon.awssdk.enhanced.dynamodb.OperationContext;
import software.amazon.awssdk.enhanced.dynamodb.TableMetadata;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.model.DescribeTableEnhancedResponse;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.DescribeTableRequest;
import software.amazon.awssdk.services.dynamodb.model.DescribeTableResponse;
@SdkInternalApi
public class DescribeTableOperation<T> implements TableOperation<T, DescribeTableRequest, DescribeTableResponse,
DescribeTableEnhancedResponse> {
public static <T> DescribeTableOperation<T> create() {
return new DescribeTableOperation<>();
}
@Override
public OperationName operationName() {
return OperationName.DESCRIBE_TABLE;
}
@Override
public DescribeTableRequest generateRequest(TableSchema<T> tableSchema,
OperationContext operationContext,
DynamoDbEnhancedClientExtension extension) {
if (!TableMetadata.primaryIndexName().equals(operationContext.indexName())) {
throw new IllegalArgumentException("DescribeTable cannot be executed against a secondary index.");
}
return DescribeTableRequest.builder()
.tableName(operationContext.tableName())
.build();
}
@Override
public Function<DescribeTableRequest, DescribeTableResponse> serviceCall(DynamoDbClient dynamoDbClient) {
return dynamoDbClient::describeTable;
}
@Override
public Function<DescribeTableRequest, CompletableFuture<DescribeTableResponse>> asyncServiceCall(
DynamoDbAsyncClient dynamoDbAsyncClient) {
return dynamoDbAsyncClient::describeTable;
}
@Override
public DescribeTableEnhancedResponse transformResponse(DescribeTableResponse response,
TableSchema<T> tableSchema,
OperationContext operationContext,
DynamoDbEnhancedClientExtension extension) {
return DescribeTableEnhancedResponse.builder()
.response(response)
.build();
}
}
| 4,555 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/operations/TransactWriteItemsOperation.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.operations;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClientExtension;
import software.amazon.awssdk.enhanced.dynamodb.model.TransactWriteItemsEnhancedRequest;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItemsRequest;
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItemsResponse;
@SdkInternalApi
public class TransactWriteItemsOperation
implements DatabaseOperation<TransactWriteItemsRequest, TransactWriteItemsResponse, Void> {
private TransactWriteItemsEnhancedRequest request;
private TransactWriteItemsOperation(TransactWriteItemsEnhancedRequest request) {
this.request = request;
}
public static TransactWriteItemsOperation create(TransactWriteItemsEnhancedRequest request) {
return new TransactWriteItemsOperation(request);
}
@Override
public OperationName operationName() {
return OperationName.TRANSACT_WRITE_ITEMS;
}
@Override
public TransactWriteItemsRequest generateRequest(DynamoDbEnhancedClientExtension extension) {
return TransactWriteItemsRequest.builder()
.transactItems(this.request.transactWriteItems())
.clientRequestToken(this.request.clientRequestToken())
.build();
}
@Override
public Void transformResponse(TransactWriteItemsResponse response, DynamoDbEnhancedClientExtension extension) {
return null; // this operation does not return results
}
@Override
public Function<TransactWriteItemsRequest, TransactWriteItemsResponse> serviceCall(
DynamoDbClient dynamoDbClient) {
return dynamoDbClient::transactWriteItems;
}
@Override
public Function<TransactWriteItemsRequest, CompletableFuture<TransactWriteItemsResponse>> asyncServiceCall(
DynamoDbAsyncClient dynamoDbAsyncClient) {
return dynamoDbAsyncClient::transactWriteItems;
}
}
| 4,556 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/operations/DatabaseOperation.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.operations;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClientExtension;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
/**
* Interface for a single operation that can be executed against a mapped database. These operations do not operate
* on a specific table or index, and may reference multiple tables and indexes (eg: batch operations). Conceptually an
* operation maps 1:1 with an actual DynamoDb call.
*
* @param <RequestT> The type of the request object for the DynamoDb call in the low level {@link DynamoDbClient}.
* @param <ResponseT> The type of the response object for the DynamoDb call in the low level {@link DynamoDbClient}.
* @param <ResultT> The type of the mapped result object that will be returned by the execution of this operation.
*/
@SdkInternalApi
public interface DatabaseOperation<RequestT, ResponseT, ResultT> {
/**
* This method generates the request that needs to be sent to a low level {@link DynamoDbClient}.
* @param extension A {@link DynamoDbEnhancedClientExtension} that may modify the request of this operation. A null
* value here will result in no modifications.
* @return A request that can be used as an argument to a {@link DynamoDbClient} call to perform the operation.
*/
RequestT generateRequest(DynamoDbEnhancedClientExtension extension);
/**
* Provides a function for making the low level synchronous SDK call to DynamoDb.
* @param dynamoDbClient A low level {@link DynamoDbClient} to make the call against.
* @return A function that calls DynamoDb with a provided request object and returns the response object.
*/
Function<RequestT, ResponseT> serviceCall(DynamoDbClient dynamoDbClient);
/**
* Provides a function for making the low level non-blocking asynchronous SDK call to DynamoDb.
* @param dynamoDbAsyncClient A low level {@link DynamoDbAsyncClient} to make the call against.
* @return A function that calls DynamoDb with a provided request object and returns a {@link CompletableFuture}
* for the response object.
*/
Function<RequestT, CompletableFuture<ResponseT>> asyncServiceCall(DynamoDbAsyncClient dynamoDbAsyncClient);
/**
* Takes the response object returned by the actual DynamoDb call and maps it into a higher level abstracted
* result object.
* @param response The response object returned by the DynamoDb call for this operation.
* @param extension A {@link DynamoDbEnhancedClientExtension} that may modify the result of this operation. A null
* value here will result in no modifications.
* @return A high level result object as specified by the implementation of this operation.
*/
ResultT transformResponse(ResponseT response, DynamoDbEnhancedClientExtension extension);
/**
* Default implementation of a complete synchronous execution of this operation. It performs three steps:
* 1) Call generateRequest() to get the request object.
* 2) Call getServiceCall() and call it using the request object generated in the previous step.
* 3) Call transformResponse() to convert the response object returned in the previous step to a high level result.
*
* @param dynamoDbClient A {@link DynamoDbClient} to make the call against.
* @param extension A {@link DynamoDbEnhancedClientExtension} that may modify the request or result of this
* operation. A null value here will result in no modifications.
* @return A high level result object as specified by the implementation of this operation.
*/
default ResultT execute(DynamoDbClient dynamoDbClient, DynamoDbEnhancedClientExtension extension) {
RequestT request = generateRequest(extension);
ResponseT response = serviceCall(dynamoDbClient).apply(request);
return transformResponse(response, extension);
}
/**
* Default implementation of a complete non-blocking asynchronous execution of this operation. It performs three
* steps:
* 1) Call generateRequest() to get the request object.
* 2) Call getServiceCall() and call it using the request object generated in the previous step.
* 3) Wraps the {@link CompletableFuture} returned by the SDK in a new one that calls transformResponse() to
* convert the response object returned in the previous step to a high level result.
*
* @param dynamoDbAsyncClient A {@link DynamoDbAsyncClient} to make the call against.
* @param extension A {@link DynamoDbEnhancedClientExtension} that may modify the request or result of this
* operation. A null value here will result in no modifications.
* @return A high level result object as specified by the implementation of this operation.
*/
default CompletableFuture<ResultT> executeAsync(DynamoDbAsyncClient dynamoDbAsyncClient,
DynamoDbEnhancedClientExtension extension) {
RequestT request = generateRequest(extension);
CompletableFuture<ResponseT> response = asyncServiceCall(dynamoDbAsyncClient).apply(request);
return response.thenApply(r -> transformResponse(r, extension));
}
/**
* The type, or name, of the operation.
*/
OperationName operationName();
}
| 4,557 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/operations/TableOperation.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.operations;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClientExtension;
import software.amazon.awssdk.enhanced.dynamodb.OperationContext;
import software.amazon.awssdk.enhanced.dynamodb.TableMetadata;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
/**
* Interface for a single operation that can be executed against a mapped database table. These operations will be
* executed against the primary index of the table. Conceptually an operation maps 1:1 with an actual DynamoDb call.
* <p>
* A concrete implementation of this interface should also implement {@link IndexOperation} with the same types if
* the operation supports being executed against both the primary index and secondary indices.
*
* @param <ItemT> The modelled object that this table maps records to.
* @param <RequestT> The type of the request object for the DynamoDb call in the low level {@link DynamoDbClient}.
* @param <ResponseT> The type of the response object for the DynamoDb call in the low level {@link DynamoDbClient}.
* @param <ResultT> The type of the mapped result object that will be returned by the execution of this operation.
*/
@SdkInternalApi
public interface TableOperation<ItemT, RequestT, ResponseT, ResultT>
extends CommonOperation<ItemT, RequestT, ResponseT, ResultT> {
/**
* Default implementation of a complete synchronous execution of this operation against the primary index. It will
* construct a context based on the given table name and then call execute() on the {@link CommonOperation} interface to
* perform the operation.
*
* @param tableSchema A {@link TableSchema} that maps the table to a modelled object.
* @param tableName The physical name of the table to execute the operation against.
* @param dynamoDbClient A {@link DynamoDbClient} to make the call against.
* @param extension A {@link DynamoDbEnhancedClientExtension} that may modify the request or result of this
* operation. A null value here will result in no modifications.
* @return A high level result object as specified by the implementation of this operation.
*/
default ResultT executeOnPrimaryIndex(TableSchema<ItemT> tableSchema,
String tableName,
DynamoDbEnhancedClientExtension extension,
DynamoDbClient dynamoDbClient) {
OperationContext context = DefaultOperationContext.create(tableName, TableMetadata.primaryIndexName());
return execute(tableSchema, context, extension, dynamoDbClient);
}
/**
* Default implementation of a complete non-blocking asynchronous execution of this operation against the primary
* index. It will construct a context based on the given table name and then call executeAsync() on the
* {@link CommonOperation} interface to perform the operation.
*
* @param tableSchema A {@link TableSchema} that maps the table to a modelled object.
* @param tableName The physical name of the table to execute the operation against.
* @param dynamoDbAsyncClient A {@link DynamoDbAsyncClient} to make the call against.
* @param extension A {@link DynamoDbEnhancedClientExtension} that may modify the request or result of this
* operation. A null value here will result in no modifications.
* @return A {@link CompletableFuture} of the high level result object as specified by the implementation of this
* operation.
*/
default CompletableFuture<ResultT> executeOnPrimaryIndexAsync(TableSchema<ItemT> tableSchema,
String tableName,
DynamoDbEnhancedClientExtension extension,
DynamoDbAsyncClient dynamoDbAsyncClient) {
OperationContext context = DefaultOperationContext.create(tableName, TableMetadata.primaryIndexName());
return executeAsync(tableSchema, context, extension, dynamoDbAsyncClient);
}
}
| 4,558 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/operations/TransactGetItemsOperation.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.operations;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import java.util.stream.Collectors;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.enhanced.dynamodb.Document;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClientExtension;
import software.amazon.awssdk.enhanced.dynamodb.internal.DefaultDocument;
import software.amazon.awssdk.enhanced.dynamodb.model.TransactGetItemsEnhancedRequest;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.TransactGetItemsRequest;
import software.amazon.awssdk.services.dynamodb.model.TransactGetItemsResponse;
@SdkInternalApi
public class TransactGetItemsOperation
implements DatabaseOperation<TransactGetItemsRequest, TransactGetItemsResponse, List<Document>> {
private TransactGetItemsEnhancedRequest request;
private TransactGetItemsOperation(TransactGetItemsEnhancedRequest request) {
this.request = request;
}
public static TransactGetItemsOperation create(TransactGetItemsEnhancedRequest request) {
return new TransactGetItemsOperation(request);
}
@Override
public OperationName operationName() {
return OperationName.TRANSACT_GET_ITEMS;
}
@Override
public TransactGetItemsRequest generateRequest(DynamoDbEnhancedClientExtension extension) {
return TransactGetItemsRequest.builder()
.transactItems(this.request.transactGetItems())
.build();
}
@Override
public Function<TransactGetItemsRequest, TransactGetItemsResponse> serviceCall(DynamoDbClient dynamoDbClient) {
return dynamoDbClient::transactGetItems;
}
@Override
public Function<TransactGetItemsRequest, CompletableFuture<TransactGetItemsResponse>> asyncServiceCall(
DynamoDbAsyncClient dynamoDbAsyncClient) {
return dynamoDbAsyncClient::transactGetItems;
}
@Override
public List<Document> transformResponse(TransactGetItemsResponse response,
DynamoDbEnhancedClientExtension extension) {
return response.responses()
.stream()
.map(r -> r == null ? null : DefaultDocument.create(r.item()))
.collect(Collectors.toList());
}
}
| 4,559 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/operations/QueryOperation.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.operations;
import java.util.Map;
import java.util.function.Function;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.async.SdkPublisher;
import software.amazon.awssdk.core.pagination.sync.SdkIterable;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClientExtension;
import software.amazon.awssdk.enhanced.dynamodb.Expression;
import software.amazon.awssdk.enhanced.dynamodb.OperationContext;
import software.amazon.awssdk.enhanced.dynamodb.TableMetadata;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.internal.EnhancedClientUtils;
import software.amazon.awssdk.enhanced.dynamodb.internal.ProjectionExpression;
import software.amazon.awssdk.enhanced.dynamodb.model.Page;
import software.amazon.awssdk.enhanced.dynamodb.model.QueryEnhancedRequest;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
import software.amazon.awssdk.services.dynamodb.model.QueryResponse;
@SdkInternalApi
public class QueryOperation<T> implements PaginatedTableOperation<T, QueryRequest, QueryResponse>,
PaginatedIndexOperation<T, QueryRequest, QueryResponse> {
private final QueryEnhancedRequest request;
private QueryOperation(QueryEnhancedRequest request) {
this.request = request;
}
public static <T> QueryOperation<T> create(QueryEnhancedRequest request) {
return new QueryOperation<>(request);
}
@Override
public OperationName operationName() {
return OperationName.QUERY;
}
@Override
public QueryRequest generateRequest(TableSchema<T> tableSchema,
OperationContext operationContext,
DynamoDbEnhancedClientExtension extension) {
Expression queryExpression = this.request.queryConditional().expression(tableSchema, operationContext.indexName());
Map<String, AttributeValue> expressionValues = queryExpression.expressionValues();
Map<String, String> expressionNames = queryExpression.expressionNames();
if (this.request.filterExpression() != null) {
expressionValues = Expression.joinValues(expressionValues, this.request.filterExpression().expressionValues());
expressionNames = Expression.joinNames(expressionNames, this.request.filterExpression().expressionNames());
}
String projectionExpressionAsString = null;
if (this.request.attributesToProject() != null) {
ProjectionExpression attributesToProject = ProjectionExpression.create(this.request.nestedAttributesToProject());
projectionExpressionAsString = attributesToProject.projectionExpressionAsString().orElse(null);
expressionNames = Expression.joinNames(expressionNames, attributesToProject.expressionAttributeNames());
}
QueryRequest.Builder queryRequest = QueryRequest.builder()
.tableName(operationContext.tableName())
.keyConditionExpression(queryExpression.expression())
.expressionAttributeValues(expressionValues)
.expressionAttributeNames(expressionNames)
.scanIndexForward(this.request.scanIndexForward())
.limit(this.request.limit())
.exclusiveStartKey(this.request.exclusiveStartKey())
.consistentRead(this.request.consistentRead())
.returnConsumedCapacity(this.request.returnConsumedCapacity())
.projectionExpression(projectionExpressionAsString);
if (!TableMetadata.primaryIndexName().equals(operationContext.indexName())) {
queryRequest = queryRequest.indexName(operationContext.indexName());
}
if (this.request.filterExpression() != null) {
queryRequest = queryRequest.filterExpression(this.request.filterExpression().expression());
}
return queryRequest.build();
}
@Override
public Function<QueryRequest, SdkIterable<QueryResponse>> serviceCall(DynamoDbClient dynamoDbClient) {
return dynamoDbClient::queryPaginator;
}
@Override
public Function<QueryRequest, SdkPublisher<QueryResponse>> asyncServiceCall(DynamoDbAsyncClient dynamoDbAsyncClient) {
return dynamoDbAsyncClient::queryPaginator;
}
@Override
public Page<T> transformResponse(QueryResponse response,
TableSchema<T> tableSchema,
OperationContext context,
DynamoDbEnhancedClientExtension dynamoDbEnhancedClientExtension) {
return EnhancedClientUtils.readAndTransformPaginatedItems(response,
tableSchema,
context,
dynamoDbEnhancedClientExtension,
QueryResponse::items,
QueryResponse::lastEvaluatedKey,
QueryResponse::count,
QueryResponse::scannedCount,
QueryResponse::consumedCapacity);
}
}
| 4,560 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/operations/OperationName.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.operations;
import software.amazon.awssdk.annotations.SdkInternalApi;
@SdkInternalApi
public enum OperationName {
NONE(null),
BATCH_GET_ITEM("BatchGetItem"),
BATCH_WRITE_ITEM("BatchWriteItem"),
CREATE_TABLE("CreateTable"),
DELETE_ITEM("DeleteItem"),
DELETE_TABLE("DeleteTable"),
DESCRIBE_TABLE("DescribeTable"),
GET_ITEM("GetItem"),
QUERY("Query"),
PUT_ITEM("PutItem"),
SCAN("Scan"),
TRANSACT_GET_ITEMS("TransactGetItems"),
TRANSACT_WRITE_ITEMS("TransactWriteItems"),
UPDATE_ITEM("UpdateItem");
private final String label;
OperationName() {
this.label = null;
}
OperationName(String label) {
this.label = label;
}
public String label() {
return label;
}
}
| 4,561 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/operations/GetItemOperation.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.operations;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClientExtension;
import software.amazon.awssdk.enhanced.dynamodb.Key;
import software.amazon.awssdk.enhanced.dynamodb.OperationContext;
import software.amazon.awssdk.enhanced.dynamodb.TableMetadata;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.internal.EnhancedClientUtils;
import software.amazon.awssdk.enhanced.dynamodb.model.GetItemEnhancedRequest;
import software.amazon.awssdk.enhanced.dynamodb.model.GetItemEnhancedResponse;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.Get;
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
import software.amazon.awssdk.services.dynamodb.model.GetItemResponse;
import software.amazon.awssdk.services.dynamodb.model.TransactGetItem;
@SdkInternalApi
public class GetItemOperation<T> implements TableOperation<T, GetItemRequest, GetItemResponse, GetItemEnhancedResponse<T>>,
BatchableReadOperation,
TransactableReadOperation<T> {
private final GetItemEnhancedRequest request;
private GetItemOperation(GetItemEnhancedRequest request) {
this.request = request;
}
public static <T> GetItemOperation<T> create(GetItemEnhancedRequest request) {
return new GetItemOperation<>(request);
}
@Override
public Boolean consistentRead() {
return this.request.consistentRead();
}
@Override
public Key key() {
return this.request.key();
}
@Override
public OperationName operationName() {
return OperationName.GET_ITEM;
}
@Override
public GetItemRequest generateRequest(TableSchema<T> tableSchema,
OperationContext context,
DynamoDbEnhancedClientExtension extension) {
if (!TableMetadata.primaryIndexName().equals(context.indexName())) {
throw new IllegalArgumentException("GetItem cannot be executed against a secondary index.");
}
return GetItemRequest.builder()
.tableName(context.tableName())
.key(this.request.key().keyMap(tableSchema, context.indexName()))
.consistentRead(this.request.consistentRead())
.returnConsumedCapacity(this.request.returnConsumedCapacityAsString())
.build();
}
@Override
public GetItemEnhancedResponse<T> transformResponse(GetItemResponse response,
TableSchema<T> tableSchema,
OperationContext context,
DynamoDbEnhancedClientExtension extension) {
T attributes = EnhancedClientUtils.readAndTransformSingleItem(response.item(), tableSchema, context, extension);
return GetItemEnhancedResponse.<T>builder()
.attributes(attributes)
.consumedCapacity(response.consumedCapacity())
.build();
}
@Override
public Function<GetItemRequest, GetItemResponse> serviceCall(DynamoDbClient dynamoDbClient) {
return dynamoDbClient::getItem;
}
@Override
public Function<GetItemRequest, CompletableFuture<GetItemResponse>> asyncServiceCall(
DynamoDbAsyncClient dynamoDbAsyncClient) {
return dynamoDbAsyncClient::getItem;
}
@Override
public TransactGetItem generateTransactGetItem(TableSchema<T> tableSchema,
OperationContext operationContext,
DynamoDbEnhancedClientExtension dynamoDbEnhancedClientExtension) {
return TransactGetItem.builder()
.get(Get.builder()
.tableName(operationContext.tableName())
.key(this.request.key().keyMap(tableSchema, operationContext.indexName()))
.build())
.build();
}
}
| 4,562 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/operations/PaginatedIndexOperation.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.operations;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.async.SdkPublisher;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClientExtension;
import software.amazon.awssdk.enhanced.dynamodb.OperationContext;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.model.Page;
import software.amazon.awssdk.enhanced.dynamodb.model.PageIterable;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
/**
* Interface for an operation that can be executed against a secondary index of a mapped database table and is
* expected to return a paginated list of results. Typically, each page of results that is served will automatically
* perform an additional service call to DynamoDb to retrieve the next set of results.
* <p></p>
* A concrete implementation of this interface should also implement {@link PaginatedTableOperation} with the same
* types if the operation supports being executed against both the primary index and secondary indices.
*
* @param <ItemT> The modelled object that this table maps records to.
* @param <RequestT> The type of the request object for the DynamoDb call in the low level {@link DynamoDbClient}.
* @param <ResponseT> The type of the response object for the DynamoDb call in the low level {@link DynamoDbClient}.
*/
@SdkInternalApi
public interface PaginatedIndexOperation<ItemT, RequestT, ResponseT>
extends PaginatedOperation<ItemT, RequestT, ResponseT> {
/**
* Default implementation of a complete synchronous execution of this operation against a secondary index. It will
* construct a context based on the given table name and secondary index name and then call execute() on the
* {@link PaginatedOperation} interface to perform the operation.
*
* @param tableSchema A {@link TableSchema} that maps the table to a modelled object.
* @param tableName The physical name of the table that contains the secondary index to execute the operation
* against.
* @param indexName The physical name of the secondary index to execute the operation against.
* @param dynamoDbClient A {@link DynamoDbClient} to make the call against.
* @param extension A {@link DynamoDbEnhancedClientExtension} that may modify the request or result of this
* operation. A null value here will result in no modifications.
* @return A high level result object as specified by the implementation of this operation.
*/
default PageIterable<ItemT> executeOnSecondaryIndex(TableSchema<ItemT> tableSchema,
String tableName,
String indexName,
DynamoDbEnhancedClientExtension extension,
DynamoDbClient dynamoDbClient) {
OperationContext context = DefaultOperationContext.create(tableName, indexName);
return execute(tableSchema, context, extension, dynamoDbClient);
}
/**
* Default implementation of a complete non-blocking asynchronous execution of this operation against a secondary
* index. It will construct a context based on the given table name and secondary index name and then call
* executeAsync() on the {@link PaginatedOperation} interface to perform the operation.
*
* @param tableSchema A {@link TableSchema} that maps the table to a modelled object.
* @param tableName The physical name of the table that contains the secondary index to execute the operation
* against.
* @param indexName The physical name of the secondary index to execute the operation against.
* @param dynamoDbAsyncClient A {@link DynamoDbAsyncClient} to make the call against.
* @param extension A {@link DynamoDbEnhancedClientExtension} that may modify the request or result of this
* operation. A null value here will result in no modifications.
* @return A high level result object as specified by the implementation of this operation.
*/
default SdkPublisher<Page<ItemT>> executeOnSecondaryIndexAsync(TableSchema<ItemT> tableSchema,
String tableName,
String indexName,
DynamoDbEnhancedClientExtension extension,
DynamoDbAsyncClient dynamoDbAsyncClient) {
OperationContext context = DefaultOperationContext.create(tableName, indexName);
return executeAsync(tableSchema, context, extension, dynamoDbAsyncClient);
}
}
| 4,563 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/operations/TransactableReadOperation.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.operations;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClientExtension;
import software.amazon.awssdk.enhanced.dynamodb.OperationContext;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.services.dynamodb.model.TransactGetItem;
@SdkInternalApi
public interface TransactableReadOperation<T> {
TransactGetItem generateTransactGetItem(TableSchema<T> tableSchema,
OperationContext operationContext,
DynamoDbEnhancedClientExtension dynamoDbEnhancedClientExtension);
}
| 4,564 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/operations/BatchableReadOperation.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.operations;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.enhanced.dynamodb.Key;
@SdkInternalApi
public interface BatchableReadOperation {
Boolean consistentRead();
Key key();
}
| 4,565 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/operations/DeleteItemOperation.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.operations;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClientExtension;
import software.amazon.awssdk.enhanced.dynamodb.Expression;
import software.amazon.awssdk.enhanced.dynamodb.Key;
import software.amazon.awssdk.enhanced.dynamodb.OperationContext;
import software.amazon.awssdk.enhanced.dynamodb.TableMetadata;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.internal.EnhancedClientUtils;
import software.amazon.awssdk.enhanced.dynamodb.model.DeleteItemEnhancedRequest;
import software.amazon.awssdk.enhanced.dynamodb.model.DeleteItemEnhancedResponse;
import software.amazon.awssdk.enhanced.dynamodb.model.TransactDeleteItemEnhancedRequest;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.Delete;
import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
import software.amazon.awssdk.services.dynamodb.model.DeleteItemResponse;
import software.amazon.awssdk.services.dynamodb.model.DeleteRequest;
import software.amazon.awssdk.services.dynamodb.model.ReturnValue;
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
import software.amazon.awssdk.services.dynamodb.model.WriteRequest;
import software.amazon.awssdk.utils.Either;
@SdkInternalApi
public class DeleteItemOperation<T>
implements TableOperation<T, DeleteItemRequest, DeleteItemResponse, DeleteItemEnhancedResponse<T>>,
TransactableWriteOperation<T>,
BatchableWriteOperation<T> {
private final Either<DeleteItemEnhancedRequest, TransactDeleteItemEnhancedRequest> request;
private DeleteItemOperation(DeleteItemEnhancedRequest request) {
this.request = Either.left(request);
}
private DeleteItemOperation(TransactDeleteItemEnhancedRequest request) {
this.request = Either.right(request);
}
public static <T> DeleteItemOperation<T> create(DeleteItemEnhancedRequest request) {
return new DeleteItemOperation<>(request);
}
public static <T> DeleteItemOperation<T> create(TransactDeleteItemEnhancedRequest request) {
return new DeleteItemOperation<>(request);
}
@Override
public OperationName operationName() {
return OperationName.DELETE_ITEM;
}
@Override
public DeleteItemRequest generateRequest(TableSchema<T> tableSchema,
OperationContext operationContext,
DynamoDbEnhancedClientExtension extension) {
if (!TableMetadata.primaryIndexName().equals(operationContext.indexName())) {
throw new IllegalArgumentException("DeleteItem cannot be executed against a secondary index.");
}
Key key = request.map(DeleteItemEnhancedRequest::key, TransactDeleteItemEnhancedRequest::key);
DeleteItemRequest.Builder requestBuilder =
DeleteItemRequest.builder()
.tableName(operationContext.tableName())
.key(key.keyMap(tableSchema, operationContext.indexName()))
.returnValues(ReturnValue.ALL_OLD);
if (request.left().isPresent()) {
requestBuilder = addPlainDeleteItemParameters(requestBuilder, request.left().get());
}
requestBuilder = addExpressionsIfExist(requestBuilder);
return requestBuilder.build();
}
@Override
public DeleteItemEnhancedResponse<T> transformResponse(DeleteItemResponse response,
TableSchema<T> tableSchema,
OperationContext operationContext,
DynamoDbEnhancedClientExtension extension) {
T attributes = EnhancedClientUtils.readAndTransformSingleItem(response.attributes(), tableSchema, operationContext,
extension);
return DeleteItemEnhancedResponse.<T>builder(null)
.attributes(attributes)
.consumedCapacity(response.consumedCapacity())
.itemCollectionMetrics(response.itemCollectionMetrics())
.build();
}
@Override
public Function<DeleteItemRequest, DeleteItemResponse> serviceCall(DynamoDbClient dynamoDbClient) {
return dynamoDbClient::deleteItem;
}
@Override
public Function<DeleteItemRequest, CompletableFuture<DeleteItemResponse>> asyncServiceCall(
DynamoDbAsyncClient dynamoDbAsyncClient) {
return dynamoDbAsyncClient::deleteItem;
}
@Override
public WriteRequest generateWriteRequest(TableSchema<T> tableSchema,
OperationContext operationContext,
DynamoDbEnhancedClientExtension extension) {
DeleteItemRequest deleteItemRequest = generateRequest(tableSchema, operationContext, extension);
return WriteRequest.builder()
.deleteRequest(DeleteRequest.builder().key(deleteItemRequest.key()).build())
.build();
}
@Override
public TransactWriteItem generateTransactWriteItem(TableSchema<T> tableSchema,
OperationContext operationContext,
DynamoDbEnhancedClientExtension dynamoDbEnhancedClientExtension) {
DeleteItemRequest deleteItemRequest = generateRequest(tableSchema, operationContext, dynamoDbEnhancedClientExtension);
Delete.Builder builder = Delete.builder()
.key(deleteItemRequest.key())
.tableName(deleteItemRequest.tableName())
.conditionExpression(deleteItemRequest.conditionExpression())
.expressionAttributeValues(deleteItemRequest.expressionAttributeValues())
.expressionAttributeNames(deleteItemRequest.expressionAttributeNames());
request.right()
.map(TransactDeleteItemEnhancedRequest::returnValuesOnConditionCheckFailureAsString)
.ifPresent(builder::returnValuesOnConditionCheckFailure);
return TransactWriteItem.builder()
.delete(builder.build())
.build();
}
private DeleteItemRequest.Builder addExpressionsIfExist(DeleteItemRequest.Builder requestBuilder) {
Expression conditionExpression = request.map(r -> Optional.ofNullable(r.conditionExpression()),
r -> Optional.ofNullable(r.conditionExpression()))
.orElse(null);
if (conditionExpression != null) {
requestBuilder = requestBuilder.conditionExpression(conditionExpression.expression());
Map<String, String> expressionNames = conditionExpression.expressionNames();
Map<String, AttributeValue> expressionValues = conditionExpression.expressionValues();
// Avoiding adding empty collections that the low level SDK will propagate to DynamoDb where it causes error.
if (expressionNames != null && !expressionNames.isEmpty()) {
requestBuilder = requestBuilder.expressionAttributeNames(expressionNames);
}
if (expressionValues != null && !expressionValues.isEmpty()) {
requestBuilder = requestBuilder.expressionAttributeValues(expressionValues);
}
}
return requestBuilder;
}
private DeleteItemRequest.Builder addPlainDeleteItemParameters(DeleteItemRequest.Builder requestBuilder,
DeleteItemEnhancedRequest enhancedRequest) {
requestBuilder = requestBuilder.returnConsumedCapacity(enhancedRequest.returnConsumedCapacityAsString());
requestBuilder = requestBuilder.returnItemCollectionMetrics(enhancedRequest.returnItemCollectionMetricsAsString());
return requestBuilder;
}
}
| 4,566 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/operations/PaginatedDatabaseOperation.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.operations;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.async.SdkPublisher;
import software.amazon.awssdk.core.pagination.sync.SdkIterable;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClientExtension;
import software.amazon.awssdk.enhanced.dynamodb.internal.TransformIterable;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
/**
* Interface for an operation that can be executed against a mapped database and is expected to return a paginated
* list of results. These operations do not operate on a specific table or index, and may reference multiple tables
* and indexes (eg: batch operations). Typically, each page of results that is served will automatically perform an
* additional service call to DynamoDb to retrieve the next set of results.
*
* @param <RequestT> The type of the request object for the DynamoDb call in the low level {@link DynamoDbClient}.
* @param <ResponseT> The type of the response object for the DynamoDb call in the low level {@link DynamoDbClient}.
* @param <ResultT> The type of the mapped result object that will be returned by the execution of this operation.
*/
@SdkInternalApi
public interface PaginatedDatabaseOperation<RequestT, ResponseT, ResultT> {
/**
* This method generates the request that needs to be sent to a low level {@link DynamoDbClient}.
* @param extension A {@link DynamoDbEnhancedClientExtension} that may modify the request of this operation. A null value
* here will result in no modifications.
* @return A request that can be used as an argument to a {@link DynamoDbClient} call to perform the operation.
*/
RequestT generateRequest(DynamoDbEnhancedClientExtension extension);
/**
* Provides a function for making the low level synchronous paginated SDK call to DynamoDb.
* @param dynamoDbClient A low level {@link DynamoDbClient} to make the call against.
* @return A function that calls DynamoDb with a provided request object and returns the response object.
*/
Function<RequestT, SdkIterable<ResponseT>> serviceCall(DynamoDbClient dynamoDbClient);
/**
* Provides a function for making the low level non-blocking asynchronous paginated SDK call to DynamoDb.
* @param dynamoDbAsyncClient A low level {@link DynamoDbAsyncClient} to make the call against.
* @return A function that calls DynamoDb with a provided request object and returns the response object.
*/
Function<RequestT, SdkPublisher<ResponseT>> asyncServiceCall(DynamoDbAsyncClient dynamoDbAsyncClient);
/**
* Takes the response object returned by the actual DynamoDb call and maps it into a higher level abstracted
* result object.
* @param response The response object returned by the DynamoDb call for this operation.
* @param extension A {@link DynamoDbEnhancedClientExtension} that may modify the result of this operation. A null value
* here will result in no modifications.
* @return A high level result object as specified by the implementation of this operation.
*/
ResultT transformResponse(ResponseT response, DynamoDbEnhancedClientExtension extension);
/**
* Default implementation of a complete synchronous execution of this operation against a database.
* It performs three steps:
* 1) Call generateRequest() to get the request object.
* 2) Call getServiceCall() and call it using the request object generated in the previous step.
* 3) Wraps the {@link SdkIterable} that was returned by the previous step with a transformation that turns each
* object returned to a high level result.
*
* @param dynamoDbClient A {@link DynamoDbClient} to make the call against.
* @param extension A {@link DynamoDbEnhancedClientExtension} that may modify the request or result of this operation. A
* null value here will result in no modifications.
* @return An {@link SdkIterable} that will iteratively return pages of high level result objects as specified by
* the implementation of this operation.
*/
default SdkIterable<ResultT> execute(DynamoDbClient dynamoDbClient, DynamoDbEnhancedClientExtension extension) {
RequestT request = generateRequest(extension);
SdkIterable<ResponseT> response = serviceCall(dynamoDbClient).apply(request);
return TransformIterable.of(response, r -> transformResponse(r, extension));
}
/**
* Default implementation of a complete non-blocking asynchronous execution of this operation against a database.
* It performs three steps:
* 1) Call generateRequest() to get the request object.
* 2) Call getServiceCall() and call it using the request object generated in the previous step.
* 3) Wraps the {@link CompletableFuture} returned by the SDK in a new one that calls transformResponse() to
* convert the response object returned in the previous step to a high level result.
*
* @param dynamoDbAsyncClient A {@link DynamoDbAsyncClient} to make the call against.
* @param extension A {@link DynamoDbEnhancedClientExtension} that may modify the request or result of this operation. A
* null value here will result in no modifications.
* @return An {@link SdkPublisher} that will publish pages of the high level result object as specified by the
* implementation of this operation.
*/
default SdkPublisher<ResultT> executeAsync(DynamoDbAsyncClient dynamoDbAsyncClient,
DynamoDbEnhancedClientExtension extension) {
RequestT request = generateRequest(extension);
SdkPublisher<ResponseT> response = asyncServiceCall(dynamoDbAsyncClient).apply(request);
return response.map(r -> transformResponse(r, extension));
}
/**
* The type, or name, of the operation.
*/
OperationName operationName();
}
| 4,567 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/operations/BatchGetItemOperation.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.operations;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.async.SdkPublisher;
import software.amazon.awssdk.core.pagination.sync.SdkIterable;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClientExtension;
import software.amazon.awssdk.enhanced.dynamodb.model.BatchGetItemEnhancedRequest;
import software.amazon.awssdk.enhanced.dynamodb.model.BatchGetResultPage;
import software.amazon.awssdk.enhanced.dynamodb.model.ReadBatch;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.BatchGetItemRequest;
import software.amazon.awssdk.services.dynamodb.model.BatchGetItemResponse;
import software.amazon.awssdk.services.dynamodb.model.KeysAndAttributes;
@SdkInternalApi
public class BatchGetItemOperation
implements PaginatedDatabaseOperation<BatchGetItemRequest, BatchGetItemResponse, BatchGetResultPage> {
private final BatchGetItemEnhancedRequest request;
private BatchGetItemOperation(BatchGetItemEnhancedRequest request) {
this.request = request;
}
public static BatchGetItemOperation create(BatchGetItemEnhancedRequest request) {
return new BatchGetItemOperation(request);
}
@Override
public OperationName operationName() {
return OperationName.BATCH_GET_ITEM;
}
@Override
public BatchGetItemRequest generateRequest(DynamoDbEnhancedClientExtension extension) {
Map<String, KeysAndAttributes> requestItems = new HashMap<>();
request.readBatches().forEach(readBatch -> addReadRequestsToMap(readBatch, requestItems));
return BatchGetItemRequest.builder()
.requestItems(Collections.unmodifiableMap(requestItems))
.returnConsumedCapacity(request.returnConsumedCapacityAsString())
.build();
}
@Override
public BatchGetResultPage transformResponse(BatchGetItemResponse response,
DynamoDbEnhancedClientExtension extension) {
return BatchGetResultPage.builder().batchGetItemResponse(response).mapperExtension(extension).build();
}
@Override
public Function<BatchGetItemRequest, SdkIterable<BatchGetItemResponse>> serviceCall(DynamoDbClient dynamoDbClient) {
return dynamoDbClient::batchGetItemPaginator;
}
@Override
public Function<BatchGetItemRequest, SdkPublisher<BatchGetItemResponse>> asyncServiceCall(
DynamoDbAsyncClient dynamoDbAsyncClient) {
return dynamoDbAsyncClient::batchGetItemPaginator;
}
private void addReadRequestsToMap(ReadBatch readBatch, Map<String, KeysAndAttributes> readRequestMap) {
KeysAndAttributes newKeysAndAttributes = readBatch.keysAndAttributes();
KeysAndAttributes existingKeysAndAttributes = readRequestMap.get(readBatch.tableName());
if (existingKeysAndAttributes == null) {
readRequestMap.put(readBatch.tableName(), newKeysAndAttributes);
return;
}
KeysAndAttributes mergedKeysAndAttributes =
mergeKeysAndAttributes(existingKeysAndAttributes, newKeysAndAttributes);
readRequestMap.put(readBatch.tableName(), mergedKeysAndAttributes);
}
private static KeysAndAttributes mergeKeysAndAttributes(KeysAndAttributes first, KeysAndAttributes second) {
if (!compareNullableBooleans(first.consistentRead(), second.consistentRead())) {
throw new IllegalArgumentException("All batchable read requests for the same table must have the "
+ "same 'consistentRead' setting.");
}
Boolean consistentRead = first.consistentRead() == null ? second.consistentRead() : first.consistentRead();
List<Map<String, AttributeValue>> keys =
Stream.concat(first.keys().stream(), second.keys().stream()).collect(Collectors.toList());
return KeysAndAttributes.builder()
.keys(keys)
.consistentRead(consistentRead)
.build();
}
private static boolean compareNullableBooleans(Boolean one, Boolean two) {
if (one == null && two == null) {
return true;
}
if (one != null) {
return one.equals(two);
} else {
return false;
}
}
}
| 4,568 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/operations/CommonOperation.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.operations;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbAsyncIndex;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbAsyncTable;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClientExtension;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbIndex;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable;
import software.amazon.awssdk.enhanced.dynamodb.OperationContext;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
/**
* Common interface for a single operation that can be executed in a synchronous or non-blocking asynchronous fashion
* against a mapped database table. These operations can be made against either the primary index of a table or a
* secondary index, although some implementations of this interface do not support secondary indices and will throw
* an exception when executed against one. Conceptually an operation maps 1:1 with an actual DynamoDb call.
* <p>
* This interface is extended by {@link TableOperation} and {@link IndexOperation} which contain implementations of
* the behavior to actually execute the operation in the context of a table or secondary index and are used by
* {@link DynamoDbTable} or {@link DynamoDbAsyncTable} and {@link DynamoDbIndex} or {@link DynamoDbAsyncIndex}
* respectively. By sharing this common interface operations are able to re-use code regardless of whether they are
* executed in the context of a primary or secondary index or whether they are being executed in a synchronous or
* non-blocking asynchronous fashion.
*
* @param <ItemT> The modelled object that this table maps records to.
* @param <RequestT> The type of the request object for the DynamoDb call in the low level {@link DynamoDbClient} or
* {@link DynamoDbAsyncClient}.
* @param <ResponseT> The type of the response object for the DynamoDb call in the low level {@link DynamoDbClient}
* or {@link DynamoDbAsyncClient}.
* @param <ResultT> The type of the mapped result object that will be returned by the execution of this operation.
*/
@SdkInternalApi
public interface CommonOperation<ItemT, RequestT, ResponseT, ResultT> {
/**
* This method generates the request that needs to be sent to a low level {@link DynamoDbClient}.
* @param tableSchema A {@link TableSchema} that maps the table to a modelled object.
* @param context An object containing the context, or target, of the command execution.
* @param extension A {@link DynamoDbEnhancedClientExtension} that may modify the request of this operation. A null
* value here will result in no modifications.
* @return A request that can be used as an argument to a {@link DynamoDbClient} call to perform the operation.
*/
RequestT generateRequest(TableSchema<ItemT> tableSchema, OperationContext context,
DynamoDbEnhancedClientExtension extension);
/**
* Provides a function for making the low level synchronous SDK call to DynamoDb.
* @param dynamoDbClient A low level {@link DynamoDbClient} to make the call against.
* @return A function that calls DynamoDb with a provided request object and returns the response object.
*/
Function<RequestT, ResponseT> serviceCall(DynamoDbClient dynamoDbClient);
/**
* Provides a function for making the low level non-blocking asynchronous SDK call to DynamoDb.
* @param dynamoDbAsyncClient A low level {@link DynamoDbAsyncClient} to make the call against.
* @return A function that calls DynamoDb with a provided request object and returns the response object.
*/
Function<RequestT, CompletableFuture<ResponseT>> asyncServiceCall(DynamoDbAsyncClient dynamoDbAsyncClient);
/**
* Takes the response object returned by the actual DynamoDb call and maps it into a higher level abstracted
* result object.
* @param response The response object returned by the DynamoDb call for this operation.
* @param tableSchema A {@link TableSchema} that maps the table to a modelled object.
* @param context An object containing the context, or target, of the command execution.
* @param extension A {@link DynamoDbEnhancedClientExtension} that may modify the result of this operation. A null
* value here will result in no modifications.
* @return A high level result object as specified by the implementation of this operation.
*/
ResultT transformResponse(ResponseT response,
TableSchema<ItemT> tableSchema,
OperationContext context,
DynamoDbEnhancedClientExtension extension);
/**
* Default implementation of a complete synchronous execution of this operation against either the primary or a
* secondary index.
* It performs three steps:
* 1) Call generateRequest() to get the request object.
* 2) Call getServiceCall() and call it using the request object generated in the previous step.
* 3) Call transformResponse() to convert the response object returned in the previous step to a high level result.
*
* @param tableSchema A {@link TableSchema} that maps the table to a modelled object.
* @param context An object containing the context, or target, of the command execution.
* @param dynamoDbClient A {@link DynamoDbClient} to make the call against.
* @param extension A {@link DynamoDbEnhancedClientExtension} that may modify the request or result of this
* operation. A null value here will result in no modifications.
* @return A high level result object as specified by the implementation of this operation.
*/
default ResultT execute(TableSchema<ItemT> tableSchema,
OperationContext context,
DynamoDbEnhancedClientExtension extension,
DynamoDbClient dynamoDbClient) {
RequestT request = generateRequest(tableSchema, context, extension);
ResponseT response = serviceCall(dynamoDbClient).apply(request);
return transformResponse(response, tableSchema, context, extension);
}
/**
* Default implementation of a complete non-blocking asynchronous execution of this operation against either the
* primary or a secondary index.
* It performs three steps:
* 1) Call generateRequest() to get the request object.
* 2) Call getServiceCall() and call it using the request object generated in the previous step.
* 3) Wraps the {@link CompletableFuture} returned by the SDK in a new one that calls transformResponse() to
* convert the response object returned in the previous step to a high level result.
*
* @param tableSchema A {@link TableSchema} that maps the table to a modelled object.
* @param context An object containing the context, or target, of the command execution.
* @param dynamoDbAsyncClient A {@link DynamoDbAsyncClient} to make the call against.
* @param extension A {@link DynamoDbEnhancedClientExtension} that may modify the request or result of this
* operation. A null value here will result in no modifications.
* @return A {@link CompletableFuture} of the high level result object as specified by the implementation of this
* operation.
*/
default CompletableFuture<ResultT> executeAsync(TableSchema<ItemT> tableSchema,
OperationContext context,
DynamoDbEnhancedClientExtension extension,
DynamoDbAsyncClient dynamoDbAsyncClient) {
RequestT request = generateRequest(tableSchema, context, extension);
CompletableFuture<ResponseT> response = asyncServiceCall(dynamoDbAsyncClient).apply(request);
return response.thenApply(r -> transformResponse(r, tableSchema, context, extension));
}
/**
* The type, or name, of the operation.
*/
OperationName operationName();
}
| 4,569 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/operations/IndexOperation.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.operations;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClientExtension;
import software.amazon.awssdk.enhanced.dynamodb.OperationContext;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
/**
* Interface for a single operation that can be executed against a secondary index of a mapped database table.
* Conceptually an operation maps 1:1 with an actual DynamoDb call.
* <p>
* A concrete implementation of this interface should also implement {@link TableOperation} with the same types if
* the operation supports being executed against both the primary index and secondary indices.
*
* @param <ItemT> The modelled object that this table maps records to.
* @param <RequestT> The type of the request object for the DynamoDb call in the low level {@link DynamoDbClient}.
* @param <ResponseT> The type of the response object for the DynamoDb call in the low level {@link DynamoDbClient}.
* @param <ResultT> The type of the mapped result object that will be returned by the execution of this operation.
*/
@SdkInternalApi
public interface IndexOperation<ItemT, RequestT, ResponseT, ResultT>
extends CommonOperation<ItemT, RequestT, ResponseT, ResultT> {
/**
* Default implementation of a complete synchronous execution of this operation against a secondary index. It will
* construct a context based on the given table name and secondary index name and then call execute() on the
* {@link CommonOperation} interface to perform the operation.
*
* @param tableSchema A {@link TableSchema} that maps the table to a modelled object.
* @param tableName The physical name of the table that contains the secondary index to execute the operation
* against.
* @param indexName The physical name of the secondary index to execute the operation against.
* @param dynamoDbClient A {@link DynamoDbClient} to make the call against.
* @param extension A {@link DynamoDbEnhancedClientExtension} that may modify the request or result of this
* operation. A null value here will result in no modifications.
* @return A high level result object as specified by the implementation of this operation.
*/
default ResultT executeOnSecondaryIndex(TableSchema<ItemT> tableSchema,
String tableName,
String indexName,
DynamoDbEnhancedClientExtension extension,
DynamoDbClient dynamoDbClient) {
OperationContext context =
DefaultOperationContext.create(tableName, indexName);
return execute(tableSchema, context, extension, dynamoDbClient);
}
/**
* Default implementation of a complete non-blocking asynchronous execution of this operation against a secondary
* index. It will construct a context based on the given table name and secondary index name and then call
* executeAsync() on the {@link CommonOperation} interface to perform the operation.
*
* @param tableSchema A {@link TableSchema} that maps the table to a modelled object.
* @param tableName The physical name of the table that contains the secondary index to execute the operation
* against.
* @param indexName The physical name of the secondary index to execute the operation against.
* @param dynamoDbAsyncClient A {@link DynamoDbAsyncClient} to make the call against.
* @param extension A {@link DynamoDbEnhancedClientExtension} that may modify the request or result of this
* operation. A null value here will result in no modifications.
* @return A high level result object as specified by the implementation of this operation.
*/
default CompletableFuture<ResultT> executeOnSecondaryIndexAsync(TableSchema<ItemT> tableSchema,
String tableName,
String indexName,
DynamoDbEnhancedClientExtension extension,
DynamoDbAsyncClient dynamoDbAsyncClient) {
OperationContext context =
DefaultOperationContext.create(tableName, indexName);
return executeAsync(tableSchema, context, extension, dynamoDbAsyncClient);
}
}
| 4,570 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/operations/UpdateItemOperation.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.operations;
import static software.amazon.awssdk.enhanced.dynamodb.internal.EnhancedClientUtils.readAndTransformSingleItem;
import static software.amazon.awssdk.enhanced.dynamodb.internal.update.UpdateExpressionUtils.operationExpression;
import static software.amazon.awssdk.utils.CollectionUtils.filterMap;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClientExtension;
import software.amazon.awssdk.enhanced.dynamodb.Expression;
import software.amazon.awssdk.enhanced.dynamodb.OperationContext;
import software.amazon.awssdk.enhanced.dynamodb.TableMetadata;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.extensions.WriteModification;
import software.amazon.awssdk.enhanced.dynamodb.internal.extensions.DefaultDynamoDbExtensionContext;
import software.amazon.awssdk.enhanced.dynamodb.internal.update.UpdateExpressionConverter;
import software.amazon.awssdk.enhanced.dynamodb.model.TransactUpdateItemEnhancedRequest;
import software.amazon.awssdk.enhanced.dynamodb.model.UpdateItemEnhancedRequest;
import software.amazon.awssdk.enhanced.dynamodb.model.UpdateItemEnhancedResponse;
import software.amazon.awssdk.enhanced.dynamodb.update.UpdateExpression;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.ReturnValue;
import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem;
import software.amazon.awssdk.services.dynamodb.model.Update;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemResponse;
import software.amazon.awssdk.utils.CollectionUtils;
import software.amazon.awssdk.utils.Either;
@SdkInternalApi
public class UpdateItemOperation<T>
implements TableOperation<T, UpdateItemRequest, UpdateItemResponse, UpdateItemEnhancedResponse<T>>,
TransactableWriteOperation<T> {
private final Either<UpdateItemEnhancedRequest<T>, TransactUpdateItemEnhancedRequest<T>> request;
private UpdateItemOperation(UpdateItemEnhancedRequest<T> request) {
this.request = Either.left(request);
}
private UpdateItemOperation(TransactUpdateItemEnhancedRequest<T> request) {
this.request = Either.right(request);
}
public static <T> UpdateItemOperation<T> create(UpdateItemEnhancedRequest<T> request) {
return new UpdateItemOperation<>(request);
}
public static <T> UpdateItemOperation<T> create(TransactUpdateItemEnhancedRequest<T> request) {
return new UpdateItemOperation<>(request);
}
@Override
public OperationName operationName() {
return OperationName.UPDATE_ITEM;
}
@Override
public UpdateItemRequest generateRequest(TableSchema<T> tableSchema,
OperationContext operationContext,
DynamoDbEnhancedClientExtension extension) {
if (!TableMetadata.primaryIndexName().equals(operationContext.indexName())) {
throw new IllegalArgumentException("UpdateItem cannot be executed against a secondary index.");
}
T item = request.map(UpdateItemEnhancedRequest::item, TransactUpdateItemEnhancedRequest::item);
Boolean ignoreNulls = request.map(r -> Optional.ofNullable(r.ignoreNulls()),
r -> Optional.ofNullable(r.ignoreNulls()))
.orElse(null);
Map<String, AttributeValue> itemMap = tableSchema.itemToMap(item, Boolean.TRUE.equals(ignoreNulls));
TableMetadata tableMetadata = tableSchema.tableMetadata();
WriteModification transformation =
extension != null
? extension.beforeWrite(DefaultDynamoDbExtensionContext.builder()
.items(itemMap)
.operationContext(operationContext)
.tableMetadata(tableMetadata)
.tableSchema(tableSchema)
.operationName(operationName())
.build())
: null;
if (transformation != null && transformation.transformedItem() != null) {
itemMap = transformation.transformedItem();
}
Collection<String> primaryKeys = tableSchema.tableMetadata().primaryKeys();
Map<String, AttributeValue> keyAttributes = filterMap(itemMap, entry -> primaryKeys.contains(entry.getKey()));
Map<String, AttributeValue> nonKeyAttributes = filterMap(itemMap, entry -> !primaryKeys.contains(entry.getKey()));
Expression updateExpression = generateUpdateExpressionIfExist(tableMetadata, transformation, nonKeyAttributes);
Expression conditionExpression = generateConditionExpressionIfExist(transformation, request);
Map<String, String> expressionNames = coalesceExpressionNames(updateExpression, conditionExpression);
Map<String, AttributeValue> expressionValues = coalesceExpressionValues(updateExpression, conditionExpression);
UpdateItemRequest.Builder requestBuilder = UpdateItemRequest.builder()
.tableName(operationContext.tableName())
.key(keyAttributes)
.returnValues(ReturnValue.ALL_NEW);
if (request.left().isPresent()) {
addPlainUpdateItemParameters(requestBuilder, request.left().get());
}
if (updateExpression != null) {
requestBuilder.updateExpression(updateExpression.expression());
}
if (conditionExpression != null) {
requestBuilder.conditionExpression(conditionExpression.expression());
}
if (CollectionUtils.isNotEmpty(expressionNames)) {
requestBuilder = requestBuilder.expressionAttributeNames(expressionNames);
}
if (CollectionUtils.isNotEmpty(expressionValues)) {
requestBuilder = requestBuilder.expressionAttributeValues(expressionValues);
}
return requestBuilder.build();
}
@Override
public UpdateItemEnhancedResponse<T> transformResponse(UpdateItemResponse response,
TableSchema<T> tableSchema,
OperationContext operationContext,
DynamoDbEnhancedClientExtension extension) {
try {
T attributes = readAndTransformSingleItem(response.attributes(), tableSchema, operationContext, extension);
return UpdateItemEnhancedResponse.<T>builder(null)
.attributes(attributes)
.consumedCapacity(response.consumedCapacity())
.itemCollectionMetrics(response.itemCollectionMetrics())
.build();
} catch (RuntimeException e) {
// With a partial update it's possible to update the record into a state that the mapper can no longer
// read or validate. This is more likely to happen with signed and encrypted records that undergo partial
// updates (that practice is discouraged for this reason).
throw new IllegalStateException("Unable to read the new item returned by UpdateItem after the update "
+ "occurred. Rollbacks are not supported by this operation, therefore the "
+ "record may no longer be readable using this model.", e);
}
}
@Override
public Function<UpdateItemRequest, UpdateItemResponse> serviceCall(DynamoDbClient dynamoDbClient) {
return dynamoDbClient::updateItem;
}
@Override
public Function<UpdateItemRequest, CompletableFuture<UpdateItemResponse>> asyncServiceCall(
DynamoDbAsyncClient dynamoDbAsyncClient) {
return dynamoDbAsyncClient::updateItem;
}
@Override
public TransactWriteItem generateTransactWriteItem(TableSchema<T> tableSchema, OperationContext operationContext,
DynamoDbEnhancedClientExtension dynamoDbEnhancedClientExtension) {
UpdateItemRequest updateItemRequest = generateRequest(tableSchema, operationContext, dynamoDbEnhancedClientExtension);
Update.Builder builder = Update.builder()
.key(updateItemRequest.key())
.tableName(updateItemRequest.tableName())
.updateExpression(updateItemRequest.updateExpression())
.conditionExpression(updateItemRequest.conditionExpression())
.expressionAttributeValues(updateItemRequest.expressionAttributeValues())
.expressionAttributeNames(updateItemRequest.expressionAttributeNames());
request.right()
.map(TransactUpdateItemEnhancedRequest::returnValuesOnConditionCheckFailureAsString)
.ifPresent(builder::returnValuesOnConditionCheckFailure);
return TransactWriteItem.builder()
.update(builder.build())
.build();
}
/**
* Retrieves the UpdateExpression from extensions if existing, and then creates an UpdateExpression for the request POJO
* if there are attributes to be updated (most likely). If both exist, they are merged and the code generates a final
* Expression that represent the result.
*/
private Expression generateUpdateExpressionIfExist(TableMetadata tableMetadata,
WriteModification transformation,
Map<String, AttributeValue> attributes) {
UpdateExpression updateExpression = null;
if (transformation != null && transformation.updateExpression() != null) {
updateExpression = transformation.updateExpression();
}
if (!attributes.isEmpty()) {
List<String> nonRemoveAttributes = UpdateExpressionConverter.findAttributeNames(updateExpression);
UpdateExpression operationUpdateExpression = operationExpression(attributes, tableMetadata, nonRemoveAttributes);
if (updateExpression == null) {
updateExpression = operationUpdateExpression;
} else {
updateExpression = UpdateExpression.mergeExpressions(updateExpression, operationUpdateExpression);
}
}
return UpdateExpressionConverter.toExpression(updateExpression);
}
/**
* Retrieves the ConditionExpression from extensions if existing, and retrieves the ConditionExpression from the request
* if existing. If both exist, they are merged.
*/
private Expression generateConditionExpressionIfExist(
WriteModification transformation,
Either<UpdateItemEnhancedRequest<T>, TransactUpdateItemEnhancedRequest<T>> request) {
Expression conditionExpression = null;
if (transformation != null && transformation.additionalConditionalExpression() != null) {
conditionExpression = transformation.additionalConditionalExpression();
}
Expression operationConditionExpression = request.map(r -> Optional.ofNullable(r.conditionExpression()),
r -> Optional.ofNullable(r.conditionExpression()))
.orElse(null);
if (operationConditionExpression != null) {
conditionExpression = operationConditionExpression.and(conditionExpression);
}
return conditionExpression;
}
private UpdateItemRequest.Builder addPlainUpdateItemParameters(UpdateItemRequest.Builder requestBuilder,
UpdateItemEnhancedRequest<?> enhancedRequest) {
requestBuilder = requestBuilder.returnConsumedCapacity(enhancedRequest.returnConsumedCapacityAsString());
requestBuilder = requestBuilder.returnItemCollectionMetrics(enhancedRequest.returnItemCollectionMetricsAsString());
return requestBuilder;
}
private static Map<String, String> coalesceExpressionNames(Expression firstExpression, Expression secondExpression) {
Map<String, String> expressionNames = null;
if (firstExpression != null && !CollectionUtils.isNullOrEmpty(firstExpression.expressionNames())) {
expressionNames = firstExpression.expressionNames();
}
if (secondExpression != null && !CollectionUtils.isNullOrEmpty(secondExpression.expressionNames())) {
expressionNames = Expression.joinNames(expressionNames, secondExpression.expressionNames());
}
return expressionNames;
}
private static Map<String, AttributeValue> coalesceExpressionValues(Expression firstExpression, Expression secondExpression) {
Map<String, AttributeValue> expressionValues = null;
if (firstExpression != null && !CollectionUtils.isNullOrEmpty(firstExpression.expressionValues())) {
expressionValues = firstExpression.expressionValues();
}
if (secondExpression != null && !CollectionUtils.isNullOrEmpty(secondExpression.expressionValues())) {
expressionValues = Expression.joinValues(expressionValues, secondExpression.expressionValues());
}
return expressionValues;
}
}
| 4,571 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/operations/DefaultOperationContext.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.operations;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.enhanced.dynamodb.OperationContext;
import software.amazon.awssdk.enhanced.dynamodb.TableMetadata;
@SdkInternalApi
public class DefaultOperationContext implements OperationContext {
private final String tableName;
private final String indexName;
private DefaultOperationContext(String tableName, String indexName) {
this.tableName = tableName;
this.indexName = indexName;
}
public static DefaultOperationContext create(String tableName, String indexName) {
return new DefaultOperationContext(tableName, indexName);
}
public static DefaultOperationContext create(String tableName) {
return new DefaultOperationContext(tableName, TableMetadata.primaryIndexName());
}
@Override
public String tableName() {
return tableName;
}
@Override
public String indexName() {
return indexName;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DefaultOperationContext that = (DefaultOperationContext) o;
if (tableName != null ? ! tableName.equals(that.tableName) : that.tableName != null) {
return false;
}
return indexName != null ? indexName.equals(that.indexName) : that.indexName == null;
}
@Override
public int hashCode() {
int result = tableName != null ? tableName.hashCode() : 0;
result = 31 * result + (indexName != null ? indexName.hashCode() : 0);
return result;
}
}
| 4,572 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/extensions/ChainExtension.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.extensions;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import software.amazon.awssdk.annotations.SdkInternalApi;
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.extensions.ReadModification;
import software.amazon.awssdk.enhanced.dynamodb.extensions.WriteModification;
import software.amazon.awssdk.enhanced.dynamodb.update.UpdateExpression;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
/**
* A meta-extension that allows multiple extensions to be chained in a specified order to act as a single composite
* extension. The order in which extensions will be used depends on the operation, for write operations they will be
* called in forward order, for read operations they will be called in reverse order. For example :-
*
* <p>
* If you create a chain of three extensions:
* ChainMapperExtension.create(extension1, extension2, extension3);
*
* <p>
* When performing any kind of write operation (eg: PutItem, UpdateItem) the beforeWrite() method will be called in
* forward order:
*
* {@literal extension1 -> extension2 -> extension3}
*
* <p>
* So the output of extension1 will be passed into extension2, and then the output of extension2 into extension3 and
* so on. For operations that read (eg: GetItem, UpdateItem) the afterRead() method will be called in reverse order:
*
* {@literal extension3 -> extension2 -> extension1}
*
* <p>
* This is designed to create a layered pattern when dealing with multiple extensions. One thing to note is that
* UpdateItem acts as both a write operation and a read operation so the chain will be called both ways within a
* single operation.
*/
@SdkInternalApi
public final class ChainExtension implements DynamoDbEnhancedClientExtension {
private final Deque<DynamoDbEnhancedClientExtension> extensionChain;
private ChainExtension(List<DynamoDbEnhancedClientExtension> extensions) {
this.extensionChain = new ArrayDeque<>(extensions);
}
/**
* Construct a new instance of {@link ChainExtension}.
* @param extensions A list of {@link DynamoDbEnhancedClientExtension} to chain together.
* @return A constructed {@link ChainExtension} object.
*/
public static ChainExtension create(DynamoDbEnhancedClientExtension... extensions) {
return new ChainExtension(Arrays.asList(extensions));
}
/**
* Construct a new instance of {@link ChainExtension}.
* @param extensions A list of {@link DynamoDbEnhancedClientExtension} to chain together.
* @return A constructed {@link ChainExtension} object.
*/
public static ChainExtension create(List<DynamoDbEnhancedClientExtension> extensions) {
return new ChainExtension(extensions);
}
/**
* Implementation of the {@link DynamoDbEnhancedClientExtension} interface that will call all the chained extensions
* in forward order, passing the results of each one to the next and coalescing the results into a single modification.
* Multiple conditional statements will be separated by the string " AND ". Expression values will be coalesced
* unless they conflict in which case an exception will be thrown. UpdateExpressions will be
* coalesced.
*
* @param context A {@link DynamoDbExtensionContext.BeforeWrite} context
* @return A single {@link WriteModification} representing the coalesced results of all the chained extensions.
*/
@Override
public WriteModification beforeWrite(DynamoDbExtensionContext.BeforeWrite context) {
Map<String, AttributeValue> transformedItem = null;
Expression conditionalExpression = null;
UpdateExpression updateExpression = null;
for (DynamoDbEnhancedClientExtension extension : this.extensionChain) {
Map<String, AttributeValue> itemToTransform = transformedItem == null ? context.items() : transformedItem;
DynamoDbExtensionContext.BeforeWrite beforeWrite =
DefaultDynamoDbExtensionContext.builder()
.items(itemToTransform)
.operationContext(context.operationContext())
.tableMetadata(context.tableMetadata())
.tableSchema(context.tableSchema())
.operationName(context.operationName())
.build();
WriteModification writeModification = extension.beforeWrite(beforeWrite);
if (writeModification.transformedItem() != null) {
transformedItem = writeModification.transformedItem();
}
conditionalExpression = mergeConditionalExpressions(conditionalExpression,
writeModification.additionalConditionalExpression());
updateExpression = mergeUpdateExpressions(updateExpression, writeModification.updateExpression());
}
return WriteModification.builder()
.transformedItem(transformedItem)
.additionalConditionalExpression(conditionalExpression)
.updateExpression(updateExpression)
.build();
}
private UpdateExpression mergeUpdateExpressions(UpdateExpression existingExpression, UpdateExpression newExpression) {
if (newExpression != null) {
if (existingExpression == null) {
existingExpression = newExpression;
} else {
existingExpression = UpdateExpression.mergeExpressions(existingExpression, newExpression);
}
}
return existingExpression;
}
private Expression mergeConditionalExpressions(Expression existingExpression, Expression newExpression) {
if (newExpression != null) {
if (existingExpression == null) {
existingExpression = newExpression;
} else {
existingExpression = existingExpression.and(newExpression);
}
}
return existingExpression;
}
/**
* Implementation of the {@link DynamoDbEnhancedClientExtension} interface that will call all the chained extensions
* in reverse order, passing the results of each one to the next and coalescing the results into a single modification.
*
* @param context A {@link DynamoDbExtensionContext.AfterRead} context
* @return A single {@link ReadModification} representing the final transformation of all the chained extensions.
*/
@Override
public ReadModification afterRead(DynamoDbExtensionContext.AfterRead context) {
Map<String, AttributeValue> transformedItem = null;
Iterator<DynamoDbEnhancedClientExtension> iterator = extensionChain.descendingIterator();
while (iterator.hasNext()) {
Map<String, AttributeValue> itemToTransform =
transformedItem == null ? context.items() : transformedItem;
DynamoDbExtensionContext.AfterRead afterRead =
DefaultDynamoDbExtensionContext.builder().items(itemToTransform)
.operationContext(context.operationContext())
.tableMetadata(context.tableMetadata())
.tableSchema(context.tableSchema())
.build();
ReadModification readModification = iterator.next().afterRead(afterRead);
if (readModification.transformedItem() != null) {
transformedItem = readModification.transformedItem();
}
}
return ReadModification.builder()
.transformedItem(transformedItem)
.build();
}
}
| 4,573 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/extensions/VersionRecordAttributeTags.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.extensions;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.enhanced.dynamodb.extensions.VersionedRecordExtension;
import software.amazon.awssdk.enhanced.dynamodb.extensions.annotations.DynamoDbVersionAttribute;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTag;
@SdkInternalApi
public final class VersionRecordAttributeTags {
private VersionRecordAttributeTags() {
}
public static StaticAttributeTag attributeTagFor(DynamoDbVersionAttribute annotation) {
return VersionedRecordExtension.AttributeTags.versionAttribute();
}
}
| 4,574 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/extensions/AutoGeneratedTimestampRecordAttributeTags.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.extensions;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.enhanced.dynamodb.extensions.AutoGeneratedTimestampRecordExtension;
import software.amazon.awssdk.enhanced.dynamodb.extensions.annotations.DynamoDbAutoGeneratedTimestampAttribute;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTag;
@SdkInternalApi
public final class AutoGeneratedTimestampRecordAttributeTags {
private AutoGeneratedTimestampRecordAttributeTags() {
}
public static StaticAttributeTag attributeTagFor(DynamoDbAutoGeneratedTimestampAttribute annotation) {
return AutoGeneratedTimestampRecordExtension.AttributeTags.autoGeneratedTimestampAttribute();
}
}
| 4,575 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/extensions/AtomicCounterTag.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.extensions;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType;
import software.amazon.awssdk.enhanced.dynamodb.TableMetadata;
import software.amazon.awssdk.enhanced.dynamodb.internal.mapper.AtomicCounter;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTag;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableMetadata;
@SdkInternalApi
public class AtomicCounterTag implements StaticAttributeTag {
public static final String CUSTOM_METADATA_KEY_PREFIX = "AtomicCounter:Counters";
private static final long DEFAULT_INCREMENT = 1L;
private static final long DEFAULT_START_VALUE = 0L;
private static final AtomicCounter DEFAULT_COUNTER = AtomicCounter.builder()
.delta(DEFAULT_INCREMENT)
.startValue(DEFAULT_START_VALUE)
.build();
private final AtomicCounter counter;
private AtomicCounterTag(AtomicCounter counter) {
this.counter = counter;
}
public static AtomicCounterTag create() {
return new AtomicCounterTag(DEFAULT_COUNTER);
}
public static AtomicCounterTag fromValues(long delta, long startValue) {
return new AtomicCounterTag(AtomicCounter.builder()
.delta(delta)
.startValue(startValue)
.build());
}
@SuppressWarnings("unchecked")
public static Map<String, AtomicCounter> resolve(TableMetadata tableMetadata) {
return tableMetadata.customMetadataObject(CUSTOM_METADATA_KEY_PREFIX, Map.class).orElseGet(HashMap::new);
}
@Override
public Consumer<StaticTableMetadata.Builder> modifyMetadata(String attributeName, AttributeValueType attributeValueType) {
return metadata -> metadata
.addCustomMetadataObject(CUSTOM_METADATA_KEY_PREFIX, Collections.singletonMap(attributeName, this.counter))
.markAttributeAsKey(attributeName, attributeValueType);
}
}
| 4,576 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/extensions/DefaultDynamoDbExtensionContext.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.extensions;
import java.util.Map;
import java.util.Objects;
import software.amazon.awssdk.annotations.NotThreadSafe;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbExtensionContext;
import software.amazon.awssdk.enhanced.dynamodb.OperationContext;
import software.amazon.awssdk.enhanced.dynamodb.TableMetadata;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.internal.operations.OperationName;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
/**
* An SDK-internal implementation of {@link DynamoDbExtensionContext.BeforeWrite} and
* {@link DynamoDbExtensionContext.AfterRead}.
*/
@SdkInternalApi
public final class DefaultDynamoDbExtensionContext implements DynamoDbExtensionContext.BeforeWrite,
DynamoDbExtensionContext.AfterRead {
private final Map<String, AttributeValue> items;
private final OperationContext operationContext;
private final TableMetadata tableMetadata;
private final TableSchema<?> tableSchema;
private final OperationName operationName;
private DefaultDynamoDbExtensionContext(Builder builder) {
this.items = builder.items;
this.operationContext = builder.operationContext;
this.tableMetadata = builder.tableMetadata;
this.tableSchema = builder.tableSchema;
this.operationName = builder.operationName != null ? builder.operationName : OperationName.NONE;
}
public static Builder builder() {
return new Builder();
}
@Override
public Map<String, AttributeValue> items() {
return items;
}
@Override
public OperationContext operationContext() {
return operationContext;
}
@Override
public TableMetadata tableMetadata() {
return tableMetadata;
}
@Override
public TableSchema<?> tableSchema() {
return tableSchema;
}
@Override
public OperationName operationName() {
return operationName;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DefaultDynamoDbExtensionContext that = (DefaultDynamoDbExtensionContext) o;
if (!Objects.equals(items, that.items)) {
return false;
}
if (!Objects.equals(operationContext, that.operationContext)) {
return false;
}
if (!Objects.equals(tableMetadata, that.tableMetadata)) {
return false;
}
if (!Objects.equals(tableSchema, that.tableSchema)) {
return false;
}
return Objects.equals(operationName, that.operationName);
}
@Override
public int hashCode() {
int result = items != null ? items.hashCode() : 0;
result = 31 * result + (operationContext != null ? operationContext.hashCode() : 0);
result = 31 * result + (tableMetadata != null ? tableMetadata.hashCode() : 0);
result = 31 * result + (tableSchema != null ? tableSchema.hashCode() : 0);
result = 31 * result + (operationName != null ? operationName.hashCode() : 0);
return result;
}
@NotThreadSafe
public static final class Builder {
private Map<String, AttributeValue> items;
private OperationContext operationContext;
private TableMetadata tableMetadata;
private TableSchema<?> tableSchema;
private OperationName operationName;
public Builder items(Map<String, AttributeValue> item) {
this.items = item;
return this;
}
public Builder operationContext(OperationContext operationContext) {
this.operationContext = operationContext;
return this;
}
public Builder tableMetadata(TableMetadata tableMetadata) {
this.tableMetadata = tableMetadata;
return this;
}
public Builder tableSchema(TableSchema<?> tableSchema) {
this.tableSchema = tableSchema;
return this;
}
public Builder operationName(OperationName operationName) {
this.operationName = operationName;
return this;
}
public DefaultDynamoDbExtensionContext build() {
return new DefaultDynamoDbExtensionContext(this);
}
}
}
| 4,577 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/client/DefaultDynamoDbAsyncTable.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.client;
import static software.amazon.awssdk.enhanced.dynamodb.internal.EnhancedClientUtils.createKeyFromItem;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbAsyncTable;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClientExtension;
import software.amazon.awssdk.enhanced.dynamodb.Key;
import software.amazon.awssdk.enhanced.dynamodb.TableMetadata;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.internal.operations.CreateTableOperation;
import software.amazon.awssdk.enhanced.dynamodb.internal.operations.DeleteItemOperation;
import software.amazon.awssdk.enhanced.dynamodb.internal.operations.DeleteTableOperation;
import software.amazon.awssdk.enhanced.dynamodb.internal.operations.DescribeTableOperation;
import software.amazon.awssdk.enhanced.dynamodb.internal.operations.GetItemOperation;
import software.amazon.awssdk.enhanced.dynamodb.internal.operations.PaginatedTableOperation;
import software.amazon.awssdk.enhanced.dynamodb.internal.operations.PutItemOperation;
import software.amazon.awssdk.enhanced.dynamodb.internal.operations.QueryOperation;
import software.amazon.awssdk.enhanced.dynamodb.internal.operations.ScanOperation;
import software.amazon.awssdk.enhanced.dynamodb.internal.operations.TableOperation;
import software.amazon.awssdk.enhanced.dynamodb.internal.operations.UpdateItemOperation;
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.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.DescribeTableRequest;
import software.amazon.awssdk.services.dynamodb.model.DescribeTableResponse;
@SdkInternalApi
public final class DefaultDynamoDbAsyncTable<T> implements DynamoDbAsyncTable<T> {
private final DynamoDbAsyncClient dynamoDbClient;
private final DynamoDbEnhancedClientExtension extension;
private final TableSchema<T> tableSchema;
private final String tableName;
DefaultDynamoDbAsyncTable(DynamoDbAsyncClient dynamoDbClient,
DynamoDbEnhancedClientExtension extension,
TableSchema<T> tableSchema,
String tableName) {
this.dynamoDbClient = dynamoDbClient;
this.extension = extension;
this.tableSchema = tableSchema;
this.tableName = tableName;
}
@Override
public DynamoDbEnhancedClientExtension mapperExtension() {
return this.extension;
}
@Override
public TableSchema<T> tableSchema() {
return this.tableSchema;
}
public DynamoDbAsyncClient dynamoDbClient() {
return dynamoDbClient;
}
@Override
public String tableName() {
return tableName;
}
@Override
public DefaultDynamoDbAsyncIndex<T> index(String indexName) {
// Force a check for the existence of the index
tableSchema.tableMetadata().indexPartitionKey(indexName);
return new DefaultDynamoDbAsyncIndex<>(dynamoDbClient, extension, tableSchema, tableName, indexName);
}
@Override
public CompletableFuture<Void> createTable(CreateTableEnhancedRequest request) {
TableOperation<T, ?, ?, Void> operation = CreateTableOperation.create(request);
return operation.executeOnPrimaryIndexAsync(tableSchema, tableName, extension, dynamoDbClient);
}
@Override
public CompletableFuture<Void> createTable(Consumer<CreateTableEnhancedRequest.Builder> requestConsumer) {
CreateTableEnhancedRequest.Builder builder = CreateTableEnhancedRequest.builder();
requestConsumer.accept(builder);
return createTable(builder.build());
}
@Override
public CompletableFuture<Void> createTable() {
return createTable(CreateTableEnhancedRequest.builder().build());
}
@Override
public CompletableFuture<T> deleteItem(DeleteItemEnhancedRequest request) {
TableOperation<T, ?, ?, DeleteItemEnhancedResponse<T>> operation = DeleteItemOperation.create(request);
return operation.executeOnPrimaryIndexAsync(tableSchema, tableName, extension, dynamoDbClient)
.thenApply(DeleteItemEnhancedResponse::attributes);
}
@Override
public CompletableFuture<T> deleteItem(Consumer<DeleteItemEnhancedRequest.Builder> requestConsumer) {
DeleteItemEnhancedRequest.Builder builder = DeleteItemEnhancedRequest.builder();
requestConsumer.accept(builder);
return deleteItem(builder.build());
}
@Override
public CompletableFuture<T> deleteItem(Key key) {
return deleteItem(r -> r.key(key));
}
@Override
public CompletableFuture<T> deleteItem(T keyItem) {
return deleteItem(keyFrom(keyItem));
}
@Override
public CompletableFuture<DeleteItemEnhancedResponse<T>> deleteItemWithResponse(DeleteItemEnhancedRequest request) {
TableOperation<T, ?, ?, DeleteItemEnhancedResponse<T>> operation = DeleteItemOperation.create(request);
return operation.executeOnPrimaryIndexAsync(tableSchema, tableName, extension, dynamoDbClient);
}
@Override
public CompletableFuture<DeleteItemEnhancedResponse<T>> deleteItemWithResponse(
Consumer<DeleteItemEnhancedRequest.Builder> requestConsumer) {
DeleteItemEnhancedRequest.Builder builder = DeleteItemEnhancedRequest.builder();
requestConsumer.accept(builder);
return deleteItemWithResponse(builder.build());
}
@Override
public CompletableFuture<T> getItem(GetItemEnhancedRequest request) {
TableOperation<T, ?, ?, GetItemEnhancedResponse<T>> operation = GetItemOperation.create(request);
CompletableFuture<GetItemEnhancedResponse<T>> future = operation.executeOnPrimaryIndexAsync(
tableSchema, tableName, extension, dynamoDbClient
);
return future.thenApply(GetItemEnhancedResponse::attributes);
}
@Override
public CompletableFuture<T> getItem(Consumer<GetItemEnhancedRequest.Builder> requestConsumer) {
GetItemEnhancedRequest.Builder builder = GetItemEnhancedRequest.builder();
requestConsumer.accept(builder);
return getItem(builder.build());
}
@Override
public CompletableFuture<T> getItem(Key key) {
return getItem(r -> r.key(key));
}
@Override
public CompletableFuture<T> getItem(T keyItem) {
return getItem(keyFrom(keyItem));
}
@Override
public CompletableFuture<GetItemEnhancedResponse<T>> getItemWithResponse(GetItemEnhancedRequest request) {
TableOperation<T, ?, ?, GetItemEnhancedResponse<T>> operation = GetItemOperation.create(request);
return operation.executeOnPrimaryIndexAsync(tableSchema, tableName, extension, dynamoDbClient);
}
@Override
public CompletableFuture<GetItemEnhancedResponse<T>> getItemWithResponse(
Consumer<GetItemEnhancedRequest.Builder> requestConsumer) {
GetItemEnhancedRequest.Builder builder = GetItemEnhancedRequest.builder();
requestConsumer.accept(builder);
return getItemWithResponse(builder.build());
}
@Override
public PagePublisher<T> query(QueryEnhancedRequest request) {
PaginatedTableOperation<T, ?, ?> operation = QueryOperation.create(request);
return operation.executeOnPrimaryIndexAsync(tableSchema, tableName, extension, dynamoDbClient);
}
@Override
public PagePublisher<T> query(Consumer<QueryEnhancedRequest.Builder> requestConsumer) {
QueryEnhancedRequest.Builder builder = QueryEnhancedRequest.builder();
requestConsumer.accept(builder);
return query(builder.build());
}
@Override
public PagePublisher<T> query(QueryConditional queryConditional) {
return query(r -> r.queryConditional(queryConditional));
}
@Override
public CompletableFuture<Void> putItem(PutItemEnhancedRequest<T> request) {
TableOperation<T, ?, ?, PutItemEnhancedResponse<T>> operation = PutItemOperation.create(request);
return operation.executeOnPrimaryIndexAsync(tableSchema, tableName, extension, dynamoDbClient).thenApply(ignored -> null);
}
@Override
public CompletableFuture<Void> putItem(Consumer<PutItemEnhancedRequest.Builder<T>> requestConsumer) {
PutItemEnhancedRequest.Builder<T> builder =
PutItemEnhancedRequest.builder(this.tableSchema.itemType().rawClass());
requestConsumer.accept(builder);
return putItem(builder.build());
}
@Override
public CompletableFuture<Void> putItem(T item) {
return putItem(r -> r.item(item));
}
@Override
public CompletableFuture<PutItemEnhancedResponse<T>> putItemWithResponse(PutItemEnhancedRequest<T> request) {
TableOperation<T, ?, ?, PutItemEnhancedResponse<T>> operation = PutItemOperation.create(request);
return operation.executeOnPrimaryIndexAsync(tableSchema, tableName, extension, dynamoDbClient);
}
@Override
public CompletableFuture<PutItemEnhancedResponse<T>> putItemWithResponse(
Consumer<PutItemEnhancedRequest.Builder<T>> requestConsumer) {
PutItemEnhancedRequest.Builder<T> builder =
PutItemEnhancedRequest.builder(this.tableSchema.itemType().rawClass());
requestConsumer.accept(builder);
return putItemWithResponse(builder.build());
}
@Override
public PagePublisher<T> scan(ScanEnhancedRequest request) {
PaginatedTableOperation<T, ?, ?> operation = ScanOperation.create(request);
return operation.executeOnPrimaryIndexAsync(tableSchema, tableName, extension, dynamoDbClient);
}
@Override
public PagePublisher<T> scan(Consumer<ScanEnhancedRequest.Builder> requestConsumer) {
ScanEnhancedRequest.Builder builder = ScanEnhancedRequest.builder();
requestConsumer.accept(builder);
return scan(builder.build());
}
@Override
public PagePublisher<T> scan() {
return scan(ScanEnhancedRequest.builder().build());
}
@Override
public CompletableFuture<T> updateItem(UpdateItemEnhancedRequest<T> request) {
TableOperation<T, ?, ?, UpdateItemEnhancedResponse<T>> operation = UpdateItemOperation.create(request);
return operation.executeOnPrimaryIndexAsync(tableSchema, tableName, extension, dynamoDbClient)
.thenApply(UpdateItemEnhancedResponse::attributes);
}
@Override
public CompletableFuture<T> updateItem(Consumer<UpdateItemEnhancedRequest.Builder<T>> requestConsumer) {
UpdateItemEnhancedRequest.Builder<T> builder =
UpdateItemEnhancedRequest.builder(this.tableSchema.itemType().rawClass());
requestConsumer.accept(builder);
return updateItem(builder.build());
}
@Override
public CompletableFuture<UpdateItemEnhancedResponse<T>> updateItemWithResponse(UpdateItemEnhancedRequest<T> request) {
TableOperation<T, ?, ?, UpdateItemEnhancedResponse<T>> operation = UpdateItemOperation.create(request);
return operation.executeOnPrimaryIndexAsync(tableSchema, tableName, extension, dynamoDbClient);
}
@Override
public CompletableFuture<UpdateItemEnhancedResponse<T>> updateItemWithResponse(
Consumer<UpdateItemEnhancedRequest.Builder<T>> requestConsumer) {
UpdateItemEnhancedRequest.Builder<T> builder =
UpdateItemEnhancedRequest.builder(this.tableSchema.itemType().rawClass());
requestConsumer.accept(builder);
return updateItemWithResponse(builder.build());
}
@Override
public CompletableFuture<T> updateItem(T item) {
return updateItem(r -> r.item(item));
}
@Override
public Key keyFrom(T item) {
return createKeyFromItem(item, tableSchema, TableMetadata.primaryIndexName());
}
@Override
public CompletableFuture<Void> deleteTable() {
TableOperation<T, ?, ?, Void> operation = DeleteTableOperation.create();
return operation.executeOnPrimaryIndexAsync(tableSchema, tableName, extension, dynamoDbClient);
}
@Override
public CompletableFuture<DescribeTableEnhancedResponse> describeTable() {
TableOperation<T, DescribeTableRequest, DescribeTableResponse, DescribeTableEnhancedResponse> operation =
DescribeTableOperation.create();
return operation.executeOnPrimaryIndexAsync(tableSchema, tableName, extension, dynamoDbClient);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DefaultDynamoDbAsyncTable<?> that = (DefaultDynamoDbAsyncTable<?>) o;
if (dynamoDbClient != null ? ! dynamoDbClient.equals(that.dynamoDbClient)
: that.dynamoDbClient != null) {
return false;
}
if (extension != null ? ! extension.equals(that.extension) : that.extension != null) {
return false;
}
if (tableSchema != null ? ! tableSchema.equals(that.tableSchema) : that.tableSchema != null) {
return false;
}
return tableName != null ? tableName.equals(that.tableName) : that.tableName == null;
}
@Override
public int hashCode() {
int result = dynamoDbClient != null ? dynamoDbClient.hashCode() : 0;
result = 31 * result + (extension != null ? extension.hashCode() : 0);
result = 31 * result + (tableSchema != null ? tableSchema.hashCode() : 0);
result = 31 * result + (tableName != null ? tableName.hashCode() : 0);
return result;
}
}
| 4,578 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/client/ExtensionResolver.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.client;
import java.util.Arrays;
import java.util.List;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClientExtension;
import software.amazon.awssdk.enhanced.dynamodb.extensions.AtomicCounterExtension;
import software.amazon.awssdk.enhanced.dynamodb.extensions.VersionedRecordExtension;
import software.amazon.awssdk.enhanced.dynamodb.internal.extensions.ChainExtension;
/**
* Static module to assist with the initialization of an extension for a DynamoDB Enhanced Client based on supplied
* configuration.
*/
@SdkInternalApi
public final class ExtensionResolver {
private static final DynamoDbEnhancedClientExtension DEFAULT_VERSIONED_RECORD_EXTENSION =
VersionedRecordExtension.builder().build();
private static final DynamoDbEnhancedClientExtension DEFAULT_ATOMIC_COUNTER_EXTENSION =
AtomicCounterExtension.builder().build();
private static final List<DynamoDbEnhancedClientExtension> DEFAULT_EXTENSIONS =
Arrays.asList(DEFAULT_VERSIONED_RECORD_EXTENSION, DEFAULT_ATOMIC_COUNTER_EXTENSION);
private ExtensionResolver() {
}
/**
* Static provider for the default extensions that are bundled with the DynamoDB Enhanced Client. Currently this is
* just the {@link software.amazon.awssdk.enhanced.dynamodb.extensions.VersionedRecordExtension}.
*
* These extensions will be used by default unless overridden in the enhanced client builder.
*/
public static List<DynamoDbEnhancedClientExtension> defaultExtensions() {
return DEFAULT_EXTENSIONS;
}
/**
* Resolves a list of extensions into a single extension. If the list is a singleton, will just return that extension
* otherwise it will combine them with the {@link software.amazon.awssdk.enhanced.dynamodb.internal.extensions.ChainExtension}
* meta-extension using the order provided in the list.
*
* @param extensions A list of extensions to be combined in strict order
* @return A single extension that combines all the supplied extensions or null if no extensions were provided
*/
public static DynamoDbEnhancedClientExtension resolveExtensions(List<DynamoDbEnhancedClientExtension> extensions) {
if (extensions == null || extensions.isEmpty()) {
return null;
}
if (extensions.size() == 1) {
return extensions.get(0);
}
return ChainExtension.create(extensions);
}
}
| 4,579 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/client/DefaultDynamoDbEnhancedAsyncClient.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.client;
import java.util.ArrayList;
import java.util.Arrays;
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.SdkInternalApi;
import software.amazon.awssdk.enhanced.dynamodb.Document;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedAsyncClient;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClientExtension;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.internal.operations.BatchGetItemOperation;
import software.amazon.awssdk.enhanced.dynamodb.internal.operations.BatchWriteItemOperation;
import software.amazon.awssdk.enhanced.dynamodb.internal.operations.TransactGetItemsOperation;
import software.amazon.awssdk.enhanced.dynamodb.internal.operations.TransactWriteItemsOperation;
import software.amazon.awssdk.enhanced.dynamodb.model.BatchGetItemEnhancedRequest;
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.TransactGetItemsEnhancedRequest;
import software.amazon.awssdk.enhanced.dynamodb.model.TransactWriteItemsEnhancedRequest;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
@SdkInternalApi
public final class DefaultDynamoDbEnhancedAsyncClient implements DynamoDbEnhancedAsyncClient {
private final DynamoDbAsyncClient dynamoDbClient;
private final DynamoDbEnhancedClientExtension extension;
private DefaultDynamoDbEnhancedAsyncClient(Builder builder) {
this.dynamoDbClient = builder.dynamoDbClient == null ? DynamoDbAsyncClient.create() : builder.dynamoDbClient;
this.extension = ExtensionResolver.resolveExtensions(builder.dynamoDbEnhancedClientExtensions);
}
public static Builder builder() {
return new Builder();
}
@Override
public <T> DefaultDynamoDbAsyncTable<T> table(String tableName, TableSchema<T> tableSchema) {
return new DefaultDynamoDbAsyncTable<>(dynamoDbClient, extension, tableSchema, tableName);
}
@Override
public BatchGetResultPagePublisher batchGetItem(BatchGetItemEnhancedRequest request) {
BatchGetItemOperation operation = BatchGetItemOperation.create(request);
return BatchGetResultPagePublisher.create(operation.executeAsync(dynamoDbClient, extension));
}
@Override
public BatchGetResultPagePublisher batchGetItem(
Consumer<BatchGetItemEnhancedRequest.Builder> requestConsumer) {
BatchGetItemEnhancedRequest.Builder builder = BatchGetItemEnhancedRequest.builder();
requestConsumer.accept(builder);
return batchGetItem(builder.build());
}
@Override
public CompletableFuture<BatchWriteResult> batchWriteItem(BatchWriteItemEnhancedRequest request) {
BatchWriteItemOperation operation = BatchWriteItemOperation.create(request);
return operation.executeAsync(dynamoDbClient, extension);
}
@Override
public CompletableFuture<BatchWriteResult> batchWriteItem(
Consumer<BatchWriteItemEnhancedRequest.Builder> requestConsumer) {
BatchWriteItemEnhancedRequest.Builder builder = BatchWriteItemEnhancedRequest.builder();
requestConsumer.accept(builder);
return batchWriteItem(builder.build());
}
@Override
public CompletableFuture<List<Document>> transactGetItems(TransactGetItemsEnhancedRequest request) {
TransactGetItemsOperation operation = TransactGetItemsOperation.create(request);
return operation.executeAsync(dynamoDbClient, extension);
}
@Override
public CompletableFuture<List<Document>> transactGetItems(
Consumer<TransactGetItemsEnhancedRequest.Builder> requestConsumer) {
TransactGetItemsEnhancedRequest.Builder builder = TransactGetItemsEnhancedRequest.builder();
requestConsumer.accept(builder);
return transactGetItems(builder.build());
}
@Override
public CompletableFuture<Void> transactWriteItems(TransactWriteItemsEnhancedRequest request) {
TransactWriteItemsOperation operation = TransactWriteItemsOperation.create(request);
return operation.executeAsync(dynamoDbClient, extension);
}
@Override
public CompletableFuture<Void> transactWriteItems(
Consumer<TransactWriteItemsEnhancedRequest.Builder> requestConsumer) {
TransactWriteItemsEnhancedRequest.Builder builder = TransactWriteItemsEnhancedRequest.builder();
requestConsumer.accept(builder);
return transactWriteItems(builder.build());
}
public DynamoDbAsyncClient dynamoDbAsyncClient() {
return dynamoDbClient;
}
public DynamoDbEnhancedClientExtension mapperExtension() {
return extension;
}
public Builder toBuilder() {
return builder().dynamoDbClient(this.dynamoDbClient).extensions(this.extension);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DefaultDynamoDbEnhancedAsyncClient that = (DefaultDynamoDbEnhancedAsyncClient) o;
if (dynamoDbClient != null ? ! dynamoDbClient.equals(that.dynamoDbClient)
: that.dynamoDbClient != null) {
return false;
}
return extension != null ? extension.equals(that.extension) : that.extension == null;
}
@Override
public int hashCode() {
int result = dynamoDbClient != null ? dynamoDbClient.hashCode() : 0;
result = 31 * result + (extension != null ? extension.hashCode() : 0);
return result;
}
@NotThreadSafe
public static final class Builder implements DynamoDbEnhancedAsyncClient.Builder {
private DynamoDbAsyncClient dynamoDbClient;
private List<DynamoDbEnhancedClientExtension> dynamoDbEnhancedClientExtensions =
new ArrayList<>(ExtensionResolver.defaultExtensions());
@Override
public DefaultDynamoDbEnhancedAsyncClient build() {
return new DefaultDynamoDbEnhancedAsyncClient(this);
}
@Override
public Builder dynamoDbClient(DynamoDbAsyncClient dynamoDbClient) {
this.dynamoDbClient = dynamoDbClient;
return this;
}
@Override
public Builder extensions(DynamoDbEnhancedClientExtension... dynamoDbEnhancedClientExtensions) {
this.dynamoDbEnhancedClientExtensions = Arrays.asList(dynamoDbEnhancedClientExtensions);
return this;
}
@Override
public Builder extensions(List<DynamoDbEnhancedClientExtension> dynamoDbEnhancedClientExtensions) {
this.dynamoDbEnhancedClientExtensions = new ArrayList<>(dynamoDbEnhancedClientExtensions);
return this;
}
}
}
| 4,580 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/client/DefaultDynamoDbAsyncIndex.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.client;
import static software.amazon.awssdk.enhanced.dynamodb.internal.EnhancedClientUtils.createKeyFromItem;
import java.util.function.Consumer;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.async.SdkPublisher;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbAsyncIndex;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClientExtension;
import software.amazon.awssdk.enhanced.dynamodb.Key;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.internal.operations.PaginatedIndexOperation;
import software.amazon.awssdk.enhanced.dynamodb.internal.operations.QueryOperation;
import software.amazon.awssdk.enhanced.dynamodb.internal.operations.ScanOperation;
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;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
@SdkInternalApi
public final class DefaultDynamoDbAsyncIndex<T> implements DynamoDbAsyncIndex<T> {
private final DynamoDbAsyncClient dynamoDbClient;
private final DynamoDbEnhancedClientExtension extension;
private final TableSchema<T> tableSchema;
private final String tableName;
private final String indexName;
DefaultDynamoDbAsyncIndex(DynamoDbAsyncClient dynamoDbClient,
DynamoDbEnhancedClientExtension extension,
TableSchema<T> tableSchema,
String tableName,
String indexName) {
this.dynamoDbClient = dynamoDbClient;
this.extension = extension;
this.tableSchema = tableSchema;
this.tableName = tableName;
this.indexName = indexName;
}
@Override
public SdkPublisher<Page<T>> query(QueryEnhancedRequest request) {
PaginatedIndexOperation<T, ?, ?> operation = QueryOperation.create(request);
return operation.executeOnSecondaryIndexAsync(tableSchema, tableName, indexName, extension, dynamoDbClient);
}
@Override
public SdkPublisher<Page<T>> query(Consumer<QueryEnhancedRequest.Builder> requestConsumer) {
QueryEnhancedRequest.Builder builder = QueryEnhancedRequest.builder();
requestConsumer.accept(builder);
return query(builder.build());
}
@Override
public SdkPublisher<Page<T>> query(QueryConditional queryConditional) {
return query(r -> r.queryConditional(queryConditional));
}
@Override
public SdkPublisher<Page<T>> scan(ScanEnhancedRequest request) {
PaginatedIndexOperation<T, ?, ?> operation = ScanOperation.create(request);
return operation.executeOnSecondaryIndexAsync(tableSchema, tableName, indexName, extension, dynamoDbClient);
}
@Override
public SdkPublisher<Page<T>> scan(Consumer<ScanEnhancedRequest.Builder> requestConsumer) {
ScanEnhancedRequest.Builder builder = ScanEnhancedRequest.builder();
requestConsumer.accept(builder);
return scan(builder.build());
}
@Override
public SdkPublisher<Page<T>> scan() {
return scan(ScanEnhancedRequest.builder().build());
}
@Override
public DynamoDbEnhancedClientExtension mapperExtension() {
return this.extension;
}
@Override
public TableSchema<T> tableSchema() {
return tableSchema;
}
public DynamoDbAsyncClient dynamoDbClient() {
return dynamoDbClient;
}
@Override
public String tableName() {
return tableName;
}
@Override
public String indexName() {
return indexName;
}
@Override
public Key keyFrom(T item) {
return createKeyFromItem(item, tableSchema, indexName);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DefaultDynamoDbAsyncIndex<?> that = (DefaultDynamoDbAsyncIndex<?>) o;
if (dynamoDbClient != null ? ! dynamoDbClient.equals(that.dynamoDbClient)
: that.dynamoDbClient != null) {
return false;
}
if (extension != null ? ! extension.equals(that.extension) : that.extension != null) {
return false;
}
if (tableSchema != null ? ! tableSchema.equals(that.tableSchema) : that.tableSchema != null) {
return false;
}
if (tableName != null ? ! tableName.equals(that.tableName) : that.tableName != null) {
return false;
}
return indexName != null ? indexName.equals(that.indexName) : that.indexName == null;
}
@Override
public int hashCode() {
int result = dynamoDbClient != null ? dynamoDbClient.hashCode() : 0;
result = 31 * result + (extension != null ? extension.hashCode() : 0);
result = 31 * result + (tableSchema != null ? tableSchema.hashCode() : 0);
result = 31 * result + (tableName != null ? tableName.hashCode() : 0);
result = 31 * result + (indexName != null ? indexName.hashCode() : 0);
return result;
}
}
| 4,581 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/client/IndexType.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.client;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* Enum collecting types of secondary indexes
*/
@SdkInternalApi
public enum IndexType {
LSI,
GSI
}
| 4,582 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/client/DefaultDynamoDbEnhancedClient.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.client;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import software.amazon.awssdk.annotations.NotThreadSafe;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.enhanced.dynamodb.Document;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClientExtension;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.internal.operations.BatchGetItemOperation;
import software.amazon.awssdk.enhanced.dynamodb.internal.operations.BatchWriteItemOperation;
import software.amazon.awssdk.enhanced.dynamodb.internal.operations.TransactGetItemsOperation;
import software.amazon.awssdk.enhanced.dynamodb.internal.operations.TransactWriteItemsOperation;
import software.amazon.awssdk.enhanced.dynamodb.model.BatchGetItemEnhancedRequest;
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.TransactGetItemsEnhancedRequest;
import software.amazon.awssdk.enhanced.dynamodb.model.TransactWriteItemsEnhancedRequest;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
@SdkInternalApi
public final class DefaultDynamoDbEnhancedClient implements DynamoDbEnhancedClient {
private final DynamoDbClient dynamoDbClient;
private final DynamoDbEnhancedClientExtension extension;
private DefaultDynamoDbEnhancedClient(Builder builder) {
this.dynamoDbClient = builder.dynamoDbClient == null ? DynamoDbClient.create() : builder.dynamoDbClient;
this.extension = ExtensionResolver.resolveExtensions(builder.dynamoDbEnhancedClientExtensions);
}
public static Builder builder() {
return new Builder();
}
@Override
public <T> DefaultDynamoDbTable<T> table(String tableName, TableSchema<T> tableSchema) {
return new DefaultDynamoDbTable<>(dynamoDbClient, extension, tableSchema, tableName);
}
@Override
public BatchGetResultPageIterable batchGetItem(BatchGetItemEnhancedRequest request) {
BatchGetItemOperation operation = BatchGetItemOperation.create(request);
return BatchGetResultPageIterable.create(operation.execute(dynamoDbClient, extension));
}
@Override
public BatchGetResultPageIterable batchGetItem(Consumer<BatchGetItemEnhancedRequest.Builder> requestConsumer) {
BatchGetItemEnhancedRequest.Builder builder = BatchGetItemEnhancedRequest.builder();
requestConsumer.accept(builder);
return batchGetItem(builder.build());
}
@Override
public BatchWriteResult batchWriteItem(BatchWriteItemEnhancedRequest request) {
BatchWriteItemOperation operation = BatchWriteItemOperation.create(request);
return operation.execute(dynamoDbClient, extension);
}
@Override
public BatchWriteResult batchWriteItem(Consumer<BatchWriteItemEnhancedRequest.Builder> requestConsumer) {
BatchWriteItemEnhancedRequest.Builder builder = BatchWriteItemEnhancedRequest.builder();
requestConsumer.accept(builder);
return batchWriteItem(builder.build());
}
@Override
public List<Document> transactGetItems(TransactGetItemsEnhancedRequest request) {
TransactGetItemsOperation operation = TransactGetItemsOperation.create(request);
return operation.execute(dynamoDbClient, extension);
}
@Override
public List<Document> transactGetItems(
Consumer<TransactGetItemsEnhancedRequest.Builder> requestConsumer) {
TransactGetItemsEnhancedRequest.Builder builder = TransactGetItemsEnhancedRequest.builder();
requestConsumer.accept(builder);
return transactGetItems(builder.build());
}
@Override
public Void transactWriteItems(TransactWriteItemsEnhancedRequest request) {
TransactWriteItemsOperation operation = TransactWriteItemsOperation.create(request);
return operation.execute(dynamoDbClient, extension);
}
@Override
public Void transactWriteItems(Consumer<TransactWriteItemsEnhancedRequest.Builder> requestConsumer) {
TransactWriteItemsEnhancedRequest.Builder builder = TransactWriteItemsEnhancedRequest.builder();
requestConsumer.accept(builder);
return transactWriteItems(builder.build());
}
public DynamoDbClient dynamoDbClient() {
return dynamoDbClient;
}
public DynamoDbEnhancedClientExtension mapperExtension() {
return extension;
}
public Builder toBuilder() {
return builder().dynamoDbClient(this.dynamoDbClient).extensions(this.extension);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DefaultDynamoDbEnhancedClient that = (DefaultDynamoDbEnhancedClient) o;
if (dynamoDbClient != null ? ! dynamoDbClient.equals(that.dynamoDbClient) : that.dynamoDbClient != null) {
return false;
}
return extension != null ?
extension.equals(that.extension) :
that.extension == null;
}
@Override
public int hashCode() {
int result = dynamoDbClient != null ? dynamoDbClient.hashCode() : 0;
result = 31 * result + (extension != null ?
extension.hashCode() : 0);
return result;
}
@NotThreadSafe
public static final class Builder implements DynamoDbEnhancedClient.Builder {
private DynamoDbClient dynamoDbClient;
private List<DynamoDbEnhancedClientExtension> dynamoDbEnhancedClientExtensions =
new ArrayList<>(ExtensionResolver.defaultExtensions());
@Override
public DefaultDynamoDbEnhancedClient build() {
return new DefaultDynamoDbEnhancedClient(this);
}
@Override
public Builder dynamoDbClient(DynamoDbClient dynamoDbClient) {
this.dynamoDbClient = dynamoDbClient;
return this;
}
@Override
public Builder extensions(DynamoDbEnhancedClientExtension... dynamoDbEnhancedClientExtensions) {
this.dynamoDbEnhancedClientExtensions = Arrays.asList(dynamoDbEnhancedClientExtensions);
return this;
}
@Override
public Builder extensions(List<DynamoDbEnhancedClientExtension> dynamoDbEnhancedClientExtensions) {
this.dynamoDbEnhancedClientExtensions = new ArrayList<>(dynamoDbEnhancedClientExtensions);
return this;
}
}
}
| 4,583 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/client/DefaultDynamoDbIndex.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.client;
import static software.amazon.awssdk.enhanced.dynamodb.internal.EnhancedClientUtils.createKeyFromItem;
import java.util.function.Consumer;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.pagination.sync.SdkIterable;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClientExtension;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbIndex;
import software.amazon.awssdk.enhanced.dynamodb.Key;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.internal.operations.PaginatedIndexOperation;
import software.amazon.awssdk.enhanced.dynamodb.internal.operations.QueryOperation;
import software.amazon.awssdk.enhanced.dynamodb.internal.operations.ScanOperation;
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;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
@SdkInternalApi
public class DefaultDynamoDbIndex<T> implements DynamoDbIndex<T> {
private final DynamoDbClient dynamoDbClient;
private final DynamoDbEnhancedClientExtension extension;
private final TableSchema<T> tableSchema;
private final String tableName;
private final String indexName;
DefaultDynamoDbIndex(DynamoDbClient dynamoDbClient,
DynamoDbEnhancedClientExtension extension,
TableSchema<T> tableSchema,
String tableName,
String indexName) {
this.dynamoDbClient = dynamoDbClient;
this.extension = extension;
this.tableSchema = tableSchema;
this.tableName = tableName;
this.indexName = indexName;
}
@Override
public SdkIterable<Page<T>> query(QueryEnhancedRequest request) {
PaginatedIndexOperation<T, ?, ?> operation = QueryOperation.create(request);
return operation.executeOnSecondaryIndex(tableSchema, tableName, indexName, extension, dynamoDbClient);
}
@Override
public SdkIterable<Page<T>> query(Consumer<QueryEnhancedRequest.Builder> requestConsumer) {
QueryEnhancedRequest.Builder builder = QueryEnhancedRequest.builder();
requestConsumer.accept(builder);
return query(builder.build());
}
@Override
public SdkIterable<Page<T>> query(QueryConditional queryConditional) {
return query(r -> r.queryConditional(queryConditional));
}
@Override
public SdkIterable<Page<T>> scan(ScanEnhancedRequest request) {
PaginatedIndexOperation<T, ?, ?> operation = ScanOperation.create(request);
return operation.executeOnSecondaryIndex(tableSchema, tableName, indexName, extension, dynamoDbClient);
}
@Override
public SdkIterable<Page<T>> scan(Consumer<ScanEnhancedRequest.Builder> requestConsumer) {
ScanEnhancedRequest.Builder builder = ScanEnhancedRequest.builder();
requestConsumer.accept(builder);
return scan(builder.build());
}
@Override
public SdkIterable<Page<T>> scan() {
return scan(ScanEnhancedRequest.builder().build());
}
@Override
public DynamoDbEnhancedClientExtension mapperExtension() {
return this.extension;
}
@Override
public TableSchema<T> tableSchema() {
return tableSchema;
}
public DynamoDbClient dynamoDbClient() {
return dynamoDbClient;
}
@Override
public String tableName() {
return tableName;
}
@Override
public String indexName() {
return indexName;
}
@Override
public Key keyFrom(T item) {
return createKeyFromItem(item, tableSchema, indexName);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DefaultDynamoDbIndex<?> that = (DefaultDynamoDbIndex<?>) o;
if (dynamoDbClient != null ? ! dynamoDbClient.equals(that.dynamoDbClient) : that.dynamoDbClient != null) {
return false;
}
if (extension != null ? ! extension.equals(that.extension) : that.extension != null) {
return false;
}
if (tableSchema != null ? ! tableSchema.equals(that.tableSchema) : that.tableSchema != null) {
return false;
}
if (tableName != null ? ! tableName.equals(that.tableName) : that.tableName != null) {
return false;
}
return indexName != null ? indexName.equals(that.indexName) : that.indexName == null;
}
@Override
public int hashCode() {
int result = dynamoDbClient != null ? dynamoDbClient.hashCode() : 0;
result = 31 * result + (extension != null ? extension.hashCode() : 0);
result = 31 * result + (tableSchema != null ? tableSchema.hashCode() : 0);
result = 31 * result + (tableName != null ? tableName.hashCode() : 0);
result = 31 * result + (indexName != null ? indexName.hashCode() : 0);
return result;
}
}
| 4,584 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/client/DefaultDynamoDbTable.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.internal.client;
import static java.util.Collections.emptyList;
import static software.amazon.awssdk.enhanced.dynamodb.internal.EnhancedClientUtils.createKeyFromItem;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClientExtension;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable;
import software.amazon.awssdk.enhanced.dynamodb.IndexMetadata;
import software.amazon.awssdk.enhanced.dynamodb.Key;
import software.amazon.awssdk.enhanced.dynamodb.KeyAttributeMetadata;
import software.amazon.awssdk.enhanced.dynamodb.TableMetadata;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.internal.operations.CreateTableOperation;
import software.amazon.awssdk.enhanced.dynamodb.internal.operations.DeleteItemOperation;
import software.amazon.awssdk.enhanced.dynamodb.internal.operations.DeleteTableOperation;
import software.amazon.awssdk.enhanced.dynamodb.internal.operations.DescribeTableOperation;
import software.amazon.awssdk.enhanced.dynamodb.internal.operations.GetItemOperation;
import software.amazon.awssdk.enhanced.dynamodb.internal.operations.PaginatedTableOperation;
import software.amazon.awssdk.enhanced.dynamodb.internal.operations.PutItemOperation;
import software.amazon.awssdk.enhanced.dynamodb.internal.operations.QueryOperation;
import software.amazon.awssdk.enhanced.dynamodb.internal.operations.ScanOperation;
import software.amazon.awssdk.enhanced.dynamodb.internal.operations.TableOperation;
import software.amazon.awssdk.enhanced.dynamodb.internal.operations.UpdateItemOperation;
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.EnhancedGlobalSecondaryIndex;
import software.amazon.awssdk.enhanced.dynamodb.model.EnhancedLocalSecondaryIndex;
import software.amazon.awssdk.enhanced.dynamodb.model.GetItemEnhancedRequest;
import software.amazon.awssdk.enhanced.dynamodb.model.GetItemEnhancedResponse;
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.DescribeTableRequest;
import software.amazon.awssdk.services.dynamodb.model.DescribeTableResponse;
import software.amazon.awssdk.services.dynamodb.model.ProjectionType;
@SdkInternalApi
public class DefaultDynamoDbTable<T> implements DynamoDbTable<T> {
private final DynamoDbClient dynamoDbClient;
private final DynamoDbEnhancedClientExtension extension;
private final TableSchema<T> tableSchema;
private final String tableName;
DefaultDynamoDbTable(DynamoDbClient dynamoDbClient,
DynamoDbEnhancedClientExtension extension,
TableSchema<T> tableSchema,
String tableName) {
this.dynamoDbClient = dynamoDbClient;
this.extension = extension;
this.tableSchema = tableSchema;
this.tableName = tableName;
}
@Override
public DynamoDbEnhancedClientExtension mapperExtension() {
return this.extension;
}
@Override
public TableSchema<T> tableSchema() {
return this.tableSchema;
}
public DynamoDbClient dynamoDbClient() {
return dynamoDbClient;
}
@Override
public String tableName() {
return tableName;
}
@Override
public DefaultDynamoDbIndex<T> index(String indexName) {
// Force a check for the existence of the index
tableSchema.tableMetadata().indexPartitionKey(indexName);
return new DefaultDynamoDbIndex<>(dynamoDbClient,
extension,
tableSchema,
tableName,
indexName);
}
@Override
public void createTable(CreateTableEnhancedRequest request) {
TableOperation<T, ?, ?, Void> operation = CreateTableOperation.create(request);
operation.executeOnPrimaryIndex(tableSchema, tableName, extension, dynamoDbClient);
}
@Override
public void createTable(Consumer<CreateTableEnhancedRequest.Builder> requestConsumer) {
CreateTableEnhancedRequest.Builder builder = CreateTableEnhancedRequest.builder();
requestConsumer.accept(builder);
createTable(builder.build());
}
@Override
public void createTable() {
Map<IndexType, List<IndexMetadata>> indexGroups = splitSecondaryIndicesToLocalAndGlobalOnes();
createTable(CreateTableEnhancedRequest.builder()
.localSecondaryIndices(extractLocalSecondaryIndices(indexGroups))
.globalSecondaryIndices(extractGlobalSecondaryIndices(indexGroups))
.build());
}
private Map<IndexType, List<IndexMetadata>> splitSecondaryIndicesToLocalAndGlobalOnes() {
Collection<IndexMetadata> indices = tableSchema.tableMetadata().indices();
return indices.stream()
.filter(index -> !TableMetadata.primaryIndexName().equals(index.name()))
.collect(Collectors.groupingBy(metadata -> {
String partitionKeyName = metadata.partitionKey().map(KeyAttributeMetadata::name).orElse(null);
if (partitionKeyName == null) {
return IndexType.LSI;
}
return IndexType.GSI;
}));
}
private List<EnhancedLocalSecondaryIndex> extractLocalSecondaryIndices(Map<IndexType, List<IndexMetadata>> indicesGroups) {
return indicesGroups.getOrDefault(IndexType.LSI, emptyList()).stream()
.map(this::mapIndexMetadataToEnhancedLocalSecondaryIndex)
.collect(Collectors.toList());
}
private EnhancedLocalSecondaryIndex mapIndexMetadataToEnhancedLocalSecondaryIndex(IndexMetadata indexMetadata) {
return EnhancedLocalSecondaryIndex.builder()
.indexName(indexMetadata.name())
.projection(pb -> pb.projectionType(ProjectionType.ALL))
.build();
}
private List<EnhancedGlobalSecondaryIndex> extractGlobalSecondaryIndices(Map<IndexType, List<IndexMetadata>> indicesGroups) {
return indicesGroups.getOrDefault(IndexType.GSI, emptyList()).stream()
.map(this::mapIndexMetadataToEnhancedGlobalSecondaryIndex)
.collect(Collectors.toList());
}
private EnhancedGlobalSecondaryIndex mapIndexMetadataToEnhancedGlobalSecondaryIndex(IndexMetadata indexMetadata) {
return EnhancedGlobalSecondaryIndex.builder()
.indexName(indexMetadata.name())
.projection(pb -> pb.projectionType(ProjectionType.ALL))
.build();
}
@Override
public T deleteItem(DeleteItemEnhancedRequest request) {
TableOperation<T, ?, ?, DeleteItemEnhancedResponse<T>> operation = DeleteItemOperation.create(request);
return operation.executeOnPrimaryIndex(tableSchema, tableName, extension, dynamoDbClient).attributes();
}
@Override
public T deleteItem(Consumer<DeleteItemEnhancedRequest.Builder> requestConsumer) {
DeleteItemEnhancedRequest.Builder builder = DeleteItemEnhancedRequest.builder();
requestConsumer.accept(builder);
return deleteItem(builder.build());
}
@Override
public T deleteItem(Key key) {
return deleteItem(r -> r.key(key));
}
@Override
public T deleteItem(T keyItem) {
return deleteItem(keyFrom(keyItem));
}
@Override
public DeleteItemEnhancedResponse<T> deleteItemWithResponse(DeleteItemEnhancedRequest request) {
TableOperation<T, ?, ?, DeleteItemEnhancedResponse<T>> operation = DeleteItemOperation.create(request);
return operation.executeOnPrimaryIndex(tableSchema, tableName, extension, dynamoDbClient);
}
@Override
public DeleteItemEnhancedResponse<T> deleteItemWithResponse(Consumer<DeleteItemEnhancedRequest.Builder> requestConsumer) {
DeleteItemEnhancedRequest.Builder builder = DeleteItemEnhancedRequest.builder();
requestConsumer.accept(builder);
return deleteItemWithResponse(builder.build());
}
@Override
public T getItem(GetItemEnhancedRequest request) {
TableOperation<T, ?, ?, GetItemEnhancedResponse<T>> operation = GetItemOperation.create(request);
return operation.executeOnPrimaryIndex(tableSchema, tableName, extension, dynamoDbClient).attributes();
}
@Override
public T getItem(Consumer<GetItemEnhancedRequest.Builder> requestConsumer) {
GetItemEnhancedRequest.Builder builder = GetItemEnhancedRequest.builder();
requestConsumer.accept(builder);
return getItem(builder.build());
}
@Override
public T getItem(Key key) {
return getItem(r -> r.key(key));
}
@Override
public T getItem(T keyItem) {
return getItem(keyFrom(keyItem));
}
@Override
public GetItemEnhancedResponse<T> getItemWithResponse(Consumer<GetItemEnhancedRequest.Builder> requestConsumer) {
GetItemEnhancedRequest.Builder builder = GetItemEnhancedRequest.builder();
requestConsumer.accept(builder);
return getItemWithResponse(builder.build());
}
@Override
public GetItemEnhancedResponse<T> getItemWithResponse(GetItemEnhancedRequest request) {
TableOperation<T, ?, ?, GetItemEnhancedResponse<T>> operation = GetItemOperation.create(request);
return operation.executeOnPrimaryIndex(tableSchema, tableName, extension, dynamoDbClient);
}
@Override
public PageIterable<T> query(QueryEnhancedRequest request) {
PaginatedTableOperation<T, ?, ?> operation = QueryOperation.create(request);
return operation.executeOnPrimaryIndex(tableSchema, tableName, extension, dynamoDbClient);
}
@Override
public PageIterable<T> query(Consumer<QueryEnhancedRequest.Builder> requestConsumer) {
QueryEnhancedRequest.Builder builder = QueryEnhancedRequest.builder();
requestConsumer.accept(builder);
return query(builder.build());
}
@Override
public PageIterable<T> query(QueryConditional queryConditional) {
return query(r -> r.queryConditional(queryConditional));
}
@Override
public void putItem(PutItemEnhancedRequest<T> request) {
TableOperation<T, ?, ?, PutItemEnhancedResponse<T>> operation = PutItemOperation.create(request);
operation.executeOnPrimaryIndex(tableSchema, tableName, extension, dynamoDbClient);
}
@Override
public void putItem(Consumer<PutItemEnhancedRequest.Builder<T>> requestConsumer) {
PutItemEnhancedRequest.Builder<T> builder =
PutItemEnhancedRequest.builder(this.tableSchema.itemType().rawClass());
requestConsumer.accept(builder);
putItem(builder.build());
}
@Override
public void putItem(T item) {
putItem(r -> r.item(item));
}
@Override
public PutItemEnhancedResponse<T> putItemWithResponse(PutItemEnhancedRequest<T> request) {
TableOperation<T, ?, ?, PutItemEnhancedResponse<T>> operation = PutItemOperation.create(request);
return operation.executeOnPrimaryIndex(tableSchema, tableName, extension, dynamoDbClient);
}
@Override
public PutItemEnhancedResponse<T> putItemWithResponse(Consumer<PutItemEnhancedRequest.Builder<T>> requestConsumer) {
PutItemEnhancedRequest.Builder<T> builder =
PutItemEnhancedRequest.builder(this.tableSchema.itemType().rawClass());
requestConsumer.accept(builder);
return putItemWithResponse(builder.build());
}
@Override
public PageIterable<T> scan(ScanEnhancedRequest request) {
PaginatedTableOperation<T, ?, ?> operation = ScanOperation.create(request);
return operation.executeOnPrimaryIndex(tableSchema, tableName, extension, dynamoDbClient);
}
@Override
public PageIterable<T> scan(Consumer<ScanEnhancedRequest.Builder> requestConsumer) {
ScanEnhancedRequest.Builder builder = ScanEnhancedRequest.builder();
requestConsumer.accept(builder);
return scan(builder.build());
}
@Override
public PageIterable<T> scan() {
return scan(ScanEnhancedRequest.builder().build());
}
@Override
public T updateItem(UpdateItemEnhancedRequest<T> request) {
TableOperation<T, ?, ?, UpdateItemEnhancedResponse<T>> operation = UpdateItemOperation.create(request);
return operation.executeOnPrimaryIndex(tableSchema, tableName, extension, dynamoDbClient).attributes();
}
@Override
public T updateItem(Consumer<UpdateItemEnhancedRequest.Builder<T>> requestConsumer) {
UpdateItemEnhancedRequest.Builder<T> builder =
UpdateItemEnhancedRequest.builder(this.tableSchema.itemType().rawClass());
requestConsumer.accept(builder);
return updateItem(builder.build());
}
@Override
public T updateItem(T item) {
return updateItem(r -> r.item(item));
}
@Override
public UpdateItemEnhancedResponse<T> updateItemWithResponse(UpdateItemEnhancedRequest<T> request) {
TableOperation<T, ?, ?, UpdateItemEnhancedResponse<T>> operation = UpdateItemOperation.create(request);
return operation.executeOnPrimaryIndex(tableSchema, tableName, extension, dynamoDbClient);
}
@Override
public UpdateItemEnhancedResponse<T> updateItemWithResponse(Consumer<UpdateItemEnhancedRequest.Builder<T>> requestConsumer) {
UpdateItemEnhancedRequest.Builder<T> builder =
UpdateItemEnhancedRequest.builder(this.tableSchema.itemType().rawClass());
requestConsumer.accept(builder);
return updateItemWithResponse(builder.build());
}
@Override
public Key keyFrom(T item) {
return createKeyFromItem(item, tableSchema, TableMetadata.primaryIndexName());
}
@Override
public void deleteTable() {
TableOperation<T, ?, ?, Void> operation = DeleteTableOperation.create();
operation.executeOnPrimaryIndex(tableSchema, tableName, extension, dynamoDbClient);
}
@Override
public DescribeTableEnhancedResponse describeTable() {
TableOperation<T, DescribeTableRequest, DescribeTableResponse, DescribeTableEnhancedResponse> operation =
DescribeTableOperation.create();
return operation.executeOnPrimaryIndex(tableSchema, tableName, extension, dynamoDbClient);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DefaultDynamoDbTable<?> that = (DefaultDynamoDbTable<?>) o;
if (dynamoDbClient != null ? ! dynamoDbClient.equals(that.dynamoDbClient) : that.dynamoDbClient != null) {
return false;
}
if (extension != null ?
!extension.equals(that.extension) :
that.extension != null) {
return false;
}
if (tableSchema != null ? ! tableSchema.equals(that.tableSchema) : that.tableSchema != null) {
return false;
}
return tableName != null ? tableName.equals(that.tableName) : that.tableName == null;
}
@Override
public int hashCode() {
int result = dynamoDbClient != null ? dynamoDbClient.hashCode() : 0;
result = 31 * result + (extension != null ?
extension.hashCode() : 0);
result = 31 * result + (tableSchema != null ? tableSchema.hashCode() : 0);
result = 31 * result + (tableName != null ? tableName.hashCode() : 0);
return result;
}
}
| 4,585 |
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/document/DocumentTableSchema.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import software.amazon.awssdk.annotations.NotThreadSafe;
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.AttributeValueType;
import software.amazon.awssdk.enhanced.dynamodb.DefaultAttributeConverterProvider;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable;
import software.amazon.awssdk.enhanced.dynamodb.EnhancedType;
import software.amazon.awssdk.enhanced.dynamodb.TableMetadata;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.internal.converter.ConverterProviderResolver;
import software.amazon.awssdk.enhanced.dynamodb.internal.document.DefaultEnhancedDocument;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticImmutableTableSchema;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableMetadata;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
/**
* Implementation of {@link TableSchema} that builds a table schema based on DynamoDB Items.
* <p>
* In Amazon DynamoDB, an item is a collection of attributes. Each attribute has a name and a value. An attribute value can be a
* scalar, a set, or a document type
* <p>
* A DocumentTableSchema is used to create a {@link DynamoDbTable} which provides read and writes access to DynamoDB table as
* {@link EnhancedDocument}.
* <p> DocumentTableSchema specifying primaryKey, sortKey and a customAttributeConverter can be created as below
* {@snippet :
* DocumentTableSchema documentTableSchema = DocumentTableSchema.builder()
* .addIndexPartitionKey("sampleIndexName", "sampleHashKey", AttributeValueType.S)
* .addIndexSortKey("sampleIndexName", "sampleSortKey", AttributeValueType.S)
* .attributeConverterProviders(customAttributeConverter, AttributeConverterProvider.defaultProvider())
* .build();
*}
* <p> DocumentTableSchema can also be created without specifying primaryKey and sortKey in which cases the
* {@link TableMetadata} of DocumentTableSchema will error if we try to access attributes from metaData. Also if
* attributeConverterProviders are not provided then {@link DefaultAttributeConverterProvider} will be used
* {@snippet :
* DocumentTableSchema documentTableSchema = DocumentTableSchema.builder().build();
*}
*
* @see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html" target="_top">Working
* with items and attributes</a>
*/
@SdkPublicApi
public final class DocumentTableSchema implements TableSchema<EnhancedDocument> {
private final TableMetadata tableMetadata;
private final List<AttributeConverterProvider> attributeConverterProviders;
private DocumentTableSchema(Builder builder) {
this.attributeConverterProviders = builder.attributeConverterProviders;
this.tableMetadata = builder.staticTableMetaDataBuilder.build();
}
public static Builder builder() {
return new Builder();
}
@Override
public EnhancedDocument mapToItem(Map<String, AttributeValue> attributeMap) {
if (attributeMap == null) {
return null;
}
DefaultEnhancedDocument.DefaultBuilder builder =
(DefaultEnhancedDocument.DefaultBuilder) DefaultEnhancedDocument.builder();
attributeMap.forEach(builder::putObject);
return builder.attributeConverterProviders(attributeConverterProviders)
.build();
}
/**
* {@inheritDoc}
*
* This flag does not have significance for the Document API, unlike Java objects where the default value of an undefined
* Object is null.In contrast to mapped classes, where a schema is present, the DocumentSchema is unaware of the entire
* schema.Therefore, if an attribute is not present, it signifies that it is null, and there is no need to handle it in a
* separate way.However, if the user explicitly wants to nullify certain attributes, then the user needs to set those
* attributes as null in the Document that needs to be updated.
*
*/
@Override
public Map<String, AttributeValue> itemToMap(EnhancedDocument item, boolean ignoreNulls) {
if (item == null) {
return null;
}
List<AttributeConverterProvider> providers = mergeAttributeConverterProviders(item);
return item.toBuilder().attributeConverterProviders(providers).build().toMap();
}
private List<AttributeConverterProvider> mergeAttributeConverterProviders(EnhancedDocument item) {
if (item.attributeConverterProviders() != null && !item.attributeConverterProviders().isEmpty()) {
Set<AttributeConverterProvider> providers = new LinkedHashSet<>();
providers.addAll(item.attributeConverterProviders());
providers.addAll(attributeConverterProviders);
return providers.stream().collect(Collectors.toList());
}
return attributeConverterProviders;
}
@Override
public Map<String, AttributeValue> itemToMap(EnhancedDocument item, Collection<String> attributes) {
if (item.toMap() == null) {
return null;
}
List<AttributeConverterProvider> providers = mergeAttributeConverterProviders(item);
return item.toBuilder().attributeConverterProviders(providers).build().toMap().entrySet()
.stream()
.filter(entry -> attributes.contains(entry.getKey()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(left, right) -> left, LinkedHashMap::new));
}
@Override
public AttributeValue attributeValue(EnhancedDocument item, String attributeName) {
if (item == null) {
return null;
}
List<AttributeConverterProvider> providers = mergeAttributeConverterProviders(item);
return item.toBuilder()
.attributeConverterProviders(providers)
.build()
.toMap()
.get(attributeName);
}
@Override
public TableMetadata tableMetadata() {
return tableMetadata;
}
@Override
public EnhancedType<EnhancedDocument> itemType() {
return EnhancedType.of(EnhancedDocument.class);
}
@Override
public List<String> attributeNames() {
return tableMetadata.keyAttributes().stream().map(key -> key.name()).collect(Collectors.toList());
}
@Override
public boolean isAbstract() {
return false;
}
@NotThreadSafe
public static final class Builder {
private final StaticTableMetadata.Builder staticTableMetaDataBuilder = StaticTableMetadata.builder();
/**
* By Default the defaultConverterProvider is used for converting AttributeValue to primitive types.
*/
private List<AttributeConverterProvider> attributeConverterProviders =
Collections.singletonList(ConverterProviderResolver.defaultConverterProvider());
/**
* 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) {
staticTableMetaDataBuilder.addIndexPartitionKey(indexName, 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) {
staticTableMetaDataBuilder.addIndexSortKey(indexName, attributeName, attributeValueType);
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 Custom types. The attribute converter providers will be loaded
* in the strict order they are supplied here.
* <p>
* By default, {@link DefaultAttributeConverterProvider} will be used, and it will provide standard converters for most
* primitive and common Java types. Configuring this will override the default behavior, so it is recommended to always
* append `DefaultAttributeConverterProvider` when you configure the custom attribute converter providers.
* <p>
* {@snippet :
* builder.attributeConverterProviders(customAttributeConverter, AttributeConverterProvider.defaultProvider());
*}
*
* @param attributeConverterProviders a list of attribute converter providers to use with the table schema
*/
public Builder 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>
* By default, {@link DefaultAttributeConverterProvider} will be used, and it will provide standard converters for most
* primitive and common Java types. Configuring this will override the default behavior, so it is recommended to always
* append `DefaultAttributeConverterProvider` when you configure the custom attribute converter providers.
* <p>
* {@snippet :
* 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 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 DocumentTableSchema build() {
return new DocumentTableSchema(this);
}
}
}
| 4,586 |
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/document/EnhancedDocument.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 software.amazon.awssdk.enhanced.dynamodb.AttributeConverterProvider.defaultProvider;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import software.amazon.awssdk.annotations.NotThreadSafe;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.core.SdkNumber;
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.document.DefaultEnhancedDocument;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.utils.Validate;
/**
* Interface representing the Document API for DynamoDB. The Document API operations are designed to work with open content,
* such as data with no fixed schema, data that cannot be modeled using rigid types, or data that has a schema.
* This interface provides all the methods required to access a Document, as well as constructor methods for creating a
* Document that can be used to read and write to DynamoDB using the EnhancedDynamoDB client.
* Additionally, this interface provides flexibility when working with data, as it allows you to work with data that is not
* necessarily tied to a specific data model.
* The EnhancedDocument interface provides two ways to use AttributeConverterProviders:
* <p>Enhanced Document with default attribute Converter to convert the attribute of DDB item to basic default primitive types in
* Java
* {@snippet :
* EnhancedDocument enhancedDocument = EnhancedDocument.builder().attributeConverterProviders(AttributeConverterProvider
* .defaultProvider()).build();
*}
* <p>Enhanced Document with Custom attribute Converter to convert the attribute of DDB Item to Custom Type.
* {@snippet :
* // CustomAttributeConverterProvider.create() is an example for some Custom converter provider
* EnhancedDocument enhancedDocumentWithCustomConverter = EnhancedDocument.builder().attributeConverterProviders
* (CustomAttributeConverterProvider.create(), AttributeConverterProvide.defaultProvider()
* .put("customObject", customObject, EnhancedType.of(CustomClass.class))
* .build();
*}
* <p>Enhanced Document can be created with Json as input using Static factory method.In this case it used
* defaultConverterProviders.
* {@snippet :
* EnhancedDocument enhancedDocumentWithCustomConverter = EnhancedDocument.fromJson("{\"k\":\"v\"}");
*}
* The attribute converter are always required to be provided, thus for default conversion
* {@link AttributeConverterProvider#defaultProvider()} must be supplied.
*/
@SdkPublicApi
public interface EnhancedDocument {
/**
* Creates a new <code>EnhancedDocument</code> instance from a JSON string.
* The {@link AttributeConverterProvider#defaultProvider()} is used as the default ConverterProvider.
* To use a custom ConverterProvider, use the builder methods: {@link Builder#json(String)} to supply the JSON string,
* then use {@link Builder#attributeConverterProviders(AttributeConverterProvider...)} to provide the custom
* ConverterProvider.
* {@snippet :
* EnhancedDocument documentFromJson = EnhancedDocument.fromJson("{\"key\": \"Value\"}");
*}
* @param json The JSON string representation of a DynamoDB Item.
* @return A new instance of EnhancedDocument.
* @throws IllegalArgumentException if the json parameter is null
*/
static EnhancedDocument fromJson(String json) {
Validate.paramNotNull(json, "json");
return DefaultEnhancedDocument.builder()
.json(json)
.attributeConverterProviders(defaultProvider())
.build();
}
/**
* Creates a new <code>EnhancedDocument</code> instance from a AttributeValue Map.
* The {@link AttributeConverterProvider#defaultProvider()} is used as the default ConverterProvider.
* Example usage:
* {@snippet :
* EnhancedDocument documentFromJson = EnhancedDocument.fromAttributeValueMap(stringKeyAttributeValueMao)});
*}
* @param attributeValueMap - Map with Attributes as String keys and AttributeValue as Value.
* @return A new instance of EnhancedDocument.
* @throws IllegalArgumentException if the json parameter is null
*/
static EnhancedDocument fromAttributeValueMap(Map<String, AttributeValue> attributeValueMap) {
Validate.paramNotNull(attributeValueMap, "attributeValueMap");
return DefaultEnhancedDocument.builder()
.attributeValueMap(attributeValueMap)
.attributeConverterProviders(defaultProvider())
.build();
}
/**
* Creates a default builder for {@link EnhancedDocument}.
*/
static Builder builder() {
return DefaultEnhancedDocument.builder();
}
/**
* Converts an existing EnhancedDocument into a builder object that can be used to modify its values and then create a new
* EnhancedDocument.
*
* @return A {@link EnhancedDocument.Builder} initialized with the values of this EnhancedDocument.
*/
Builder toBuilder();
/**
* Checks if the document is a {@code null} value.
*
* @param attributeName Name of the attribute that needs to be checked.
* @return true if the specified attribute exists with a null value; false otherwise.
*/
boolean isNull(String attributeName);
/**
* Checks if the attribute exists in the document.
*
* @param attributeName Name of the attribute that needs to be checked.
* @return true if the specified attribute exists with a null/non-null value; false otherwise.
*/
boolean isPresent(String attributeName);
/**
* Returns the value of the specified attribute in the current document as a specified {@link EnhancedType}; or null if the
* attribute either doesn't exist or the attribute value is null.
* <p>
* <b>Retrieving String Type for a document</b>
* {@snippet :
* String resultCustom = document.get("key", EnhancedType.of(String.class));
* }
* <b>Retrieving Custom Type for which Convertor Provider was defined while creating the document</b>
* {@snippet :
* Custom resultCustom = document.get("key", EnhancedType.of(Custom.class));
* }
* <b>Retrieving list of strings in a document</b>
* {@snippet :
* List<String> resultList = document.get("key", EnhancedType.listOf(String.class));
* }
* <b>Retrieving a Map with List of strings in its values</b>
* {@snippet :
* Map<String, List<String>>> resultNested = document.get("key", new EnhancedType<Map<String, List<String>>>(){});
* }
* </p>
* @param attributeName Name of the attribute.
* @param type EnhancedType of the value
* @param <T> The type of the attribute value.
* @return Attribute value of type T
* }
*/
<T> T get(String attributeName, EnhancedType<T> type);
/**
* Returns the value of the specified attribute in the current document as a specified class type; or null if the
* attribute either doesn't exist or the attribute value is null.
* <p>
* <b>Retrieving String Type for a document</b>
* {@snippet :
* String resultCustom = document.get("key", String.class);
* }
* <b>Retrieving Custom Type for which Convertor Provider was defined while creating the document</b>
* {@snippet :
* Custom resultCustom = document.get("key", Custom.class);
* }
* <p>
* Note :
* This API should not be used to retrieve values of List and Map types.
* Instead, getList and getMap APIs should be used to retrieve attributes of type List and Map, respectively.
* </p>
* @param attributeName Name of the attribute.
* @param clazz Class type of value.
* @param <T> The type of the attribute value.
* @return Attribute value of type T
* }
*/
<T> T get(String attributeName, Class<T> clazz);
/**
* Gets the String value of specified attribute in the document.
*
* @param attributeName Name of the attribute.
* @return value of the specified attribute in the current document as a string; or null if the attribute either doesn't exist
* or the attribute value is null
*/
String getString(String attributeName);
/**
* Gets the {@link SdkNumber} value of specified attribute in the document.
*
* @param attributeName Name of the attribute.
* @return value of the specified attribute in the current document as a number; or null if the attribute either doesn't exist
* or the attribute value is null
*/
SdkNumber getNumber(String attributeName);
/**
* Gets the {@link SdkBytes} value of specified attribute in the document.
*
* @param attributeName Name of the attribute.
* @return the value of the specified attribute in the current document as SdkBytes; or null if the attribute either
* doesn't exist or the attribute value is null.
*/
SdkBytes getBytes(String attributeName);
/**
* Gets the Set of String values of the given attribute in the current document.
* @param attributeName the name of the attribute.
* @return the value of the specified attribute in the current document as a set of strings; or null if the attribute either
* does not exist or the attribute value is null.
*/
Set<String> getStringSet(String attributeName);
/**
* Gets the Set of String values of the given attribute in the current document.
* @param attributeName Name of the attribute.
* @return value of the specified attribute in the current document as a set of SdkNumber; or null if the attribute either
* doesn't exist or the attribute value is null.
*/
Set<SdkNumber> getNumberSet(String attributeName);
/**
* Gets the Set of String values of the given attribute in the current document.
* @param attributeName Name of the attribute.
* @return value of the specified attribute in the current document as a set of SdkBytes;
* or null if the attribute doesn't exist.
*/
Set<SdkBytes> getBytesSet(String attributeName);
/**
* Gets the List of values of type T for the given attribute in the current document.
*
* @param attributeName Name of the attribute.
* @param type {@link EnhancedType} of Type T.
* @param <T> Type T of List elements
* @return value of the specified attribute in the current document as a list of type T,
* or null if the attribute does not exist.
*/
<T> List<T> getList(String attributeName, EnhancedType<T> type);
/**
* Returns a map of a specific Key-type and Value-type based on the given attribute name, key type, and value type.
* Example usage: When getting an attribute as a map of {@link UUID} keys and {@link Integer} values, use this API
* as shown below:
* {@snippet :
Map<String, Integer> result = document.getMap("key", EnhancedType.of(String.class), EnhancedType.of(Integer.class));
* }
* @param attributeName The name of the attribute that needs to be get as Map.
* @param keyType Enhanced Type of Key attribute, like String, UUID etc that can be represented as String Keys.
* @param valueType Enhanced Type of Values , which have converters defineds in
* {@link Builder#attributeConverterProviders(AttributeConverterProvider...)} for the document
* @return Map of type K and V with the given attribute name, key type, and value type.
* @param <K> The type of the Map keys.
* @param <V> The type of the Map values.
*/
<K, V> Map<K, V> getMap(String attributeName, EnhancedType<K> keyType, EnhancedType<V> valueType);
/**
* Gets the JSON document value of the specified attribute.
*
* @param attributeName Name of the attribute.
* @return value of the specified attribute in the current document as a JSON string; or null if the attribute either
* doesn't exist or the attribute value is null.
*/
String getJson(String attributeName);
/**
* Gets the {@link Boolean} value for the specified attribute.
*
* @param attributeName Name of the attribute.
* @return value of the specified attribute in the current document as a Boolean representation; or null if the attribute
* either doesn't exist or the attribute value is null.
* @throws RuntimeException
* if the attribute value cannot be converted to a Boolean representation.
* Note that the Boolean representation of 0 and 1 in Numbers and "0" and "1" in Strings is false and true,
* respectively.
*
*/
Boolean getBoolean(String attributeName);
/**
* Retrieves a list of {@link AttributeValue} objects for a specified attribute in a document.
* This API should be used when the elements of the list are a combination of different types such as Strings, Maps,
* and Numbers.
* If all elements in the list are of a known fixed type, use {@link EnhancedDocument#getList(String, EnhancedType)} instead.
*
* @param attributeName Name of the attribute.
* @return value of the specified attribute in the current document as a List of {@link AttributeValue}
*/
List<AttributeValue> getListOfUnknownType(String attributeName);
/**
* Retrieves a Map with String keys and corresponding AttributeValue objects as values for a specified attribute in a
* document. This API is particularly useful when the values of the map are of different types such as strings, maps, and
* numbers. However, if all the values in the map for a given attribute key are of a known fixed type, it is recommended to
* use the method EnhancedDocument#getMap(String, EnhancedType, EnhancedType) instead.
*
* @param attributeName Name of the attribute.
* @return value of the specified attribute in the current document as a {@link AttributeValue}
*/
Map<String, AttributeValue> getMapOfUnknownType(String attributeName);
/**
*
* @return document as a JSON string. Note all binary data will become base-64 encoded in the resultant string.
*/
String toJson();
/**
* This method converts a document into a key-value map with the keys as String objects and the values as AttributeValue
* objects. It can be particularly useful for documents with attributes of unknown types, as it allows for further processing
* or manipulation of the document data in a AttributeValue format.
* @return Document as a String AttributeValue Key-Value Map
*/
Map<String, AttributeValue> toMap();
/**
*
* @return List of AttributeConverterProvider defined for the given Document.
*/
List<AttributeConverterProvider> attributeConverterProviders();
@NotThreadSafe
interface Builder {
/**
* Appends an attribute of name attributeName with specified {@link String} value to the document builder.
* Use this method when you need to add a string value to a document. If you need to add an attribute with a value of a
* different type, such as a number or a map, use the appropriate put method instead
*
* @param attributeName the name of the attribute to be added to the document.
* @param value The string value that needs to be set.
* @return Builder instance to construct a {@link EnhancedDocument}
*/
Builder putString(String attributeName, String value);
/**
* Appends an attribute of name attributeName with specified {@link Number} value to the document builder.
* Use this method when you need to add a number value to a document. If you need to add an attribute with a value of a
* different type, such as a string or a map, use the appropriate put method instead
* @param attributeName the name of the attribute to be added to the document.
* @param value The number value that needs to be set.
* @return Builder instance to construct a {@link EnhancedDocument}
*/
Builder putNumber(String attributeName, Number value);
/**
* Appends an attribute of name attributeName with specified {@link SdkBytes} value to the document builder.
* Use this method when you need to add a binary value to a document. If you need to add an attribute with a value of a
* different type, such as a string or a map, use the appropriate put method instead
* @param attributeName the name of the attribute to be added to the document.
* @param value The byte array value that needs to be set.
* @return Builder instance to construct a {@link EnhancedDocument}
*/
Builder putBytes(String attributeName, SdkBytes value);
/**
* Use this method when you need to add a boolean value to a document. If you need to add an attribute with a value of a
* different type, such as a string or a map, use the appropriate put method instead.
* @param attributeName the name of the attribute to be added to the document.
* @param value The boolean value that needs to be set.
* @return Builder instance to construct a {@link EnhancedDocument}
*/
Builder putBoolean(String attributeName, boolean value);
/**
* Appends an attribute of name attributeName with a null value.
* Use this method is the attribute needs to explicitly set to null in Dynamo DB table.
*
* @param attributeName the name of the attribute to be added to the document.
* @return Builder instance to construct a {@link EnhancedDocument}
*/
Builder putNull(String attributeName);
/**
* Appends an attribute to the document builder with a Set of Strings as its value.
* This method is intended for use in DynamoDB where attribute values are stored as Sets of Strings.
* @param attributeName the name of the attribute to be added to the document.
* @param values Set of String values that needs to be set.
* @return Builder instance to construct a {@link EnhancedDocument}
*/
Builder putStringSet(String attributeName, Set<String> values);
/**
* Appends an attribute of name attributeName with specified Set of {@link Number} values to the document builder.
*
* @param attributeName the name of the attribute to be added to the document.
* @param values Set of Number values that needs to be set.
* @return Builder instance to construct a {@link EnhancedDocument}
*/
Builder putNumberSet(String attributeName, Set<Number> values);
/**
* Appends an attribute of name attributeName with specified Set of {@link SdkBytes} values to the document builder.
*
* @param attributeName the name of the attribute to be added to the document.
* @param values Set of SdkBytes values that needs to be set.
* @return Builder instance to construct a {@link EnhancedDocument}
*/
Builder putBytesSet(String attributeName, Set<SdkBytes> values);
/**
* Appends an attribute with the specified name and a list of {@link EnhancedType} T type elements to the document
* builder.
* Use {@link EnhancedType#of(Class)} to specify the class type of the list elements.
* <p>For example, to insert a list of String type:
* {@snippet :
* EnhancedDocument.builder().putList(stringList, EnhancedType.of(String.class))
* }
* <p>Example for inserting a List of Custom type .
* {@snippet :
* EnhancedDocument.builder().putList(stringList, EnhancedType.of(CustomClass.class));
* }
* Note that the AttributeConverterProvider added to the DocumentBuilder should provide the converter for the class T that
* is to be inserted.
* @param attributeName the name of the attribute to be added to the document.
* @param value The list of values that needs to be set.
* @return Builder instance to construct a {@link EnhancedDocument}
*/
<T> Builder putList(String attributeName, List<T> value, EnhancedType<T> type);
/**
* Appends an attribute named {@code attributeName} with a value of type {@link EnhancedType} T.
* Use this method to insert attribute values of custom types that have attribute converters defined in a converter
* provider.
* Example:
{@snippet :
* EnhancedDocument.builder().put("customKey", customValue, EnhancedType.of(CustomClass.class));
*}
* Use {@link #putString(String, String)} or {@link #putNumber(String, Number)} for inserting simple value types of
* attributes.
* Use {@link #putList(String, List, EnhancedType)} or {@link #putMap(String, Map, EnhancedType, EnhancedType)} for
* inserting collections of attribute values.
* Note that the attribute converter provider added to the DocumentBuilder must provide the converter for the class T
* that is to be inserted.
@param attributeName the name of the attribute to be added to the document.
@param value the value to set.
@param type the Enhanced type of the value to set.
@return a builder instance to construct a {@link EnhancedDocument}.
@param <T> the type of the value to set.
*/
<T> Builder put(String attributeName, T value, EnhancedType<T> type);
/**
* Appends an attribute named {@code attributeName} with a value of Class type T.
* Use this method to insert attribute values of custom types that have attribute converters defined in a converter
* provider.
* Example:
{@snippet :
* EnhancedDocument.builder().put("customKey", customValue, CustomClass.class);
*}
* Use {@link #putString(String, String)} or {@link #putNumber(String, Number)} for inserting simple value types of
* attributes.
* Use {@link #putList(String, List, EnhancedType)} or {@link #putMap(String, Map, EnhancedType, EnhancedType)} for
* inserting collections of attribute values.
* Note that the attribute converter provider added to the DocumentBuilder must provide the converter for the class T
* that is to be inserted.
@param attributeName the name of the attribute to be added to the document.
@param value the value to set.
@param type the type of the value to set.
@return a builder instance to construct a {@link EnhancedDocument}.
@param <T> the type of the value to set.
*/
<T> Builder put(String attributeName, T value, Class<T> type);
/**
* Appends an attribute with the specified name and a Map containing keys and values of {@link EnhancedType} K
* and V types,
* respectively, to the document builder. Use {@link EnhancedType#of(Class)} to specify the class type of the keys and
* values.
* <p>For example, to insert a map with String keys and Long values:
* {@snippet :
* EnhancedDocument.builder().putMap("stringMap", mapWithStringKeyNumberValue, EnhancedType.of(String.class),
* EnhancedType.of(String.class), EnhancedType.of(Long.class))
*}
* <p>For example, to insert a map of String Key and Custom Values:
* {@snippet :
* EnhancedDocument.builder().putMap("customMap", mapWithStringKeyCustomValue, EnhancedType.of(String.class),
* EnhancedType.of(String.class), EnhancedType.of(Custom.class))
*}
* Note that the AttributeConverterProvider added to the DocumentBuilder should provide the converter for the classes
* K and V that
* are to be inserted.
* @param attributeName the name of the attribute to be added to the document
* @param value The Map of values that needs to be set.
* @param keyType Enhanced type of Key class
* @param valueType Enhanced type of Value class.
* @return Builder instance to construct a {@link EnhancedDocument}
*/
<K, V> Builder putMap(String attributeName, Map<K, V> value, EnhancedType<K> keyType, EnhancedType<V> valueType);
/**
Appends an attribute to the document builder with the specified name and value of a JSON document in string format.
* @param attributeName the name of the attribute to be added to the document.
* @param json JSON document in the form of a string.
* @return Builder instance to construct a {@link EnhancedDocument}
*/
Builder putJson(String attributeName, String json);
/**
* Removes a previously appended attribute.
* This can be used where a previously added attribute to the Builder is no longer needed.
* @param attributeName The attribute that needs to be removed.
* @return Builder instance to construct a {@link EnhancedDocument}
*/
Builder remove(String attributeName);
/**
* Appends collection of attributeConverterProvider to the document builder. These
* AttributeConverterProvider will be used to convert any given key to custom type T.
* The first matching converter from the given provider will be selected based on the order in which they are added.
* @param attributeConverterProvider determining the {@link AttributeConverter} to use for converting a value.
* @return Builder instance to construct a {@link EnhancedDocument}
*/
Builder addAttributeConverterProvider(AttributeConverterProvider attributeConverterProvider);
/**
* Sets the collection of attributeConverterProviders to the document builder. These AttributeConverterProvider will be
* used to convert value of any given key to custom type T.
* The first matching converter from the given provider will be selected based on the order in which they are added.
* @param attributeConverterProviders determining the {@link AttributeConverter} to use for converting a value.
* @return Builder instance to construct a {@link EnhancedDocument}
*/
Builder attributeConverterProviders(List<AttributeConverterProvider> attributeConverterProviders);
/**
* Sets collection of attributeConverterProviders to the document builder. These AttributeConverterProvider will be
* used to convert any given key to custom type T.
* The first matching converter from the given provider will be selected based on the order in which they are added.
* @param attributeConverterProvider determining the {@link AttributeConverter} to use for converting a value.
* @return Builder instance to construct a {@link EnhancedDocument}
*/
Builder attributeConverterProviders(AttributeConverterProvider... attributeConverterProvider);
/**
* Sets the attributes of the document builder to those specified in the provided JSON string, and completely replaces
* any previously set attributes.
*
* @param json a JSON document represented as a string
* @return a builder instance to construct a {@link EnhancedDocument}
* @throws NullPointerException if the json parameter is null
*/
Builder json(String json);
/**
* Sets the attributes of the document builder to those specified in the provided from a AttributeValue Map, and
* completely replaces any previously set attributes.
*
* @param attributeValueMap - Map with Attributes as String keys and AttributeValue as Value.
* @return Builder instance to construct a {@link EnhancedDocument}
*/
Builder attributeValueMap(Map<String, AttributeValue> attributeValueMap);
/**
* Builds an instance of {@link EnhancedDocument}.
*
* @return instance of {@link EnhancedDocument} implementation.
*/
EnhancedDocument build();
}
}
| 4,587 |
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/extensions/ReadModification.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 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;
/**
* Simple object for storing a modification to a read operation. If a transformedItem is supplied then this item will
* be completely substituted in place of the item that was actually read.
*/
@SdkPublicApi
@ThreadSafe
public final class ReadModification {
private final Map<String, AttributeValue> transformedItem;
private ReadModification(Map<String, AttributeValue> transformedItem) {
this.transformedItem = transformedItem;
}
public static Builder builder() {
return new Builder();
}
public Map<String, AttributeValue> transformedItem() {
return transformedItem;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ReadModification that = (ReadModification) o;
return transformedItem != null ? transformedItem.equals(that.transformedItem) : that.transformedItem == null;
}
@Override
public int hashCode() {
return transformedItem != null ? transformedItem.hashCode() : 0;
}
@NotThreadSafe
public static final class Builder {
private Map<String, AttributeValue> transformedItem;
private Builder() {
}
public Builder transformedItem(Map<String, AttributeValue> transformedItem) {
this.transformedItem = transformedItem;
return this;
}
public ReadModification build() {
return new ReadModification(transformedItem);
}
}
}
| 4,588 |
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/extensions/AtomicCounterExtension.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 software.amazon.awssdk.enhanced.dynamodb.internal.EnhancedClientUtils.keyRef;
import static software.amazon.awssdk.enhanced.dynamodb.internal.EnhancedClientUtils.valueRef;
import static software.amazon.awssdk.enhanced.dynamodb.internal.update.UpdateExpressionUtils.ifNotExists;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClientExtension;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbExtensionContext;
import software.amazon.awssdk.enhanced.dynamodb.extensions.annotations.DynamoDbAtomicCounter;
import software.amazon.awssdk.enhanced.dynamodb.internal.extensions.AtomicCounterTag;
import software.amazon.awssdk.enhanced.dynamodb.internal.mapper.AtomicCounter;
import software.amazon.awssdk.enhanced.dynamodb.mapper.BeanTableSchema;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema;
import software.amazon.awssdk.enhanced.dynamodb.update.SetAction;
import software.amazon.awssdk.enhanced.dynamodb.update.UpdateExpression;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.utils.CollectionUtils;
import software.amazon.awssdk.utils.Logger;
/**
* This extension enables atomic counter attributes to be changed in DynamoDb by creating instructions for modifying
* an existing value or setting a start value. The extension is loaded by default when you instantiate a
* {@link DynamoDbEnhancedClient} and only needs to be added to the client if you are adding custom extensions to the client.
* <p>
* To utilize atomic counters, first create a field in your model that will be used to store the counter.
* This class field should of type {@link Long} and you need to tag it as an atomic counter:
* <ul>
* <li>If you are using the
* {@link BeanTableSchema}, you should annotate with
* {@link DynamoDbAtomicCounter}</li>
* <li>If you are using the {@link StaticTableSchema},
* use the {@link StaticAttributeTags#atomicCounter()} static attribute tag.</li>
* </ul>
* <p>
* Every time a new update of the record is successfully written to the database, the counter will be updated automatically.
* By default, the counter starts at 0 and increments by 1 for each update. The tags provide the capability of adjusting
* the counter start and increment/decrement values such as described in {@link DynamoDbAtomicCounter}.
* <p>
* Example 1: Using a bean based table schema
* <pre>
* {@code
* @DynamoDbBean
* public class CounterRecord {
* @DynamoDbAtomicCounter(delta = 5, startValue = 10)
* public Long getCustomCounter() {
* return customCounter;
* }
* }
* }
* </pre>
* <p>
* Example 2: Using a static table schema
* <pre>
* {@code
* private static final StaticTableSchema<AtomicCounterItem> ITEM_MAPPER =
* StaticTableSchema.builder(AtomicCounterItem.class)
* .newItemSupplier(AtomicCounterItem::new)
* .addAttribute(Long.class, a -> a.name("defaultCounter")
* .getter(AtomicCounterItem::getDefaultCounter)
* .setter(AtomicCounterItem::setDefaultCounter)
* .addTag(StaticAttributeTags.atomicCounter()))
* .build();
* }
* </pre>
* <p>
* <b>NOTES: </b>
* <ul>
* <li>When using putItem, the counter will be reset to its start value.</li>
* <li>The extension will remove any existing occurrences of the atomic counter attributes from the record during an
* <i>updateItem</i> operation. Manually editing attributes marked as atomic counters will have <b>NO EFFECT</b>.</li>
* </ul>
*/
@SdkPublicApi
public final class AtomicCounterExtension implements DynamoDbEnhancedClientExtension {
private static final Logger log = Logger.loggerFor(AtomicCounterExtension.class);
private AtomicCounterExtension() {
}
public static AtomicCounterExtension.Builder builder() {
return new AtomicCounterExtension.Builder();
}
/**
* @param context The {@link DynamoDbExtensionContext.BeforeWrite} context containing the state of the execution.
* @return WriteModification contains an update expression representing the counters.
*/
@Override
public WriteModification beforeWrite(DynamoDbExtensionContext.BeforeWrite context) {
Map<String, AtomicCounter> counters = AtomicCounterTag.resolve(context.tableMetadata());
WriteModification.Builder modificationBuilder = WriteModification.builder();
if (CollectionUtils.isNullOrEmpty(counters)) {
return modificationBuilder.build();
}
switch (context.operationName()) {
case PUT_ITEM:
modificationBuilder.transformedItem(addToItem(counters, context.items()));
break;
case UPDATE_ITEM:
modificationBuilder.updateExpression(createUpdateExpression(counters));
modificationBuilder.transformedItem(filterFromItem(counters, context.items()));
break;
default: break;
}
return modificationBuilder.build();
}
private UpdateExpression createUpdateExpression(Map<String, AtomicCounter> counters) {
return UpdateExpression.builder()
.actions(counters.entrySet().stream().map(this::counterAction).collect(Collectors.toList()))
.build();
}
private Map<String, AttributeValue> addToItem(Map<String, AtomicCounter> counters, Map<String, AttributeValue> items) {
Map<String, AttributeValue> itemToTransform = new HashMap<>(items);
counters.forEach((attribute, counter) -> itemToTransform.put(attribute, attributeValue(counter.startValue().value())));
return Collections.unmodifiableMap(itemToTransform);
}
private Map<String, AttributeValue> filterFromItem(Map<String, AtomicCounter> counters, Map<String, AttributeValue> items) {
Map<String, AttributeValue> itemToTransform = new HashMap<>(items);
List<String> removedAttributes = new ArrayList<>();
for (String attributeName : counters.keySet()) {
if (itemToTransform.containsKey(attributeName)) {
itemToTransform.remove(attributeName);
removedAttributes.add(attributeName);
}
}
if (!removedAttributes.isEmpty()) {
log.debug(() -> String.format("Filtered atomic counter attributes from existing update item to avoid collisions: %s",
String.join(",", removedAttributes)));
}
return Collections.unmodifiableMap(itemToTransform);
}
private SetAction counterAction(Map.Entry<String, AtomicCounter> e) {
String attributeName = e.getKey();
AtomicCounter counter = e.getValue();
String startValueName = attributeName + counter.startValue().name();
String deltaValueName = attributeName + counter.delta().name();
String valueExpression = ifNotExists(attributeName, startValueName) + " + " + valueRef(deltaValueName);
AttributeValue startValue = attributeValue(counter.startValue().value() - counter.delta().value());
AttributeValue deltaValue = attributeValue(counter.delta().value());
return SetAction.builder()
.path(keyRef(attributeName))
.value(valueExpression)
.putExpressionName(keyRef(attributeName), attributeName)
.putExpressionValue(valueRef(startValueName), startValue)
.putExpressionValue(valueRef(deltaValueName), deltaValue)
.build();
}
private AttributeValue attributeValue(long value) {
return AtomicCounter.CounterAttribute.resolvedValue(value);
}
public static final class Builder {
private Builder() {
}
public AtomicCounterExtension build() {
return new AtomicCounterExtension();
}
}
}
| 4,589 |
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/extensions/VersionedRecordExtension.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 software.amazon.awssdk.enhanced.dynamodb.internal.EnhancedClientUtils.isNullAttributeValue;
import static software.amazon.awssdk.enhanced.dynamodb.internal.EnhancedClientUtils.keyRef;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
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.AttributeValueType;
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.mapper.StaticAttributeTag;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableMetadata;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
/**
* This extension implements optimistic locking on record writes by means of a 'record version number' that is used
* to automatically track each revision of the record as it is modified.
* <p>
* This extension is loaded by default when you instantiate a
* {@link software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient} so unless you are using a custom extension
* there is no need to specify it.
* <p>
* To utilize versioned record locking, first create an attribute in your model that will be used to store the record
* version number. This attribute must be an 'integer' type numeric (long or integer), and you need to tag it as the
* version attribute. If you are using the {@link software.amazon.awssdk.enhanced.dynamodb.mapper.BeanTableSchema} then
* you should use the {@link software.amazon.awssdk.enhanced.dynamodb.extensions.annotations.DynamoDbVersionAttribute}
* annotation, otherwise if you are using the {@link software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema}
* then you should use the {@link AttributeTags#versionAttribute()} static attribute tag.
* <p>
* Then, whenever a record is written the write operation will only succeed if the version number of the record has not
* been modified since it was last read by the application. Every time a new version of the record is successfully
* written to the database, the record version number will be automatically incremented.
*/
@SdkPublicApi
@ThreadSafe
public final class VersionedRecordExtension implements DynamoDbEnhancedClientExtension {
private static final Function<String, String> VERSIONED_RECORD_EXPRESSION_VALUE_KEY_MAPPER = key -> ":old_" + key + "_value";
private static final String CUSTOM_METADATA_KEY = "VersionedRecordExtension:VersionAttribute";
private static final VersionAttribute VERSION_ATTRIBUTE = new VersionAttribute();
private VersionedRecordExtension() {
}
public static Builder builder() {
return new Builder();
}
public static final class AttributeTags {
private AttributeTags() {
}
public static StaticAttributeTag versionAttribute() {
return VERSION_ATTRIBUTE;
}
}
private static class VersionAttribute implements StaticAttributeTag {
@Override
public Consumer<StaticTableMetadata.Builder> modifyMetadata(String attributeName,
AttributeValueType attributeValueType) {
if (attributeValueType != AttributeValueType.N) {
throw new IllegalArgumentException(String.format(
"Attribute '%s' of type %s is not a suitable type to be used as a version attribute. Only type 'N' " +
"is supported.", attributeName, attributeValueType.name()));
}
return metadata -> metadata.addCustomMetadataObject(CUSTOM_METADATA_KEY, attributeName)
.markAttributeAsKey(attributeName, attributeValueType);
}
}
@Override
public WriteModification beforeWrite(DynamoDbExtensionContext.BeforeWrite context) {
Optional<String> versionAttributeKey = context.tableMetadata()
.customMetadataObject(CUSTOM_METADATA_KEY, String.class);
if (!versionAttributeKey.isPresent()) {
return WriteModification.builder().build();
}
Map<String, AttributeValue> itemToTransform = new HashMap<>(context.items());
String attributeKeyRef = keyRef(versionAttributeKey.get());
AttributeValue newVersionValue;
Expression condition;
Optional<AttributeValue> existingVersionValue =
Optional.ofNullable(itemToTransform.get(versionAttributeKey.get()));
if (!existingVersionValue.isPresent() || isNullAttributeValue(existingVersionValue.get())) {
// First version of the record
newVersionValue = AttributeValue.builder().n("1").build();
condition = Expression.builder()
.expression(String.format("attribute_not_exists(%s)", attributeKeyRef))
.expressionNames(Collections.singletonMap(attributeKeyRef, versionAttributeKey.get()))
.build();
} else {
// Existing record, increment version
if (existingVersionValue.get().n() == null) {
// In this case a non-null version attribute is present, but it's not an N
throw new IllegalArgumentException("Version attribute appears to be the wrong type. N is required.");
}
int existingVersion = Integer.parseInt(existingVersionValue.get().n());
String existingVersionValueKey = VERSIONED_RECORD_EXPRESSION_VALUE_KEY_MAPPER.apply(versionAttributeKey.get());
newVersionValue = AttributeValue.builder().n(Integer.toString(existingVersion + 1)).build();
condition = Expression.builder()
.expression(String.format("%s = %s", attributeKeyRef, existingVersionValueKey))
.expressionNames(Collections.singletonMap(attributeKeyRef, versionAttributeKey.get()))
.expressionValues(Collections.singletonMap(existingVersionValueKey,
existingVersionValue.get()))
.build();
}
itemToTransform.put(versionAttributeKey.get(), newVersionValue);
return WriteModification.builder()
.transformedItem(Collections.unmodifiableMap(itemToTransform))
.additionalConditionalExpression(condition)
.build();
}
@NotThreadSafe
public static final class Builder {
private Builder() {
}
public VersionedRecordExtension build() {
return new VersionedRecordExtension();
}
}
}
| 4,590 |
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/extensions/WriteModification.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 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.enhanced.dynamodb.Expression;
import software.amazon.awssdk.enhanced.dynamodb.update.UpdateExpression;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
/**
* Simple object for storing a modification to a write operation.
* <p>
* If a transformedItem is supplied then this item will be completely substituted in place of the item that was
* previously going to be written.
* <p>
* If an additionalConditionalExpression is supplied then this condition will be coalesced with any other conditions
* and added as a parameter to the write operation.
* <p>
* If an updateExpression is supplied then this update expression will be coalesced with any other update expressions
* and added as a parameter to the write operation.
*/
@SdkPublicApi
@ThreadSafe
public final class WriteModification {
private final Map<String, AttributeValue> transformedItem;
private final Expression additionalConditionalExpression;
private final UpdateExpression updateExpression;
private WriteModification(Builder builder) {
this.transformedItem = builder.transformedItem;
this.additionalConditionalExpression = builder.additionalConditionalExpression;
this.updateExpression = builder.updateExpression;
}
public static Builder builder() {
return new Builder();
}
public Map<String, AttributeValue> transformedItem() {
return transformedItem;
}
public Expression additionalConditionalExpression() {
return additionalConditionalExpression;
}
public UpdateExpression updateExpression() {
return updateExpression;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
WriteModification that = (WriteModification) o;
if (transformedItem != null ? ! transformedItem.equals(that.transformedItem) : that.transformedItem != null) {
return false;
}
if (additionalConditionalExpression != null ?
! additionalConditionalExpression.equals(that.additionalConditionalExpression) :
that.additionalConditionalExpression != null) {
return false;
}
return updateExpression != null ?
updateExpression.equals(that.updateExpression) :
that.updateExpression == null;
}
@Override
public int hashCode() {
int result = transformedItem != null ? transformedItem.hashCode() : 0;
result = 31 * result + (additionalConditionalExpression != null ? additionalConditionalExpression.hashCode() : 0);
result = 31 * result + (updateExpression != null ? updateExpression.hashCode() : 0);
return result;
}
@NotThreadSafe
public static final class Builder {
private Map<String, AttributeValue> transformedItem;
private Expression additionalConditionalExpression;
private UpdateExpression updateExpression;
private Builder() {
}
public Builder transformedItem(Map<String, AttributeValue> transformedItem) {
this.transformedItem = transformedItem;
return this;
}
public Builder additionalConditionalExpression(Expression additionalConditionalExpression) {
this.additionalConditionalExpression = additionalConditionalExpression;
return this;
}
public Builder updateExpression(UpdateExpression updateExpression) {
this.updateExpression = updateExpression;
return this;
}
public WriteModification build() {
return new WriteModification(this);
}
}
}
| 4,591 |
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/extensions/AutoGeneratedTimestampRecordExtension.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 java.time.Clock;
import java.time.Instant;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
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.enhanced.dynamodb.AttributeConverter;
import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClientExtension;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbExtensionContext;
import software.amazon.awssdk.enhanced.dynamodb.EnhancedType;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTag;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableMetadata;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.utils.Validate;
/**
* This extension enables selected attributes to be automatically updated with a current timestamp every time they are written
* to the database.
* <p>
* This extension is not loaded by default when you instantiate a
* {@link software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient}. Thus you need to specify it in custom extension
* while creating the enhanced client.
* <p>
* Example to add AutoGeneratedTimestampRecordExtension along with default extensions is
* <code>DynamoDbEnhancedClient.builder().extensions(Stream.concat(ExtensionResolver.defaultExtensions().stream(),
* Stream.of(AutoGeneratedTimestampRecordExtension.create())).collect(Collectors.toList())).build();</code>
* </p>
* <p>
* Example to just add AutoGeneratedTimestampRecordExtension without default extensions is
* <code>DynamoDbEnhancedClient.builder().extensions(AutoGeneratedTimestampRecordExtension.create())).build();</code>
* </p>
* </p>
* <p>
* To utilize auto generated timestamp update, first create a field in your model that will be used to store the record
* timestamp of modification. This class field must be an {@link Instant} Class type, and you need to tag it as the
* autoGeneratedTimeStampAttribute. If you are using the
* {@link software.amazon.awssdk.enhanced.dynamodb.mapper.BeanTableSchema}
* then you should use the
* {@link software.amazon.awssdk.enhanced.dynamodb.extensions.annotations.DynamoDbAutoGeneratedTimestampAttribute}
* annotation, otherwise if you are using the {@link software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema}
* then you should use the {@link AttributeTags#autoGeneratedTimestampAttribute()} static attribute tag.
* <p>
* Every time a new update of the record is successfully written to the database, the timestamp at which it was modified will
* be automatically updated. This extension applies the conversions as defined in the attribute convertor.
*/
@SdkPublicApi
@ThreadSafe
public final class AutoGeneratedTimestampRecordExtension implements DynamoDbEnhancedClientExtension {
private static final String CUSTOM_METADATA_KEY = "AutoGeneratedTimestampExtension:AutoGeneratedTimestampAttribute";
private static final AutoGeneratedTimestampAttribute
AUTO_GENERATED_TIMESTAMP_ATTRIBUTE = new AutoGeneratedTimestampAttribute();
private final Clock clock;
private AutoGeneratedTimestampRecordExtension() {
this.clock = Clock.systemUTC();
}
/**
* Attribute tag to identify the meta data for {@link AutoGeneratedTimestampRecordExtension}.
*/
public static final class AttributeTags {
private AttributeTags() {
}
/**
* Tags which indicate that the given attribute is supported wih Auto Generated Timestamp Record Extension.
* @return Tag name for AutoGenerated Timestamp Records
*/
public static StaticAttributeTag autoGeneratedTimestampAttribute() {
return AUTO_GENERATED_TIMESTAMP_ATTRIBUTE;
}
}
private AutoGeneratedTimestampRecordExtension(Builder builder) {
this.clock = builder.baseClock == null ? Clock.systemUTC() : builder.baseClock;
}
/**
* Create a builder that can be used to create a {@link AutoGeneratedTimestampRecordExtension}.
* @return Builder to create AutoGeneratedTimestampRecordExtension,
*/
public static Builder builder() {
return new Builder();
}
/**
* Returns a builder initialized with all existing values on the Extension object.
*/
public Builder toBuilder() {
return builder().baseClock(this.clock);
}
/**
* @return an Instance of {@link AutoGeneratedTimestampRecordExtension}
*/
public static AutoGeneratedTimestampRecordExtension create() {
return new AutoGeneratedTimestampRecordExtension();
}
/**
* @param context The {@link DynamoDbExtensionContext.BeforeWrite} context containing the state of the execution.
* @return WriteModification Instance updated with attribute updated with Extension.
*/
@Override
public WriteModification beforeWrite(DynamoDbExtensionContext.BeforeWrite context) {
Collection<String> customMetadataObject = context.tableMetadata()
.customMetadataObject(CUSTOM_METADATA_KEY, Collection.class).orElse(null);
if (customMetadataObject == null) {
return WriteModification.builder().build();
}
Map<String, AttributeValue> itemToTransform = new HashMap<>(context.items());
customMetadataObject.forEach(
key -> insertTimestampInItemToTransform(itemToTransform, key,
context.tableSchema().converterForAttribute(key)));
return WriteModification.builder()
.transformedItem(Collections.unmodifiableMap(itemToTransform))
.build();
}
private void insertTimestampInItemToTransform(Map<String, AttributeValue> itemToTransform,
String key,
AttributeConverter converter) {
itemToTransform.put(key, converter.transformFrom(clock.instant()));
}
/**
* Builder for a {@link AutoGeneratedTimestampRecordExtension}
*/
@NotThreadSafe
public static final class Builder {
private Clock baseClock;
private Builder() {
}
/**
* Sets the clock instance , else Clock.systemUTC() is used by default.
* Every time a new timestamp is generated this clock will be used to get the current point in time. If a custom clock
* is not specified, the default system clock will be used.
*
* @param clock Clock instance to set the current timestamp.
* @return This builder for method chaining.
*/
public Builder baseClock(Clock clock) {
this.baseClock = clock;
return this;
}
/**
* Builds an {@link AutoGeneratedTimestampRecordExtension} based on the values stored in this builder
*/
public AutoGeneratedTimestampRecordExtension build() {
return new AutoGeneratedTimestampRecordExtension(this);
}
}
private static class AutoGeneratedTimestampAttribute implements StaticAttributeTag {
@Override
public <R> void validateType(String attributeName, EnhancedType<R> type,
AttributeValueType attributeValueType) {
Validate.notNull(type, "type is null");
Validate.notNull(type.rawClass(), "rawClass is null");
Validate.notNull(attributeValueType, "attributeValueType is null");
if (!type.rawClass().equals(Instant.class)) {
throw new IllegalArgumentException(String.format(
"Attribute '%s' of Class type %s is not a suitable Java Class type to be used as a Auto Generated "
+ "Timestamp attribute. Only java.time.Instant Class type is supported.", attributeName, type.rawClass()));
}
}
@Override
public Consumer<StaticTableMetadata.Builder> modifyMetadata(String attributeName,
AttributeValueType attributeValueType) {
return metadata -> metadata.addCustomMetadataObject(CUSTOM_METADATA_KEY, Collections.singleton(attributeName))
.markAttributeAsKey(attributeName, attributeValueType);
}
}
}
| 4,592 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/extensions | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/extensions/annotations/DynamoDbAutoGeneratedTimestampAttribute.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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.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.extensions.AutoGeneratedTimestampRecordAttributeTags;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.BeanTableSchemaAttributeTag;
/**
* Denotes this attribute as recording the auto generated last updated timestamp for the record.
* Every time a record with this attribute is written to the database it will update the attribute with current timestamp when
* its updated.
*/
@SdkPublicApi
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@BeanTableSchemaAttributeTag(AutoGeneratedTimestampRecordAttributeTags.class)
public @interface DynamoDbAutoGeneratedTimestampAttribute {
}
| 4,593 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/extensions | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/extensions/annotations/DynamoDbVersionAttribute.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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.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.extensions.VersionRecordAttributeTags;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.BeanTableSchemaAttributeTag;
/**
* Denotes this attribute as recording the version record number to be used for optimistic locking. Every time a record
* with this attribute is written to the database it will be incremented and a condition added to the request to check
* for an exact match of the old version.
*/
@SdkPublicApi
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@BeanTableSchemaAttributeTag(VersionRecordAttributeTags.class)
public @interface DynamoDbVersionAttribute {
}
| 4,594 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/extensions | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/extensions/annotations/DynamoDbAtomicCounter.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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.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;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.BeanTableSchemaAttributeTag;
/**
* Used to explicitly designate an attribute to be an auto-generated counter updated unconditionally in DynamoDB.
* By default, the counter will start on 0 and increment with 1 for each subsequent calls to updateItem.
* By supplying a negative integer delta value, the attribute works as a decreasing counter.
*/
@SdkPublicApi
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@BeanTableSchemaAttributeTag(BeanTableSchemaAttributeTags.class)
public @interface DynamoDbAtomicCounter {
/**
* The value to increment (positive) or decrement (negative) the counter with for each update.
*/
long delta() default 1;
/**
* The starting value of the counter.
*/
long startValue() default 0;
}
| 4,595 |
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/model/QueryConditional.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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.function.Consumer;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.enhanced.dynamodb.Expression;
import software.amazon.awssdk.enhanced.dynamodb.Key;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.internal.conditional.BeginsWithConditional;
import software.amazon.awssdk.enhanced.dynamodb.internal.conditional.BetweenConditional;
import software.amazon.awssdk.enhanced.dynamodb.internal.conditional.EqualToConditional;
import software.amazon.awssdk.enhanced.dynamodb.internal.conditional.SingleKeyItemConditional;
/**
* An interface for a literal conditional that can be used in an enhanced DynamoDB query. Contains convenient static
* methods that can be used to construct the most common conditional statements. Query conditionals are not linked to
* any specific table or schema and can be re-used in different contexts.
* <p>
* Example:
* <pre>
* {@code
* QueryConditional sortValueGreaterThanFour = QueryConditional.sortGreaterThan(k -> k.partitionValue(10).sortValue(4));
* }
* </pre>
*/
@SdkPublicApi
@ThreadSafe
public interface QueryConditional {
/**
* Creates a {@link QueryConditional} that matches when the key of an index is equal to a specific value.
* @param key the literal key used to compare the value of the index against
*/
static QueryConditional keyEqualTo(Key key) {
return new EqualToConditional(key);
}
/**
* Creates a {@link QueryConditional} that matches when the key of an index is equal to a specific value.
* @param keyConsumer 'builder consumer' for the literal key used to compare the value of the index against
*/
static QueryConditional keyEqualTo(Consumer<Key.Builder> keyConsumer) {
Key.Builder builder = Key.builder();
keyConsumer.accept(builder);
return keyEqualTo(builder.build());
}
/**
* Creates a {@link QueryConditional} that matches when the key of an index is greater than a specific value.
* @param key the literal key used to compare the value of the index against
*/
static QueryConditional sortGreaterThan(Key key) {
return new SingleKeyItemConditional(key, ">");
}
/**
* Creates a {@link QueryConditional} that matches when the key of an index is greater than a specific value.
* @param keyConsumer 'builder consumer' for the literal key used to compare the value of the index against
*/
static QueryConditional sortGreaterThan(Consumer<Key.Builder> keyConsumer) {
Key.Builder builder = Key.builder();
keyConsumer.accept(builder);
return sortGreaterThan(builder.build());
}
/**
* Creates a {@link QueryConditional} that matches when the key of an index is greater than or equal to a specific
* value.
* @param key the literal key used to compare the value of the index against
*/
static QueryConditional sortGreaterThanOrEqualTo(Key key) {
return new SingleKeyItemConditional(key, ">=");
}
/**
* Creates a {@link QueryConditional} that matches when the key of an index is greater than or equal to a specific
* value.
* @param keyConsumer 'builder consumer' for the literal key used to compare the value of the index against
*/
static QueryConditional sortGreaterThanOrEqualTo(Consumer<Key.Builder> keyConsumer) {
Key.Builder builder = Key.builder();
keyConsumer.accept(builder);
return sortGreaterThanOrEqualTo(builder.build());
}
/**
* Creates a {@link QueryConditional} that matches when the key of an index is less than a specific value.
* @param key the literal key used to compare the value of the index against
*/
static QueryConditional sortLessThan(Key key) {
return new SingleKeyItemConditional(key, "<");
}
/**
* Creates a {@link QueryConditional} that matches when the key of an index is less than a specific value.
* @param keyConsumer 'builder consumer' for the literal key used to compare the value of the index against
*/
static QueryConditional sortLessThan(Consumer<Key.Builder> keyConsumer) {
Key.Builder builder = Key.builder();
keyConsumer.accept(builder);
return sortLessThan(builder.build());
}
/**
* Creates a {@link QueryConditional} that matches when the key of an index is less than or equal to a specific
* value.
* @param key the literal key used to compare the value of the index against
*/
static QueryConditional sortLessThanOrEqualTo(Key key) {
return new SingleKeyItemConditional(key, "<=");
}
/**
* Creates a {@link QueryConditional} that matches when the key of an index is less than or equal to a specific
* value.
* @param keyConsumer 'builder consumer' for the literal key used to compare the value of the index against
*/
static QueryConditional sortLessThanOrEqualTo(Consumer<Key.Builder> keyConsumer) {
Key.Builder builder = Key.builder();
keyConsumer.accept(builder);
return sortLessThanOrEqualTo(builder.build());
}
/**
* Creates a {@link QueryConditional} that matches when the key of an index is between two specific values.
* @param keyFrom the literal key used to compare the start of the range to compare the value of the index against
* @param keyTo the literal key used to compare the end of the range to compare the value of the index against
*/
static QueryConditional sortBetween(Key keyFrom, Key keyTo) {
return new BetweenConditional(keyFrom, keyTo);
}
/**
* Creates a {@link QueryConditional} that matches when the key of an index is between two specific values.
* @param keyFromConsumer 'builder consumer' for the literal key used to compare the start of the range to compare
* the value of the index against
* @param keyToConsumer 'builder consumer' for the literal key used to compare the end of the range to compare the
* value of the index against
*/
static QueryConditional sortBetween(Consumer<Key.Builder> keyFromConsumer, Consumer<Key.Builder> keyToConsumer) {
Key.Builder builderFrom = Key.builder();
Key.Builder builderTo = Key.builder();
keyFromConsumer.accept(builderFrom);
keyToConsumer.accept(builderTo);
return sortBetween(builderFrom.build(), builderTo.build());
}
/**
* Creates a {@link QueryConditional} that matches when the key of an index begins with a specific value.
* @param key the literal key used to compare the start of the value of the index against
*/
static QueryConditional sortBeginsWith(Key key) {
return new BeginsWithConditional(key);
}
/**
* Creates a {@link QueryConditional} that matches when the key of an index begins with a specific value.
* @param keyConsumer 'builder consumer' the literal key used to compare the start of the value of the index
* against
*/
static QueryConditional sortBeginsWith(Consumer<Key.Builder> keyConsumer) {
Key.Builder builder = Key.builder();
keyConsumer.accept(builder);
return sortBeginsWith(builder.build());
}
/**
* Generates a conditional {@link Expression} based on specific context that is supplied as arguments.
* @param tableSchema A {@link TableSchema} that this expression will be used with
* @param indexName The specific index name of the index this expression will be used with
* @return A specific {@link Expression} that can be used as part of a query request
*/
Expression expression(TableSchema<?> tableSchema, String indexName);
}
| 4,596 |
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/model/Page.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.ConsumedCapacity;
import software.amazon.awssdk.utils.ToString;
/**
* An immutable object that holds a page of queried or scanned results from DynamoDb.
* <p>
* Contains a reference to the last evaluated key for the current page; see {@link #lastEvaluatedKey()} for more information.
* @param <T> The modelled type of the object that has been read.
*/
@SdkPublicApi
@ThreadSafe
public final class Page<T> {
private final List<T> items;
private final Map<String, AttributeValue> lastEvaluatedKey;
private final Integer count;
private final Integer scannedCount;
private final ConsumedCapacity consumedCapacity;
private Page(List<T> items, Map<String, AttributeValue> lastEvaluatedKey) {
this.items = items;
this.lastEvaluatedKey = lastEvaluatedKey;
this.count = null;
this.scannedCount = null;
this.consumedCapacity = null;
}
private Page(Builder<T> builder) {
this.items = builder.items;
this.lastEvaluatedKey = builder.lastEvaluatedKey;
this.count = builder.count;
this.scannedCount = builder.scannedCount;
this.consumedCapacity = builder.consumedCapacity;
}
/**
* Static constructor for this object. Deprecated in favor of using the builder() pattern to construct this object.
*
* @param items A list of items to store for the page.
* @param lastEvaluatedKey A 'lastEvaluatedKey' to store for the page.
* @param <T> The modelled type of the object that has been read.
* @return A newly constructed {@link Page} object.
*/
@Deprecated
public static <T> Page<T> create(List<T> items, Map<String, AttributeValue> lastEvaluatedKey) {
return new Page<>(items, lastEvaluatedKey);
}
/**
* Static constructor for this object that sets a null 'lastEvaluatedKey' which indicates this is the final page
* of results. Deprecated in favor of using the builder() pattern to construct this object.
* @param items A list of items to store for the page.
* @param <T> The modelled type of the object that has been read.
* @return A newly constructed {@link Page} object.
*/
@Deprecated
public static <T> Page<T> create(List<T> items) {
return new Page<>(items, null);
}
/**
* Returns a page of mapped objects that represent records from a database query or scan.
* @return A list of mapped objects.
*/
public List<T> items() {
return items;
}
/**
* Returns the 'lastEvaluatedKey' that DynamoDb returned from the last page query or scan. This key can be used
* to continue the query or scan if passed into a request.
* @return The 'lastEvaluatedKey' from the last query or scan operation or null if the no more pages are available.
*/
public Map<String, AttributeValue> lastEvaluatedKey() {
return lastEvaluatedKey;
}
/**
* The count of the returned items from the last page query or scan, after any filters were applied.
*/
public Integer count() {
return count;
}
/**
* The scanned count of the returned items from the last page query or scan, before any filters were applied.
* This number will be equal or greater than the count.
*/
public Integer scannedCount() {
return scannedCount;
}
/**
* Returns the capacity units consumed by the last page query or scan. Will only be returned if it has been
* explicitly requested by the user when calling the operation.
*
* @return The 'consumedCapacity' from the last query or scan operation or null if it was not requested.
*/
public ConsumedCapacity consumedCapacity() {
return consumedCapacity;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Page<?> page = (Page<?>) o;
if (items != null ? ! items.equals(page.items) : page.items != null) {
return false;
}
if (lastEvaluatedKey != null ? ! lastEvaluatedKey.equals(page.lastEvaluatedKey) : page.lastEvaluatedKey != null) {
return false;
}
if (consumedCapacity != null ? ! consumedCapacity.equals(page.consumedCapacity) : page.consumedCapacity != null) {
return false;
}
if (count != null ? ! count.equals(page.count) : page.count != null) {
return false;
}
return scannedCount != null ? scannedCount.equals(page.scannedCount) : page.scannedCount == null;
}
@Override
public int hashCode() {
int result = items != null ? items.hashCode() : 0;
result = 31 * result + (lastEvaluatedKey != null ? lastEvaluatedKey.hashCode() : 0);
result = 31 * result + (consumedCapacity != null ? consumedCapacity.hashCode() : 0);
result = 31 * result + (count != null ? count.hashCode() : 0);
result = 31 * result + (scannedCount != null ? scannedCount.hashCode() : 0);
return result;
}
@Override
public String toString() {
return ToString.builder("Page")
.add("lastEvaluatedKey", lastEvaluatedKey)
.add("items", items)
.build();
}
public static <T> Builder<T> builder(Class<T> itemClass) {
return new Builder<>();
}
public static final class Builder<T> {
private List<T> items;
private Map<String, AttributeValue> lastEvaluatedKey;
private Integer count;
private Integer scannedCount;
private ConsumedCapacity consumedCapacity;
public Builder<T> items(List<T> items) {
this.items = new ArrayList<>(items);
return this;
}
public Builder<T> lastEvaluatedKey(Map<String, AttributeValue> lastEvaluatedKey) {
this.lastEvaluatedKey = new HashMap<>(lastEvaluatedKey);
return this;
}
public Builder<T> count(Integer count) {
this.count = count;
return this;
}
public Builder<T> scannedCount(Integer scannedCount) {
this.scannedCount = scannedCount;
return this;
}
public Builder<T> consumedCapacity(ConsumedCapacity consumedCapacity) {
this.consumedCapacity = consumedCapacity;
return this;
}
public Page<T> build() {
return new Page<T>(this);
}
}
}
| 4,597 |
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/model/BatchGetResultPage.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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.emptyList;
import static software.amazon.awssdk.enhanced.dynamodb.internal.EnhancedClientUtils.readAndTransformSingleItem;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
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.DynamoDbEnhancedClient;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClientExtension;
import software.amazon.awssdk.enhanced.dynamodb.Key;
import software.amazon.awssdk.enhanced.dynamodb.MappedTableResource;
import software.amazon.awssdk.enhanced.dynamodb.internal.operations.DefaultOperationContext;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.BatchGetItemResponse;
import software.amazon.awssdk.services.dynamodb.model.ConsumedCapacity;
import software.amazon.awssdk.services.dynamodb.model.KeysAndAttributes;
/**
* Defines one result page with retrieved items in the result of a batchGetItem() operation, such as
* {@link DynamoDbEnhancedClient#batchGetItem(BatchGetItemEnhancedRequest)}.
* <p>
* Use the {@link #resultsForTable(MappedTableResource)} method once for each table present in the request
* to retrieve items from that table in the page.
*/
@SdkPublicApi
@ThreadSafe
public final class BatchGetResultPage {
private final BatchGetItemResponse batchGetItemResponse;
private final DynamoDbEnhancedClientExtension dynamoDbEnhancedClientExtension;
private BatchGetResultPage(Builder builder) {
this.batchGetItemResponse = builder.batchGetItemResponse;
this.dynamoDbEnhancedClientExtension = builder.dynamoDbEnhancedClientExtension;
}
/**
* Creates a newly initialized builder for a result object.
*/
public static Builder builder() {
return new Builder();
}
/**
* Retrieve all items on this result page belonging to the supplied table. Call this method once for each table present in the
* batch request.
*
* @param mappedTable the table to retrieve items for
* @param <T> the type of the table items
* @return a list of items
*/
public <T> List<T> resultsForTable(MappedTableResource<T> mappedTable) {
List<Map<String, AttributeValue>> results =
batchGetItemResponse.responses()
.getOrDefault(mappedTable.tableName(), emptyList());
return results.stream()
.map(itemMap -> readAndTransformSingleItem(itemMap,
mappedTable.tableSchema(),
DefaultOperationContext.create(mappedTable.tableName()),
dynamoDbEnhancedClientExtension))
.collect(Collectors.toList());
}
/**
* Returns a list of keys associated with a given table that were not processed during the operation, typically
* because the total size of the request is too large or exceeds the provisioned throughput of the table. If an item
* was attempted to be retrieved but not found in the table, it will not appear in this list or the results list.
*
* @param mappedTable the table to retrieve the unprocessed keys for
* @return a list of unprocessed keys
*/
public List<Key> unprocessedKeysForTable(MappedTableResource<?> mappedTable) {
KeysAndAttributes keysAndAttributes = this.batchGetItemResponse.unprocessedKeys().get(mappedTable.tableName());
if (keysAndAttributes == null) {
return Collections.emptyList();
}
String partitionKey = mappedTable.tableSchema().tableMetadata().primaryPartitionKey();
Optional<String> sortKey = mappedTable.tableSchema().tableMetadata().primarySortKey();
return keysAndAttributes.keys()
.stream()
.map(keyMap -> {
AttributeValue partitionValue = keyMap.get(partitionKey);
AttributeValue sortValue = sortKey.map(keyMap::get).orElse(null);
return Key.builder()
.partitionValue(partitionValue)
.sortValue(sortValue)
.build(); })
.collect(Collectors.toList());
}
public List<ConsumedCapacity> consumedCapacity() {
return this.batchGetItemResponse.consumedCapacity();
}
/**
* A builder that is used to create a result object with the desired parameters.
*/
@NotThreadSafe
public static final class Builder {
private BatchGetItemResponse batchGetItemResponse;
private DynamoDbEnhancedClientExtension dynamoDbEnhancedClientExtension;
private Builder() {
}
/**
* Adds a response to the result object. Required.
*
* @param batchGetItemResponse
* @return a builder of this type
*/
public Builder batchGetItemResponse(BatchGetItemResponse batchGetItemResponse) {
this.batchGetItemResponse = batchGetItemResponse;
return this;
}
/**
* Adds a mapper extension that can be used to modify the values read from the database.
* @see DynamoDbEnhancedClientExtension
*
* @param dynamoDbEnhancedClientExtension the supplied mapper extension
* @return a builder of this type
*/
public Builder mapperExtension(DynamoDbEnhancedClientExtension dynamoDbEnhancedClientExtension) {
this.dynamoDbEnhancedClientExtension = dynamoDbEnhancedClientExtension;
return this;
}
public BatchGetResultPage build() {
return new BatchGetResultPage(this);
}
}
}
| 4,598 |
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/model/GetItemEnhancedRequest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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;
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.enhanced.dynamodb.DynamoDbAsyncTable;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable;
import software.amazon.awssdk.enhanced.dynamodb.Key;
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
import software.amazon.awssdk.services.dynamodb.model.ReturnConsumedCapacity;
/**
* Defines parameters used to retrieve an item from a DynamoDb table using the getItem() operation (such as
* {@link DynamoDbTable#getItem(GetItemEnhancedRequest)} or {@link DynamoDbAsyncTable#getItem(GetItemEnhancedRequest)}).
* <p>
* A valid request object must contain a primary {@link Key} to reference the item to get.
*/
@SdkPublicApi
@ThreadSafe
public final class GetItemEnhancedRequest {
private final Key key;
private final Boolean consistentRead;
private final String returnConsumedCapacity;
private GetItemEnhancedRequest(Builder builder) {
this.key = builder.key;
this.consistentRead = builder.consistentRead;
this.returnConsumedCapacity = builder.returnConsumedCapacity;
}
/**
* All requests must be constructed using a Builder.
* @return a builder of this type
*/
public static Builder builder() {
return new Builder();
}
/**
* @return a builder with all existing values set
*/
public Builder toBuilder() {
return builder().key(key).consistentRead(consistentRead).returnConsumedCapacity(returnConsumedCapacity);
}
/**
* @return whether or not this request will use consistent read
*/
public Boolean consistentRead() {
return this.consistentRead;
}
/**
* Returns the primary {@link Key} for the item to get.
*/
public Key key() {
return this.key;
}
/**
* Whether to return the capacity consumed by this operation.
*
* @see GetItemRequest#returnConsumedCapacity()
*/
public ReturnConsumedCapacity returnConsumedCapacity() {
return ReturnConsumedCapacity.fromValue(returnConsumedCapacity);
}
/**
* Whether to return the capacity consumed by this operation.
* <p>
* Similar to {@link #returnConsumedCapacity()} but return the value as a string. This is useful in situations where the
* value is not defined in {@link ReturnConsumedCapacity}.
*/
public String returnConsumedCapacityAsString() {
return returnConsumedCapacity;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
GetItemEnhancedRequest that = (GetItemEnhancedRequest) o;
return Objects.equals(key, that.key)
&& Objects.equals(consistentRead, that.consistentRead)
&& Objects.equals(returnConsumedCapacity, that.returnConsumedCapacity);
}
@Override
public int hashCode() {
int result = key != null ? key.hashCode() : 0;
result = 31 * result + (consistentRead != null ? consistentRead.hashCode() : 0);
result = 31 * result + (returnConsumedCapacity != null ? returnConsumedCapacity.hashCode() : 0);
return result;
}
/**
* A builder that is used to create a request with the desired parameters.
* <p>
* <b>Note</b>: A valid request builder must define a {@link Key}.
*/
@NotThreadSafe
public static final class Builder {
private Key key;
private Boolean consistentRead;
private String returnConsumedCapacity;
private Builder() {
}
/**
* Determines the read consistency model: If set to true, the operation uses strongly consistent reads; otherwise,
* the operation uses eventually consistent reads.
* <p>
* By default, the value of this property is set to <em>false</em>.
*
* @param consistentRead sets consistency model of the operation to use strong consistency
* @return a builder of this type
*/
public Builder consistentRead(Boolean consistentRead) {
this.consistentRead = consistentRead;
return this;
}
/**
* Sets the primary {@link Key} that will be used to match the item to retrieve.
*
* @param key the primary key to use in the request.
* @return a builder of this type
*/
public Builder key(Key key) {
this.key = key;
return this;
}
/**
* Sets the primary {@link Key} that will be used to match the item to retrieve
* by accepting a consumer of {@link Key.Builder}.
*
* @param keyConsumer a {@link Consumer} of {@link Key}
* @return a builder of this type
*/
public Builder key(Consumer<Key.Builder> keyConsumer) {
Key.Builder builder = Key.builder();
keyConsumer.accept(builder);
return key(builder.build());
}
/**
* Whether to return the capacity consumed by this operation.
*
* @see GetItemRequest.Builder#returnConsumedCapacity(ReturnConsumedCapacity)
*/
public Builder returnConsumedCapacity(ReturnConsumedCapacity returnConsumedCapacity) {
this.returnConsumedCapacity = returnConsumedCapacity == null ? null : returnConsumedCapacity.toString();
return this;
}
/**
* Whether to return the capacity consumed by this operation.
*
* @see GetItemRequest.Builder#returnConsumedCapacity(String)
*/
public Builder returnConsumedCapacity(String returnConsumedCapacity) {
this.returnConsumedCapacity = returnConsumedCapacity;
return this;
}
public GetItemEnhancedRequest build() {
return new GetItemEnhancedRequest(this);
}
}
}
| 4,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.