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/mapper
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper/annotations/DynamoDbAttribute.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.mapper.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import software.amazon.awssdk.annotations.SdkPublicApi; /** * Used to explicitly designate a field or getter or setter to participate as an attribute in the mapped database * object with a custom name. A string value must be specified to specify a different name for the attribute than the * mapper would automatically infer using a naming strategy. * * <p> * Example using {@link DynamoDbAttribute}: * <pre> * {@code * @DynamoDbBean * public class Bean { * private String internalKey; * * @DynamoDbAttribute("renamedInternalKey") * public String getInternalKey() { * return this.internalKey; * } * * public void setInternalKey(String internalKey) { * return this.internalKey = internalKey;} * } * } * } * </pre> */ @Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @SdkPublicApi public @interface DynamoDbAttribute { /** * The attribute name that this property should map to in the DynamoDb record. The value is case sensitive. */ String value(); }
4,400
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper/annotations/DynamoDbImmutable.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.mapper.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.enhanced.dynamodb.AttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.AttributeConverterProvider; import software.amazon.awssdk.enhanced.dynamodb.DefaultAttributeConverterProvider; import software.amazon.awssdk.enhanced.dynamodb.mapper.ImmutableTableSchema; /** * Class level annotation that identifies this class as being a DynamoDb mappable entity. Any class used to initialize * a {@link ImmutableTableSchema} must have this annotation. If a class is used as an attribute type within another * annotated DynamoDb class, either as a document or flattened with the {@link DynamoDbFlatten} annotation, it will also * require this annotation to work automatically without an explicit {@link AttributeConverter}. * <p> * <b>Attribute Converter Providers</b><br> * Using {@link AttributeConverterProvider}s is optional and, if used, the supplied provider supersedes the default * converter provided by the table schema. * <p> * Note: * <ul> * <li>The converter(s) must provide {@link AttributeConverter}s for all types used in the schema. </li> * <li>The table schema DefaultAttributeConverterProvider provides standard converters for most primitive * and common Java types. Use custom AttributeConverterProviders when you have specific needs for type conversion * that the defaults do not cover.</li> * <li>If you provide a list of attribute converter providers, you can add DefaultAttributeConverterProvider * to the end of the list to fall back on the defaults.</li> * <li>Providing an empty list {} will cause no providers to get loaded.</li> * </ul> * * Example using attribute converter providers with one custom provider and the default provider: * <pre> * {@code * (converterProviders = {CustomAttributeConverter.class, DefaultAttributeConverterProvider.class}); * } * </pre> * * <p> * Example using {@link DynamoDbImmutable}: * <pre> * {@code * @DynamoDbImmutable(builder = Customer.Builder.class) * public class Customer { * private final String accountId; * private final int subId; * private final String name; * private final Instant createdDate; * * private Customer(Builder b) { * this.accountId = b.accountId; * this.subId = b.subId; * this.name = b.name; * this.createdDate = b.createdDate; * } * * // This method will be automatically discovered and used by the TableSchema * public static Builder builder() { return new Builder(); } * * @DynamoDbPartitionKey * public String accountId() { return this.accountId; } * * @DynamoDbSortKey * public int subId() { return this.subId; } * * @DynamoDbSecondaryPartitionKey(indexNames = "customers_by_name") * public String name() { return this.name; } * * @DynamoDbSecondarySortKey(indexNames = {"customers_by_date", "customers_by_name"}) * public Instant createdDate() { return this.createdDate; } * * public static final class Builder { * private String accountId; * private int subId; * private String name; * private Instant createdDate; * * private Builder() {} * * public Builder accountId(String accountId) { this.accountId = accountId; return this; } * public Builder subId(int subId) { this.subId = subId; return this; } * public Builder name(String name) { this.name = name; return this; } * public Builder createdDate(Instant createdDate) { this.createdDate = createdDate; return this; } * * // This method will be automatically discovered and used by the TableSchema * public Customer build() { return new Customer(this); } * } * } * } * </pre> */ @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @SdkPublicApi public @interface DynamoDbImmutable { Class<? extends AttributeConverterProvider>[] converterProviders() default { DefaultAttributeConverterProvider.class }; /** * The builder class that can be used to construct instances of the annotated immutable class */ Class<?> builder(); }
4,401
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper/annotations/BeanTableSchemaAttributeTag.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.mapper.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.enhanced.dynamodb.internal.mapper.BeanTableSchemaAttributeTags; import software.amazon.awssdk.enhanced.dynamodb.mapper.BeanTableSchema; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTag; /** * This meta-annotation is not used directly in DynamoDb beans, it is used to annotate other annotations that are * used with DynamoDb beans. You should use this meta-annotation if you are creating new annotations for the * BeanTableSchema. * * Meta-annotation for BeanTableSchema annotations that are used to assign an {@link StaticAttributeTag} to a property on the * bean. When an annotation that is annotated with this meta-annotation is found on a property being scanned by the * {@link BeanTableSchema} then a static method * named 'attributeTagFor' will be invoked passing in a single argument which is the property annotation itself. * * See {@link BeanTableSchemaAttributeTags} for an example of how to implement the {@link StaticAttributeTag} suppliers for * bean mapper annotations. */ @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @SdkPublicApi public @interface BeanTableSchemaAttributeTag { Class<?> value(); }
4,402
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper/annotations/DynamoDbConvertedBy.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.mapper.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.enhanced.dynamodb.AttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.AttributeConverterProvider; /** * Associates a custom {@link AttributeConverter} with this attribute. This annotation is optional and takes * precedence over any converter for this type provided by the table schema {@link AttributeConverterProvider} * if it exists. Use custom AttributeConverterProvider when you have specific needs for type conversion * that the defaults do not cover. */ @Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @SdkPublicApi public @interface DynamoDbConvertedBy { Class<? extends AttributeConverter> value(); }
4,403
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper/annotations/DynamoDbUpdateBehavior.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.mapper.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.enhanced.dynamodb.internal.mapper.BeanTableSchemaAttributeTags; import software.amazon.awssdk.enhanced.dynamodb.mapper.UpdateBehavior; /** * Specifies the behavior when this attribute is updated as part of an 'update' operation such as UpdateItem. See * documentation of {@link UpdateBehavior} for details on the different behaviors supported and the default behavior. */ @SdkPublicApi @Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @BeanTableSchemaAttributeTag(BeanTableSchemaAttributeTags.class) public @interface DynamoDbUpdateBehavior { UpdateBehavior value(); }
4,404
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper/annotations/DynamoDbPreserveEmptyObject.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.mapper.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.Map; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; /** * Specifies that when calling {@link TableSchema#mapToItem(Map)}, a separate DynamoDB object that is stored in the current * object should be initialized as empty class if all fields in this class are null. Note that if this annotation is absent, * the object will be null. * * <p> * Example using {@link DynamoDbPreserveEmptyObject}: * <pre> * <code> * &#64;DynamoDbBean * public class NestedBean { * private AbstractBean innerBean1; * private AbstractBean innerBean2; * * &#64;DynamoDbPreserveEmptyObject * public AbstractBean getInnerBean1() { * return innerBean1; * } * public void setInnerBean1(AbstractBean innerBean) { * this.innerBean1 = innerBean; * } * * public AbstractBean getInnerBean2() { * return innerBean; * } * public void setInnerBean2(AbstractBean innerBean) { * this.innerBean2 = innerBean; * } * } * * BeanTableSchema<NestedBean> beanTableSchema = BeanTableSchema.create(NestedBean.class); * AbstractBean innerBean1 = new AbstractBean(); * AbstractBean innerBean2 = new AbstractBean(); * * NestedBean bean = new NestedBean(); * bean.setInnerBean1(innerBean1); * bean.setInnerBean2(innerBean2); * * Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(bean, true); * NestedBean nestedBean = beanTableSchema.mapToItem(itemMap); * * // innerBean1 w/ @DynamoDbPreserveEmptyObject is mapped to empty object * assertThat(nestedBean.getInnerBean1(), is(innerBean1)); * * // innerBean2 w/o @DynamoDbPreserveEmptyObject is mapped to null. * assertThat(nestedBean.getInnerBean2(), isNull()); * </code> * </pre> */ @SdkPublicApi @Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) public @interface DynamoDbPreserveEmptyObject { }
4,405
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper/annotations/DynamoDbSecondaryPartitionKey.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.mapper.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.enhanced.dynamodb.internal.mapper.BeanTableSchemaAttributeTags; /** * Denotes a partition key for a global secondary index. * * <p>You must also specify at least one index name. * * <p>The index name will be used if a table is created from this bean. For data-oriented operations like reads and writes, this * name does not need to match the service-side name of the index. */ @SdkPublicApi @Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @BeanTableSchemaAttributeTag(BeanTableSchemaAttributeTags.class) public @interface DynamoDbSecondaryPartitionKey { /** * The names of one or more global secondary indices that this partition key should participate in. */ String[] indexNames(); }
4,406
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper/annotations/DynamoDbPartitionKey.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.mapper.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.enhanced.dynamodb.internal.mapper.BeanTableSchemaAttributeTags; /** * Denotes this attribute as being the primary partition key of the DynamoDb table. This attribute must map to a * DynamoDb scalar type (string, number or binary) to be valid. Every mapped table schema must have exactly one of these. * * <p> * Example using {@link DynamoDbPartitionKey}: * <pre> * {@code * @DynamoDbBean * public class Customer { * private String id; * private Instant createdOn; * * @DynamoDbPartitionKey * public String getId() { * return this.id; * } * * public void setId(String id) { * this.name = id; * } * * public Instant getCreatedOn() { * return this.createdOn; * } * public void setCreatedOn(Instant createdOn) { * this.createdOn = createdOn; * } * } * } * </pre> */ @SdkPublicApi @Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @BeanTableSchemaAttributeTag(BeanTableSchemaAttributeTags.class) public @interface DynamoDbPartitionKey { }
4,407
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper/annotations/DynamoDbIgnoreNulls.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.mapper.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; /** * Specifies that when calling {@link TableSchema#itemToMap(Object, boolean)}, a separate DynamoDB object that is * stored in the current object should ignore the attributes with null values. Note that if this annotation is absent, NULL * attributes will be created. * * <p> * Example using {@link DynamoDbIgnoreNulls}: * <pre> * <code> * &#64;DynamoDbBean * public class NestedBean { * private AbstractBean innerBean1; * private AbstractBean innerBean2; * * &#64;DynamoDbIgnoreNulls * public AbstractBean getInnerBean1() { * return innerBean1; * } * public void setInnerBean1(AbstractBean innerBean) { * this.innerBean1 = innerBean; * } * * public AbstractBean getInnerBean2() { * return innerBean; * } * public void setInnerBean2(AbstractBean innerBean) { * this.innerBean2 = innerBean; * } * } * * BeanTableSchema<NestedBean> beanTableSchema = BeanTableSchema.create(NestedBean.class); * AbstractBean innerBean1 = new AbstractBean(); * AbstractBean innerBean2 = new AbstractBean(); * * NestedBean bean = new NestedBean(); * bean.setInnerBean1(innerBean1); * bean.setInnerBean2(innerBean2); * * Map<String, AttributeValue> itemMap = beanTableSchema.itemToMap(bean, true); * * // innerBean1 w/ @DynamoDbIgnoreNulls does not have any attribute values because all the fields are null * assertThat(itemMap.get("innerBean1").m(), empty()); * * // innerBean2 w/o @DynamoDbIgnoreNulls has a NULLL attribute. * assertThat(nestedBean.getInnerBean2(), hasEntry("attribute", nullAttributeValue())); * </code> * </pre> */ @SdkPublicApi @Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) public @interface DynamoDbIgnoreNulls { }
4,408
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper/annotations/DynamoDbIgnore.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.mapper.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import software.amazon.awssdk.annotations.SdkPublicApi; /** * Opts this attribute out of participating in the table schema. It will be completely ignored by the mapper. * <p> * Example using {@link DynamoDbAttribute}: * <pre> * {@code * @DynamoDbBean * public class Bean { * private String internalKey; * * @DynamoDbIgnore * public String getInternalKey() { * return this.internalKey; * } * * public void setInternalKey(String internalKey) { * return this.internalKey = internalKey;} * } * } * } * </pre> */ @Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @SdkPublicApi public @interface DynamoDbIgnore { }
4,409
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/internal/AttributeConfiguration.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkInternalApi; /** * Internal configuration for attribute */ @SdkInternalApi public final class AttributeConfiguration { private final boolean preserveEmptyObject; private final boolean ignoreNulls; public AttributeConfiguration(Builder builder) { this.preserveEmptyObject = builder.preserveEmptyObject; this.ignoreNulls = builder.ignoreNulls; } public boolean preserveEmptyObject() { return preserveEmptyObject; } public boolean ignoreNulls() { return ignoreNulls; } public static Builder builder() { return new Builder(); } @NotThreadSafe public static final class Builder { private boolean preserveEmptyObject; private boolean ignoreNulls; private Builder() { } public Builder preserveEmptyObject(boolean preserveEmptyObject) { this.preserveEmptyObject = preserveEmptyObject; return this; } public Builder ignoreNulls(boolean ignoreNulls) { this.ignoreNulls = ignoreNulls; return this; } public AttributeConfiguration build() { return new AttributeConfiguration(this); } } }
4,410
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/internal/ApplyUserAgentInterceptor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal; import java.util.function.Consumer; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration; import software.amazon.awssdk.core.ApiName; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.services.dynamodb.model.DynamoDbRequest; /** * Apply dynamodb enhanced client specific user agent to the request */ @SdkInternalApi public final class ApplyUserAgentInterceptor implements ExecutionInterceptor { private static final ApiName API_NAME = ApiName.builder().version("ddb-enh").name("hll").build(); private static final Consumer<AwsRequestOverrideConfiguration.Builder> USER_AGENT_APPLIER = b -> b.addApiName(API_NAME); @Override public SdkRequest modifyRequest(Context.ModifyRequest context, ExecutionAttributes executionAttributes) { if (!(context.request() instanceof DynamoDbRequest)) { // should never happen return context.request(); } DynamoDbRequest request = (DynamoDbRequest) context.request(); AwsRequestOverrideConfiguration overrideConfiguration = request.overrideConfiguration().map(c -> c.toBuilder() .applyMutation(USER_AGENT_APPLIER) .build()) .orElse((AwsRequestOverrideConfiguration.builder() .applyMutation(USER_AGENT_APPLIER) .build())); return request.toBuilder().overrideConfiguration(overrideConfiguration).build(); } }
4,411
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/internal/TransformIterator.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal; import java.util.Iterator; import java.util.function.Function; import software.amazon.awssdk.annotations.SdkInternalApi; // TODO: Consider moving to SDK core @SdkInternalApi public class TransformIterator<T, R> implements Iterator<R> { private final Iterator<T> wrappedIterator; private final Function<T, R> transformFunction; private TransformIterator(Iterator<T> wrappedIterator, Function<T, R> transformFunction) { this.wrappedIterator = wrappedIterator; this.transformFunction = transformFunction; } public static <T, R> TransformIterator<T, R> create(Iterator<T> iterator, Function<T, R> transformFunction) { return new TransformIterator<>(iterator, transformFunction); } @Override public boolean hasNext() { return wrappedIterator.hasNext(); } @Override public R next() { return transformFunction.apply(wrappedIterator.next()); } }
4,412
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/internal/DynamoDbEnhancedLogger.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.enhanced.dynamodb.mapper.BeanTableSchema; import software.amazon.awssdk.enhanced.dynamodb.mapper.ImmutableTableSchema; import software.amazon.awssdk.utils.Logger; @SdkInternalApi public class DynamoDbEnhancedLogger { /** * Logger used for to assist customers in debugging {@link BeanTableSchema} and {@link ImmutableTableSchema} loading. */ public static final Logger BEAN_LOGGER = Logger.loggerFor("software.amazon.awssdk.enhanced.dynamodb.beans"); private DynamoDbEnhancedLogger() { } }
4,413
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/internal/EnhancedClientUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; import software.amazon.awssdk.annotations.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.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.extensions.ReadModification; import software.amazon.awssdk.enhanced.dynamodb.internal.extensions.DefaultDynamoDbExtensionContext; import software.amazon.awssdk.enhanced.dynamodb.model.Page; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.ConsumedCapacity; @SdkInternalApi public final class EnhancedClientUtils { private static final Set<Character> SPECIAL_CHARACTERS = Stream.of( '*', '.', '-', '#', '+', ':', '/', '(', ')', ' ', '&', '<', '>', '?', '=', '!', '@', '%', '$', '|').collect(Collectors.toSet()); private EnhancedClientUtils() { } /** There is a divergence in what constitutes an acceptable attribute name versus a token used in expression * names or values. Since the mapper translates one to the other, it is necessary to scrub out all these * 'illegal' characters before adding them to expression values or expression names. * * @param key A key that may contain non alpha-numeric characters acceptable to a DynamoDb attribute name. * @return A key that has all these characters scrubbed and overwritten with an underscore. */ public static String cleanAttributeName(String key) { boolean somethingChanged = false; char[] chars = key.toCharArray(); for (int i = 0; i < chars.length; ++i) { if (SPECIAL_CHARACTERS.contains(chars[i])) { chars[i] = '_'; somethingChanged = true; } } return somethingChanged ? new String(chars) : key; } /** * Creates a key token to be used with an ExpressionNames map. */ public static String keyRef(String key) { return "#AMZN_MAPPED_" + cleanAttributeName(key); } /** * Creates a value token to be used with an ExpressionValues map. */ public static String valueRef(String value) { return ":AMZN_MAPPED_" + cleanAttributeName(value); } public static <T> T readAndTransformSingleItem(Map<String, AttributeValue> itemMap, TableSchema<T> tableSchema, OperationContext operationContext, DynamoDbEnhancedClientExtension dynamoDbEnhancedClientExtension) { if (itemMap == null || itemMap.isEmpty()) { return null; } if (dynamoDbEnhancedClientExtension != null) { ReadModification readModification = dynamoDbEnhancedClientExtension.afterRead( DefaultDynamoDbExtensionContext.builder() .items(itemMap) .tableSchema(tableSchema) .operationContext(operationContext) .tableMetadata(tableSchema.tableMetadata()) .build()); if (readModification != null && readModification.transformedItem() != null) { return tableSchema.mapToItem(readModification.transformedItem()); } } return tableSchema.mapToItem(itemMap); } public static <ResponseT, ItemT> Page<ItemT> readAndTransformPaginatedItems( ResponseT response, TableSchema<ItemT> tableSchema, OperationContext operationContext, DynamoDbEnhancedClientExtension dynamoDbEnhancedClientExtension, Function<ResponseT, List<Map<String, AttributeValue>>> getItems, Function<ResponseT, Map<String, AttributeValue>> getLastEvaluatedKey, Function<ResponseT, Integer> count, Function<ResponseT, Integer> scannedCount, Function<ResponseT, ConsumedCapacity> consumedCapacity) { List<ItemT> collect = getItems.apply(response) .stream() .map(itemMap -> readAndTransformSingleItem(itemMap, tableSchema, operationContext, dynamoDbEnhancedClientExtension)) .collect(Collectors.toList()); Page.Builder<ItemT> pageBuilder = Page.builder(tableSchema.itemType().rawClass()) .items(collect) .count(count.apply(response)) .scannedCount(scannedCount.apply(response)) .consumedCapacity(consumedCapacity.apply(response)); if (getLastEvaluatedKey.apply(response) != null && !getLastEvaluatedKey.apply(response).isEmpty()) { pageBuilder.lastEvaluatedKey(getLastEvaluatedKey.apply(response)); } return pageBuilder.build(); } public static <T> Key createKeyFromItem(T item, TableSchema<T> tableSchema, String indexName) { String partitionKeyName = tableSchema.tableMetadata().indexPartitionKey(indexName); Optional<String> sortKeyName = tableSchema.tableMetadata().indexSortKey(indexName); AttributeValue partitionKeyValue = tableSchema.attributeValue(item, partitionKeyName); Optional<AttributeValue> sortKeyValue = sortKeyName.map(key -> tableSchema.attributeValue(item, key)); return sortKeyValue.map( attributeValue -> Key.builder() .partitionValue(partitionKeyValue) .sortValue(attributeValue) .build()) .orElseGet( () -> Key.builder() .partitionValue(partitionKeyValue).build()); } public static Key createKeyFromMap(Map<String, AttributeValue> itemMap, TableSchema<?> tableSchema, String indexName) { String partitionKeyName = tableSchema.tableMetadata().indexPartitionKey(indexName); Optional<String> sortKeyName = tableSchema.tableMetadata().indexSortKey(indexName); AttributeValue partitionKeyValue = itemMap.get(partitionKeyName); Optional<AttributeValue> sortKeyValue = sortKeyName.map(itemMap::get); return sortKeyValue.map( attributeValue -> Key.builder() .partitionValue(partitionKeyValue) .sortValue(attributeValue) .build()) .orElseGet( () -> Key.builder() .partitionValue(partitionKeyValue).build()); } public static <T> List<T> getItemsFromSupplier(List<Supplier<T>> itemSupplierList) { if (itemSupplierList == null || itemSupplierList.isEmpty()) { return null; } return Collections.unmodifiableList(itemSupplierList.stream() .map(Supplier::get) .collect(Collectors.toList())); } /** * A helper method to test if an {@link AttributeValue} is a 'null' constant. This will not test if the * AttributeValue object is null itself, and in fact will throw a NullPointerException if you pass in null. * @param attributeValue An {@link AttributeValue} to test for null. * @return true if the supplied AttributeValue represents a null value, or false if it does not. */ public static boolean isNullAttributeValue(AttributeValue attributeValue) { return attributeValue.nul() != null && attributeValue.nul(); } }
4,414
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/internal/AttributeValues.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * This static helper class contains some literal {@link AttributeValue} constants and converters. Primarily these * will be used if constructing a literal key object or for use in a custom filter expression. Eg: * * {@code Key<?> myKey = Key.create(stringValue("id123"), numberValue(4.23)); * Expression filterExpression = Expression.of("id = :filter_id", singletonMap(":filter_id", stringValue("id123")); } */ @SdkInternalApi public final class AttributeValues { private static final AttributeValue NULL_ATTRIBUTE_VALUE = AttributeValue.builder().nul(true).build(); private AttributeValues() { } /** * The constant that represents a 'null' in a DynamoDb record. * @return An {@link AttributeValue} of type NUL that represents 'null'. */ public static AttributeValue nullAttributeValue() { return NULL_ATTRIBUTE_VALUE; } /** * Creates a literal string {@link AttributeValue}. * @param value A string to create the literal from. * @return An {@link AttributeValue} of type S that represents the string literal. */ public static AttributeValue stringValue(String value) { return AttributeValue.builder().s(value).build(); } /** * Creates a literal numeric {@link AttributeValue} from any type of Java number. * @param value A number to create the literal from. * @return An {@link AttributeValue} of type n that represents the numeric literal. */ public static AttributeValue numberValue(Number value) { return AttributeValue.builder().n(value.toString()).build(); } /** * Creates a literal binary {@link AttributeValue} from raw bytes. * @param value bytes to create the literal from. * @return An {@link AttributeValue} of type B that represents the binary literal. */ public static AttributeValue binaryValue(SdkBytes value) { return AttributeValue.builder().b(value).build(); } }
4,415
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/internal/ProjectionExpression.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal; import static software.amazon.awssdk.enhanced.dynamodb.internal.EnhancedClientUtils.cleanAttributeName; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.UnaryOperator; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.enhanced.dynamodb.NestedAttributeName; import software.amazon.awssdk.utils.CollectionUtils; import software.amazon.awssdk.utils.Pair; /** * This class represents the concept of a projection expression, which allows the user to specify which specific attributes * should be returned when a table is queried. By default, all attribute names in a projection expression are replaced with * a cleaned placeholder version of itself, prefixed with <i>#AMZN_MAPPED</i>. * <p> * A ProjectionExpression can return a correctly formatted projection expression string * containing placeholder names (see {@link #projectionExpressionAsString()}), as well as the expression attribute names map which * contains the mapping from the placeholder attribute name to the actual attribute name (see * {@link #expressionAttributeNames()}). * <p> * <b>Resolving duplicates</b> * <ul> * <li>If the input to the ProjectionExpression contains the same attribute name in more than one place, independent of * nesting level, it will be mapped to a single placeholder</li> * <li>If two attributes resolves to the same placeholder name, a disambiguator is added to the placeholder in order to * make it unique.</li> * </ul> * <p> * <b>Placeholder conversion examples</b> * <ul> * <li>'MyAttribute' maps to {@code #AMZN_MAPPED_MyAttribute}</li> * <li>'MyAttribute' appears twice in input but maps to only one entry {@code #AMZN_MAPPED_MyAttribute}.</li> * <li>'MyAttribute-1' maps to {@code #AMZN_MAPPED_MyAttribute_1}</li> * <li>'MyAttribute-1' and 'MyAttribute.1' in the same input maps to {@code #AMZN_MAPPED_0_MyAttribute_1} and * {@code #AMZN_MAPPED_1_MyAttribute_1}</li> * </ul> * <b>Projection expression usage example</b> * <pre> * {@code * List<NestedAttributeName> attributeNames = Arrays.asList( * NestedAttributeName.create("MyAttribute") * NestedAttributeName.create("MyAttribute.WithDot", "MyAttribute.03"), * NestedAttributeName.create("MyAttribute:03, "MyAttribute") * ); * ProjectionExpression projectionExpression = ProjectionExpression.create(attributeNames); * Map<String, String> expressionAttributeNames = projectionExpression.expressionAttributeNames(); * Optional<String> projectionExpressionString = projectionExpression.projectionExpressionAsString(); * } * * results in * * expressionAttributeNames: { * #AMZN_MAPPED_MyAttribute : MyAttribute, * #AMZN_MAPPED_MyAttribute_WithDot : MyAttribute.WithDot} * #AMZN_MAPPED_0_MyAttribute_03 : MyAttribute.03} * #AMZN_MAPPED_1_MyAttribute_03 : MyAttribute:03} * } * and * * projectionExpressionString: "#AMZN_MAPPED_MyAttribute,#AMZN_MAPPED_MyAttribute_WithDot.#AMZN_MAPPED_0_MyAttribute_03, * #AMZN_MAPPED_1_MyAttribute_03.#AMZN_MAPPED_MyAttribute" * </pre> * <p> * For more information, see <a href= * "https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.ProjectionExpressions.html" * >Projection Expressions</a> in the <i>Amazon DynamoDB Developer Guide</i>. * </p> */ @SdkInternalApi public class ProjectionExpression { private static final String AMZN_MAPPED = "#AMZN_MAPPED_"; private static final UnaryOperator<String> PROJECTION_EXPRESSION_KEY_MAPPER = k -> AMZN_MAPPED + cleanAttributeName(k); private final Optional<String> projectionExpressionAsString; private final Map<String, String> expressionAttributeNames; private ProjectionExpression(List<NestedAttributeName> nestedAttributeNames) { this.expressionAttributeNames = createAttributePlaceholders(nestedAttributeNames); this.projectionExpressionAsString = buildProjectionExpression(nestedAttributeNames, this.expressionAttributeNames); } public static ProjectionExpression create(List<NestedAttributeName> nestedAttributeNames) { return new ProjectionExpression(nestedAttributeNames); } public Map<String, String> expressionAttributeNames() { return this.expressionAttributeNames; } public Optional<String> projectionExpressionAsString() { return this.projectionExpressionAsString; } /** * Creates a map of modified attribute/placeholder name -> real attribute name based on what is essentially a list of list of * attribute names. Duplicates are removed from the list of attribute names and then the names are transformed * into DDB-compatible 'placeholders' using the supplied function, resulting in a * map of placeholder name -> list of original attribute names that resolved to that placeholder. * If different original attribute names end up having the same placeholder name, a disambiguator is added to those * placeholders to make them unique and the number of map entries expand with the length of that list; however this is * a rare use-case and normally it's a 1:1 relation. */ private static Map<String, String> createAttributePlaceholders(List<NestedAttributeName> nestedAttributeNames) { if (CollectionUtils.isNullOrEmpty(nestedAttributeNames)) { return new HashMap<>(); } Map<String, List<String>> placeholderToAttributeNames = nestedAttributeNames.stream() .flatMap(n -> n.elements().stream()) .distinct() .collect(Collectors.groupingBy(PROJECTION_EXPRESSION_KEY_MAPPER, Collectors.toList())); return Collections.unmodifiableMap( placeholderToAttributeNames.entrySet() .stream() .flatMap(entry -> disambiguateNonUniquePlaceholderNames(entry.getKey(), entry.getValue())) .collect(Collectors.toMap(Pair::left, Pair::right))); } private static Stream<Pair<String, String>> disambiguateNonUniquePlaceholderNames(String placeholder, List<String> values) { if (values.size() == 1) { return Stream.of(Pair.of(placeholder, values.get(0))); } return IntStream.range(0, values.size()) .mapToObj(index -> Pair.of(addDisambiguator(placeholder, index), values.get(index))); } private static String addDisambiguator(String placeholder, int index) { return AMZN_MAPPED + index + "_" + placeholder.substring(AMZN_MAPPED.length()); } /** * The projection expression contains only placeholder names, and is based on the list if nested attribute names, which * are converted into string representations with each attribute name replaced by its placeholder name as specified * in the expressionAttributeNames map. Because we need to find the placeholder value of an attribute, the * expressionAttributeNames map must be reversed before doing a lookup. */ private static Optional<String> buildProjectionExpression(List<NestedAttributeName> nestedAttributeNames, Map<String, String> expressionAttributeNames) { if (CollectionUtils.isNullOrEmpty(nestedAttributeNames)) { return Optional.empty(); } Map<String, String> attributeToPlaceholderNames = CollectionUtils.inverseMap(expressionAttributeNames); return Optional.of(nestedAttributeNames.stream() .map(attributeName -> convertToNameExpression(attributeName, attributeToPlaceholderNames)) .distinct() .collect(Collectors.joining(","))); } private static String convertToNameExpression(NestedAttributeName nestedAttributeName, Map<String, String> attributeToSanitizedMap) { return nestedAttributeName.elements() .stream() .map(attributeToSanitizedMap::get) .collect(Collectors.joining(".")); } }
4,416
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/internal/TransformIterable.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal; import java.util.Iterator; import java.util.function.Function; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.pagination.sync.SdkIterable; // TODO: Consider moving to SDK core @SdkInternalApi public class TransformIterable<T, R> implements SdkIterable<R> { private final Iterable<T> wrappedIterable; private final Function<T, R> transformFunction; private TransformIterable(Iterable<T> wrappedIterable, Function<T, R> transformFunction) { this.wrappedIterable = wrappedIterable; this.transformFunction = transformFunction; } public static <T, R> TransformIterable<T, R> of(SdkIterable<T> iterable, Function<T, R> transformFunction) { return new TransformIterable<>(iterable, transformFunction); } @Override public Iterator<R> iterator() { return TransformIterator.create(wrappedIterable.iterator(), transformFunction); } }
4,417
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/internal/DefaultDocument.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal; import static software.amazon.awssdk.enhanced.dynamodb.internal.EnhancedClientUtils.readAndTransformSingleItem; import java.util.Map; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.enhanced.dynamodb.Document; import software.amazon.awssdk.enhanced.dynamodb.MappedTableResource; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.DefaultOperationContext; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; @SdkInternalApi public final class DefaultDocument implements Document { private final Map<String, AttributeValue> itemMap; private DefaultDocument(Map<String, AttributeValue> itemMap) { this.itemMap = itemMap; } public static DefaultDocument create(Map<String, AttributeValue> itemMap) { return new DefaultDocument(itemMap); } @Override public <T> T getItem(MappedTableResource<T> mappedTableResource) { return readAndTransformSingleItem(itemMap, mappedTableResource.tableSchema(), DefaultOperationContext.create(mappedTableResource.tableName()), mappedTableResource.mapperExtension()); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DefaultDocument that = (DefaultDocument) o; return itemMap != null ? itemMap.equals(that.itemMap) : that.itemMap == null; } @Override public int hashCode() { return itemMap != null ? itemMap.hashCode() : 0; } }
4,418
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/immutable/ImmutablePropertyDescriptor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.immutable; import java.lang.reflect.Method; import software.amazon.awssdk.annotations.SdkInternalApi; @SdkInternalApi public final class ImmutablePropertyDescriptor { private final String name; private final Method getter; private final Method setter; private ImmutablePropertyDescriptor(String name, Method getter, Method setter) { this.name = name; this.getter = getter; this.setter = setter; } public static ImmutablePropertyDescriptor create(String name, Method getter, Method setter) { return new ImmutablePropertyDescriptor(name, getter, setter); } public String name() { return name; } public Method getter() { return getter; } public Method setter() { return setter; } }
4,419
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/immutable/ImmutableIntrospector.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.immutable; import java.beans.Transient; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbIgnore; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbImmutable; @SdkInternalApi public class ImmutableIntrospector { private static final String BUILD_METHOD = "build"; private static final String BUILDER_METHOD = "builder"; private static final String TO_BUILDER_METHOD = "toBuilder"; private static final String GET_PREFIX = "get"; private static final String IS_PREFIX = "is"; private static final String SET_PREFIX = "set"; private static final String[] METHODS_TO_IGNORE = { TO_BUILDER_METHOD }; private static volatile ImmutableIntrospector INSTANCE = null; // Methods from Object are commonly overridden and confuse the mapper, automatically exclude any method with a name // that matches a method defined on Object. private final Set<String> namesToExclude; private ImmutableIntrospector() { this.namesToExclude = Collections.unmodifiableSet( Stream.concat(Arrays.stream(Object.class.getMethods()).map(Method::getName), Arrays.stream(METHODS_TO_IGNORE)) .collect(Collectors.toSet())); } public static <T> ImmutableInfo<T> getImmutableInfo(Class<T> immutableClass) { if (INSTANCE == null) { synchronized (ImmutableIntrospector.class) { if (INSTANCE == null) { INSTANCE = new ImmutableIntrospector(); } } } return INSTANCE.introspect(immutableClass); } private <T> ImmutableInfo<T> introspect(Class<T> immutableClass) { Class<?> builderClass = validateAndGetBuilderClass(immutableClass); Optional<Method> staticBuilderMethod = findStaticBuilderMethod(immutableClass, builderClass); List<Method> getters = filterAndCollectGetterMethods(immutableClass.getMethods()); Map<String, Method> indexedBuilderMethods = filterAndIndexBuilderMethods(builderClass.getMethods()); Method buildMethod = extractBuildMethod(indexedBuilderMethods, immutableClass) .orElseThrow( () -> new IllegalArgumentException( "An immutable builder class must have a public method named 'build()' that takes no arguments " + "and returns an instance of the immutable class it builds")); List<ImmutablePropertyDescriptor> propertyDescriptors = getters.stream() .map(getter -> { validateGetter(getter); String propertyName = normalizeGetterName(getter); Method setter = extractSetterMethod(propertyName, indexedBuilderMethods, getter, builderClass) .orElseThrow( () -> generateExceptionForMethod( getter, "A method was found on the immutable class that does not appear to have a " + "matching setter on the builder class.")); return ImmutablePropertyDescriptor.create(propertyName, getter, setter); }).collect(Collectors.toList()); if (!indexedBuilderMethods.isEmpty()) { throw generateExceptionForMethod(indexedBuilderMethods.values().iterator().next(), "A method was found on the immutable class builder that does not appear " + "to have a matching getter on the immutable class."); } return ImmutableInfo.builder(immutableClass) .builderClass(builderClass) .staticBuilderMethod(staticBuilderMethod.orElse(null)) .buildMethod(buildMethod) .propertyDescriptors(propertyDescriptors) .build(); } private boolean isMappableMethod(Method method) { return method.getDeclaringClass() != Object.class && method.getAnnotation(DynamoDbIgnore.class) == null && method.getAnnotation(Transient.class) == null && !method.isSynthetic() && !method.isBridge() && !Modifier.isStatic(method.getModifiers()) && !namesToExclude.contains(method.getName()); } private Optional<Method> findStaticBuilderMethod(Class<?> immutableClass, Class<?> builderClass) { try { Method method = immutableClass.getMethod(BUILDER_METHOD); if (Modifier.isStatic(method.getModifiers()) && method.getReturnType().isAssignableFrom(builderClass)) { return Optional.of(method); } } catch (NoSuchMethodException ignored) { // no-op } return Optional.empty(); } private IllegalArgumentException generateExceptionForMethod(Method getter, String message) { return new IllegalArgumentException( message + " Use the @DynamoDbIgnore annotation on the method if you do not want it to be included in the " + "TableSchema introspection. [Method = \"" + getter + "\"]"); } private Class<?> validateAndGetBuilderClass(Class<?> immutableClass) { DynamoDbImmutable dynamoDbImmutable = immutableClass.getAnnotation(DynamoDbImmutable.class); if (dynamoDbImmutable == null) { throw new IllegalArgumentException("A DynamoDb immutable class must be annotated with @DynamoDbImmutable"); } return dynamoDbImmutable.builder(); } private void validateGetter(Method getter) { if (getter.getReturnType() == void.class || getter.getReturnType() == Void.class) { throw generateExceptionForMethod(getter, "A method was found on the immutable class that does not appear " + "to be a valid getter due to the return type being void."); } if (getter.getParameterCount() != 0) { throw generateExceptionForMethod(getter, "A method was found on the immutable class that does not appear " + "to be a valid getter due to it having one or more parameters."); } } private List<Method> filterAndCollectGetterMethods(Method[] rawMethods) { return Arrays.stream(rawMethods) .filter(this::isMappableMethod) .collect(Collectors.toList()); } private Map<String, Method> filterAndIndexBuilderMethods(Method[] rawMethods) { return Arrays.stream(rawMethods) .filter(this::isMappableMethod) .collect(Collectors.toMap(this::normalizeSetterName, m -> m)); } private String normalizeSetterName(Method setter) { String setterName = setter.getName(); if (setterName.length() > 3 && Character.isUpperCase(setterName.charAt(3)) && setterName.startsWith(SET_PREFIX)) { return Character.toLowerCase(setterName.charAt(3)) + setterName.substring(4); } return setterName; } private String normalizeGetterName(Method getter) { String getterName = getter.getName(); if (getterName.length() > 2 && Character.isUpperCase(getterName.charAt(2)) && getterName.startsWith(IS_PREFIX) && isMethodBoolean(getter)) { return Character.toLowerCase(getterName.charAt(2)) + getterName.substring(3); } if (getterName.length() > 3 && Character.isUpperCase(getterName.charAt(3)) && getterName.startsWith(GET_PREFIX)) { return Character.toLowerCase(getterName.charAt(3)) + getterName.substring(4); } return getterName; } private boolean isMethodBoolean(Method method) { return method.getReturnType() == boolean.class || method.getReturnType() == Boolean.class; } private Optional<Method> extractBuildMethod(Map<String, Method> indexedBuilderMethods, Class<?> immutableClass) { Method buildMethod = indexedBuilderMethods.get(BUILD_METHOD); if (buildMethod == null || buildMethod.getParameterCount() != 0 || !immutableClass.equals(buildMethod.getReturnType())) { return Optional.empty(); } indexedBuilderMethods.remove(BUILD_METHOD); return Optional.of(buildMethod); } private Optional<Method> extractSetterMethod(String propertyName, Map<String, Method> indexedBuilderMethods, Method getterMethod, Class<?> builderClass) { Method setterMethod = indexedBuilderMethods.get(propertyName); if (setterMethod == null || !setterHasValidSignature(setterMethod, getterMethod.getReturnType(), builderClass)) { return Optional.empty(); } indexedBuilderMethods.remove(propertyName); return Optional.of(setterMethod); } private boolean setterHasValidSignature(Method setterMethod, Class<?> expectedType, Class<?> builderClass) { return setterHasValidParameterSignature(setterMethod, expectedType) && setterHasValidReturnType(setterMethod, builderClass); } private boolean setterHasValidParameterSignature(Method setterMethod, Class<?> expectedType) { return setterMethod.getParameterCount() == 1 && expectedType.equals(setterMethod.getParameterTypes()[0]); } private boolean setterHasValidReturnType(Method setterMethod, Class<?> builderClass) { if (setterMethod.getReturnType() == void.class || setterMethod.getReturnType() == Void.class) { return true; } return setterMethod.getReturnType().isAssignableFrom(builderClass); } }
4,420
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/immutable/ImmutableInfo.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.immutable; import java.lang.reflect.Method; import java.util.Collection; import java.util.Optional; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkInternalApi; @SdkInternalApi public class ImmutableInfo<T> { private final Class<T> immutableClass; private final Class<?> builderClass; private final Method staticBuilderMethod; private final Method buildMethod; private final Collection<ImmutablePropertyDescriptor> propertyDescriptors; private ImmutableInfo(Builder<T> b) { this.immutableClass = b.immutableClass; this.builderClass = b.builderClass; this.staticBuilderMethod = b.staticBuilderMethod; this.buildMethod = b.buildMethod; this.propertyDescriptors = b.propertyDescriptors; } public Class<T> immutableClass() { return immutableClass; } public Class<?> builderClass() { return builderClass; } public Optional<Method> staticBuilderMethod() { return Optional.ofNullable(staticBuilderMethod); } public Method buildMethod() { return buildMethod; } public Collection<ImmutablePropertyDescriptor> propertyDescriptors() { return propertyDescriptors; } public static <T> Builder<T> builder(Class<T> immutableClass) { return new Builder<>(immutableClass); } @NotThreadSafe public static final class Builder<T> { private final Class<T> immutableClass; private Class<?> builderClass; private Method staticBuilderMethod; private Method buildMethod; private Collection<ImmutablePropertyDescriptor> propertyDescriptors; private Builder(Class<T> immutableClass) { this.immutableClass = immutableClass; } public Builder<T> builderClass(Class<?> builderClass) { this.builderClass = builderClass; return this; } public Builder<T> staticBuilderMethod(Method builderMethod) { this.staticBuilderMethod = builderMethod; return this; } public Builder<T> buildMethod(Method buildMethod) { this.buildMethod = buildMethod; return this; } public Builder<T> propertyDescriptors(Collection<ImmutablePropertyDescriptor> propertyDescriptors) { this.propertyDescriptors = propertyDescriptors; return this; } public ImmutableInfo<T> build() { return new ImmutableInfo<>(this); } } }
4,421
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/conditional/BeginsWithConditional.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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.conditional; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.nullAttributeValue; import java.util.Collections; import java.util.HashMap; import java.util.Map; import software.amazon.awssdk.annotations.SdkInternalApi; 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.EnhancedClientUtils; import software.amazon.awssdk.enhanced.dynamodb.model.QueryConditional; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; @SdkInternalApi public class BeginsWithConditional implements QueryConditional { private final Key key; public BeginsWithConditional(Key key) { this.key = key; } @Override public Expression expression(TableSchema<?> tableSchema, String indexName) { QueryConditionalKeyValues queryConditionalKeyValues = QueryConditionalKeyValues.from(key, tableSchema, indexName); if (queryConditionalKeyValues.sortValue().equals(nullAttributeValue())) { throw new IllegalArgumentException("Attempt to query using a 'beginsWith' condition operator against a " + "null sort key."); } if (queryConditionalKeyValues.sortValue().n() != null) { throw new IllegalArgumentException("Attempt to query using a 'beginsWith' condition operator against " + "a numeric sort key."); } String partitionKeyToken = EnhancedClientUtils.keyRef(queryConditionalKeyValues.partitionKey()); String partitionValueToken = EnhancedClientUtils.valueRef(queryConditionalKeyValues.partitionKey()); String sortKeyToken = EnhancedClientUtils.keyRef(queryConditionalKeyValues.sortKey()); String sortValueToken = EnhancedClientUtils.valueRef(queryConditionalKeyValues.sortKey()); String queryExpression = String.format("%s = %s AND begins_with ( %s, %s )", partitionKeyToken, partitionValueToken, sortKeyToken, sortValueToken); Map<String, AttributeValue> expressionAttributeValues = new HashMap<>(); expressionAttributeValues.put(partitionValueToken, queryConditionalKeyValues.partitionValue()); expressionAttributeValues.put(sortValueToken, queryConditionalKeyValues.sortValue()); Map<String, String> expressionAttributeNames = new HashMap<>(); expressionAttributeNames.put(partitionKeyToken, queryConditionalKeyValues.partitionKey()); expressionAttributeNames.put(sortKeyToken, queryConditionalKeyValues.sortKey()); return Expression.builder() .expression(queryExpression) .expressionValues(Collections.unmodifiableMap(expressionAttributeValues)) .expressionNames(expressionAttributeNames) .build(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } BeginsWithConditional that = (BeginsWithConditional) o; return key != null ? key.equals(that.key) : that.key == null; } @Override public int hashCode() { return key != null ? key.hashCode() : 0; } }
4,422
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/conditional/EqualToConditional.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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.conditional; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.nullAttributeValue; import static software.amazon.awssdk.enhanced.dynamodb.internal.EnhancedClientUtils.isNullAttributeValue; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Optional; import software.amazon.awssdk.annotations.SdkInternalApi; 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.EnhancedClientUtils; import software.amazon.awssdk.enhanced.dynamodb.model.QueryConditional; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; @SdkInternalApi public class EqualToConditional implements QueryConditional { private final Key key; public EqualToConditional(Key key) { this.key = key; } @Override public Expression expression(TableSchema<?> tableSchema, String indexName) { String partitionKey = tableSchema.tableMetadata().indexPartitionKey(indexName); AttributeValue partitionValue = key.partitionKeyValue(); if (partitionValue == null || partitionValue.equals(nullAttributeValue())) { throw new IllegalArgumentException("Partition key must be a valid scalar value to execute a query " + "against. The provided partition key was set to null."); } Optional<AttributeValue> sortKeyValue = key.sortKeyValue(); if (sortKeyValue.isPresent()) { Optional<String> sortKey = tableSchema.tableMetadata().indexSortKey(indexName); if (!sortKey.isPresent()) { throw new IllegalArgumentException("A sort key was supplied as part of a query conditional " + "against an index that does not support a sort key. Index: " + indexName); } return partitionAndSortExpression(partitionKey, sortKey.get(), partitionValue, sortKeyValue.get()); } else { return partitionOnlyExpression(partitionKey, partitionValue); } } private Expression partitionOnlyExpression(String partitionKey, AttributeValue partitionValue) { String partitionKeyToken = EnhancedClientUtils.keyRef(partitionKey); String partitionKeyValueToken = EnhancedClientUtils.valueRef(partitionKey); String queryExpression = String.format("%s = %s", partitionKeyToken, partitionKeyValueToken); return Expression.builder() .expression(queryExpression) .expressionNames(Collections.singletonMap(partitionKeyToken, partitionKey)) .expressionValues(Collections.singletonMap(partitionKeyValueToken, partitionValue)) .build(); } private Expression partitionAndSortExpression(String partitionKey, String sortKey, AttributeValue partitionValue, AttributeValue sortKeyValue) { // When a sort key is explicitly provided as null treat as partition only expression if (isNullAttributeValue(sortKeyValue)) { return partitionOnlyExpression(partitionKey, partitionValue); } String partitionKeyToken = EnhancedClientUtils.keyRef(partitionKey); String partitionKeyValueToken = EnhancedClientUtils.valueRef(partitionKey); String sortKeyToken = EnhancedClientUtils.keyRef(sortKey); String sortKeyValueToken = EnhancedClientUtils.valueRef(sortKey); String queryExpression = String.format("%s = %s AND %s = %s", partitionKeyToken, partitionKeyValueToken, sortKeyToken, sortKeyValueToken); Map<String, AttributeValue> expressionAttributeValues = new HashMap<>(); expressionAttributeValues.put(partitionKeyValueToken, partitionValue); expressionAttributeValues.put(sortKeyValueToken, sortKeyValue); Map<String, String> expressionAttributeNames = new HashMap<>(); expressionAttributeNames.put(partitionKeyToken, partitionKey); expressionAttributeNames.put(sortKeyToken, sortKey); return Expression.builder() .expression(queryExpression) .expressionValues(expressionAttributeValues) .expressionNames(expressionAttributeNames) .build(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } EqualToConditional that = (EqualToConditional) o; return key != null ? key.equals(that.key) : that.key == null; } @Override public int hashCode() { return key != null ? key.hashCode() : 0; } }
4,423
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/conditional/QueryConditionalKeyValues.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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.conditional; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.enhanced.dynamodb.Key; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * Internal helper class to act as a struct to store specific key values that are used throughout various * {@link software.amazon.awssdk.enhanced.dynamodb.model.QueryConditional} implementations. */ @SdkInternalApi class QueryConditionalKeyValues { private final String partitionKey; private final AttributeValue partitionValue; private final String sortKey; private final AttributeValue sortValue; private QueryConditionalKeyValues(String partitionKey, AttributeValue partitionValue, String sortKey, AttributeValue sortValue) { this.partitionKey = partitionKey; this.partitionValue = partitionValue; this.sortKey = sortKey; this.sortValue = sortValue; } static QueryConditionalKeyValues from(Key key, TableSchema<?> tableSchema, String indexName) { String partitionKey = tableSchema.tableMetadata().indexPartitionKey(indexName); AttributeValue partitionValue = key.partitionKeyValue(); String sortKey = tableSchema.tableMetadata().indexSortKey(indexName).orElseThrow( () -> new IllegalArgumentException("A query conditional requires a sort key to be present on the table " + "or index being queried, yet none have been defined in the " + "model")); AttributeValue sortValue = key.sortKeyValue().orElseThrow( () -> new IllegalArgumentException("A query conditional requires a sort key to compare with, " + "however one was not provided.")); return new QueryConditionalKeyValues(partitionKey, partitionValue, sortKey, sortValue); } String partitionKey() { return partitionKey; } AttributeValue partitionValue() { return partitionValue; } String sortKey() { return sortKey; } AttributeValue sortValue() { return sortValue; } }
4,424
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/conditional/SingleKeyItemConditional.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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.conditional; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.nullAttributeValue; import java.util.HashMap; import java.util.Map; import software.amazon.awssdk.annotations.SdkInternalApi; 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.EnhancedClientUtils; import software.amazon.awssdk.enhanced.dynamodb.model.QueryConditional; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * A {@link QueryConditional} implementation that matches values from a specific key using a supplied operator for the * sort key value comparison. The partition key value will always have an equivalence comparison applied. * <p> * This class is used by higher-level (more specific) {@link QueryConditional} implementations such as * {@link QueryConditional#sortGreaterThan(Key)} to reduce code duplication. */ @SdkInternalApi public class SingleKeyItemConditional implements QueryConditional { private final Key key; private final String operator; public SingleKeyItemConditional(Key key, String operator) { this.key = key; this.operator = operator; } @Override public Expression expression(TableSchema<?> tableSchema, String indexName) { QueryConditionalKeyValues queryConditionalKeyValues = QueryConditionalKeyValues.from(key, tableSchema, indexName); if (queryConditionalKeyValues.sortValue().equals(nullAttributeValue())) { throw new IllegalArgumentException("Attempt to query using a relative condition operator against a " + "null sort key."); } String partitionKeyToken = EnhancedClientUtils.keyRef(queryConditionalKeyValues.partitionKey()); String partitionValueToken = EnhancedClientUtils.valueRef(queryConditionalKeyValues.partitionKey()); String sortKeyToken = EnhancedClientUtils.keyRef(queryConditionalKeyValues.sortKey()); String sortValueToken = EnhancedClientUtils.valueRef(queryConditionalKeyValues.sortKey()); String queryExpression = String.format("%s = %s AND %s %s %s", partitionKeyToken, partitionValueToken, sortKeyToken, operator, sortValueToken); Map<String, AttributeValue> expressionAttributeValues = new HashMap<>(); expressionAttributeValues.put(partitionValueToken, queryConditionalKeyValues.partitionValue()); expressionAttributeValues.put(sortValueToken, queryConditionalKeyValues.sortValue()); Map<String, String> expressionAttributeNames = new HashMap<>(); expressionAttributeNames.put(partitionKeyToken, queryConditionalKeyValues.partitionKey()); expressionAttributeNames.put(sortKeyToken, queryConditionalKeyValues.sortKey()); return Expression.builder() .expression(queryExpression) .expressionValues(expressionAttributeValues) .expressionNames(expressionAttributeNames) .build(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SingleKeyItemConditional that = (SingleKeyItemConditional) o; if (key != null ? ! key.equals(that.key) : that.key != null) { return false; } return operator != null ? operator.equals(that.operator) : that.operator == null; } @Override public int hashCode() { int result = key != null ? key.hashCode() : 0; result = 31 * result + (operator != null ? operator.hashCode() : 0); return result; } }
4,425
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/conditional/BetweenConditional.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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.conditional; import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.nullAttributeValue; import static software.amazon.awssdk.enhanced.dynamodb.internal.EnhancedClientUtils.cleanAttributeName; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.function.UnaryOperator; import software.amazon.awssdk.annotations.SdkInternalApi; 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.EnhancedClientUtils; import software.amazon.awssdk.enhanced.dynamodb.model.QueryConditional; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; @SdkInternalApi public class BetweenConditional implements QueryConditional { private static final UnaryOperator<String> EXPRESSION_OTHER_VALUE_KEY_MAPPER = k -> ":AMZN_MAPPED_" + cleanAttributeName(k) + "2"; private final Key key1; private final Key key2; public BetweenConditional(Key key1, Key key2) { this.key1 = key1; this.key2 = key2; } @Override public Expression expression(TableSchema<?> tableSchema, String indexName) { QueryConditionalKeyValues queryConditionalKeyValues1 = QueryConditionalKeyValues.from(key1, tableSchema, indexName); QueryConditionalKeyValues queryConditionalKeyValues2 = QueryConditionalKeyValues.from(key2, tableSchema, indexName); if (queryConditionalKeyValues1.sortValue().equals(nullAttributeValue()) || queryConditionalKeyValues2.sortValue().equals(nullAttributeValue())) { throw new IllegalArgumentException("Attempt to query using a 'between' condition operator where one " + "of the items has a null sort key."); } String partitionKeyToken = EnhancedClientUtils.keyRef(queryConditionalKeyValues1.partitionKey()); String partitionValueToken = EnhancedClientUtils.valueRef(queryConditionalKeyValues1.partitionKey()); String sortKeyToken = EnhancedClientUtils.keyRef(queryConditionalKeyValues1.sortKey()); String sortKeyValueToken1 = EnhancedClientUtils.valueRef(queryConditionalKeyValues1.sortKey()); String sortKeyValueToken2 = EXPRESSION_OTHER_VALUE_KEY_MAPPER.apply(queryConditionalKeyValues2.sortKey()); String queryExpression = String.format("%s = %s AND %s BETWEEN %s AND %s", partitionKeyToken, partitionValueToken, sortKeyToken, sortKeyValueToken1, sortKeyValueToken2); Map<String, AttributeValue> expressionAttributeValues = new HashMap<>(); expressionAttributeValues.put(partitionValueToken, queryConditionalKeyValues1.partitionValue()); expressionAttributeValues.put(sortKeyValueToken1, queryConditionalKeyValues1.sortValue()); expressionAttributeValues.put(sortKeyValueToken2, queryConditionalKeyValues2.sortValue()); Map<String, String> expressionAttributeNames = new HashMap<>(); expressionAttributeNames.put(partitionKeyToken, queryConditionalKeyValues1.partitionKey()); expressionAttributeNames.put(sortKeyToken, queryConditionalKeyValues1.sortKey()); return Expression.builder() .expression(queryExpression) .expressionValues(Collections.unmodifiableMap(expressionAttributeValues)) .expressionNames(expressionAttributeNames) .build(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } BetweenConditional that = (BetweenConditional) o; if (key1 != null ? ! key1.equals(that.key1) : that.key1 != null) { return false; } return key2 != null ? key2.equals(that.key2) : that.key2 == null; } @Override public int hashCode() { int result = key1 != null ? key1.hashCode() : 0; result = 31 * result + (key2 != null ? key2.hashCode() : 0); return result; } }
4,426
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/update/UpdateExpressionUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.update; import static software.amazon.awssdk.enhanced.dynamodb.internal.EnhancedClientUtils.isNullAttributeValue; 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.utils.CollectionUtils.filterMap; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.enhanced.dynamodb.TableMetadata; import software.amazon.awssdk.enhanced.dynamodb.internal.EnhancedClientUtils; import software.amazon.awssdk.enhanced.dynamodb.internal.mapper.UpdateBehaviorTag; import software.amazon.awssdk.enhanced.dynamodb.mapper.UpdateBehavior; import software.amazon.awssdk.enhanced.dynamodb.update.RemoveAction; import software.amazon.awssdk.enhanced.dynamodb.update.SetAction; import software.amazon.awssdk.enhanced.dynamodb.update.UpdateExpression; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; @SdkInternalApi public final class UpdateExpressionUtils { private UpdateExpressionUtils() { } /** * A function to specify an initial value if the attribute represented by 'key' does not exist. */ public static String ifNotExists(String key, String initValue) { return "if_not_exists(" + keyRef(key) + ", " + valueRef(initValue) + ")"; } /** * Generates an UpdateExpression representing a POJO, with only SET and REMOVE actions. */ public static UpdateExpression operationExpression(Map<String, AttributeValue> itemMap, TableMetadata tableMetadata, List<String> nonRemoveAttributes) { Map<String, AttributeValue> setAttributes = filterMap(itemMap, e -> !isNullAttributeValue(e.getValue())); UpdateExpression setAttributeExpression = UpdateExpression.builder() .actions(setActionsFor(setAttributes, tableMetadata)) .build(); Map<String, AttributeValue> removeAttributes = filterMap(itemMap, e -> isNullAttributeValue(e.getValue()) && !nonRemoveAttributes.contains(e.getKey())); UpdateExpression removeAttributeExpression = UpdateExpression.builder() .actions(removeActionsFor(removeAttributes)) .build(); return UpdateExpression.mergeExpressions(setAttributeExpression, removeAttributeExpression); } /** * Creates a list of SET actions for all attributes supplied in the map. */ private static List<SetAction> setActionsFor(Map<String, AttributeValue> attributesToSet, TableMetadata tableMetadata) { return attributesToSet.entrySet() .stream() .map(entry -> setValue(entry.getKey(), entry.getValue(), UpdateBehaviorTag.resolveForAttribute(entry.getKey(), tableMetadata))) .collect(Collectors.toList()); } /** * Creates a list of REMOVE actions for all attributes supplied in the map. */ private static List<RemoveAction> removeActionsFor(Map<String, AttributeValue> attributesToSet) { return attributesToSet.entrySet() .stream() .map(entry -> remove(entry.getKey())) .collect(Collectors.toList()); } /** * Creates a REMOVE action for an attribute, using a token as a placeholder for the attribute name. */ private static RemoveAction remove(String attributeName) { return RemoveAction.builder() .path(keyRef(attributeName)) .expressionNames(Collections.singletonMap(keyRef(attributeName), attributeName)) .build(); } /** * Creates a SET action for an attribute, using a token as a placeholder for the attribute name. * * @see UpdateBehavior for information about the values available. */ private static SetAction setValue(String attributeName, AttributeValue value, UpdateBehavior updateBehavior) { return SetAction.builder() .path(keyRef(attributeName)) .value(behaviorBasedValue(updateBehavior).apply(attributeName)) .expressionNames(expressionNamesFor(attributeName)) .expressionValues(Collections.singletonMap(valueRef(attributeName), value)) .build(); } /** * When we know we want to update the attribute no matter if it exists or not, we simply need to replace the value with * a value token in the expression. If we only want to set the value if the attribute doesn't exist, we use * the DDB function ifNotExists. */ private static Function<String, String> behaviorBasedValue(UpdateBehavior updateBehavior) { switch (updateBehavior) { case WRITE_ALWAYS: return v -> valueRef(v); case WRITE_IF_NOT_EXISTS: return k -> ifNotExists(k, k); default: throw new IllegalArgumentException("Unsupported update behavior '" + updateBehavior + "'"); } } /** * Simple utility method that can create an ExpressionNames map based on a list of attribute names. */ private static Map<String, String> expressionNamesFor(String... attributeNames) { return Arrays.stream(attributeNames) .collect(Collectors.toMap(EnhancedClientUtils::keyRef, Function.identity())); } }
4,427
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/update/UpdateExpressionConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.update; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.enhanced.dynamodb.Expression; import software.amazon.awssdk.enhanced.dynamodb.update.AddAction; import software.amazon.awssdk.enhanced.dynamodb.update.DeleteAction; import software.amazon.awssdk.enhanced.dynamodb.update.RemoveAction; import software.amazon.awssdk.enhanced.dynamodb.update.SetAction; import software.amazon.awssdk.enhanced.dynamodb.update.UpdateExpression; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * * In order to convert it to the format that DynamoDB accepts, the toExpression() method will create an Expression * with a coalesced string representation of its actions, and the ExpressionNames and ExpressionValues maps associated * with all present actions. * * Note: Once an Expression has been obtained, you cannot combine it with another update Expression since they can't be * reliably combined using a token. * * * Validation * When an UpdateExpression is created or merged with another, the code validates the integrity of the expression to ensure * a successful database update. * - The same attribute MAY NOT be chosen for updates in more than one action expression. This is checked by verifying that * attribute only has one representation in the AttributeNames map. * - The same attribute MAY NOT have more than one value. This is checked by verifying that attribute only has one * representation in the AttributeValues map. */ @SdkInternalApi public final class UpdateExpressionConverter { private static final String REMOVE = "REMOVE "; private static final String SET = "SET "; private static final String DELETE = "DELETE "; private static final String ADD = "ADD "; private static final String ACTION_SEPARATOR = ", "; private static final String GROUP_SEPARATOR = " "; private static final char DOT = '.'; private static final char LEFT_BRACKET = '['; private UpdateExpressionConverter() { } /** * Returns an {@link Expression} where all update actions in the UpdateExpression have been concatenated according * to the rules of DDB Update Expressions, and all expression names and values have been combined into single maps, * respectively. * * Observe that the resulting expression string should never be joined with another expression string, independently * of whether it represents an update expression, conditional expression or another type of expression, since once * the string is generated that update expression is the final format accepted by DDB. * * @return an Expression representing the concatenation of all actions in this UpdateExpression */ public static Expression toExpression(UpdateExpression expression) { if (expression == null) { return null; } Map<String, AttributeValue> expressionValues = mergeExpressionValues(expression); Map<String, String> expressionNames = mergeExpressionNames(expression); List<String> groupExpressions = groupExpressions(expression); return Expression.builder() .expression(String.join(GROUP_SEPARATOR, groupExpressions)) .expressionNames(expressionNames) .expressionValues(expressionValues) .build(); } /** * Attempts to find the list of attribute names that will be updated for the supplied {@link UpdateExpression} by looking at * the combined collection of paths and ExpressionName values. Because attribute names can be composed from nested * attribute references and list references, the leftmost part will be returned if composition is detected. * <p> * Examples: The expression contains a {@link DeleteAction} with a path value of 'MyAttribute[1]'; the list returned * will have 'MyAttribute' as an element.} * * @return A list of top level attribute names that have update actions associated. */ public static List<String> findAttributeNames(UpdateExpression updateExpression) { if (updateExpression == null) { return Collections.emptyList(); } List<String> attributeNames = listPathsWithoutTokens(updateExpression); List<String> attributeNamesFromTokens = listAttributeNamesFromTokens(updateExpression); attributeNames.addAll(attributeNamesFromTokens); return attributeNames; } private static List<String> groupExpressions(UpdateExpression expression) { List<String> groupExpressions = new ArrayList<>(); if (!expression.setActions().isEmpty()) { groupExpressions.add(SET + expression.setActions().stream() .map(a -> String.format("%s = %s", a.path(), a.value())) .collect(Collectors.joining(ACTION_SEPARATOR))); } if (!expression.removeActions().isEmpty()) { groupExpressions.add(REMOVE + expression.removeActions().stream() .map(RemoveAction::path) .collect(Collectors.joining(ACTION_SEPARATOR))); } if (!expression.deleteActions().isEmpty()) { groupExpressions.add(DELETE + expression.deleteActions().stream() .map(a -> String.format("%s %s", a.path(), a.value())) .collect(Collectors.joining(ACTION_SEPARATOR))); } if (!expression.addActions().isEmpty()) { groupExpressions.add(ADD + expression.addActions().stream() .map(a -> String.format("%s %s", a.path(), a.value())) .collect(Collectors.joining(ACTION_SEPARATOR))); } return groupExpressions; } private static Stream<Map<String, String>> streamOfExpressionNames(UpdateExpression expression) { return Stream.concat(expression.setActions().stream().map(SetAction::expressionNames), Stream.concat(expression.removeActions().stream().map(RemoveAction::expressionNames), Stream.concat(expression.deleteActions().stream() .map(DeleteAction::expressionNames), expression.addActions().stream() .map(AddAction::expressionNames)))); } private static Map<String, AttributeValue> mergeExpressionValues(UpdateExpression expression) { return streamOfExpressionValues(expression) .reduce(Expression::joinValues) .orElseGet(Collections::emptyMap); } private static Stream<Map<String, AttributeValue>> streamOfExpressionValues(UpdateExpression expression) { return Stream.concat(expression.setActions().stream().map(SetAction::expressionValues), Stream.concat(expression.deleteActions().stream().map(DeleteAction::expressionValues), expression.addActions().stream().map(AddAction::expressionValues))); } private static Map<String, String> mergeExpressionNames(UpdateExpression expression) { return streamOfExpressionNames(expression) .reduce(Expression::joinNames) .orElseGet(Collections::emptyMap); } private static List<String> listPathsWithoutTokens(UpdateExpression expression) { return Stream.concat(expression.setActions().stream().map(SetAction::path), Stream.concat(expression.removeActions().stream().map(RemoveAction::path), Stream.concat(expression.deleteActions().stream().map(DeleteAction::path), expression.addActions().stream().map(AddAction::path)))) .map(UpdateExpressionConverter::removeNestingAndListReference) .filter(attributeName -> !attributeName.contains("#")) .collect(Collectors.toList()); } private static List<String> listAttributeNamesFromTokens(UpdateExpression updateExpression) { return mergeExpressionNames(updateExpression).values().stream() .map(UpdateExpressionConverter::removeNestingAndListReference) .collect(Collectors.toList()); } private static String removeNestingAndListReference(String attributeName) { return attributeName.substring(0, getRemovalIndex(attributeName)); } private static int getRemovalIndex(String attributeName) { for (int i = 0; i < attributeName.length(); i++) { char c = attributeName.charAt(i); if (c == DOT || c == LEFT_BRACKET) { return attributeName.indexOf(c); } } return attributeName.length(); } }
4,428
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/converter/ConverterProviderResolver.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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; import java.util.List; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.enhanced.dynamodb.AttributeConverterProvider; import software.amazon.awssdk.enhanced.dynamodb.DefaultAttributeConverterProvider; /** * Static module to assist with the initialization of attribute converter providers for a StaticTableSchema. */ @SdkInternalApi public final class ConverterProviderResolver { private static final AttributeConverterProvider DEFAULT_ATTRIBUTE_CONVERTER = DefaultAttributeConverterProvider.create(); private ConverterProviderResolver() { } /** * Static provider for the default attribute converters that are bundled with the DynamoDB Enhanced Client. * This provider will be used by default unless overridden in the static table schema builder or using bean * annotations. */ public static AttributeConverterProvider defaultConverterProvider() { return DEFAULT_ATTRIBUTE_CONVERTER; } /** * Resolves a list of attribute converter providers into a single provider. If the list is a singleton, * it will just return that provider, otherwise it will combine them into a * {@link ChainConverterProvider} using the order provided in the list. * * @param providers A list of providers to be combined in strict order * @return A single provider that combines all the supplied providers or null if no providers were supplied */ public static AttributeConverterProvider resolveProviders(List<AttributeConverterProvider> providers) { if (providers == null || providers.isEmpty()) { return null; } if (providers.size() == 1) { return providers.get(0); } return ChainConverterProvider.create(providers); } }
4,429
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/converter/ConverterUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.enhanced.dynamodb.AttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.DoubleAttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.FloatAttributeConverter; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.utils.Validate; /** * Internal utilities that are used by some {@link AttributeConverter}s in the aid * of converting to an {@link AttributeValue} and vice-versa. */ @SdkInternalApi public class ConverterUtils { private ConverterUtils() { } /** * Validates that a given Double input is a valid double supported by {@link DoubleAttributeConverter}. * @param input */ public static void validateDouble(Double input) { Validate.isTrue(!Double.isNaN(input), "NaN is not supported by the default converters."); Validate.isTrue(Double.isFinite(input), "Infinite numbers are not supported by the default converters."); } /** * Validates that a given Float input is a valid double supported by {@link FloatAttributeConverter}. * @param input */ public static void validateFloat(Float input) { Validate.isTrue(!Float.isNaN(input), "NaN is not supported by the default converters."); Validate.isTrue(Float.isFinite(input), "Infinite numbers are not supported by the default converters."); } public static String padLeft(int paddingAmount, int valueToPad) { String result; String value = Integer.toString(valueToPad); if (value.length() == paddingAmount) { result = value; } else { int padding = paddingAmount - value.length(); StringBuilder sb = new StringBuilder(paddingAmount); for (int i = 0; i < padding; i++) { sb.append('0'); } result = sb.append(value).toString(); } return result; } public static String[] splitNumberOnDecimal(String valueToSplit) { int i = valueToSplit.indexOf('.'); if (i == -1) { return new String[] { valueToSplit, "0" }; } else { // Ends with '.' is not supported. return new String[] { valueToSplit.substring(0, i), valueToSplit.substring(i + 1) }; } } public static LocalDateTime convertFromLocalDate(LocalDate localDate) { return LocalDateTime.of(localDate, LocalTime.MIDNIGHT); } }
4,430
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/converter/ChainConverterProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Objects; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.enhanced.dynamodb.AttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.AttributeConverterProvider; import software.amazon.awssdk.enhanced.dynamodb.EnhancedType; /** * A {@link AttributeConverterProvider} that allows multiple providers to be chained in a specified order * to act as a single composite provider. When searching for an attribute converter for a type, * the providers will be called in forward/ascending order, attempting to find a converter from the * first provider, then the second, and so on, until a match is found or the operation fails. */ @SdkInternalApi public final class ChainConverterProvider implements AttributeConverterProvider { private final List<AttributeConverterProvider> providerChain; private ChainConverterProvider(List<AttributeConverterProvider> providers) { this.providerChain = new ArrayList<>(providers); } /** * Construct a new instance of {@link ChainConverterProvider}. * @param providers A list of {@link AttributeConverterProvider} to chain together. * @return A constructed {@link ChainConverterProvider} object. */ public static ChainConverterProvider create(AttributeConverterProvider... providers) { return new ChainConverterProvider(Arrays.asList(providers)); } /** * Construct a new instance of {@link ChainConverterProvider}. * @param providers A list of {@link AttributeConverterProvider} to chain together. * @return A constructed {@link ChainConverterProvider} object. */ public static ChainConverterProvider create(List<AttributeConverterProvider> providers) { return new ChainConverterProvider(providers); } public List<AttributeConverterProvider> chainedProviders() { return Collections.unmodifiableList(this.providerChain); } @Override public <T> AttributeConverter<T> converterFor(EnhancedType<T> enhancedType) { return this.providerChain.stream() .filter(provider -> provider.converterFor(enhancedType) != null) .map(p -> p.converterFor(enhancedType)) .findFirst().orElse(null); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ChainConverterProvider that = (ChainConverterProvider) o; return Objects.equals(providerChain, that.providerChain); } @Override public int hashCode() { return providerChain != null ? providerChain.hashCode() : 0; } }
4,431
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/converter/StringConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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; 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; /** * Converts a specific Java type to/from a {@link String}. */ @SdkInternalApi @ThreadSafe @Immutable public interface StringConverter<T> { /** * Convert the provided object into a string. */ default String toString(T object) { return object.toString(); } /** * Convert the provided string into an object. */ T fromString(String string); /** * The type supported by this converter. */ EnhancedType<T> type(); }
4,432
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/converter/PrimitiveConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.enhanced.dynamodb.AttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.EnhancedType; /** * Interface for {@link StringConverter} and {@link AttributeConverter} implementations * that support boxed and primitive types. */ @SdkInternalApi @ThreadSafe public interface PrimitiveConverter<T> { /** * The type supported by this converter. */ EnhancedType<T> primitiveType(); }
4,433
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/converter/StringConverterProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.enhanced.dynamodb.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.string.DefaultStringConverterProvider; /** * Interface for providing string converters for Java objects. */ @SdkInternalApi public interface StringConverterProvider { <T> StringConverter<T> converterFor(EnhancedType<T> enhancedType); static StringConverterProvider defaultProvider() { return DefaultStringConverterProvider.create(); } }
4,434
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/converter/TypeConvertingVisitor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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; import java.util.List; import java.util.Map; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.enhanced.dynamodb.AttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.EnhancedAttributeValue; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.utils.Validate; /** * A visitor across all possible types of a {@link EnhancedAttributeValue}. * * <p> * This is useful in {@link AttributeConverter} implementations, without having to write a switch statement on the * {@link EnhancedAttributeValue#type()}. * * @see EnhancedAttributeValue#convert(TypeConvertingVisitor) */ @SdkInternalApi public abstract class TypeConvertingVisitor<T> { protected final Class<?> targetType; private final Class<?> converterClass; /** * Called by subclasses to provide enhanced logging when a specific type isn't handled. * * <p> * Reasons this call may fail with a {@link RuntimeException}: * <ol> * <li>If the provided type is null.</li> * </ol> * * @param targetType The type to which this visitor is converting. */ protected TypeConvertingVisitor(Class<?> targetType) { this(targetType, null); } /** * Called by subclasses to provide enhanced logging when a specific type isn't handled. * * <p> * Reasons this call may fail with a {@link RuntimeException}: * <ol> * <li>If the provided type is null.</li> * </ol> * * @param targetType The type to which this visitor is converting. * @param converterClass The converter implementation that is creating this visitor. This may be null. */ protected TypeConvertingVisitor(Class<?> targetType, Class<?> converterClass) { Validate.paramNotNull(targetType, "targetType"); this.targetType = targetType; this.converterClass = converterClass; } /** * Convert the provided value into the target type. * * <p> * Reasons this call may fail with a {@link RuntimeException}: * <ol> * <li>If the value cannot be converted by this visitor.</li> * </ol> */ public final T convert(EnhancedAttributeValue value) { switch (value.type()) { case NULL: return convertNull(); case M: return convertMap(value.asMap()); case S: return convertString(value.asString()); case N: return convertNumber(value.asNumber()); case B: return convertBytes(value.asBytes()); case BOOL: return convertBoolean(value.asBoolean()); case SS: return convertSetOfStrings(value.asSetOfStrings()); case NS: return convertSetOfNumbers(value.asSetOfNumbers()); case BS: return convertSetOfBytes(value.asSetOfBytes()); case L: return convertListOfAttributeValues(value.asListOfAttributeValues()); default: throw new IllegalStateException("Unsupported type: " + value.type()); } } /** * Invoked when visiting an attribute in which {@link EnhancedAttributeValue#isNull()} is true. */ public T convertNull() { return null; } /** * Invoked when visiting an attribute in which {@link EnhancedAttributeValue#isMap()} is true. The provided value is the * underlying value of the {@link EnhancedAttributeValue} being converted. */ public T convertMap(Map<String, AttributeValue> value) { return defaultConvert(AttributeValueType.M, value); } /** * Invoked when visiting an attribute in which {@link EnhancedAttributeValue#isString()} is true. The provided value is the * underlying value of the {@link EnhancedAttributeValue} being converted. */ public T convertString(String value) { return defaultConvert(AttributeValueType.S, value); } /** * Invoked when visiting an attribute in which {@link EnhancedAttributeValue#isNumber()} is true. The provided value is the * underlying value of the {@link EnhancedAttributeValue} being converted. */ public T convertNumber(String value) { return defaultConvert(AttributeValueType.N, value); } /** * Invoked when visiting an attribute in which {@link EnhancedAttributeValue#isBytes()} is true. The provided value is the * underlying value of the {@link EnhancedAttributeValue} being converted. */ public T convertBytes(SdkBytes value) { return defaultConvert(AttributeValueType.B, value); } /** * Invoked when visiting an attribute in which {@link EnhancedAttributeValue#isBoolean()} is true. The provided value is the * underlying value of the {@link EnhancedAttributeValue} being converted. */ public T convertBoolean(Boolean value) { return defaultConvert(AttributeValueType.BOOL, value); } /** * Invoked when visiting an attribute in which {@link EnhancedAttributeValue#isSetOfStrings()} is true. The provided value is * the underlying value of the {@link EnhancedAttributeValue} being converted. */ public T convertSetOfStrings(List<String> value) { return defaultConvert(AttributeValueType.SS, value); } /** * Invoked when visiting an attribute in which {@link EnhancedAttributeValue#isSetOfNumbers()} is true. The provided value is * the underlying value of the {@link EnhancedAttributeValue} being converted. */ public T convertSetOfNumbers(List<String> value) { return defaultConvert(AttributeValueType.NS, value); } /** * Invoked when visiting an attribute in which {@link EnhancedAttributeValue#isSetOfBytes()} is true. The provided value is * the underlying value of the {@link EnhancedAttributeValue} being converted. */ public T convertSetOfBytes(List<SdkBytes> value) { return defaultConvert(AttributeValueType.BS, value); } /** * Invoked when visiting an attribute in which {@link EnhancedAttributeValue#isListOfAttributeValues()} is true. The provided * value is the underlying value of the {@link EnhancedAttributeValue} being converted. */ public T convertListOfAttributeValues(List<AttributeValue> value) { return defaultConvert(AttributeValueType.L, value); } /** * This is invoked by default if a different "convert" method is not overridden. By default, this throws an exception. * * @param type The type that wasn't handled by another "convert" method. * @param value The value that wasn't handled by another "convert" method. */ public T defaultConvert(AttributeValueType type, Object value) { if (converterClass != null) { throw new IllegalStateException(converterClass.getTypeName() + " cannot convert an attribute of type " + type + " into the requested type " + targetType); } throw new IllegalStateException("Cannot convert attribute of type " + type + " into a " + targetType); } }
4,435
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/attribute/CharSequenceAttributeConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkInternalApi; 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.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.string.CharSequenceStringConverter; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * A converter between {@link CharSequence} and {@link AttributeValue}. * * <p> * This stores values in DynamoDB as a string. * * <p> * This supports reading every string value supported by DynamoDB, making it fully compatible with custom converters as * well as internal converters (e.g. {@link StringAttributeConverter}). * * <p> * This can be created via {@link #create()}. */ @SdkInternalApi @ThreadSafe @Immutable public final class CharSequenceAttributeConverter implements AttributeConverter<CharSequence> { private static final CharSequenceStringConverter CHAR_SEQUENCE_STRING_CONVERTER = CharSequenceStringConverter.create(); private static final StringAttributeConverter STRING_ATTRIBUTE_CONVERTER = StringAttributeConverter.create(); private CharSequenceAttributeConverter() { } public static CharSequenceAttributeConverter create() { return new CharSequenceAttributeConverter(); } @Override public EnhancedType<CharSequence> type() { return EnhancedType.of(CharSequence.class); } @Override public AttributeValueType attributeValueType() { return AttributeValueType.S; } @Override public AttributeValue transformFrom(CharSequence input) { return AttributeValue.builder().s(CHAR_SEQUENCE_STRING_CONVERTER.toString(input)).build(); } @Override public CharSequence transformTo(AttributeValue input) { String string = STRING_ATTRIBUTE_CONVERTER.transformTo(input); return CHAR_SEQUENCE_STRING_CONVERTER.fromString(string); } }
4,436
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/attribute/ZoneOffsetAttributeConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute; import java.time.DateTimeException; 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.AttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType; import software.amazon.awssdk.enhanced.dynamodb.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.TypeConvertingVisitor; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.string.ZoneOffsetStringConverter; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * A converter between {@link ZoneOffset} and {@link AttributeValue}. * * <p> * This stores and reads values in DynamoDB as a string using {@link ZoneOffset#toString()} and {@link ZoneOffset#of(String)}. * * <p> * This can be created via {@link #create()}. */ @SdkInternalApi @ThreadSafe @Immutable public final class ZoneOffsetAttributeConverter implements AttributeConverter<ZoneOffset> { public static final ZoneOffsetStringConverter STRING_CONVERTER = ZoneOffsetStringConverter.create(); public static ZoneOffsetAttributeConverter create() { return new ZoneOffsetAttributeConverter(); } @Override public EnhancedType<ZoneOffset> type() { return EnhancedType.of(ZoneOffset.class); } @Override public AttributeValueType attributeValueType() { return AttributeValueType.S; } @Override public AttributeValue transformFrom(ZoneOffset input) { return AttributeValue.builder().s(STRING_CONVERTER.toString(input)).build(); } @Override public ZoneOffset transformTo(AttributeValue input) { try { return EnhancedAttributeValue.fromAttributeValue(input).convert(Visitor.INSTANCE); } catch (DateTimeException e) { throw new IllegalArgumentException(e); } } private static final class Visitor extends TypeConvertingVisitor<ZoneOffset> { private static final Visitor INSTANCE = new Visitor(); private Visitor() { super(ZoneOffset.class, ZoneOffsetAttributeConverter.class); } @Override public ZoneOffset convertString(String value) { return STRING_CONVERTER.fromString(value); } } }
4,437
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/attribute/ListAttributeConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute; import static java.util.stream.Collectors.toList; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.function.Function; import java.util.function.Supplier; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.enhanced.dynamodb.AttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType; import software.amazon.awssdk.enhanced.dynamodb.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.TypeConvertingVisitor; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * A converter between a specific {@link Collection} type and {@link EnhancedAttributeValue}. * * <p> * This stores values in DynamoDB as a list of attribute values. This uses a configured {@link AttributeConverter} to convert * the collection contents to an attribute value. * * <p> * This supports reading a list of attribute values. This uses a configured {@link AttributeConverter} to convert * the collection contents. * * <p> * A builder is exposed to allow defining how the collection and element types are created and converted: * <p> * <code> * {@literal AttributeConverter<List<Integer>> listConverter = * CollectionAttributeConverter.builder(EnhancedType.listOf(Integer.class)) * .collectionConstructor(ArrayList::new) * .elementConverter(IntegerAttributeConverter.create()) * .build()} * </code> * * <p> * For frequently-used types, static methods are exposed to reduce the amount of boilerplate involved in creation: * <p> * <code> * {@literal AttributeConverter<List<Integer>> listConverter = * CollectionAttributeConverter.listConverter(IntegerAttributeConverter.create());} * </code> * <p> * <code> * {@literal AttributeConverter<Collection<Integer>> collectionConverer = * CollectionAttributeConverter.collectionConverter(IntegerAttributeConverter.create());} * </code> * <p> * <code> * {@literal AttributeConverter<Set<Integer>> setConverter = * CollectionAttributeConverter.setConverter(IntegerAttributeConverter.create());} * </code> * <p> * <code> * {@literal AttributeConverter<SortedSet<Integer>> sortedSetConverter = * CollectionAttributeConverter.sortedSetConverter(IntegerAttributeConverter.create());} * </code> * * @see MapAttributeConverter */ @SdkInternalApi @ThreadSafe @Immutable public class ListAttributeConverter<T extends Collection<?>> implements AttributeConverter<T> { private final Delegate<T, ?> delegate; private ListAttributeConverter(Delegate<T, ?> delegate) { this.delegate = delegate; } public static <U> ListAttributeConverter<List<U>> create(AttributeConverter<U> elementConverter) { return builder(EnhancedType.listOf(elementConverter.type())) .collectionConstructor(ArrayList::new) .elementConverter(elementConverter) .build(); } public static <T extends Collection<U>, U> ListAttributeConverter.Builder<T, U> builder(EnhancedType<T> collectionType) { return new Builder<>(collectionType); } @Override public EnhancedType<T> type() { return delegate.type(); } @Override public AttributeValueType attributeValueType() { return AttributeValueType.L; } @Override public AttributeValue transformFrom(T input) { return delegate.transformFrom(input); } @Override public T transformTo(AttributeValue input) { return delegate.transformTo(input); } private static final class Delegate<T extends Collection<U>, U> implements AttributeConverter<T> { private final EnhancedType<T> type; private final Supplier<? extends T> collectionConstructor; private final AttributeConverter<U> elementConverter; private Delegate(Builder<T, U> builder) { this.type = builder.collectionType; this.collectionConstructor = builder.collectionConstructor; this.elementConverter = builder.elementConverter; } @Override public EnhancedType<T> type() { return type; } @Override public AttributeValueType attributeValueType() { return AttributeValueType.L; } @Override public AttributeValue transformFrom(T input) { return EnhancedAttributeValue.fromListOfAttributeValues(input.stream() .map(elementConverter::transformFrom) .collect(toList())) .toAttributeValue(); } @Override public T transformTo(AttributeValue input) { return EnhancedAttributeValue.fromAttributeValue(input) .convert(new TypeConvertingVisitor<T>(type.rawClass(), ListAttributeConverter.class) { @Override public T convertSetOfStrings(List<String> value) { return convertCollection(value, v -> AttributeValue.builder().s(v).build()); } @Override public T convertSetOfNumbers(List<String> value) { return convertCollection(value, v -> AttributeValue.builder().n(v).build()); } @Override public T convertSetOfBytes(List<SdkBytes> value) { return convertCollection(value, v -> AttributeValue.builder().b(v).build()); } @Override public T convertListOfAttributeValues(List<AttributeValue> value) { return convertCollection(value, Function.identity()); } private <V> T convertCollection(Collection<V> collection, Function<V, AttributeValue> transformFrom) { Collection<Object> result = (Collection<Object>) collectionConstructor.get(); collection.stream() .map(transformFrom) .map(elementConverter::transformTo) .forEach(result::add); // This is a safe cast - We know the values we added to the list // match the type that the customer requested. return (T) result; } }); } } @NotThreadSafe public static final class Builder<T extends Collection<U>, U> { private final EnhancedType<T> collectionType; private Supplier<? extends T> collectionConstructor; private AttributeConverter<U> elementConverter; private Builder(EnhancedType<T> collectionType) { this.collectionType = collectionType; } public Builder<T, U> collectionConstructor(Supplier<? extends T> collectionConstructor) { this.collectionConstructor = collectionConstructor; return this; } public Builder<T, U> elementConverter(AttributeConverter<U> elementConverter) { this.elementConverter = elementConverter; return this; } public ListAttributeConverter<T> build() { return new ListAttributeConverter<>(new Delegate<>(this)); } } }
4,438
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/attribute/SdkNumberAttributeConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.core.SdkNumber; import software.amazon.awssdk.enhanced.dynamodb.AttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType; import software.amazon.awssdk.enhanced.dynamodb.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.TypeConvertingVisitor; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.string.SdkNumberStringConverter; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * A converter between {@link SdkNumber} and {@link AttributeValue}. * * <p> * This stores values in DynamoDB as a number. * * <p> * This supports reading the full range of integers supported by DynamoDB. For smaller numbers, consider using * {@link ShortAttributeConverter}, {@link IntegerAttributeConverter} or {@link LongAttributeConverter}. * * This can be created via {@link #create()}. */ @SdkInternalApi @ThreadSafe @Immutable public final class SdkNumberAttributeConverter implements AttributeConverter<SdkNumber> { private static final Visitor VISITOR = new Visitor(); private static final SdkNumberStringConverter STRING_CONVERTER = SdkNumberStringConverter.create(); private SdkNumberAttributeConverter() { } public static SdkNumberAttributeConverter create() { return new SdkNumberAttributeConverter(); } @Override public EnhancedType<SdkNumber> type() { return EnhancedType.of(SdkNumber.class); } @Override public AttributeValueType attributeValueType() { return AttributeValueType.N; } @Override public AttributeValue transformFrom(SdkNumber input) { return AttributeValue.builder().n(STRING_CONVERTER.toString(input)).build(); } @Override public SdkNumber transformTo(AttributeValue input) { if (input.n() != null) { return EnhancedAttributeValue.fromNumber(input.n()).convert(VISITOR); } return EnhancedAttributeValue.fromAttributeValue(input).convert(VISITOR); } private static final class Visitor extends TypeConvertingVisitor<SdkNumber> { private Visitor() { super(SdkNumber.class, SdkNumberAttributeConverter.class); } @Override public SdkNumber convertString(String value) { return STRING_CONVERTER.fromString(value); } @Override public SdkNumber convertNumber(String value) { return STRING_CONVERTER.fromString(value); } } }
4,439
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/attribute/DoubleAttributeConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkInternalApi; 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.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.ConverterUtils; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.PrimitiveConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.TypeConvertingVisitor; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.string.DoubleStringConverter; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * A converter between {@link Double} and {@link AttributeValue}. * * <p> * This stores values in DynamoDB as a number. * * <p> * This supports converting numbers stored in DynamoDB into a double-precision floating point number, within the range * {@link Double#MIN_VALUE}, {@link Double#MAX_VALUE}. For less precision or smaller values, consider using * {@link FloatAttributeConverter}. For greater precision or larger values, consider using {@link BigDecimalAttributeConverter}. * * <p> * If values are known to be whole numbers, it is recommended to use a perfect-precision whole number representation like those * provided by {@link ShortAttributeConverter}, {@link IntegerAttributeConverter} or {@link BigIntegerAttributeConverter}. * * <p> * This can be created via {@link #create()}. */ @SdkInternalApi @ThreadSafe @Immutable public final class DoubleAttributeConverter implements AttributeConverter<Double>, PrimitiveConverter<Double> { private static final Visitor VISITOR = new Visitor(); private static final DoubleStringConverter STRING_CONVERTER = DoubleStringConverter.create(); private DoubleAttributeConverter() { } public static DoubleAttributeConverter create() { return new DoubleAttributeConverter(); } @Override public EnhancedType<Double> type() { return EnhancedType.of(Double.class); } @Override public AttributeValueType attributeValueType() { return AttributeValueType.N; } @Override public AttributeValue transformFrom(Double input) { ConverterUtils.validateDouble(input); return AttributeValue.builder().n(STRING_CONVERTER.toString(input)).build(); } @Override public Double transformTo(AttributeValue input) { Double result; if (input.n() != null) { result = EnhancedAttributeValue.fromNumber(input.n()).convert(VISITOR); } else { result = EnhancedAttributeValue.fromAttributeValue(input).convert(VISITOR); } ConverterUtils.validateDouble(result); return result; } @Override public EnhancedType<Double> primitiveType() { return EnhancedType.of(double.class); } private static final class Visitor extends TypeConvertingVisitor<Double> { private Visitor() { super(Double.class, DoubleAttributeConverter.class); } @Override public Double convertString(String value) { return STRING_CONVERTER.fromString(value); } @Override public Double convertNumber(String value) { return STRING_CONVERTER.fromString(value); } } }
4,440
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/attribute/MapAttributeConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute; import java.util.LinkedHashMap; import java.util.Map; import java.util.NavigableMap; import java.util.SortedMap; import java.util.TreeMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.function.Supplier; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkInternalApi; 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.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.StringConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.TypeConvertingVisitor; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * A converter between a specific {@link Map} type and {@link AttributeValue}. * * <p> * This stores values in DynamoDB as a map from string to attribute value. This uses a configured {@link StringAttributeConverter} * to convert the map keys to a string, and a configured {@link AttributeConverter} to convert the map values to an attribute * value. * * <p> * This supports reading maps from DynamoDB. This uses a configured {@link StringAttributeConverter} to convert the map keys, and * a configured {@link AttributeConverter} to convert the map values. * * <p> * A builder is exposed to allow defining how the map, key and value types are created and converted: * <p> * <code> * {@literal AttributeConverter<Map<MonthDay, String>> mapConverter = * MapAttributeConverter.builder(EnhancedType.mapOf(Integer.class, String.class)) * .mapConstructor(HashMap::new) * .keyConverter(MonthDayStringConverter.create()) * .valueConverter(StringAttributeConverter.create()) * .build();} * </code> * * <p> * For frequently-used types, static methods are exposed to reduce the amount of boilerplate involved in creation: * <code> * {@literal AttributeConverter<Map<MonthDay, String>> mapConverter = * MapAttributeConverter.mapConverter(MonthDayStringConverter.create(), * StringAttributeConverter.create());} * </code> * <p> * <code> * {@literal AttributeConverter<SortedMap<MonthDay, String>> sortedMapConverter = * MapAttributeConverter.sortedMapConverter(MonthDayStringConverter.create(), * StringAttributeConverter.create());} * </code> * * @see MapAttributeConverter */ @SdkInternalApi @ThreadSafe @Immutable public class MapAttributeConverter<T extends Map<?, ?>> implements AttributeConverter<T> { private final Delegate<T, ?, ?> delegate; private MapAttributeConverter(Delegate<T, ?, ?> delegate) { this.delegate = delegate; } public static <K, V> MapAttributeConverter<Map<K, V>> mapConverter(StringConverter<K> keyConverter, AttributeConverter<V> valueConverter) { return builder(EnhancedType.mapOf(keyConverter.type(), valueConverter.type())) .mapConstructor(LinkedHashMap::new) .keyConverter(keyConverter) .valueConverter(valueConverter) .build(); } public static <K, V> MapAttributeConverter<ConcurrentMap<K, V>> concurrentMapConverter(StringConverter<K> keyConverter, AttributeConverter<V> valueConverter) { return builder(EnhancedType.concurrentMapOf(keyConverter.type(), valueConverter.type())) .mapConstructor(ConcurrentHashMap::new) .keyConverter(keyConverter) .valueConverter(valueConverter) .build(); } public static <K, V> MapAttributeConverter<SortedMap<K, V>> sortedMapConverter(StringConverter<K> keyConverter, AttributeConverter<V> valueConverter) { return builder(EnhancedType.sortedMapOf(keyConverter.type(), valueConverter.type())) .mapConstructor(TreeMap::new) .keyConverter(keyConverter) .valueConverter(valueConverter) .build(); } public static <K, V> MapAttributeConverter<NavigableMap<K, V>> navigableMapConverter(StringConverter<K> keyConverter, AttributeConverter<V> valueConverter) { return builder(EnhancedType.navigableMapOf(keyConverter.type(), valueConverter.type())) .mapConstructor(TreeMap::new) .keyConverter(keyConverter) .valueConverter(valueConverter) .build(); } public static <T extends Map<K, V>, K, V> Builder<T, K, V> builder(EnhancedType<T> mapType) { return new Builder<>(mapType); } @Override public EnhancedType<T> type() { return delegate.type(); } @Override public AttributeValueType attributeValueType() { return AttributeValueType.M; } @Override public AttributeValue transformFrom(T input) { return delegate.toAttributeValue(input).toAttributeValue(); } @Override public T transformTo(AttributeValue input) { return delegate.fromAttributeValue(input); } private static final class Delegate<T extends Map<K, V>, K, V> { private final EnhancedType<T> type; private final Supplier<? extends T> mapConstructor; private final StringConverter<K> keyConverter; private final AttributeConverter<V> valueConverter; private Delegate(Builder<T, K, V> builder) { this.type = builder.mapType; this.mapConstructor = builder.mapConstructor; this.keyConverter = builder.keyConverter; this.valueConverter = builder.valueConverter; } public EnhancedType<T> type() { return type; } public EnhancedAttributeValue toAttributeValue(T input) { Map<String, AttributeValue> result = new LinkedHashMap<>(); input.forEach((k, v) -> result.put(keyConverter.toString(k), valueConverter.transformFrom(v))); return EnhancedAttributeValue.fromMap(result); } public T fromAttributeValue(AttributeValue input) { return EnhancedAttributeValue.fromAttributeValue(input) .convert(new TypeConvertingVisitor<T>(Map.class, MapAttributeConverter.class) { @Override public T convertMap(Map<String, AttributeValue> value) { T result = mapConstructor.get(); value.forEach((k, v) -> result.put(keyConverter.fromString(k), valueConverter.transformTo(v))); return result; } }); } } @NotThreadSafe public static final class Builder<T extends Map<K, V>, K, V> { private final EnhancedType<T> mapType; private StringConverter<K> keyConverter; private AttributeConverter<V> valueConverter; private Supplier<? extends T> mapConstructor; private Builder(EnhancedType<T> mapType) { this.mapType = mapType; } public Builder<T, K, V> mapConstructor(Supplier<?> mapConstructor) { this.mapConstructor = (Supplier<? extends T>) mapConstructor; return this; } public Builder<T, K, V> keyConverter(StringConverter<K> keyConverter) { this.keyConverter = keyConverter; return this; } public Builder<T, K, V> valueConverter(AttributeConverter<V> valueConverter) { this.valueConverter = valueConverter; return this; } public MapAttributeConverter<T> build() { return new MapAttributeConverter<>(new Delegate<>(this)); } } }
4,441
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/attribute/DurationAttributeConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute; import static software.amazon.awssdk.enhanced.dynamodb.internal.converter.ConverterUtils.padLeft; import java.time.Duration; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkInternalApi; 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.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.ConverterUtils; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.TypeConvertingVisitor; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * A converter between {@link Duration} and {@link AttributeValue}. * * <p> * This stores and reads values in DynamoDB as a number, so that they can be sorted numerically as part of a sort key. * * <p> * Durations are stored in the format "[-]X[.YYYYYYYYY]", where X is the number of seconds in the duration, and Y is the number of * nanoseconds in the duration, left padded with zeroes to a length of 9. The Y and decimal point may be excluded for durations * that are of whole seconds. The duration may be preceded by a - to indicate a negative duration. * * <p> * Examples: * <ul> * <li>{@code Duration.ofDays(1)} is stored as {@code ItemAttributeValueMapper.fromNumber("86400")}</li> * <li>{@code Duration.ofSeconds(9)} is stored as {@code ItemAttributeValueMapper.fromNumber("9")}</li> * <li>{@code Duration.ofSeconds(-9)} is stored as {@code ItemAttributeValueMapper.fromNumber("-9")}</li> * <li>{@code Duration.ofNanos(1_234_567_890)} is stored as {@code ItemAttributeValueMapper.fromNumber("1.234567890")}</li> * <li>{@code Duration.ofMillis(1)} is stored as {@code ItemAttributeValueMapper.fromNumber("0.001000000")}</li> * <li>{@code Duration.ofNanos(1)} is stored as {@code ItemAttributeValueMapper.fromNumber("0.000000001")}</li> * <li>{@code Duration.ofNanos(-1)} is stored as {@code ItemAttributeValueMapper.fromNumber("-0.000000001")}</li> * </ul> * * <p> * This can be created via {@link #create()}. */ @SdkInternalApi @ThreadSafe @Immutable public final class DurationAttributeConverter implements AttributeConverter<Duration> { private static final Visitor VISITOR = new Visitor(); private DurationAttributeConverter() { } public static DurationAttributeConverter create() { return new DurationAttributeConverter(); } @Override public EnhancedType<Duration> type() { return EnhancedType.of(Duration.class); } @Override public AttributeValueType attributeValueType() { return AttributeValueType.N; } @Override public AttributeValue transformFrom(Duration input) { return AttributeValue.builder() .n(input.getSeconds() + (input.getNano() == 0 ? "" : "." + padLeft(9, input.getNano()))) .build(); } @Override public Duration transformTo(AttributeValue input) { if (input.n() != null) { return EnhancedAttributeValue.fromNumber(input.n()).convert(VISITOR); } return EnhancedAttributeValue.fromAttributeValue(input).convert(VISITOR); } private static final class Visitor extends TypeConvertingVisitor<Duration> { private Visitor() { super(Duration.class, DurationAttributeConverter.class); } @Override public Duration convertNumber(String value) { String[] splitOnDecimal = ConverterUtils.splitNumberOnDecimal(value); long seconds = Long.parseLong(splitOnDecimal[0]); int nanoAdjustment = Integer.parseInt(splitOnDecimal[1]); if (seconds < 0) { nanoAdjustment = -nanoAdjustment; } return Duration.ofSeconds(seconds, nanoAdjustment); } } }
4,442
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/attribute/InstantAsStringAttributeConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute; import 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.AttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType; import software.amazon.awssdk.enhanced.dynamodb.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.TypeConvertingVisitor; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * A converter between {@link Instant} and {@link AttributeValue}. * * <p> * This stores values in DynamoDB as a string. * * <p> * Values are stored in ISO-8601 format, with nanosecond precision and a time zone of UTC. * * <p> * Examples: * <ul> * <li>{@code Instant.EPOCH.plusSeconds(1)} is stored as * an AttributeValue with the String "1970-01-01T00:00:01Z"</li> * <li>{@code Instant.EPOCH.minusSeconds(1)} is stored as * an AttributeValue with the String "1969-12-31T23:59:59Z"</li> * <li>{@code Instant.EPOCH.plusMillis(1)} is stored as * an AttributeValue with the String "1970-01-01T00:00:00.001Z"</li> * <li>{@code Instant.EPOCH.minusMillis(1)} is stored as * an AttributeValue with the String "1969-12-31T23:59:59.999Z"</li> * <li>{@code Instant.EPOCH.plusNanos(1)} is stored as * an AttributeValue with the String "1970-01-01T00:00:00.000000001Z"</li> * <li>{@code Instant.EPOCH.minusNanos(1)} is stored as * an AttributeValue with the String "1969-12-31T23:59:59.999999999Z"</li> * </ul> * See {@link Instant} for more details on the serialization format. * <p> * This converter can read any values written by itself, or values with zero offset written by * {@link OffsetDateTimeAsStringAttributeConverter}, and values with zero offset and without time zone named written by * {@link ZoneOffsetAttributeConverter}. Offset and zoned times will be automatically converted to the * equivalent {@link Instant}. * * <p> * This serialization is lexicographically orderable when the year is not negative. * <p> * This can be created via {@link #create()}. */ @SdkInternalApi @ThreadSafe @Immutable public final class InstantAsStringAttributeConverter implements AttributeConverter<Instant> { private static final Visitor VISITOR = new Visitor(); private InstantAsStringAttributeConverter() { } public static InstantAsStringAttributeConverter create() { return new InstantAsStringAttributeConverter(); } @Override public EnhancedType<Instant> type() { return EnhancedType.of(Instant.class); } @Override public AttributeValueType attributeValueType() { return AttributeValueType.S; } @Override public AttributeValue transformFrom(Instant input) { return AttributeValue.builder().s(input.toString()).build(); } @Override public Instant transformTo(AttributeValue input) { try { if (input.s() != null) { return EnhancedAttributeValue.fromString(input.s()).convert(VISITOR); } return EnhancedAttributeValue.fromAttributeValue(input).convert(VISITOR); } catch (RuntimeException e) { throw new IllegalArgumentException(e); } } private static final class Visitor extends TypeConvertingVisitor<Instant> { private Visitor() { super(Instant.class, InstantAsStringAttributeConverter.class); } @Override public Instant convertString(String value) { return Instant.parse(value); } } }
4,443
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/attribute/UrlAttributeConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute; import 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.AttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType; import software.amazon.awssdk.enhanced.dynamodb.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.TypeConvertingVisitor; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.string.UrlStringConverter; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * A converter between {@link URL} and {@link AttributeValue}. * * <p> * This stores and reads values in DynamoDB as a string, according to the format of {@link URL#URL(String)} and * {@link URL#toString()}. */ @SdkInternalApi @ThreadSafe @Immutable public final class UrlAttributeConverter implements AttributeConverter<URL> { public static final UrlStringConverter STRING_CONVERTER = UrlStringConverter.create(); public static UrlAttributeConverter create() { return new UrlAttributeConverter(); } @Override public EnhancedType<URL> type() { return EnhancedType.of(URL.class); } @Override public AttributeValueType attributeValueType() { return AttributeValueType.S; } @Override public AttributeValue transformFrom(URL input) { return AttributeValue.builder().s(STRING_CONVERTER.toString(input)).build(); } @Override public URL transformTo(AttributeValue input) { return EnhancedAttributeValue.fromAttributeValue(input).convert(Visitor.INSTANCE); } private static final class Visitor extends TypeConvertingVisitor<URL> { private static final Visitor INSTANCE = new Visitor(); private Visitor() { super(URL.class, UrlAttributeConverter.class); } @Override public URL convertString(String value) { return STRING_CONVERTER.fromString(value); } } }
4,444
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/attribute/LongAttributeConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkInternalApi; 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.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.PrimitiveConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.TypeConvertingVisitor; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.string.LongStringConverter; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * A converter between {@link Long} and {@link AttributeValue}. * * <p> * This stores values in DynamoDB as a number. * * <p> * This supports reading numbers between {@link Long#MIN_VALUE} and {@link Long#MAX_VALUE} from DynamoDB. For smaller * numbers, consider using {@link ShortAttributeConverter} or {@link IntegerAttributeConverter}. For larger numbers, consider * using {@link BigIntegerAttributeConverter}. Numbers outside of the supported range will cause a {@link NumberFormatException} * on conversion. * * <p> * This does not support reading decimal numbers. For decimal numbers, consider using {@link FloatAttributeConverter}, * {@link DoubleAttributeConverter} or {@link BigDecimalAttributeConverter}. Decimal numbers will cause a * {@link NumberFormatException} on conversion. */ @SdkInternalApi @ThreadSafe @Immutable public final class LongAttributeConverter implements AttributeConverter<Long>, PrimitiveConverter<Long> { private static final Visitor VISITOR = new Visitor(); private static final LongStringConverter STRING_CONVERTER = LongStringConverter.create(); private LongAttributeConverter() { } @Override public EnhancedType<Long> type() { return EnhancedType.of(Long.class); } @Override public AttributeValueType attributeValueType() { return AttributeValueType.N; } public static LongAttributeConverter create() { return new LongAttributeConverter(); } @Override public AttributeValue transformFrom(Long input) { return AttributeValue.builder().n(STRING_CONVERTER.toString(input)).build(); } @Override public Long transformTo(AttributeValue input) { if (input.n() != null) { return EnhancedAttributeValue.fromNumber(input.n()).convert(VISITOR); } return EnhancedAttributeValue.fromAttributeValue(input).convert(VISITOR); } @Override public EnhancedType<Long> primitiveType() { return EnhancedType.of(long.class); } private static final class Visitor extends TypeConvertingVisitor<Long> { private Visitor() { super(Long.class, LongAttributeConverter.class); } @Override public Long convertString(String value) { return STRING_CONVERTER.fromString(value); } @Override public Long convertNumber(String value) { return STRING_CONVERTER.fromString(value); } } }
4,445
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/attribute/BigDecimalAttributeConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute; import java.math.BigDecimal; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkInternalApi; 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.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.TypeConvertingVisitor; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.string.BigDecimalStringConverter; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * A converter between {@link BigDecimal} and {@link AttributeValue}. * * <p> * This stores values in DynamoDB as a number. * * <p> * This supports perfect precision with the full range of numbers that can be stored in DynamoDB. For less precision or * smaller values, consider using {@link FloatAttributeConverter} or {@link DoubleAttributeConverter}. * * <p> * If values are known to be whole numbers, it is recommended to use a perfect-precision whole number representation like those * provided by {@link ShortAttributeConverter}, {@link IntegerAttributeConverter} or {@link BigIntegerAttributeConverter}. * * <p> * This can be created via {@link #create()}. */ @SdkInternalApi @ThreadSafe @Immutable public final class BigDecimalAttributeConverter implements AttributeConverter<BigDecimal> { private static final Visitor VISITOR = new Visitor(); private static final BigDecimalStringConverter STRING_CONVERTER = BigDecimalStringConverter.create(); private BigDecimalAttributeConverter() { } public static BigDecimalAttributeConverter create() { return new BigDecimalAttributeConverter(); } @Override public EnhancedType<BigDecimal> type() { return EnhancedType.of(BigDecimal.class); } @Override public AttributeValueType attributeValueType() { return AttributeValueType.N; } @Override public AttributeValue transformFrom(BigDecimal input) { return AttributeValue.builder().n(STRING_CONVERTER.toString(input)).build(); } @Override public BigDecimal transformTo(AttributeValue input) { if (input.n() != null) { return EnhancedAttributeValue.fromNumber(input.n()).convert(VISITOR); } return EnhancedAttributeValue.fromAttributeValue(input).convert(VISITOR); } private static final class Visitor extends TypeConvertingVisitor<BigDecimal> { private Visitor() { super(BigDecimal.class, BigDecimalAttributeConverter.class); } @Override public BigDecimal convertString(String value) { return STRING_CONVERTER.fromString(value); } @Override public BigDecimal convertNumber(String value) { return STRING_CONVERTER.fromString(value); } } }
4,446
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/attribute/ByteBufferAttributeConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute; import java.nio.ByteBuffer; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.enhanced.dynamodb.AttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType; import software.amazon.awssdk.enhanced.dynamodb.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.TypeConvertingVisitor; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * A converter between {@link ByteBuffer} and {@link AttributeValue}. * * <p> * This stores values in DynamoDB as a binary blob. * * <p> * This supports reading every byte value supported by DynamoDB, making it fully compatible with custom converters as * well as internal converters (e.g. {@link SdkBytesAttributeConverter}). * * <p> * This can be created via {@link #create()}. */ @SdkInternalApi @ThreadSafe @Immutable public final class ByteBufferAttributeConverter implements AttributeConverter<ByteBuffer> { private static final Visitor VISITOR = new Visitor(); private ByteBufferAttributeConverter() { } public static ByteBufferAttributeConverter create() { return new ByteBufferAttributeConverter(); } @Override public EnhancedType<ByteBuffer> type() { return EnhancedType.of(ByteBuffer.class); } @Override public AttributeValueType attributeValueType() { return AttributeValueType.B; } @Override public AttributeValue transformFrom(ByteBuffer input) { return AttributeValue.builder().b(SdkBytes.fromByteBuffer(input)).build(); } @Override public ByteBuffer transformTo(AttributeValue input) { if (input.b() != null) { return EnhancedAttributeValue.fromBytes(input.b()).convert(VISITOR); } return EnhancedAttributeValue.fromAttributeValue(input).convert(VISITOR); } private static final class Visitor extends TypeConvertingVisitor<ByteBuffer> { private Visitor() { super(ByteBuffer.class, ByteBufferAttributeConverter.class); } @Override public ByteBuffer convertBytes(SdkBytes value) { return value.asByteBuffer(); } } }
4,447
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/attribute/FloatAttributeConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkInternalApi; 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.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.ConverterUtils; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.PrimitiveConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.TypeConvertingVisitor; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.string.FloatStringConverter; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * A converter between {@link Float} and {@link AttributeValue}. * * <p> * This stores values in DynamoDB as a number. * * <p> * This supports converting numbers stored in DynamoDB into a single-precision floating point number, within the range * {@link Float#MIN_VALUE}, {@link Float#MAX_VALUE}. For more precision or larger values, consider using * {@link DoubleAttributeConverter} or {@link BigDecimalAttributeConverter}. * * <p> * If values are known to be whole numbers, it is recommended to use a perfect-precision whole number representation like those * provided by {@link ShortAttributeConverter}, {@link IntegerAttributeConverter} or {@link BigIntegerAttributeConverter}. * * <p> * This can be created via {@link #create()}. */ @SdkInternalApi @ThreadSafe @Immutable public final class FloatAttributeConverter implements AttributeConverter<Float>, PrimitiveConverter<Float> { private static final Visitor VISITOR = new Visitor(); private static final FloatStringConverter STRING_CONVERTER = FloatStringConverter.create(); private FloatAttributeConverter() { } public static FloatAttributeConverter create() { return new FloatAttributeConverter(); } @Override public EnhancedType<Float> type() { return EnhancedType.of(Float.class); } @Override public AttributeValueType attributeValueType() { return AttributeValueType.N; } @Override public AttributeValue transformFrom(Float input) { ConverterUtils.validateFloat(input); return AttributeValue.builder().n(STRING_CONVERTER.toString(input)).build(); } @Override public Float transformTo(AttributeValue input) { Float result; if (input.n() != null) { result = EnhancedAttributeValue.fromNumber(input.n()).convert(VISITOR); } else { result = EnhancedAttributeValue.fromAttributeValue(input).convert(VISITOR); } ConverterUtils.validateFloat(result); return result; } @Override public EnhancedType<Float> primitiveType() { return EnhancedType.of(float.class); } private static final class Visitor extends TypeConvertingVisitor<Float> { private Visitor() { super(Float.class, FloatAttributeConverter.class); } @Override public Float convertString(String value) { return STRING_CONVERTER.fromString(value); } @Override public Float convertNumber(String value) { return STRING_CONVERTER.fromString(value); } } }
4,448
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/attribute/StringAttributeConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute; import static java.util.stream.Collectors.toList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.function.BinaryOperator; import java.util.stream.Collectors; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.enhanced.dynamodb.AttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType; import software.amazon.awssdk.enhanced.dynamodb.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.TypeConvertingVisitor; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.string.BooleanStringConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.string.ByteArrayStringConverter; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * A converter between {@link String} and {@link AttributeValue}. * * <p> * This stores values in DynamoDB as a string. * * <p> * This supports reading any DynamoDB attribute type into a string type, so it is very useful for logging information stored in * DynamoDB. */ @SdkInternalApi @ThreadSafe @Immutable public final class StringAttributeConverter implements AttributeConverter<String> { public static StringAttributeConverter create() { return new StringAttributeConverter(); } @Override public EnhancedType<String> type() { return EnhancedType.of(String.class); } @Override public AttributeValueType attributeValueType() { return AttributeValueType.S; } @Override public AttributeValue transformFrom(String input) { return input == null ? AttributeValues.nullAttributeValue() : AttributeValue.builder().s(input).build(); } @Override public String transformTo(AttributeValue input) { return Visitor.toString(input); } private static final class Visitor extends TypeConvertingVisitor<String> { private static final Visitor INSTANCE = new Visitor(); private Visitor() { super(String.class, StringAttributeConverter.class); } @Override public String convertString(String value) { return value; } @Override public String convertNumber(String value) { return value; } @Override public String convertBytes(SdkBytes value) { return ByteArrayStringConverter.create().toString(value.asByteArray()); } @Override public String convertBoolean(Boolean value) { return BooleanStringConverter.create().toString(value); } @Override public String convertSetOfStrings(List<String> value) { return value.toString(); } @Override public String convertSetOfNumbers(List<String> value) { return value.toString(); } @Override public String convertSetOfBytes(List<SdkBytes> value) { return value.stream() .map(this::convertBytes) .collect(Collectors.joining(",", "[", "]")); } @Override public String convertMap(Map<String, AttributeValue> value) { BinaryOperator<Object> throwingMerger = (l, r) -> { // Should not happen: we're converting from map. throw new IllegalStateException(); }; return value.entrySet().stream() .collect(Collectors.toMap(Map.Entry::getKey, i -> toString(i.getValue()), throwingMerger, LinkedHashMap::new)) .toString(); } @Override public String convertListOfAttributeValues(List<AttributeValue> value) { return value.stream() .map(Visitor::toString) .collect(toList()) .toString(); } public static String toString(AttributeValue attributeValue) { return EnhancedAttributeValue.fromAttributeValue(attributeValue).convert(Visitor.INSTANCE); } } }
4,449
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/attribute/OptionalLongAttributeConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute; import java.math.BigDecimal; import java.math.BigInteger; 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.AttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType; import software.amazon.awssdk.enhanced.dynamodb.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.TypeConvertingVisitor; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.string.OptionalLongStringConverter; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * A converter between {@link OptionalLong} and {@link AttributeValue}. * * <p> * This stores values in DynamoDB as a number. * * <p> * This supports reading numbers between {@link Long#MIN_VALUE} and {@link Long#MAX_VALUE} from DynamoDB. Null values are * converted to {@code OptionalLong.empty()}. For larger numbers, consider using the {@link OptionalAttributeConverter} * along with a {@link BigInteger}. For shorter numbers, consider using the {@link OptionalIntAttributeConverter} or * {@link OptionalAttributeConverter} along with a {@link Short} type. * * <p> * This does not support reading decimal numbers. For decimal numbers, consider using {@link OptionalDoubleAttributeConverter}, * or the {@link OptionalAttributeConverter} with a {@link Float} or {@link BigDecimal}. Decimal numbers will cause a * {@link NumberFormatException} on conversion. * * <p> * This can be created via {@link #create()}. */ @SdkInternalApi @ThreadSafe @Immutable public final class OptionalLongAttributeConverter implements AttributeConverter<OptionalLong> { private static final Visitor VISITOR = new Visitor(); private static final OptionalLongStringConverter STRING_CONVERTER = OptionalLongStringConverter.create(); private OptionalLongAttributeConverter() { } @Override public EnhancedType<OptionalLong> type() { return EnhancedType.of(OptionalLong.class); } @Override public AttributeValueType attributeValueType() { return AttributeValueType.N; } public static OptionalLongAttributeConverter create() { return new OptionalLongAttributeConverter(); } @Override public AttributeValue transformFrom(OptionalLong input) { if (input.isPresent()) { return AttributeValue.builder().n(STRING_CONVERTER.toString(input)).build(); } else { return AttributeValues.nullAttributeValue(); } } @Override public OptionalLong transformTo(AttributeValue input) { if (input.n() != null) { return EnhancedAttributeValue.fromNumber(input.n()).convert(VISITOR); } return EnhancedAttributeValue.fromAttributeValue(input).convert(VISITOR); } private static final class Visitor extends TypeConvertingVisitor<OptionalLong> { private Visitor() { super(OptionalLong.class, OptionalLongAttributeConverter.class); } @Override public OptionalLong convertNull() { return OptionalLong.empty(); } @Override public OptionalLong convertString(String value) { return STRING_CONVERTER.fromString(value); } @Override public OptionalLong convertNumber(String value) { return STRING_CONVERTER.fromString(value); } } }
4,450
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/attribute/SdkBytesAttributeConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.enhanced.dynamodb.AttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType; import software.amazon.awssdk.enhanced.dynamodb.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.TypeConvertingVisitor; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * A converter between {@link SdkBytes} and {@link AttributeValue}. * * <p> * This stores values in DynamoDB as a binary blob. * * <p> * This supports reading every byte value supported by DynamoDB, making it fully compatible with custom converters as * well as internal converters (e.g. {@link ByteArrayAttributeConverter}). * * <p> * This can be created via {@link #create()}. */ @SdkInternalApi @ThreadSafe @Immutable public final class SdkBytesAttributeConverter implements AttributeConverter<SdkBytes> { private static final Visitor VISITOR = new Visitor(); private SdkBytesAttributeConverter() { } @Override public EnhancedType<SdkBytes> type() { return EnhancedType.of(SdkBytes.class); } @Override public AttributeValueType attributeValueType() { return AttributeValueType.B; } public static SdkBytesAttributeConverter create() { return new SdkBytesAttributeConverter(); } @Override public AttributeValue transformFrom(SdkBytes input) { return AttributeValue.builder().b(input).build(); } @Override public SdkBytes transformTo(AttributeValue input) { return EnhancedAttributeValue.fromBytes(input.b()).convert(VISITOR); } private static final class Visitor extends TypeConvertingVisitor<SdkBytes> { private Visitor() { super(SdkBytes.class, SdkBytesAttributeConverter.class); } @Override public SdkBytes convertBytes(SdkBytes value) { return value; } } }
4,451
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/attribute/PeriodAttributeConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute; import java.time.Period; import java.time.format.DateTimeParseException; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkInternalApi; 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.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.TypeConvertingVisitor; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.string.PeriodStringConverter; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * A converter between {@link Period} and {@link AttributeValue}. * * <p> * This stores and reads values in DynamoDB as a string, according to the format of {@link Period#parse(CharSequence)} and * {@link Period#toString()}. * <p> * This can be created via {@link #create()}. */ @SdkInternalApi @ThreadSafe @Immutable public final class PeriodAttributeConverter implements AttributeConverter<Period> { private static final Visitor VISITOR = new Visitor(); private static final PeriodStringConverter STRING_CONVERTER = PeriodStringConverter.create(); private PeriodAttributeConverter() { } public static PeriodAttributeConverter create() { return new PeriodAttributeConverter(); } @Override public EnhancedType<Period> type() { return EnhancedType.of(Period.class); } @Override public AttributeValueType attributeValueType() { return AttributeValueType.S; } @Override public AttributeValue transformFrom(Period input) { return AttributeValue.builder().s(STRING_CONVERTER.toString(input)).build(); } @Override public Period transformTo(AttributeValue input) { try { return EnhancedAttributeValue.fromAttributeValue(input).convert(VISITOR); } catch (DateTimeParseException e) { throw new IllegalArgumentException(e); } } private static final class Visitor extends TypeConvertingVisitor<Period> { private Visitor() { super(Period.class, PeriodAttributeConverter.class); } @Override public Period convertString(String value) { return STRING_CONVERTER.fromString(value); } } }
4,452
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/attribute/StringBufferAttributeConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkInternalApi; 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.EnhancedType; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * A converter between {@link StringBuffer} and {@link AttributeValue}. * * <p> * This stores values in DynamoDB as a string. * * <p> * This supports reading any DynamoDB attribute type into a string buffer. */ @SdkInternalApi @ThreadSafe @Immutable public final class StringBufferAttributeConverter implements AttributeConverter<StringBuffer> { public static final StringAttributeConverter STRING_CONVERTER = StringAttributeConverter.create(); public static StringBufferAttributeConverter create() { return new StringBufferAttributeConverter(); } @Override public EnhancedType<StringBuffer> type() { return EnhancedType.of(StringBuffer.class); } @Override public AttributeValueType attributeValueType() { return AttributeValueType.S; } @Override public AttributeValue transformFrom(StringBuffer input) { return STRING_CONVERTER.transformFrom(input.toString()); } @Override public StringBuffer transformTo(AttributeValue input) { return new StringBuffer(STRING_CONVERTER.transformTo(input)); } }
4,453
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/attribute/BooleanAttributeConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute; import java.util.concurrent.atomic.AtomicBoolean; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkInternalApi; 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.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.PrimitiveConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.TypeConvertingVisitor; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.string.BooleanStringConverter; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * A converter between {@link AtomicBoolean} and {@link AttributeValue}. * * <p> * This stores values in DynamoDB as a boolean. * * <p> * This supports reading every boolean value supported by DynamoDB, making it fully compatible with custom converters as well * as internal converters (e.g. {@link AtomicBooleanAttributeConverter}). * * <p> * This can be created via {@link #create()}. */ @SdkInternalApi @ThreadSafe @Immutable public final class BooleanAttributeConverter implements AttributeConverter<Boolean>, PrimitiveConverter<Boolean> { private static final Visitor VISITOR = new Visitor(); private static final BooleanStringConverter STRING_CONVERTER = BooleanStringConverter.create(); private BooleanAttributeConverter() { } public static BooleanAttributeConverter create() { return new BooleanAttributeConverter(); } @Override public EnhancedType<Boolean> type() { return EnhancedType.of(Boolean.class); } @Override public AttributeValueType attributeValueType() { return AttributeValueType.BOOL; } @Override public AttributeValue transformFrom(Boolean input) { return AttributeValue.builder().bool(input).build(); } @Override public Boolean transformTo(AttributeValue input) { if (input.bool() != null) { return EnhancedAttributeValue.fromBoolean(input.bool()).convert(VISITOR); } return EnhancedAttributeValue.fromAttributeValue(input).convert(VISITOR); } @Override public EnhancedType<Boolean> primitiveType() { return EnhancedType.of(boolean.class); } private static final class Visitor extends TypeConvertingVisitor<Boolean> { private Visitor() { super(Boolean.class, BooleanAttributeConverter.class); } @Override public Boolean convertString(String value) { return STRING_CONVERTER.fromString(value); } @Override public Boolean convertNumber(String value) { switch (value) { case "0": return false; case "1": return true; default: throw new IllegalArgumentException("Number could not be converted to boolean: " + value); } } @Override public Boolean convertBoolean(Boolean value) { return value; } } }
4,454
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/attribute/ByteArrayAttributeConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.enhanced.dynamodb.AttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType; import software.amazon.awssdk.enhanced.dynamodb.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.TypeConvertingVisitor; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * A converter between {@code byte[]} and {@link AttributeValue}. * * <p> * This stores values in DynamoDB as a binary blob. * * <p> * This supports reading every byte value supported by DynamoDB, making it fully compatible with custom converters as * well as internal converters (e.g. {@link SdkBytesAttributeConverter}). * * <p> * This can be created via {@link #create()}. */ @SdkInternalApi @ThreadSafe @Immutable public final class ByteArrayAttributeConverter implements AttributeConverter<byte[]> { private static final Visitor VISITOR = new Visitor(); private ByteArrayAttributeConverter() { } public static ByteArrayAttributeConverter create() { return new ByteArrayAttributeConverter(); } @Override public EnhancedType<byte[]> type() { return EnhancedType.of(byte[].class); } @Override public AttributeValueType attributeValueType() { return AttributeValueType.B; } @Override public AttributeValue transformFrom(byte[] input) { return AttributeValue.builder().b(SdkBytes.fromByteArray(input)).build(); } @Override public byte[] transformTo(AttributeValue input) { if (input.b() != null) { return EnhancedAttributeValue.fromBytes(input.b()).convert(VISITOR); } return EnhancedAttributeValue.fromAttributeValue(input).convert(VISITOR); } private static final class Visitor extends TypeConvertingVisitor<byte[]> { private Visitor() { super(byte[].class, ByteArrayAttributeConverter.class); } @Override public byte[] convertBytes(SdkBytes value) { return value.asByteArray(); } } }
4,455
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/attribute/DocumentAttributeConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.enhanced.dynamodb.AttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType; import software.amazon.awssdk.enhanced.dynamodb.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.EnhancedTypeDocumentConfiguration; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * {@link AttributeConverter} for converting nested table schemas */ @SdkInternalApi public class DocumentAttributeConverter<T> implements AttributeConverter<T> { private final TableSchema<T> tableSchema; private final EnhancedType<T> enhancedType; private final boolean preserveEmptyObject; private final boolean ignoreNulls; private DocumentAttributeConverter(TableSchema<T> tableSchema, EnhancedType<T> enhancedType) { this.tableSchema = tableSchema; this.enhancedType = enhancedType; this.preserveEmptyObject = enhancedType.documentConfiguration() .map(EnhancedTypeDocumentConfiguration::preserveEmptyObject) .orElse(false); this.ignoreNulls = enhancedType.documentConfiguration() .map(EnhancedTypeDocumentConfiguration::ignoreNulls) .orElse(false); } public static <T> DocumentAttributeConverter<T> create(TableSchema<T> tableSchema, EnhancedType<T> enhancedType) { return new DocumentAttributeConverter<>(tableSchema, enhancedType); } @Override public AttributeValue transformFrom(T input) { return AttributeValue.builder().m(tableSchema.itemToMap(input, ignoreNulls)).build(); } @Override public T transformTo(AttributeValue input) { return tableSchema.mapToItem(input.m(), preserveEmptyObject); } @Override public AttributeValueType attributeValueType() { return AttributeValueType.M; } @Override public EnhancedType<T> type() { return enhancedType; } }
4,456
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/attribute/LocalDateTimeAttributeConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.Year; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkInternalApi; 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.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.ConverterUtils; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.TypeConvertingVisitor; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * A converter between {@link LocalDateTime} and {@link AttributeValue}. * * <p> * This stores and reads values in DynamoDB as a string. * * <p> * Values are stored with nanosecond precision. * * <p> * LocalDateTimes are stored in the official {@link LocalDateTime} format "[-]YYYY-MM-DDTHH:II:SS[.NNNNNNNNN]", where: * <ol> * <li>Y is a year between {@link Year#MIN_VALUE} and {@link Year#MAX_VALUE} (prefixed with - if it is negative)</li> * <li>M is a 2-character, zero-prefixed month between 01 and 12</li> * <li>D is a 2-character, zero-prefixed day between 01 and 31</li> * <li>H is a 2-character, zero-prefixed hour between 00 and 23</li> * <li>I is a 2-character, zero-prefixed minute between 00 and 59</li> * <li>S is a 2-character, zero-prefixed second between 00 and 59</li> * <li>N is a 9-character, zero-prefixed nanosecond between 000,000,000 and 999,999,999. * The . and N may be excluded if N is 0.</li> * </ol> * See {@link LocalDateTime} for more details on the serialization format. * <p> * This is format-compatible with the {@link LocalDateAttributeConverter}, allowing values stored as {@link LocalDate} to be * retrieved as {@link LocalDateTime}s. The time associated with a value stored as a {@link LocalDate} is the * beginning of the day (midnight). * * <p> * This serialization is lexicographically orderable when the year is not negative. * </p> * * Examples: * <ul> * <li>{@code LocalDateTime.of(1988, 5, 21, 0, 0, 0)} is stored as * an AttributeValue with the String "1988-05-21T00:00"</li> * <li>{@code LocalDateTime.of(-1988, 5, 21, 0, 0, 0)} is stored as * an AttributeValue with the String "-1988-05-21T00:00"</li> * <li>{@code LocalDateTime.of(1988, 5, 21, 0, 0, 0).plusSeconds(1)} is stored as * an AttributeValue with the String "1988-05-21T00:00:01"</li> * <li>{@code LocalDateTime.of(1988, 5, 21, 0, 0, 0).minusSeconds(1)} is stored as * an AttributeValue with the String "1988-05-20T23:59:59"</li> * <li>{@code LocalDateTime.of(1988, 5, 21, 0, 0, 0).plusNanos(1)} is stored as * an AttributeValue with the String "1988-05-21T00:00:00.0000000001"</li> * <li>{@code LocalDateTime.of(1988, 5, 21, 0, 0, 0).minusNanos(1)} is stored as * an AttributeValue with the String "1988-05-20T23:59:59.999999999"</li> * </ul> * * <p> * This can be created via {@link #create()}. */ @SdkInternalApi @ThreadSafe @Immutable public final class LocalDateTimeAttributeConverter implements AttributeConverter<LocalDateTime> { private static final Visitor VISITOR = new Visitor(); public static LocalDateTimeAttributeConverter create() { return new LocalDateTimeAttributeConverter(); } @Override public EnhancedType<LocalDateTime> type() { return EnhancedType.of(LocalDateTime.class); } @Override public AttributeValueType attributeValueType() { return AttributeValueType.S; } @Override public AttributeValue transformFrom(LocalDateTime input) { return AttributeValue.builder().s(input.toString()).build(); } @Override public LocalDateTime transformTo(AttributeValue input) { try { if (input.s() != null) { return EnhancedAttributeValue.fromString(input.s()).convert(VISITOR); } return EnhancedAttributeValue.fromAttributeValue(input).convert(VISITOR); } catch (RuntimeException e) { throw new IllegalArgumentException(e); } } private static final class Visitor extends TypeConvertingVisitor<LocalDateTime> { private Visitor() { super(LocalDateTime.class, InstantAsStringAttributeConverter.class); } @Override public LocalDateTime convertString(String value) { if (value.contains("T")) { // AttributeValue.S in LocalDateTime format return LocalDateTime.parse(value); } else { // AttributeValue.S in LocalDate format return ConverterUtils.convertFromLocalDate(LocalDate.parse(value)); } } } }
4,457
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/attribute/UriAttributeConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute; import 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.AttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType; import software.amazon.awssdk.enhanced.dynamodb.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.TypeConvertingVisitor; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.string.UriStringConverter; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * A converter between {@link URI} and {@link AttributeValue}. * * <p> * This stores and reads values in DynamoDB as a string, according to the format of {@link URI#create(String)} and * {@link URI#toString()}. */ @SdkInternalApi @ThreadSafe @Immutable public final class UriAttributeConverter implements AttributeConverter<URI> { public static final UriStringConverter STRING_CONVERTER = UriStringConverter.create(); public static UriAttributeConverter create() { return new UriAttributeConverter(); } @Override public EnhancedType<URI> type() { return EnhancedType.of(URI.class); } @Override public AttributeValueType attributeValueType() { return AttributeValueType.S; } @Override public AttributeValue transformFrom(URI input) { return AttributeValue.builder().s(STRING_CONVERTER.toString(input)).build(); } @Override public URI transformTo(AttributeValue input) { return EnhancedAttributeValue.fromAttributeValue(input).convert(Visitor.INSTANCE); } private static final class Visitor extends TypeConvertingVisitor<URI> { private static final Visitor INSTANCE = new Visitor(); private Visitor() { super(URI.class, UriAttributeConverter.class); } @Override public URI convertString(String value) { return STRING_CONVERTER.fromString(value); } } }
4,458
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/attribute/OptionalDoubleAttributeConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute; import java.math.BigDecimal; import java.math.BigInteger; 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.AttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType; import software.amazon.awssdk.enhanced.dynamodb.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.ConverterUtils; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.TypeConvertingVisitor; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.string.OptionalDoubleStringConverter; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * A converter between {@link OptionalDouble} and {@link AttributeValue}. * * <p> * This stores values in DynamoDB as a number. * * <p> * This supports converting numbers stored in DynamoDB into a double-precision floating point number, within the range * {@link Double#MIN_VALUE}, {@link Double#MAX_VALUE}. Null values are converted to {@code OptionalDouble.empty()}. For less * precision or smaller values, consider using {@link OptionalAttributeConverter} along with a {@link Float} type. * For greater precision or larger values, consider using {@link OptionalAttributeConverter} along with a * {@link BigDecimal} type. * * <p> * If values are known to be whole numbers, it is recommended to use a perfect-precision whole number representation like those * provided by {@link OptionalIntAttributeConverter}, {@link OptionalLongAttributeConverter}, or a * {@link OptionalAttributeConverter} along with a {@link BigInteger} type. * * <p> * This can be created via {@link #create()}. */ @SdkInternalApi @ThreadSafe @Immutable public final class OptionalDoubleAttributeConverter implements AttributeConverter<OptionalDouble> { private static final Visitor VISITOR = new Visitor(); private static final OptionalDoubleStringConverter STRING_CONVERTER = OptionalDoubleStringConverter.create(); private OptionalDoubleAttributeConverter() { } public static OptionalDoubleAttributeConverter create() { return new OptionalDoubleAttributeConverter(); } @Override public EnhancedType<OptionalDouble> type() { return EnhancedType.of(OptionalDouble.class); } @Override public AttributeValueType attributeValueType() { return AttributeValueType.N; } @Override public AttributeValue transformFrom(OptionalDouble input) { if (input.isPresent()) { ConverterUtils.validateDouble(input.getAsDouble()); return AttributeValue.builder().n(STRING_CONVERTER.toString(input)).build(); } else { return AttributeValues.nullAttributeValue(); } } @Override public OptionalDouble transformTo(AttributeValue input) { OptionalDouble result; if (input.n() != null) { result = EnhancedAttributeValue.fromNumber(input.n()).convert(VISITOR); } else { result = EnhancedAttributeValue.fromAttributeValue(input).convert(VISITOR); } result.ifPresent(ConverterUtils::validateDouble); return result; } private static final class Visitor extends TypeConvertingVisitor<OptionalDouble> { private Visitor() { super(OptionalDouble.class, OptionalDoubleAttributeConverter.class); } @Override public OptionalDouble convertNull() { return OptionalDouble.empty(); } @Override public OptionalDouble convertString(String value) { return STRING_CONVERTER.fromString(value); } @Override public OptionalDouble convertNumber(String value) { return STRING_CONVERTER.fromString(value); } } }
4,459
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/attribute/OptionalIntAttributeConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute; import java.math.BigDecimal; import java.math.BigInteger; import java.util.OptionalInt; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkInternalApi; 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.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.TypeConvertingVisitor; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.string.OptionalIntStringConverter; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * A converter between {@link OptionalInt} and {@link AttributeValue}. * * <p> * This stores values in DynamoDB as a number. * * <p> * This supports reading numbers between {@link Integer#MIN_VALUE} and {@link Integer#MAX_VALUE} from DynamoDB. Null values are * converted to {@code OptionalInt.empty()}. For larger numbers, consider using the {@link OptionalLongAttributeConverter} or * the {@link OptionalAttributeConverter} along with a {@link BigInteger}. For shorter numbers, consider using the * {@link OptionalAttributeConverter} along with a {@link Short} type. * * <p> * This does not support reading decimal numbers. For decimal numbers, consider using {@link OptionalDoubleAttributeConverter}, * or the {@link OptionalAttributeConverter} with a {@link Float} or {@link BigDecimal}. Decimal numbers will cause a * {@link NumberFormatException} on conversion. * * <p> * This can be created via {@link #create()}. */ @SdkInternalApi @ThreadSafe @Immutable public final class OptionalIntAttributeConverter implements AttributeConverter<OptionalInt> { private static final Visitor VISITOR = new Visitor(); private static final OptionalIntStringConverter STRING_CONVERTER = OptionalIntStringConverter.create(); private OptionalIntAttributeConverter() { } @Override public EnhancedType<OptionalInt> type() { return EnhancedType.of(OptionalInt.class); } @Override public AttributeValueType attributeValueType() { return AttributeValueType.N; } public static OptionalIntAttributeConverter create() { return new OptionalIntAttributeConverter(); } @Override public AttributeValue transformFrom(OptionalInt input) { if (input.isPresent()) { return AttributeValue.builder().n(STRING_CONVERTER.toString(input)).build(); } else { return AttributeValues.nullAttributeValue(); } } @Override public OptionalInt transformTo(AttributeValue input) { if (input.n() != null) { return EnhancedAttributeValue.fromNumber(input.n()).convert(VISITOR); } return EnhancedAttributeValue.fromAttributeValue(input).convert(VISITOR); } private static final class Visitor extends TypeConvertingVisitor<OptionalInt> { private Visitor() { super(OptionalInt.class, OptionalIntAttributeConverter.class); } @Override public OptionalInt convertNull() { return OptionalInt.empty(); } @Override public OptionalInt convertString(String value) { return STRING_CONVERTER.fromString(value); } @Override public OptionalInt convertNumber(String value) { return STRING_CONVERTER.fromString(value); } } }
4,460
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/attribute/LocalDateAttributeConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.Year; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkInternalApi; 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.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.TypeConvertingVisitor; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * A converter between {@link LocalDate} and {@link AttributeValue}. * * <p> * This stores and reads values in DynamoDB as a String. * * <p> * LocalDates are stored in the official {@link LocalDate} format "[-]YYYY-MM-DD", where: * <ol> * <li>Y is a year between {@link Year#MIN_VALUE} and {@link Year#MAX_VALUE} (prefixed with - if it is negative)</li> * <li>M is a 2-character, zero-prefixed month between 01 and 12</li> * <li>D is a 2-character, zero-prefixed day between 01 and 31</li> * </ol> * See {@link LocalDate} for more details on the serialization format. * * <p> * This is unidirectional format-compatible with the {@link LocalDateTimeAttributeConverter}, allowing values * stored as {@link LocalDate} to be retrieved as {@link LocalDateTime}s. * * <p> * This serialization is lexicographically orderable when the year is not negative. * <p> * * Examples: * <ul> * <li>{@code LocalDate.of(1988, 5, 21)} is stored as as an AttributeValue with the String "1988-05-21"</li> * <li>{@code LocalDate.of(0, 1, 1)} is stored as as an AttributeValue with the String "0000-01-01"</li> * </ul> * * <p> * This can be created via {@link #create()}. */ @SdkInternalApi @ThreadSafe @Immutable public final class LocalDateAttributeConverter implements AttributeConverter<LocalDate> { private static final Visitor VISITOR = new Visitor(); private LocalDateAttributeConverter() { } public static LocalDateAttributeConverter create() { return new LocalDateAttributeConverter(); } @Override public EnhancedType<LocalDate> type() { return EnhancedType.of(LocalDate.class); } @Override public AttributeValueType attributeValueType() { return AttributeValueType.S; } @Override public AttributeValue transformFrom(LocalDate input) { return AttributeValue.builder().s(input.toString()).build(); } @Override public LocalDate transformTo(AttributeValue input) { try { if (input.s() != null) { return EnhancedAttributeValue.fromString(input.s()).convert(VISITOR); } return EnhancedAttributeValue.fromAttributeValue(input).convert(VISITOR); } catch (RuntimeException e) { throw new IllegalArgumentException(e); } } private static final class Visitor extends TypeConvertingVisitor<LocalDate> { private Visitor() { super(LocalDate.class, InstantAsStringAttributeConverter.class); } @Override public LocalDate convertString(String value) { return LocalDate.parse(value); } } }
4,461
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/attribute/ByteAttributeConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkInternalApi; 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.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.PrimitiveConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.TypeConvertingVisitor; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.string.ByteStringConverter; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * A converter between {@link Byte} and {@link AttributeValue}. * * <p> * This stores values in DynamoDB as a single byte. * * <p> * This only supports reading a single byte from DynamoDB. Any binary data greater than 1 byte will cause a RuntimeException * during conversion. * * <p> * This can be created via {@link #create()}. */ @SdkInternalApi @ThreadSafe @Immutable public final class ByteAttributeConverter implements AttributeConverter<Byte>, PrimitiveConverter<Byte> { private static final ByteStringConverter STRING_CONVERTER = ByteStringConverter.create(); private static final Visitor VISITOR = new Visitor(); private ByteAttributeConverter() { } public static ByteAttributeConverter create() { return new ByteAttributeConverter(); } @Override public AttributeValue transformFrom(Byte input) { return AttributeValue.builder().n(STRING_CONVERTER.toString(input)).build(); } @Override public Byte transformTo(AttributeValue input) { if (input.b() != null) { return EnhancedAttributeValue.fromNumber(input.n()).convert(VISITOR); } return EnhancedAttributeValue.fromAttributeValue(input).convert(VISITOR); } @Override public EnhancedType<Byte> type() { return EnhancedType.of(Byte.class); } @Override public AttributeValueType attributeValueType() { return AttributeValueType.N; } @Override public EnhancedType<Byte> primitiveType() { return EnhancedType.of(byte.class); } private static final class Visitor extends TypeConvertingVisitor<Byte> { private Visitor() { super(Byte.class, ByteAttributeConverter.class); } @Override public Byte convertNumber(String number) { return Byte.parseByte(number); } } }
4,462
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/attribute/LocaleAttributeConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute; import java.util.Locale; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkInternalApi; 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.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.TypeConvertingVisitor; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.string.LocaleStringConverter; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * A converter between {@link Locale} and {@link AttributeValue}. * * <p> * This stores and reads values in DynamoDB as a string, according to the format of * {@link Locale#forLanguageTag(String)} and {@link Locale#toLanguageTag()}. */ @SdkInternalApi @ThreadSafe @Immutable public final class LocaleAttributeConverter implements AttributeConverter<Locale> { public static final LocaleStringConverter STRING_CONVERTER = LocaleStringConverter.create(); public static LocaleAttributeConverter create() { return new LocaleAttributeConverter(); } @Override public EnhancedType<Locale> type() { return EnhancedType.of(Locale.class); } @Override public AttributeValueType attributeValueType() { return AttributeValueType.S; } @Override public AttributeValue transformFrom(Locale input) { return AttributeValue.builder().s(STRING_CONVERTER.toString(input)).build(); } @Override public Locale transformTo(AttributeValue input) { return EnhancedAttributeValue.fromAttributeValue(input).convert(Visitor.INSTANCE); } private static final class Visitor extends TypeConvertingVisitor<Locale> { private static final Visitor INSTANCE = new Visitor(); private Visitor() { super(Locale.class, LocaleAttributeConverter.class); } @Override public Locale convertString(String value) { return STRING_CONVERTER.fromString(value); } } }
4,463
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/attribute/EnhancedAttributeValue.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.util.SdkAutoConstructMap; import software.amazon.awssdk.enhanced.dynamodb.AttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.TypeConvertingVisitor; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.utils.ToString; import software.amazon.awssdk.utils.Validate; /** * A simpler, and more user-friendly version of the generated {@link AttributeValue}. * * <p> * This is a union type of the types exposed by DynamoDB, exactly as they're exposed by DynamoDB. * * <p> * An instance of {@link EnhancedAttributeValue} represents exactly one DynamoDB type, like String (s), Number (n) or Bytes (b). * This type can be determined with the {@link #type()} method or the {@code is*} methods like {@link #isString()} or * {@link #isNumber()}. Once the type is known, the value can be extracted with {@code as*} methods like {@link #asString()} * or {@link #asNumber()}. * * <p> * When converting an {@link EnhancedAttributeValue} into a concrete Java type, it can be tedious to use the {@link #type()} or * {@code is*} methods. For this reason, a {@link #convert(TypeConvertingVisitor)} method is provided that exposes a polymorphic * way of converting a value into another type. * * <p> * An instance of {@link EnhancedAttributeValue} is created with the {@code from*} methods, like {@link #fromString(String)} or * {@link #fromNumber(String)}. */ @SdkInternalApi @ThreadSafe @Immutable public final class EnhancedAttributeValue { private final AttributeValueType type; private final boolean isNull; private final Map<String, AttributeValue> mapValue; private final String stringValue; private final String numberValue; private final SdkBytes bytesValue; private final Boolean booleanValue; private final List<String> setOfStringsValue; private final List<String> setOfNumbersValue; private final List<SdkBytes> setOfBytesValue; private final List<AttributeValue> listOfAttributeValuesValue; private EnhancedAttributeValue(InternalBuilder builder) { this.type = builder.type; this.isNull = builder.isNull; this.stringValue = builder.stringValue; this.numberValue = builder.numberValue; this.bytesValue = builder.bytesValue; this.booleanValue = builder.booleanValue; this.mapValue = builder.mapValue == null ? null : Collections.unmodifiableMap(builder.mapValue); this.setOfStringsValue = builder.setOfStringsValue == null ? null : Collections.unmodifiableList(builder.setOfStringsValue); this.setOfNumbersValue = builder.setOfNumbersValue == null ? null : Collections.unmodifiableList(builder.setOfNumbersValue); this.setOfBytesValue = builder.setOfBytesValue == null ? null : Collections.unmodifiableList(builder.setOfBytesValue); this.listOfAttributeValuesValue = builder.listOfAttributeValuesValue == null ? null : Collections.unmodifiableList(builder.listOfAttributeValuesValue); } /** * Create an {@link EnhancedAttributeValue} for the null DynamoDB type. * * <p> * Equivalent to: {@code EnhancedAttributeValue.fromGeneratedAttributeValue(AttributeValue.builder().nul(true).build())} * * <p> * This call should never fail with an {@link Exception}. */ public static EnhancedAttributeValue nullValue() { return new InternalBuilder().isNull().build(); } /** * Create an {@link EnhancedAttributeValue} for a map (m) DynamoDB type. * * <p> * Equivalent to: {@code EnhancedAttributeValue.fromGeneratedAttributeValue(AttributeValue.builder().m(...).build())} * * <p> * This call will fail with a {@link RuntimeException} if the provided map is null or has null keys. */ public static EnhancedAttributeValue fromMap(Map<String, AttributeValue> mapValue) { Validate.paramNotNull(mapValue, "mapValue"); Validate.noNullElements(mapValue.keySet(), "Map must not have null keys."); return new InternalBuilder().mapValue(mapValue).build(); } /** * Create an {@link EnhancedAttributeValue} for a string (s) DynamoDB type. * * <p> * Equivalent to: {@code EnhancedAttributeValue.fromGeneratedAttributeValue(AttributeValue.builder().s(...).build())} * * <p> * This call will fail with a {@link RuntimeException} if the provided value is null. Use {@link #nullValue()} for * null values. */ public static EnhancedAttributeValue fromString(String stringValue) { Validate.paramNotNull(stringValue, "stringValue"); return new InternalBuilder().stringValue(stringValue).build(); } /** * Create an {@link EnhancedAttributeValue} for a number (n) DynamoDB type. * * <p> * This is a String, because it matches the underlying DynamoDB representation. * * <p> * Equivalent to: {@code EnhancedAttributeValue.fromGeneratedAttributeValue(AttributeValue.builder().n(...).build())} * * <p> * This call will fail with a {@link RuntimeException} if the provided value is null. Use {@link #nullValue()} for * null values. */ public static EnhancedAttributeValue fromNumber(String numberValue) { Validate.paramNotNull(numberValue, "numberValue"); return new InternalBuilder().numberValue(numberValue).build(); } /** * Create an {@link EnhancedAttributeValue} for a bytes (b) DynamoDB type. * * <p> * Equivalent to: {@code EnhancedAttributeValue.fromGeneratedAttributeValue(AttributeValue.builder().b(...).build())} * * <p> * This call will fail with a {@link RuntimeException} if the provided value is null. Use {@link #nullValue()} for * null values. */ public static EnhancedAttributeValue fromBytes(SdkBytes bytesValue) { Validate.paramNotNull(bytesValue, "bytesValue"); return new InternalBuilder().bytesValue(bytesValue).build(); } /** * Create an {@link EnhancedAttributeValue} for a boolean (bool) DynamoDB type. * * <p> * Equivalent to: {@code EnhancedAttributeValue.fromGeneratedAttributeValue(AttributeValue.builder().bool(...).build())} * * <p> * This call will fail with a {@link RuntimeException} if the provided value is null. Use {@link #nullValue()} for * null values. */ public static EnhancedAttributeValue fromBoolean(Boolean booleanValue) { Validate.paramNotNull(booleanValue, "booleanValue"); return new InternalBuilder().booleanValue(booleanValue).build(); } /** * Create an {@link EnhancedAttributeValue} for a set-of-strings (ss) DynamoDB type. * * <p> * Equivalent to: {@code EnhancedAttributeValue.fromGeneratedAttributeValue(AttributeValue.builder().ss(...).build())} * * <p> * This call will fail with a {@link RuntimeException} if the provided value is null or contains a null value. Use * {@link #fromListOfAttributeValues(List)} for null values. This <i>will not</i> validate that there are no * duplicate values. */ public static EnhancedAttributeValue fromSetOfStrings(String... setOfStringsValue) { Validate.paramNotNull(setOfStringsValue, "setOfStringsValue"); return fromSetOfStrings(Arrays.asList(setOfStringsValue)); } /** * Create an {@link EnhancedAttributeValue} for a set-of-strings (ss) DynamoDB type. * * <p> * Equivalent to: {@code EnhancedAttributeValue.fromGeneratedAttributeValue(AttributeValue.builder().ss(...).build())} * * <p> * This call will fail with a {@link RuntimeException} if the provided value is null or contains a null value. Use * {@link #fromListOfAttributeValues(List)} for null values. This <i>will not</i> validate that there are no * duplicate values. */ public static EnhancedAttributeValue fromSetOfStrings(Collection<String> setOfStringsValue) { Validate.paramNotNull(setOfStringsValue, "setOfStringsValue"); return fromSetOfStrings(new ArrayList<>(setOfStringsValue)); } /** * Create an {@link EnhancedAttributeValue} for a set-of-strings (ss) DynamoDB type. * * <p> * Equivalent to: {@code EnhancedAttributeValue.fromGeneratedAttributeValue(AttributeValue.builder().ss(...).build())} * * <p> * This call will fail with a {@link RuntimeException} if the provided value is null or contains a null value. Use * {@link #fromListOfAttributeValues(List)} for null values. This <i>will not</i> validate that there are no * duplicate values. */ public static EnhancedAttributeValue fromSetOfStrings(List<String> setOfStringsValue) { Validate.paramNotNull(setOfStringsValue, "setOfStringsValue"); Validate.noNullElements(setOfStringsValue, "Set must not have null values."); return new InternalBuilder().setOfStringsValue(setOfStringsValue).build(); } /** * Create an {@link EnhancedAttributeValue} for a set-of-numbers (ns) DynamoDB type. * * <p> * Equivalent to: {@code EnhancedAttributeValue.fromGeneratedAttributeValue(AttributeValue.builder().ns(...).build())} * * <p> * This call will fail with a {@link RuntimeException} if the provided value is null or contains a null value. Use * {@link #fromListOfAttributeValues(List)} for null values. This <i>will not</i> validate that there are no * duplicate values. */ public static EnhancedAttributeValue fromSetOfNumbers(String... setOfNumbersValue) { Validate.paramNotNull(setOfNumbersValue, "setOfNumbersValue"); return fromSetOfNumbers(Arrays.asList(setOfNumbersValue)); } /** * Create an {@link EnhancedAttributeValue} for a set-of-numbers (ns) DynamoDB type. * * <p> * Equivalent to: {@code EnhancedAttributeValue.fromGeneratedAttributeValue(AttributeValue.builder().ns(...).build())} * * <p> * This call will fail with a {@link RuntimeException} if the provided value is null or contains a null value. Use * {@link #fromListOfAttributeValues(List)} for null values. This <i>will not</i> validate that there are no * duplicate values. */ public static EnhancedAttributeValue fromSetOfNumbers(Collection<String> setOfNumbersValue) { Validate.paramNotNull(setOfNumbersValue, "setOfNumbersValue"); return fromSetOfNumbers(new ArrayList<>(setOfNumbersValue)); } /** * Create an {@link EnhancedAttributeValue} for a set-of-numbers (ns) DynamoDB type. * * <p> * Equivalent to: {@code EnhancedAttributeValue.fromGeneratedAttributeValue(AttributeValue.builder().ns(...).build())} * * <p> * This call will fail with a {@link RuntimeException} if the provided value is null or contains a null value. Use * {@link #fromListOfAttributeValues(List)} for null values. This <i>will not</i> validate that there are no * duplicate values. */ public static EnhancedAttributeValue fromSetOfNumbers(List<String> setOfNumbersValue) { Validate.paramNotNull(setOfNumbersValue, "setOfNumbersValue"); Validate.noNullElements(setOfNumbersValue, "Set must not have null values."); return new InternalBuilder().setOfNumbersValue(setOfNumbersValue).build(); } /** * Create an {@link EnhancedAttributeValue} for a set-of-bytes (bs) DynamoDB type. * * <p> * Equivalent to: {@code EnhancedAttributeValue.fromGeneratedAttributeValue(AttributeValue.builder().bs(...).build())} * * <p> * This call will fail with a {@link RuntimeException} if the provided value is null or contains a null value. Use * {@link #fromListOfAttributeValues(List)} for null values. This <i>will not</i> validate that there are no * duplicate values. */ public static EnhancedAttributeValue fromSetOfBytes(Collection<SdkBytes> setOfBytesValue) { Validate.paramNotNull(setOfBytesValue, "setOfBytesValue"); return fromSetOfBytes(new ArrayList<>(setOfBytesValue)); } /** * Create an {@link EnhancedAttributeValue} for a set-of-bytes (bs) DynamoDB type. * * <p> * Equivalent to: {@code EnhancedAttributeValue.fromGeneratedAttributeValue(AttributeValue.builder().bs(...).build())} * * <p> * This call will fail with a {@link RuntimeException} if the provided value is null or contains a null value. Use * {@link #fromListOfAttributeValues(List)} for null values. This <i>will not</i> validate that there are no * duplicate values. */ public static EnhancedAttributeValue fromSetOfBytes(SdkBytes... setOfBytesValue) { Validate.paramNotNull(setOfBytesValue, "setOfBytesValue"); return fromSetOfBytes(Arrays.asList(setOfBytesValue)); } /** * Create an {@link EnhancedAttributeValue} for a set-of-bytes (bs) DynamoDB type. * * <p> * Equivalent to: {@code EnhancedAttributeValue.fromGeneratedAttributeValue(AttributeValue.builder().bs(...).build())} * * <p> * This call will fail with a {@link RuntimeException} if the provided value is null or contains a null value. Use * {@link #fromListOfAttributeValues(List)} for null values. This <i>will not</i> validate that there are no * duplicate values. */ public static EnhancedAttributeValue fromSetOfBytes(List<SdkBytes> setOfBytesValue) { Validate.paramNotNull(setOfBytesValue, "setOfBytesValue"); Validate.noNullElements(setOfBytesValue, "Set must not have null values."); return new InternalBuilder().setOfBytesValue(setOfBytesValue).build(); } /** * Create an {@link EnhancedAttributeValue} for a list-of-attributes (l) DynamoDB type. * * <p> * Equivalent to: {@code EnhancedAttributeValue.fromGeneratedAttributeValue(AttributeValue.builder().l(...).build())} * * <p> * This call will fail with a {@link RuntimeException} if the provided value is null or contains a null value. Use * {@link #nullValue()} for null values. */ public static EnhancedAttributeValue fromListOfAttributeValues(AttributeValue... listOfAttributeValuesValue) { Validate.paramNotNull(listOfAttributeValuesValue, "listOfAttributeValuesValue"); return fromListOfAttributeValues(Arrays.asList(listOfAttributeValuesValue)); } /** * Create an {@link EnhancedAttributeValue} for a list-of-attributes (l) DynamoDB type. * * <p> * Equivalent to: {@code EnhancedAttributeValue.fromGeneratedAttributeValue(AttributeValue.builder().l(...).build())} * * <p> * This call will fail with a {@link RuntimeException} if the provided value is null or contains a null value. Use * {@link #nullValue()} for null values. */ public static EnhancedAttributeValue fromListOfAttributeValues(List<AttributeValue> listOfAttributeValuesValue) { Validate.paramNotNull(listOfAttributeValuesValue, "listOfAttributeValuesValue"); Validate.noNullElements(listOfAttributeValuesValue, "List must not have null values."); return new InternalBuilder().listOfAttributeValuesValue(listOfAttributeValuesValue).build(); } /** * Create an {@link EnhancedAttributeValue} from a generated {@link AttributeValue}. * * <p> * This call will fail with a {@link RuntimeException} if the provided value is null ({@link AttributeValue#nul()} is okay). */ public static EnhancedAttributeValue fromAttributeValue(AttributeValue attributeValue) { Validate.notNull(attributeValue, "Generated attribute value must not contain null values. " + "Use AttributeValue#nul() instead."); if (attributeValue.s() != null) { return EnhancedAttributeValue.fromString(attributeValue.s()); } if (attributeValue.n() != null) { return EnhancedAttributeValue.fromNumber(attributeValue.n()); } if (attributeValue.bool() != null) { return EnhancedAttributeValue.fromBoolean(attributeValue.bool()); } if (Boolean.TRUE.equals(attributeValue.nul())) { return EnhancedAttributeValue.nullValue(); } if (attributeValue.b() != null) { return EnhancedAttributeValue.fromBytes(attributeValue.b()); } if (attributeValue.hasM()) { return EnhancedAttributeValue.fromMap(attributeValue.m()); } if (attributeValue.hasL()) { return EnhancedAttributeValue.fromListOfAttributeValues(attributeValue.l()); } if (attributeValue.hasBs()) { return EnhancedAttributeValue.fromSetOfBytes(attributeValue.bs()); } if (attributeValue.hasSs()) { return EnhancedAttributeValue.fromSetOfStrings(attributeValue.ss()); } if (attributeValue.hasNs()) { return EnhancedAttributeValue.fromSetOfNumbers(attributeValue.ns()); } throw new IllegalStateException("Unable to convert attribute value: " + attributeValue); } /** * Retrieve the underlying DynamoDB type of this value, such as String (s) or Number (n). * * <p> * This call should never fail with an {@link Exception}. */ public AttributeValueType type() { return type; } /** * Apply the provided visitor to this item attribute value, converting it into a specific type. This is useful in * {@link AttributeConverter} implementations, without having to write a switch statement on the {@link #type()}. * * <p> * Reasons this call may fail with a {@link RuntimeException}: * <ol> * <li>If the provided visitor is null.</li> * <li>If the value cannot be converted by this visitor.</li> * </ol> */ public <T> T convert(TypeConvertingVisitor<T> convertingVisitor) { Validate.paramNotNull(convertingVisitor, "convertingVisitor"); return convertingVisitor.convert(this); } /** * Returns true if the underlying DynamoDB type of this value is a Map (m). * * <p> * This call should never fail with an {@link Exception}. */ public boolean isMap() { return mapValue != null; } /** * Returns true if the underlying DynamoDB type of this value is a String (s). * * <p> * This call should never fail with an {@link Exception}. */ public boolean isString() { return stringValue != null; } /** * Returns true if the underlying DynamoDB type of this value is a Number (n). * * <p> * This call should never fail with an {@link Exception}. */ public boolean isNumber() { return numberValue != null; } /** * Returns true if the underlying DynamoDB type of this value is Bytes (b). * * <p> * This call should never fail with an {@link Exception}. */ public boolean isBytes() { return bytesValue != null; } /** * Returns true if the underlying DynamoDB type of this value is a Boolean (bool). * * <p> * This call should never fail with an {@link Exception}. */ public boolean isBoolean() { return booleanValue != null; } /** * Returns true if the underlying DynamoDB type of this value is a Set of Strings (ss). * * <p> * This call should never fail with an {@link Exception}. */ public boolean isSetOfStrings() { return setOfStringsValue != null; } /** * Returns true if the underlying DynamoDB type of this value is a Set of Numbers (ns). * * <p> * This call should never fail with an {@link Exception}. */ public boolean isSetOfNumbers() { return setOfNumbersValue != null; } /** * Returns true if the underlying DynamoDB type of this value is a Set of Bytes (bs). * * <p> * This call should never fail with an {@link Exception}. */ public boolean isSetOfBytes() { return setOfBytesValue != null; } /** * Returns true if the underlying DynamoDB type of this value is a List of AttributeValues (l). * * <p> * This call should never fail with an {@link Exception}. */ public boolean isListOfAttributeValues() { return listOfAttributeValuesValue != null; } /** * Returns true if the underlying DynamoDB type of this value is Null (null). * * <p> * This call should never fail with an {@link Exception}. */ public boolean isNull() { return isNull; } /** * Retrieve this value as a map. * * <p> * This call will fail with a {@link RuntimeException} if {@link #isMap()} is false. */ public Map<String, AttributeValue> asMap() { Validate.isTrue(isMap(), "Value is not a map."); return mapValue; } /** * Retrieve this value as a string. * * <p> * This call will fail with a {@link RuntimeException} if {@link #isString()} is false. */ public String asString() { Validate.isTrue(isString(), "Value is not a string."); return stringValue; } /** * Retrieve this value as a number. * * Note: This returns a {@code String} (instead of a {@code Number}), because that's the generated type from * DynamoDB: {@link AttributeValue#n()}. * * <p> * This call will fail with a {@link RuntimeException} if {@link #isNumber()} is false. */ public String asNumber() { Validate.isTrue(isNumber(), "Value is not a number."); return numberValue; } /** * Retrieve this value as bytes. * * <p> * This call will fail with a {@link RuntimeException} if {@link #isBytes()} is false. */ public SdkBytes asBytes() { Validate.isTrue(isBytes(), "Value is not bytes."); return bytesValue; } /** * Retrieve this value as a boolean. * * <p> * This call will fail with a {@link RuntimeException} if {@link #isBoolean()} is false. */ public Boolean asBoolean() { Validate.isTrue(isBoolean(), "Value is not a boolean."); return booleanValue; } /** * Retrieve this value as a set of strings. * * <p> * Note: This returns a {@code List} (instead of a {@code Set}), because that's the generated type from * DynamoDB: {@link AttributeValue#ss()}. * * <p> * This call will fail with a {@link RuntimeException} if {@link #isSetOfStrings()} is false. */ public List<String> asSetOfStrings() { Validate.isTrue(isSetOfStrings(), "Value is not a list of strings."); return setOfStringsValue; } /** * Retrieve this value as a set of numbers. * * <p> * Note: This returns a {@code List<String>} (instead of a {@code Set<Number>}), because that's the generated type from * DynamoDB: {@link AttributeValue#ns()}. * * <p> * This call will fail with a {@link RuntimeException} if {@link #isSetOfNumbers()} is false. */ public List<String> asSetOfNumbers() { Validate.isTrue(isSetOfNumbers(), "Value is not a list of numbers."); return setOfNumbersValue; } /** * Retrieve this value as a set of bytes. * * <p> * Note: This returns a {@code List} (instead of a {@code Set}), because that's the generated type from * DynamoDB: {@link AttributeValue#bs()}. * * <p> * This call will fail with a {@link RuntimeException} if {@link #isSetOfBytes()} is false. */ public List<SdkBytes> asSetOfBytes() { Validate.isTrue(isSetOfBytes(), "Value is not a list of bytes."); return setOfBytesValue; } /** * Retrieve this value as a list of attribute values. * * <p> * This call will fail with a {@link RuntimeException} if {@link #isListOfAttributeValues()} is false. */ public List<AttributeValue> asListOfAttributeValues() { Validate.isTrue(isListOfAttributeValues(), "Value is not a list of attribute values."); return listOfAttributeValuesValue; } /** * Convert this {@link EnhancedAttributeValue} into a generated {@code Map<String, AttributeValue>}. * * <p> * This call will fail with a {@link RuntimeException} if {@link #isMap()} is false. */ public Map<String, AttributeValue> toAttributeValueMap() { Validate.validState(isMap(), "Cannot convert an attribute value of type %s to a generated item. Must be %s.", type(), AttributeValueType.M); AttributeValue generatedAttributeValue = toAttributeValue(); Validate.validState(generatedAttributeValue.m() != null && !(generatedAttributeValue.m() instanceof SdkAutoConstructMap), "Map EnhancedAttributeValue was not converted into a Map AttributeValue."); return generatedAttributeValue.m(); } /** * Convert this {@link EnhancedAttributeValue} into a generated {@link AttributeValue}. * * <p> * This call should never fail with an {@link Exception}. */ public AttributeValue toAttributeValue() { return convert(ToGeneratedAttributeValueVisitor.INSTANCE); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } EnhancedAttributeValue that = (EnhancedAttributeValue) o; if (isNull != that.isNull) { return false; } if (type != that.type) { return false; } if (mapValue != null ? !mapValue.equals(that.mapValue) : that.mapValue != null) { return false; } if (stringValue != null ? !stringValue.equals(that.stringValue) : that.stringValue != null) { return false; } if (numberValue != null ? !numberValue.equals(that.numberValue) : that.numberValue != null) { return false; } if (bytesValue != null ? !bytesValue.equals(that.bytesValue) : that.bytesValue != null) { return false; } if (booleanValue != null ? !booleanValue.equals(that.booleanValue) : that.booleanValue != null) { return false; } if (setOfStringsValue != null ? !setOfStringsValue.equals(that.setOfStringsValue) : that.setOfStringsValue != null) { return false; } if (setOfNumbersValue != null ? !setOfNumbersValue.equals(that.setOfNumbersValue) : that.setOfNumbersValue != null) { return false; } if (setOfBytesValue != null ? !setOfBytesValue.equals(that.setOfBytesValue) : that.setOfBytesValue != null) { return false; } return listOfAttributeValuesValue != null ? listOfAttributeValuesValue.equals(that.listOfAttributeValuesValue) : that.listOfAttributeValuesValue == null; } @Override public int hashCode() { int result = type.hashCode(); result = 31 * result + (isNull ? 1 : 0); result = 31 * result + (mapValue != null ? mapValue.hashCode() : 0); result = 31 * result + (stringValue != null ? stringValue.hashCode() : 0); result = 31 * result + (numberValue != null ? numberValue.hashCode() : 0); result = 31 * result + (bytesValue != null ? bytesValue.hashCode() : 0); result = 31 * result + (booleanValue != null ? booleanValue.hashCode() : 0); result = 31 * result + (setOfStringsValue != null ? setOfStringsValue.hashCode() : 0); result = 31 * result + (setOfNumbersValue != null ? setOfNumbersValue.hashCode() : 0); result = 31 * result + (setOfBytesValue != null ? setOfBytesValue.hashCode() : 0); result = 31 * result + (listOfAttributeValuesValue != null ? listOfAttributeValuesValue.hashCode() : 0); return result; } @Override public String toString() { Object value = convert(ToStringVisitor.INSTANCE); return ToString.builder("EnhancedAttributeValue") .add("type", type) .add("value", value) .build(); } private static class ToGeneratedAttributeValueVisitor extends TypeConvertingVisitor<AttributeValue> { private static final ToGeneratedAttributeValueVisitor INSTANCE = new ToGeneratedAttributeValueVisitor(); private ToGeneratedAttributeValueVisitor() { super(AttributeValue.class); } @Override public AttributeValue convertNull() { return AttributeValue.builder().nul(true).build(); } @Override public AttributeValue convertMap(Map<String, AttributeValue> value) { return AttributeValue.builder().m(value).build(); } @Override public AttributeValue convertString(String value) { return AttributeValue.builder().s(value).build(); } @Override public AttributeValue convertNumber(String value) { return AttributeValue.builder().n(value).build(); } @Override public AttributeValue convertBytes(SdkBytes value) { return AttributeValue.builder().b(value).build(); } @Override public AttributeValue convertBoolean(Boolean value) { return AttributeValue.builder().bool(value).build(); } @Override public AttributeValue convertSetOfStrings(List<String> value) { return AttributeValue.builder().ss(value).build(); } @Override public AttributeValue convertSetOfNumbers(List<String> value) { return AttributeValue.builder().ns(value).build(); } @Override public AttributeValue convertSetOfBytes(List<SdkBytes> value) { return AttributeValue.builder().bs(value).build(); } @Override public AttributeValue convertListOfAttributeValues(List<AttributeValue> value) { return AttributeValue.builder().l(value).build(); } } private static class ToStringVisitor extends TypeConvertingVisitor<Object> { private static final ToStringVisitor INSTANCE = new ToStringVisitor(); private ToStringVisitor() { super(Object.class); } @Override public Object convertNull() { return "null"; } @Override public Object defaultConvert(AttributeValueType type, Object value) { return value; } } private static class InternalBuilder { private AttributeValueType type; private boolean isNull = false; private Map<String, AttributeValue> mapValue; private String stringValue; private String numberValue; private SdkBytes bytesValue; private Boolean booleanValue; private List<String> setOfStringsValue; private List<String> setOfNumbersValue; private List<SdkBytes> setOfBytesValue; private List<AttributeValue> listOfAttributeValuesValue; public InternalBuilder isNull() { this.type = AttributeValueType.NULL; this.isNull = true; return this; } private InternalBuilder mapValue(Map<String, AttributeValue> mapValue) { this.type = AttributeValueType.M; this.mapValue = mapValue; return this; } private InternalBuilder stringValue(String stringValue) { this.type = AttributeValueType.S; this.stringValue = stringValue; return this; } private InternalBuilder numberValue(String numberValue) { this.type = AttributeValueType.N; this.numberValue = numberValue; return this; } private InternalBuilder bytesValue(SdkBytes bytesValue) { this.type = AttributeValueType.B; this.bytesValue = bytesValue; return this; } private InternalBuilder booleanValue(Boolean booleanValue) { this.type = AttributeValueType.BOOL; this.booleanValue = booleanValue; return this; } private InternalBuilder setOfStringsValue(List<String> setOfStringsValue) { this.type = AttributeValueType.SS; this.setOfStringsValue = setOfStringsValue; return this; } private InternalBuilder setOfNumbersValue(List<String> setOfNumbersValue) { this.type = AttributeValueType.NS; this.setOfNumbersValue = setOfNumbersValue; return this; } private InternalBuilder setOfBytesValue(List<SdkBytes> setOfBytesValue) { this.type = AttributeValueType.BS; this.setOfBytesValue = setOfBytesValue; return this; } private InternalBuilder listOfAttributeValuesValue(List<AttributeValue> listOfAttributeValuesValue) { this.type = AttributeValueType.L; this.listOfAttributeValuesValue = listOfAttributeValuesValue; return this; } private EnhancedAttributeValue build() { return new EnhancedAttributeValue(this); } } }
4,464
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/attribute/AtomicIntegerAttributeConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute; import 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.AttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType; import software.amazon.awssdk.enhanced.dynamodb.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.TypeConvertingVisitor; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.string.AtomicIntegerStringConverter; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * A converter between {@link AtomicInteger} and {@link AttributeValue}. * * <p> * This stores values in DynamoDB as a number. * * <p> * This supports reading numbers between {@link Integer#MIN_VALUE} and {@link Integer#MAX_VALUE} from DynamoDB. For smaller * numbers, consider using {@link ShortAttributeConverter}. For larger numbers, consider using {@link LongAttributeConverter} * or {@link BigIntegerAttributeConverter}. Numbers outside of the supported range will cause a {@link NumberFormatException} * on conversion. * * <p> * This does not support reading decimal numbers. For decimal numbers, consider using {@link FloatAttributeConverter}, * {@link DoubleAttributeConverter} or {@link BigDecimalAttributeConverter}. Decimal numbers will cause a * {@link NumberFormatException} on conversion. * * <p> * This can be created via {@link #create()}. */ @SdkInternalApi @ThreadSafe @Immutable public final class AtomicIntegerAttributeConverter implements AttributeConverter<AtomicInteger> { private static final Visitor VISITOR = new Visitor(); private static final AtomicIntegerStringConverter STRING_CONVERTER = AtomicIntegerStringConverter.create(); private AtomicIntegerAttributeConverter() { } @Override public EnhancedType<AtomicInteger> type() { return EnhancedType.of(AtomicInteger.class); } @Override public AttributeValueType attributeValueType() { return AttributeValueType.S; } public static AtomicIntegerAttributeConverter create() { return new AtomicIntegerAttributeConverter(); } @Override public AttributeValue transformFrom(AtomicInteger input) { return AttributeValue.builder().n(STRING_CONVERTER.toString(input)).build(); } @Override public AtomicInteger transformTo(AttributeValue input) { if (input.n() != null) { return EnhancedAttributeValue.fromNumber(input.n()).convert(VISITOR); } return EnhancedAttributeValue.fromAttributeValue(input).convert(VISITOR); } private static final class Visitor extends TypeConvertingVisitor<AtomicInteger> { private Visitor() { super(AtomicInteger.class, AtomicIntegerAttributeConverter.class); } @Override public AtomicInteger convertString(String value) { return STRING_CONVERTER.fromString(value); } @Override public AtomicInteger convertNumber(String value) { return STRING_CONVERTER.fromString(value); } } }
4,465
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/attribute/CharacterArrayAttributeConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkInternalApi; 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.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.string.CharacterArrayStringConverter; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * A converter between {@code char[]} and {@link AttributeValue}. * * <p> * This stores values in DynamoDB as a string. * * <p> * This supports reading every string value supported by DynamoDB, making it fully compatible with custom converters as * well as internal converters (e.g. {@link StringAttributeConverter}). * * <p> * This can be created via {@link #create()}. */ @SdkInternalApi @ThreadSafe @Immutable public final class CharacterArrayAttributeConverter implements AttributeConverter<char[]> { private static final CharacterArrayStringConverter CHAR_ARRAY_STRING_CONVERTER = CharacterArrayStringConverter.create(); private static final StringAttributeConverter STRING_ATTRIBUTE_CONVERTER = StringAttributeConverter.create(); private CharacterArrayAttributeConverter() { } public static CharacterArrayAttributeConverter create() { return new CharacterArrayAttributeConverter(); } @Override public EnhancedType<char[]> type() { return EnhancedType.of(char[].class); } @Override public AttributeValueType attributeValueType() { return AttributeValueType.S; } @Override public AttributeValue transformFrom(char[] input) { return AttributeValue.builder().s(CHAR_ARRAY_STRING_CONVERTER.toString(input)).build(); } @Override public char[] transformTo(AttributeValue input) { return CHAR_ARRAY_STRING_CONVERTER.fromString(STRING_ATTRIBUTE_CONVERTER.transformTo(input)); } }
4,466
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/attribute/ZoneIdAttributeConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute; import java.time.ZoneId; import java.time.zone.ZoneRulesException; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkInternalApi; 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.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.string.ZoneIdStringConverter; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * A converter between {@link ZoneId} and {@link AttributeValue}. * * <p> * This stores and reads values in DynamoDB as a string using {@link ZoneId#toString()} and {@link ZoneId#of(String)}. * * <p> * This can be created via {@link #create()}. */ @SdkInternalApi @ThreadSafe @Immutable public final class ZoneIdAttributeConverter implements AttributeConverter<ZoneId> { public static final ZoneIdStringConverter STRING_CONVERTER = ZoneIdStringConverter.create(); public static ZoneIdAttributeConverter create() { return new ZoneIdAttributeConverter(); } @Override public EnhancedType<ZoneId> type() { return EnhancedType.of(ZoneId.class); } @Override public AttributeValueType attributeValueType() { return AttributeValueType.S; } @Override public AttributeValue transformFrom(ZoneId input) { return AttributeValue.builder().s(STRING_CONVERTER.toString(input)).build(); } @Override public ZoneId transformTo(AttributeValue input) { try { return STRING_CONVERTER.fromString(input.s()); } catch (ZoneRulesException e) { throw new IllegalArgumentException(e); } } }
4,467
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/attribute/AtomicBooleanAttributeConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute; import java.util.concurrent.atomic.AtomicBoolean; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkInternalApi; 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.EnhancedType; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * A converter between {@link AtomicBoolean} and {@link AttributeValue}. * * <p> * This stores values in DynamoDB as a boolean. * * <p> * This supports reading every boolean value supported by DynamoDB, making it fully compatible with custom converters as * well as internal converters (e.g. {@link BooleanAttributeConverter}). * * <p> * This can be created via {@link #create()}. */ @SdkInternalApi @ThreadSafe @Immutable public final class AtomicBooleanAttributeConverter implements AttributeConverter<AtomicBoolean> { private static final BooleanAttributeConverter BOOLEAN_CONVERTER = BooleanAttributeConverter.create(); private AtomicBooleanAttributeConverter() { } @Override public EnhancedType<AtomicBoolean> type() { return EnhancedType.of(AtomicBoolean.class); } @Override public AttributeValueType attributeValueType() { return AttributeValueType.BOOL; } public static AtomicBooleanAttributeConverter create() { return new AtomicBooleanAttributeConverter(); } @Override public AttributeValue transformFrom(AtomicBoolean input) { return AttributeValue.builder().bool(input.get()).build(); } @Override public AtomicBoolean transformTo(AttributeValue input) { return new AtomicBoolean(BOOLEAN_CONVERTER.transformTo(input)); } }
4,468
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/attribute/AtomicLongAttributeConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute; import 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.AttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType; import software.amazon.awssdk.enhanced.dynamodb.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.TypeConvertingVisitor; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.string.AtomicLongStringConverter; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * A converter between {@link AtomicLong} and {@link AttributeValue}. * * <p> * This stores values in DynamoDB as a number. * * <p> * This supports reading numbers between {@link Long#MIN_VALUE} and {@link Long#MAX_VALUE} from DynamoDB. For smaller * numbers, consider using {@link ShortAttributeConverter} or {@link IntegerAttributeConverter}. For larger numbers, consider * using {@link BigIntegerAttributeConverter}. Numbers outside of the supported range will cause a {@link NumberFormatException} * on conversion. * * <p> * This does not support reading decimal numbers. For decimal numbers, consider using {@link FloatAttributeConverter}, * {@link DoubleAttributeConverter} or {@link BigDecimalAttributeConverter}. Decimal numbers will cause a * {@link NumberFormatException} on conversion. * * <p> * This can be created via {@link #create()}. */ @SdkInternalApi @ThreadSafe @Immutable public final class AtomicLongAttributeConverter implements AttributeConverter<AtomicLong> { private static final Visitor VISITOR = new Visitor(); private static final AtomicLongStringConverter STRING_CONVERTER = AtomicLongStringConverter.create(); private AtomicLongAttributeConverter() { } @Override public EnhancedType<AtomicLong> type() { return EnhancedType.of(AtomicLong.class); } @Override public AttributeValueType attributeValueType() { return AttributeValueType.N; } public static AtomicLongAttributeConverter create() { return new AtomicLongAttributeConverter(); } @Override public AttributeValue transformFrom(AtomicLong input) { return AttributeValue.builder().n(STRING_CONVERTER.toString(input)).build(); } @Override public AtomicLong transformTo(AttributeValue input) { if (input.n() != null) { return EnhancedAttributeValue.fromNumber(input.n()).convert(VISITOR); } return EnhancedAttributeValue.fromAttributeValue(input).convert(VISITOR); } private static final class Visitor extends TypeConvertingVisitor<AtomicLong> { private Visitor() { super(AtomicLong.class, AtomicLongAttributeConverter.class); } @Override public AtomicLong convertString(String value) { return STRING_CONVERTER.fromString(value); } @Override public AtomicLong convertNumber(String value) { return STRING_CONVERTER.fromString(value); } } }
4,469
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/attribute/ShortAttributeConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkInternalApi; 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.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.PrimitiveConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.TypeConvertingVisitor; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.string.ShortStringConverter; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * A converter between {@link Short} and {@link AttributeValue}. * * <p> * This stores values in DynamoDB as a number. * * <p> * This supports reading numbers between {@link Short#MIN_VALUE} and {@link Short#MAX_VALUE} from DynamoDB. For larger numbers, * consider using {@link IntegerAttributeConverter}, {@link LongAttributeConverter} or {@link BigIntegerAttributeConverter}. * Numbers outside of the supported range will cause a {@link NumberFormatException} on conversion. * * <p> * This does not support reading decimal numbers. For decimal numbers, consider using {@link FloatAttributeConverter}, * {@link DoubleAttributeConverter} or {@link BigDecimalAttributeConverter}. Decimal numbers will cause a * {@link NumberFormatException} on conversion. */ @SdkInternalApi @ThreadSafe @Immutable public final class ShortAttributeConverter implements AttributeConverter<Short>, PrimitiveConverter<Short> { public static final ShortStringConverter STRING_CONVERTER = ShortStringConverter.create(); public static ShortAttributeConverter create() { return new ShortAttributeConverter(); } @Override public EnhancedType<Short> type() { return EnhancedType.of(Short.class); } @Override public AttributeValueType attributeValueType() { return AttributeValueType.N; } @Override public AttributeValue transformFrom(Short input) { return AttributeValue.builder().n(STRING_CONVERTER.toString(input)).build(); } @Override public Short transformTo(AttributeValue input) { if (input.n() != null) { return EnhancedAttributeValue.fromNumber(input.n()).convert(Visitor.INSTANCE); } return EnhancedAttributeValue.fromAttributeValue(input).convert(Visitor.INSTANCE); } @Override public EnhancedType<Short> primitiveType() { return EnhancedType.of(short.class); } private static final class Visitor extends TypeConvertingVisitor<Short> { private static final Visitor INSTANCE = new Visitor(); private Visitor() { super(Short.class, ShortAttributeConverter.class); } @Override public Short convertString(String value) { return STRING_CONVERTER.fromString(value); } @Override public Short convertNumber(String value) { return STRING_CONVERTER.fromString(value); } } }
4,470
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/attribute/BigIntegerAttributeConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute; import 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.AttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType; import software.amazon.awssdk.enhanced.dynamodb.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.TypeConvertingVisitor; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.string.BigIntegerStringConverter; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * A converter between {@link BigInteger} and {@link AttributeValue}. * * <p> * This stores values in DynamoDB as a number. * * <p> * This supports reading the full range of integers supported by DynamoDB. For smaller numbers, consider using * {@link ShortAttributeConverter}, {@link IntegerAttributeConverter} or {@link LongAttributeConverter}. * * <p> * This does not support reading decimal numbers. For decimal numbers, consider using {@link FloatAttributeConverter}, * {@link DoubleAttributeConverter} or {@link BigDecimalAttributeConverter}. Decimal numbers will cause a * {@link NumberFormatException} on conversion. * * <p> * This can be created via {@link #create()}. */ @SdkInternalApi @ThreadSafe @Immutable public final class BigIntegerAttributeConverter implements AttributeConverter<BigInteger> { private static final Visitor VISITOR = new Visitor(); private static final BigIntegerStringConverter STRING_CONVERTER = BigIntegerStringConverter.create(); private BigIntegerAttributeConverter() { } public static BigIntegerAttributeConverter create() { return new BigIntegerAttributeConverter(); } @Override public EnhancedType<BigInteger> type() { return EnhancedType.of(BigInteger.class); } @Override public AttributeValueType attributeValueType() { return AttributeValueType.N; } @Override public AttributeValue transformFrom(BigInteger input) { return AttributeValue.builder().n(STRING_CONVERTER.toString(input)).build(); } @Override public BigInteger transformTo(AttributeValue input) { if (input.n() != null) { return EnhancedAttributeValue.fromNumber(input.n()).convert(VISITOR); } return EnhancedAttributeValue.fromAttributeValue(input).convert(VISITOR); } private static final class Visitor extends TypeConvertingVisitor<BigInteger> { private Visitor() { super(BigInteger.class, BigIntegerAttributeConverter.class); } @Override public BigInteger convertString(String value) { return STRING_CONVERTER.fromString(value); } @Override public BigInteger convertNumber(String value) { return STRING_CONVERTER.fromString(value); } } }
4,471
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/attribute/ZonedDateTimeAsStringAttributeConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute; import java.time.Instant; import java.time.OffsetDateTime; 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.AttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType; import software.amazon.awssdk.enhanced.dynamodb.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.TypeConvertingVisitor; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * A converter between {@link ZonedDateTime} and {@link AttributeValue}. * * <p> * This stores values in DynamoDB as a string. * * <p> * Values are stored in a ISO-8601-like format, with the non-offset zone IDs being added at the end of the string in square * brackets. If the zone ID offset has seconds, then they will also be included, even though this is not part of the ISO-8601 * standard. For full ISO-8601 compliance, it is better to use {@link OffsetDateTime}s (without second-level precision in its * offset) or {@link Instant}s, assuming the time zone information is not strictly required. * * <p> * Examples: * <ul> * <li>{@code Instant.EPOCH.atZone(ZoneId.of("Europe/Paris"))} is stored as * an AttributeValue with the String "1970-01-01T01:00+01:00[Europe/Paris]"</li> * <li>{@code OffsetDateTime.MIN.toZonedDateTime()} is stored as * an AttributeValue with the String "-999999999-01-01T00:00+18:00"</li> * <li>{@code OffsetDateTime.MAX.toZonedDateTime()} is stored as * an AttributeValue with the String "+999999999-12-31T23:59:59.999999999-18:00"</li> * <li>{@code Instant.EPOCH.atZone(ZoneOffset.UTC)} is stored as * an AttributeValue with the String "1970-01-01T00:00Z"</li> * </ul> * See {@link OffsetDateTime} for more details on the serialization format. * <p> * This converter can read any values written by itself, {@link InstantAsStringAttributeConverter}, * or {@link OffsetDateTimeAsStringAttributeConverter}. Values written by * {@code Instant} converters are treated as if they are in the UTC time zone. * * <p> * This serialization is lexicographically orderable when the year is not negative. * <p> * This can be created via {@link #create()}. */ @SdkInternalApi @ThreadSafe @Immutable public final class ZonedDateTimeAsStringAttributeConverter implements AttributeConverter<ZonedDateTime> { private static final Visitor VISITOR = new Visitor(); public static ZonedDateTimeAsStringAttributeConverter create() { return new ZonedDateTimeAsStringAttributeConverter(); } @Override public EnhancedType<ZonedDateTime> type() { return EnhancedType.of(ZonedDateTime.class); } @Override public AttributeValueType attributeValueType() { return AttributeValueType.S; } @Override public AttributeValue transformFrom(ZonedDateTime input) { return AttributeValue.builder().s(input.toString()).build(); } @Override public ZonedDateTime transformTo(AttributeValue input) { try { if (input.s() != null) { return EnhancedAttributeValue.fromString(input.s()).convert(VISITOR); } return EnhancedAttributeValue.fromAttributeValue(input).convert(VISITOR); } catch (RuntimeException e) { throw new IllegalArgumentException(e); } } private static final class Visitor extends TypeConvertingVisitor<ZonedDateTime> { private Visitor() { super(ZonedDateTime.class, InstantAsStringAttributeConverter.class); } @Override public ZonedDateTime convertString(String value) { return ZonedDateTime.parse(value); } } }
4,472
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/attribute/JsonItemAttributeConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.enhanced.dynamodb.AttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType; import software.amazon.awssdk.enhanced.dynamodb.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.TypeConvertingVisitor; import software.amazon.awssdk.protocols.jsoncore.JsonNode; import software.amazon.awssdk.protocols.jsoncore.internal.ArrayJsonNode; import software.amazon.awssdk.protocols.jsoncore.internal.BooleanJsonNode; import software.amazon.awssdk.protocols.jsoncore.internal.NullJsonNode; import software.amazon.awssdk.protocols.jsoncore.internal.NumberJsonNode; import software.amazon.awssdk.protocols.jsoncore.internal.ObjectJsonNode; import software.amazon.awssdk.protocols.jsoncore.internal.StringJsonNode; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.utils.BinaryUtils; /** * An Internal converter between JsonNode and {@link AttributeValue}. * * <p> * This converts the Attribute Value read from the DDB to JsonNode. */ @SdkInternalApi @ThreadSafe @Immutable public final class JsonItemAttributeConverter implements AttributeConverter<JsonNode> { private static final Visitor VISITOR = new Visitor(); private JsonItemAttributeConverter() { } public static JsonItemAttributeConverter create() { return new JsonItemAttributeConverter(); } @Override public EnhancedType<JsonNode> type() { return EnhancedType.of(JsonNode.class); } @Override public AttributeValueType attributeValueType() { return AttributeValueType.M; } @Override public AttributeValue transformFrom(JsonNode input) { JsonNodeToAttributeValueMapConverter attributeValueMapConverter = JsonNodeToAttributeValueMapConverter.instance(); return input.visit(attributeValueMapConverter); } @Override public JsonNode transformTo(AttributeValue input) { if (AttributeValue.fromNul(true).equals(input)) { return NullJsonNode.instance(); } return EnhancedAttributeValue.fromAttributeValue(input).convert(VISITOR); } private static final class Visitor extends TypeConvertingVisitor<JsonNode> { private Visitor() { super(JsonNode.class, JsonItemAttributeConverter.class); } @Override public JsonNode convertMap(Map<String, AttributeValue> value) { if (value == null) { return null; } Map<String, JsonNode> jsonNodeMap = new LinkedHashMap<>(); value.entrySet().forEach( k -> { JsonNode jsonNode = this.convert(EnhancedAttributeValue.fromAttributeValue(k.getValue())); jsonNodeMap.put(k.getKey(), jsonNode == null ? NullJsonNode.instance() : jsonNode); }); return new ObjectJsonNode(jsonNodeMap); } @Override public JsonNode convertString(String value) { if (value == null) { return null; } return new StringJsonNode(value); } @Override public JsonNode convertNumber(String value) { if (value == null) { return null; } return new NumberJsonNode(value); } @Override public JsonNode convertBytes(SdkBytes value) { if (value == null) { return null; } return new StringJsonNode(BinaryUtils.toBase64(value.asByteArray())); } @Override public JsonNode convertBoolean(Boolean value) { if (value == null) { return null; } return new BooleanJsonNode(value); } @Override public JsonNode convertSetOfStrings(List<String> value) { if (value == null) { return null; } return new ArrayJsonNode(value.stream().map(StringJsonNode::new).collect(Collectors.toList())); } @Override public JsonNode convertSetOfNumbers(List<String> value) { if (value == null) { return null; } return new ArrayJsonNode(value.stream().map(NumberJsonNode::new).collect(Collectors.toList())); } @Override public JsonNode convertSetOfBytes(List<SdkBytes> value) { if (value == null) { return null; } return new ArrayJsonNode(value.stream().map( sdkByte -> new StringJsonNode(BinaryUtils.toBase64(sdkByte.asByteArray())) ).collect(Collectors.toList())); } @Override public JsonNode convertListOfAttributeValues(List<AttributeValue> value) { if (value == null) { return null; } return new ArrayJsonNode(value.stream().map( attributeValue -> { EnhancedAttributeValue enhancedAttributeValue = EnhancedAttributeValue.fromAttributeValue(attributeValue); return enhancedAttributeValue.isNull() ? NullJsonNode.instance() : enhancedAttributeValue.convert(VISITOR); }).collect(Collectors.toList())); } } }
4,473
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/attribute/LocalTimeAttributeConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute; import java.time.DateTimeException; 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.AttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType; import software.amazon.awssdk.enhanced.dynamodb.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.TypeConvertingVisitor; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * A converter between {@link LocalTime} and {@link AttributeValue}. * * <p> * This stores and reads values in DynamoDB as a String. * * <p> * LocalTimes are stored in the official {@link LocalTime} format "HH:II:SS[.NNNNNNNNN]", where: * <ol> * <li>H is a 2-character, zero-prefixed hour between 00 and 23</li> * <li>I is a 2-character, zero-prefixed minute between 00 and 59</li> * <li>S is a 2-character, zero-prefixed second between 00 and 59</li> * <li>N is a 9-character, zero-prefixed nanosecond between 000,000,000 and 999,999,999. * The . and N may be excluded if N is 0.</li> * </ol> * See {@link LocalTime} for more details on the serialization format. * * <p> * This serialization is lexicographically orderable. * <p> * * Examples: * <ul> * <li>{@code LocalTime.of(5, 30, 0)} is stored as an AttributeValue with the String "05:30"</li> * <li>{@code LocalTime.of(5, 30, 0, 1)} is stored as an AttributeValue with the String "05:30:00.000000001"</li> * </ul> * * <p> * This can be created via {@link #create()}. */ @SdkInternalApi @ThreadSafe @Immutable public final class LocalTimeAttributeConverter implements AttributeConverter<LocalTime> { private static final Visitor VISITOR = new Visitor(); private LocalTimeAttributeConverter() { } public static LocalTimeAttributeConverter create() { return new LocalTimeAttributeConverter(); } @Override public EnhancedType<LocalTime> type() { return EnhancedType.of(LocalTime.class); } @Override public AttributeValueType attributeValueType() { return AttributeValueType.S; } @Override public AttributeValue transformFrom(LocalTime input) { return AttributeValue.builder().s(input.toString()).build(); } @Override public LocalTime transformTo(AttributeValue input) { if (input.s() != null) { return EnhancedAttributeValue.fromString(input.s()).convert(VISITOR); } return EnhancedAttributeValue.fromAttributeValue(input).convert(VISITOR); } private static final class Visitor extends TypeConvertingVisitor<LocalTime> { private Visitor() { super(LocalTime.class, InstantAsStringAttributeConverter.class); } @Override public LocalTime convertString(String value) { try { return LocalTime.parse(value); } catch (DateTimeException e) { throw new IllegalArgumentException(e); } } } }
4,474
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/attribute/OptionalAttributeConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute; import java.util.Optional; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkInternalApi; 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.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * A converter between {@link Optional} and {@link EnhancedAttributeValue}. */ @SdkInternalApi @ThreadSafe @Immutable public class OptionalAttributeConverter<T> implements AttributeConverter<Optional<T>> { private final AttributeConverter delegate; private OptionalAttributeConverter(AttributeConverter delegate) { this.delegate = delegate; } public static OptionalAttributeConverter create(AttributeConverter delegate) { return new OptionalAttributeConverter(delegate); } @Override public EnhancedType<Optional<T>> type() { return EnhancedType.optionalOf(delegate.type().rawClass()); } @Override public AttributeValueType attributeValueType() { return AttributeValueType.S; } @Override public AttributeValue transformFrom(Optional<T> input) { if (!input.isPresent()) { return AttributeValues.nullAttributeValue(); } return delegate.transformFrom(input.get()); } @SuppressWarnings("unchecked") @Override public Optional<T> transformTo(AttributeValue input) { Optional<T> result; if (Boolean.TRUE.equals(input.nul())) { // This is safe - An Optional.empty() can be used for any Optional<?> subtype. result = Optional.empty(); } else { result = (Optional<T>) Optional.ofNullable(delegate.transformTo(input)); } return result; } }
4,475
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/attribute/OffsetDateTimeAsStringAttributeConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute; import java.time.OffsetDateTime; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkInternalApi; 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.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.TypeConvertingVisitor; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * A converter between {@link OffsetDateTime} and {@link AttributeValue}. * * <p> * This stores values in DynamoDB as a string. * * <p> * Values are stored in ISO-8601 format, with nanosecond precision. If the offset has seconds then they will also be included, * even though this is not part of the ISO-8601 standard. For full ISO-8601 compliance, ensure your {@code OffsetDateTime}s do * not have offsets at the precision level of seconds. * * <p> * Examples: * <ul> * <li>{@code OffsetDateTime.MIN} is stored as * an AttributeValue with the String "-999999999-01-01T00:00+18:00"</li> * <li>{@code OffsetDateTime.MAX} is stored as * an AttributeValue with the String "+999999999-12-31T23:59:59.999999999-18:00"</li> * <li>{@code Instant.EPOCH.atOffset(ZoneOffset.UTC).plusSeconds(1)} is stored as * an AttributeValue with the String "1970-01-01T00:00:01Z"</li> * <li>{@code Instant.EPOCH.atOffset(ZoneOffset.UTC).minusSeconds(1)} is stored as * an AttributeValue with the String "1969-12-31T23:59:59Z"</li> * <li>{@code Instant.EPOCH.atOffset(ZoneOffset.UTC).plusMillis(1)} is stored as * an AttributeValue with the String "1970-01-01T00:00:00.001Z"</li> * <li>{@code Instant.EPOCH.atOffset(ZoneOffset.UTC).minusMillis(1)} is stored as * an AttributeValue with the String "1969-12-31T23:59:59.999Z"</li> * <li>{@code Instant.EPOCH.atOffset(ZoneOffset.UTC).plusNanos(1)} is stored as * an AttributeValue with the String "1970-01-01T00:00:00.000000001Z"</li> * <li>{@code Instant.EPOCH.atOffset(ZoneOffset.UTC).minusNanos(1)} is stored as * an AttributeValue with the String "1969-12-31T23:59:59.999999999Z"</li> * </ul> * See {@link OffsetDateTime} for more details on the serialization format. * <p> * This converter can read any values written by itself or {@link InstantAsStringAttributeConverter}, * and values without a time zone named written by{@link ZonedDateTimeAsStringAttributeConverter}. * Values written by {@code Instant} converters are treated as if they are in the UTC time zone * (and an offset of 0 seconds will be returned). * * <p> * This serialization is lexicographically orderable when the year is not negative. * <p> * This can be created via {@link #create()}. */ @SdkInternalApi @ThreadSafe @Immutable public final class OffsetDateTimeAsStringAttributeConverter implements AttributeConverter<OffsetDateTime> { private static final Visitor VISITOR = new Visitor(); public static OffsetDateTimeAsStringAttributeConverter create() { return new OffsetDateTimeAsStringAttributeConverter(); } @Override public EnhancedType<OffsetDateTime> type() { return EnhancedType.of(OffsetDateTime.class); } @Override public AttributeValueType attributeValueType() { return AttributeValueType.S; } @Override public AttributeValue transformFrom(OffsetDateTime input) { return AttributeValue.builder().s(input.toString()).build(); } @Override public OffsetDateTime transformTo(AttributeValue input) { try { if (input.s() != null) { return EnhancedAttributeValue.fromString(input.s()).convert(VISITOR); } return EnhancedAttributeValue.fromAttributeValue(input).convert(VISITOR); } catch (RuntimeException e) { throw new IllegalArgumentException(e); } } private static final class Visitor extends TypeConvertingVisitor<OffsetDateTime> { private Visitor() { super(OffsetDateTime.class, InstantAsStringAttributeConverter.class); } @Override public OffsetDateTime convertString(String value) { return OffsetDateTime.parse(value); } } }
4,476
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/attribute/CharacterAttributeConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkInternalApi; 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.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.PrimitiveConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.TypeConvertingVisitor; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.string.CharacterStringConverter; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * A converter between {@link Character} and {@link AttributeValue}. * * <p> * This stores values in DynamoDB as a single-character string. * * <p> * This only supports reading a single character from DynamoDB. Any string longer than 1 character will cause a RuntimeException * during conversion. * * <p> * This can be created via {@link #create()}. */ @SdkInternalApi @ThreadSafe @Immutable public final class CharacterAttributeConverter implements AttributeConverter<Character>, PrimitiveConverter<Character> { private static final Visitor VISITOR = new Visitor(); private static final CharacterStringConverter STRING_CONVERTER = CharacterStringConverter.create(); private CharacterAttributeConverter() { } public static CharacterAttributeConverter create() { return new CharacterAttributeConverter(); } @Override public EnhancedType<Character> type() { return EnhancedType.of(Character.class); } @Override public AttributeValueType attributeValueType() { return AttributeValueType.S; } @Override public AttributeValue transformFrom(Character input) { return AttributeValue.builder().s(STRING_CONVERTER.toString(input)).build(); } @Override public Character transformTo(AttributeValue input) { if (input.s() != null) { return EnhancedAttributeValue.fromString(input.s()).convert(VISITOR); } return EnhancedAttributeValue.fromAttributeValue(input).convert(VISITOR); } @Override public EnhancedType<Character> primitiveType() { return EnhancedType.of(char.class); } private static final class Visitor extends TypeConvertingVisitor<Character> { private Visitor() { super(Character.class, CharacterAttributeConverter.class); } @Override public Character convertString(String value) { return STRING_CONVERTER.fromString(value); } } }
4,477
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/attribute/JsonNodeToAttributeValueMapConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.protocols.jsoncore.JsonNode; import software.amazon.awssdk.protocols.jsoncore.JsonNodeVisitor; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; @SdkInternalApi public class JsonNodeToAttributeValueMapConverter implements JsonNodeVisitor<AttributeValue> { private static final JsonNodeToAttributeValueMapConverter INSTANCE = new JsonNodeToAttributeValueMapConverter(); private JsonNodeToAttributeValueMapConverter() { } public static JsonNodeToAttributeValueMapConverter instance() { return INSTANCE; } @Override public AttributeValue visitNull() { return AttributeValue.fromNul(true); } @Override public AttributeValue visitBoolean(boolean bool) { return AttributeValue.builder().bool(bool).build(); } @Override public AttributeValue visitNumber(String number) { return AttributeValue.builder().n(number).build(); } @Override public AttributeValue visitString(String string) { return AttributeValue.builder().s(string).build(); } @Override public AttributeValue visitArray(List<JsonNode> array) { return AttributeValue.builder().l(array.stream() .map(node -> node.visit(this)) .collect(Collectors.toList())) .build(); } @Override public AttributeValue visitObject(Map<String, JsonNode> object) { return AttributeValue.builder().m(object.entrySet().stream() .collect(Collectors.toMap( Map.Entry::getKey, entry -> entry.getValue().visit(this), (left, right) -> left, LinkedHashMap::new))) .build(); } @Override public AttributeValue visitEmbeddedObject(Object embeddedObject) { throw new UnsupportedOperationException("Embedded objects are not supported within Document types."); } }
4,478
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/attribute/UuidAttributeConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute; import java.util.UUID; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkInternalApi; 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.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.TypeConvertingVisitor; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.string.UuidStringConverter; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * A converter between {@link UUID} and {@link AttributeValue}. * * <p> * This supports storing and reading values in DynamoDB as a string. */ @SdkInternalApi @ThreadSafe @Immutable public final class UuidAttributeConverter implements AttributeConverter<UUID> { public static final UuidStringConverter STRING_CONVERTER = UuidStringConverter.create(); public static UuidAttributeConverter create() { return new UuidAttributeConverter(); } @Override public EnhancedType<UUID> type() { return EnhancedType.of(UUID.class); } @Override public AttributeValueType attributeValueType() { return AttributeValueType.S; } @Override public AttributeValue transformFrom(UUID input) { return AttributeValue.builder().s(STRING_CONVERTER.toString(input)).build(); } @Override public UUID transformTo(AttributeValue input) { return EnhancedAttributeValue.fromAttributeValue(input).convert(Visitor.INSTANCE); } private static final class Visitor extends TypeConvertingVisitor<UUID> { private static final Visitor INSTANCE = new Visitor(); private Visitor() { super(UUID.class, UuidAttributeConverter.class); } @Override public UUID convertString(String value) { return STRING_CONVERTER.fromString(value); } } }
4,479
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/attribute/IntegerAttributeConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute; import 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.AttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType; import software.amazon.awssdk.enhanced.dynamodb.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.PrimitiveConverter; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.TypeConvertingVisitor; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.string.IntegerStringConverter; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * A converter between {@link Integer} and {@link AttributeValue}. * * <p> * This stores values in DynamoDB as a number. * * <p> * This supports reading numbers between {@link Integer#MIN_VALUE} and {@link Integer#MAX_VALUE} from DynamoDB. For smaller * numbers, consider using {@link ShortAttributeConverter}. For larger numbers, consider using {@link LongAttributeConverter} * or {@link BigIntegerAttributeConverter}. Numbers outside of the supported range will cause a {@link NumberFormatException} * on conversion. * * <p> * This does not support reading decimal numbers. For decimal numbers, consider using {@link FloatAttributeConverter}, * {@link DoubleAttributeConverter} or {@link BigDecimalAttributeConverter}. Decimal numbers will cause a * {@link NumberFormatException} on conversion. */ @SdkInternalApi @ThreadSafe @Immutable public final class IntegerAttributeConverter implements AttributeConverter<Integer>, PrimitiveConverter<Integer> { public static final IntegerStringConverter INTEGER_STRING_CONVERTER = IntegerStringConverter.create(); private IntegerAttributeConverter() { } public static IntegerAttributeConverter create() { return new IntegerAttributeConverter(); } @Override public EnhancedType<Integer> type() { return EnhancedType.of(Integer.class); } @Override public AttributeValueType attributeValueType() { return AttributeValueType.N; } @Override public AttributeValue transformFrom(Integer input) { return AttributeValue.builder().n(INTEGER_STRING_CONVERTER.toString(input)).build(); } @Override public Integer transformTo(AttributeValue input) { if (input.n() != null) { return EnhancedAttributeValue.fromNumber(input.n()).convert(Visitor.INSTANCE); } return EnhancedAttributeValue.fromAttributeValue(input).convert(Visitor.INSTANCE); } @Override public EnhancedType<Integer> primitiveType() { return EnhancedType.of(int.class); } private static final class Visitor extends TypeConvertingVisitor<Integer> { private static final Visitor INSTANCE = new Visitor(); private Visitor() { super(Instant.class, IntegerAttributeConverter.class); } @Override public Integer convertString(String value) { return INTEGER_STRING_CONVERTER.fromString(value); } @Override public Integer convertNumber(String value) { return INTEGER_STRING_CONVERTER.fromString(value); } } }
4,480
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/attribute/MonthDayAttributeConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute; import java.time.MonthDay; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkInternalApi; 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.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.TypeConvertingVisitor; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * A converter between {@link MonthDay} and {@link AttributeValue}. * * <p> * This stores and reads values in DynamoDB as a String. * * <p> * MonthDays are stored in the official {@link MonthDay} format "--MM-DD", where: * <ol> * <li>M is a 2-character, zero-prefixed month between 01 and 12</li> * <li>D is a 2-character, zero-prefixed day between 01 and 31</li> * </ol> * See {@link MonthDay} for more details on the serialization format. * * <p> * This serialization is lexicographically orderable. * <p> * * Examples: * <ul> * <li>{@code MonthDay.of(5, 21)} is stored as as an AttributeValue with the String "--05-21"</li> * <li>{@code MonthDay.of(12, 1)} is stored as as an AttributeValue with the String "--12-01"</li> * </ul> * * <p> * This can be created via {@link #create()}. */ @SdkInternalApi @ThreadSafe @Immutable public final class MonthDayAttributeConverter implements AttributeConverter<MonthDay> { private static final Visitor VISITOR = new Visitor(); private MonthDayAttributeConverter() { } public static MonthDayAttributeConverter create() { return new MonthDayAttributeConverter(); } @Override public EnhancedType<MonthDay> type() { return EnhancedType.of(MonthDay.class); } @Override public AttributeValueType attributeValueType() { return AttributeValueType.S; } @Override public AttributeValue transformFrom(MonthDay input) { return AttributeValue.builder().s(input.toString()).build(); } @Override public MonthDay transformTo(AttributeValue input) { try { if (input.s() != null) { return EnhancedAttributeValue.fromString(input.s()).convert(VISITOR); } return EnhancedAttributeValue.fromAttributeValue(input).convert(VISITOR); } catch (RuntimeException e) { throw new IllegalArgumentException(e); } } private static final class Visitor extends TypeConvertingVisitor<MonthDay> { private Visitor() { super(MonthDay.class, MonthDayAttributeConverter.class); } @Override public MonthDay convertString(String value) { return MonthDay.parse(value); } } }
4,481
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/attribute/SetAttributeConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute; import static java.util.stream.Collectors.toList; import java.util.Collection; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.enhanced.dynamodb.AttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType; import software.amazon.awssdk.enhanced.dynamodb.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.TypeConvertingVisitor; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.utils.Validate; /** * A converter between a specific {@link Collection} type and {@link EnhancedAttributeValue}. * * <p> * This stores values in DynamoDB as a list of attribute values. This uses a configured {@link AttributeConverter} to convert * the collection contents to an attribute value. * * <p> * This supports reading a list of attribute values. This uses a configured {@link AttributeConverter} to convert * the collection contents. * * <p> * A builder is exposed to allow defining how the collection and element types are created and converted: * <code> * {@literal AttributeConverter<List<Integer>> listConverter = * CollectionAttributeConverter.builder(EnhancedType.listOf(Integer.class)) * .collectionConstructor(ArrayList::new) * .elementConverter(IntegerAttributeConverter.create()) * .build()} * </code> * * <p> * For frequently-used types, static methods are exposed to reduce the amount of boilerplate involved in creation: * <code> * {@literal AttributeConverter<List<Integer>> listConverter = * CollectionAttributeConverter.listConverter(IntegerAttributeConverter.create());} * </code> * <p> * <code> * {@literal AttributeConverter<Collection<Integer>> collectionConverer = * CollectionAttributeConverter.collectionConverter(IntegerAttributeConverter.create());} * </code> * <p> * <code> * {@literal AttributeConverter<Set<Integer>> setConverter = * CollectionAttributeConverter.setConverter(IntegerAttributeConverter.create());} * </code> * <p> * <code> * {@literal AttributeConverter<SortedSet<Integer>> sortedSetConverter = * CollectionAttributeConverter.sortedSetConverter(IntegerAttributeConverter.create());} * </code> * * @see MapAttributeConverter */ @SdkInternalApi @ThreadSafe @Immutable public class SetAttributeConverter<T extends Collection<?>> implements AttributeConverter<T> { private final Delegate<T, ?> delegate; private SetAttributeConverter(Delegate<T, ?> delegate) { this.delegate = delegate; } public static <U> SetAttributeConverter<Set<U>> setConverter(AttributeConverter<U> elementConverter) { return builder(EnhancedType.setOf(elementConverter.type())) .collectionConstructor(LinkedHashSet::new) .elementConverter(elementConverter) .build(); } public static <T extends Collection<U>, U> SetAttributeConverter.Builder<T, U> builder(EnhancedType<T> collectionType) { return new Builder<>(collectionType); } @Override public EnhancedType<T> type() { return delegate.type(); } @Override public AttributeValueType attributeValueType() { return delegate.attributeValueType(); } @Override public AttributeValue transformFrom(T input) { return delegate.transformFrom(input); } @Override public T transformTo(AttributeValue input) { return delegate.transformTo(input); } private static final class Delegate<T extends Collection<U>, U> implements AttributeConverter<T> { private final EnhancedType<T> type; private final Supplier<? extends T> collectionConstructor; private final AttributeConverter<U> elementConverter; private final AttributeValueType attributeValueType; private Delegate(Builder<T, U> builder) { this.type = builder.collectionType; this.collectionConstructor = builder.collectionConstructor; this.elementConverter = builder.elementConverter; this.attributeValueType = attributeValueTypeForSet(this.elementConverter); } @Override public EnhancedType<T> type() { return type; } @Override public AttributeValueType attributeValueType() { return attributeValueType; } @Override public AttributeValue transformFrom(T input) { return flatten(input.stream() .map(elementConverter::transformFrom) .collect(toList())); } @Override public T transformTo(AttributeValue input) { return EnhancedAttributeValue.fromAttributeValue(input) .convert(new TypeConvertingVisitor<T>(type.rawClass(), SetAttributeConverter.class) { @Override public T convertSetOfStrings(List<String> value) { return convertCollection(value, v -> AttributeValue.builder().s(v).build()); } @Override public T convertSetOfNumbers(List<String> value) { return convertCollection(value, v -> AttributeValue.builder().n(v).build()); } @Override public T convertSetOfBytes(List<SdkBytes> value) { return convertCollection(value, v -> AttributeValue.builder().b(v).build()); } @Override public T convertListOfAttributeValues(List<AttributeValue> value) { return convertCollection(value, Function.identity()); } private <V> T convertCollection(Collection<V> collection, Function<V, AttributeValue> transformFrom) { Collection<Object> result = (Collection<Object>) collectionConstructor.get(); collection.stream() .map(transformFrom) .map(elementConverter::transformTo) .forEach(result::add); // This is a safe cast - We know the values we added to the list // match the type that the customer requested. return (T) result; } }); } private AttributeValueType attributeValueTypeForSet(AttributeConverter<U> innerType) { switch (innerType.attributeValueType()) { case N: return AttributeValueType.NS; case S: return AttributeValueType.SS; case B: return AttributeValueType.BS; default: throw new IllegalArgumentException( String.format("SetAttributeConverter cannot be created with a parameterized type of '%s'. " + "Supported parameterized types must convert to B, S or N DynamoDB " + "AttributeValues.", innerType.type().rawClass())); } } /** * Takes a list of {@link AttributeValue}s and flattens into a resulting * single {@link AttributeValue} set of the corresponding type. */ public AttributeValue flatten(List<AttributeValue> listOfAttributeValues) { Validate.paramNotNull(listOfAttributeValues, "listOfAttributeValues"); Validate.noNullElements(listOfAttributeValues, "List must not have null values."); switch (attributeValueType) { case NS: return AttributeValue.builder() .ns(listOfAttributeValues.stream() .peek(av -> Validate.isTrue(av.n() != null, "Attribute value must be N.")) .map(AttributeValue::n) .collect(Collectors.toList())) .build(); case SS: return AttributeValue.builder() .ss(listOfAttributeValues.stream() .peek(av -> Validate.isTrue(av.s() != null, "Attribute value must be S.")) .map(AttributeValue::s) .collect(Collectors.toList())) .build(); case BS: return AttributeValue.builder() .bs(listOfAttributeValues.stream() .peek(av -> Validate.isTrue(av.b() != null, "Attribute value must be B.")) .map(AttributeValue::b) .collect(Collectors.toList())) .build(); default: throw new IllegalStateException("Unsupported set attribute value type: " + attributeValueType); } } } @NotThreadSafe public static final class Builder<T extends Collection<U>, U> { private final EnhancedType<T> collectionType; private Supplier<? extends T> collectionConstructor; private AttributeConverter<U> elementConverter; private Builder(EnhancedType<T> collectionType) { this.collectionType = collectionType; } public Builder<T, U> collectionConstructor(Supplier<? extends T> collectionConstructor) { this.collectionConstructor = collectionConstructor; return this; } public Builder<T, U> elementConverter(AttributeConverter<U> elementConverter) { this.elementConverter = elementConverter; return this; } public SetAttributeConverter<T> build() { return new SetAttributeConverter<>(new Delegate<>(this)); } } }
4,482
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/attribute/StringBuilderAttributeConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkInternalApi; 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.EnhancedType; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * A converter between {@link StringBuffer} and {@link AttributeValue}. * * <p> * This stores values in DynamoDB as a string. * * <p> * This supports reading any DynamoDB attribute type into a string builder. */ @SdkInternalApi @ThreadSafe @Immutable public final class StringBuilderAttributeConverter implements AttributeConverter<StringBuilder> { public static final StringAttributeConverter STRING_CONVERTER = StringAttributeConverter.create(); public static StringBuilderAttributeConverter create() { return new StringBuilderAttributeConverter(); } @Override public EnhancedType<StringBuilder> type() { return EnhancedType.of(StringBuilder.class); } @Override public AttributeValueType attributeValueType() { return AttributeValueType.S; } @Override public AttributeValue transformFrom(StringBuilder input) { return STRING_CONVERTER.transformFrom(input.toString()); } @Override public StringBuilder transformTo(AttributeValue input) { return new StringBuilder(STRING_CONVERTER.transformTo(input)); } }
4,483
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/BigDecimalStringConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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.BigDecimal; 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 BigDecimal} and {@link String}. * * <p> * This converts values using {@link BigDecimal#toString()} and {@link BigDecimal#BigDecimal(String)}. */ @SdkInternalApi @ThreadSafe @Immutable public class BigDecimalStringConverter implements StringConverter<BigDecimal> { private BigDecimalStringConverter() { } public static BigDecimalStringConverter create() { return new BigDecimalStringConverter(); } @Override public EnhancedType<BigDecimal> type() { return EnhancedType.of(BigDecimal.class); } @Override public BigDecimal fromString(String string) { return new BigDecimal(string); } }
4,484
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/DefaultStringConverterProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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.ArrayList; import java.util.Collection; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.NotThreadSafe; 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.enhanced.dynamodb.internal.converter.StringConverterProvider; import software.amazon.awssdk.utils.Validate; /** * <p> * Included converters: * <ul> * <li>{@link AtomicIntegerStringConverter}</li> * <li>{@link AtomicLongStringConverter}</li> * <li>{@link BigDecimalStringConverter}</li> * <li>{@link BigIntegerStringConverter}</li> * <li>{@link DoubleStringConverter}</li> * <li>{@link DurationStringConverter}</li> * <li>{@link FloatStringConverter}</li> * <li>{@link InstantStringConverter}</li> * <li>{@link IntegerStringConverter}</li> * <li>{@link LocalDateStringConverter}</li> * <li>{@link LocalDateTimeStringConverter}</li> * <li>{@link LocalTimeStringConverter}</li> * <li>{@link LocaleStringConverter}</li> * <li>{@link LongStringConverter}</li> * <li>{@link MonthDayStringConverter}</li> * <li>{@link OptionalDoubleStringConverter}</li> * <li>{@link OptionalIntStringConverter}</li> * <li>{@link OptionalLongStringConverter}</li> * <li>{@link ShortStringConverter}</li> * <li>{@link CharacterArrayStringConverter}</li> * <li>{@link CharacterStringConverter}</li> * <li>{@link CharSequenceStringConverter}</li> * <li>{@link OffsetDateTimeStringConverter}</li> * <li>{@link PeriodStringConverter}</li> * <li>{@link StringStringConverter}</li> * <li>{@link StringBufferStringConverter}</li> * <li>{@link StringBuilderStringConverter}</li> * <li>{@link UriStringConverter}</li> * <li>{@link UrlStringConverter}</li> * <li>{@link UuidStringConverter}</li> * <li>{@link ZonedDateTimeStringConverter}</li> * <li>{@link ZoneIdStringConverter}</li> * <li>{@link ZoneOffsetStringConverter}</li> * <li>{@link ByteArrayStringConverter}</li> * <li>{@link ByteStringConverter}</li> * <li>{@link SdkBytesStringConverter}</li> * <li>{@link AtomicBooleanStringConverter}</li> * <li>{@link BooleanStringConverter}</li> * </ul> * * <p> * This can be created via {@link #create()}. */ @SdkInternalApi @ThreadSafe @Immutable public class DefaultStringConverterProvider implements StringConverterProvider { private final ConcurrentHashMap<EnhancedType<?>, StringConverter<?>> converterCache = new ConcurrentHashMap<>(); private DefaultStringConverterProvider(Builder builder) { // Converters are used in the REVERSE order of how they were added to the builder. for (int i = builder.converters.size() - 1; i >= 0; i--) { StringConverter<?> converter = builder.converters.get(i); converterCache.put(converter.type(), converter); if (converter instanceof PrimitiveConverter) { PrimitiveConverter primitiveConverter = (PrimitiveConverter) converter; converterCache.put(primitiveConverter.primitiveType(), converter); } } } /** * Create a builder for a {@link DefaultStringConverterProvider}. */ public static Builder builder() { return new Builder(); } public static DefaultStringConverterProvider create() { return DefaultStringConverterProvider.builder() .addConverter(ByteArrayStringConverter.create()) .addConverter(CharacterArrayStringConverter.create()) .addConverter(BooleanStringConverter.create()) .addConverter(ShortStringConverter.create()) .addConverter(IntegerStringConverter.create()) .addConverter(LongStringConverter.create()) .addConverter(FloatStringConverter.create()) .addConverter(DoubleStringConverter.create()) .addConverter(CharacterStringConverter.create()) .addConverter(ByteStringConverter.create()) .addConverter(StringStringConverter.create()) .addConverter(CharSequenceStringConverter.create()) .addConverter(StringBufferStringConverter.create()) .addConverter(StringBuilderStringConverter.create()) .addConverter(BigIntegerStringConverter.create()) .addConverter(BigDecimalStringConverter.create()) .addConverter(AtomicLongStringConverter.create()) .addConverter(AtomicIntegerStringConverter.create()) .addConverter(AtomicBooleanStringConverter.create()) .addConverter(OptionalIntStringConverter.create()) .addConverter(OptionalLongStringConverter.create()) .addConverter(OptionalDoubleStringConverter.create()) .addConverter(InstantStringConverter.create()) .addConverter(DurationStringConverter.create()) .addConverter(LocalDateStringConverter.create()) .addConverter(LocalTimeStringConverter.create()) .addConverter(LocalDateTimeStringConverter.create()) .addConverter(LocaleStringConverter.create()) .addConverter(OffsetTimeStringConverter.create()) .addConverter(OffsetDateTimeStringConverter.create()) .addConverter(ZonedDateTimeStringConverter.create()) .addConverter(YearStringConverter.create()) .addConverter(YearMonthStringConverter.create()) .addConverter(MonthDayStringConverter.create()) .addConverter(PeriodStringConverter.create()) .addConverter(ZoneOffsetStringConverter.create()) .addConverter(ZoneIdStringConverter.create()) .addConverter(UuidStringConverter.create()) .addConverter(UrlStringConverter.create()) .addConverter(UriStringConverter.create()) .build(); } @Override public <T> StringConverter converterFor(EnhancedType<T> enhancedType) { @SuppressWarnings("unchecked") // We initialized correctly, so this is safe. StringConverter<T> converter = (StringConverter<T>) converterCache.get(enhancedType); if (converter == null) { throw new IllegalArgumentException("No string converter exists for " + enhancedType.rawClass()); } return converter; } /** * A builder for configuring and creating {@link DefaultStringConverterProvider}s. */ @NotThreadSafe public static class Builder { private List<StringConverter<?>> converters = new ArrayList<>(); private Builder() { } public Builder addConverters(Collection<? extends StringConverter<?>> converters) { Validate.paramNotNull(converters, "converters"); Validate.noNullElements(converters, "Converters must not contain null members."); this.converters.addAll(converters); return this; } public Builder addConverter(StringConverter<?> converter) { Validate.paramNotNull(converter, "converter"); this.converters.add(converter); return this; } public Builder clearConverters() { this.converters.clear(); return this; } public DefaultStringConverterProvider build() { return new DefaultStringConverterProvider(this); } } }
4,485
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/MonthDayStringConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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.MonthDay; 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 MonthDay} and {@link String}. */ @SdkInternalApi @ThreadSafe @Immutable public class MonthDayStringConverter implements StringConverter<MonthDay> { private MonthDayStringConverter() { } public static MonthDayStringConverter create() { return new MonthDayStringConverter(); } @Override public EnhancedType<MonthDay> type() { return EnhancedType.of(MonthDay.class); } @Override public MonthDay fromString(String string) { return MonthDay.parse(string); } }
4,486
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/SdkNumberStringConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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.core.SdkNumber; import software.amazon.awssdk.enhanced.dynamodb.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.StringConverter; /** * A converter between {@link SdkNumber} and {@link String}. * * <p> * This converts values using {@link SdkNumber#toString()} and {@link SdkNumber#fromString(String)}}. */ @SdkInternalApi @ThreadSafe @Immutable public class SdkNumberStringConverter implements StringConverter<SdkNumber> { private SdkNumberStringConverter() { } public static SdkNumberStringConverter create() { return new SdkNumberStringConverter(); } @Override public EnhancedType<SdkNumber> type() { return EnhancedType.of(SdkNumber.class); } @Override public SdkNumber fromString(String string) { return SdkNumber.fromString(string); } }
4,487
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/AtomicBooleanStringConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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.AtomicBoolean; 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 AtomicBoolean} and {@link String}. * * <p> * This converts values using {@link BooleanStringConverter}. */ @SdkInternalApi @ThreadSafe @Immutable public class AtomicBooleanStringConverter implements StringConverter<AtomicBoolean> { private static BooleanStringConverter BOOLEAN_CONVERTER = BooleanStringConverter.create(); private AtomicBooleanStringConverter() { } public static AtomicBooleanStringConverter create() { return new AtomicBooleanStringConverter(); } @Override public EnhancedType<AtomicBoolean> type() { return EnhancedType.of(AtomicBoolean.class); } @Override public String toString(AtomicBoolean object) { return BOOLEAN_CONVERTER.toString(object.get()); } @Override public AtomicBoolean fromString(String string) { return new AtomicBoolean(BOOLEAN_CONVERTER.fromString(string)); } }
4,488
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/CharSequenceStringConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 CharSequence} and {@link String}. */ @SdkInternalApi @ThreadSafe @Immutable public class CharSequenceStringConverter implements StringConverter<CharSequence> { private CharSequenceStringConverter() { } public static CharSequenceStringConverter create() { return new CharSequenceStringConverter(); } @Override public EnhancedType<CharSequence> type() { return EnhancedType.of(CharSequence.class); } @Override public CharSequence fromString(String string) { return string; } }
4,489
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/OffsetDateTimeStringConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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.OffsetDateTime; 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 OffsetDateTime} and {@link String}. */ @SdkInternalApi @ThreadSafe @Immutable public class OffsetDateTimeStringConverter implements StringConverter<OffsetDateTime> { private OffsetDateTimeStringConverter() { } public static OffsetDateTimeStringConverter create() { return new OffsetDateTimeStringConverter(); } @Override public EnhancedType<OffsetDateTime> type() { return EnhancedType.of(OffsetDateTime.class); } @Override public OffsetDateTime fromString(String string) { return OffsetDateTime.parse(string); } }
4,490
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/StringStringConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 String} and {@link String}. */ @SdkInternalApi @ThreadSafe @Immutable public class StringStringConverter implements StringConverter<String> { private StringStringConverter() { } public static StringStringConverter create() { return new StringStringConverter(); } @Override public EnhancedType<String> type() { return EnhancedType.of(String.class); } @Override public String toString(String object) { return object; } @Override public String fromString(String string) { return string; } }
4,491
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/DoubleStringConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 Double} and {@link String}. */ @SdkInternalApi @ThreadSafe @Immutable public class DoubleStringConverter implements StringConverter<Double>, PrimitiveConverter<Double> { private DoubleStringConverter() { } public static DoubleStringConverter create() { return new DoubleStringConverter(); } @Override public EnhancedType<Double> type() { return EnhancedType.of(Double.class); } @Override public EnhancedType<Double> primitiveType() { return EnhancedType.of(double.class); } @Override public Double fromString(String string) { return Double.valueOf(string); } }
4,492
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/SdkBytesStringConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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.core.SdkBytes; 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 SdkBytes} and {@link String}. */ @SdkInternalApi @ThreadSafe @Immutable public class SdkBytesStringConverter implements StringConverter<SdkBytes> { private SdkBytesStringConverter() { } public static SdkBytesStringConverter create() { return new SdkBytesStringConverter(); } @Override public EnhancedType<SdkBytes> type() { return EnhancedType.of(SdkBytes.class); } @Override public String toString(SdkBytes object) { return BinaryUtils.toBase64(object.asByteArray()); } @Override public SdkBytes fromString(String string) { return SdkBytes.fromByteArray(BinaryUtils.fromBase64(string)); } }
4,493
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/OptionalIntStringConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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.OptionalInt; 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 OptionalInt} and {@link String}. */ @SdkInternalApi @ThreadSafe @Immutable public class OptionalIntStringConverter implements StringConverter<OptionalInt> { private static IntegerStringConverter INTEGER_CONVERTER = IntegerStringConverter.create(); private OptionalIntStringConverter() { } public static OptionalIntStringConverter create() { return new OptionalIntStringConverter(); } @Override public EnhancedType<OptionalInt> type() { return EnhancedType.of(OptionalInt.class); } @Override public String toString(OptionalInt object) { if (!object.isPresent()) { return null; } return INTEGER_CONVERTER.toString(object.getAsInt()); } @Override public OptionalInt fromString(String string) { if (string == null) { return OptionalInt.empty(); } return OptionalInt.of(INTEGER_CONVERTER.fromString(string)); } }
4,494
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/YearStringConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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.Year; 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 Year} and {@link String}. */ @SdkInternalApi @ThreadSafe @Immutable public class YearStringConverter implements StringConverter<Year> { private YearStringConverter() { } public static YearStringConverter create() { return new YearStringConverter(); } @Override public EnhancedType<Year> type() { return EnhancedType.of(Year.class); } @Override public Year fromString(String string) { return Year.parse(string); } }
4,495
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/LocaleStringConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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.Locale; 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 Locale} and {@link String}. */ @SdkInternalApi @ThreadSafe @Immutable public class LocaleStringConverter implements StringConverter<Locale> { private LocaleStringConverter() { } public static LocaleStringConverter create() { return new LocaleStringConverter(); } @Override public EnhancedType<Locale> type() { return EnhancedType.of(Locale.class); } @Override public Locale fromString(String string) { return Locale.forLanguageTag(string); } @Override public String toString(Locale locale) { return locale.toLanguageTag(); } }
4,496
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/ByteStringConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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 using {@link Byte#toString()} and {@link Byte#valueOf(String)}. */ @SdkInternalApi @ThreadSafe @Immutable public class ByteStringConverter implements StringConverter<Byte>, PrimitiveConverter<Byte> { private ByteStringConverter() { } public static ByteStringConverter create() { return new ByteStringConverter(); } @Override public EnhancedType<Byte> type() { return EnhancedType.of(Byte.class); } @Override public EnhancedType<Byte> primitiveType() { return EnhancedType.of(byte.class); } @Override public Byte fromString(String string) { return Byte.valueOf(string); } }
4,497
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/DurationStringConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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.Duration; 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 Duration} and {@link String}. */ @SdkInternalApi @ThreadSafe @Immutable public class DurationStringConverter implements StringConverter<Duration> { private DurationStringConverter() { } public static DurationStringConverter create() { return new DurationStringConverter(); } @Override public EnhancedType<Duration> type() { return EnhancedType.of(Duration.class); } @Override public Duration fromString(String string) { return Duration.parse(string); } }
4,498
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/UuidStringConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 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.UUID; 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 UUID} and {@link String}. */ @SdkInternalApi @ThreadSafe @Immutable public class UuidStringConverter implements StringConverter<UUID> { private UuidStringConverter() { } public static UuidStringConverter create() { return new UuidStringConverter(); } @Override public EnhancedType<UUID> type() { return EnhancedType.of(UUID.class); } @Override public UUID fromString(String string) { return UUID.fromString(string); } }
4,499