index int64 0 0 | repo_id stringlengths 26 205 | file_path stringlengths 51 246 | content stringlengths 8 433k | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/Key.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb;
import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.nullAttributeValue;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import software.amazon.awssdk.annotations.NotThreadSafe;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.utils.Validate;
/**
* An object that represents a key that can be used to either identify a specific record or form part of a query
* conditional. Keys are literal and hence not typed, and can be re-used in commands for different modelled types if
* the literal values are to be the same.
* <p>
* A key will always have a single partition key value associated with it, and optionally will have a sort key value.
* The names of the keys themselves are not part of this object.
*/
@SdkPublicApi
@ThreadSafe
public final class Key {
private final AttributeValue partitionValue;
private final AttributeValue sortValue;
private Key(Builder builder) {
Validate.isTrue(builder.partitionValue != null && !builder.partitionValue.equals(nullAttributeValue()),
"partitionValue should not be null");
this.partitionValue = builder.partitionValue;
this.sortValue = builder.sortValue;
}
/**
* Returns a new builder that can be used to construct an instance of this class.
* @return A newly initialized {@link Builder} object.
*/
public static Builder builder() {
return new Builder();
}
/**
* Return a map of the key elements that can be passed directly to DynamoDb.
* @param tableSchema A tableschema to determine the key attribute names from.
* @param index The name of the index to use when determining the key attribute names.
* @return A map of attribute names to {@link AttributeValue}.
*/
public Map<String, AttributeValue> keyMap(TableSchema<?> tableSchema, String index) {
Map<String, AttributeValue> keyMap = new HashMap<>();
keyMap.put(tableSchema.tableMetadata().indexPartitionKey(index), partitionValue);
if (sortValue != null) {
keyMap.put(tableSchema.tableMetadata().indexSortKey(index).orElseThrow(
() -> new IllegalArgumentException("A sort key value was supplied for an index that does not support "
+ "one. Index: " + index)), sortValue);
}
return Collections.unmodifiableMap(keyMap);
}
/**
* Get the literal value of the partition key stored in this object.
* @return An {@link AttributeValue} representing the literal value of the partition key.
*/
public AttributeValue partitionKeyValue() {
return partitionValue;
}
/**
* Get the literal value of the sort key stored in this object if available.
* @return An optional {@link AttributeValue} representing the literal value of the sort key, or empty if there
* is no sort key value in this Key.
*/
public Optional<AttributeValue> sortKeyValue() {
return Optional.ofNullable(sortValue);
}
/**
* Return a map of the key elements that form the primary key of a table that can be passed directly to DynamoDb.
* @param tableSchema A tableschema to determine the key attribute names from.
* @return A map of attribute names to {@link AttributeValue}.
*/
public Map<String, AttributeValue> primaryKeyMap(TableSchema<?> tableSchema) {
return keyMap(tableSchema, TableMetadata.primaryIndexName());
}
/**
* Converts an existing key into a builder object that can be used to modify its values and then create a new key.
* @return A {@link Builder} initialized with the values of this key.
*/
public Builder toBuilder() {
return new Builder().partitionValue(this.partitionValue).sortValue(this.sortValue);
}
/**
* Builder for {@link Key}
*/
@NotThreadSafe
public static final class Builder {
private AttributeValue partitionValue;
private AttributeValue sortValue;
private Builder() {
}
/**
* Value to be used for the partition key
* @param partitionValue partition key value
*/
public Builder partitionValue(AttributeValue partitionValue) {
this.partitionValue = partitionValue;
return this;
}
/**
* String value to be used for the partition key. The string will be converted into an AttributeValue of type S.
* @param partitionValue partition key value
*/
public Builder partitionValue(String partitionValue) {
this.partitionValue = AttributeValues.stringValue(partitionValue);
return this;
}
/**
* Numeric value to be used for the partition key. The number will be converted into an AttributeValue of type N.
* @param partitionValue partition key value
*/
public Builder partitionValue(Number partitionValue) {
this.partitionValue = AttributeValues.numberValue(partitionValue);
return this;
}
/**
* Binary value to be used for the partition key. The input will be converted into an AttributeValue of type B.
* @param partitionValue the bytes to be used for the binary key value.
*/
public Builder partitionValue(SdkBytes partitionValue) {
this.partitionValue = AttributeValues.binaryValue(partitionValue);
return this;
}
/**
* Value to be used for the sort key
* @param sortValue sort key value
*/
public Builder sortValue(AttributeValue sortValue) {
this.sortValue = sortValue;
return this;
}
/**
* String value to be used for the sort key. The string will be converted into an AttributeValue of type S.
* @param sortValue sort key value
*/
public Builder sortValue(String sortValue) {
this.sortValue = AttributeValues.stringValue(sortValue);
return this;
}
/**
* Numeric value to be used for the sort key. The number will be converted into an AttributeValue of type N.
* @param sortValue sort key value
*/
public Builder sortValue(Number sortValue) {
this.sortValue = AttributeValues.numberValue(sortValue);
return this;
}
/**
* Binary value to be used for the sort key. The input will be converted into an AttributeValue of type B.
* @param sortValue the bytes to be used for the binary key value.
*/
public Builder sortValue(SdkBytes sortValue) {
this.sortValue = AttributeValues.binaryValue(sortValue);
return this;
}
/**
* Construct a {@link Key} from this builder.
*/
public Key build() {
return new Key(this);
}
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Key key = (Key) o;
if (partitionValue != null ? ! partitionValue.equals(key.partitionValue) :
key.partitionValue != null) {
return false;
}
return sortValue != null ? sortValue.equals(key.sortValue) : key.sortValue == null;
}
@Override
public int hashCode() {
int result = partitionValue != null ? partitionValue.hashCode() : 0;
result = 31 * result + (sortValue != null ? sortValue.hashCode() : 0);
return result;
}
}
| 4,100 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/NestedAttributeName.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import software.amazon.awssdk.annotations.NotThreadSafe;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.enhanced.dynamodb.model.QueryEnhancedRequest;
import software.amazon.awssdk.enhanced.dynamodb.model.ScanEnhancedRequest;
import software.amazon.awssdk.utils.Validate;
/**
* A high-level representation of a DynamoDB nested attribute name that can be used in various situations where the API requires
* or accepts a nested attribute name. The nested attributes are represented by a list of strings where each element
* corresponds to a nesting level. A simple (top-level) attribute name can be represented by creating an instance with a
* single string element.
* <p>
* NestedAttributeName is used directly in {@link QueryEnhancedRequest#nestedAttributesToProject()}
* and {@link ScanEnhancedRequest#nestedAttributesToProject()}, and indirectly by
* {@link QueryEnhancedRequest#attributesToProject()} and {@link ScanEnhancedRequest#attributesToProject()}.
* <p>
* Examples of creating NestedAttributeNames:
* <ul>
* <li>Simple attribute {@code Level0} can be created as {@code NestedAttributeName.create("Level0")}</li>
* <li>Nested attribute {@code Level0.Level1} can be created as {@code NestedAttributeName.create("Level0", "Level1")}</li>
* <li>Nested attribute {@code Level0.Level-2} can be created as {@code NestedAttributeName.create("Level0", "Level-2")}</li>
* <li>List item 0 of {@code ListAttribute} can be created as {@code NestedAttributeName.create("ListAttribute[0]")}
* </li>
* </ul>
*/
@SdkPublicApi
@ThreadSafe
public final class NestedAttributeName {
private final List<String> elements;
private NestedAttributeName(List<String> nestedAttributeNames) {
Validate.validState(nestedAttributeNames != null, "nestedAttributeNames must not be null.");
Validate.notEmpty(nestedAttributeNames, "nestedAttributeNames must not be empty");
Validate.noNullElements(nestedAttributeNames, "nestedAttributeNames must not contain null values");
this.elements = Collections.unmodifiableList(nestedAttributeNames);
}
/**
* Creates a NestedAttributeName with a single element, which is effectively just a simple attribute name without nesting.
* <p>
* <b>Example:</b>create("foo") will create NestedAttributeName corresponding to Attribute foo.
*
* @param element Attribute Name. Single String represents just a simple attribute name without nesting.
* @return NestedAttributeName with attribute name as specified element.
*/
public static NestedAttributeName create(String element) {
return new Builder().addElement(element).build();
}
/**
* Creates a NestedAttributeName from a list of elements that compose the full path of the nested attribute.
* <p>
* <b>Example:</b>create("foo", "bar") will create NestedAttributeName which represents foo.bar nested attribute.
*
* @param elements Nested Attribute Names. Each of strings in varargs represent the nested attribute name
* at subsequent levels.
* @return NestedAttributeName with Nested attribute name set as specified in elements var args.
*/
public static NestedAttributeName create(String... elements) {
return new Builder().elements(elements).build();
}
/**
* Creates a NestedAttributeName from a list of elements that compose the full path of the nested attribute.
* <p>
* <b>Example:</b>create(Arrays.asList("foo", "bar")) will create NestedAttributeName
* which represents foo.bar nested attribute.
*
* @param elements List of Nested Attribute Names. Each of strings in List represent the nested attribute name
* at subsequent levels.
* @return NestedAttributeName with Nested attribute name set as specified in elements Collections.
*/
public static NestedAttributeName create(List<String> elements) {
return new Builder().elements(elements).build();
}
/**
* Create a builder that can be used to create a {@link NestedAttributeName}.
*/
public static Builder builder() {
return new Builder();
}
/**
* Gets elements of NestedAttributeName in the form of List. Each element in the list corresponds
* to the subsequent Nested Attribute name.
*
* @return List of nested attributes, each entry in the list represent one level of nesting.
* Example, A Two level Attribute name foo.bar will be represented as ["foo", "bar"]
*/
public List<String> elements() {
return elements;
}
/**
* Returns a builder initialized with all existing values on the request object.
*/
public Builder toBuilder() {
return builder().elements(elements);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
NestedAttributeName that = (NestedAttributeName) o;
return elements != null
? elements.equals(that.elements) : that.elements == null;
}
@Override
public int hashCode() {
return elements != null ? elements.hashCode() : 0;
}
@Override
public String toString() {
return elements == null ? "" : elements.stream().collect(Collectors.joining("."));
}
/**
* A builder for {@link NestedAttributeName}.
*/
@NotThreadSafe
public static class Builder {
private List<String> elements = null;
private Builder() {
}
/**
* Adds a single element of NestedAttributeName.
* Subsequent calls to this method can add attribute Names at subsequent nesting levels.
* <p>
* <b>Example:</b>builder().addElement("foo").addElement("bar") will add elements in NestedAttributeName
* which represent a Nested Attribute Name foo.bar
*
* @param element Attribute Name.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Builder addElement(String element) {
if (elements == null) {
elements = new ArrayList<>();
}
elements.add(element);
return this;
}
/**
* Adds a single element of NestedAttributeName.
* Subsequent calls to this method will append the new elements to the end of the existing chain of elements
* creating new levels of nesting.
* <p>
* <b>Example:</b>builder().addElements("foo","bar") will add elements in NestedAttributeName
* which represent a Nested Attribute Name foo.bar
*
* @param elements Nested Attribute Names. Each of strings in varargs represent the nested attribute name
* at subsequent levels.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Builder addElements(String... elements) {
if (this.elements == null) {
this.elements = new ArrayList<>();
}
this.elements.addAll(Arrays.asList(elements));
return this;
}
/**
* Adds a List of elements to NestedAttributeName.
* Subsequent calls to this method will append the new elements to the end of the existing chain of elements
* creating new levels of nesting.
* <p>
* <b>Example:</b>builder().addElements(Arrays.asList("foo","bar")) will add elements in NestedAttributeName
* to represent a Nested Attribute Name foo.bar
*
* @param elements List of Strings where each string corresponds to subsequent nesting attribute name.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Builder addElements(List<String> elements) {
if (this.elements == null) {
this.elements = new ArrayList<>();
}
this.elements.addAll(elements);
return this;
}
/**
* Set elements of NestedAttributeName with list of Strings. Will overwrite any existing elements stored by this builder.
* <p>
* <b>Example:</b>builder().elements("foo","bar") will set the elements in NestedAttributeName
* to represent a nested attribute name of 'foo.bar'
*
* @param elements a list of strings that correspond to the elements in a nested attribute name.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Builder elements(String... elements) {
this.elements = new ArrayList<>(Arrays.asList(elements));
return this;
}
/**
* Sets the elements that compose a nested attribute name. Will overwrite any existing elements stored by this builder.
* <p>
* <b>Example:</b>builder().elements(Arrays.asList("foo","bar")) will add elements in NestedAttributeName
* which represent a Nested Attribute Name foo.bar
*
* @param elements a list of strings that correspond to the elements in a nested attribute name.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Builder elements(List<String> elements) {
this.elements = new ArrayList<>(elements);
return this;
}
public NestedAttributeName build() {
return new NestedAttributeName(elements);
}
}
}
| 4,101 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/DynamoDbEnhancedAsyncClient.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import software.amazon.awssdk.annotations.NotThreadSafe;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.core.async.SdkPublisher;
import software.amazon.awssdk.enhanced.dynamodb.internal.client.DefaultDynamoDbEnhancedAsyncClient;
import software.amazon.awssdk.enhanced.dynamodb.model.BatchGetItemEnhancedRequest;
import software.amazon.awssdk.enhanced.dynamodb.model.BatchGetResultPage;
import software.amazon.awssdk.enhanced.dynamodb.model.BatchGetResultPagePublisher;
import software.amazon.awssdk.enhanced.dynamodb.model.BatchWriteItemEnhancedRequest;
import software.amazon.awssdk.enhanced.dynamodb.model.BatchWriteResult;
import software.amazon.awssdk.enhanced.dynamodb.model.ConditionCheck;
import software.amazon.awssdk.enhanced.dynamodb.model.DeleteItemEnhancedRequest;
import software.amazon.awssdk.enhanced.dynamodb.model.GetItemEnhancedRequest;
import software.amazon.awssdk.enhanced.dynamodb.model.PutItemEnhancedRequest;
import software.amazon.awssdk.enhanced.dynamodb.model.TransactGetItemsEnhancedRequest;
import software.amazon.awssdk.enhanced.dynamodb.model.TransactWriteItemsEnhancedRequest;
import software.amazon.awssdk.enhanced.dynamodb.model.UpdateItemEnhancedRequest;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
/**
* Asynchronous interface for running commands against a DynamoDb database.
* <p>
* By default, all command methods throw an {@link UnsupportedOperationException} to prevent interface extensions from breaking
* implementing classes.
*/
@SdkPublicApi
@ThreadSafe
public interface DynamoDbEnhancedAsyncClient extends DynamoDbEnhancedResource {
/**
* Returns a mapped table that can be used to execute commands that work with mapped items against that table.
*
* @param tableName The name of the physical table persisted by DynamoDb.
* @param tableSchema A {@link TableSchema} that maps the table to a modelled object.
* @return A {@link DynamoDbAsyncTable} object that can be used to execute table operations against.
* @param <T> THe modelled object type being mapped to this table.
*/
<T> DynamoDbAsyncTable<T> table(String tableName, TableSchema<T> tableSchema);
/**
* Retrieves items from one or more tables by their primary keys, see {@link Key}. BatchGetItem is a composite operation
* where the request contains one batch of {@link GetItemEnhancedRequest} per targeted table.
* The operation makes several calls to the database; each time you iterate over the result to retrieve a page,
* a call is made for the items on that page.
* <p>
* The additional configuration parameters that the enhanced client supports are defined
* in the {@link BatchGetItemEnhancedRequest}.
* <p>
* <b>Partial results</b>. A single call to DynamoDb has restraints on how much data can be retrieved.
* If those limits are exceeded, the call yields a partial result. This may also be the case if
* provisional throughput is exceeded or there is an internal DynamoDb processing failure. The operation automatically
* retries any unprocessed keys returned from DynamoDb in subsequent calls for pages.
* <p>
* This operation calls the low-level {@link DynamoDbAsyncClient#batchGetItemPaginator} operation. Consult the
* BatchGetItem documentation for further details and constraints as well as current limits of data retrieval.
* <p>
* Example:
* <pre>
* {@code
*
* BatchGetResultPagePublisher publisher = enhancedClient.batchGetItem(
* BatchGetItemEnhancedRequest.builder()
* .readBatches(ReadBatch.builder(FirstItem.class)
* .mappedTableResource(firstItemTable)
* .addGetItem(GetItemEnhancedRequest.builder().key(key1).build())
* .addGetItem(GetItemEnhancedRequest.builder().key(key2).build())
* .build(),
* ReadBatch.builder(SecondItem.class)
* .mappedTableResource(secondItemTable)
* .addGetItem(GetItemEnhancedRequest.builder().key(key3).build())
* .build())
* .build());
* }
* </pre>
*
* <p>
* The returned {@link BatchGetResultPagePublisher} can be subscribed to request a stream of {@link BatchGetResultPage}s
* or a stream of flattened results belonging to the supplied table across all pages.
*
* <p>
* 1) Subscribing to {@link BatchGetResultPage}s
* <pre>
* {@code
* publisher.subscribe(page -> {
* page.resultsForTable(firstItemTable).forEach(item -> System.out.println(item));
* page.resultsForTable(secondItemTable).forEach(item -> System.out.println(item));
* });
* }
* </pre>
*
* <p>
* 2) Subscribing to results across all pages
* <pre>
* {@code
* publisher.resultsForTable(firstItemTable).subscribe(item -> System.out.println(item));
* publisher.resultsForTable(secondItemTable).subscribe(item -> System.out.println(item));
* }
* </pre>
* @see #batchGetItem(Consumer)
* @see DynamoDbAsyncClient#batchGetItemPaginator
* @param request A {@link BatchGetItemEnhancedRequest} containing keys grouped by tables.
* @return a publisher {@link SdkPublisher} with paginated results of type {@link BatchGetResultPage}.
*/
default BatchGetResultPagePublisher batchGetItem(BatchGetItemEnhancedRequest request) {
throw new UnsupportedOperationException();
}
/**
* Retrieves items from one or more tables by their primary keys, see {@link Key}. BatchGetItem is a composite operation
* where the request contains one batch of {@link GetItemEnhancedRequest} per targeted table.
* The operation makes several calls to the database; each time you iterate over the result to retrieve a page,
* a call is made for the items on that page.
* <p>
* <b>Note:</b> This is a convenience method that creates an instance of the request builder avoiding the need to create one
* manually via {@link BatchGetItemEnhancedRequest#builder()}.
* <p>
* Example:
* <pre>
* {@code
*
* BatchGetResultPagePublisher batchResults = enhancedClient.batchGetItem(r -> r.addReadBatches(
* ReadBatch.builder(FirstItem.class)
* .mappedTableResource(firstItemTable)
* .addGetItem(i -> i.key(key1))
* .addGetItem(i -> i.key(key2))
* .build(),
* ReadBatch.builder(SecondItem.class)
* .mappedTableResource(secondItemTable)
* .addGetItem(i -> i.key(key3))
* .build()));
* }
* </pre>
*
* @see #batchGetItem(BatchGetItemEnhancedRequest)
* @see DynamoDbAsyncClient#batchGetItem
* @param requestConsumer a {@link Consumer} of {@link BatchGetItemEnhancedRequest.Builder} containing keys grouped by tables.
* @return a publisher {@link SdkPublisher} with paginated results of type {@link BatchGetResultPage}.
*/
default BatchGetResultPagePublisher batchGetItem(Consumer<BatchGetItemEnhancedRequest.Builder> requestConsumer) {
throw new UnsupportedOperationException();
}
/**
* Puts and/or deletes multiple items in one or more tables. BatchWriteItem is a composite operation where the request
* contains one batch of (a mix of) {@link PutItemEnhancedRequest} and {@link DeleteItemEnhancedRequest} per targeted table.
* <p>
* The additional configuration parameters that the enhanced client supports are defined
* in the {@link BatchWriteItemEnhancedRequest}.
* <p>
* <b>Note: </b> BatchWriteItem cannot update items. Instead, use the individual updateItem operation
* {@link DynamoDbAsyncTable#updateItem(UpdateItemEnhancedRequest)}.
* <p>
* <b>Partial updates</b><br>Each delete or put call is atomic, but the operation as a whole is not.
* If individual operations fail due to exceeded provisional throughput internal DynamoDb processing failures,
* the failed requests can be retrieved through the result, see {@link BatchWriteResult}.
* <p>
* There are some conditions that cause the whole batch operation to fail. These include non-existing tables, erroneously
* defined primary key attributes, attempting to put and delete the same item as well as referring more than once to the same
* hash and range (sort) key.
* <p>
* This operation calls the low-level DynamoDB API BatchWriteItem operation. Consult the BatchWriteItem documentation for
* further details and constraints, current limits of data to write and/or delete, how to handle partial updates and retries
* and under which conditions the operation will fail.
* <p>
* Example:
* <pre>
* {@code
*
* BatchWriteResult batchResult = enhancedClient.batchWriteItem(
* BatchWriteItemEnhancedRequest.builder()
* .writeBatches(WriteBatch.builder(FirstItem.class)
* .mappedTableResource(firstItemTable)
* .addPutItem(PutItemEnhancedRequest.builder().item(item1).build())
* .addDeleteItem(DeleteItemEnhancedRequest.builder()
* .key(key2)
* .build())
* .build(),
* WriteBatch.builder(SecondItem.class)
* .mappedTableResource(secondItemTable)
* .addPutItem(PutItemEnhancedRequest.builder().item(item3).build())
* .build())
* .build()).join();
* }
* </pre>
*
* @param request A {@link BatchWriteItemEnhancedRequest} containing keys and items grouped by tables.
* @return a {@link CompletableFuture} of {@link BatchWriteResult}, containing any unprocessed requests.
*/
default CompletableFuture<BatchWriteResult> batchWriteItem(BatchWriteItemEnhancedRequest request) {
throw new UnsupportedOperationException();
}
/**
* Puts and/or deletes multiple items in one or more tables. BatchWriteItem is a composite operation where the request
* contains one batch of (a mix of) {@link PutItemEnhancedRequest} and {@link DeleteItemEnhancedRequest} per targeted table.
* <p>
* The additional configuration parameters that the enhanced client supports are defined
* in the {@link BatchWriteItemEnhancedRequest}.
* <p>
* <b>Note: </b> BatchWriteItem cannot update items. Instead, use the individual updateItem operation
* {@link DynamoDbAsyncTable#updateItem}}.
* <p>
* <b>Partial updates</b><br>Each delete or put call is atomic, but the operation as a whole is not.
* If individual operations fail due to exceeded provisional throughput internal DynamoDb processing failures,
* the failed requests can be retrieved through the result, see {@link BatchWriteResult}.
* <p>
* There are some conditions that cause the whole batch operation to fail. These include non-existing tables, erroneously
* defined primary key attributes, attempting to put and delete the same item as well as referring more than once to the same
* hash and range (sort) key.
* <p>
* This operation calls the low-level DynamoDB API BatchWriteItem operation. Consult the BatchWriteItem documentation for
* further details and constraints, current limits of data to write and/or delete, how to handle partial updates and retries
* and under which conditions the operation will fail.
* <p>
* <b>Note:</b> This is a convenience method that creates an instance of the request builder avoiding the need to create one
* manually via {@link BatchWriteItemEnhancedRequest#builder()}.
* <p>
* Example:
* <pre>
* {@code
*
* BatchWriteResult batchResult = enhancedClient.batchWriteItem(r -> r.writeBatches(
* WriteBatch.builder(FirstItem.class)
* .mappedTableResource(firstItemTable)
* .addPutItem(i -> i.item(item1))
* .addDeleteItem(i -> i.key(key2))
* .build(),
* WriteBatch.builder(SecondItem.class)
* .mappedTableResource(secondItemTable)
* .addPutItem(i -> i.item(item3))
* .build())).join();
* }
* </pre>
*
* @param requestConsumer a {@link Consumer} of {@link BatchWriteItemEnhancedRequest} containing keys and items grouped by
* tables.
* @return a {@link CompletableFuture} of {@link BatchWriteResult}, containing any unprocessed requests.
*/
default CompletableFuture<BatchWriteResult> batchWriteItem(Consumer<BatchWriteItemEnhancedRequest.Builder> requestConsumer) {
throw new UnsupportedOperationException();
}
/**
* Retrieves multiple items from one or more tables in a single atomic transaction. TransactGetItem is a composite operation
* where the request contains a set of get requests, each containing a table reference and a
* {@link GetItemEnhancedRequest}.
* <p>
* The additional configuration parameters that the enhanced client supports are defined
* in the {@link TransactGetItemsEnhancedRequest}.
* <p>
* DynamoDb will reject a call to TransactGetItems if the call exceeds limits such as provisioned throughput or allowed size
* of items, if the request contains errors or if there are conflicting operations accessing the same item, for instance
* updating and reading at the same time.
* <p>
* This operation calls the low-level DynamoDB API TransactGetItems operation. Consult the TransactGetItems documentation for
* further details and constraints.
* <p>
* Examples:
* <pre>
* {@code
*
* List<TransactGetResultPage> results = enhancedClient.transactGetItems(
* TransactGetItemsEnhancedRequest.builder()
* .addGetItem(firstItemTable, GetItemEnhancedRequest.builder().key(key1).build())
* .addGetItem(firstItemTable, GetItemEnhancedRequest.builder().key(key2).build())
* .addGetItem(firstItemTable, GetItemEnhancedRequest.builder().key(key3).build())
* .addGetItem(secondItemTable, GetItemEnhancedRequest.builder().key(key4).build())
* .build()).join();
* }
* </pre>
*
* @param request A {@link TransactGetItemsEnhancedRequest} containing keys with table references.
* @return a {@link CompletableFuture} containing a list of {@link Document} with the results.
*/
default CompletableFuture<List<Document>> transactGetItems(TransactGetItemsEnhancedRequest request) {
throw new UnsupportedOperationException();
}
/**
* Retrieves multiple items from one or more tables in a single atomic transaction. TransactGetItem is a composite operation
* where the request contains a set of get requests, each containing a table reference and a
* {@link GetItemEnhancedRequest}.
* <p>
* The additional configuration parameters that the enhanced client supports are defined
* in the {@link TransactGetItemsEnhancedRequest}.
* <p>
* DynamoDb will reject a call to TransactGetItems if the call exceeds limits such as provisioned throughput or allowed size
* of items, if the request contains errors or if there are conflicting operations accessing the same item, for instance
* updating and reading at the same time.
* <p>
* This operation calls the low-level DynamoDB API TransactGetItems operation. Consult the TransactGetItems documentation for
* further details and constraints.
* <p>
* <b>Note:</b> This is a convenience method that creates an instance of the request builder avoiding the need to create one
* manually via {@link TransactGetItemsEnhancedRequest#builder()}.
* <p>
* Examples:
* <pre>
* {@code
*
* List<TransactGetResultPage> results = = enhancedClient.transactGetItems(
* r -> r.addGetItem(firstItemTable, i -> i.key(k -> k.partitionValue(0)))
* .addGetItem(firstItemTable, i -> i.key(k -> k.partitionValue(1)))
* .addGetItem(firstItemTable, i -> i.key(k -> k.partitionValue(2)))
* .addGetItem(secondItemTable, i -> i.key(k -> k.partitionValue(0)))).join();
* }
* </pre>
*
* @param requestConsumer a {@link Consumer} of {@link TransactGetItemsEnhancedRequest} containing keys with table references.
* @return a {@link CompletableFuture} containing a list of {@link Document} with the results.
*/
default CompletableFuture<List<Document>> transactGetItems(
Consumer<TransactGetItemsEnhancedRequest.Builder> requestConsumer) {
throw new UnsupportedOperationException();
}
/**
* Writes and/or modifies multiple items from one or more tables in a single atomic transaction. TransactGetItem is a
* composite operation where the request contains a set of action requests, each containing a table reference and
* one of the following requests:
* <ul>
* <li>Condition check of item - {@link ConditionCheck}</li>
* <li>Delete item - {@link DeleteItemEnhancedRequest}</li>
* <li>Put item - {@link PutItemEnhancedRequest}</li>
* <li>Update item - {@link UpdateItemEnhancedRequest}</li>
* </ul>
* <p>
* The additional configuration parameters that the enhanced client supports are defined
* in the {@link TransactWriteItemsEnhancedRequest}.
* <p>
* DynamoDb will reject a call to TransactWriteItems if the call exceeds limits such as provisioned throughput or allowed size
* of items, if the request contains errors or if there are conflicting operations accessing the same item. If the request
* contains condition checks that aren't met, this will also cause rejection.
* <p>
* This operation calls the low-level DynamoDB API TransactWriteItems operation. Consult the TransactWriteItems documentation
* for further details and constraints, current limits of data to write and/or delete and under which conditions the operation
* will fail.
* <p>
* Example:
* <pre>
* {@code
*
* enhancedClient.transactWriteItems(
* TransactWriteItemsEnhancedRequest.builder()
* .addPutItem(firstItemTable, PutItemEnhancedRequest.builder().item(item1).build())
* .addDeleteItem(firstItemTable, DeleteItemEnhancedRequest.builder().key(key2).build())
* .addConditionCheck(firstItemTable,
* ConditionCheck.builder()
* .key(key3)
* .conditionExpression(conditionExpression)
* .build())
* .addUpdateItem(secondItemTable,
* UpdateItemEnhancedRequest.builder().item(item4).build())
* .build()).join();
* }
* </pre>
*
* @param request A {@link BatchWriteItemEnhancedRequest} containing keys grouped by tables.
* @return a {@link CompletableFuture} of {@link Void}.
*/
default CompletableFuture<Void> transactWriteItems(TransactWriteItemsEnhancedRequest request) {
throw new UnsupportedOperationException();
}
/**
* Writes and/or modifies multiple items from one or more tables in a single atomic transaction. TransactGetItem is a
* composite operation where the request contains a set of action requests, each containing a table reference and
* one of the following requests:
* <ul>
* <li>Condition check of item - {@link ConditionCheck}</li>
* <li>Delete item - {@link DeleteItemEnhancedRequest}</li>
* <li>Put item - {@link PutItemEnhancedRequest}</li>
* <li>Update item - {@link UpdateItemEnhancedRequest}</li>
* </ul>
* <p>
* The additional configuration parameters that the enhanced client supports are defined
* in the {@link TransactWriteItemsEnhancedRequest}.
* <p>
* DynamoDb will reject a call to TransactWriteItems if the call exceeds limits such as provisioned throughput or allowed size
* of items, if the request contains errors or if there are conflicting operations accessing the same item. If the request
* contains condition checks that aren't met, this will also cause rejection.
* <p>
* This operation calls the low-level DynamoDB API TransactWriteItems operation. Consult the TransactWriteItems documentation
* for further details and constraints, current limits of data to write and/or delete and under which conditions the operation
* will fail.
* <p>
* <b>Note:</b> This is a convenience method that creates an instance of the request builder avoiding the need to create one
* manually via {@link TransactWriteItemsEnhancedRequest#builder()}.
* <p>
* Example:
* <pre>
* {@code
*
* enhancedClient.transactWriteItems(r -> r.addPutItem(firstItemTable, i -> i.item(item1))
* .addDeleteItem(firstItemTable, i -> i.key(k -> k.partitionValue(2)))
* .addConditionCheck(firstItemTable, i -> i.key(key3)
* .conditionExpression(conditionExpression))
* .addUpdateItem(secondItemTable, i -> i.item(item4))).join();
* }
* </pre>
*
* @param requestConsumer a {@link Consumer} of {@link TransactWriteItemsEnhancedRequest} containing keys and items grouped by
* tables.
* @return a {@link CompletableFuture} of {@link Void}.
*/
default CompletableFuture<Void> transactWriteItems(Consumer<TransactWriteItemsEnhancedRequest.Builder> requestConsumer) {
throw new UnsupportedOperationException();
}
/**
* Creates a default builder for {@link DynamoDbEnhancedAsyncClient}.
*/
static DynamoDbEnhancedAsyncClient.Builder builder() {
return DefaultDynamoDbEnhancedAsyncClient.builder();
}
/**
* Creates a {@link DynamoDbEnhancedClient} with a default {@link DynamoDbAsyncClient}
*/
static DynamoDbEnhancedAsyncClient create() {
return builder().build();
}
/**
* The builder definition for a {@link DynamoDbEnhancedAsyncClient}.
*/
@NotThreadSafe
interface Builder extends DynamoDbEnhancedResource.Builder {
/**
* The regular low-level SDK client to use with the enhanced client.
* @param dynamoDbClient an initialized {@link DynamoDbAsyncClient}
*/
Builder dynamoDbClient(DynamoDbAsyncClient dynamoDbClient);
@Override
Builder extensions(DynamoDbEnhancedClientExtension... dynamoDbEnhancedClientExtensions);
@Override
Builder extensions(List<DynamoDbEnhancedClientExtension> dynamoDbEnhancedClientExtensions);
/**
* Builds an enhanced client based on the settings supplied to this builder
* @return An initialized {@link DynamoDbEnhancedAsyncClient}
*/
DynamoDbEnhancedAsyncClient build();
}
}
| 4,102 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/AttributeConverter.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb;
import java.time.Instant;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.InstantAsStringAttributeConverter;
import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.StringAttributeConverter;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
/**
* Converts between a specific Java type and an {@link AttributeValue}.
*
* <p>
* Examples:
* <ul>
* <li>The {@link StringAttributeConverter} converts a {@link String} into a DynamoDB string
* ({@link software.amazon.awssdk.services.dynamodb.model.AttributeValue#s()}).</li>
* <li>The {@link InstantAsStringAttributeConverter} converts an {@link Instant} into a DynamoDB string
* ({@link software.amazon.awssdk.services.dynamodb.model.AttributeValue#s()}).</li>
* </ul>
*/
@SdkPublicApi
@ThreadSafe
public interface AttributeConverter<T> {
/**
* Convert the provided Java object into an {@link AttributeValue}. This will raise a {@link RuntimeException} if the
* conversion fails, or the input is null.
*
* <p>
* Example:
* <pre>
* {@code
* InstantAsStringAttributeConverter converter = InstantAsStringAttributeConverter.create();
* assertEquals(converter.transformFrom(Instant.EPOCH),
* EnhancedAttributeValue.fromString("1970-01-01T00:00:00Z").toAttributeValue());
* }
* </pre>
*/
AttributeValue transformFrom(T input);
/**
* Convert the provided {@link AttributeValue} into a Java object. This will raise a {@link RuntimeException} if the
* conversion fails, or the input is null.
*
* <p>
* <pre>
* Example:
* {@code
* InstantAsStringAttributeConverter converter = InstantAsStringAttributeConverter.create();
* assertEquals(converter.transformTo(EnhancedAttributeValue.fromString("1970-01-01T00:00:00Z").toAttributeValue()),
* Instant.EPOCH);
* }
* </pre>
*/
T transformTo(AttributeValue input);
/**
* The type supported by this converter.
*/
EnhancedType<T> type();
/**
* The {@link AttributeValueType} that a converter stores and reads values
* from DynamoDB via the {@link AttributeValue} class.
*/
AttributeValueType attributeValueType();
}
| 4,103 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/AttributeValueType.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType;
@SdkPublicApi
@ThreadSafe
public enum AttributeValueType {
B(ScalarAttributeType.B), // binary
BOOL, // boolean
BS, // binary set
L, // list
M, // documentMap
N(ScalarAttributeType.N), // number
NS, // number set
S(ScalarAttributeType.S), // string
SS, // string set
NULL; // null
private final ScalarAttributeType scalarAttributeType;
AttributeValueType() {
this.scalarAttributeType = null;
}
AttributeValueType(ScalarAttributeType scalarAttributeType) {
this.scalarAttributeType = scalarAttributeType;
}
public ScalarAttributeType scalarAttributeType() {
return scalarAttributeType;
}
}
| 4,104 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/update/AddAction.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.update;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* A representation of a single {@link UpdateExpression} ADD action.
* <p>
* At a minimum, this action must contain a path string referencing the attribute that should be acted upon and a value string
* referencing the value to be added to the attribute. The value should be substituted with tokens using the
* ':value_token' syntax and values associated with the token must be explicitly added to the expressionValues map.
* Consult the DynamoDB UpdateExpression documentation for details on this action.
* <p>
* Optionally, attribute names can be substituted with tokens using the '#name_token' syntax. If tokens are used in the
* expression then the names associated with those tokens must be explicitly added to the expressionNames map
* that is also stored on this object.
* <p>
* Example:-
* <pre>
* {@code
* AddUpdateAction addAction = AddUpdateAction.builder()
* .path("#a")
* .value(":b")
* .putExpressionName("#a", "attributeA")
* .putExpressionValue(":b", myAttributeValue)
* .build();
* }
* </pre>
*/
@SdkPublicApi
public final class AddAction implements UpdateAction, ToCopyableBuilder<AddAction.Builder, AddAction> {
private final String path;
private final String value;
private final Map<String, String> expressionNames;
private final Map<String, AttributeValue> expressionValues;
private AddAction(Builder builder) {
this.path = Validate.paramNotNull(builder.path, "path");
this.value = Validate.paramNotNull(builder.value, "value");
this.expressionValues = wrapSecure(Validate.paramNotNull(builder.expressionValues, "expressionValues"));
this.expressionNames = wrapSecure(builder.expressionNames != null ? builder.expressionNames : new HashMap<>());
}
private static <T, U> Map<T, U> wrapSecure(Map<T, U> map) {
return Collections.unmodifiableMap(new HashMap<>(map));
}
/**
* Constructs a new builder for {@link AddAction}.
*
* @return a new builder.
*/
public static Builder builder() {
return new Builder();
}
@Override
public Builder toBuilder() {
return builder().path(path)
.value(value)
.expressionNames(expressionNames)
.expressionValues(expressionValues);
}
public String path() {
return path;
}
public String value() {
return value;
}
public Map<String, String> expressionNames() {
return expressionNames;
}
public Map<String, AttributeValue> expressionValues() {
return expressionValues;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AddAction that = (AddAction) o;
if (path != null ? ! path.equals(that.path) : that.path != null) {
return false;
}
if (value != null ? ! value.equals(that.value) : that.value != null) {
return false;
}
if (expressionValues != null ? ! expressionValues.equals(that.expressionValues) :
that.expressionValues != null) {
return false;
}
return expressionNames != null ? expressionNames.equals(that.expressionNames) : that.expressionNames == null;
}
@Override
public int hashCode() {
int result = path != null ? path.hashCode() : 0;
result = 31 * result + (value != null ? value.hashCode() : 0);
result = 31 * result + (expressionValues != null ? expressionValues.hashCode() : 0);
result = 31 * result + (expressionNames != null ? expressionNames.hashCode() : 0);
return result;
}
/**
* A builder for {@link AddAction}
*/
public static final class Builder implements CopyableBuilder<Builder, AddAction> {
private String path;
private String value;
private Map<String, String> expressionNames;
private Map<String, AttributeValue> expressionValues;
private Builder() {
}
/**
* A string expression representing the attribute to be acted upon
*/
public Builder path(String path) {
this.path = path;
return this;
}
/**
* A string expression representing the value used in the action. The value must be represented as an
* expression attribute value token.
*/
public Builder value(String value) {
this.value = value;
return this;
}
/**
* Sets the 'expression values' token map that maps from value references (expression attribute values) to
* DynamoDB AttributeValues, overriding any existing values.
* The value reference should always start with ':' (colon).
*
* @see #putExpressionValue(String, AttributeValue)
*/
public Builder expressionValues(Map<String, AttributeValue> expressionValues) {
this.expressionValues = expressionValues == null ? null : new HashMap<>(expressionValues);
return this;
}
/**
* Adds a single element to the 'expression values' token map.
*
* @see #expressionValues(Map)
*/
public Builder putExpressionValue(String key, AttributeValue value) {
if (this.expressionValues == null) {
this.expressionValues = new HashMap<>();
}
this.expressionValues.put(key, value);
return this;
}
/**
* Sets the optional 'expression names' token map, overriding any existing values. Use if the attribute
* references in the path expression are token ('expression attribute names') prepended with the
* '#' (pound) sign. It should map from token name to real attribute name.
*
* @see #putExpressionName(String, String)
*/
public Builder expressionNames(Map<String, String> expressionNames) {
this.expressionNames = expressionNames == null ? null : new HashMap<>(expressionNames);
return this;
}
/**
* Adds a single element to the optional 'expression names' token map.
*
* @see #expressionNames(Map)
*/
public Builder putExpressionName(String key, String value) {
if (this.expressionNames == null) {
this.expressionNames = new HashMap<>();
}
this.expressionNames.put(key, value);
return this;
}
/**
* Builds an {@link AddAction} based on the values stored in this builder.
*/
public AddAction build() {
return new AddAction(this);
}
}
}
| 4,105 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/update/SetAction.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.update;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* A representation of a single {@link UpdateExpression} SET action.
* <p>
* At a minimum, this action must contain a path string referencing the attribute that should be acted upon and a value string
* referencing the value to set or change.
* <p>
* The value string may contain just an operand, or operands combined with '+' or '-'. Furthermore, an operand can be a
* reference to a specific value or a function. All references to values should be substituted with tokens using the
* ':value_token' syntax and values associated with the token must be explicitly added to the expressionValues map.
* Consult the DynamoDB UpdateExpression documentation for details on this action.
* <p>
* Optionally, attribute names can be substituted with tokens using the '#name_token' syntax. If tokens are used in the
* expression then the names associated with those tokens must be explicitly added to the expressionNames map
* that is also stored on this object.
* <p>
* Example:-
* <pre>
* {@code
* //Simply setting the value of 'attributeA' to 'myAttributeValue'
* SetUpdateAction setAction1 = SetUpdateAction.builder()
* .path("#a")
* .value(":b")
* .putExpressionName("#a", "attributeA")
* .putExpressionValue(":b", myAttributeValue)
* .build();
*
* //Increasing the value of 'attributeA' with 'delta' if it already exists, otherwise sets it to 'startValue'
* SetUpdateAction setAction2 = SetUpdateAction.builder()
* .path("#a")
* .value("if_not_exists(#a, :startValue) + :delta")
* .putExpressionName("#a", "attributeA")
* .putExpressionValue(":delta", myNumericAttributeValue1)
* .putExpressionValue(":startValue", myNumericAttributeValue2)
* .build();
* }
* </pre>
*/
@SdkPublicApi
public final class SetAction implements UpdateAction, ToCopyableBuilder<SetAction.Builder, SetAction> {
private final String path;
private final String value;
private final Map<String, String> expressionNames;
private final Map<String, AttributeValue> expressionValues;
private SetAction(Builder builder) {
this.path = Validate.paramNotNull(builder.path, "path");
this.value = Validate.paramNotNull(builder.value, "value");
this.expressionValues = wrapSecure(Validate.paramNotNull(builder.expressionValues, "expressionValues"));
this.expressionNames = wrapSecure(builder.expressionNames != null ? builder.expressionNames : new HashMap<>());
}
private static <T, U> Map<T, U> wrapSecure(Map<T, U> map) {
return Collections.unmodifiableMap(new HashMap<>(map));
}
/**
* Constructs a new builder for {@link SetAction}.
*
* @return a new builder.
*/
public static Builder builder() {
return new Builder();
}
@Override
public Builder toBuilder() {
return builder().path(path)
.value(value)
.expressionNames(expressionNames)
.expressionValues(expressionValues);
}
public String path() {
return path;
}
public String value() {
return value;
}
public Map<String, String> expressionNames() {
return expressionNames;
}
public Map<String, AttributeValue> expressionValues() {
return expressionValues;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SetAction that = (SetAction) o;
if (path != null ? ! path.equals(that.path) : that.path != null) {
return false;
}
if (value != null ? ! value.equals(that.value) : that.value != null) {
return false;
}
if (expressionValues != null ? ! expressionValues.equals(that.expressionValues) :
that.expressionValues != null) {
return false;
}
return expressionNames != null ? expressionNames.equals(that.expressionNames) : that.expressionNames == null;
}
@Override
public int hashCode() {
int result = path != null ? path.hashCode() : 0;
result = 31 * result + (value != null ? value.hashCode() : 0);
result = 31 * result + (expressionValues != null ? expressionValues.hashCode() : 0);
result = 31 * result + (expressionNames != null ? expressionNames.hashCode() : 0);
return result;
}
/**
* A builder for {@link SetAction}
*/
public static final class Builder implements CopyableBuilder<Builder, SetAction> {
private String path;
private String value;
private Map<String, String> expressionNames;
private Map<String, AttributeValue> expressionValues;
private Builder() {
}
/**
* A string expression representing the attribute to be acted upon
*/
public Builder path(String path) {
this.path = path;
return this;
}
/**
* A string expression representing the value used in the action. The value must be represented as an
* expression attribute value token.
*/
public Builder value(String value) {
this.value = value;
return this;
}
/**
* Sets the 'expression values' token map that maps from value references (expression attribute values) to
* DynamoDB AttributeValues, overriding any existing values.
* The value reference should always start with ':' (colon).
*
* @see #putExpressionValue(String, AttributeValue)
*/
public Builder expressionValues(Map<String, AttributeValue> expressionValues) {
this.expressionValues = expressionValues == null ? null : new HashMap<>(expressionValues);
return this;
}
/**
* Adds a single element to the 'expression values' token map.
*
* @see #expressionValues(Map)
*/
public Builder putExpressionValue(String key, AttributeValue value) {
if (this.expressionValues == null) {
this.expressionValues = new HashMap<>();
}
this.expressionValues.put(key, value);
return this;
}
/**
* Sets the optional 'expression names' token map, overriding any existing values. Use if the attribute
* references in the path expression are token ('expression attribute names') prepended with the
* '#' (pound) sign. It should map from token name to real attribute name.
*
* @see #putExpressionName(String, String)
*/
public Builder expressionNames(Map<String, String> expressionNames) {
this.expressionNames = expressionNames == null ? null : new HashMap<>(expressionNames);
return this;
}
/**
* Adds a single element to the optional 'expression names' token map.
*
* @see #expressionNames(Map)
*/
public Builder putExpressionName(String key, String value) {
if (this.expressionNames == null) {
this.expressionNames = new HashMap<>();
}
this.expressionNames.put(key, value);
return this;
}
/**
* Builds an {@link SetAction} based on the values stored in this builder.
*/
public SetAction build() {
return new SetAction(this);
}
}
}
| 4,106 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/update/RemoveAction.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.update;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* A representation of a single {@link UpdateExpression} REMOVE action.
* <p>
* At a minimum, this action must contain a path string referencing the attribute that should be removed when applying this
* action. Consult the DynamoDB UpdateExpression documentation for details on this action.
* <p>
* Optionally, attribute names can be substituted with tokens using the '#name_token' syntax. If tokens are used in the
* expression then the names associated with those tokens must be explicitly added to the expressionNames map
* that is also stored on this object.
* <p>
* Example:-
* <pre>
* {@code
* RemoveUpdateAction removeAction = RemoveUpdateAction.builder()
* .path("#a")
* .putExpressionName("#a", "attributeA")
* .build();
* }
* </pre>
*/
@SdkPublicApi
public final class RemoveAction implements UpdateAction, ToCopyableBuilder<RemoveAction.Builder, RemoveAction> {
private final String path;
private final Map<String, String> expressionNames;
private RemoveAction(Builder builder) {
this.path = Validate.paramNotNull(builder.path, "path");
this.expressionNames = wrapSecure(builder.expressionNames != null ? builder.expressionNames : new HashMap<>());
}
private static <T, U> Map<T, U> wrapSecure(Map<T, U> map) {
return Collections.unmodifiableMap(new HashMap<>(map));
}
/**
* Constructs a new builder for {@link RemoveAction}.
*
* @return a new builder.
*/
public static Builder builder() {
return new Builder();
}
@Override
public Builder toBuilder() {
return builder().path(path)
.expressionNames(expressionNames);
}
public String path() {
return path;
}
public Map<String, String> expressionNames() {
return expressionNames;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
RemoveAction that = (RemoveAction) o;
if (path != null ? ! path.equals(that.path) : that.path != null) {
return false;
}
return expressionNames != null ? expressionNames.equals(that.expressionNames) : that.expressionNames == null;
}
@Override
public int hashCode() {
int result = path != null ? path.hashCode() : 0;
result = 31 * result + (expressionNames != null ? expressionNames.hashCode() : 0);
return result;
}
/**
* A builder for {@link RemoveAction}
*/
public static final class Builder implements CopyableBuilder<Builder, RemoveAction> {
private String path;
private Map<String, String> expressionNames;
private Builder() {
}
/**
* A string expression representing the attribute to remove
*/
public Builder path(String path) {
this.path = path;
return this;
}
/**
* Sets the optional 'expression names' token map, overriding any existing values. Use if the attribute
* references in the path expression are token ('expression attribute names') prepended with the
* '#' (pound) sign. It should map from token name to real attribute name.
*
* @see #putExpressionName(String, String)
*/
public Builder expressionNames(Map<String, String> expressionNames) {
this.expressionNames = expressionNames == null ? null : new HashMap<>(expressionNames);
return this;
}
/**
* Adds a single element to the optional 'expression names' token map.
*
* @see #expressionNames(Map)
*/
public Builder putExpressionName(String key, String value) {
if (this.expressionNames == null) {
this.expressionNames = new HashMap<>();
}
this.expressionNames.put(key, value);
return this;
}
/**
* Builds an {@link RemoveAction} based on the values stored in this builder.
*/
public RemoveAction build() {
return new RemoveAction(this);
}
}
}
| 4,107 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/update/DeleteAction.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.update;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* A representation of a single {@link UpdateExpression} DELETE action.
* <p>
* At a minimum, this action must contain a path string referencing the attribute that should be acted upon and a value string
* referencing the value (subset) to be removed from the attribute. The value should be substituted with tokens using the
* ':value_token' syntax and values associated with the token must be explicitly added to the expressionValues map.
* Consult the DynamoDB UpdateExpression documentation for details on this action.
* <p>
* Optionally, attribute names can be substituted with tokens using the '#name_token' syntax. If tokens are used in the
* expression then the names associated with those tokens must be explicitly added to the expressionNames map
* that is also stored on this object.
* <p>
* Example:-
* <pre>
* {@code
* DeleteUpdateAction deleteAction = DeleteUpdateAction.builder()
* .path("#a")
* .value(":b")
* .putExpressionName("#a", "attributeA")
* .putExpressionValue(":b", myAttributeValue)
* .build();
* }
* </pre>
*/
@SdkPublicApi
public final class DeleteAction implements UpdateAction, ToCopyableBuilder<DeleteAction.Builder, DeleteAction> {
private final String path;
private final String value;
private final Map<String, String> expressionNames;
private final Map<String, AttributeValue> expressionValues;
private DeleteAction(Builder builder) {
this.path = Validate.paramNotNull(builder.path, "path");
this.value = Validate.paramNotNull(builder.value, "value");
this.expressionValues = wrapSecure(Validate.paramNotNull(builder.expressionValues, "expressionValues"));
this.expressionNames = wrapSecure(builder.expressionNames != null ? builder.expressionNames : new HashMap<>());
}
private static <T, U> Map<T, U> wrapSecure(Map<T, U> map) {
return Collections.unmodifiableMap(new HashMap<>(map));
}
/**
* Constructs a new builder for {@link DeleteAction}.
*
* @return a new builder.
*/
public static Builder builder() {
return new Builder();
}
@Override
public Builder toBuilder() {
return builder().path(path)
.value(value)
.expressionNames(expressionNames)
.expressionValues(expressionValues);
}
public String path() {
return path;
}
public String value() {
return value;
}
public Map<String, String> expressionNames() {
return expressionNames;
}
public Map<String, AttributeValue> expressionValues() {
return expressionValues;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DeleteAction that = (DeleteAction) o;
if (path != null ? ! path.equals(that.path) : that.path != null) {
return false;
}
if (value != null ? ! value.equals(that.value) : that.value != null) {
return false;
}
if (expressionValues != null ? ! expressionValues.equals(that.expressionValues) :
that.expressionValues != null) {
return false;
}
return expressionNames != null ? expressionNames.equals(that.expressionNames) : that.expressionNames == null;
}
@Override
public int hashCode() {
int result = path != null ? path.hashCode() : 0;
result = 31 * result + (value != null ? value.hashCode() : 0);
result = 31 * result + (expressionValues != null ? expressionValues.hashCode() : 0);
result = 31 * result + (expressionNames != null ? expressionNames.hashCode() : 0);
return result;
}
/**
* A builder for {@link DeleteAction}
*/
public static final class Builder implements CopyableBuilder<Builder, DeleteAction> {
private String path;
private String value;
private Map<String, String> expressionNames;
private Map<String, AttributeValue> expressionValues;
private Builder() {
}
/**
* A string expression representing the attribute to be acted upon
*/
public Builder path(String path) {
this.path = path;
return this;
}
/**
* A string expression representing the value used in the action. The value must be represented as an
* expression attribute value token.
*/
public Builder value(String value) {
this.value = value;
return this;
}
/**
* Sets the 'expression values' token map that maps from value references (expression attribute values) to
* DynamoDB AttributeValues, overriding any existing values.
* The value reference should always start with ':' (colon).
*
* @see #putExpressionValue(String, AttributeValue)
*/
public Builder expressionValues(Map<String, AttributeValue> expressionValues) {
this.expressionValues = expressionValues == null ? null : new HashMap<>(expressionValues);
return this;
}
/**
* Adds a single element to the 'expression values' token map.
*
* @see #expressionValues(Map)
*/
public Builder putExpressionValue(String key, AttributeValue value) {
if (this.expressionValues == null) {
this.expressionValues = new HashMap<>();
}
this.expressionValues.put(key, value);
return this;
}
/**
* Sets the optional 'expression names' token map, overriding any existing values. Use if the attribute
* references in the path expression are token ('expression attribute names') prepended with the
* '#' (pound) sign. It should map from token name to real attribute name.
*
* @see #putExpressionName(String, String)
*/
public Builder expressionNames(Map<String, String> expressionNames) {
this.expressionNames = expressionNames == null ? null : new HashMap<>(expressionNames);
return this;
}
/**
* Adds a single element to the optional 'expression names' token map.
*
* @see #expressionNames(Map)
*/
public Builder putExpressionName(String key, String value) {
if (this.expressionNames == null) {
this.expressionNames = new HashMap<>();
}
this.expressionNames.put(key, value);
return this;
}
/**
* Builds an {@link DeleteAction} based on the values stored in this builder.
*/
public DeleteAction build() {
return new DeleteAction(this);
}
}
}
| 4,108 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/update/UpdateExpression.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.update;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import software.amazon.awssdk.annotations.SdkPublicApi;
/**
* Contains sets of {@link UpdateAction} that represent the four DynamoDB update actions: SET, ADD, REMOVE and DELETE.
* <p>
* Use this class to build an immutable UpdateExpression with one or more UpdateAction. An UpdateExpression may be merged
* with another. When two UpdateExpression are merged, the actions of each group of UpdateAction, should they exist, are
* combined; all SET actions from each expression are concatenated, all REMOVE actions etc.
* <p>
* DynamoDb Enhanced will convert the UpdateExpression to a format readable by DynamoDb,
* <p>
* Example:-
* <pre>
* {@code
* RemoveUpdateAction removeAction = ...
* SetUpdateAction setAction = ...
* UpdateExpression.builder()
* .addAction(removeAction)
* .addAction(setAction)
* .build();
* }
* </pre>
*
* See respective subtype of {@link UpdateAction}, for example {@link SetAction}, for details on creating that action.
*/
@SdkPublicApi
public final class UpdateExpression {
private final List<RemoveAction> removeActions;
private final List<SetAction> setActions;
private final List<DeleteAction> deleteActions;
private final List<AddAction> addActions;
private UpdateExpression(Builder builder) {
this.removeActions = builder.removeActions;
this.setActions = builder.setActions;
this.deleteActions = builder.deleteActions;
this.addActions = builder.addActions;
}
/**
* Constructs a new builder for {@link UpdateExpression}.
*
* @return a new builder.
*/
public static Builder builder() {
return new Builder();
}
public List<RemoveAction> removeActions() {
return Collections.unmodifiableList(new ArrayList<>(removeActions));
}
public List<SetAction> setActions() {
return Collections.unmodifiableList(new ArrayList<>(setActions));
}
public List<DeleteAction> deleteActions() {
return Collections.unmodifiableList(new ArrayList<>(deleteActions));
}
public List<AddAction> addActions() {
return Collections.unmodifiableList(new ArrayList<>(addActions));
}
/**
* Merges two UpdateExpression, returning a new
*/
public static UpdateExpression mergeExpressions(UpdateExpression expression1, UpdateExpression expression2) {
if (expression1 == null) {
return expression2;
}
if (expression2 == null) {
return expression1;
}
Builder builder = builder();
builder.removeActions = Stream.concat(expression1.removeActions.stream(),
expression2.removeActions.stream()).collect(Collectors.toList());
builder.setActions = Stream.concat(expression1.setActions.stream(),
expression2.setActions.stream()).collect(Collectors.toList());
builder.deleteActions = Stream.concat(expression1.deleteActions.stream(),
expression2.deleteActions.stream()).collect(Collectors.toList());
builder.addActions = Stream.concat(expression1.addActions.stream(),
expression2.addActions.stream()).collect(Collectors.toList());
return builder.build();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
UpdateExpression that = (UpdateExpression) o;
if (removeActions != null ? ! removeActions.equals(that.removeActions) : that.removeActions != null) {
return false;
}
if (setActions != null ? ! setActions.equals(that.setActions) : that.setActions != null) {
return false;
}
if (deleteActions != null ? ! deleteActions.equals(that.deleteActions) : that.deleteActions != null) {
return false;
}
return addActions != null ? addActions.equals(that.addActions) : that.addActions == null;
}
@Override
public int hashCode() {
int result = removeActions != null ? removeActions.hashCode() : 0;
result = 31 * result + (setActions != null ? setActions.hashCode() : 0);
result = 31 * result + (deleteActions != null ? deleteActions.hashCode() : 0);
result = 31 * result + (addActions != null ? addActions.hashCode() : 0);
return result;
}
/**
* A builder for {@link UpdateExpression}
*/
public static final class Builder {
private List<RemoveAction> removeActions = new ArrayList<>();
private List<SetAction> setActions = new ArrayList<>();
private List<DeleteAction> deleteActions = new ArrayList<>();
private List<AddAction> addActions = new ArrayList<>();
private Builder() {
}
/**
* Add an action of type {@link RemoveAction}
*/
public Builder addAction(RemoveAction action) {
removeActions.add(action);
return this;
}
/**
* Add an action of type {@link SetAction}
*/
public Builder addAction(SetAction action) {
setActions.add(action);
return this;
}
/**
* Add an action of type {@link DeleteAction}
*/
public Builder addAction(DeleteAction action) {
deleteActions.add(action);
return this;
}
/**
* Add an action of type {@link AddAction}
*/
public Builder addAction(AddAction action) {
addActions.add(action);
return this;
}
/**
* Adds a list of {@link UpdateAction} of any subtype to the builder, overwriting any previous values.
*/
public Builder actions(List<? extends UpdateAction> actions) {
replaceActions(actions);
return this;
}
/**
* Adds a list of {@link UpdateAction} of any subtype to the builder, overwriting any previous values.
*/
public Builder actions(UpdateAction... actions) {
actions(Arrays.asList(actions));
return this;
}
/**
* Builds an {@link UpdateExpression} based on the values stored in this builder.
*/
public UpdateExpression build() {
return new UpdateExpression(this);
}
private void replaceActions(List<? extends UpdateAction> actions) {
if (actions != null) {
this.removeActions = new ArrayList<>();
this.setActions = new ArrayList<>();
this.deleteActions = new ArrayList<>();
this.addActions = new ArrayList<>();
actions.forEach(this::assignAction);
}
}
private void assignAction(UpdateAction action) {
if (action instanceof RemoveAction) {
addAction((RemoveAction) action);
} else if (action instanceof SetAction) {
addAction((SetAction) action);
} else if (action instanceof DeleteAction) {
addAction((DeleteAction) action);
} else if (action instanceof AddAction) {
addAction((AddAction) action);
} else {
throw new IllegalArgumentException(
String.format("Do not recognize UpdateAction: %s", action.getClass()));
}
}
}
}
| 4,109 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/update/UpdateAction.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.update;
import software.amazon.awssdk.annotations.SdkPublicApi;
/**
* An update action represents a part of an {@link UpdateExpression}
*/
@SdkPublicApi
public interface UpdateAction {
}
| 4,110 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper/StaticImmutableTableSchema.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.mapper;
import static java.util.Collections.unmodifiableMap;
import static software.amazon.awssdk.enhanced.dynamodb.internal.EnhancedClientUtils.isNullAttributeValue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Stream;
import software.amazon.awssdk.annotations.NotThreadSafe;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.enhanced.dynamodb.AttributeConverter;
import software.amazon.awssdk.enhanced.dynamodb.AttributeConverterProvider;
import software.amazon.awssdk.enhanced.dynamodb.DefaultAttributeConverterProvider;
import software.amazon.awssdk.enhanced.dynamodb.EnhancedType;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.internal.converter.ConverterProviderResolver;
import software.amazon.awssdk.enhanced.dynamodb.internal.mapper.ResolvedImmutableAttribute;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
/**
* Implementation of {@link TableSchema} that builds a schema for immutable data objects based on directly declared
* attributes. Just like {@link StaticTableSchema} which is the equivalent implementation for mutable objects, this is
* the most direct, and thus fastest, implementation of {@link TableSchema}.
* <p>
* Example using a fictional 'Customer' immutable data item class that has an inner builder class named 'Builder':-
* {@code
* static final TableSchema<Customer> CUSTOMER_TABLE_SCHEMA =
* StaticImmutableTableSchema.builder(Customer.class, Customer.Builder.class)
* .newItemBuilder(Customer::builder, Customer.Builder::build)
* .addAttribute(String.class, a -> a.name("account_id")
* .getter(Customer::accountId)
* .setter(Customer.Builder::accountId)
* .tags(primaryPartitionKey()))
* .addAttribute(Integer.class, a -> a.name("sub_id")
* .getter(Customer::subId)
* .setter(Customer.Builder::subId)
* .tags(primarySortKey()))
* .addAttribute(String.class, a -> a.name("name")
* .getter(Customer::name)
* .setter(Customer.Builder::name)
* .tags(secondaryPartitionKey("customers_by_name")))
* .addAttribute(Instant.class, a -> a.name("created_date")
* .getter(Customer::createdDate)
* .setter(Customer.Builder::createdDate)
* .tags(secondarySortKey("customers_by_date"),
* secondarySortKey("customers_by_name")))
* .build();
* }
*/
@SdkPublicApi
@ThreadSafe
public final class StaticImmutableTableSchema<T, B> implements TableSchema<T> {
private final List<ResolvedImmutableAttribute<T, B>> attributeMappers;
private final Supplier<B> newBuilderSupplier;
private final Function<B, T> buildItemFunction;
private final Map<String, ResolvedImmutableAttribute<T, B>> indexedMappers;
private final StaticTableMetadata tableMetadata;
private final EnhancedType<T> itemType;
private final AttributeConverterProvider attributeConverterProvider;
private final Map<String, FlattenedMapper<T, B, ?>> indexedFlattenedMappers;
private final List<String> attributeNames;
private static class FlattenedMapper<T, B, T1> {
private final Function<T, T1> otherItemGetter;
private final BiConsumer<B, T1> otherItemSetter;
private final TableSchema<T1> otherItemTableSchema;
private FlattenedMapper(Function<T, T1> otherItemGetter,
BiConsumer<B, T1> otherItemSetter,
TableSchema<T1> otherItemTableSchema) {
this.otherItemGetter = otherItemGetter;
this.otherItemSetter = otherItemSetter;
this.otherItemTableSchema = otherItemTableSchema;
}
public TableSchema<T1> getOtherItemTableSchema() {
return otherItemTableSchema;
}
private B mapToItem(B thisBuilder,
Supplier<B> thisBuilderConstructor,
Map<String, AttributeValue> attributeValues) {
T1 otherItem = this.otherItemTableSchema.mapToItem(attributeValues);
if (otherItem != null) {
if (thisBuilder == null) {
thisBuilder = thisBuilderConstructor.get();
}
this.otherItemSetter.accept(thisBuilder, otherItem);
}
return thisBuilder;
}
private Map<String, AttributeValue> itemToMap(T item, boolean ignoreNulls) {
T1 otherItem = this.otherItemGetter.apply(item);
if (otherItem == null) {
return Collections.emptyMap();
}
return this.otherItemTableSchema.itemToMap(otherItem, ignoreNulls);
}
private AttributeValue attributeValue(T item, String attributeName) {
T1 otherItem = this.otherItemGetter.apply(item);
if (otherItem == null) {
return null;
}
AttributeValue attributeValue = this.otherItemTableSchema.attributeValue(otherItem, attributeName);
return isNullAttributeValue(attributeValue) ? null : attributeValue;
}
}
private StaticImmutableTableSchema(Builder<T, B> builder) {
StaticTableMetadata.Builder tableMetadataBuilder = StaticTableMetadata.builder();
this.attributeConverterProvider =
ConverterProviderResolver.resolveProviders(builder.attributeConverterProviders);
// Resolve declared attributes and find converters for them
Stream<ResolvedImmutableAttribute<T, B>> attributesStream = builder.attributes == null ?
Stream.empty() : builder.attributes.stream().map(a -> a.resolve(this.attributeConverterProvider));
// Merge resolved declared attributes
List<ResolvedImmutableAttribute<T, B>> mutableAttributeMappers = new ArrayList<>();
Map<String, ResolvedImmutableAttribute<T, B>> mutableIndexedMappers = new HashMap<>();
Set<String> mutableAttributeNames = new LinkedHashSet<>();
Stream.concat(attributesStream, builder.additionalAttributes.stream()).forEach(
resolvedAttribute -> {
String attributeName = resolvedAttribute.attributeName();
if (mutableAttributeNames.contains(attributeName)) {
throw new IllegalArgumentException(
"Attempt to add an attribute to a mapper that already has one with the same name. " +
"[Attribute name: " + attributeName + "]");
}
mutableAttributeNames.add(attributeName);
mutableAttributeMappers.add(resolvedAttribute);
mutableIndexedMappers.put(attributeName, resolvedAttribute);
// Merge in metadata associated with attribute
tableMetadataBuilder.mergeWith(resolvedAttribute.tableMetadata());
}
);
Map<String, FlattenedMapper<T, B, ?>> mutableFlattenedMappers = new HashMap<>();
builder.flattenedMappers.forEach(
flattenedMapper -> {
flattenedMapper.otherItemTableSchema.attributeNames().forEach(
attributeName -> {
if (mutableAttributeNames.contains(attributeName)) {
throw new IllegalArgumentException(
"Attempt to add an attribute to a mapper that already has one with the same name. " +
"[Attribute name: " + attributeName + "]");
}
mutableAttributeNames.add(attributeName);
mutableFlattenedMappers.put(attributeName, flattenedMapper);
}
);
tableMetadataBuilder.mergeWith(flattenedMapper.getOtherItemTableSchema().tableMetadata());
}
);
// Apply table-tags to table metadata
if (builder.tags != null) {
builder.tags.forEach(staticTableTag -> staticTableTag.modifyMetadata().accept(tableMetadataBuilder));
}
this.attributeMappers = Collections.unmodifiableList(mutableAttributeMappers);
this.indexedMappers = Collections.unmodifiableMap(mutableIndexedMappers);
this.attributeNames = Collections.unmodifiableList(new ArrayList<>(mutableAttributeNames));
this.indexedFlattenedMappers = Collections.unmodifiableMap(mutableFlattenedMappers);
this.newBuilderSupplier = builder.newBuilderSupplier;
this.buildItemFunction = builder.buildItemFunction;
this.tableMetadata = tableMetadataBuilder.build();
this.itemType = builder.itemType;
}
/**
* Creates a builder for a {@link StaticImmutableTableSchema} typed to specific immutable data item class.
* @param itemClass The immutable data item class object that the {@link StaticImmutableTableSchema} is to map to.
* @param builderClass The builder class object that can be used to construct instances of the immutable data item.
* @return A newly initialized builder
*/
public static <T, B> Builder<T, B> builder(Class<T> itemClass, Class<B> builderClass) {
return new Builder<>(EnhancedType.of(itemClass), EnhancedType.of(builderClass));
}
/**
* Creates a builder for a {@link StaticImmutableTableSchema} typed to specific immutable data item class.
* @param itemType The {@link EnhancedType} of the immutable data item class object that the
* {@link StaticImmutableTableSchema} is to map to.
* @param builderType The builder {@link EnhancedType} that can be used to construct instances of the immutable data item.
* @return A newly initialized builder
*/
public static <T, B> Builder<T, B> builder(EnhancedType<T> itemType, EnhancedType<B> builderType) {
return new Builder<>(itemType, builderType);
}
/**
* Builder for a {@link StaticImmutableTableSchema}
* @param <T> The immutable data item class object that the {@link StaticImmutableTableSchema} is to map to.
* @param <B> The builder class object that can be used to construct instances of the immutable data item.
*/
@NotThreadSafe
public static final class Builder<T, B> {
private final EnhancedType<T> itemType;
private final EnhancedType<B> builderType;
private final List<ResolvedImmutableAttribute<T, B>> additionalAttributes = new ArrayList<>();
private final List<FlattenedMapper<T, B, ?>> flattenedMappers = new ArrayList<>();
private List<ImmutableAttribute<T, B, ?>> attributes;
private Supplier<B> newBuilderSupplier;
private Function<B, T> buildItemFunction;
private List<StaticTableTag> tags;
private List<AttributeConverterProvider> attributeConverterProviders =
Collections.singletonList(ConverterProviderResolver.defaultConverterProvider());
private Builder(EnhancedType<T> itemType, EnhancedType<B> builderType) {
this.itemType = itemType;
this.builderType = builderType;
}
/**
* Methods used to construct a new instance of the immutable data object.
* @param newBuilderMethod A method to create a new builder for the immutable data object.
* @param buildMethod A method on the builder to build a new instance of the immutable data object.
*/
public Builder<T, B> newItemBuilder(Supplier<B> newBuilderMethod, Function<B, T> buildMethod) {
this.newBuilderSupplier = newBuilderMethod;
this.buildItemFunction = buildMethod;
return this;
}
/**
* A list of attributes that can be mapped between the data item object and the database record that are to
* be associated with the schema. Will overwrite any existing attributes.
*/
@SafeVarargs
public final Builder<T, B> attributes(ImmutableAttribute<T, B, ?>... immutableAttributes) {
this.attributes = Arrays.asList(immutableAttributes);
return this;
}
/**
* A list of attributes that can be mapped between the data item object and the database record that are to
* be associated with the schema. Will overwrite any existing attributes.
*/
public Builder<T, B> attributes(Collection<ImmutableAttribute<T, B, ?>> immutableAttributes) {
this.attributes = new ArrayList<>(immutableAttributes);
return this;
}
/**
* Adds a single attribute to the table schema that can be mapped between the data item object and the database
* record.
*/
public <R> Builder<T, B> addAttribute(EnhancedType<R> attributeType,
Consumer<ImmutableAttribute.Builder<T, B, R>> immutableAttribute) {
ImmutableAttribute.Builder<T, B, R> builder =
ImmutableAttribute.builder(itemType, builderType, attributeType);
immutableAttribute.accept(builder);
return addAttribute(builder.build());
}
/**
* Adds a single attribute to the table schema that can be mapped between the data item object and the database
* record.
*/
public <R> Builder<T, B> addAttribute(Class<R> attributeClass,
Consumer<ImmutableAttribute.Builder<T, B, R>> immutableAttribute) {
return addAttribute(EnhancedType.of(attributeClass), immutableAttribute);
}
/**
* Adds a single attribute to the table schema that can be mapped between the data item object and the database
* record.
*/
public Builder<T, B> addAttribute(ImmutableAttribute<T, B, ?> immutableAttribute) {
if (this.attributes == null) {
this.attributes = new ArrayList<>();
}
this.attributes.add(immutableAttribute);
return this;
}
/**
* Associate one or more {@link StaticTableTag} with this schema. See documentation on the tags themselves to
* understand what each one does. This method will overwrite any existing table tags.
*/
public Builder<T, B> tags(StaticTableTag... staticTableTags) {
this.tags = Arrays.asList(staticTableTags);
return this;
}
/**
* Associate one or more {@link StaticTableTag} with this schema. See documentation on the tags themselves to
* understand what each one does. This method will overwrite any existing table tags.
*/
public Builder<T, B> tags(Collection<StaticTableTag> staticTableTags) {
this.tags = new ArrayList<>(staticTableTags);
return this;
}
/**
* Associates a {@link StaticTableTag} with this schema. See documentation on the tags themselves to understand
* what each one does. This method will add the tag to the list of existing table tags.
*/
public Builder<T, B> addTag(StaticTableTag staticTableTag) {
if (this.tags == null) {
this.tags = new ArrayList<>();
}
this.tags.add(staticTableTag);
return this;
}
/**
* Flattens all the attributes defined in another {@link TableSchema} into the database record this schema
* maps to. Functions to get and set an object that the flattened schema maps to is required.
*/
public <T1> Builder<T, B> flatten(TableSchema<T1> otherTableSchema,
Function<T, T1> otherItemGetter,
BiConsumer<B, T1> otherItemSetter) {
if (otherTableSchema.isAbstract()) {
throw new IllegalArgumentException("Cannot flatten an abstract TableSchema. You must supply a concrete " +
"TableSchema that is able to create items");
}
FlattenedMapper<T, B, T1> flattenedMapper =
new FlattenedMapper<>(otherItemGetter, otherItemSetter, otherTableSchema);
this.flattenedMappers.add(flattenedMapper);
return this;
}
/**
* Extends the {@link StaticImmutableTableSchema} of a super-class, effectively rolling all the attributes modelled by
* the super-class into the {@link StaticImmutableTableSchema} of the sub-class. The extended immutable table schema
* must be using a builder class that is also a super-class of the builder being used for the current immutable
* table schema.
*/
public Builder<T, B> extend(StaticImmutableTableSchema<? super T, ? super B> superTableSchema) {
Stream<ResolvedImmutableAttribute<T, B>> attributeStream =
upcastingTransformForAttributes(superTableSchema.attributeMappers);
attributeStream.forEach(this.additionalAttributes::add);
return this;
}
/**
* Specifies the {@link AttributeConverterProvider}s to use with the table schema.
* The list of attribute converter providers must provide {@link AttributeConverter}s for all types used
* in the schema. The attribute converter providers will be loaded in the strict order they are supplied here.
* <p>
* Calling this method will override the default attribute converter provider
* {@link DefaultAttributeConverterProvider}, which provides standard converters for most primitive
* and common Java types, so that provider must included in the supplied list if it is to be
* used. Providing an empty list here will cause no providers to get loaded.
* <p>
* Adding one custom attribute converter provider and using the default as fallback:
* {@code
* builder.attributeConverterProviders(customAttributeConverter, AttributeConverterProvider.defaultProvider())
* }
*
* @param attributeConverterProviders a list of attribute converter providers to use with the table schema
*/
public Builder<T, B> attributeConverterProviders(AttributeConverterProvider... attributeConverterProviders) {
this.attributeConverterProviders = Arrays.asList(attributeConverterProviders);
return this;
}
/**
* Specifies the {@link AttributeConverterProvider}s to use with the table schema.
* The list of attribute converter providers must provide {@link AttributeConverter}s for all types used
* in the schema. The attribute converter providers will be loaded in the strict order they are supplied here.
* <p>
* Calling this method will override the default attribute converter provider
* {@link DefaultAttributeConverterProvider}, which provides standard converters
* for most primitive and common Java types, so that provider must included in the supplied list if it is to be
* used. Providing an empty list here will cause no providers to get loaded.
* <p>
* Adding one custom attribute converter provider and using the default as fallback:
* {@code
* List<AttributeConverterProvider> providers = new ArrayList<>(
* customAttributeConverter,
* AttributeConverterProvider.defaultProvider());
* builder.attributeConverterProviders(providers);
* }
*
* @param attributeConverterProviders a list of attribute converter providers to use with the table schema
*/
public Builder<T, B> attributeConverterProviders(List<AttributeConverterProvider> attributeConverterProviders) {
this.attributeConverterProviders = new ArrayList<>(attributeConverterProviders);
return this;
}
/**
* Builds a {@link StaticImmutableTableSchema} based on the values this builder has been configured with
*/
public StaticImmutableTableSchema<T, B> build() {
return new StaticImmutableTableSchema<>(this);
}
private static <T extends T1, T1, B extends B1, B1> Stream<ResolvedImmutableAttribute<T, B>>
upcastingTransformForAttributes(Collection<ResolvedImmutableAttribute<T1, B1>> superAttributes) {
return superAttributes.stream().map(attribute -> attribute.transform(x -> x, x -> x));
}
}
@Override
public StaticTableMetadata tableMetadata() {
return tableMetadata;
}
@Override
public T mapToItem(Map<String, AttributeValue> attributeMap, boolean preserveEmptyObject) {
B builder = null;
// Instantiate the builder right now if preserveEmtpyBean is true, otherwise lazily instantiate the builder once
// we have an attribute to write
if (preserveEmptyObject) {
builder = constructNewBuilder();
}
Map<FlattenedMapper<T, B, ?>, Map<String, AttributeValue>> flattenedAttributeValuesMap = new LinkedHashMap<>();
for (Map.Entry<String, AttributeValue> entry : attributeMap.entrySet()) {
String key = entry.getKey();
AttributeValue value = entry.getValue();
if (!isNullAttributeValue(value)) {
ResolvedImmutableAttribute<T, B> attributeMapper = indexedMappers.get(key);
if (attributeMapper != null) {
if (builder == null) {
builder = constructNewBuilder();
}
attributeMapper.updateItemMethod().accept(builder, value);
} else {
FlattenedMapper<T, B, ?> flattenedMapper = this.indexedFlattenedMappers.get(key);
if (flattenedMapper != null) {
Map<String, AttributeValue> flattenedAttributeValues =
flattenedAttributeValuesMap.get(flattenedMapper);
if (flattenedAttributeValues == null) {
flattenedAttributeValues = new HashMap<>();
}
flattenedAttributeValues.put(key, value);
flattenedAttributeValuesMap.put(flattenedMapper, flattenedAttributeValues);
}
}
}
}
for (Map.Entry<FlattenedMapper<T, B, ?>, Map<String, AttributeValue>> entry :
flattenedAttributeValuesMap.entrySet()) {
builder = entry.getKey().mapToItem(builder, this::constructNewBuilder, entry.getValue());
}
return builder == null ? null : buildItemFunction.apply(builder);
}
@Override
public T mapToItem(Map<String, AttributeValue> attributeMap) {
return mapToItem(attributeMap, false);
}
@Override
public Map<String, AttributeValue> itemToMap(T item, boolean ignoreNulls) {
Map<String, AttributeValue> attributeValueMap = new HashMap<>();
attributeMappers.forEach(attributeMapper -> {
String attributeKey = attributeMapper.attributeName();
AttributeValue attributeValue = attributeMapper.attributeGetterMethod().apply(item);
if (!ignoreNulls || !isNullAttributeValue(attributeValue)) {
attributeValueMap.put(attributeKey, attributeValue);
}
});
indexedFlattenedMappers.forEach((name, flattenedMapper) -> {
attributeValueMap.putAll(flattenedMapper.itemToMap(item, ignoreNulls));
});
return unmodifiableMap(attributeValueMap);
}
@Override
public Map<String, AttributeValue> itemToMap(T item, Collection<String> attributes) {
Map<String, AttributeValue> attributeValueMap = new HashMap<>();
attributes.forEach(key -> {
AttributeValue attributeValue = attributeValue(item, key);
if (attributeValue == null || !isNullAttributeValue(attributeValue)) {
attributeValueMap.put(key, attributeValue);
}
});
return unmodifiableMap(attributeValueMap);
}
@Override
public AttributeValue attributeValue(T item, String key) {
ResolvedImmutableAttribute<T, B> attributeMapper = indexedMappers.get(key);
if (attributeMapper == null) {
FlattenedMapper<T, B, ?> flattenedMapper = indexedFlattenedMappers.get(key);
if (flattenedMapper == null) {
throw new IllegalArgumentException(String.format("TableSchema does not know how to retrieve requested "
+ "attribute '%s' from mapped object.", key));
}
return flattenedMapper.attributeValue(item, key);
}
AttributeValue attributeValue = attributeMapper.attributeGetterMethod().apply(item);
return isNullAttributeValue(attributeValue) ? null : attributeValue;
}
@Override
public EnhancedType<T> itemType() {
return this.itemType;
}
@Override
public List<String> attributeNames() {
return this.attributeNames;
}
@Override
public boolean isAbstract() {
return this.buildItemFunction == null;
}
/**
* The table schema {@link AttributeConverterProvider}.
* @see Builder#attributeConverterProvider
*/
public AttributeConverterProvider attributeConverterProvider() {
return this.attributeConverterProvider;
}
private B constructNewBuilder() {
if (newBuilderSupplier == null) {
throw new UnsupportedOperationException("An abstract TableSchema cannot be used to map a database record "
+ "to a concrete object. Add a 'newItemBuilder' to the "
+ "TableSchema to give it the ability to create mapped objects.");
}
return newBuilderSupplier.get();
}
@Override
public AttributeConverter<T> converterForAttribute(Object key) {
ResolvedImmutableAttribute<T, B> resolvedImmutableAttribute = indexedMappers.get(key);
if (resolvedImmutableAttribute != null) {
return resolvedImmutableAttribute.attributeConverter();
}
// If no resolvedAttribute is found look through flattened attributes
FlattenedMapper<T, B, ?> flattenedMapper = indexedFlattenedMappers.get(key);
if (flattenedMapper != null) {
return (AttributeConverter) flattenedMapper.getOtherItemTableSchema().converterForAttribute(key);
}
return null;
}
}
| 4,111 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper/StaticAttributeTag.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.mapper;
import java.util.function.Consumer;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType;
import software.amazon.awssdk.enhanced.dynamodb.EnhancedType;
/**
* Interface for a tag that can be applied to any {@link StaticAttribute}. When a tagged attribute is added to a
* {@link software.amazon.awssdk.enhanced.dynamodb.TableSchema}, the table metadata stored on the schema will be updated
* by calling the {@link #modifyMetadata(String, AttributeValueType)} method for every tag associated with the
* attribute.
* <p>
* Common implementations of this interface that can be used to declare indices in your schema can be found in
* {@link StaticAttributeTags}.
*/
@SdkPublicApi
@ThreadSafe
public interface StaticAttributeTag {
/**
* A function that modifies an existing {@link StaticTableSchema.Builder} when this tag is applied to a specific
* attribute. This will be used by the {@link StaticTableSchema} to capture all the metadata associated with
* tagged attributes when constructing the table schema.
*
* @param attributeName The name of the attribute this tag has been applied to.
* @param attributeValueType The type of the attribute this tag has been applied to. This can be used for
* validation, for instance if you have an attribute tag that should only be associated
* with a string.
* @return a consumer that modifies an existing {@link StaticTableSchema.Builder}.
*/
Consumer<StaticTableMetadata.Builder> modifyMetadata(String attributeName,
AttributeValueType attributeValueType);
/**
* Function that validates the Converted return type is suitable for the extension.
* @param <R> the class that the value of this attribute converts to.
* @param attributeName The name of the attribute this tag has been applied to.
* @param enhancedType The type of the object to be converted
* @param attributeValueType Attribute Value type of the attribute.
*/
default <R> void validateType(String attributeName, EnhancedType<R> enhancedType,
AttributeValueType attributeValueType) {
}
}
| 4,112 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper/ImmutableTableSchema.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.mapper;
import static software.amazon.awssdk.enhanced.dynamodb.internal.DynamoDbEnhancedLogger.BEAN_LOGGER;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.WeakHashMap;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.enhanced.dynamodb.AttributeConverter;
import software.amazon.awssdk.enhanced.dynamodb.AttributeConverterProvider;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient;
import software.amazon.awssdk.enhanced.dynamodb.EnhancedType;
import software.amazon.awssdk.enhanced.dynamodb.EnhancedTypeDocumentConfiguration;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.internal.AttributeConfiguration;
import software.amazon.awssdk.enhanced.dynamodb.internal.immutable.ImmutableInfo;
import software.amazon.awssdk.enhanced.dynamodb.internal.immutable.ImmutableIntrospector;
import software.amazon.awssdk.enhanced.dynamodb.internal.immutable.ImmutablePropertyDescriptor;
import software.amazon.awssdk.enhanced.dynamodb.internal.mapper.BeanAttributeGetter;
import software.amazon.awssdk.enhanced.dynamodb.internal.mapper.BeanAttributeSetter;
import software.amazon.awssdk.enhanced.dynamodb.internal.mapper.MetaTableSchema;
import software.amazon.awssdk.enhanced.dynamodb.internal.mapper.MetaTableSchemaCache;
import software.amazon.awssdk.enhanced.dynamodb.internal.mapper.ObjectConstructor;
import software.amazon.awssdk.enhanced.dynamodb.internal.mapper.ObjectGetterMethod;
import software.amazon.awssdk.enhanced.dynamodb.internal.mapper.StaticGetterMethod;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.BeanTableSchemaAttributeTag;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbAttribute;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbConvertedBy;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbFlatten;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbIgnoreNulls;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbImmutable;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPreserveEmptyObject;
/**
* Implementation of {@link TableSchema} that builds a table schema based on properties and annotations of an immutable
* class with an associated builder class. Example:
* <pre>
* <code>
* {@literal @}DynamoDbImmutable(builder = Customer.Builder.class)
* public class Customer {
* {@literal @}DynamoDbPartitionKey
* public String accountId() { ... }
*
* {@literal @}DynamoDbSortKey
* public int subId() { ... }
*
* // Defines a GSI (customers_by_name) with a partition key of 'name'
* {@literal @}DynamoDbSecondaryPartitionKey(indexNames = "customers_by_name")
* public String name() { ... }
*
* // Defines an LSI (customers_by_date) with a sort key of 'createdDate' and also declares the
* // same attribute as a sort key for the GSI named 'customers_by_name'
* {@literal @}DynamoDbSecondarySortKey(indexNames = {"customers_by_date", "customers_by_name"})
* public Instant createdDate() { ... }
*
* // Not required to be an inner-class, but builders often are
* public static final class Builder {
* public Builder accountId(String accountId) { ... };
* public Builder subId(int subId) { ... };
* public Builder name(String name) { ... };
* public Builder createdDate(Instant createdDate) { ... };
*
* public Customer build() { ... };
* }
* }
* </pre>
*
* Creating an {@link ImmutableTableSchema} is a moderately expensive operation, and should be performed sparingly. This is
* usually done once at application startup.
*
* If this table schema is not behaving as you expect, enable debug logging for 'software.amazon.awssdk.enhanced.dynamodb.beans'.
*
* @param <T> The type of object that this {@link TableSchema} maps to.
*/
@SdkPublicApi
@ThreadSafe
public final class ImmutableTableSchema<T> extends WrappedTableSchema<T, StaticImmutableTableSchema<T, ?>> {
private static final String ATTRIBUTE_TAG_STATIC_SUPPLIER_NAME = "attributeTagFor";
private static final Map<Class<?>, ImmutableTableSchema<?>> IMMUTABLE_TABLE_SCHEMA_CACHE =
Collections.synchronizedMap(new WeakHashMap<>());
private ImmutableTableSchema(StaticImmutableTableSchema<T, ?> wrappedTableSchema) {
super(wrappedTableSchema);
}
/**
* Scans an immutable class and builds an {@link ImmutableTableSchema} from it that can be used with the
* {@link DynamoDbEnhancedClient}.
*
* Creating an {@link ImmutableTableSchema} is a moderately expensive operation, and should be performed sparingly. This is
* usually done once at application startup.
*
* @param immutableClass The annotated immutable class to build the table schema from.
* @param <T> The immutable class type.
* @return An initialized {@link ImmutableTableSchema}
*/
@SuppressWarnings("unchecked")
public static <T> ImmutableTableSchema<T> create(Class<T> immutableClass) {
return (ImmutableTableSchema<T>) IMMUTABLE_TABLE_SCHEMA_CACHE.computeIfAbsent(
immutableClass, clz -> create(clz, new MetaTableSchemaCache()));
}
private static <T> ImmutableTableSchema<T> create(Class<T> immutableClass,
MetaTableSchemaCache metaTableSchemaCache) {
debugLog(immutableClass, () -> "Creating immutable schema");
// Fetch or create a new reference to this yet-to-be-created TableSchema in the cache
MetaTableSchema<T> metaTableSchema = metaTableSchemaCache.getOrCreate(immutableClass);
ImmutableTableSchema<T> newTableSchema =
new ImmutableTableSchema<>(createStaticImmutableTableSchema(immutableClass, metaTableSchemaCache));
metaTableSchema.initialize(newTableSchema);
return newTableSchema;
}
// Called when creating an immutable TableSchema recursively. Utilizes the MetaTableSchema cache to stop infinite
// recursion
static <T> TableSchema<T> recursiveCreate(Class<T> immutableClass, MetaTableSchemaCache metaTableSchemaCache) {
Optional<MetaTableSchema<T>> metaTableSchema = metaTableSchemaCache.get(immutableClass);
// If we get a cache hit...
if (metaTableSchema.isPresent()) {
// Either: use the cached concrete TableSchema if we have one
if (metaTableSchema.get().isInitialized()) {
return metaTableSchema.get().concreteTableSchema();
}
// Or: return the uninitialized MetaTableSchema as this must be a recursive reference and it will be
// initialized later as the chain completes
return metaTableSchema.get();
}
// Otherwise: cache doesn't know about this class; create a new one from scratch
return create(immutableClass, metaTableSchemaCache);
}
private static <T> StaticImmutableTableSchema<T, ?> createStaticImmutableTableSchema(
Class<T> immutableClass, MetaTableSchemaCache metaTableSchemaCache) {
ImmutableInfo<T> immutableInfo = ImmutableIntrospector.getImmutableInfo(immutableClass);
Class<?> builderClass = immutableInfo.builderClass();
return createStaticImmutableTableSchema(immutableClass, builderClass, immutableInfo, metaTableSchemaCache);
}
private static <T, B> StaticImmutableTableSchema<T, B> createStaticImmutableTableSchema(
Class<T> immutableClass,
Class<B> builderClass,
ImmutableInfo<T> immutableInfo,
MetaTableSchemaCache metaTableSchemaCache) {
Supplier<B> newBuilderSupplier = newObjectSupplier(immutableInfo, builderClass);
Function<B, T> buildFunction = ObjectGetterMethod.create(builderClass, immutableInfo.buildMethod());
StaticImmutableTableSchema.Builder<T, B> builder =
StaticImmutableTableSchema.builder(immutableClass, builderClass)
.newItemBuilder(newBuilderSupplier, buildFunction);
builder.attributeConverterProviders(
createConverterProvidersFromAnnotation(immutableClass, immutableClass.getAnnotation(DynamoDbImmutable.class)));
List<ImmutableAttribute<T, B, ?>> attributes = new ArrayList<>();
immutableInfo.propertyDescriptors()
.forEach(propertyDescriptor -> {
DynamoDbFlatten dynamoDbFlatten = getPropertyAnnotation(propertyDescriptor, DynamoDbFlatten.class);
if (dynamoDbFlatten != null) {
builder.flatten(TableSchema.fromClass(propertyDescriptor.getter().getReturnType()),
getterForProperty(propertyDescriptor, immutableClass),
setterForProperty(propertyDescriptor, builderClass));
} else {
AttributeConfiguration beanAttributeConfiguration = resolveAttributeConfiguration(propertyDescriptor);
ImmutableAttribute.Builder<T, B, ?> attributeBuilder =
immutableAttributeBuilder(propertyDescriptor,
immutableClass,
builderClass,
metaTableSchemaCache,
beanAttributeConfiguration);
Optional<AttributeConverter> attributeConverter =
createAttributeConverterFromAnnotation(propertyDescriptor);
attributeConverter.ifPresent(attributeBuilder::attributeConverter);
addTagsToAttribute(attributeBuilder, propertyDescriptor);
attributes.add(attributeBuilder.build());
}
});
builder.attributes(attributes);
return builder.build();
}
private static List<AttributeConverterProvider> createConverterProvidersFromAnnotation(Class<?> immutableClass,
DynamoDbImmutable dynamoDbImmutable) {
Class<? extends AttributeConverterProvider>[] providerClasses = dynamoDbImmutable.converterProviders();
return Arrays.stream(providerClasses)
.peek(c -> debugLog(immutableClass, () -> "Adding Converter: " + c.getTypeName()))
.map(c -> (AttributeConverterProvider) newObjectSupplierForClass(c).get())
.collect(Collectors.toList());
}
private static <T, B> ImmutableAttribute.Builder<T, B, ?> immutableAttributeBuilder(
ImmutablePropertyDescriptor propertyDescriptor,
Class<T> immutableClass, Class<B> builderClass,
MetaTableSchemaCache metaTableSchemaCache,
AttributeConfiguration beanAttributeConfiguration) {
Type propertyType = propertyDescriptor.getter().getGenericReturnType();
EnhancedType<?> propertyTypeToken = convertTypeToEnhancedType(propertyType,
metaTableSchemaCache,
beanAttributeConfiguration);
return ImmutableAttribute.builder(immutableClass, builderClass, propertyTypeToken)
.name(attributeNameForProperty(propertyDescriptor))
.getter(getterForProperty(propertyDescriptor, immutableClass))
.setter(setterForProperty(propertyDescriptor, builderClass));
}
/**
* Converts a {@link Type} to an {@link EnhancedType}. Usually {@link EnhancedType#of} is capable of doing this all
* by itself, but for the ImmutableTableSchema we want to detect if a parameterized class is being passed without a
* converter that is actually another annotated class in which case we want to capture its schema and add it to the
* EnhancedType. Unfortunately this means we have to duplicate some of the recursive Type parsing that
* EnhancedClient otherwise does all by itself.
*/
@SuppressWarnings("unchecked")
private static EnhancedType<?> convertTypeToEnhancedType(Type type, MetaTableSchemaCache metaTableSchemaCache,
AttributeConfiguration attributeConfiguration) {
Class<?> clazz = null;
if (type instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) type;
Type rawType = parameterizedType.getRawType();
if (List.class.equals(rawType)) {
EnhancedType<?> enhancedType = convertTypeToEnhancedType(parameterizedType.getActualTypeArguments()[0],
metaTableSchemaCache, attributeConfiguration);
return EnhancedType.listOf(enhancedType);
}
if (Map.class.equals(rawType)) {
EnhancedType<?> enhancedType = convertTypeToEnhancedType(parameterizedType.getActualTypeArguments()[1],
metaTableSchemaCache, attributeConfiguration);
return EnhancedType.mapOf(EnhancedType.of(parameterizedType.getActualTypeArguments()[0]),
enhancedType);
}
if (rawType instanceof Class) {
clazz = (Class<?>) rawType;
}
} else if (type instanceof Class) {
clazz = (Class<?>) type;
}
if (clazz != null) {
Consumer<EnhancedTypeDocumentConfiguration.Builder> attrConfiguration =
b -> b.preserveEmptyObject(attributeConfiguration.preserveEmptyObject())
.ignoreNulls(attributeConfiguration.ignoreNulls());
if (clazz.getAnnotation(DynamoDbImmutable.class) != null) {
return EnhancedType.documentOf(
(Class<Object>) clazz,
(TableSchema<Object>) ImmutableTableSchema.recursiveCreate(clazz, metaTableSchemaCache),
attrConfiguration);
} else if (clazz.getAnnotation(DynamoDbBean.class) != null) {
return EnhancedType.documentOf(
(Class<Object>) clazz,
(TableSchema<Object>) BeanTableSchema.recursiveCreate(clazz, metaTableSchemaCache),
attrConfiguration);
}
}
return EnhancedType.of(type);
}
private static Optional<AttributeConverter> createAttributeConverterFromAnnotation(
ImmutablePropertyDescriptor propertyDescriptor) {
DynamoDbConvertedBy attributeConverterBean =
getPropertyAnnotation(propertyDescriptor, DynamoDbConvertedBy.class);
Optional<Class<?>> optionalClass = Optional.ofNullable(attributeConverterBean)
.map(DynamoDbConvertedBy::value);
return optionalClass.map(clazz -> (AttributeConverter) newObjectSupplierForClass(clazz).get());
}
/**
* This method scans all the annotations on a property and looks for a meta-annotation of
* {@link BeanTableSchemaAttributeTag}. If the meta-annotation is found, it attempts to create
* an annotation tag based on a standard named static method
* of the class that tag has been annotated with passing in the original property annotation as an argument.
*/
private static void addTagsToAttribute(ImmutableAttribute.Builder<?, ?, ?> attributeBuilder,
ImmutablePropertyDescriptor propertyDescriptor) {
propertyAnnotations(propertyDescriptor).forEach(annotation -> {
BeanTableSchemaAttributeTag beanTableSchemaAttributeTag =
annotation.annotationType().getAnnotation(BeanTableSchemaAttributeTag.class);
if (beanTableSchemaAttributeTag != null) {
Class<?> tagClass = beanTableSchemaAttributeTag.value();
Method tagMethod;
try {
tagMethod = tagClass.getDeclaredMethod(ATTRIBUTE_TAG_STATIC_SUPPLIER_NAME,
annotation.annotationType());
} catch (NoSuchMethodException e) {
throw new RuntimeException(
String.format("Could not find a static method named '%s' on class '%s' that returns " +
"an AttributeTag for annotation '%s'", ATTRIBUTE_TAG_STATIC_SUPPLIER_NAME,
tagClass, annotation.annotationType()), e);
}
if (!Modifier.isStatic(tagMethod.getModifiers())) {
throw new RuntimeException(
String.format("Could not find a static method named '%s' on class '%s' that returns " +
"an AttributeTag for annotation '%s'", ATTRIBUTE_TAG_STATIC_SUPPLIER_NAME,
tagClass, annotation.annotationType()));
}
StaticAttributeTag staticAttributeTag;
try {
staticAttributeTag = (StaticAttributeTag) tagMethod.invoke(null, annotation);
} catch (IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException(
String.format("Could not invoke method to create AttributeTag for annotation '%s' on class " +
"'%s'.", annotation.annotationType(), tagClass), e);
}
attributeBuilder.addTag(staticAttributeTag);
}
});
}
private static <T, R> Supplier<R> newObjectSupplier(ImmutableInfo<T> immutableInfo, Class<R> builderClass) {
if (immutableInfo.staticBuilderMethod().isPresent()) {
return StaticGetterMethod.create(immutableInfo.staticBuilderMethod().get());
}
return newObjectSupplierForClass(builderClass);
}
private static <R> Supplier<R> newObjectSupplierForClass(Class<R> clazz) {
try {
Constructor<R> constructor = clazz.getConstructor();
debugLog(clazz, () -> "Constructor: " + constructor);
return ObjectConstructor.create(clazz, constructor);
} catch (NoSuchMethodException e) {
throw new IllegalArgumentException(
String.format("Builder class '%s' appears to have no default constructor thus cannot be used with " +
"the ImmutableTableSchema", clazz), e);
}
}
private static <T, R> Function<T, R> getterForProperty(ImmutablePropertyDescriptor propertyDescriptor,
Class<T> immutableClass) {
Method readMethod = propertyDescriptor.getter();
debugLog(immutableClass, () -> "Property " + propertyDescriptor.name() + " read method: " + readMethod);
return BeanAttributeGetter.create(immutableClass, readMethod);
}
private static <T, R> BiConsumer<T, R> setterForProperty(ImmutablePropertyDescriptor propertyDescriptor,
Class<T> builderClass) {
Method writeMethod = propertyDescriptor.setter();
debugLog(builderClass, () -> "Property " + propertyDescriptor.name() + " write method: " + writeMethod);
return BeanAttributeSetter.create(builderClass, writeMethod);
}
private static String attributeNameForProperty(ImmutablePropertyDescriptor propertyDescriptor) {
DynamoDbAttribute dynamoDbAttribute = getPropertyAnnotation(propertyDescriptor, DynamoDbAttribute.class);
if (dynamoDbAttribute != null) {
return dynamoDbAttribute.value();
}
return propertyDescriptor.name();
}
private static <R extends Annotation> R getPropertyAnnotation(ImmutablePropertyDescriptor propertyDescriptor,
Class<R> annotationType) {
R getterAnnotation = propertyDescriptor.getter().getAnnotation(annotationType);
R setterAnnotation = propertyDescriptor.setter().getAnnotation(annotationType);
if (getterAnnotation != null) {
return getterAnnotation;
}
return setterAnnotation;
}
private static List<? extends Annotation> propertyAnnotations(ImmutablePropertyDescriptor propertyDescriptor) {
return Stream.concat(Arrays.stream(propertyDescriptor.getter().getAnnotations()),
Arrays.stream(propertyDescriptor.setter().getAnnotations()))
.collect(Collectors.toList());
}
private static AttributeConfiguration resolveAttributeConfiguration(ImmutablePropertyDescriptor propertyDescriptor) {
boolean shouldPreserveEmptyObject = getPropertyAnnotation(propertyDescriptor,
DynamoDbPreserveEmptyObject.class) != null;
boolean ignoreNulls = getPropertyAnnotation(propertyDescriptor,
DynamoDbIgnoreNulls.class) != null;
return AttributeConfiguration.builder()
.preserveEmptyObject(shouldPreserveEmptyObject)
.ignoreNulls(ignoreNulls)
.build();
}
private static void debugLog(Class<?> beanClass, Supplier<String> logMessage) {
BEAN_LOGGER.debug(() -> beanClass.getTypeName() + " - " + logMessage.get());
}
}
| 4,113 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper/ImmutableAttribute.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.mapper;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.Function;
import software.amazon.awssdk.annotations.NotThreadSafe;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.enhanced.dynamodb.AttributeConverter;
import software.amazon.awssdk.enhanced.dynamodb.AttributeConverterProvider;
import software.amazon.awssdk.enhanced.dynamodb.EnhancedType;
import software.amazon.awssdk.enhanced.dynamodb.internal.mapper.ResolvedImmutableAttribute;
import software.amazon.awssdk.utils.Validate;
/**
* A class that represents an attribute on an mapped immutable item. A {@link StaticImmutableTableSchema} composes
* multiple attributes that map to a common immutable item class.
* <p>
* The recommended way to use this class is by calling
* {@link software.amazon.awssdk.enhanced.dynamodb.TableSchema#builder(Class, Class)}.
* Example:
* {@code
* TableSchema.builder(Customer.class, Customer.Builder.class)
* .addAttribute(String.class,
* a -> a.name("customer_name").getter(Customer::name).setter(Customer.Builder::name))
* // ...
* .build();
* }
* <p>
* It's also possible to construct this class on its own using the static builder. Example:
* {@code
* ImmutableAttribute<Customer, Customer.Builder, ?> customerNameAttribute =
* ImmutableAttribute.builder(Customer.class, Customer.Builder.class, String.class)
* .name("customer_name")
* .getter(Customer::name)
* .setter(Customer.Builder::name)
* .build();
* }
* @param <T> the class of the immutable item this attribute maps into.
* @param <B> the class of the builder for the immutable item this attribute maps into.
* @param <R> the class that the value of this attribute converts to.
*/
@SdkPublicApi
@ThreadSafe
public final class ImmutableAttribute<T, B, R> {
private final String name;
private final Function<T, R> getter;
private final BiConsumer<B, R> setter;
private final Collection<StaticAttributeTag> tags;
private final EnhancedType<R> type;
private final AttributeConverter<R> attributeConverter;
private ImmutableAttribute(Builder<T, B, R> builder) {
this.name = Validate.paramNotNull(builder.name, "name");
this.getter = Validate.paramNotNull(builder.getter, "getter");
this.setter = Validate.paramNotNull(builder.setter, "setter");
this.tags = builder.tags == null ? Collections.emptyList() : Collections.unmodifiableCollection(builder.tags);
this.type = Validate.paramNotNull(builder.type, "type");
this.attributeConverter = builder.attributeConverter;
}
/**
* Constructs a new builder for this class using supplied types.
* @param itemClass The class of the immutable item that this attribute composes.
* @param builderClass The class of the builder for the immutable item that this attribute composes.
* @param attributeType A {@link EnhancedType} that represents the type of the value this attribute stores.
* @return A new typed builder for an attribute.
*/
public static <T, B, R> Builder<T, B, R> builder(Class<T> itemClass,
Class<B> builderClass,
EnhancedType<R> attributeType) {
return new Builder<>(attributeType);
}
/**
* Constructs a new builder for this class using supplied types.
* @param itemType The {@link EnhancedType} of the immutable item that this attribute composes.
* @param builderType The {@link EnhancedType} of the builder for the immutable item that this attribute composes.
* @param attributeType A {@link EnhancedType} that represents the type of the value this attribute stores.
* @return A new typed builder for an attribute.
*/
public static <T, B, R> Builder<T, B, R> builder(EnhancedType<T> itemType,
EnhancedType<B> builderType,
EnhancedType<R> attributeType) {
return new Builder<>(attributeType);
}
/**
* Constructs a new builder for this class using supplied types.
* @param itemClass The class of the item that this attribute composes.
* @param builderClass The class of the builder for the immutable item that this attribute composes.
* @param attributeClass A class that represents the type of the value this attribute stores.
* @return A new typed builder for an attribute.
*/
public static <T, B, R> Builder<T, B, R> builder(Class<T> itemClass,
Class<B> builderClass,
Class<R> attributeClass) {
return new Builder<>(EnhancedType.of(attributeClass));
}
/**
* The name of this attribute
*/
public String name() {
return this.name;
}
/**
* A function that can get the value of this attribute from a modelled immutable item it composes.
*/
public Function<T, R> getter() {
return this.getter;
}
/**
* A function that can set the value of this attribute on a builder for the immutable modelled item it composes.
*/
public BiConsumer<B, R> setter() {
return this.setter;
}
/**
* A collection of {@link StaticAttributeTag} associated with this attribute.
*/
public Collection<StaticAttributeTag> tags() {
return this.tags;
}
/**
* A {@link EnhancedType} that represents the type of the value this attribute stores.
*/
public EnhancedType<R> type() {
return this.type;
}
/**
* A custom {@link AttributeConverter} that will be used to convert this attribute.
* If no custom converter was provided, the value will be null.
* @see Builder#attributeConverter
*/
public AttributeConverter<R> attributeConverter() {
return this.attributeConverter;
}
/**
* Converts an instance of this class to a {@link Builder} that can be used to modify and reconstruct it.
*/
public Builder<T, B, R> toBuilder() {
return new Builder<T, B, R>(this.type).name(this.name)
.getter(this.getter)
.setter(this.setter)
.tags(this.tags)
.attributeConverter(this.attributeConverter);
}
ResolvedImmutableAttribute<T, B> resolve(AttributeConverterProvider attributeConverterProvider) {
return ResolvedImmutableAttribute.create(this,
converterFrom(attributeConverterProvider));
}
private AttributeConverter<R> converterFrom(AttributeConverterProvider attributeConverterProvider) {
return (attributeConverter != null) ? attributeConverter : attributeConverterProvider.converterFor(type);
}
/**
* A typed builder for {@link ImmutableAttribute}.
* @param <T> the class of the item this attribute maps into.
* @param <R> the class that the value of this attribute converts to.
*/
@NotThreadSafe
public static final class Builder<T, B, R> {
private final EnhancedType<R> type;
private String name;
private Function<T, R> getter;
private BiConsumer<B, R> setter;
private List<StaticAttributeTag> tags;
private AttributeConverter<R> attributeConverter;
private Builder(EnhancedType<R> type) {
this.type = type;
}
/**
* The name of this attribute
*/
public Builder<T, B, R> name(String name) {
this.name = name;
return this;
}
/**
* A function that can get the value of this attribute from a modelled item it composes.
*/
public Builder<T, B, R> getter(Function<T, R> getter) {
this.getter = getter;
return this;
}
/**
* A function that can set the value of this attribute on a modelled item it composes.
*/
public Builder<T, B, R> setter(BiConsumer<B, R> setter) {
this.setter = setter;
return this;
}
/**
* A collection of {@link StaticAttributeTag} associated with this attribute. Overwrites any existing tags.
*/
public Builder<T, B, R> tags(Collection<StaticAttributeTag> tags) {
this.tags = new ArrayList<>(tags);
return this;
}
/**
* A collection of {@link StaticAttributeTag} associated with this attribute. Overwrites any existing tags.
*/
public Builder<T, B, R> tags(StaticAttributeTag... tags) {
this.tags = Arrays.asList(tags);
return this;
}
/**
* Associates a single {@link StaticAttributeTag} with this attribute. Adds to any existing tags.
*/
public Builder<T, B, R> addTag(StaticAttributeTag tag) {
if (this.tags == null) {
this.tags = new ArrayList<>();
}
this.tags.add(tag);
return this;
}
/**
* An {@link AttributeConverter} for the attribute type ({@link EnhancedType}), that can convert this attribute.
* It takes precedence over any converter for this type provided by the table schema
* {@link AttributeConverterProvider}.
*/
public Builder<T, B, R> attributeConverter(AttributeConverter<R> attributeConverter) {
this.attributeConverter = attributeConverter;
return this;
}
/**
* Builds a {@link StaticAttributeTag} from the values stored in this builder.
*/
public ImmutableAttribute<T, B, R> build() {
return new ImmutableAttribute<>(this);
}
}
}
| 4,114 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper/StaticTableSchema.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.mapper;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import software.amazon.awssdk.annotations.NotThreadSafe;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.enhanced.dynamodb.AttributeConverter;
import software.amazon.awssdk.enhanced.dynamodb.AttributeConverterProvider;
import software.amazon.awssdk.enhanced.dynamodb.DefaultAttributeConverterProvider;
import software.amazon.awssdk.enhanced.dynamodb.EnhancedType;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
/**
* Implementation of {@link TableSchema} that builds a schema based on directly declared attributes and methods to
* get and set those attributes. Just like {@link StaticImmutableTableSchema} which is the equivalent implementation for
* immutable objects, this is the most direct, and thus fastest, implementation of {@link TableSchema}.
* <p>
* Example using a fictional 'Customer' data item class:-
* <pre>{@code
* static final TableSchema<Customer> CUSTOMER_TABLE_SCHEMA =
* StaticTableSchema.builder(Customer.class)
* .newItemSupplier(Customer::new)
* .addAttribute(String.class, a -> a.name("account_id")
* .getter(Customer::getAccountId)
* .setter(Customer::setAccountId)
* .tags(primaryPartitionKey()))
* .addAttribute(Integer.class, a -> a.name("sub_id")
* .getter(Customer::getSubId)
* .setter(Customer::setSubId)
* .tags(primarySortKey()))
* .addAttribute(String.class, a -> a.name("name")
* .getter(Customer::getName)
* .setter(Customer::setName)
* .tags(secondaryPartitionKey("customers_by_name")))
* .addAttribute(Instant.class, a -> a.name("created_date")
* .getter(Customer::getCreatedDate)
* .setter(Customer::setCreatedDate)
* .tags(secondarySortKey("customers_by_date"),
* secondarySortKey("customers_by_name")))
* .build();
* }</pre>
*/
@SdkPublicApi
@ThreadSafe
public final class StaticTableSchema<T> extends WrappedTableSchema<T, StaticImmutableTableSchema<T, T>> {
private StaticTableSchema(Builder<T> builder) {
super(builder.delegateBuilder.build());
}
/**
* Creates a builder for a {@link StaticTableSchema} typed to specific data item class.
* @param itemClass The data item class object that the {@link StaticTableSchema} is to map to.
* @return A newly initialized builder
*/
public static <T> Builder<T> builder(Class<T> itemClass) {
return new Builder<>(EnhancedType.of(itemClass));
}
/**
* Creates a builder for a {@link StaticTableSchema} typed to specific data item class.
* @param itemType The {@link EnhancedType} of the data item class object that the {@link StaticTableSchema} is to map to.
* @return A newly initialized builder
*/
public static <T> Builder<T> builder(EnhancedType<T> itemType) {
return new Builder<>(itemType);
}
/**
* Builder for a {@link StaticTableSchema}
* @param <T> The data item type that the {@link StaticTableSchema} this builder will build is to map to.
*/
@NotThreadSafe
public static final class Builder<T> {
private final StaticImmutableTableSchema.Builder<T, T> delegateBuilder;
private final EnhancedType<T> itemType;
private Builder(EnhancedType<T> itemType) {
this.delegateBuilder = StaticImmutableTableSchema.builder(itemType, itemType);
this.itemType = itemType;
}
/**
* A function that can be used to create new instances of the data item class.
*/
public Builder<T> newItemSupplier(Supplier<T> newItemSupplier) {
this.delegateBuilder.newItemBuilder(newItemSupplier, Function.identity());
return this;
}
/**
* A list of attributes that can be mapped between the data item object and the database record that are to
* be associated with the schema. Will overwrite any existing attributes.
*/
@SafeVarargs
public final Builder<T> attributes(StaticAttribute<T, ?>... staticAttributes) {
this.delegateBuilder.attributes(Arrays.stream(staticAttributes)
.map(StaticAttribute::toImmutableAttribute)
.collect(Collectors.toList()));
return this;
}
/**
* A list of attributes that can be mapped between the data item object and the database record that are to
* be associated with the schema. Will overwrite any existing attributes.
*/
public Builder<T> attributes(Collection<StaticAttribute<T, ?>> staticAttributes) {
this.delegateBuilder.attributes(staticAttributes.stream()
.map(StaticAttribute::toImmutableAttribute)
.collect(Collectors.toList()));
return this;
}
/**
* Adds a single attribute to the table schema that can be mapped between the data item object and the database
* record.
*/
public <R> Builder<T> addAttribute(EnhancedType<R> attributeType,
Consumer<StaticAttribute.Builder<T, R>> staticAttribute) {
StaticAttribute.Builder<T, R> builder = StaticAttribute.builder(itemType, attributeType);
staticAttribute.accept(builder);
this.delegateBuilder.addAttribute(builder.build().toImmutableAttribute());
return this;
}
/**
* Adds a single attribute to the table schema that can be mapped between the data item object and the database
* record.
*/
public <R> Builder<T> addAttribute(Class<R> attributeClass,
Consumer<StaticAttribute.Builder<T, R>> staticAttribute) {
StaticAttribute.Builder<T, R> builder = StaticAttribute.builder(itemType, EnhancedType.of(attributeClass));
staticAttribute.accept(builder);
this.delegateBuilder.addAttribute(builder.build().toImmutableAttribute());
return this;
}
/**
* Adds a single attribute to the table schema that can be mapped between the data item object and the database
* record.
*/
public Builder<T> addAttribute(StaticAttribute<T, ?> staticAttribute) {
this.delegateBuilder.addAttribute(staticAttribute.toImmutableAttribute());
return this;
}
/**
* Flattens all the attributes defined in another {@link StaticTableSchema} into the database record this schema
* maps to. Functions to get and set an object that the flattened schema maps to is required.
*/
public <R> Builder<T> flatten(TableSchema<R> otherTableSchema,
Function<T, R> otherItemGetter,
BiConsumer<T, R> otherItemSetter) {
this.delegateBuilder.flatten(otherTableSchema, otherItemGetter, otherItemSetter);
return this;
}
/**
* Extends the {@link StaticTableSchema} of a super-class, effectively rolling all the attributes modelled by
* the super-class into the {@link StaticTableSchema} of the sub-class.
*/
public Builder<T> extend(StaticTableSchema<? super T> superTableSchema) {
this.delegateBuilder.extend(superTableSchema.toImmutableTableSchema());
return this;
}
/**
* Associate one or more {@link StaticTableTag} with this schema. See documentation on the tags themselves to
* understand what each one does. This method will overwrite any existing table tags.
*/
public Builder<T> tags(StaticTableTag... staticTableTags) {
this.delegateBuilder.tags(staticTableTags);
return this;
}
/**
* Associate one or more {@link StaticTableTag} with this schema. See documentation on the tags themselves to
* understand what each one does. This method will overwrite any existing table tags.
*/
public Builder<T> tags(Collection<StaticTableTag> staticTableTags) {
this.delegateBuilder.tags(staticTableTags);
return this;
}
/**
* Associates a {@link StaticTableTag} with this schema. See documentation on the tags themselves to understand
* what each one does. This method will add the tag to the list of existing table tags.
*/
public Builder<T> addTag(StaticTableTag staticTableTag) {
this.delegateBuilder.addTag(staticTableTag);
return this;
}
/**
* Specifies the {@link AttributeConverterProvider}s to use with the table schema.
* The list of attribute converter providers must provide {@link AttributeConverter}s for all types used
* in the schema. The attribute converter providers will be loaded in the strict order they are supplied here.
* <p>
* Calling this method will override the default attribute converter provider
* {@link DefaultAttributeConverterProvider}, which provides standard converters for most primitive
* and common Java types, so that provider must included in the supplied list if it is to be
* used. Providing an empty list here will cause no providers to get loaded.
* <p>
* Adding one custom attribute converter provider and using the default as fallback:
* {@code
* builder.attributeConverterProviders(customAttributeConverter, AttributeConverterProvider.defaultProvider())
* }
*
* @param attributeConverterProviders a list of attribute converter providers to use with the table schema
*/
public Builder<T> attributeConverterProviders(AttributeConverterProvider... attributeConverterProviders) {
this.delegateBuilder.attributeConverterProviders(attributeConverterProviders);
return this;
}
/**
* Specifies the {@link AttributeConverterProvider}s to use with the table schema.
* The list of attribute converter providers must provide {@link AttributeConverter}s for all types used
* in the schema. The attribute converter providers will be loaded in the strict order they are supplied here.
* <p>
* Calling this method will override the default attribute converter provider
* {@link DefaultAttributeConverterProvider}, which provides standard converters
* for most primitive and common Java types, so that provider must included in the supplied list if it is to be
* used. Providing an empty list here will cause no providers to get loaded.
* <p>
* Adding one custom attribute converter provider and using the default as fallback:
* {@code
* List<AttributeConverterProvider> providers = new ArrayList<>(
* customAttributeConverter,
* AttributeConverterProvider.defaultProvider());
* builder.attributeConverterProviders(providers);
* }
*
* @param attributeConverterProviders a list of attribute converter providers to use with the table schema
*/
public Builder<T> attributeConverterProviders(List<AttributeConverterProvider> attributeConverterProviders) {
this.delegateBuilder.attributeConverterProviders(attributeConverterProviders);
return this;
}
/**
* Builds a {@link StaticTableSchema} based on the values this builder has been configured with
*/
public StaticTableSchema<T> build() {
return new StaticTableSchema<>(this);
}
}
private StaticImmutableTableSchema<T, T> toImmutableTableSchema() {
return delegateTableSchema();
}
/**
* The table schema {@link AttributeConverterProvider}.
* @see Builder#attributeConverterProvider
*/
public AttributeConverterProvider attributeConverterProvider() {
return delegateTableSchema().attributeConverterProvider();
}
}
| 4,115 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper/StaticTableTag.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.mapper;
import java.util.function.Consumer;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.ThreadSafe;
/**
* Interface for a tag that can be applied to any {@link StaticTableSchema}. When the table schema is instantiated,
* the table metadata stored on the schema will be updated by calling the {@link #modifyMetadata()} method for every tag
* associated with the table.
*/
@SdkPublicApi
@ThreadSafe
public interface StaticTableTag {
/**
* A function that modifies an existing {@link StaticTableSchema.Builder} when this tag is applied to a table. This
* will be used by the {@link StaticTableSchema} to capture all the metadata associated with tags that have been
* applied to the table.
*
* @return a consumer that modifies an existing {@link StaticTableSchema.Builder}.
*/
Consumer<StaticTableMetadata.Builder> modifyMetadata();
}
| 4,116 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper/StaticTableMetadata.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.mapper;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import software.amazon.awssdk.annotations.NotThreadSafe;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType;
import software.amazon.awssdk.enhanced.dynamodb.IndexMetadata;
import software.amazon.awssdk.enhanced.dynamodb.KeyAttributeMetadata;
import software.amazon.awssdk.enhanced.dynamodb.TableMetadata;
import software.amazon.awssdk.enhanced.dynamodb.internal.mapper.StaticIndexMetadata;
import software.amazon.awssdk.enhanced.dynamodb.internal.mapper.StaticKeyAttributeMetadata;
import software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType;
/**
* Implementation of {@link TableMetadata} that can be constructed directly using literal values for metadata objects.
* This implementation is used by {@link StaticTableSchema} and associated interfaces such as {@link StaticAttributeTag}
* and {@link StaticTableTag} which permit manipulation of the table metadata.
*/
@SdkPublicApi
@ThreadSafe
public final class StaticTableMetadata implements TableMetadata {
private final Map<String, Object> customMetadata;
private final Map<String, IndexMetadata> indexByNameMap;
private final Map<String, KeyAttributeMetadata> keyAttributes;
private StaticTableMetadata(Builder builder) {
this.customMetadata = Collections.unmodifiableMap(builder.customMetadata);
this.indexByNameMap = Collections.unmodifiableMap(builder.indexByNameMap);
this.keyAttributes = Collections.unmodifiableMap(builder.keyAttributes);
}
/**
* Create a new builder for this class
* @return A newly initialized {@link Builder} for building a {@link StaticTableMetadata} object.
*/
public static Builder builder() {
return new Builder();
}
@Override
public <T> Optional<T> customMetadataObject(String key, Class<? extends T> objectClass) {
Object genericObject = customMetadata.get(key);
if (genericObject == null) {
return Optional.empty();
}
if (!objectClass.isAssignableFrom(genericObject.getClass())) {
throw new IllegalArgumentException("Attempt to retrieve a custom metadata object as a type that is not "
+ "assignable for that object. Custom metadata key: " + key + "; "
+ "requested object class: " + objectClass.getCanonicalName() + "; "
+ "found object class: " + genericObject.getClass().getCanonicalName());
}
return Optional.of(objectClass.cast(genericObject));
}
@Override
public String indexPartitionKey(String indexName) {
IndexMetadata index = getIndex(indexName);
if (!index.partitionKey().isPresent()) {
if (!TableMetadata.primaryIndexName().equals(indexName) && index.sortKey().isPresent()) {
// Local secondary index, use primary partition key
return primaryPartitionKey();
}
throw new IllegalArgumentException("Attempt to execute an operation against an index that requires a "
+ "partition key without assigning a partition key to that index. "
+ "Index name: " + indexName);
}
return index.partitionKey().get().name();
}
@Override
public Optional<String> indexSortKey(String indexName) {
IndexMetadata index = getIndex(indexName);
return index.sortKey().map(KeyAttributeMetadata::name);
}
@Override
public Collection<String> indexKeys(String indexName) {
IndexMetadata index = getIndex(indexName);
if (index.sortKey().isPresent()) {
if (!TableMetadata.primaryIndexName().equals(indexName) && !index.partitionKey().isPresent()) {
// Local secondary index, use primary index for partition key
return Collections.unmodifiableList(Arrays.asList(primaryPartitionKey(), index.sortKey().get().name()));
}
return Collections.unmodifiableList(Arrays.asList(index.partitionKey().get().name(), index.sortKey().get().name()));
} else {
return Collections.singletonList(index.partitionKey().get().name());
}
}
@Override
public Collection<String> allKeys() {
return this.keyAttributes.keySet();
}
@Override
public Collection<IndexMetadata> indices() {
return indexByNameMap.values();
}
@Override
public Map<String, Object> customMetadata() {
return this.customMetadata;
}
@Override
public Collection<KeyAttributeMetadata> keyAttributes() {
return this.keyAttributes.values();
}
private IndexMetadata getIndex(String indexName) {
IndexMetadata index = indexByNameMap.get(indexName);
if (index == null) {
if (TableMetadata.primaryIndexName().equals(indexName)) {
throw new IllegalArgumentException("Attempt to execute an operation that requires a primary index "
+ "without defining any primary key attributes in the table "
+ "metadata.");
} else {
throw new IllegalArgumentException("Attempt to execute an operation that requires a secondary index "
+ "without defining the index attributes in the table metadata. "
+ "Index name: " + indexName);
}
}
return index;
}
@Override
public Optional<ScalarAttributeType> scalarAttributeType(String keyAttribute) {
KeyAttributeMetadata key = this.keyAttributes.get(keyAttribute);
if (key == null) {
throw new IllegalArgumentException("Key attribute '" + keyAttribute + "' not found in table metadata.");
}
return Optional.ofNullable(key.attributeValueType().scalarAttributeType());
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
StaticTableMetadata that = (StaticTableMetadata) o;
if (customMetadata != null ? ! customMetadata.equals(that.customMetadata) : that.customMetadata != null) {
return false;
}
if (indexByNameMap != null ? ! indexByNameMap.equals(that.indexByNameMap) : that.indexByNameMap != null) {
return false;
}
return keyAttributes != null ? keyAttributes.equals(that.keyAttributes) : that.keyAttributes == null;
}
@Override
public int hashCode() {
int result = customMetadata != null ? customMetadata.hashCode() : 0;
result = 31 * result + (indexByNameMap != null ? indexByNameMap.hashCode() : 0);
result = 31 * result + (keyAttributes != null ? keyAttributes.hashCode() : 0);
return result;
}
/**
* Builder for {@link StaticTableMetadata}
*/
@NotThreadSafe
public static class Builder {
private final Map<String, Object> customMetadata = new LinkedHashMap<>();
private final Map<String, IndexMetadata> indexByNameMap = new LinkedHashMap<>();
private final Map<String, KeyAttributeMetadata> keyAttributes = new LinkedHashMap<>();
private Builder() {
}
/**
* Builds an immutable instance of {@link StaticTableMetadata} from the values supplied to the builder.
*/
public StaticTableMetadata build() {
return new StaticTableMetadata(this);
}
/**
* Adds a single custom object to the metadata, keyed by a string. Attempting to add a metadata object with a
* key that matches one that has already been added will cause an exception to be thrown.
* @param key a string key that will be used to retrieve the custom metadata
* @param object an object that will be stored in the custom metadata map
* @throws IllegalArgumentException if the custom metadata map already contains an entry with the same key
*/
public Builder addCustomMetadataObject(String key, Object object) {
if (customMetadata.containsKey(key)) {
throw new IllegalArgumentException("Attempt to set a custom metadata object that has already been set. "
+ "Custom metadata object key: " + key);
}
customMetadata.put(key, object);
return this;
}
/**
* Adds collection of custom objects to the custom metadata, keyed by a string.
* If a collection is already present then it will append the newly added collection to the existing collection.
*
* @param key a string key that will be used to retrieve the custom metadata
* @param objects Collection of objects that will be stored in the custom metadata map
*/
public Builder addCustomMetadataObject(String key, Collection<Object> objects) {
Object collectionInMetadata = customMetadata.get(key);
Object customObjectToPut = collectionInMetadata != null
? Stream.concat(((Collection<Object>) collectionInMetadata).stream(),
objects.stream()).collect(Collectors.toSet())
: objects;
customMetadata.put(key, customObjectToPut);
return this;
}
/**
* Adds map of custom objects to the custom metadata, keyed by a string.
* If a map is already present then it will merge the new map with the existing map.
*
* @param key a string key that will be used to retrieve the custom metadata
* @param objectMap Map of objects that will be stored in the custom metadata map
*/
public Builder addCustomMetadataObject(String key, Map<Object, Object> objectMap) {
Object collectionInMetadata = customMetadata.get(key);
Object customObjectToPut = collectionInMetadata != null
? Stream.concat(((Map<Object, Object>) collectionInMetadata).entrySet().stream(),
objectMap.entrySet().stream())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))
: objectMap;
customMetadata.put(key, customObjectToPut);
return this;
}
/**
* Adds information about a partition key associated with a specific index.
* @param indexName the name of the index to associate the partition key with
* @param attributeName the name of the attribute that represents the partition key
* @param attributeValueType the {@link AttributeValueType} of the partition key
* @throws IllegalArgumentException if a partition key has already been defined for this index
*/
public Builder addIndexPartitionKey(String indexName, String attributeName, AttributeValueType attributeValueType) {
IndexMetadata index = indexByNameMap.get(indexName);
if (index != null && index.partitionKey().isPresent()) {
throw new IllegalArgumentException("Attempt to set an index partition key that conflicts with an "
+ "existing index partition key of the same name and index. Index "
+ "name: " + indexName + "; attribute name: " + attributeName);
}
KeyAttributeMetadata partitionKey = StaticKeyAttributeMetadata.create(attributeName, attributeValueType);
indexByNameMap.put(indexName,
StaticIndexMetadata.builderFrom(index).name(indexName).partitionKey(partitionKey).build());
markAttributeAsKey(attributeName, attributeValueType);
return this;
}
/**
* Adds information about a sort key associated with a specific index.
* @param indexName the name of the index to associate the sort key with
* @param attributeName the name of the attribute that represents the sort key
* @param attributeValueType the {@link AttributeValueType} of the sort key
* @throws IllegalArgumentException if a sort key has already been defined for this index
*/
public Builder addIndexSortKey(String indexName, String attributeName, AttributeValueType attributeValueType) {
IndexMetadata index = indexByNameMap.get(indexName);
if (index != null && index.sortKey().isPresent()) {
throw new IllegalArgumentException("Attempt to set an index sort key that conflicts with an existing"
+ " index sort key of the same name and index. Index name: "
+ indexName + "; attribute name: " + attributeName);
}
KeyAttributeMetadata sortKey = StaticKeyAttributeMetadata.create(attributeName, attributeValueType);
indexByNameMap.put(indexName,
StaticIndexMetadata.builderFrom(index).name(indexName).sortKey(sortKey).build());
markAttributeAsKey(attributeName, attributeValueType);
return this;
}
/**
* Declares a 'key-like' attribute that is not an actual DynamoDB key. These pseudo-keys can then be recognized
* by extensions and treated appropriately, often being protected from manipulations as those would alter the
* meaning of the record. One example usage of this is a 'versioned record attribute': although the version is
* not part of the primary key of the record, it effectively serves as such.
* @param attributeName the name of the attribute to mark as a pseudo-key
* @param attributeValueType the {@link AttributeValueType} of the pseudo-key
*/
public Builder markAttributeAsKey(String attributeName, AttributeValueType attributeValueType) {
KeyAttributeMetadata existing = keyAttributes.get(attributeName);
if (existing != null && existing.attributeValueType() != attributeValueType) {
throw new IllegalArgumentException("Attempt to mark an attribute as a key with a different "
+ "AttributeValueType than one that has already been recorded.");
}
if (existing == null) {
keyAttributes.put(attributeName, StaticKeyAttributeMetadata.create(attributeName, attributeValueType));
}
return this;
}
/**
* Package-private method to merge the contents of a constructed {@link TableMetadata} into this builder.
*/
Builder mergeWith(TableMetadata other) {
other.indices().forEach(
index -> {
index.partitionKey().ifPresent(
partitionKey -> addIndexPartitionKey(index.name(),
partitionKey.name(),
partitionKey.attributeValueType()));
index.sortKey().ifPresent(
sortKey -> addIndexSortKey(index.name(), sortKey.name(), sortKey.attributeValueType())
);
});
other.customMetadata().forEach(this::mergeCustomMetaDataObject);
other.keyAttributes().forEach(keyAttribute -> markAttributeAsKey(keyAttribute.name(),
keyAttribute.attributeValueType()));
return this;
}
private void mergeCustomMetaDataObject(String key, Object object) {
if (object instanceof Collection) {
this.addCustomMetadataObject(key, (Collection<Object>) object);
} else if (object instanceof Map) {
this.addCustomMetadataObject(key, (Map<Object, Object>) object);
} else {
this.addCustomMetadataObject(key, object);
}
}
}
}
| 4,117 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper/BeanTableSchema.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.mapper;
import static software.amazon.awssdk.enhanced.dynamodb.internal.DynamoDbEnhancedLogger.BEAN_LOGGER;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.beans.Transient;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.WeakHashMap;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.enhanced.dynamodb.AttributeConverter;
import software.amazon.awssdk.enhanced.dynamodb.AttributeConverterProvider;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient;
import software.amazon.awssdk.enhanced.dynamodb.EnhancedType;
import software.amazon.awssdk.enhanced.dynamodb.EnhancedTypeDocumentConfiguration;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.internal.AttributeConfiguration;
import software.amazon.awssdk.enhanced.dynamodb.internal.mapper.BeanAttributeGetter;
import software.amazon.awssdk.enhanced.dynamodb.internal.mapper.BeanAttributeSetter;
import software.amazon.awssdk.enhanced.dynamodb.internal.mapper.MetaTableSchema;
import software.amazon.awssdk.enhanced.dynamodb.internal.mapper.MetaTableSchemaCache;
import software.amazon.awssdk.enhanced.dynamodb.internal.mapper.ObjectConstructor;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.BeanTableSchemaAttributeTag;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbAttribute;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbConvertedBy;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbFlatten;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbIgnore;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbIgnoreNulls;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbImmutable;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPreserveEmptyObject;
/**
* Implementation of {@link TableSchema} that builds a table schema based on properties and annotations of a bean
* class. Example:
* <pre>
* <code>
* {@literal @}DynamoDbBean
* public class Customer {
* private String accountId;
* private int subId; // primitive types are supported
* private String name;
* private Instant createdDate;
*
* {@literal @}DynamoDbPartitionKey
* public String getAccountId() { return this.accountId; }
* public void setAccountId(String accountId) { this.accountId = accountId; }
*
* {@literal @}DynamoDbSortKey
* public int getSubId() { return this.subId; }
* public void setSubId(int subId) { this.subId = subId; }
*
* // Defines a GSI (customers_by_name) with a partition key of 'name'
* {@literal @}DynamoDbSecondaryPartitionKey(indexNames = "customers_by_name")
* public String getName() { return this.name; }
* public void setName(String name) { this.name = name; }
*
* // Defines an LSI (customers_by_date) with a sort key of 'createdDate' and also declares the
* // same attribute as a sort key for the GSI named 'customers_by_name'
* {@literal @}DynamoDbSecondarySortKey(indexNames = {"customers_by_date", "customers_by_name"})
* public Instant getCreatedDate() { return this.createdDate; }
* public void setCreatedDate(Instant createdDate) { this.createdDate = createdDate; }
* }
*
* </pre>
*
* Creating an {@link BeanTableSchema} is a moderately expensive operation, and should be performed sparingly. This is
* usually done once at application startup.
*
* If this table schema is not behaving as you expect, enable debug logging for 'software.amazon.awssdk.enhanced.dynamodb.beans'.
*
* @param <T> The type of object that this {@link TableSchema} maps to.
*/
@SdkPublicApi
@ThreadSafe
public final class BeanTableSchema<T> extends WrappedTableSchema<T, StaticTableSchema<T>> {
private static final Map<Class<?>, BeanTableSchema<?>> BEAN_TABLE_SCHEMA_CACHE =
Collections.synchronizedMap(new WeakHashMap<>());
private static final String ATTRIBUTE_TAG_STATIC_SUPPLIER_NAME = "attributeTagFor";
private BeanTableSchema(StaticTableSchema<T> staticTableSchema) {
super(staticTableSchema);
}
/**
* Scans a bean class and builds a {@link BeanTableSchema} from it that can be used with the
* {@link DynamoDbEnhancedClient}.
*
* <p>
* It's recommended to only create a {@link BeanTableSchema} once for a single bean class, usually at application start up,
* because it's a moderately expensive operation.
*
* @param beanClass The bean class to build the table schema from.
* @param <T> The bean class type.
* @return An initialized {@link BeanTableSchema}
*/
@SuppressWarnings("unchecked")
public static <T> BeanTableSchema<T> create(Class<T> beanClass) {
return (BeanTableSchema<T>) BEAN_TABLE_SCHEMA_CACHE.computeIfAbsent(beanClass, clz -> create(clz,
new MetaTableSchemaCache()));
}
private static <T> BeanTableSchema<T> create(Class<T> beanClass, MetaTableSchemaCache metaTableSchemaCache) {
debugLog(beanClass, () -> "Creating bean schema");
// Fetch or create a new reference to this yet-to-be-created TableSchema in the cache
MetaTableSchema<T> metaTableSchema = metaTableSchemaCache.getOrCreate(beanClass);
BeanTableSchema<T> newTableSchema =
new BeanTableSchema<>(createStaticTableSchema(beanClass, metaTableSchemaCache));
metaTableSchema.initialize(newTableSchema);
return newTableSchema;
}
// Called when creating an immutable TableSchema recursively. Utilizes the MetaTableSchema cache to stop infinite
// recursion
static <T> TableSchema<T> recursiveCreate(Class<T> beanClass, MetaTableSchemaCache metaTableSchemaCache) {
Optional<MetaTableSchema<T>> metaTableSchema = metaTableSchemaCache.get(beanClass);
// If we get a cache hit...
if (metaTableSchema.isPresent()) {
// Either: use the cached concrete TableSchema if we have one
if (metaTableSchema.get().isInitialized()) {
return metaTableSchema.get().concreteTableSchema();
}
// Or: return the uninitialized MetaTableSchema as this must be a recursive reference and it will be
// initialized later as the chain completes
return metaTableSchema.get();
}
// Otherwise: cache doesn't know about this class; create a new one from scratch
return create(beanClass);
}
private static <T> StaticTableSchema<T> createStaticTableSchema(Class<T> beanClass,
MetaTableSchemaCache metaTableSchemaCache) {
DynamoDbBean dynamoDbBean = beanClass.getAnnotation(DynamoDbBean.class);
if (dynamoDbBean == null) {
throw new IllegalArgumentException("A DynamoDb bean class must be annotated with @DynamoDbBean, but " +
beanClass.getTypeName() + " was not.");
}
BeanInfo beanInfo;
try {
beanInfo = Introspector.getBeanInfo(beanClass);
} catch (IntrospectionException e) {
throw new IllegalArgumentException(e);
}
Supplier<T> newObjectSupplier = newObjectSupplierForClass(beanClass);
StaticTableSchema.Builder<T> builder = StaticTableSchema.builder(beanClass)
.newItemSupplier(newObjectSupplier);
builder.attributeConverterProviders(createConverterProvidersFromAnnotation(beanClass, dynamoDbBean));
List<StaticAttribute<T, ?>> attributes = new ArrayList<>();
Arrays.stream(beanInfo.getPropertyDescriptors())
.filter(p -> isMappableProperty(beanClass, p))
.forEach(propertyDescriptor -> {
DynamoDbFlatten dynamoDbFlatten = getPropertyAnnotation(propertyDescriptor, DynamoDbFlatten.class);
if (dynamoDbFlatten != null) {
builder.flatten(TableSchema.fromClass(propertyDescriptor.getReadMethod().getReturnType()),
getterForProperty(propertyDescriptor, beanClass),
setterForProperty(propertyDescriptor, beanClass));
} else {
AttributeConfiguration attributeConfiguration =
resolveAttributeConfiguration(propertyDescriptor);
StaticAttribute.Builder<T, ?> attributeBuilder =
staticAttributeBuilder(propertyDescriptor, beanClass, metaTableSchemaCache, attributeConfiguration);
Optional<AttributeConverter> attributeConverter =
createAttributeConverterFromAnnotation(propertyDescriptor);
attributeConverter.ifPresent(attributeBuilder::attributeConverter);
addTagsToAttribute(attributeBuilder, propertyDescriptor);
attributes.add(attributeBuilder.build());
}
});
builder.attributes(attributes);
return builder.build();
}
private static AttributeConfiguration resolveAttributeConfiguration(PropertyDescriptor propertyDescriptor) {
boolean shouldPreserveEmptyObject = getPropertyAnnotation(propertyDescriptor,
DynamoDbPreserveEmptyObject.class) != null;
boolean shouldIgnoreNulls = getPropertyAnnotation(propertyDescriptor,
DynamoDbIgnoreNulls.class) != null;
return AttributeConfiguration.builder()
.preserveEmptyObject(shouldPreserveEmptyObject)
.ignoreNulls(shouldIgnoreNulls)
.build();
}
private static List<AttributeConverterProvider> createConverterProvidersFromAnnotation(Class<?> beanClass,
DynamoDbBean dynamoDbBean) {
Class<? extends AttributeConverterProvider>[] providerClasses = dynamoDbBean.converterProviders();
return Arrays.stream(providerClasses)
.peek(c -> debugLog(beanClass, () -> "Adding Converter: " + c.getTypeName()))
.map(c -> (AttributeConverterProvider) newObjectSupplierForClass(c).get())
.collect(Collectors.toList());
}
private static <T> StaticAttribute.Builder<T, ?> staticAttributeBuilder(PropertyDescriptor propertyDescriptor,
Class<T> beanClass,
MetaTableSchemaCache metaTableSchemaCache,
AttributeConfiguration attributeConfiguration) {
Type propertyType = propertyDescriptor.getReadMethod().getGenericReturnType();
EnhancedType<?> propertyTypeToken = convertTypeToEnhancedType(propertyType, metaTableSchemaCache, attributeConfiguration);
return StaticAttribute.builder(beanClass, propertyTypeToken)
.name(attributeNameForProperty(propertyDescriptor))
.getter(getterForProperty(propertyDescriptor, beanClass))
.setter(setterForProperty(propertyDescriptor, beanClass));
}
/**
* Converts a {@link Type} to an {@link EnhancedType}. Usually {@link EnhancedType#of} is capable of doing this all
* by itself, but for the BeanTableSchema we want to detect if a parameterized class is being passed without a
* converter that is actually another annotated class in which case we want to capture its schema and add it to the
* EnhancedType. Unfortunately this means we have to duplicate some of the recursive Type parsing that
* EnhancedClient otherwise does all by itself.
*/
@SuppressWarnings("unchecked")
private static EnhancedType<?> convertTypeToEnhancedType(Type type, MetaTableSchemaCache metaTableSchemaCache,
AttributeConfiguration attributeConfiguration) {
Class<?> clazz = null;
if (type instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) type;
Type rawType = parameterizedType.getRawType();
if (List.class.equals(rawType)) {
EnhancedType<?> enhancedType = convertTypeToEnhancedType(parameterizedType.getActualTypeArguments()[0],
metaTableSchemaCache, attributeConfiguration);
return EnhancedType.listOf(enhancedType);
}
if (Map.class.equals(rawType)) {
EnhancedType<?> enhancedType = convertTypeToEnhancedType(parameterizedType.getActualTypeArguments()[1],
metaTableSchemaCache, attributeConfiguration);
return EnhancedType.mapOf(EnhancedType.of(parameterizedType.getActualTypeArguments()[0]),
enhancedType);
}
if (rawType instanceof Class) {
clazz = (Class<?>) rawType;
}
} else if (type instanceof Class) {
clazz = (Class<?>) type;
}
if (clazz != null) {
Consumer<EnhancedTypeDocumentConfiguration.Builder> attrConfiguration =
b -> b.preserveEmptyObject(attributeConfiguration.preserveEmptyObject())
.ignoreNulls(attributeConfiguration.ignoreNulls());
if (clazz.getAnnotation(DynamoDbImmutable.class) != null) {
return EnhancedType.documentOf(
(Class<Object>) clazz,
(TableSchema<Object>) ImmutableTableSchema.recursiveCreate(clazz, metaTableSchemaCache),
attrConfiguration);
} else if (clazz.getAnnotation(DynamoDbBean.class) != null) {
return EnhancedType.documentOf(
(Class<Object>) clazz,
(TableSchema<Object>) BeanTableSchema.recursiveCreate(clazz, metaTableSchemaCache),
attrConfiguration);
}
}
return EnhancedType.of(type);
}
private static Optional<AttributeConverter> createAttributeConverterFromAnnotation(
PropertyDescriptor propertyDescriptor) {
DynamoDbConvertedBy attributeConverterBean =
getPropertyAnnotation(propertyDescriptor, DynamoDbConvertedBy.class);
Optional<Class<?>> optionalClass = Optional.ofNullable(attributeConverterBean)
.map(DynamoDbConvertedBy::value);
return optionalClass.map(clazz -> (AttributeConverter) newObjectSupplierForClass(clazz).get());
}
/**
* This method scans all the annotations on a property and looks for a meta-annotation of
* {@link BeanTableSchemaAttributeTag}. If the meta-annotation is found, it attempts to create
* an annotation tag based on a standard named static method
* of the class that tag has been annotated with passing in the original property annotation as an argument.
*/
private static void addTagsToAttribute(StaticAttribute.Builder<?, ?> attributeBuilder,
PropertyDescriptor propertyDescriptor) {
propertyAnnotations(propertyDescriptor).forEach(annotation -> {
BeanTableSchemaAttributeTag beanTableSchemaAttributeTag =
annotation.annotationType().getAnnotation(BeanTableSchemaAttributeTag.class);
if (beanTableSchemaAttributeTag != null) {
Class<?> tagClass = beanTableSchemaAttributeTag.value();
Method tagMethod;
try {
tagMethod = tagClass.getDeclaredMethod(ATTRIBUTE_TAG_STATIC_SUPPLIER_NAME,
annotation.annotationType());
} catch (NoSuchMethodException e) {
throw new RuntimeException(
String.format("Could not find a static method named '%s' on class '%s' that returns " +
"an AttributeTag for annotation '%s'", ATTRIBUTE_TAG_STATIC_SUPPLIER_NAME,
tagClass, annotation.annotationType()), e);
}
if (!Modifier.isStatic(tagMethod.getModifiers())) {
throw new RuntimeException(
String.format("Could not find a static method named '%s' on class '%s' that returns " +
"an AttributeTag for annotation '%s'", ATTRIBUTE_TAG_STATIC_SUPPLIER_NAME,
tagClass, annotation.annotationType()));
}
StaticAttributeTag staticAttributeTag;
try {
staticAttributeTag = (StaticAttributeTag) tagMethod.invoke(null, annotation);
} catch (IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException(
String.format("Could not invoke method to create AttributeTag for annotation '%s' on class " +
"'%s'.", annotation.annotationType(), tagClass), e);
}
attributeBuilder.addTag(staticAttributeTag);
}
});
}
private static <R> Supplier<R> newObjectSupplierForClass(Class<R> clazz) {
try {
Constructor<R> constructor = clazz.getConstructor();
debugLog(clazz, () -> "Constructor: " + constructor);
return ObjectConstructor.create(clazz, constructor);
} catch (NoSuchMethodException e) {
throw new IllegalArgumentException(
String.format("Class '%s' appears to have no default constructor thus cannot be used with the " +
"BeanTableSchema", clazz), e);
}
}
private static <T, R> Function<T, R> getterForProperty(PropertyDescriptor propertyDescriptor, Class<T> beanClass) {
Method readMethod = propertyDescriptor.getReadMethod();
debugLog(beanClass, () -> "Property " + propertyDescriptor.getDisplayName() + " read method: " + readMethod);
return BeanAttributeGetter.create(beanClass, readMethod);
}
private static <T, R> BiConsumer<T, R> setterForProperty(PropertyDescriptor propertyDescriptor,
Class<T> beanClass) {
Method writeMethod = propertyDescriptor.getWriteMethod();
debugLog(beanClass, () -> "Property " + propertyDescriptor.getDisplayName() + " write method: " + writeMethod);
return BeanAttributeSetter.create(beanClass, writeMethod);
}
private static String attributeNameForProperty(PropertyDescriptor propertyDescriptor) {
DynamoDbAttribute dynamoDbAttribute = getPropertyAnnotation(propertyDescriptor, DynamoDbAttribute.class);
if (dynamoDbAttribute != null) {
return dynamoDbAttribute.value();
}
return propertyDescriptor.getName();
}
private static boolean isMappableProperty(Class<?> beanClass, PropertyDescriptor propertyDescriptor) {
if (propertyDescriptor.getReadMethod() == null) {
debugLog(beanClass, () -> "Ignoring bean property " + propertyDescriptor.getDisplayName() + " because it has no "
+ "read (get/is) method.");
return false;
}
if (propertyDescriptor.getWriteMethod() == null) {
debugLog(beanClass, () -> "Ignoring bean property " + propertyDescriptor.getDisplayName() + " because it has no "
+ "write (set) method.");
return false;
}
if (getPropertyAnnotation(propertyDescriptor, DynamoDbIgnore.class) != null ||
getPropertyAnnotation(propertyDescriptor, Transient.class) != null) {
debugLog(beanClass, () -> "Ignoring bean property " + propertyDescriptor.getDisplayName() + " because it has "
+ "@DynamoDbIgnore or @Transient.");
return false;
}
return true;
}
private static <R extends Annotation> R getPropertyAnnotation(PropertyDescriptor propertyDescriptor,
Class<R> annotationType) {
R getterAnnotation = propertyDescriptor.getReadMethod().getAnnotation(annotationType);
R setterAnnotation = propertyDescriptor.getWriteMethod().getAnnotation(annotationType);
if (getterAnnotation != null) {
return getterAnnotation;
}
// TODO: It's a common mistake that superclasses might have annotations that the child classes do not inherit, but the
// customer expects them to be inherited. We should either allow inheriting those annotations, allow specifying an
// annotation to inherit them, or log when this situation happens.
return setterAnnotation;
}
private static List<? extends Annotation> propertyAnnotations(PropertyDescriptor propertyDescriptor) {
return Stream.concat(Arrays.stream(propertyDescriptor.getReadMethod().getAnnotations()),
Arrays.stream(propertyDescriptor.getWriteMethod().getAnnotations()))
.collect(Collectors.toList());
}
private static void debugLog(Class<?> beanClass, Supplier<String> logMessage) {
BEAN_LOGGER.debug(() -> beanClass.getTypeName() + " - " + logMessage.get());
}
}
| 4,118 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper/UpdateBehavior.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.mapper;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.ThreadSafe;
/**
* Update behaviors that can be applied to individual attributes. This behavior will only apply to 'update' operations
* such as UpdateItem, and not 'put' operations such as PutItem.
* <p>
* If an update behavior is not specified for an attribute, the default behavior of {@link #WRITE_ALWAYS} will be
* applied.
*/
@SdkPublicApi
@ThreadSafe
public enum UpdateBehavior {
/**
* Always overwrite with the new value if one is provided, or remove any existing value if a null value is
* provided and 'ignoreNulls' is set to false.
* <p>
* This is the default behavior applied to all attributes unless otherwise specified.
*/
WRITE_ALWAYS,
/**
* Write the new value if there is no existing value in the persisted record or a new record is being written,
* otherwise leave the existing value.
* <p>
* IMPORTANT: If a null value is provided and 'ignoreNulls' is set to false, the attribute
* will always be removed from the persisted record as DynamoDb does not support conditional removal with this
* method.
*/
WRITE_IF_NOT_EXISTS
}
| 4,119 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper/StaticAttributeTags.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.mapper;
import java.util.Collection;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType;
import software.amazon.awssdk.enhanced.dynamodb.TableMetadata;
import software.amazon.awssdk.enhanced.dynamodb.internal.extensions.AtomicCounterTag;
import software.amazon.awssdk.enhanced.dynamodb.internal.mapper.UpdateBehaviorTag;
/**
* Common implementations of {@link StaticAttributeTag}. These tags can be used to mark your attributes as having certain
* characteristics or features, such as primary or secondary keys in your {@link StaticTableSchema} definitions.
*/
@SdkPublicApi
@ThreadSafe
public final class StaticAttributeTags {
private static final StaticAttributeTag PRIMARY_PARTITION_KEY_SINGLETON =
new KeyAttributeTag((tableMetadataBuilder, attribute) ->
tableMetadataBuilder.addIndexPartitionKey(TableMetadata.primaryIndexName(),
attribute.getAttributeName(),
attribute.getAttributeValueType()));
private static final StaticAttributeTag PRIMARY_SORT_KEY_SINGLETON =
new KeyAttributeTag((tableMetadataBuilder, attribute) ->
tableMetadataBuilder.addIndexSortKey(TableMetadata.primaryIndexName(),
attribute.getAttributeName(),
attribute.getAttributeValueType()));
private StaticAttributeTags() {
}
/**
* Marks an attribute as being the primary partition key of the table it participates in. Only one attribute can
* be marked this way in a given table schema.
*/
public static StaticAttributeTag primaryPartitionKey() {
return PRIMARY_PARTITION_KEY_SINGLETON;
}
/**
* Marks an attribute as being the primary sort key of the table it participates in. Only one attribute can be
* marked this way in a given table schema.
*/
public static StaticAttributeTag primarySortKey() {
return PRIMARY_SORT_KEY_SINGLETON;
}
/**
* Marks an attribute as being a partition key for a secondary index.
* @param indexName The name of the index this key participates in.
*/
public static StaticAttributeTag secondaryPartitionKey(String indexName) {
return new KeyAttributeTag((tableMetadataBuilder, attribute) ->
tableMetadataBuilder.addIndexPartitionKey(indexName,
attribute.getAttributeName(),
attribute.getAttributeValueType()));
}
/**
* Marks an attribute as being a partition key for multiple secondary indices.
* @param indexNames The names of the indices this key participates in.
*/
public static StaticAttributeTag secondaryPartitionKey(Collection<String> indexNames) {
return new KeyAttributeTag(
(tableMetadataBuilder, attribute) ->
indexNames.forEach(
indexName -> tableMetadataBuilder.addIndexPartitionKey(indexName,
attribute.getAttributeName(),
attribute.getAttributeValueType())));
}
/**
* Marks an attribute as being a sort key for a secondary index.
* @param indexName The name of the index this key participates in.
*/
public static StaticAttributeTag secondarySortKey(String indexName) {
return new KeyAttributeTag((tableMetadataBuilder, attribute) ->
tableMetadataBuilder.addIndexSortKey(indexName,
attribute.getAttributeName(),
attribute.getAttributeValueType()));
}
/**
* Marks an attribute as being a sort key for multiple secondary indices.
* @param indexNames The names of the indices this key participates in.
*/
public static StaticAttributeTag secondarySortKey(Collection<String> indexNames) {
return new KeyAttributeTag(
(tableMetadataBuilder, attribute) ->
indexNames.forEach(
indexName -> tableMetadataBuilder.addIndexSortKey(indexName,
attribute.getAttributeName(),
attribute.getAttributeValueType())));
}
/**
* Specifies the behavior when this attribute is updated as part of an 'update' operation such as UpdateItem. See
* documentation of {@link UpdateBehavior} for details on the different behaviors supported and the default
* behavior.
* @param updateBehavior The {@link UpdateBehavior} to be applied to this attribute
*/
public static StaticAttributeTag updateBehavior(UpdateBehavior updateBehavior) {
return UpdateBehaviorTag.fromUpdateBehavior(updateBehavior);
}
/**
* Used to explicitly designate an attribute to be an auto-generated counter updated unconditionally in DynamoDB.
* By supplying a negative integer delta value, the attribute works as a decreasing counter.
*
* @param delta The value to increment (positive) or decrement (negative) the counter with for each update.
* @param startValue The starting value of the counter.
*/
public static StaticAttributeTag atomicCounter(long delta, long startValue) {
return AtomicCounterTag.fromValues(delta, startValue);
}
/**
* Used to explicitly designate an attribute to be a default auto-generated, increasing counter updated unconditionally in
* DynamoDB. The counter will have 0 as its first written value and increment with 1 for each subsequent calls to updateItem.
* */
public static StaticAttributeTag atomicCounter() {
return AtomicCounterTag.create();
}
private static class KeyAttributeTag implements StaticAttributeTag {
private final BiConsumer<StaticTableMetadata.Builder, AttributeAndType> tableMetadataKeySetter;
private KeyAttributeTag(BiConsumer<StaticTableMetadata.Builder, AttributeAndType> tableMetadataKeySetter) {
this.tableMetadataKeySetter = tableMetadataKeySetter;
}
@Override
public Consumer<StaticTableMetadata.Builder> modifyMetadata(String attributeName,
AttributeValueType attributeValueType) {
return metadata -> {
if (attributeValueType.scalarAttributeType() == null) {
throw new IllegalArgumentException(
String.format("Attribute '%s' of type %s is not a suitable type to be used as a key.",
attributeName, attributeValueType.name()));
}
tableMetadataKeySetter.accept(metadata, new AttributeAndType(attributeName, attributeValueType));
};
}
}
private static class AttributeAndType {
private final String attributeName;
private final AttributeValueType attributeValueType;
private AttributeAndType(String attributeName, AttributeValueType attributeValueType) {
this.attributeName = attributeName;
this.attributeValueType = attributeValueType;
}
private String getAttributeName() {
return attributeName;
}
private AttributeValueType getAttributeValueType() {
return attributeValueType;
}
}
}
| 4,120 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper/StaticAttribute.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.mapper;
import java.util.Collection;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import software.amazon.awssdk.annotations.NotThreadSafe;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.enhanced.dynamodb.AttributeConverter;
import software.amazon.awssdk.enhanced.dynamodb.AttributeConverterProvider;
import software.amazon.awssdk.enhanced.dynamodb.EnhancedType;
/**
* A class that represents an attribute that can be read from and written to an mapped item. A {@link StaticTableSchema}
* composes multiple attributes that map to a common item class.
* <p>
* The recommended way to use this class is by calling {@link StaticTableSchema.Builder#addAttribute(Class, Consumer)}.
* Example:
* <pre>{@code
* StaticTableSchema.builder()
* .addAttribute(String.class,
* a -> a.name("customer_name").getter(Customer::getName).setter(Customer::setName))
* // ...
* .build();
* }</pre>
* <p>
* It's also possible to construct this class on its own using the static builder. Example:
* <pre>{@code
* StaticAttribute<Customer, ?> customerNameAttribute =
* StaticAttribute.builder(Customer.class, String.class)
* .name("customer_name")
* .getter(Customer::getName)
* .setter(Customer::setName)
* .build();
* }
* </pre>
* @param <T> the class of the item this attribute maps into.
* @param <R> the class that the value of this attribute converts to.
*/
@SdkPublicApi
@ThreadSafe
public final class StaticAttribute<T, R> {
private final ImmutableAttribute<T, T, R> delegateAttribute;
private StaticAttribute(Builder<T, R> builder) {
this.delegateAttribute = builder.delegateBuilder.build();
}
/**
* Constructs a new builder for this class using supplied types.
* @param itemClass The class of the item that this attribute composes.
* @param attributeType A {@link EnhancedType} that represents the type of the value this attribute stores.
* @return A new typed builder for an attribute.
*/
public static <T, R> Builder<T, R> builder(Class<T> itemClass, EnhancedType<R> attributeType) {
return new Builder<>(EnhancedType.of(itemClass), attributeType);
}
/**
* Constructs a new builder for this class using supplied types.
* @param itemType The {@link EnhancedType} of the item that this attribute composes.
* @param attributeType A {@link EnhancedType} that represents the type of the value this attribute stores.
* @return A new typed builder for an attribute.
*/
public static <T, R> Builder<T, R> builder(EnhancedType<T> itemType, EnhancedType<R> attributeType) {
return new Builder<>(itemType, attributeType);
}
/**
* Constructs a new builder for this class using supplied types.
* @param itemClass The class of the item that this attribute composes.
* @param attributeClass A class that represents the type of the value this attribute stores.
* @return A new typed builder for an attribute.
*/
public static <T, R> Builder<T, R> builder(Class<T> itemClass, Class<R> attributeClass) {
return new Builder<>(EnhancedType.of(itemClass), EnhancedType.of(attributeClass));
}
/**
* The name of this attribute
*/
public String name() {
return this.delegateAttribute.name();
}
/**
* A function that can get the value of this attribute from a modelled item it composes.
*/
public Function<T, R> getter() {
return this.delegateAttribute.getter();
}
/**
* A function that can set the value of this attribute on a modelled item it composes.
*/
public BiConsumer<T, R> setter() {
return this.delegateAttribute.setter();
}
/**
* A collection of {@link StaticAttributeTag} associated with this attribute.
*/
public Collection<StaticAttributeTag> tags() {
return this.delegateAttribute.tags();
}
/**
* A {@link EnhancedType} that represents the type of the value this attribute stores.
*/
public EnhancedType<R> type() {
return this.delegateAttribute.type();
}
/**
* A custom {@link AttributeConverter} that will be used to convert this attribute.
* If no custom converter was provided, the value will be null.
* @see Builder#attributeConverter
*/
public AttributeConverter<R> attributeConverter() {
return this.delegateAttribute.attributeConverter();
}
/**
* Converts an instance of this class to a {@link Builder} that can be used to modify and reconstruct it.
*/
public Builder<T, R> toBuilder() {
return new Builder<>(this.delegateAttribute.toBuilder());
}
ImmutableAttribute<T, T, R> toImmutableAttribute() {
return this.delegateAttribute;
}
/**
* A typed builder for {@link StaticAttribute}.
* @param <T> the class of the item this attribute maps into.
* @param <R> the class that the value of this attribute converts to.
*/
@NotThreadSafe
public static final class Builder<T, R> {
private final ImmutableAttribute.Builder<T, T, R> delegateBuilder;
private Builder(EnhancedType<T> itemType, EnhancedType<R> type) {
this.delegateBuilder = ImmutableAttribute.builder(itemType, itemType, type);
}
private Builder(ImmutableAttribute.Builder<T, T, R> delegateBuilder) {
this.delegateBuilder = delegateBuilder;
}
/**
* The name of this attribute
*/
public Builder<T, R> name(String name) {
this.delegateBuilder.name(name);
return this;
}
/**
* A function that can get the value of this attribute from a modelled item it composes.
*/
public Builder<T, R> getter(Function<T, R> getter) {
this.delegateBuilder.getter(getter);
return this;
}
/**
* A function that can set the value of this attribute on a modelled item it composes.
*/
public Builder<T, R> setter(BiConsumer<T, R> setter) {
this.delegateBuilder.setter(setter);
return this;
}
/**
* A collection of {@link StaticAttributeTag} associated with this attribute. Overwrites any existing tags.
*/
public Builder<T, R> tags(Collection<StaticAttributeTag> tags) {
this.delegateBuilder.tags(tags);
return this;
}
/**
* A collection of {@link StaticAttributeTag} associated with this attribute. Overwrites any existing tags.
*/
public Builder<T, R> tags(StaticAttributeTag... tags) {
this.delegateBuilder.tags(tags);
return this;
}
/**
* Associates a single {@link StaticAttributeTag} with this attribute. Adds to any existing tags.
*/
public Builder<T, R> addTag(StaticAttributeTag tag) {
this.delegateBuilder.addTag(tag);
return this;
}
/**
* An {@link AttributeConverter} for the attribute type ({@link EnhancedType}), that can convert this attribute.
* It takes precedence over any converter for this type provided by the table schema
* {@link AttributeConverterProvider}.
*/
public Builder<T, R> attributeConverter(AttributeConverter<R> attributeConverter) {
this.delegateBuilder.attributeConverter(attributeConverter);
return this;
}
/**
* Builds a {@link StaticAttributeTag} from the values stored in this builder.
*/
public StaticAttribute<T, R> build() {
return new StaticAttribute<>(this);
}
}
}
| 4,121 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper/WrappedTableSchema.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.mapper;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.enhanced.dynamodb.AttributeConverter;
import software.amazon.awssdk.enhanced.dynamodb.EnhancedType;
import software.amazon.awssdk.enhanced.dynamodb.TableMetadata;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
/**
* Base class for any {@link TableSchema} implementation that wraps and acts as a different {@link TableSchema}
* implementation.
* @param <T> The parameterized type of the {@link TableSchema} being proxied.
* @param <R> The actual type of the {@link TableSchema} being proxied.
*/
@SdkPublicApi
@ThreadSafe
public abstract class WrappedTableSchema<T, R extends TableSchema<T>> implements TableSchema<T> {
private final R delegateTableSchema;
/**
* Standard constructor.
* @param delegateTableSchema An instance of {@link TableSchema} to be wrapped and proxied by this class.
*/
protected WrappedTableSchema(R delegateTableSchema) {
this.delegateTableSchema = delegateTableSchema;
}
/**
* The delegate table schema that is wrapped and proxied by this class.
*/
protected R delegateTableSchema() {
return this.delegateTableSchema;
}
@Override
public T mapToItem(Map<String, AttributeValue> attributeMap) {
return this.delegateTableSchema.mapToItem(attributeMap);
}
@Override
public T mapToItem(Map<String, AttributeValue> attributeMap, boolean preserveEmptyObject) {
return this.delegateTableSchema.mapToItem(attributeMap, preserveEmptyObject);
}
@Override
public Map<String, AttributeValue> itemToMap(T item, boolean ignoreNulls) {
return this.delegateTableSchema.itemToMap(item, ignoreNulls);
}
@Override
public Map<String, AttributeValue> itemToMap(T item, Collection<String> attributes) {
return this.delegateTableSchema.itemToMap(item, attributes);
}
@Override
public AttributeValue attributeValue(T item, String attributeName) {
return this.delegateTableSchema.attributeValue(item, attributeName);
}
@Override
public TableMetadata tableMetadata() {
return this.delegateTableSchema.tableMetadata();
}
@Override
public EnhancedType<T> itemType() {
return this.delegateTableSchema.itemType();
}
@Override
public List<String> attributeNames() {
return this.delegateTableSchema.attributeNames();
}
@Override
public boolean isAbstract() {
return this.delegateTableSchema.isAbstract();
}
@Override
public AttributeConverter<T> converterForAttribute(Object key) {
return this.delegateTableSchema.converterForAttribute(key);
}
}
| 4,122 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper/annotations/DynamoDbSortKey.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.mapper.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.enhanced.dynamodb.internal.mapper.BeanTableSchemaAttributeTags;
/**
* Denotes this attribute as being the optional primary sort key of the DynamoDb table. This attribute must map to a
* DynamoDb scalar type (string, number or binary) to be valid.
*
* Example using {@link DynamoDbSortKey}:
* <pre>
* {@code
* @DynamoDbBean
* public class Customer {
* private String accountId;
* private int subId;
*
* @DynamoDbPartitionKey
* public String getAccountId() {
* return this.accountId;
* }
*
* public void setAccountId(String accountId) {
* this.accountId = accountId;
* }
*
* @DynamoDbSortKey
* public int getSubId() {
* return this.subId;
* }
* public void setSubId(int subId) {
* this.subId = subId;
* }
* }
* }
* </pre>
*/
@SdkPublicApi
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@BeanTableSchemaAttributeTag(BeanTableSchemaAttributeTags.class)
public @interface DynamoDbSortKey {
}
| 4,123 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper/annotations/DynamoDbBean.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.mapper.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.enhanced.dynamodb.AttributeConverter;
import software.amazon.awssdk.enhanced.dynamodb.AttributeConverterProvider;
import software.amazon.awssdk.enhanced.dynamodb.DefaultAttributeConverterProvider;
import software.amazon.awssdk.enhanced.dynamodb.mapper.BeanTableSchema;
/**
* Class level annotation that identifies this class as being a DynamoDb mappable entity. Any class used to initialize
* a {@link BeanTableSchema} must have this annotation. If a class is used as an attribute type within another
* annotated DynamoDb class, either as a document or flattened with the {@link DynamoDbFlatten} annotation, it will also
* require this annotation to work automatically without an explicit {@link AttributeConverter}.
* <p>
* <b>Attribute Converter Providers</b><br>
* Using {@link AttributeConverterProvider}s is optional and, if used, the supplied provider supersedes the default
* converter provided by the table schema.
* <p>
* Note:
* <ul>
* <li>The converter(s) must provide {@link AttributeConverter}s for all types used in the schema. </li>
* <li>The table schema DefaultAttributeConverterProvider provides standard converters for most primitive
* and common Java types. Use custom AttributeConverterProviders when you have specific needs for type conversion
* that the defaults do not cover.</li>
* <li>If you provide a list of attribute converter providers, you can add DefaultAttributeConverterProvider
* to the end of the list to fall back on the defaults.</li>
* <li>Providing an empty list {} will cause no providers to get loaded.</li>
* </ul>
*
* Example using attribute converter providers with one custom provider and the default provider:
* <pre>
* {@code
* (converterProviders = {CustomAttributeConverter.class, DefaultAttributeConverterProvider.class});
* }
* </pre>
* <p>
* Example using {@link DynamoDbBean}:
* <pre>
* {@code
* @DynamoDbBean
* public class Customer {
* private String id;
* private Instant createdOn;
*
* @DynamoDbPartitionKey
* public String getId() {
* return this.id;
* }
*
* public void setId(String id) {
* this.id = id;
* }
*
* public Instant getCreatedOn() {
* return this.createdOn;
* }
* public void setCreatedOn(Instant createdOn) {
* this.createdOn = createdOn;
* }
* }
* }
* </pre>
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@SdkPublicApi
public @interface DynamoDbBean {
Class<? extends AttributeConverterProvider>[] converterProviders()
default { DefaultAttributeConverterProvider.class };
}
| 4,124 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper/annotations/DynamoDbSecondarySortKey.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.mapper.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.enhanced.dynamodb.internal.mapper.BeanTableSchemaAttributeTags;
/**
* Denotes an optional sort key for a global or local secondary index.
*
* <p>You must also specify at least one index name. For global secondary indices, this must match an index name specified in
* a {@link DynamoDbSecondaryPartitionKey}. Any index names specified that do not have an associated
* {@link DynamoDbSecondaryPartitionKey} are treated as local secondary indexes.
*
* <p>The index name will be used if a table is created from this bean. For data-oriented operations like reads and writes, this
* name does not need to match the service-side name of the index.
*/
@SdkPublicApi
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@BeanTableSchemaAttributeTag(BeanTableSchemaAttributeTags.class)
public @interface DynamoDbSecondarySortKey {
/**
* The names of one or more local or global secondary indices that this sort key should participate in.
*
* <p>For global secondary indices, this must match an index name specified in a {@link DynamoDbSecondaryPartitionKey}. Any
* index names specified that do not have an associated {@link DynamoDbSecondaryPartitionKey} are treated as local
* secondary indexes.
*/
String[] indexNames();
}
| 4,125 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/mapper/annotations/DynamoDbFlatten.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.mapper.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import software.amazon.awssdk.annotations.SdkPublicApi;
/**
* This annotation is used to flatten all the attributes of a separate DynamoDb bean that is stored in the current bean
* object and add them as top level attributes to the record that is read and written to the database. The target bean
* to flatten must be specified as part of this annotation.
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@SdkPublicApi
public @interface DynamoDbFlatten {
/**
* @deprecated This is no longer used, the class type of the attribute will be used instead.
*/
@Deprecated
Class<?> dynamoDbBeanClass() default Object.class;
}
| 4,126 |
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,127 |
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,128 |
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,129 |
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,130 |
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,131 |
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>
* @DynamoDbBean
* public class NestedBean {
* private AbstractBean innerBean1;
* private AbstractBean innerBean2;
*
* @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,132 |
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,133 |
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,134 |
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>
* @DynamoDbBean
* public class NestedBean {
* private AbstractBean innerBean1;
* private AbstractBean innerBean2;
*
* @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,135 |
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,136 |
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,137 |
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,138 |
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,139 |
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,140 |
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,141 |
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,142 |
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,143 |
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,144 |
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,145 |
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,146 |
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,147 |
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,148 |
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,149 |
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,150 |
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,151 |
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,152 |
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,153 |
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,154 |
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,155 |
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,156 |
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,157 |
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,158 |
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,159 |
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,160 |
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,161 |
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,162 |
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,163 |
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,164 |
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,165 |
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,166 |
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,167 |
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,168 |
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,169 |
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,170 |
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,171 |
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,172 |
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,173 |
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,174 |
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,175 |
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,176 |
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,177 |
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,178 |
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,179 |
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,180 |
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,181 |
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,182 |
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,183 |
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,184 |
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,185 |
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,186 |
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,187 |
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,188 |
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,189 |
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,190 |
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,191 |
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,192 |
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,193 |
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,194 |
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,195 |
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,196 |
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,197 |
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,198 |
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,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.