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/dynamodb/internal
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/extensions/ChainExtension.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.extensions; import java.util.ArrayDeque; import java.util.Arrays; import java.util.Deque; import java.util.Iterator; import java.util.List; import java.util.Map; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClientExtension; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbExtensionContext; import software.amazon.awssdk.enhanced.dynamodb.Expression; import software.amazon.awssdk.enhanced.dynamodb.extensions.ReadModification; import software.amazon.awssdk.enhanced.dynamodb.extensions.WriteModification; import software.amazon.awssdk.enhanced.dynamodb.update.UpdateExpression; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * A meta-extension that allows multiple extensions to be chained in a specified order to act as a single composite * extension. The order in which extensions will be used depends on the operation, for write operations they will be * called in forward order, for read operations they will be called in reverse order. For example :- * * <p> * If you create a chain of three extensions: * ChainMapperExtension.create(extension1, extension2, extension3); * * <p> * When performing any kind of write operation (eg: PutItem, UpdateItem) the beforeWrite() method will be called in * forward order: * * {@literal extension1 -> extension2 -> extension3} * * <p> * So the output of extension1 will be passed into extension2, and then the output of extension2 into extension3 and * so on. For operations that read (eg: GetItem, UpdateItem) the afterRead() method will be called in reverse order: * * {@literal extension3 -> extension2 -> extension1} * * <p> * This is designed to create a layered pattern when dealing with multiple extensions. One thing to note is that * UpdateItem acts as both a write operation and a read operation so the chain will be called both ways within a * single operation. */ @SdkInternalApi public final class ChainExtension implements DynamoDbEnhancedClientExtension { private final Deque<DynamoDbEnhancedClientExtension> extensionChain; private ChainExtension(List<DynamoDbEnhancedClientExtension> extensions) { this.extensionChain = new ArrayDeque<>(extensions); } /** * Construct a new instance of {@link ChainExtension}. * @param extensions A list of {@link DynamoDbEnhancedClientExtension} to chain together. * @return A constructed {@link ChainExtension} object. */ public static ChainExtension create(DynamoDbEnhancedClientExtension... extensions) { return new ChainExtension(Arrays.asList(extensions)); } /** * Construct a new instance of {@link ChainExtension}. * @param extensions A list of {@link DynamoDbEnhancedClientExtension} to chain together. * @return A constructed {@link ChainExtension} object. */ public static ChainExtension create(List<DynamoDbEnhancedClientExtension> extensions) { return new ChainExtension(extensions); } /** * Implementation of the {@link DynamoDbEnhancedClientExtension} interface that will call all the chained extensions * in forward order, passing the results of each one to the next and coalescing the results into a single modification. * Multiple conditional statements will be separated by the string " AND ". Expression values will be coalesced * unless they conflict in which case an exception will be thrown. UpdateExpressions will be * coalesced. * * @param context A {@link DynamoDbExtensionContext.BeforeWrite} context * @return A single {@link WriteModification} representing the coalesced results of all the chained extensions. */ @Override public WriteModification beforeWrite(DynamoDbExtensionContext.BeforeWrite context) { Map<String, AttributeValue> transformedItem = null; Expression conditionalExpression = null; UpdateExpression updateExpression = null; for (DynamoDbEnhancedClientExtension extension : this.extensionChain) { Map<String, AttributeValue> itemToTransform = transformedItem == null ? context.items() : transformedItem; DynamoDbExtensionContext.BeforeWrite beforeWrite = DefaultDynamoDbExtensionContext.builder() .items(itemToTransform) .operationContext(context.operationContext()) .tableMetadata(context.tableMetadata()) .tableSchema(context.tableSchema()) .operationName(context.operationName()) .build(); WriteModification writeModification = extension.beforeWrite(beforeWrite); if (writeModification.transformedItem() != null) { transformedItem = writeModification.transformedItem(); } conditionalExpression = mergeConditionalExpressions(conditionalExpression, writeModification.additionalConditionalExpression()); updateExpression = mergeUpdateExpressions(updateExpression, writeModification.updateExpression()); } return WriteModification.builder() .transformedItem(transformedItem) .additionalConditionalExpression(conditionalExpression) .updateExpression(updateExpression) .build(); } private UpdateExpression mergeUpdateExpressions(UpdateExpression existingExpression, UpdateExpression newExpression) { if (newExpression != null) { if (existingExpression == null) { existingExpression = newExpression; } else { existingExpression = UpdateExpression.mergeExpressions(existingExpression, newExpression); } } return existingExpression; } private Expression mergeConditionalExpressions(Expression existingExpression, Expression newExpression) { if (newExpression != null) { if (existingExpression == null) { existingExpression = newExpression; } else { existingExpression = existingExpression.and(newExpression); } } return existingExpression; } /** * Implementation of the {@link DynamoDbEnhancedClientExtension} interface that will call all the chained extensions * in reverse order, passing the results of each one to the next and coalescing the results into a single modification. * * @param context A {@link DynamoDbExtensionContext.AfterRead} context * @return A single {@link ReadModification} representing the final transformation of all the chained extensions. */ @Override public ReadModification afterRead(DynamoDbExtensionContext.AfterRead context) { Map<String, AttributeValue> transformedItem = null; Iterator<DynamoDbEnhancedClientExtension> iterator = extensionChain.descendingIterator(); while (iterator.hasNext()) { Map<String, AttributeValue> itemToTransform = transformedItem == null ? context.items() : transformedItem; DynamoDbExtensionContext.AfterRead afterRead = DefaultDynamoDbExtensionContext.builder().items(itemToTransform) .operationContext(context.operationContext()) .tableMetadata(context.tableMetadata()) .tableSchema(context.tableSchema()) .build(); ReadModification readModification = iterator.next().afterRead(afterRead); if (readModification.transformedItem() != null) { transformedItem = readModification.transformedItem(); } } return ReadModification.builder() .transformedItem(transformedItem) .build(); } }
4,300
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/extensions/VersionRecordAttributeTags.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.extensions; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.enhanced.dynamodb.extensions.VersionedRecordExtension; import software.amazon.awssdk.enhanced.dynamodb.extensions.annotations.DynamoDbVersionAttribute; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTag; @SdkInternalApi public final class VersionRecordAttributeTags { private VersionRecordAttributeTags() { } public static StaticAttributeTag attributeTagFor(DynamoDbVersionAttribute annotation) { return VersionedRecordExtension.AttributeTags.versionAttribute(); } }
4,301
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/extensions/AutoGeneratedTimestampRecordAttributeTags.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.extensions; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.enhanced.dynamodb.extensions.AutoGeneratedTimestampRecordExtension; import software.amazon.awssdk.enhanced.dynamodb.extensions.annotations.DynamoDbAutoGeneratedTimestampAttribute; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTag; @SdkInternalApi public final class AutoGeneratedTimestampRecordAttributeTags { private AutoGeneratedTimestampRecordAttributeTags() { } public static StaticAttributeTag attributeTagFor(DynamoDbAutoGeneratedTimestampAttribute annotation) { return AutoGeneratedTimestampRecordExtension.AttributeTags.autoGeneratedTimestampAttribute(); } }
4,302
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/extensions/AtomicCounterTag.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.extensions; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.function.Consumer; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType; import software.amazon.awssdk.enhanced.dynamodb.TableMetadata; import software.amazon.awssdk.enhanced.dynamodb.internal.mapper.AtomicCounter; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTag; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableMetadata; @SdkInternalApi public class AtomicCounterTag implements StaticAttributeTag { public static final String CUSTOM_METADATA_KEY_PREFIX = "AtomicCounter:Counters"; private static final long DEFAULT_INCREMENT = 1L; private static final long DEFAULT_START_VALUE = 0L; private static final AtomicCounter DEFAULT_COUNTER = AtomicCounter.builder() .delta(DEFAULT_INCREMENT) .startValue(DEFAULT_START_VALUE) .build(); private final AtomicCounter counter; private AtomicCounterTag(AtomicCounter counter) { this.counter = counter; } public static AtomicCounterTag create() { return new AtomicCounterTag(DEFAULT_COUNTER); } public static AtomicCounterTag fromValues(long delta, long startValue) { return new AtomicCounterTag(AtomicCounter.builder() .delta(delta) .startValue(startValue) .build()); } @SuppressWarnings("unchecked") public static Map<String, AtomicCounter> resolve(TableMetadata tableMetadata) { return tableMetadata.customMetadataObject(CUSTOM_METADATA_KEY_PREFIX, Map.class).orElseGet(HashMap::new); } @Override public Consumer<StaticTableMetadata.Builder> modifyMetadata(String attributeName, AttributeValueType attributeValueType) { return metadata -> metadata .addCustomMetadataObject(CUSTOM_METADATA_KEY_PREFIX, Collections.singletonMap(attributeName, this.counter)) .markAttributeAsKey(attributeName, attributeValueType); } }
4,303
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/extensions/DefaultDynamoDbExtensionContext.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.extensions; import java.util.Map; import java.util.Objects; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbExtensionContext; import software.amazon.awssdk.enhanced.dynamodb.OperationContext; import software.amazon.awssdk.enhanced.dynamodb.TableMetadata; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.OperationName; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * An SDK-internal implementation of {@link DynamoDbExtensionContext.BeforeWrite} and * {@link DynamoDbExtensionContext.AfterRead}. */ @SdkInternalApi public final class DefaultDynamoDbExtensionContext implements DynamoDbExtensionContext.BeforeWrite, DynamoDbExtensionContext.AfterRead { private final Map<String, AttributeValue> items; private final OperationContext operationContext; private final TableMetadata tableMetadata; private final TableSchema<?> tableSchema; private final OperationName operationName; private DefaultDynamoDbExtensionContext(Builder builder) { this.items = builder.items; this.operationContext = builder.operationContext; this.tableMetadata = builder.tableMetadata; this.tableSchema = builder.tableSchema; this.operationName = builder.operationName != null ? builder.operationName : OperationName.NONE; } public static Builder builder() { return new Builder(); } @Override public Map<String, AttributeValue> items() { return items; } @Override public OperationContext operationContext() { return operationContext; } @Override public TableMetadata tableMetadata() { return tableMetadata; } @Override public TableSchema<?> tableSchema() { return tableSchema; } @Override public OperationName operationName() { return operationName; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DefaultDynamoDbExtensionContext that = (DefaultDynamoDbExtensionContext) o; if (!Objects.equals(items, that.items)) { return false; } if (!Objects.equals(operationContext, that.operationContext)) { return false; } if (!Objects.equals(tableMetadata, that.tableMetadata)) { return false; } if (!Objects.equals(tableSchema, that.tableSchema)) { return false; } return Objects.equals(operationName, that.operationName); } @Override public int hashCode() { int result = items != null ? items.hashCode() : 0; result = 31 * result + (operationContext != null ? operationContext.hashCode() : 0); result = 31 * result + (tableMetadata != null ? tableMetadata.hashCode() : 0); result = 31 * result + (tableSchema != null ? tableSchema.hashCode() : 0); result = 31 * result + (operationName != null ? operationName.hashCode() : 0); return result; } @NotThreadSafe public static final class Builder { private Map<String, AttributeValue> items; private OperationContext operationContext; private TableMetadata tableMetadata; private TableSchema<?> tableSchema; private OperationName operationName; public Builder items(Map<String, AttributeValue> item) { this.items = item; return this; } public Builder operationContext(OperationContext operationContext) { this.operationContext = operationContext; return this; } public Builder tableMetadata(TableMetadata tableMetadata) { this.tableMetadata = tableMetadata; return this; } public Builder tableSchema(TableSchema<?> tableSchema) { this.tableSchema = tableSchema; return this; } public Builder operationName(OperationName operationName) { this.operationName = operationName; return this; } public DefaultDynamoDbExtensionContext build() { return new DefaultDynamoDbExtensionContext(this); } } }
4,304
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/client/DefaultDynamoDbAsyncTable.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.client; import static software.amazon.awssdk.enhanced.dynamodb.internal.EnhancedClientUtils.createKeyFromItem; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbAsyncTable; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClientExtension; import software.amazon.awssdk.enhanced.dynamodb.Key; import software.amazon.awssdk.enhanced.dynamodb.TableMetadata; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.CreateTableOperation; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.DeleteItemOperation; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.DeleteTableOperation; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.DescribeTableOperation; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.GetItemOperation; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.PaginatedTableOperation; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.PutItemOperation; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.QueryOperation; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.ScanOperation; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.TableOperation; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.UpdateItemOperation; import software.amazon.awssdk.enhanced.dynamodb.model.CreateTableEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.DeleteItemEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.DeleteItemEnhancedResponse; import software.amazon.awssdk.enhanced.dynamodb.model.DescribeTableEnhancedResponse; import software.amazon.awssdk.enhanced.dynamodb.model.GetItemEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.GetItemEnhancedResponse; import software.amazon.awssdk.enhanced.dynamodb.model.PagePublisher; import software.amazon.awssdk.enhanced.dynamodb.model.PutItemEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.PutItemEnhancedResponse; import software.amazon.awssdk.enhanced.dynamodb.model.QueryConditional; import software.amazon.awssdk.enhanced.dynamodb.model.QueryEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.ScanEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.UpdateItemEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.UpdateItemEnhancedResponse; import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient; import software.amazon.awssdk.services.dynamodb.model.DescribeTableRequest; import software.amazon.awssdk.services.dynamodb.model.DescribeTableResponse; @SdkInternalApi public final class DefaultDynamoDbAsyncTable<T> implements DynamoDbAsyncTable<T> { private final DynamoDbAsyncClient dynamoDbClient; private final DynamoDbEnhancedClientExtension extension; private final TableSchema<T> tableSchema; private final String tableName; DefaultDynamoDbAsyncTable(DynamoDbAsyncClient dynamoDbClient, DynamoDbEnhancedClientExtension extension, TableSchema<T> tableSchema, String tableName) { this.dynamoDbClient = dynamoDbClient; this.extension = extension; this.tableSchema = tableSchema; this.tableName = tableName; } @Override public DynamoDbEnhancedClientExtension mapperExtension() { return this.extension; } @Override public TableSchema<T> tableSchema() { return this.tableSchema; } public DynamoDbAsyncClient dynamoDbClient() { return dynamoDbClient; } @Override public String tableName() { return tableName; } @Override public DefaultDynamoDbAsyncIndex<T> index(String indexName) { // Force a check for the existence of the index tableSchema.tableMetadata().indexPartitionKey(indexName); return new DefaultDynamoDbAsyncIndex<>(dynamoDbClient, extension, tableSchema, tableName, indexName); } @Override public CompletableFuture<Void> createTable(CreateTableEnhancedRequest request) { TableOperation<T, ?, ?, Void> operation = CreateTableOperation.create(request); return operation.executeOnPrimaryIndexAsync(tableSchema, tableName, extension, dynamoDbClient); } @Override public CompletableFuture<Void> createTable(Consumer<CreateTableEnhancedRequest.Builder> requestConsumer) { CreateTableEnhancedRequest.Builder builder = CreateTableEnhancedRequest.builder(); requestConsumer.accept(builder); return createTable(builder.build()); } @Override public CompletableFuture<Void> createTable() { return createTable(CreateTableEnhancedRequest.builder().build()); } @Override public CompletableFuture<T> deleteItem(DeleteItemEnhancedRequest request) { TableOperation<T, ?, ?, DeleteItemEnhancedResponse<T>> operation = DeleteItemOperation.create(request); return operation.executeOnPrimaryIndexAsync(tableSchema, tableName, extension, dynamoDbClient) .thenApply(DeleteItemEnhancedResponse::attributes); } @Override public CompletableFuture<T> deleteItem(Consumer<DeleteItemEnhancedRequest.Builder> requestConsumer) { DeleteItemEnhancedRequest.Builder builder = DeleteItemEnhancedRequest.builder(); requestConsumer.accept(builder); return deleteItem(builder.build()); } @Override public CompletableFuture<T> deleteItem(Key key) { return deleteItem(r -> r.key(key)); } @Override public CompletableFuture<T> deleteItem(T keyItem) { return deleteItem(keyFrom(keyItem)); } @Override public CompletableFuture<DeleteItemEnhancedResponse<T>> deleteItemWithResponse(DeleteItemEnhancedRequest request) { TableOperation<T, ?, ?, DeleteItemEnhancedResponse<T>> operation = DeleteItemOperation.create(request); return operation.executeOnPrimaryIndexAsync(tableSchema, tableName, extension, dynamoDbClient); } @Override public CompletableFuture<DeleteItemEnhancedResponse<T>> deleteItemWithResponse( Consumer<DeleteItemEnhancedRequest.Builder> requestConsumer) { DeleteItemEnhancedRequest.Builder builder = DeleteItemEnhancedRequest.builder(); requestConsumer.accept(builder); return deleteItemWithResponse(builder.build()); } @Override public CompletableFuture<T> getItem(GetItemEnhancedRequest request) { TableOperation<T, ?, ?, GetItemEnhancedResponse<T>> operation = GetItemOperation.create(request); CompletableFuture<GetItemEnhancedResponse<T>> future = operation.executeOnPrimaryIndexAsync( tableSchema, tableName, extension, dynamoDbClient ); return future.thenApply(GetItemEnhancedResponse::attributes); } @Override public CompletableFuture<T> getItem(Consumer<GetItemEnhancedRequest.Builder> requestConsumer) { GetItemEnhancedRequest.Builder builder = GetItemEnhancedRequest.builder(); requestConsumer.accept(builder); return getItem(builder.build()); } @Override public CompletableFuture<T> getItem(Key key) { return getItem(r -> r.key(key)); } @Override public CompletableFuture<T> getItem(T keyItem) { return getItem(keyFrom(keyItem)); } @Override public CompletableFuture<GetItemEnhancedResponse<T>> getItemWithResponse(GetItemEnhancedRequest request) { TableOperation<T, ?, ?, GetItemEnhancedResponse<T>> operation = GetItemOperation.create(request); return operation.executeOnPrimaryIndexAsync(tableSchema, tableName, extension, dynamoDbClient); } @Override public CompletableFuture<GetItemEnhancedResponse<T>> getItemWithResponse( Consumer<GetItemEnhancedRequest.Builder> requestConsumer) { GetItemEnhancedRequest.Builder builder = GetItemEnhancedRequest.builder(); requestConsumer.accept(builder); return getItemWithResponse(builder.build()); } @Override public PagePublisher<T> query(QueryEnhancedRequest request) { PaginatedTableOperation<T, ?, ?> operation = QueryOperation.create(request); return operation.executeOnPrimaryIndexAsync(tableSchema, tableName, extension, dynamoDbClient); } @Override public PagePublisher<T> query(Consumer<QueryEnhancedRequest.Builder> requestConsumer) { QueryEnhancedRequest.Builder builder = QueryEnhancedRequest.builder(); requestConsumer.accept(builder); return query(builder.build()); } @Override public PagePublisher<T> query(QueryConditional queryConditional) { return query(r -> r.queryConditional(queryConditional)); } @Override public CompletableFuture<Void> putItem(PutItemEnhancedRequest<T> request) { TableOperation<T, ?, ?, PutItemEnhancedResponse<T>> operation = PutItemOperation.create(request); return operation.executeOnPrimaryIndexAsync(tableSchema, tableName, extension, dynamoDbClient).thenApply(ignored -> null); } @Override public CompletableFuture<Void> putItem(Consumer<PutItemEnhancedRequest.Builder<T>> requestConsumer) { PutItemEnhancedRequest.Builder<T> builder = PutItemEnhancedRequest.builder(this.tableSchema.itemType().rawClass()); requestConsumer.accept(builder); return putItem(builder.build()); } @Override public CompletableFuture<Void> putItem(T item) { return putItem(r -> r.item(item)); } @Override public CompletableFuture<PutItemEnhancedResponse<T>> putItemWithResponse(PutItemEnhancedRequest<T> request) { TableOperation<T, ?, ?, PutItemEnhancedResponse<T>> operation = PutItemOperation.create(request); return operation.executeOnPrimaryIndexAsync(tableSchema, tableName, extension, dynamoDbClient); } @Override public CompletableFuture<PutItemEnhancedResponse<T>> putItemWithResponse( Consumer<PutItemEnhancedRequest.Builder<T>> requestConsumer) { PutItemEnhancedRequest.Builder<T> builder = PutItemEnhancedRequest.builder(this.tableSchema.itemType().rawClass()); requestConsumer.accept(builder); return putItemWithResponse(builder.build()); } @Override public PagePublisher<T> scan(ScanEnhancedRequest request) { PaginatedTableOperation<T, ?, ?> operation = ScanOperation.create(request); return operation.executeOnPrimaryIndexAsync(tableSchema, tableName, extension, dynamoDbClient); } @Override public PagePublisher<T> scan(Consumer<ScanEnhancedRequest.Builder> requestConsumer) { ScanEnhancedRequest.Builder builder = ScanEnhancedRequest.builder(); requestConsumer.accept(builder); return scan(builder.build()); } @Override public PagePublisher<T> scan() { return scan(ScanEnhancedRequest.builder().build()); } @Override public CompletableFuture<T> updateItem(UpdateItemEnhancedRequest<T> request) { TableOperation<T, ?, ?, UpdateItemEnhancedResponse<T>> operation = UpdateItemOperation.create(request); return operation.executeOnPrimaryIndexAsync(tableSchema, tableName, extension, dynamoDbClient) .thenApply(UpdateItemEnhancedResponse::attributes); } @Override public CompletableFuture<T> updateItem(Consumer<UpdateItemEnhancedRequest.Builder<T>> requestConsumer) { UpdateItemEnhancedRequest.Builder<T> builder = UpdateItemEnhancedRequest.builder(this.tableSchema.itemType().rawClass()); requestConsumer.accept(builder); return updateItem(builder.build()); } @Override public CompletableFuture<UpdateItemEnhancedResponse<T>> updateItemWithResponse(UpdateItemEnhancedRequest<T> request) { TableOperation<T, ?, ?, UpdateItemEnhancedResponse<T>> operation = UpdateItemOperation.create(request); return operation.executeOnPrimaryIndexAsync(tableSchema, tableName, extension, dynamoDbClient); } @Override public CompletableFuture<UpdateItemEnhancedResponse<T>> updateItemWithResponse( Consumer<UpdateItemEnhancedRequest.Builder<T>> requestConsumer) { UpdateItemEnhancedRequest.Builder<T> builder = UpdateItemEnhancedRequest.builder(this.tableSchema.itemType().rawClass()); requestConsumer.accept(builder); return updateItemWithResponse(builder.build()); } @Override public CompletableFuture<T> updateItem(T item) { return updateItem(r -> r.item(item)); } @Override public Key keyFrom(T item) { return createKeyFromItem(item, tableSchema, TableMetadata.primaryIndexName()); } @Override public CompletableFuture<Void> deleteTable() { TableOperation<T, ?, ?, Void> operation = DeleteTableOperation.create(); return operation.executeOnPrimaryIndexAsync(tableSchema, tableName, extension, dynamoDbClient); } @Override public CompletableFuture<DescribeTableEnhancedResponse> describeTable() { TableOperation<T, DescribeTableRequest, DescribeTableResponse, DescribeTableEnhancedResponse> operation = DescribeTableOperation.create(); return operation.executeOnPrimaryIndexAsync(tableSchema, tableName, extension, dynamoDbClient); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DefaultDynamoDbAsyncTable<?> that = (DefaultDynamoDbAsyncTable<?>) o; if (dynamoDbClient != null ? ! dynamoDbClient.equals(that.dynamoDbClient) : that.dynamoDbClient != null) { return false; } if (extension != null ? ! extension.equals(that.extension) : that.extension != null) { return false; } if (tableSchema != null ? ! tableSchema.equals(that.tableSchema) : that.tableSchema != null) { return false; } return tableName != null ? tableName.equals(that.tableName) : that.tableName == null; } @Override public int hashCode() { int result = dynamoDbClient != null ? dynamoDbClient.hashCode() : 0; result = 31 * result + (extension != null ? extension.hashCode() : 0); result = 31 * result + (tableSchema != null ? tableSchema.hashCode() : 0); result = 31 * result + (tableName != null ? tableName.hashCode() : 0); return result; } }
4,305
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/client/ExtensionResolver.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.client; import java.util.Arrays; import java.util.List; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClientExtension; import software.amazon.awssdk.enhanced.dynamodb.extensions.AtomicCounterExtension; import software.amazon.awssdk.enhanced.dynamodb.extensions.VersionedRecordExtension; import software.amazon.awssdk.enhanced.dynamodb.internal.extensions.ChainExtension; /** * Static module to assist with the initialization of an extension for a DynamoDB Enhanced Client based on supplied * configuration. */ @SdkInternalApi public final class ExtensionResolver { private static final DynamoDbEnhancedClientExtension DEFAULT_VERSIONED_RECORD_EXTENSION = VersionedRecordExtension.builder().build(); private static final DynamoDbEnhancedClientExtension DEFAULT_ATOMIC_COUNTER_EXTENSION = AtomicCounterExtension.builder().build(); private static final List<DynamoDbEnhancedClientExtension> DEFAULT_EXTENSIONS = Arrays.asList(DEFAULT_VERSIONED_RECORD_EXTENSION, DEFAULT_ATOMIC_COUNTER_EXTENSION); private ExtensionResolver() { } /** * Static provider for the default extensions that are bundled with the DynamoDB Enhanced Client. Currently this is * just the {@link software.amazon.awssdk.enhanced.dynamodb.extensions.VersionedRecordExtension}. * * These extensions will be used by default unless overridden in the enhanced client builder. */ public static List<DynamoDbEnhancedClientExtension> defaultExtensions() { return DEFAULT_EXTENSIONS; } /** * Resolves a list of extensions into a single extension. If the list is a singleton, will just return that extension * otherwise it will combine them with the {@link software.amazon.awssdk.enhanced.dynamodb.internal.extensions.ChainExtension} * meta-extension using the order provided in the list. * * @param extensions A list of extensions to be combined in strict order * @return A single extension that combines all the supplied extensions or null if no extensions were provided */ public static DynamoDbEnhancedClientExtension resolveExtensions(List<DynamoDbEnhancedClientExtension> extensions) { if (extensions == null || extensions.isEmpty()) { return null; } if (extensions.size() == 1) { return extensions.get(0); } return ChainExtension.create(extensions); } }
4,306
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/client/DefaultDynamoDbEnhancedAsyncClient.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.client; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.enhanced.dynamodb.Document; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedAsyncClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClientExtension; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.BatchGetItemOperation; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.BatchWriteItemOperation; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.TransactGetItemsOperation; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.TransactWriteItemsOperation; import software.amazon.awssdk.enhanced.dynamodb.model.BatchGetItemEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.BatchGetResultPagePublisher; import software.amazon.awssdk.enhanced.dynamodb.model.BatchWriteItemEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.BatchWriteResult; import software.amazon.awssdk.enhanced.dynamodb.model.TransactGetItemsEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.TransactWriteItemsEnhancedRequest; import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient; @SdkInternalApi public final class DefaultDynamoDbEnhancedAsyncClient implements DynamoDbEnhancedAsyncClient { private final DynamoDbAsyncClient dynamoDbClient; private final DynamoDbEnhancedClientExtension extension; private DefaultDynamoDbEnhancedAsyncClient(Builder builder) { this.dynamoDbClient = builder.dynamoDbClient == null ? DynamoDbAsyncClient.create() : builder.dynamoDbClient; this.extension = ExtensionResolver.resolveExtensions(builder.dynamoDbEnhancedClientExtensions); } public static Builder builder() { return new Builder(); } @Override public <T> DefaultDynamoDbAsyncTable<T> table(String tableName, TableSchema<T> tableSchema) { return new DefaultDynamoDbAsyncTable<>(dynamoDbClient, extension, tableSchema, tableName); } @Override public BatchGetResultPagePublisher batchGetItem(BatchGetItemEnhancedRequest request) { BatchGetItemOperation operation = BatchGetItemOperation.create(request); return BatchGetResultPagePublisher.create(operation.executeAsync(dynamoDbClient, extension)); } @Override public BatchGetResultPagePublisher batchGetItem( Consumer<BatchGetItemEnhancedRequest.Builder> requestConsumer) { BatchGetItemEnhancedRequest.Builder builder = BatchGetItemEnhancedRequest.builder(); requestConsumer.accept(builder); return batchGetItem(builder.build()); } @Override public CompletableFuture<BatchWriteResult> batchWriteItem(BatchWriteItemEnhancedRequest request) { BatchWriteItemOperation operation = BatchWriteItemOperation.create(request); return operation.executeAsync(dynamoDbClient, extension); } @Override public CompletableFuture<BatchWriteResult> batchWriteItem( Consumer<BatchWriteItemEnhancedRequest.Builder> requestConsumer) { BatchWriteItemEnhancedRequest.Builder builder = BatchWriteItemEnhancedRequest.builder(); requestConsumer.accept(builder); return batchWriteItem(builder.build()); } @Override public CompletableFuture<List<Document>> transactGetItems(TransactGetItemsEnhancedRequest request) { TransactGetItemsOperation operation = TransactGetItemsOperation.create(request); return operation.executeAsync(dynamoDbClient, extension); } @Override public CompletableFuture<List<Document>> transactGetItems( Consumer<TransactGetItemsEnhancedRequest.Builder> requestConsumer) { TransactGetItemsEnhancedRequest.Builder builder = TransactGetItemsEnhancedRequest.builder(); requestConsumer.accept(builder); return transactGetItems(builder.build()); } @Override public CompletableFuture<Void> transactWriteItems(TransactWriteItemsEnhancedRequest request) { TransactWriteItemsOperation operation = TransactWriteItemsOperation.create(request); return operation.executeAsync(dynamoDbClient, extension); } @Override public CompletableFuture<Void> transactWriteItems( Consumer<TransactWriteItemsEnhancedRequest.Builder> requestConsumer) { TransactWriteItemsEnhancedRequest.Builder builder = TransactWriteItemsEnhancedRequest.builder(); requestConsumer.accept(builder); return transactWriteItems(builder.build()); } public DynamoDbAsyncClient dynamoDbAsyncClient() { return dynamoDbClient; } public DynamoDbEnhancedClientExtension mapperExtension() { return extension; } public Builder toBuilder() { return builder().dynamoDbClient(this.dynamoDbClient).extensions(this.extension); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DefaultDynamoDbEnhancedAsyncClient that = (DefaultDynamoDbEnhancedAsyncClient) o; if (dynamoDbClient != null ? ! dynamoDbClient.equals(that.dynamoDbClient) : that.dynamoDbClient != null) { return false; } return extension != null ? extension.equals(that.extension) : that.extension == null; } @Override public int hashCode() { int result = dynamoDbClient != null ? dynamoDbClient.hashCode() : 0; result = 31 * result + (extension != null ? extension.hashCode() : 0); return result; } @NotThreadSafe public static final class Builder implements DynamoDbEnhancedAsyncClient.Builder { private DynamoDbAsyncClient dynamoDbClient; private List<DynamoDbEnhancedClientExtension> dynamoDbEnhancedClientExtensions = new ArrayList<>(ExtensionResolver.defaultExtensions()); @Override public DefaultDynamoDbEnhancedAsyncClient build() { return new DefaultDynamoDbEnhancedAsyncClient(this); } @Override public Builder dynamoDbClient(DynamoDbAsyncClient dynamoDbClient) { this.dynamoDbClient = dynamoDbClient; return this; } @Override public Builder extensions(DynamoDbEnhancedClientExtension... dynamoDbEnhancedClientExtensions) { this.dynamoDbEnhancedClientExtensions = Arrays.asList(dynamoDbEnhancedClientExtensions); return this; } @Override public Builder extensions(List<DynamoDbEnhancedClientExtension> dynamoDbEnhancedClientExtensions) { this.dynamoDbEnhancedClientExtensions = new ArrayList<>(dynamoDbEnhancedClientExtensions); return this; } } }
4,307
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/client/DefaultDynamoDbAsyncIndex.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.client; import static software.amazon.awssdk.enhanced.dynamodb.internal.EnhancedClientUtils.createKeyFromItem; import java.util.function.Consumer; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.async.SdkPublisher; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbAsyncIndex; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClientExtension; import software.amazon.awssdk.enhanced.dynamodb.Key; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.PaginatedIndexOperation; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.QueryOperation; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.ScanOperation; import software.amazon.awssdk.enhanced.dynamodb.model.Page; import software.amazon.awssdk.enhanced.dynamodb.model.QueryConditional; import software.amazon.awssdk.enhanced.dynamodb.model.QueryEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.ScanEnhancedRequest; import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient; @SdkInternalApi public final class DefaultDynamoDbAsyncIndex<T> implements DynamoDbAsyncIndex<T> { private final DynamoDbAsyncClient dynamoDbClient; private final DynamoDbEnhancedClientExtension extension; private final TableSchema<T> tableSchema; private final String tableName; private final String indexName; DefaultDynamoDbAsyncIndex(DynamoDbAsyncClient dynamoDbClient, DynamoDbEnhancedClientExtension extension, TableSchema<T> tableSchema, String tableName, String indexName) { this.dynamoDbClient = dynamoDbClient; this.extension = extension; this.tableSchema = tableSchema; this.tableName = tableName; this.indexName = indexName; } @Override public SdkPublisher<Page<T>> query(QueryEnhancedRequest request) { PaginatedIndexOperation<T, ?, ?> operation = QueryOperation.create(request); return operation.executeOnSecondaryIndexAsync(tableSchema, tableName, indexName, extension, dynamoDbClient); } @Override public SdkPublisher<Page<T>> query(Consumer<QueryEnhancedRequest.Builder> requestConsumer) { QueryEnhancedRequest.Builder builder = QueryEnhancedRequest.builder(); requestConsumer.accept(builder); return query(builder.build()); } @Override public SdkPublisher<Page<T>> query(QueryConditional queryConditional) { return query(r -> r.queryConditional(queryConditional)); } @Override public SdkPublisher<Page<T>> scan(ScanEnhancedRequest request) { PaginatedIndexOperation<T, ?, ?> operation = ScanOperation.create(request); return operation.executeOnSecondaryIndexAsync(tableSchema, tableName, indexName, extension, dynamoDbClient); } @Override public SdkPublisher<Page<T>> scan(Consumer<ScanEnhancedRequest.Builder> requestConsumer) { ScanEnhancedRequest.Builder builder = ScanEnhancedRequest.builder(); requestConsumer.accept(builder); return scan(builder.build()); } @Override public SdkPublisher<Page<T>> scan() { return scan(ScanEnhancedRequest.builder().build()); } @Override public DynamoDbEnhancedClientExtension mapperExtension() { return this.extension; } @Override public TableSchema<T> tableSchema() { return tableSchema; } public DynamoDbAsyncClient dynamoDbClient() { return dynamoDbClient; } @Override public String tableName() { return tableName; } @Override public String indexName() { return indexName; } @Override public Key keyFrom(T item) { return createKeyFromItem(item, tableSchema, indexName); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DefaultDynamoDbAsyncIndex<?> that = (DefaultDynamoDbAsyncIndex<?>) o; if (dynamoDbClient != null ? ! dynamoDbClient.equals(that.dynamoDbClient) : that.dynamoDbClient != null) { return false; } if (extension != null ? ! extension.equals(that.extension) : that.extension != null) { return false; } if (tableSchema != null ? ! tableSchema.equals(that.tableSchema) : that.tableSchema != null) { return false; } if (tableName != null ? ! tableName.equals(that.tableName) : that.tableName != null) { return false; } return indexName != null ? indexName.equals(that.indexName) : that.indexName == null; } @Override public int hashCode() { int result = dynamoDbClient != null ? dynamoDbClient.hashCode() : 0; result = 31 * result + (extension != null ? extension.hashCode() : 0); result = 31 * result + (tableSchema != null ? tableSchema.hashCode() : 0); result = 31 * result + (tableName != null ? tableName.hashCode() : 0); result = 31 * result + (indexName != null ? indexName.hashCode() : 0); return result; } }
4,308
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/client/IndexType.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.client; import software.amazon.awssdk.annotations.SdkInternalApi; /** * Enum collecting types of secondary indexes */ @SdkInternalApi public enum IndexType { LSI, GSI }
4,309
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/client/DefaultDynamoDbEnhancedClient.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.client; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.function.Consumer; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.enhanced.dynamodb.Document; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClientExtension; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.BatchGetItemOperation; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.BatchWriteItemOperation; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.TransactGetItemsOperation; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.TransactWriteItemsOperation; import software.amazon.awssdk.enhanced.dynamodb.model.BatchGetItemEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.BatchGetResultPageIterable; import software.amazon.awssdk.enhanced.dynamodb.model.BatchWriteItemEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.BatchWriteResult; import software.amazon.awssdk.enhanced.dynamodb.model.TransactGetItemsEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.TransactWriteItemsEnhancedRequest; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; @SdkInternalApi public final class DefaultDynamoDbEnhancedClient implements DynamoDbEnhancedClient { private final DynamoDbClient dynamoDbClient; private final DynamoDbEnhancedClientExtension extension; private DefaultDynamoDbEnhancedClient(Builder builder) { this.dynamoDbClient = builder.dynamoDbClient == null ? DynamoDbClient.create() : builder.dynamoDbClient; this.extension = ExtensionResolver.resolveExtensions(builder.dynamoDbEnhancedClientExtensions); } public static Builder builder() { return new Builder(); } @Override public <T> DefaultDynamoDbTable<T> table(String tableName, TableSchema<T> tableSchema) { return new DefaultDynamoDbTable<>(dynamoDbClient, extension, tableSchema, tableName); } @Override public BatchGetResultPageIterable batchGetItem(BatchGetItemEnhancedRequest request) { BatchGetItemOperation operation = BatchGetItemOperation.create(request); return BatchGetResultPageIterable.create(operation.execute(dynamoDbClient, extension)); } @Override public BatchGetResultPageIterable batchGetItem(Consumer<BatchGetItemEnhancedRequest.Builder> requestConsumer) { BatchGetItemEnhancedRequest.Builder builder = BatchGetItemEnhancedRequest.builder(); requestConsumer.accept(builder); return batchGetItem(builder.build()); } @Override public BatchWriteResult batchWriteItem(BatchWriteItemEnhancedRequest request) { BatchWriteItemOperation operation = BatchWriteItemOperation.create(request); return operation.execute(dynamoDbClient, extension); } @Override public BatchWriteResult batchWriteItem(Consumer<BatchWriteItemEnhancedRequest.Builder> requestConsumer) { BatchWriteItemEnhancedRequest.Builder builder = BatchWriteItemEnhancedRequest.builder(); requestConsumer.accept(builder); return batchWriteItem(builder.build()); } @Override public List<Document> transactGetItems(TransactGetItemsEnhancedRequest request) { TransactGetItemsOperation operation = TransactGetItemsOperation.create(request); return operation.execute(dynamoDbClient, extension); } @Override public List<Document> transactGetItems( Consumer<TransactGetItemsEnhancedRequest.Builder> requestConsumer) { TransactGetItemsEnhancedRequest.Builder builder = TransactGetItemsEnhancedRequest.builder(); requestConsumer.accept(builder); return transactGetItems(builder.build()); } @Override public Void transactWriteItems(TransactWriteItemsEnhancedRequest request) { TransactWriteItemsOperation operation = TransactWriteItemsOperation.create(request); return operation.execute(dynamoDbClient, extension); } @Override public Void transactWriteItems(Consumer<TransactWriteItemsEnhancedRequest.Builder> requestConsumer) { TransactWriteItemsEnhancedRequest.Builder builder = TransactWriteItemsEnhancedRequest.builder(); requestConsumer.accept(builder); return transactWriteItems(builder.build()); } public DynamoDbClient dynamoDbClient() { return dynamoDbClient; } public DynamoDbEnhancedClientExtension mapperExtension() { return extension; } public Builder toBuilder() { return builder().dynamoDbClient(this.dynamoDbClient).extensions(this.extension); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DefaultDynamoDbEnhancedClient that = (DefaultDynamoDbEnhancedClient) o; if (dynamoDbClient != null ? ! dynamoDbClient.equals(that.dynamoDbClient) : that.dynamoDbClient != null) { return false; } return extension != null ? extension.equals(that.extension) : that.extension == null; } @Override public int hashCode() { int result = dynamoDbClient != null ? dynamoDbClient.hashCode() : 0; result = 31 * result + (extension != null ? extension.hashCode() : 0); return result; } @NotThreadSafe public static final class Builder implements DynamoDbEnhancedClient.Builder { private DynamoDbClient dynamoDbClient; private List<DynamoDbEnhancedClientExtension> dynamoDbEnhancedClientExtensions = new ArrayList<>(ExtensionResolver.defaultExtensions()); @Override public DefaultDynamoDbEnhancedClient build() { return new DefaultDynamoDbEnhancedClient(this); } @Override public Builder dynamoDbClient(DynamoDbClient dynamoDbClient) { this.dynamoDbClient = dynamoDbClient; return this; } @Override public Builder extensions(DynamoDbEnhancedClientExtension... dynamoDbEnhancedClientExtensions) { this.dynamoDbEnhancedClientExtensions = Arrays.asList(dynamoDbEnhancedClientExtensions); return this; } @Override public Builder extensions(List<DynamoDbEnhancedClientExtension> dynamoDbEnhancedClientExtensions) { this.dynamoDbEnhancedClientExtensions = new ArrayList<>(dynamoDbEnhancedClientExtensions); return this; } } }
4,310
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/client/DefaultDynamoDbIndex.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.client; import static software.amazon.awssdk.enhanced.dynamodb.internal.EnhancedClientUtils.createKeyFromItem; import java.util.function.Consumer; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.pagination.sync.SdkIterable; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClientExtension; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbIndex; import software.amazon.awssdk.enhanced.dynamodb.Key; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.PaginatedIndexOperation; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.QueryOperation; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.ScanOperation; import software.amazon.awssdk.enhanced.dynamodb.model.Page; import software.amazon.awssdk.enhanced.dynamodb.model.QueryConditional; import software.amazon.awssdk.enhanced.dynamodb.model.QueryEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.ScanEnhancedRequest; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; @SdkInternalApi public class DefaultDynamoDbIndex<T> implements DynamoDbIndex<T> { private final DynamoDbClient dynamoDbClient; private final DynamoDbEnhancedClientExtension extension; private final TableSchema<T> tableSchema; private final String tableName; private final String indexName; DefaultDynamoDbIndex(DynamoDbClient dynamoDbClient, DynamoDbEnhancedClientExtension extension, TableSchema<T> tableSchema, String tableName, String indexName) { this.dynamoDbClient = dynamoDbClient; this.extension = extension; this.tableSchema = tableSchema; this.tableName = tableName; this.indexName = indexName; } @Override public SdkIterable<Page<T>> query(QueryEnhancedRequest request) { PaginatedIndexOperation<T, ?, ?> operation = QueryOperation.create(request); return operation.executeOnSecondaryIndex(tableSchema, tableName, indexName, extension, dynamoDbClient); } @Override public SdkIterable<Page<T>> query(Consumer<QueryEnhancedRequest.Builder> requestConsumer) { QueryEnhancedRequest.Builder builder = QueryEnhancedRequest.builder(); requestConsumer.accept(builder); return query(builder.build()); } @Override public SdkIterable<Page<T>> query(QueryConditional queryConditional) { return query(r -> r.queryConditional(queryConditional)); } @Override public SdkIterable<Page<T>> scan(ScanEnhancedRequest request) { PaginatedIndexOperation<T, ?, ?> operation = ScanOperation.create(request); return operation.executeOnSecondaryIndex(tableSchema, tableName, indexName, extension, dynamoDbClient); } @Override public SdkIterable<Page<T>> scan(Consumer<ScanEnhancedRequest.Builder> requestConsumer) { ScanEnhancedRequest.Builder builder = ScanEnhancedRequest.builder(); requestConsumer.accept(builder); return scan(builder.build()); } @Override public SdkIterable<Page<T>> scan() { return scan(ScanEnhancedRequest.builder().build()); } @Override public DynamoDbEnhancedClientExtension mapperExtension() { return this.extension; } @Override public TableSchema<T> tableSchema() { return tableSchema; } public DynamoDbClient dynamoDbClient() { return dynamoDbClient; } @Override public String tableName() { return tableName; } @Override public String indexName() { return indexName; } @Override public Key keyFrom(T item) { return createKeyFromItem(item, tableSchema, indexName); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DefaultDynamoDbIndex<?> that = (DefaultDynamoDbIndex<?>) o; if (dynamoDbClient != null ? ! dynamoDbClient.equals(that.dynamoDbClient) : that.dynamoDbClient != null) { return false; } if (extension != null ? ! extension.equals(that.extension) : that.extension != null) { return false; } if (tableSchema != null ? ! tableSchema.equals(that.tableSchema) : that.tableSchema != null) { return false; } if (tableName != null ? ! tableName.equals(that.tableName) : that.tableName != null) { return false; } return indexName != null ? indexName.equals(that.indexName) : that.indexName == null; } @Override public int hashCode() { int result = dynamoDbClient != null ? dynamoDbClient.hashCode() : 0; result = 31 * result + (extension != null ? extension.hashCode() : 0); result = 31 * result + (tableSchema != null ? tableSchema.hashCode() : 0); result = 31 * result + (tableName != null ? tableName.hashCode() : 0); result = 31 * result + (indexName != null ? indexName.hashCode() : 0); return result; } }
4,311
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/internal/client/DefaultDynamoDbTable.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.internal.client; import static java.util.Collections.emptyList; import static software.amazon.awssdk.enhanced.dynamodb.internal.EnhancedClientUtils.createKeyFromItem; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.function.Consumer; import java.util.stream.Collectors; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClientExtension; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.IndexMetadata; import software.amazon.awssdk.enhanced.dynamodb.Key; import software.amazon.awssdk.enhanced.dynamodb.KeyAttributeMetadata; import software.amazon.awssdk.enhanced.dynamodb.TableMetadata; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.CreateTableOperation; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.DeleteItemOperation; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.DeleteTableOperation; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.DescribeTableOperation; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.GetItemOperation; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.PaginatedTableOperation; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.PutItemOperation; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.QueryOperation; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.ScanOperation; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.TableOperation; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.UpdateItemOperation; import software.amazon.awssdk.enhanced.dynamodb.model.CreateTableEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.DeleteItemEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.DeleteItemEnhancedResponse; import software.amazon.awssdk.enhanced.dynamodb.model.DescribeTableEnhancedResponse; import software.amazon.awssdk.enhanced.dynamodb.model.EnhancedGlobalSecondaryIndex; import software.amazon.awssdk.enhanced.dynamodb.model.EnhancedLocalSecondaryIndex; import software.amazon.awssdk.enhanced.dynamodb.model.GetItemEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.GetItemEnhancedResponse; import software.amazon.awssdk.enhanced.dynamodb.model.PageIterable; import software.amazon.awssdk.enhanced.dynamodb.model.PutItemEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.PutItemEnhancedResponse; import software.amazon.awssdk.enhanced.dynamodb.model.QueryConditional; import software.amazon.awssdk.enhanced.dynamodb.model.QueryEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.ScanEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.UpdateItemEnhancedRequest; import software.amazon.awssdk.enhanced.dynamodb.model.UpdateItemEnhancedResponse; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.DescribeTableRequest; import software.amazon.awssdk.services.dynamodb.model.DescribeTableResponse; import software.amazon.awssdk.services.dynamodb.model.ProjectionType; @SdkInternalApi public class DefaultDynamoDbTable<T> implements DynamoDbTable<T> { private final DynamoDbClient dynamoDbClient; private final DynamoDbEnhancedClientExtension extension; private final TableSchema<T> tableSchema; private final String tableName; DefaultDynamoDbTable(DynamoDbClient dynamoDbClient, DynamoDbEnhancedClientExtension extension, TableSchema<T> tableSchema, String tableName) { this.dynamoDbClient = dynamoDbClient; this.extension = extension; this.tableSchema = tableSchema; this.tableName = tableName; } @Override public DynamoDbEnhancedClientExtension mapperExtension() { return this.extension; } @Override public TableSchema<T> tableSchema() { return this.tableSchema; } public DynamoDbClient dynamoDbClient() { return dynamoDbClient; } @Override public String tableName() { return tableName; } @Override public DefaultDynamoDbIndex<T> index(String indexName) { // Force a check for the existence of the index tableSchema.tableMetadata().indexPartitionKey(indexName); return new DefaultDynamoDbIndex<>(dynamoDbClient, extension, tableSchema, tableName, indexName); } @Override public void createTable(CreateTableEnhancedRequest request) { TableOperation<T, ?, ?, Void> operation = CreateTableOperation.create(request); operation.executeOnPrimaryIndex(tableSchema, tableName, extension, dynamoDbClient); } @Override public void createTable(Consumer<CreateTableEnhancedRequest.Builder> requestConsumer) { CreateTableEnhancedRequest.Builder builder = CreateTableEnhancedRequest.builder(); requestConsumer.accept(builder); createTable(builder.build()); } @Override public void createTable() { Map<IndexType, List<IndexMetadata>> indexGroups = splitSecondaryIndicesToLocalAndGlobalOnes(); createTable(CreateTableEnhancedRequest.builder() .localSecondaryIndices(extractLocalSecondaryIndices(indexGroups)) .globalSecondaryIndices(extractGlobalSecondaryIndices(indexGroups)) .build()); } private Map<IndexType, List<IndexMetadata>> splitSecondaryIndicesToLocalAndGlobalOnes() { Collection<IndexMetadata> indices = tableSchema.tableMetadata().indices(); return indices.stream() .filter(index -> !TableMetadata.primaryIndexName().equals(index.name())) .collect(Collectors.groupingBy(metadata -> { String partitionKeyName = metadata.partitionKey().map(KeyAttributeMetadata::name).orElse(null); if (partitionKeyName == null) { return IndexType.LSI; } return IndexType.GSI; })); } private List<EnhancedLocalSecondaryIndex> extractLocalSecondaryIndices(Map<IndexType, List<IndexMetadata>> indicesGroups) { return indicesGroups.getOrDefault(IndexType.LSI, emptyList()).stream() .map(this::mapIndexMetadataToEnhancedLocalSecondaryIndex) .collect(Collectors.toList()); } private EnhancedLocalSecondaryIndex mapIndexMetadataToEnhancedLocalSecondaryIndex(IndexMetadata indexMetadata) { return EnhancedLocalSecondaryIndex.builder() .indexName(indexMetadata.name()) .projection(pb -> pb.projectionType(ProjectionType.ALL)) .build(); } private List<EnhancedGlobalSecondaryIndex> extractGlobalSecondaryIndices(Map<IndexType, List<IndexMetadata>> indicesGroups) { return indicesGroups.getOrDefault(IndexType.GSI, emptyList()).stream() .map(this::mapIndexMetadataToEnhancedGlobalSecondaryIndex) .collect(Collectors.toList()); } private EnhancedGlobalSecondaryIndex mapIndexMetadataToEnhancedGlobalSecondaryIndex(IndexMetadata indexMetadata) { return EnhancedGlobalSecondaryIndex.builder() .indexName(indexMetadata.name()) .projection(pb -> pb.projectionType(ProjectionType.ALL)) .build(); } @Override public T deleteItem(DeleteItemEnhancedRequest request) { TableOperation<T, ?, ?, DeleteItemEnhancedResponse<T>> operation = DeleteItemOperation.create(request); return operation.executeOnPrimaryIndex(tableSchema, tableName, extension, dynamoDbClient).attributes(); } @Override public T deleteItem(Consumer<DeleteItemEnhancedRequest.Builder> requestConsumer) { DeleteItemEnhancedRequest.Builder builder = DeleteItemEnhancedRequest.builder(); requestConsumer.accept(builder); return deleteItem(builder.build()); } @Override public T deleteItem(Key key) { return deleteItem(r -> r.key(key)); } @Override public T deleteItem(T keyItem) { return deleteItem(keyFrom(keyItem)); } @Override public DeleteItemEnhancedResponse<T> deleteItemWithResponse(DeleteItemEnhancedRequest request) { TableOperation<T, ?, ?, DeleteItemEnhancedResponse<T>> operation = DeleteItemOperation.create(request); return operation.executeOnPrimaryIndex(tableSchema, tableName, extension, dynamoDbClient); } @Override public DeleteItemEnhancedResponse<T> deleteItemWithResponse(Consumer<DeleteItemEnhancedRequest.Builder> requestConsumer) { DeleteItemEnhancedRequest.Builder builder = DeleteItemEnhancedRequest.builder(); requestConsumer.accept(builder); return deleteItemWithResponse(builder.build()); } @Override public T getItem(GetItemEnhancedRequest request) { TableOperation<T, ?, ?, GetItemEnhancedResponse<T>> operation = GetItemOperation.create(request); return operation.executeOnPrimaryIndex(tableSchema, tableName, extension, dynamoDbClient).attributes(); } @Override public T getItem(Consumer<GetItemEnhancedRequest.Builder> requestConsumer) { GetItemEnhancedRequest.Builder builder = GetItemEnhancedRequest.builder(); requestConsumer.accept(builder); return getItem(builder.build()); } @Override public T getItem(Key key) { return getItem(r -> r.key(key)); } @Override public T getItem(T keyItem) { return getItem(keyFrom(keyItem)); } @Override public GetItemEnhancedResponse<T> getItemWithResponse(Consumer<GetItemEnhancedRequest.Builder> requestConsumer) { GetItemEnhancedRequest.Builder builder = GetItemEnhancedRequest.builder(); requestConsumer.accept(builder); return getItemWithResponse(builder.build()); } @Override public GetItemEnhancedResponse<T> getItemWithResponse(GetItemEnhancedRequest request) { TableOperation<T, ?, ?, GetItemEnhancedResponse<T>> operation = GetItemOperation.create(request); return operation.executeOnPrimaryIndex(tableSchema, tableName, extension, dynamoDbClient); } @Override public PageIterable<T> query(QueryEnhancedRequest request) { PaginatedTableOperation<T, ?, ?> operation = QueryOperation.create(request); return operation.executeOnPrimaryIndex(tableSchema, tableName, extension, dynamoDbClient); } @Override public PageIterable<T> query(Consumer<QueryEnhancedRequest.Builder> requestConsumer) { QueryEnhancedRequest.Builder builder = QueryEnhancedRequest.builder(); requestConsumer.accept(builder); return query(builder.build()); } @Override public PageIterable<T> query(QueryConditional queryConditional) { return query(r -> r.queryConditional(queryConditional)); } @Override public void putItem(PutItemEnhancedRequest<T> request) { TableOperation<T, ?, ?, PutItemEnhancedResponse<T>> operation = PutItemOperation.create(request); operation.executeOnPrimaryIndex(tableSchema, tableName, extension, dynamoDbClient); } @Override public void putItem(Consumer<PutItemEnhancedRequest.Builder<T>> requestConsumer) { PutItemEnhancedRequest.Builder<T> builder = PutItemEnhancedRequest.builder(this.tableSchema.itemType().rawClass()); requestConsumer.accept(builder); putItem(builder.build()); } @Override public void putItem(T item) { putItem(r -> r.item(item)); } @Override public PutItemEnhancedResponse<T> putItemWithResponse(PutItemEnhancedRequest<T> request) { TableOperation<T, ?, ?, PutItemEnhancedResponse<T>> operation = PutItemOperation.create(request); return operation.executeOnPrimaryIndex(tableSchema, tableName, extension, dynamoDbClient); } @Override public PutItemEnhancedResponse<T> putItemWithResponse(Consumer<PutItemEnhancedRequest.Builder<T>> requestConsumer) { PutItemEnhancedRequest.Builder<T> builder = PutItemEnhancedRequest.builder(this.tableSchema.itemType().rawClass()); requestConsumer.accept(builder); return putItemWithResponse(builder.build()); } @Override public PageIterable<T> scan(ScanEnhancedRequest request) { PaginatedTableOperation<T, ?, ?> operation = ScanOperation.create(request); return operation.executeOnPrimaryIndex(tableSchema, tableName, extension, dynamoDbClient); } @Override public PageIterable<T> scan(Consumer<ScanEnhancedRequest.Builder> requestConsumer) { ScanEnhancedRequest.Builder builder = ScanEnhancedRequest.builder(); requestConsumer.accept(builder); return scan(builder.build()); } @Override public PageIterable<T> scan() { return scan(ScanEnhancedRequest.builder().build()); } @Override public T updateItem(UpdateItemEnhancedRequest<T> request) { TableOperation<T, ?, ?, UpdateItemEnhancedResponse<T>> operation = UpdateItemOperation.create(request); return operation.executeOnPrimaryIndex(tableSchema, tableName, extension, dynamoDbClient).attributes(); } @Override public T updateItem(Consumer<UpdateItemEnhancedRequest.Builder<T>> requestConsumer) { UpdateItemEnhancedRequest.Builder<T> builder = UpdateItemEnhancedRequest.builder(this.tableSchema.itemType().rawClass()); requestConsumer.accept(builder); return updateItem(builder.build()); } @Override public T updateItem(T item) { return updateItem(r -> r.item(item)); } @Override public UpdateItemEnhancedResponse<T> updateItemWithResponse(UpdateItemEnhancedRequest<T> request) { TableOperation<T, ?, ?, UpdateItemEnhancedResponse<T>> operation = UpdateItemOperation.create(request); return operation.executeOnPrimaryIndex(tableSchema, tableName, extension, dynamoDbClient); } @Override public UpdateItemEnhancedResponse<T> updateItemWithResponse(Consumer<UpdateItemEnhancedRequest.Builder<T>> requestConsumer) { UpdateItemEnhancedRequest.Builder<T> builder = UpdateItemEnhancedRequest.builder(this.tableSchema.itemType().rawClass()); requestConsumer.accept(builder); return updateItemWithResponse(builder.build()); } @Override public Key keyFrom(T item) { return createKeyFromItem(item, tableSchema, TableMetadata.primaryIndexName()); } @Override public void deleteTable() { TableOperation<T, ?, ?, Void> operation = DeleteTableOperation.create(); operation.executeOnPrimaryIndex(tableSchema, tableName, extension, dynamoDbClient); } @Override public DescribeTableEnhancedResponse describeTable() { TableOperation<T, DescribeTableRequest, DescribeTableResponse, DescribeTableEnhancedResponse> operation = DescribeTableOperation.create(); return operation.executeOnPrimaryIndex(tableSchema, tableName, extension, dynamoDbClient); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DefaultDynamoDbTable<?> that = (DefaultDynamoDbTable<?>) o; if (dynamoDbClient != null ? ! dynamoDbClient.equals(that.dynamoDbClient) : that.dynamoDbClient != null) { return false; } if (extension != null ? !extension.equals(that.extension) : that.extension != null) { return false; } if (tableSchema != null ? ! tableSchema.equals(that.tableSchema) : that.tableSchema != null) { return false; } return tableName != null ? tableName.equals(that.tableName) : that.tableName == null; } @Override public int hashCode() { int result = dynamoDbClient != null ? dynamoDbClient.hashCode() : 0; result = 31 * result + (extension != null ? extension.hashCode() : 0); result = 31 * result + (tableSchema != null ? tableSchema.hashCode() : 0); result = 31 * result + (tableName != null ? tableName.hashCode() : 0); return result; } }
4,312
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/document/DocumentTableSchema.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.document; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.enhanced.dynamodb.AttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.AttributeConverterProvider; import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType; import software.amazon.awssdk.enhanced.dynamodb.DefaultAttributeConverterProvider; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.TableMetadata; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.internal.converter.ConverterProviderResolver; import software.amazon.awssdk.enhanced.dynamodb.internal.document.DefaultEnhancedDocument; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticImmutableTableSchema; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableMetadata; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * Implementation of {@link TableSchema} that builds a table schema based on DynamoDB Items. * <p> * In Amazon DynamoDB, an item is a collection of attributes. Each attribute has a name and a value. An attribute value can be a * scalar, a set, or a document type * <p> * A DocumentTableSchema is used to create a {@link DynamoDbTable} which provides read and writes access to DynamoDB table as * {@link EnhancedDocument}. * <p> DocumentTableSchema specifying primaryKey, sortKey and a customAttributeConverter can be created as below * {@snippet : * DocumentTableSchema documentTableSchema = DocumentTableSchema.builder() * .addIndexPartitionKey("sampleIndexName", "sampleHashKey", AttributeValueType.S) * .addIndexSortKey("sampleIndexName", "sampleSortKey", AttributeValueType.S) * .attributeConverterProviders(customAttributeConverter, AttributeConverterProvider.defaultProvider()) * .build(); *} * <p> DocumentTableSchema can also be created without specifying primaryKey and sortKey in which cases the * {@link TableMetadata} of DocumentTableSchema will error if we try to access attributes from metaData. Also if * attributeConverterProviders are not provided then {@link DefaultAttributeConverterProvider} will be used * {@snippet : * DocumentTableSchema documentTableSchema = DocumentTableSchema.builder().build(); *} * * @see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html" target="_top">Working * with items and attributes</a> */ @SdkPublicApi public final class DocumentTableSchema implements TableSchema<EnhancedDocument> { private final TableMetadata tableMetadata; private final List<AttributeConverterProvider> attributeConverterProviders; private DocumentTableSchema(Builder builder) { this.attributeConverterProviders = builder.attributeConverterProviders; this.tableMetadata = builder.staticTableMetaDataBuilder.build(); } public static Builder builder() { return new Builder(); } @Override public EnhancedDocument mapToItem(Map<String, AttributeValue> attributeMap) { if (attributeMap == null) { return null; } DefaultEnhancedDocument.DefaultBuilder builder = (DefaultEnhancedDocument.DefaultBuilder) DefaultEnhancedDocument.builder(); attributeMap.forEach(builder::putObject); return builder.attributeConverterProviders(attributeConverterProviders) .build(); } /** * {@inheritDoc} * * This flag does not have significance for the Document API, unlike Java objects where the default value of an undefined * Object is null.In contrast to mapped classes, where a schema is present, the DocumentSchema is unaware of the entire * schema.Therefore, if an attribute is not present, it signifies that it is null, and there is no need to handle it in a * separate way.However, if the user explicitly wants to nullify certain attributes, then the user needs to set those * attributes as null in the Document that needs to be updated. * */ @Override public Map<String, AttributeValue> itemToMap(EnhancedDocument item, boolean ignoreNulls) { if (item == null) { return null; } List<AttributeConverterProvider> providers = mergeAttributeConverterProviders(item); return item.toBuilder().attributeConverterProviders(providers).build().toMap(); } private List<AttributeConverterProvider> mergeAttributeConverterProviders(EnhancedDocument item) { if (item.attributeConverterProviders() != null && !item.attributeConverterProviders().isEmpty()) { Set<AttributeConverterProvider> providers = new LinkedHashSet<>(); providers.addAll(item.attributeConverterProviders()); providers.addAll(attributeConverterProviders); return providers.stream().collect(Collectors.toList()); } return attributeConverterProviders; } @Override public Map<String, AttributeValue> itemToMap(EnhancedDocument item, Collection<String> attributes) { if (item.toMap() == null) { return null; } List<AttributeConverterProvider> providers = mergeAttributeConverterProviders(item); return item.toBuilder().attributeConverterProviders(providers).build().toMap().entrySet() .stream() .filter(entry -> attributes.contains(entry.getKey())) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (left, right) -> left, LinkedHashMap::new)); } @Override public AttributeValue attributeValue(EnhancedDocument item, String attributeName) { if (item == null) { return null; } List<AttributeConverterProvider> providers = mergeAttributeConverterProviders(item); return item.toBuilder() .attributeConverterProviders(providers) .build() .toMap() .get(attributeName); } @Override public TableMetadata tableMetadata() { return tableMetadata; } @Override public EnhancedType<EnhancedDocument> itemType() { return EnhancedType.of(EnhancedDocument.class); } @Override public List<String> attributeNames() { return tableMetadata.keyAttributes().stream().map(key -> key.name()).collect(Collectors.toList()); } @Override public boolean isAbstract() { return false; } @NotThreadSafe public static final class Builder { private final StaticTableMetadata.Builder staticTableMetaDataBuilder = StaticTableMetadata.builder(); /** * By Default the defaultConverterProvider is used for converting AttributeValue to primitive types. */ private List<AttributeConverterProvider> attributeConverterProviders = Collections.singletonList(ConverterProviderResolver.defaultConverterProvider()); /** * Adds information about a partition key associated with a specific index. * * @param indexName the name of the index to associate the partition key with * @param attributeName the name of the attribute that represents the partition key * @param attributeValueType the {@link AttributeValueType} of the partition key * @throws IllegalArgumentException if a partition key has already been defined for this index */ public Builder addIndexPartitionKey(String indexName, String attributeName, AttributeValueType attributeValueType) { staticTableMetaDataBuilder.addIndexPartitionKey(indexName, attributeName, attributeValueType); return this; } /** * Adds information about a sort key associated with a specific index. * * @param indexName the name of the index to associate the sort key with * @param attributeName the name of the attribute that represents the sort key * @param attributeValueType the {@link AttributeValueType} of the sort key * @throws IllegalArgumentException if a sort key has already been defined for this index */ public Builder addIndexSortKey(String indexName, String attributeName, AttributeValueType attributeValueType) { staticTableMetaDataBuilder.addIndexSortKey(indexName, attributeName, attributeValueType); return this; } /** * Specifies the {@link AttributeConverterProvider}s to use with the table schema. The list of attribute converter * providers must provide {@link AttributeConverter}s for Custom types. The attribute converter providers will be loaded * in the strict order they are supplied here. * <p> * By default, {@link DefaultAttributeConverterProvider} will be used, and it will provide standard converters for most * primitive and common Java types. Configuring this will override the default behavior, so it is recommended to always * append `DefaultAttributeConverterProvider` when you configure the custom attribute converter providers. * <p> * {@snippet : * builder.attributeConverterProviders(customAttributeConverter, AttributeConverterProvider.defaultProvider()); *} * * @param attributeConverterProviders a list of attribute converter providers to use with the table schema */ public Builder attributeConverterProviders(AttributeConverterProvider... attributeConverterProviders) { this.attributeConverterProviders = Arrays.asList(attributeConverterProviders); return this; } /** * Specifies the {@link AttributeConverterProvider}s to use with the table schema. The list of attribute converter * providers must provide {@link AttributeConverter}s for all types used in the schema. The attribute converter providers * will be loaded in the strict order they are supplied here. * <p> * By default, {@link DefaultAttributeConverterProvider} will be used, and it will provide standard converters for most * primitive and common Java types. Configuring this will override the default behavior, so it is recommended to always * append `DefaultAttributeConverterProvider` when you configure the custom attribute converter providers. * <p> * {@snippet : * List<AttributeConverterProvider> providers = new ArrayList<>( customAttributeConverter, * AttributeConverterProvider.defaultProvider()); * builder.attributeConverterProviders(providers); *} * * @param attributeConverterProviders a list of attribute converter providers to use with the table schema */ public Builder attributeConverterProviders(List<AttributeConverterProvider> attributeConverterProviders) { this.attributeConverterProviders = new ArrayList<>(attributeConverterProviders); return this; } /** * Builds a {@link StaticImmutableTableSchema} based on the values this builder has been configured with */ public DocumentTableSchema build() { return new DocumentTableSchema(this); } } }
4,313
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/document/EnhancedDocument.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.document; import static software.amazon.awssdk.enhanced.dynamodb.AttributeConverterProvider.defaultProvider; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.SdkNumber; import software.amazon.awssdk.enhanced.dynamodb.AttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.AttributeConverterProvider; import software.amazon.awssdk.enhanced.dynamodb.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.internal.document.DefaultEnhancedDocument; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.utils.Validate; /** * Interface representing the Document API for DynamoDB. The Document API operations are designed to work with open content, * such as data with no fixed schema, data that cannot be modeled using rigid types, or data that has a schema. * This interface provides all the methods required to access a Document, as well as constructor methods for creating a * Document that can be used to read and write to DynamoDB using the EnhancedDynamoDB client. * Additionally, this interface provides flexibility when working with data, as it allows you to work with data that is not * necessarily tied to a specific data model. * The EnhancedDocument interface provides two ways to use AttributeConverterProviders: * <p>Enhanced Document with default attribute Converter to convert the attribute of DDB item to basic default primitive types in * Java * {@snippet : * EnhancedDocument enhancedDocument = EnhancedDocument.builder().attributeConverterProviders(AttributeConverterProvider * .defaultProvider()).build(); *} * <p>Enhanced Document with Custom attribute Converter to convert the attribute of DDB Item to Custom Type. * {@snippet : * // CustomAttributeConverterProvider.create() is an example for some Custom converter provider * EnhancedDocument enhancedDocumentWithCustomConverter = EnhancedDocument.builder().attributeConverterProviders * (CustomAttributeConverterProvider.create(), AttributeConverterProvide.defaultProvider() * .put("customObject", customObject, EnhancedType.of(CustomClass.class)) * .build(); *} * <p>Enhanced Document can be created with Json as input using Static factory method.In this case it used * defaultConverterProviders. * {@snippet : * EnhancedDocument enhancedDocumentWithCustomConverter = EnhancedDocument.fromJson("{\"k\":\"v\"}"); *} * The attribute converter are always required to be provided, thus for default conversion * {@link AttributeConverterProvider#defaultProvider()} must be supplied. */ @SdkPublicApi public interface EnhancedDocument { /** * Creates a new <code>EnhancedDocument</code> instance from a JSON string. * The {@link AttributeConverterProvider#defaultProvider()} is used as the default ConverterProvider. * To use a custom ConverterProvider, use the builder methods: {@link Builder#json(String)} to supply the JSON string, * then use {@link Builder#attributeConverterProviders(AttributeConverterProvider...)} to provide the custom * ConverterProvider. * {@snippet : * EnhancedDocument documentFromJson = EnhancedDocument.fromJson("{\"key\": \"Value\"}"); *} * @param json The JSON string representation of a DynamoDB Item. * @return A new instance of EnhancedDocument. * @throws IllegalArgumentException if the json parameter is null */ static EnhancedDocument fromJson(String json) { Validate.paramNotNull(json, "json"); return DefaultEnhancedDocument.builder() .json(json) .attributeConverterProviders(defaultProvider()) .build(); } /** * Creates a new <code>EnhancedDocument</code> instance from a AttributeValue Map. * The {@link AttributeConverterProvider#defaultProvider()} is used as the default ConverterProvider. * Example usage: * {@snippet : * EnhancedDocument documentFromJson = EnhancedDocument.fromAttributeValueMap(stringKeyAttributeValueMao)}); *} * @param attributeValueMap - Map with Attributes as String keys and AttributeValue as Value. * @return A new instance of EnhancedDocument. * @throws IllegalArgumentException if the json parameter is null */ static EnhancedDocument fromAttributeValueMap(Map<String, AttributeValue> attributeValueMap) { Validate.paramNotNull(attributeValueMap, "attributeValueMap"); return DefaultEnhancedDocument.builder() .attributeValueMap(attributeValueMap) .attributeConverterProviders(defaultProvider()) .build(); } /** * Creates a default builder for {@link EnhancedDocument}. */ static Builder builder() { return DefaultEnhancedDocument.builder(); } /** * Converts an existing EnhancedDocument into a builder object that can be used to modify its values and then create a new * EnhancedDocument. * * @return A {@link EnhancedDocument.Builder} initialized with the values of this EnhancedDocument. */ Builder toBuilder(); /** * Checks if the document is a {@code null} value. * * @param attributeName Name of the attribute that needs to be checked. * @return true if the specified attribute exists with a null value; false otherwise. */ boolean isNull(String attributeName); /** * Checks if the attribute exists in the document. * * @param attributeName Name of the attribute that needs to be checked. * @return true if the specified attribute exists with a null/non-null value; false otherwise. */ boolean isPresent(String attributeName); /** * Returns the value of the specified attribute in the current document as a specified {@link EnhancedType}; or null if the * attribute either doesn't exist or the attribute value is null. * <p> * <b>Retrieving String Type for a document</b> * {@snippet : * String resultCustom = document.get("key", EnhancedType.of(String.class)); * } * <b>Retrieving Custom Type for which Convertor Provider was defined while creating the document</b> * {@snippet : * Custom resultCustom = document.get("key", EnhancedType.of(Custom.class)); * } * <b>Retrieving list of strings in a document</b> * {@snippet : * List<String> resultList = document.get("key", EnhancedType.listOf(String.class)); * } * <b>Retrieving a Map with List of strings in its values</b> * {@snippet : * Map<String, List<String>>> resultNested = document.get("key", new EnhancedType<Map<String, List<String>>>(){}); * } * </p> * @param attributeName Name of the attribute. * @param type EnhancedType of the value * @param <T> The type of the attribute value. * @return Attribute value of type T * } */ <T> T get(String attributeName, EnhancedType<T> type); /** * Returns the value of the specified attribute in the current document as a specified class type; or null if the * attribute either doesn't exist or the attribute value is null. * <p> * <b>Retrieving String Type for a document</b> * {@snippet : * String resultCustom = document.get("key", String.class); * } * <b>Retrieving Custom Type for which Convertor Provider was defined while creating the document</b> * {@snippet : * Custom resultCustom = document.get("key", Custom.class); * } * <p> * Note : * This API should not be used to retrieve values of List and Map types. * Instead, getList and getMap APIs should be used to retrieve attributes of type List and Map, respectively. * </p> * @param attributeName Name of the attribute. * @param clazz Class type of value. * @param <T> The type of the attribute value. * @return Attribute value of type T * } */ <T> T get(String attributeName, Class<T> clazz); /** * Gets the String value of specified attribute in the document. * * @param attributeName Name of the attribute. * @return value of the specified attribute in the current document as a string; or null if the attribute either doesn't exist * or the attribute value is null */ String getString(String attributeName); /** * Gets the {@link SdkNumber} value of specified attribute in the document. * * @param attributeName Name of the attribute. * @return value of the specified attribute in the current document as a number; or null if the attribute either doesn't exist * or the attribute value is null */ SdkNumber getNumber(String attributeName); /** * Gets the {@link SdkBytes} value of specified attribute in the document. * * @param attributeName Name of the attribute. * @return the value of the specified attribute in the current document as SdkBytes; or null if the attribute either * doesn't exist or the attribute value is null. */ SdkBytes getBytes(String attributeName); /** * Gets the Set of String values of the given attribute in the current document. * @param attributeName the name of the attribute. * @return the value of the specified attribute in the current document as a set of strings; or null if the attribute either * does not exist or the attribute value is null. */ Set<String> getStringSet(String attributeName); /** * Gets the Set of String values of the given attribute in the current document. * @param attributeName Name of the attribute. * @return value of the specified attribute in the current document as a set of SdkNumber; or null if the attribute either * doesn't exist or the attribute value is null. */ Set<SdkNumber> getNumberSet(String attributeName); /** * Gets the Set of String values of the given attribute in the current document. * @param attributeName Name of the attribute. * @return value of the specified attribute in the current document as a set of SdkBytes; * or null if the attribute doesn't exist. */ Set<SdkBytes> getBytesSet(String attributeName); /** * Gets the List of values of type T for the given attribute in the current document. * * @param attributeName Name of the attribute. * @param type {@link EnhancedType} of Type T. * @param <T> Type T of List elements * @return value of the specified attribute in the current document as a list of type T, * or null if the attribute does not exist. */ <T> List<T> getList(String attributeName, EnhancedType<T> type); /** * Returns a map of a specific Key-type and Value-type based on the given attribute name, key type, and value type. * Example usage: When getting an attribute as a map of {@link UUID} keys and {@link Integer} values, use this API * as shown below: * {@snippet : Map<String, Integer> result = document.getMap("key", EnhancedType.of(String.class), EnhancedType.of(Integer.class)); * } * @param attributeName The name of the attribute that needs to be get as Map. * @param keyType Enhanced Type of Key attribute, like String, UUID etc that can be represented as String Keys. * @param valueType Enhanced Type of Values , which have converters defineds in * {@link Builder#attributeConverterProviders(AttributeConverterProvider...)} for the document * @return Map of type K and V with the given attribute name, key type, and value type. * @param <K> The type of the Map keys. * @param <V> The type of the Map values. */ <K, V> Map<K, V> getMap(String attributeName, EnhancedType<K> keyType, EnhancedType<V> valueType); /** * Gets the JSON document value of the specified attribute. * * @param attributeName Name of the attribute. * @return value of the specified attribute in the current document as a JSON string; or null if the attribute either * doesn't exist or the attribute value is null. */ String getJson(String attributeName); /** * Gets the {@link Boolean} value for the specified attribute. * * @param attributeName Name of the attribute. * @return value of the specified attribute in the current document as a Boolean representation; or null if the attribute * either doesn't exist or the attribute value is null. * @throws RuntimeException * if the attribute value cannot be converted to a Boolean representation. * Note that the Boolean representation of 0 and 1 in Numbers and "0" and "1" in Strings is false and true, * respectively. * */ Boolean getBoolean(String attributeName); /** * Retrieves a list of {@link AttributeValue} objects for a specified attribute in a document. * This API should be used when the elements of the list are a combination of different types such as Strings, Maps, * and Numbers. * If all elements in the list are of a known fixed type, use {@link EnhancedDocument#getList(String, EnhancedType)} instead. * * @param attributeName Name of the attribute. * @return value of the specified attribute in the current document as a List of {@link AttributeValue} */ List<AttributeValue> getListOfUnknownType(String attributeName); /** * Retrieves a Map with String keys and corresponding AttributeValue objects as values for a specified attribute in a * document. This API is particularly useful when the values of the map are of different types such as strings, maps, and * numbers. However, if all the values in the map for a given attribute key are of a known fixed type, it is recommended to * use the method EnhancedDocument#getMap(String, EnhancedType, EnhancedType) instead. * * @param attributeName Name of the attribute. * @return value of the specified attribute in the current document as a {@link AttributeValue} */ Map<String, AttributeValue> getMapOfUnknownType(String attributeName); /** * * @return document as a JSON string. Note all binary data will become base-64 encoded in the resultant string. */ String toJson(); /** * This method converts a document into a key-value map with the keys as String objects and the values as AttributeValue * objects. It can be particularly useful for documents with attributes of unknown types, as it allows for further processing * or manipulation of the document data in a AttributeValue format. * @return Document as a String AttributeValue Key-Value Map */ Map<String, AttributeValue> toMap(); /** * * @return List of AttributeConverterProvider defined for the given Document. */ List<AttributeConverterProvider> attributeConverterProviders(); @NotThreadSafe interface Builder { /** * Appends an attribute of name attributeName with specified {@link String} value to the document builder. * Use this method when you need to add a string value to a document. If you need to add an attribute with a value of a * different type, such as a number or a map, use the appropriate put method instead * * @param attributeName the name of the attribute to be added to the document. * @param value The string value that needs to be set. * @return Builder instance to construct a {@link EnhancedDocument} */ Builder putString(String attributeName, String value); /** * Appends an attribute of name attributeName with specified {@link Number} value to the document builder. * Use this method when you need to add a number value to a document. If you need to add an attribute with a value of a * different type, such as a string or a map, use the appropriate put method instead * @param attributeName the name of the attribute to be added to the document. * @param value The number value that needs to be set. * @return Builder instance to construct a {@link EnhancedDocument} */ Builder putNumber(String attributeName, Number value); /** * Appends an attribute of name attributeName with specified {@link SdkBytes} value to the document builder. * Use this method when you need to add a binary value to a document. If you need to add an attribute with a value of a * different type, such as a string or a map, use the appropriate put method instead * @param attributeName the name of the attribute to be added to the document. * @param value The byte array value that needs to be set. * @return Builder instance to construct a {@link EnhancedDocument} */ Builder putBytes(String attributeName, SdkBytes value); /** * Use this method when you need to add a boolean value to a document. If you need to add an attribute with a value of a * different type, such as a string or a map, use the appropriate put method instead. * @param attributeName the name of the attribute to be added to the document. * @param value The boolean value that needs to be set. * @return Builder instance to construct a {@link EnhancedDocument} */ Builder putBoolean(String attributeName, boolean value); /** * Appends an attribute of name attributeName with a null value. * Use this method is the attribute needs to explicitly set to null in Dynamo DB table. * * @param attributeName the name of the attribute to be added to the document. * @return Builder instance to construct a {@link EnhancedDocument} */ Builder putNull(String attributeName); /** * Appends an attribute to the document builder with a Set of Strings as its value. * This method is intended for use in DynamoDB where attribute values are stored as Sets of Strings. * @param attributeName the name of the attribute to be added to the document. * @param values Set of String values that needs to be set. * @return Builder instance to construct a {@link EnhancedDocument} */ Builder putStringSet(String attributeName, Set<String> values); /** * Appends an attribute of name attributeName with specified Set of {@link Number} values to the document builder. * * @param attributeName the name of the attribute to be added to the document. * @param values Set of Number values that needs to be set. * @return Builder instance to construct a {@link EnhancedDocument} */ Builder putNumberSet(String attributeName, Set<Number> values); /** * Appends an attribute of name attributeName with specified Set of {@link SdkBytes} values to the document builder. * * @param attributeName the name of the attribute to be added to the document. * @param values Set of SdkBytes values that needs to be set. * @return Builder instance to construct a {@link EnhancedDocument} */ Builder putBytesSet(String attributeName, Set<SdkBytes> values); /** * Appends an attribute with the specified name and a list of {@link EnhancedType} T type elements to the document * builder. * Use {@link EnhancedType#of(Class)} to specify the class type of the list elements. * <p>For example, to insert a list of String type: * {@snippet : * EnhancedDocument.builder().putList(stringList, EnhancedType.of(String.class)) * } * <p>Example for inserting a List of Custom type . * {@snippet : * EnhancedDocument.builder().putList(stringList, EnhancedType.of(CustomClass.class)); * } * Note that the AttributeConverterProvider added to the DocumentBuilder should provide the converter for the class T that * is to be inserted. * @param attributeName the name of the attribute to be added to the document. * @param value The list of values that needs to be set. * @return Builder instance to construct a {@link EnhancedDocument} */ <T> Builder putList(String attributeName, List<T> value, EnhancedType<T> type); /** * Appends an attribute named {@code attributeName} with a value of type {@link EnhancedType} T. * Use this method to insert attribute values of custom types that have attribute converters defined in a converter * provider. * Example: {@snippet : * EnhancedDocument.builder().put("customKey", customValue, EnhancedType.of(CustomClass.class)); *} * Use {@link #putString(String, String)} or {@link #putNumber(String, Number)} for inserting simple value types of * attributes. * Use {@link #putList(String, List, EnhancedType)} or {@link #putMap(String, Map, EnhancedType, EnhancedType)} for * inserting collections of attribute values. * Note that the attribute converter provider added to the DocumentBuilder must provide the converter for the class T * that is to be inserted. @param attributeName the name of the attribute to be added to the document. @param value the value to set. @param type the Enhanced type of the value to set. @return a builder instance to construct a {@link EnhancedDocument}. @param <T> the type of the value to set. */ <T> Builder put(String attributeName, T value, EnhancedType<T> type); /** * Appends an attribute named {@code attributeName} with a value of Class type T. * Use this method to insert attribute values of custom types that have attribute converters defined in a converter * provider. * Example: {@snippet : * EnhancedDocument.builder().put("customKey", customValue, CustomClass.class); *} * Use {@link #putString(String, String)} or {@link #putNumber(String, Number)} for inserting simple value types of * attributes. * Use {@link #putList(String, List, EnhancedType)} or {@link #putMap(String, Map, EnhancedType, EnhancedType)} for * inserting collections of attribute values. * Note that the attribute converter provider added to the DocumentBuilder must provide the converter for the class T * that is to be inserted. @param attributeName the name of the attribute to be added to the document. @param value the value to set. @param type the type of the value to set. @return a builder instance to construct a {@link EnhancedDocument}. @param <T> the type of the value to set. */ <T> Builder put(String attributeName, T value, Class<T> type); /** * Appends an attribute with the specified name and a Map containing keys and values of {@link EnhancedType} K * and V types, * respectively, to the document builder. Use {@link EnhancedType#of(Class)} to specify the class type of the keys and * values. * <p>For example, to insert a map with String keys and Long values: * {@snippet : * EnhancedDocument.builder().putMap("stringMap", mapWithStringKeyNumberValue, EnhancedType.of(String.class), * EnhancedType.of(String.class), EnhancedType.of(Long.class)) *} * <p>For example, to insert a map of String Key and Custom Values: * {@snippet : * EnhancedDocument.builder().putMap("customMap", mapWithStringKeyCustomValue, EnhancedType.of(String.class), * EnhancedType.of(String.class), EnhancedType.of(Custom.class)) *} * Note that the AttributeConverterProvider added to the DocumentBuilder should provide the converter for the classes * K and V that * are to be inserted. * @param attributeName the name of the attribute to be added to the document * @param value The Map of values that needs to be set. * @param keyType Enhanced type of Key class * @param valueType Enhanced type of Value class. * @return Builder instance to construct a {@link EnhancedDocument} */ <K, V> Builder putMap(String attributeName, Map<K, V> value, EnhancedType<K> keyType, EnhancedType<V> valueType); /** Appends an attribute to the document builder with the specified name and value of a JSON document in string format. * @param attributeName the name of the attribute to be added to the document. * @param json JSON document in the form of a string. * @return Builder instance to construct a {@link EnhancedDocument} */ Builder putJson(String attributeName, String json); /** * Removes a previously appended attribute. * This can be used where a previously added attribute to the Builder is no longer needed. * @param attributeName The attribute that needs to be removed. * @return Builder instance to construct a {@link EnhancedDocument} */ Builder remove(String attributeName); /** * Appends collection of attributeConverterProvider to the document builder. These * AttributeConverterProvider will be used to convert any given key to custom type T. * The first matching converter from the given provider will be selected based on the order in which they are added. * @param attributeConverterProvider determining the {@link AttributeConverter} to use for converting a value. * @return Builder instance to construct a {@link EnhancedDocument} */ Builder addAttributeConverterProvider(AttributeConverterProvider attributeConverterProvider); /** * Sets the collection of attributeConverterProviders to the document builder. These AttributeConverterProvider will be * used to convert value of any given key to custom type T. * The first matching converter from the given provider will be selected based on the order in which they are added. * @param attributeConverterProviders determining the {@link AttributeConverter} to use for converting a value. * @return Builder instance to construct a {@link EnhancedDocument} */ Builder attributeConverterProviders(List<AttributeConverterProvider> attributeConverterProviders); /** * Sets collection of attributeConverterProviders to the document builder. These AttributeConverterProvider will be * used to convert any given key to custom type T. * The first matching converter from the given provider will be selected based on the order in which they are added. * @param attributeConverterProvider determining the {@link AttributeConverter} to use for converting a value. * @return Builder instance to construct a {@link EnhancedDocument} */ Builder attributeConverterProviders(AttributeConverterProvider... attributeConverterProvider); /** * Sets the attributes of the document builder to those specified in the provided JSON string, and completely replaces * any previously set attributes. * * @param json a JSON document represented as a string * @return a builder instance to construct a {@link EnhancedDocument} * @throws NullPointerException if the json parameter is null */ Builder json(String json); /** * Sets the attributes of the document builder to those specified in the provided from a AttributeValue Map, and * completely replaces any previously set attributes. * * @param attributeValueMap - Map with Attributes as String keys and AttributeValue as Value. * @return Builder instance to construct a {@link EnhancedDocument} */ Builder attributeValueMap(Map<String, AttributeValue> attributeValueMap); /** * Builds an instance of {@link EnhancedDocument}. * * @return instance of {@link EnhancedDocument} implementation. */ EnhancedDocument build(); } }
4,314
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/extensions/ReadModification.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.extensions; import java.util.Map; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * Simple object for storing a modification to a read operation. If a transformedItem is supplied then this item will * be completely substituted in place of the item that was actually read. */ @SdkPublicApi @ThreadSafe public final class ReadModification { private final Map<String, AttributeValue> transformedItem; private ReadModification(Map<String, AttributeValue> transformedItem) { this.transformedItem = transformedItem; } public static Builder builder() { return new Builder(); } public Map<String, AttributeValue> transformedItem() { return transformedItem; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ReadModification that = (ReadModification) o; return transformedItem != null ? transformedItem.equals(that.transformedItem) : that.transformedItem == null; } @Override public int hashCode() { return transformedItem != null ? transformedItem.hashCode() : 0; } @NotThreadSafe public static final class Builder { private Map<String, AttributeValue> transformedItem; private Builder() { } public Builder transformedItem(Map<String, AttributeValue> transformedItem) { this.transformedItem = transformedItem; return this; } public ReadModification build() { return new ReadModification(transformedItem); } } }
4,315
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/extensions/AtomicCounterExtension.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.extensions; import static software.amazon.awssdk.enhanced.dynamodb.internal.EnhancedClientUtils.keyRef; import static software.amazon.awssdk.enhanced.dynamodb.internal.EnhancedClientUtils.valueRef; import static software.amazon.awssdk.enhanced.dynamodb.internal.update.UpdateExpressionUtils.ifNotExists; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClientExtension; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbExtensionContext; import software.amazon.awssdk.enhanced.dynamodb.extensions.annotations.DynamoDbAtomicCounter; import software.amazon.awssdk.enhanced.dynamodb.internal.extensions.AtomicCounterTag; import software.amazon.awssdk.enhanced.dynamodb.internal.mapper.AtomicCounter; import software.amazon.awssdk.enhanced.dynamodb.mapper.BeanTableSchema; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema; import software.amazon.awssdk.enhanced.dynamodb.update.SetAction; import software.amazon.awssdk.enhanced.dynamodb.update.UpdateExpression; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.utils.CollectionUtils; import software.amazon.awssdk.utils.Logger; /** * This extension enables atomic counter attributes to be changed in DynamoDb by creating instructions for modifying * an existing value or setting a start value. The extension is loaded by default when you instantiate a * {@link DynamoDbEnhancedClient} and only needs to be added to the client if you are adding custom extensions to the client. * <p> * To utilize atomic counters, first create a field in your model that will be used to store the counter. * This class field should of type {@link Long} and you need to tag it as an atomic counter: * <ul> * <li>If you are using the * {@link BeanTableSchema}, you should annotate with * {@link DynamoDbAtomicCounter}</li> * <li>If you are using the {@link StaticTableSchema}, * use the {@link StaticAttributeTags#atomicCounter()} static attribute tag.</li> * </ul> * <p> * Every time a new update of the record is successfully written to the database, the counter will be updated automatically. * By default, the counter starts at 0 and increments by 1 for each update. The tags provide the capability of adjusting * the counter start and increment/decrement values such as described in {@link DynamoDbAtomicCounter}. * <p> * Example 1: Using a bean based table schema * <pre> * {@code * @DynamoDbBean * public class CounterRecord { * @DynamoDbAtomicCounter(delta = 5, startValue = 10) * public Long getCustomCounter() { * return customCounter; * } * } * } * </pre> * <p> * Example 2: Using a static table schema * <pre> * {@code * private static final StaticTableSchema<AtomicCounterItem> ITEM_MAPPER = * StaticTableSchema.builder(AtomicCounterItem.class) * .newItemSupplier(AtomicCounterItem::new) * .addAttribute(Long.class, a -> a.name("defaultCounter") * .getter(AtomicCounterItem::getDefaultCounter) * .setter(AtomicCounterItem::setDefaultCounter) * .addTag(StaticAttributeTags.atomicCounter())) * .build(); * } * </pre> * <p> * <b>NOTES: </b> * <ul> * <li>When using putItem, the counter will be reset to its start value.</li> * <li>The extension will remove any existing occurrences of the atomic counter attributes from the record during an * <i>updateItem</i> operation. Manually editing attributes marked as atomic counters will have <b>NO EFFECT</b>.</li> * </ul> */ @SdkPublicApi public final class AtomicCounterExtension implements DynamoDbEnhancedClientExtension { private static final Logger log = Logger.loggerFor(AtomicCounterExtension.class); private AtomicCounterExtension() { } public static AtomicCounterExtension.Builder builder() { return new AtomicCounterExtension.Builder(); } /** * @param context The {@link DynamoDbExtensionContext.BeforeWrite} context containing the state of the execution. * @return WriteModification contains an update expression representing the counters. */ @Override public WriteModification beforeWrite(DynamoDbExtensionContext.BeforeWrite context) { Map<String, AtomicCounter> counters = AtomicCounterTag.resolve(context.tableMetadata()); WriteModification.Builder modificationBuilder = WriteModification.builder(); if (CollectionUtils.isNullOrEmpty(counters)) { return modificationBuilder.build(); } switch (context.operationName()) { case PUT_ITEM: modificationBuilder.transformedItem(addToItem(counters, context.items())); break; case UPDATE_ITEM: modificationBuilder.updateExpression(createUpdateExpression(counters)); modificationBuilder.transformedItem(filterFromItem(counters, context.items())); break; default: break; } return modificationBuilder.build(); } private UpdateExpression createUpdateExpression(Map<String, AtomicCounter> counters) { return UpdateExpression.builder() .actions(counters.entrySet().stream().map(this::counterAction).collect(Collectors.toList())) .build(); } private Map<String, AttributeValue> addToItem(Map<String, AtomicCounter> counters, Map<String, AttributeValue> items) { Map<String, AttributeValue> itemToTransform = new HashMap<>(items); counters.forEach((attribute, counter) -> itemToTransform.put(attribute, attributeValue(counter.startValue().value()))); return Collections.unmodifiableMap(itemToTransform); } private Map<String, AttributeValue> filterFromItem(Map<String, AtomicCounter> counters, Map<String, AttributeValue> items) { Map<String, AttributeValue> itemToTransform = new HashMap<>(items); List<String> removedAttributes = new ArrayList<>(); for (String attributeName : counters.keySet()) { if (itemToTransform.containsKey(attributeName)) { itemToTransform.remove(attributeName); removedAttributes.add(attributeName); } } if (!removedAttributes.isEmpty()) { log.debug(() -> String.format("Filtered atomic counter attributes from existing update item to avoid collisions: %s", String.join(",", removedAttributes))); } return Collections.unmodifiableMap(itemToTransform); } private SetAction counterAction(Map.Entry<String, AtomicCounter> e) { String attributeName = e.getKey(); AtomicCounter counter = e.getValue(); String startValueName = attributeName + counter.startValue().name(); String deltaValueName = attributeName + counter.delta().name(); String valueExpression = ifNotExists(attributeName, startValueName) + " + " + valueRef(deltaValueName); AttributeValue startValue = attributeValue(counter.startValue().value() - counter.delta().value()); AttributeValue deltaValue = attributeValue(counter.delta().value()); return SetAction.builder() .path(keyRef(attributeName)) .value(valueExpression) .putExpressionName(keyRef(attributeName), attributeName) .putExpressionValue(valueRef(startValueName), startValue) .putExpressionValue(valueRef(deltaValueName), deltaValue) .build(); } private AttributeValue attributeValue(long value) { return AtomicCounter.CounterAttribute.resolvedValue(value); } public static final class Builder { private Builder() { } public AtomicCounterExtension build() { return new AtomicCounterExtension(); } } }
4,316
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/extensions/VersionedRecordExtension.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.extensions; import static software.amazon.awssdk.enhanced.dynamodb.internal.EnhancedClientUtils.isNullAttributeValue; import static software.amazon.awssdk.enhanced.dynamodb.internal.EnhancedClientUtils.keyRef; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.function.Consumer; import java.util.function.Function; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClientExtension; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbExtensionContext; import software.amazon.awssdk.enhanced.dynamodb.Expression; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTag; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableMetadata; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * This extension implements optimistic locking on record writes by means of a 'record version number' that is used * to automatically track each revision of the record as it is modified. * <p> * This extension is loaded by default when you instantiate a * {@link software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient} so unless you are using a custom extension * there is no need to specify it. * <p> * To utilize versioned record locking, first create an attribute in your model that will be used to store the record * version number. This attribute must be an 'integer' type numeric (long or integer), and you need to tag it as the * version attribute. If you are using the {@link software.amazon.awssdk.enhanced.dynamodb.mapper.BeanTableSchema} then * you should use the {@link software.amazon.awssdk.enhanced.dynamodb.extensions.annotations.DynamoDbVersionAttribute} * annotation, otherwise if you are using the {@link software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema} * then you should use the {@link AttributeTags#versionAttribute()} static attribute tag. * <p> * Then, whenever a record is written the write operation will only succeed if the version number of the record has not * been modified since it was last read by the application. Every time a new version of the record is successfully * written to the database, the record version number will be automatically incremented. */ @SdkPublicApi @ThreadSafe public final class VersionedRecordExtension implements DynamoDbEnhancedClientExtension { private static final Function<String, String> VERSIONED_RECORD_EXPRESSION_VALUE_KEY_MAPPER = key -> ":old_" + key + "_value"; private static final String CUSTOM_METADATA_KEY = "VersionedRecordExtension:VersionAttribute"; private static final VersionAttribute VERSION_ATTRIBUTE = new VersionAttribute(); private VersionedRecordExtension() { } public static Builder builder() { return new Builder(); } public static final class AttributeTags { private AttributeTags() { } public static StaticAttributeTag versionAttribute() { return VERSION_ATTRIBUTE; } } private static class VersionAttribute implements StaticAttributeTag { @Override public Consumer<StaticTableMetadata.Builder> modifyMetadata(String attributeName, AttributeValueType attributeValueType) { if (attributeValueType != AttributeValueType.N) { throw new IllegalArgumentException(String.format( "Attribute '%s' of type %s is not a suitable type to be used as a version attribute. Only type 'N' " + "is supported.", attributeName, attributeValueType.name())); } return metadata -> metadata.addCustomMetadataObject(CUSTOM_METADATA_KEY, attributeName) .markAttributeAsKey(attributeName, attributeValueType); } } @Override public WriteModification beforeWrite(DynamoDbExtensionContext.BeforeWrite context) { Optional<String> versionAttributeKey = context.tableMetadata() .customMetadataObject(CUSTOM_METADATA_KEY, String.class); if (!versionAttributeKey.isPresent()) { return WriteModification.builder().build(); } Map<String, AttributeValue> itemToTransform = new HashMap<>(context.items()); String attributeKeyRef = keyRef(versionAttributeKey.get()); AttributeValue newVersionValue; Expression condition; Optional<AttributeValue> existingVersionValue = Optional.ofNullable(itemToTransform.get(versionAttributeKey.get())); if (!existingVersionValue.isPresent() || isNullAttributeValue(existingVersionValue.get())) { // First version of the record newVersionValue = AttributeValue.builder().n("1").build(); condition = Expression.builder() .expression(String.format("attribute_not_exists(%s)", attributeKeyRef)) .expressionNames(Collections.singletonMap(attributeKeyRef, versionAttributeKey.get())) .build(); } else { // Existing record, increment version if (existingVersionValue.get().n() == null) { // In this case a non-null version attribute is present, but it's not an N throw new IllegalArgumentException("Version attribute appears to be the wrong type. N is required."); } int existingVersion = Integer.parseInt(existingVersionValue.get().n()); String existingVersionValueKey = VERSIONED_RECORD_EXPRESSION_VALUE_KEY_MAPPER.apply(versionAttributeKey.get()); newVersionValue = AttributeValue.builder().n(Integer.toString(existingVersion + 1)).build(); condition = Expression.builder() .expression(String.format("%s = %s", attributeKeyRef, existingVersionValueKey)) .expressionNames(Collections.singletonMap(attributeKeyRef, versionAttributeKey.get())) .expressionValues(Collections.singletonMap(existingVersionValueKey, existingVersionValue.get())) .build(); } itemToTransform.put(versionAttributeKey.get(), newVersionValue); return WriteModification.builder() .transformedItem(Collections.unmodifiableMap(itemToTransform)) .additionalConditionalExpression(condition) .build(); } @NotThreadSafe public static final class Builder { private Builder() { } public VersionedRecordExtension build() { return new VersionedRecordExtension(); } } }
4,317
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/extensions/WriteModification.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.extensions; import java.util.Map; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.enhanced.dynamodb.Expression; import software.amazon.awssdk.enhanced.dynamodb.update.UpdateExpression; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * Simple object for storing a modification to a write operation. * <p> * If a transformedItem is supplied then this item will be completely substituted in place of the item that was * previously going to be written. * <p> * If an additionalConditionalExpression is supplied then this condition will be coalesced with any other conditions * and added as a parameter to the write operation. * <p> * If an updateExpression is supplied then this update expression will be coalesced with any other update expressions * and added as a parameter to the write operation. */ @SdkPublicApi @ThreadSafe public final class WriteModification { private final Map<String, AttributeValue> transformedItem; private final Expression additionalConditionalExpression; private final UpdateExpression updateExpression; private WriteModification(Builder builder) { this.transformedItem = builder.transformedItem; this.additionalConditionalExpression = builder.additionalConditionalExpression; this.updateExpression = builder.updateExpression; } public static Builder builder() { return new Builder(); } public Map<String, AttributeValue> transformedItem() { return transformedItem; } public Expression additionalConditionalExpression() { return additionalConditionalExpression; } public UpdateExpression updateExpression() { return updateExpression; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } WriteModification that = (WriteModification) o; if (transformedItem != null ? ! transformedItem.equals(that.transformedItem) : that.transformedItem != null) { return false; } if (additionalConditionalExpression != null ? ! additionalConditionalExpression.equals(that.additionalConditionalExpression) : that.additionalConditionalExpression != null) { return false; } return updateExpression != null ? updateExpression.equals(that.updateExpression) : that.updateExpression == null; } @Override public int hashCode() { int result = transformedItem != null ? transformedItem.hashCode() : 0; result = 31 * result + (additionalConditionalExpression != null ? additionalConditionalExpression.hashCode() : 0); result = 31 * result + (updateExpression != null ? updateExpression.hashCode() : 0); return result; } @NotThreadSafe public static final class Builder { private Map<String, AttributeValue> transformedItem; private Expression additionalConditionalExpression; private UpdateExpression updateExpression; private Builder() { } public Builder transformedItem(Map<String, AttributeValue> transformedItem) { this.transformedItem = transformedItem; return this; } public Builder additionalConditionalExpression(Expression additionalConditionalExpression) { this.additionalConditionalExpression = additionalConditionalExpression; return this; } public Builder updateExpression(UpdateExpression updateExpression) { this.updateExpression = updateExpression; return this; } public WriteModification build() { return new WriteModification(this); } } }
4,318
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/extensions/AutoGeneratedTimestampRecordExtension.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.extensions; import java.time.Clock; import java.time.Instant; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.function.Consumer; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.enhanced.dynamodb.AttributeConverter; import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClientExtension; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbExtensionContext; import software.amazon.awssdk.enhanced.dynamodb.EnhancedType; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTag; import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableMetadata; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.utils.Validate; /** * This extension enables selected attributes to be automatically updated with a current timestamp every time they are written * to the database. * <p> * This extension is not loaded by default when you instantiate a * {@link software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient}. Thus you need to specify it in custom extension * while creating the enhanced client. * <p> * Example to add AutoGeneratedTimestampRecordExtension along with default extensions is * <code>DynamoDbEnhancedClient.builder().extensions(Stream.concat(ExtensionResolver.defaultExtensions().stream(), * Stream.of(AutoGeneratedTimestampRecordExtension.create())).collect(Collectors.toList())).build();</code> * </p> * <p> * Example to just add AutoGeneratedTimestampRecordExtension without default extensions is * <code>DynamoDbEnhancedClient.builder().extensions(AutoGeneratedTimestampRecordExtension.create())).build();</code> * </p> * </p> * <p> * To utilize auto generated timestamp update, first create a field in your model that will be used to store the record * timestamp of modification. This class field must be an {@link Instant} Class type, and you need to tag it as the * autoGeneratedTimeStampAttribute. If you are using the * {@link software.amazon.awssdk.enhanced.dynamodb.mapper.BeanTableSchema} * then you should use the * {@link software.amazon.awssdk.enhanced.dynamodb.extensions.annotations.DynamoDbAutoGeneratedTimestampAttribute} * annotation, otherwise if you are using the {@link software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema} * then you should use the {@link AttributeTags#autoGeneratedTimestampAttribute()} static attribute tag. * <p> * Every time a new update of the record is successfully written to the database, the timestamp at which it was modified will * be automatically updated. This extension applies the conversions as defined in the attribute convertor. */ @SdkPublicApi @ThreadSafe public final class AutoGeneratedTimestampRecordExtension implements DynamoDbEnhancedClientExtension { private static final String CUSTOM_METADATA_KEY = "AutoGeneratedTimestampExtension:AutoGeneratedTimestampAttribute"; private static final AutoGeneratedTimestampAttribute AUTO_GENERATED_TIMESTAMP_ATTRIBUTE = new AutoGeneratedTimestampAttribute(); private final Clock clock; private AutoGeneratedTimestampRecordExtension() { this.clock = Clock.systemUTC(); } /** * Attribute tag to identify the meta data for {@link AutoGeneratedTimestampRecordExtension}. */ public static final class AttributeTags { private AttributeTags() { } /** * Tags which indicate that the given attribute is supported wih Auto Generated Timestamp Record Extension. * @return Tag name for AutoGenerated Timestamp Records */ public static StaticAttributeTag autoGeneratedTimestampAttribute() { return AUTO_GENERATED_TIMESTAMP_ATTRIBUTE; } } private AutoGeneratedTimestampRecordExtension(Builder builder) { this.clock = builder.baseClock == null ? Clock.systemUTC() : builder.baseClock; } /** * Create a builder that can be used to create a {@link AutoGeneratedTimestampRecordExtension}. * @return Builder to create AutoGeneratedTimestampRecordExtension, */ public static Builder builder() { return new Builder(); } /** * Returns a builder initialized with all existing values on the Extension object. */ public Builder toBuilder() { return builder().baseClock(this.clock); } /** * @return an Instance of {@link AutoGeneratedTimestampRecordExtension} */ public static AutoGeneratedTimestampRecordExtension create() { return new AutoGeneratedTimestampRecordExtension(); } /** * @param context The {@link DynamoDbExtensionContext.BeforeWrite} context containing the state of the execution. * @return WriteModification Instance updated with attribute updated with Extension. */ @Override public WriteModification beforeWrite(DynamoDbExtensionContext.BeforeWrite context) { Collection<String> customMetadataObject = context.tableMetadata() .customMetadataObject(CUSTOM_METADATA_KEY, Collection.class).orElse(null); if (customMetadataObject == null) { return WriteModification.builder().build(); } Map<String, AttributeValue> itemToTransform = new HashMap<>(context.items()); customMetadataObject.forEach( key -> insertTimestampInItemToTransform(itemToTransform, key, context.tableSchema().converterForAttribute(key))); return WriteModification.builder() .transformedItem(Collections.unmodifiableMap(itemToTransform)) .build(); } private void insertTimestampInItemToTransform(Map<String, AttributeValue> itemToTransform, String key, AttributeConverter converter) { itemToTransform.put(key, converter.transformFrom(clock.instant())); } /** * Builder for a {@link AutoGeneratedTimestampRecordExtension} */ @NotThreadSafe public static final class Builder { private Clock baseClock; private Builder() { } /** * Sets the clock instance , else Clock.systemUTC() is used by default. * Every time a new timestamp is generated this clock will be used to get the current point in time. If a custom clock * is not specified, the default system clock will be used. * * @param clock Clock instance to set the current timestamp. * @return This builder for method chaining. */ public Builder baseClock(Clock clock) { this.baseClock = clock; return this; } /** * Builds an {@link AutoGeneratedTimestampRecordExtension} based on the values stored in this builder */ public AutoGeneratedTimestampRecordExtension build() { return new AutoGeneratedTimestampRecordExtension(this); } } private static class AutoGeneratedTimestampAttribute implements StaticAttributeTag { @Override public <R> void validateType(String attributeName, EnhancedType<R> type, AttributeValueType attributeValueType) { Validate.notNull(type, "type is null"); Validate.notNull(type.rawClass(), "rawClass is null"); Validate.notNull(attributeValueType, "attributeValueType is null"); if (!type.rawClass().equals(Instant.class)) { throw new IllegalArgumentException(String.format( "Attribute '%s' of Class type %s is not a suitable Java Class type to be used as a Auto Generated " + "Timestamp attribute. Only java.time.Instant Class type is supported.", attributeName, type.rawClass())); } } @Override public Consumer<StaticTableMetadata.Builder> modifyMetadata(String attributeName, AttributeValueType attributeValueType) { return metadata -> metadata.addCustomMetadataObject(CUSTOM_METADATA_KEY, Collections.singleton(attributeName)) .markAttributeAsKey(attributeName, attributeValueType); } } }
4,319
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/extensions
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/extensions/annotations/DynamoDbAutoGeneratedTimestampAttribute.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.extensions.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.enhanced.dynamodb.internal.extensions.AutoGeneratedTimestampRecordAttributeTags; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.BeanTableSchemaAttributeTag; /** * Denotes this attribute as recording the auto generated last updated timestamp for the record. * Every time a record with this attribute is written to the database it will update the attribute with current timestamp when * its updated. */ @SdkPublicApi @Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @BeanTableSchemaAttributeTag(AutoGeneratedTimestampRecordAttributeTags.class) public @interface DynamoDbAutoGeneratedTimestampAttribute { }
4,320
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/extensions
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/extensions/annotations/DynamoDbVersionAttribute.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.extensions.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.enhanced.dynamodb.internal.extensions.VersionRecordAttributeTags; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.BeanTableSchemaAttributeTag; /** * Denotes this attribute as recording the version record number to be used for optimistic locking. Every time a record * with this attribute is written to the database it will be incremented and a condition added to the request to check * for an exact match of the old version. */ @SdkPublicApi @Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @BeanTableSchemaAttributeTag(VersionRecordAttributeTags.class) public @interface DynamoDbVersionAttribute { }
4,321
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/extensions
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/extensions/annotations/DynamoDbAtomicCounter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.extensions.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.enhanced.dynamodb.internal.mapper.BeanTableSchemaAttributeTags; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.BeanTableSchemaAttributeTag; /** * Used to explicitly designate an attribute to be an auto-generated counter updated unconditionally in DynamoDB. * By default, the counter will start on 0 and increment with 1 for each subsequent calls to updateItem. * By supplying a negative integer delta value, the attribute works as a decreasing counter. */ @SdkPublicApi @Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @BeanTableSchemaAttributeTag(BeanTableSchemaAttributeTags.class) public @interface DynamoDbAtomicCounter { /** * The value to increment (positive) or decrement (negative) the counter with for each update. */ long delta() default 1; /** * The starting value of the counter. */ long startValue() default 0; }
4,322
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/model/QueryConditional.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.model; import java.util.function.Consumer; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.enhanced.dynamodb.Expression; import software.amazon.awssdk.enhanced.dynamodb.Key; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.internal.conditional.BeginsWithConditional; import software.amazon.awssdk.enhanced.dynamodb.internal.conditional.BetweenConditional; import software.amazon.awssdk.enhanced.dynamodb.internal.conditional.EqualToConditional; import software.amazon.awssdk.enhanced.dynamodb.internal.conditional.SingleKeyItemConditional; /** * An interface for a literal conditional that can be used in an enhanced DynamoDB query. Contains convenient static * methods that can be used to construct the most common conditional statements. Query conditionals are not linked to * any specific table or schema and can be re-used in different contexts. * <p> * Example: * <pre> * {@code * QueryConditional sortValueGreaterThanFour = QueryConditional.sortGreaterThan(k -> k.partitionValue(10).sortValue(4)); * } * </pre> */ @SdkPublicApi @ThreadSafe public interface QueryConditional { /** * Creates a {@link QueryConditional} that matches when the key of an index is equal to a specific value. * @param key the literal key used to compare the value of the index against */ static QueryConditional keyEqualTo(Key key) { return new EqualToConditional(key); } /** * Creates a {@link QueryConditional} that matches when the key of an index is equal to a specific value. * @param keyConsumer 'builder consumer' for the literal key used to compare the value of the index against */ static QueryConditional keyEqualTo(Consumer<Key.Builder> keyConsumer) { Key.Builder builder = Key.builder(); keyConsumer.accept(builder); return keyEqualTo(builder.build()); } /** * Creates a {@link QueryConditional} that matches when the key of an index is greater than a specific value. * @param key the literal key used to compare the value of the index against */ static QueryConditional sortGreaterThan(Key key) { return new SingleKeyItemConditional(key, ">"); } /** * Creates a {@link QueryConditional} that matches when the key of an index is greater than a specific value. * @param keyConsumer 'builder consumer' for the literal key used to compare the value of the index against */ static QueryConditional sortGreaterThan(Consumer<Key.Builder> keyConsumer) { Key.Builder builder = Key.builder(); keyConsumer.accept(builder); return sortGreaterThan(builder.build()); } /** * Creates a {@link QueryConditional} that matches when the key of an index is greater than or equal to a specific * value. * @param key the literal key used to compare the value of the index against */ static QueryConditional sortGreaterThanOrEqualTo(Key key) { return new SingleKeyItemConditional(key, ">="); } /** * Creates a {@link QueryConditional} that matches when the key of an index is greater than or equal to a specific * value. * @param keyConsumer 'builder consumer' for the literal key used to compare the value of the index against */ static QueryConditional sortGreaterThanOrEqualTo(Consumer<Key.Builder> keyConsumer) { Key.Builder builder = Key.builder(); keyConsumer.accept(builder); return sortGreaterThanOrEqualTo(builder.build()); } /** * Creates a {@link QueryConditional} that matches when the key of an index is less than a specific value. * @param key the literal key used to compare the value of the index against */ static QueryConditional sortLessThan(Key key) { return new SingleKeyItemConditional(key, "<"); } /** * Creates a {@link QueryConditional} that matches when the key of an index is less than a specific value. * @param keyConsumer 'builder consumer' for the literal key used to compare the value of the index against */ static QueryConditional sortLessThan(Consumer<Key.Builder> keyConsumer) { Key.Builder builder = Key.builder(); keyConsumer.accept(builder); return sortLessThan(builder.build()); } /** * Creates a {@link QueryConditional} that matches when the key of an index is less than or equal to a specific * value. * @param key the literal key used to compare the value of the index against */ static QueryConditional sortLessThanOrEqualTo(Key key) { return new SingleKeyItemConditional(key, "<="); } /** * Creates a {@link QueryConditional} that matches when the key of an index is less than or equal to a specific * value. * @param keyConsumer 'builder consumer' for the literal key used to compare the value of the index against */ static QueryConditional sortLessThanOrEqualTo(Consumer<Key.Builder> keyConsumer) { Key.Builder builder = Key.builder(); keyConsumer.accept(builder); return sortLessThanOrEqualTo(builder.build()); } /** * Creates a {@link QueryConditional} that matches when the key of an index is between two specific values. * @param keyFrom the literal key used to compare the start of the range to compare the value of the index against * @param keyTo the literal key used to compare the end of the range to compare the value of the index against */ static QueryConditional sortBetween(Key keyFrom, Key keyTo) { return new BetweenConditional(keyFrom, keyTo); } /** * Creates a {@link QueryConditional} that matches when the key of an index is between two specific values. * @param keyFromConsumer 'builder consumer' for the literal key used to compare the start of the range to compare * the value of the index against * @param keyToConsumer 'builder consumer' for the literal key used to compare the end of the range to compare the * value of the index against */ static QueryConditional sortBetween(Consumer<Key.Builder> keyFromConsumer, Consumer<Key.Builder> keyToConsumer) { Key.Builder builderFrom = Key.builder(); Key.Builder builderTo = Key.builder(); keyFromConsumer.accept(builderFrom); keyToConsumer.accept(builderTo); return sortBetween(builderFrom.build(), builderTo.build()); } /** * Creates a {@link QueryConditional} that matches when the key of an index begins with a specific value. * @param key the literal key used to compare the start of the value of the index against */ static QueryConditional sortBeginsWith(Key key) { return new BeginsWithConditional(key); } /** * Creates a {@link QueryConditional} that matches when the key of an index begins with a specific value. * @param keyConsumer 'builder consumer' the literal key used to compare the start of the value of the index * against */ static QueryConditional sortBeginsWith(Consumer<Key.Builder> keyConsumer) { Key.Builder builder = Key.builder(); keyConsumer.accept(builder); return sortBeginsWith(builder.build()); } /** * Generates a conditional {@link Expression} based on specific context that is supplied as arguments. * @param tableSchema A {@link TableSchema} that this expression will be used with * @param indexName The specific index name of the index this expression will be used with * @return A specific {@link Expression} that can be used as part of a query request */ Expression expression(TableSchema<?> tableSchema, String indexName); }
4,323
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/model/Page.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.model; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.ConsumedCapacity; import software.amazon.awssdk.utils.ToString; /** * An immutable object that holds a page of queried or scanned results from DynamoDb. * <p> * Contains a reference to the last evaluated key for the current page; see {@link #lastEvaluatedKey()} for more information. * @param <T> The modelled type of the object that has been read. */ @SdkPublicApi @ThreadSafe public final class Page<T> { private final List<T> items; private final Map<String, AttributeValue> lastEvaluatedKey; private final Integer count; private final Integer scannedCount; private final ConsumedCapacity consumedCapacity; private Page(List<T> items, Map<String, AttributeValue> lastEvaluatedKey) { this.items = items; this.lastEvaluatedKey = lastEvaluatedKey; this.count = null; this.scannedCount = null; this.consumedCapacity = null; } private Page(Builder<T> builder) { this.items = builder.items; this.lastEvaluatedKey = builder.lastEvaluatedKey; this.count = builder.count; this.scannedCount = builder.scannedCount; this.consumedCapacity = builder.consumedCapacity; } /** * Static constructor for this object. Deprecated in favor of using the builder() pattern to construct this object. * * @param items A list of items to store for the page. * @param lastEvaluatedKey A 'lastEvaluatedKey' to store for the page. * @param <T> The modelled type of the object that has been read. * @return A newly constructed {@link Page} object. */ @Deprecated public static <T> Page<T> create(List<T> items, Map<String, AttributeValue> lastEvaluatedKey) { return new Page<>(items, lastEvaluatedKey); } /** * Static constructor for this object that sets a null 'lastEvaluatedKey' which indicates this is the final page * of results. Deprecated in favor of using the builder() pattern to construct this object. * @param items A list of items to store for the page. * @param <T> The modelled type of the object that has been read. * @return A newly constructed {@link Page} object. */ @Deprecated public static <T> Page<T> create(List<T> items) { return new Page<>(items, null); } /** * Returns a page of mapped objects that represent records from a database query or scan. * @return A list of mapped objects. */ public List<T> items() { return items; } /** * Returns the 'lastEvaluatedKey' that DynamoDb returned from the last page query or scan. This key can be used * to continue the query or scan if passed into a request. * @return The 'lastEvaluatedKey' from the last query or scan operation or null if the no more pages are available. */ public Map<String, AttributeValue> lastEvaluatedKey() { return lastEvaluatedKey; } /** * The count of the returned items from the last page query or scan, after any filters were applied. */ public Integer count() { return count; } /** * The scanned count of the returned items from the last page query or scan, before any filters were applied. * This number will be equal or greater than the count. */ public Integer scannedCount() { return scannedCount; } /** * Returns the capacity units consumed by the last page query or scan. Will only be returned if it has been * explicitly requested by the user when calling the operation. * * @return The 'consumedCapacity' from the last query or scan operation or null if it was not requested. */ public ConsumedCapacity consumedCapacity() { return consumedCapacity; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Page<?> page = (Page<?>) o; if (items != null ? ! items.equals(page.items) : page.items != null) { return false; } if (lastEvaluatedKey != null ? ! lastEvaluatedKey.equals(page.lastEvaluatedKey) : page.lastEvaluatedKey != null) { return false; } if (consumedCapacity != null ? ! consumedCapacity.equals(page.consumedCapacity) : page.consumedCapacity != null) { return false; } if (count != null ? ! count.equals(page.count) : page.count != null) { return false; } return scannedCount != null ? scannedCount.equals(page.scannedCount) : page.scannedCount == null; } @Override public int hashCode() { int result = items != null ? items.hashCode() : 0; result = 31 * result + (lastEvaluatedKey != null ? lastEvaluatedKey.hashCode() : 0); result = 31 * result + (consumedCapacity != null ? consumedCapacity.hashCode() : 0); result = 31 * result + (count != null ? count.hashCode() : 0); result = 31 * result + (scannedCount != null ? scannedCount.hashCode() : 0); return result; } @Override public String toString() { return ToString.builder("Page") .add("lastEvaluatedKey", lastEvaluatedKey) .add("items", items) .build(); } public static <T> Builder<T> builder(Class<T> itemClass) { return new Builder<>(); } public static final class Builder<T> { private List<T> items; private Map<String, AttributeValue> lastEvaluatedKey; private Integer count; private Integer scannedCount; private ConsumedCapacity consumedCapacity; public Builder<T> items(List<T> items) { this.items = new ArrayList<>(items); return this; } public Builder<T> lastEvaluatedKey(Map<String, AttributeValue> lastEvaluatedKey) { this.lastEvaluatedKey = new HashMap<>(lastEvaluatedKey); return this; } public Builder<T> count(Integer count) { this.count = count; return this; } public Builder<T> scannedCount(Integer scannedCount) { this.scannedCount = scannedCount; return this; } public Builder<T> consumedCapacity(ConsumedCapacity consumedCapacity) { this.consumedCapacity = consumedCapacity; return this; } public Page<T> build() { return new Page<T>(this); } } }
4,324
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/model/BatchGetResultPage.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.model; import static java.util.Collections.emptyList; import static software.amazon.awssdk.enhanced.dynamodb.internal.EnhancedClientUtils.readAndTransformSingleItem; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClientExtension; import software.amazon.awssdk.enhanced.dynamodb.Key; import software.amazon.awssdk.enhanced.dynamodb.MappedTableResource; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.DefaultOperationContext; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.BatchGetItemResponse; import software.amazon.awssdk.services.dynamodb.model.ConsumedCapacity; import software.amazon.awssdk.services.dynamodb.model.KeysAndAttributes; /** * Defines one result page with retrieved items in the result of a batchGetItem() operation, such as * {@link DynamoDbEnhancedClient#batchGetItem(BatchGetItemEnhancedRequest)}. * <p> * Use the {@link #resultsForTable(MappedTableResource)} method once for each table present in the request * to retrieve items from that table in the page. */ @SdkPublicApi @ThreadSafe public final class BatchGetResultPage { private final BatchGetItemResponse batchGetItemResponse; private final DynamoDbEnhancedClientExtension dynamoDbEnhancedClientExtension; private BatchGetResultPage(Builder builder) { this.batchGetItemResponse = builder.batchGetItemResponse; this.dynamoDbEnhancedClientExtension = builder.dynamoDbEnhancedClientExtension; } /** * Creates a newly initialized builder for a result object. */ public static Builder builder() { return new Builder(); } /** * Retrieve all items on this result page belonging to the supplied table. Call this method once for each table present in the * batch request. * * @param mappedTable the table to retrieve items for * @param <T> the type of the table items * @return a list of items */ public <T> List<T> resultsForTable(MappedTableResource<T> mappedTable) { List<Map<String, AttributeValue>> results = batchGetItemResponse.responses() .getOrDefault(mappedTable.tableName(), emptyList()); return results.stream() .map(itemMap -> readAndTransformSingleItem(itemMap, mappedTable.tableSchema(), DefaultOperationContext.create(mappedTable.tableName()), dynamoDbEnhancedClientExtension)) .collect(Collectors.toList()); } /** * Returns a list of keys associated with a given table that were not processed during the operation, typically * because the total size of the request is too large or exceeds the provisioned throughput of the table. If an item * was attempted to be retrieved but not found in the table, it will not appear in this list or the results list. * * @param mappedTable the table to retrieve the unprocessed keys for * @return a list of unprocessed keys */ public List<Key> unprocessedKeysForTable(MappedTableResource<?> mappedTable) { KeysAndAttributes keysAndAttributes = this.batchGetItemResponse.unprocessedKeys().get(mappedTable.tableName()); if (keysAndAttributes == null) { return Collections.emptyList(); } String partitionKey = mappedTable.tableSchema().tableMetadata().primaryPartitionKey(); Optional<String> sortKey = mappedTable.tableSchema().tableMetadata().primarySortKey(); return keysAndAttributes.keys() .stream() .map(keyMap -> { AttributeValue partitionValue = keyMap.get(partitionKey); AttributeValue sortValue = sortKey.map(keyMap::get).orElse(null); return Key.builder() .partitionValue(partitionValue) .sortValue(sortValue) .build(); }) .collect(Collectors.toList()); } public List<ConsumedCapacity> consumedCapacity() { return this.batchGetItemResponse.consumedCapacity(); } /** * A builder that is used to create a result object with the desired parameters. */ @NotThreadSafe public static final class Builder { private BatchGetItemResponse batchGetItemResponse; private DynamoDbEnhancedClientExtension dynamoDbEnhancedClientExtension; private Builder() { } /** * Adds a response to the result object. Required. * * @param batchGetItemResponse * @return a builder of this type */ public Builder batchGetItemResponse(BatchGetItemResponse batchGetItemResponse) { this.batchGetItemResponse = batchGetItemResponse; return this; } /** * Adds a mapper extension that can be used to modify the values read from the database. * @see DynamoDbEnhancedClientExtension * * @param dynamoDbEnhancedClientExtension the supplied mapper extension * @return a builder of this type */ public Builder mapperExtension(DynamoDbEnhancedClientExtension dynamoDbEnhancedClientExtension) { this.dynamoDbEnhancedClientExtension = dynamoDbEnhancedClientExtension; return this; } public BatchGetResultPage build() { return new BatchGetResultPage(this); } } }
4,325
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/model/GetItemEnhancedRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.model; import java.util.Objects; import java.util.function.Consumer; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbAsyncTable; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.Key; import software.amazon.awssdk.services.dynamodb.model.GetItemRequest; import software.amazon.awssdk.services.dynamodb.model.ReturnConsumedCapacity; /** * Defines parameters used to retrieve an item from a DynamoDb table using the getItem() operation (such as * {@link DynamoDbTable#getItem(GetItemEnhancedRequest)} or {@link DynamoDbAsyncTable#getItem(GetItemEnhancedRequest)}). * <p> * A valid request object must contain a primary {@link Key} to reference the item to get. */ @SdkPublicApi @ThreadSafe public final class GetItemEnhancedRequest { private final Key key; private final Boolean consistentRead; private final String returnConsumedCapacity; private GetItemEnhancedRequest(Builder builder) { this.key = builder.key; this.consistentRead = builder.consistentRead; this.returnConsumedCapacity = builder.returnConsumedCapacity; } /** * All requests must be constructed using a Builder. * @return a builder of this type */ public static Builder builder() { return new Builder(); } /** * @return a builder with all existing values set */ public Builder toBuilder() { return builder().key(key).consistentRead(consistentRead).returnConsumedCapacity(returnConsumedCapacity); } /** * @return whether or not this request will use consistent read */ public Boolean consistentRead() { return this.consistentRead; } /** * Returns the primary {@link Key} for the item to get. */ public Key key() { return this.key; } /** * Whether to return the capacity consumed by this operation. * * @see GetItemRequest#returnConsumedCapacity() */ public ReturnConsumedCapacity returnConsumedCapacity() { return ReturnConsumedCapacity.fromValue(returnConsumedCapacity); } /** * Whether to return the capacity consumed by this operation. * <p> * Similar to {@link #returnConsumedCapacity()} but return the value as a string. This is useful in situations where the * value is not defined in {@link ReturnConsumedCapacity}. */ public String returnConsumedCapacityAsString() { return returnConsumedCapacity; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } GetItemEnhancedRequest that = (GetItemEnhancedRequest) o; return Objects.equals(key, that.key) && Objects.equals(consistentRead, that.consistentRead) && Objects.equals(returnConsumedCapacity, that.returnConsumedCapacity); } @Override public int hashCode() { int result = key != null ? key.hashCode() : 0; result = 31 * result + (consistentRead != null ? consistentRead.hashCode() : 0); result = 31 * result + (returnConsumedCapacity != null ? returnConsumedCapacity.hashCode() : 0); return result; } /** * A builder that is used to create a request with the desired parameters. * <p> * <b>Note</b>: A valid request builder must define a {@link Key}. */ @NotThreadSafe public static final class Builder { private Key key; private Boolean consistentRead; private String returnConsumedCapacity; private Builder() { } /** * Determines the read consistency model: If set to true, the operation uses strongly consistent reads; otherwise, * the operation uses eventually consistent reads. * <p> * By default, the value of this property is set to <em>false</em>. * * @param consistentRead sets consistency model of the operation to use strong consistency * @return a builder of this type */ public Builder consistentRead(Boolean consistentRead) { this.consistentRead = consistentRead; return this; } /** * Sets the primary {@link Key} that will be used to match the item to retrieve. * * @param key the primary key to use in the request. * @return a builder of this type */ public Builder key(Key key) { this.key = key; return this; } /** * Sets the primary {@link Key} that will be used to match the item to retrieve * by accepting a consumer of {@link Key.Builder}. * * @param keyConsumer a {@link Consumer} of {@link Key} * @return a builder of this type */ public Builder key(Consumer<Key.Builder> keyConsumer) { Key.Builder builder = Key.builder(); keyConsumer.accept(builder); return key(builder.build()); } /** * Whether to return the capacity consumed by this operation. * * @see GetItemRequest.Builder#returnConsumedCapacity(ReturnConsumedCapacity) */ public Builder returnConsumedCapacity(ReturnConsumedCapacity returnConsumedCapacity) { this.returnConsumedCapacity = returnConsumedCapacity == null ? null : returnConsumedCapacity.toString(); return this; } /** * Whether to return the capacity consumed by this operation. * * @see GetItemRequest.Builder#returnConsumedCapacity(String) */ public Builder returnConsumedCapacity(String returnConsumedCapacity) { this.returnConsumedCapacity = returnConsumedCapacity; return this; } public GetItemEnhancedRequest build() { return new GetItemEnhancedRequest(this); } } }
4,326
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/model/PagePublisher.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.model; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.core.async.SdkPublisher; /** * Represents the result from paginated operations such as scan and query. * <p> * You can either subscribe to the {@link Page}s or flattened items across <b>all</b> pages via {@link #items()}. * * Example: * <p> * 1) Subscribing to {@link Page}s * <pre> * {@code * * PagePublisher<MyItem> publisher = mappedTable.scan(); * publisher.subscribe(page -> page.items().forEach(item -> System.out.println(item))) * .exceptionally(failure -> { * failure.printStackTrace(); * return null; * }); * } * </pre> * * <p> * 2) Subscribing to items across all pages. * <pre> * {@code * * PagePublisher<MyItem> publisher = mappedTable.scan(); * publisher.items() * .subscribe(item -> System.out.println(item)) * .exceptionally(failure -> { * failure.printStackTrace(); * return null; * }); * } * </pre> * * @param <T> The modelled type of the object in a page. */ @SdkPublicApi @ThreadSafe public interface PagePublisher<T> extends SdkPublisher<Page<T>> { /** * Creates a flattened items publisher with the underlying page publisher. */ static <T> PagePublisher<T> create(SdkPublisher<Page<T>> publisher) { return publisher::subscribe; } /** * Returns a publisher that can be used to request a stream of items across all pages. * * <p> * This method is useful if you are interested in subscribing the items in the response pages * instead of the top level pages. */ default SdkPublisher<T> items() { return this.flatMapIterable(Page::items); } }
4,327
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/model/DeleteItemEnhancedRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.model; import java.util.Objects; import java.util.function.Consumer; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbAsyncTable; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.Expression; import software.amazon.awssdk.enhanced.dynamodb.Key; import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest; import software.amazon.awssdk.services.dynamodb.model.PutItemRequest; import software.amazon.awssdk.services.dynamodb.model.ReturnConsumedCapacity; import software.amazon.awssdk.services.dynamodb.model.ReturnItemCollectionMetrics; /** * Defines parameters used to remove an item from a DynamoDb table using the deleteItem() operation (such as * {@link DynamoDbTable#deleteItem(DeleteItemEnhancedRequest)} or * {@link DynamoDbAsyncTable#deleteItem(DeleteItemEnhancedRequest)}). * <p> * A valid request object must contain a primary {@link Key} to reference the item to delete. */ @SdkPublicApi @ThreadSafe public final class DeleteItemEnhancedRequest { private final Key key; private final Expression conditionExpression; private final String returnConsumedCapacity; private final String returnItemCollectionMetrics; private DeleteItemEnhancedRequest(Builder builder) { this.key = builder.key; this.conditionExpression = builder.conditionExpression; this.returnConsumedCapacity = builder.returnConsumedCapacity; this.returnItemCollectionMetrics = builder.returnItemCollectionMetrics; } /** * Creates a newly initialized builder for a request object. */ public static Builder builder() { return new Builder(); } /** * Returns a builder initialized with all existing values on the request object. */ public Builder toBuilder() { return builder().key(key) .conditionExpression(conditionExpression) .returnConsumedCapacity(returnConsumedCapacity) .returnItemCollectionMetrics(returnItemCollectionMetrics); } /** * Returns the primary {@link Key} for the item to delete. */ public Key key() { return key; } /** * Returns the condition {@link Expression} set on this request object, or null if it doesn't exist. */ public Expression conditionExpression() { return conditionExpression; } /** * Whether to return the capacity consumed by this operation. * * @see PutItemRequest#returnConsumedCapacity() */ public ReturnConsumedCapacity returnConsumedCapacity() { return ReturnConsumedCapacity.fromValue(returnConsumedCapacity); } /** * Whether to return the capacity consumed by this operation. * <p> * Similar to {@link #returnConsumedCapacity()} but return the value as a string. This is useful in situations where the * value is not defined in {@link ReturnConsumedCapacity}. */ public String returnConsumedCapacityAsString() { return returnConsumedCapacity; } /** * Whether to return the item collection metrics. * * @see DeleteItemRequest#returnItemCollectionMetrics() */ public ReturnItemCollectionMetrics returnItemCollectionMetrics() { return ReturnItemCollectionMetrics.fromValue(returnItemCollectionMetrics); } /** * Whether to return the item collection metrics. * <p> * Similar to {@link #returnItemCollectionMetrics()} but return the value as a string. This is useful in situations * where the * value is not defined in {@link ReturnItemCollectionMetrics}. */ public String returnItemCollectionMetricsAsString() { return returnItemCollectionMetrics; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DeleteItemEnhancedRequest that = (DeleteItemEnhancedRequest) o; return Objects.equals(key, that.key) && Objects.equals(conditionExpression, that.conditionExpression) && Objects.equals(returnConsumedCapacity, that.returnConsumedCapacity) && Objects.equals(returnItemCollectionMetrics, that.returnItemCollectionMetrics); } @Override public int hashCode() { int result = key != null ? key.hashCode() : 0; result = 31 * result + (conditionExpression != null ? conditionExpression.hashCode() : 0); result = 31 * result + (returnConsumedCapacity != null ? returnConsumedCapacity.hashCode() : 0); result = 31 * result + (returnItemCollectionMetrics != null ? returnItemCollectionMetrics.hashCode() : 0); return result; } /** * A builder that is used to create a request with the desired parameters. * <p> * <b>Note</b>: A valid request builder must define a {@link Key}. */ @NotThreadSafe public static final class Builder { private Key key; private Expression conditionExpression; private String returnConsumedCapacity; private String returnItemCollectionMetrics; private Builder() { } /** * Sets the primary {@link Key} that will be used to match the item to delete. * * @param key the primary key to use in the request. * @return a builder of this type */ public Builder key(Key key) { this.key = key; return this; } /** * Sets the primary {@link Key} that will be used to match the item to delete * on the builder by accepting a consumer of {@link Key.Builder}. * * @param keyConsumer a {@link Consumer} of {@link Key} * @return a builder of this type */ public Builder key(Consumer<Key.Builder> keyConsumer) { Key.Builder builder = Key.builder(); keyConsumer.accept(builder); return key(builder.build()); } /** * Defines a logical expression on an item's attribute values which, if evaluating to true, * will allow the delete operation to succeed. If evaluating to false, the operation will not succeed. * <p> * See {@link Expression} for condition syntax and examples. * * @param conditionExpression a condition written as an {@link Expression} * @return a builder of this type */ public Builder conditionExpression(Expression conditionExpression) { this.conditionExpression = conditionExpression; return this; } /** * Whether to return the capacity consumed by this operation. * * @see DeleteItemRequest.Builder#returnConsumedCapacity(ReturnConsumedCapacity) */ public Builder returnConsumedCapacity(ReturnConsumedCapacity returnConsumedCapacity) { this.returnConsumedCapacity = returnConsumedCapacity == null ? null : returnConsumedCapacity.toString(); return this; } /** * Whether to return the capacity consumed by this operation. * * @see DeleteItemRequest.Builder#returnConsumedCapacity(String) */ public Builder returnConsumedCapacity(String returnConsumedCapacity) { this.returnConsumedCapacity = returnConsumedCapacity; return this; } /** * Whether to return the item collection metrics. * * @see DeleteItemRequest.Builder#returnItemCollectionMetrics(ReturnItemCollectionMetrics) */ public Builder returnItemCollectionMetrics(ReturnItemCollectionMetrics returnItemCollectionMetrics) { this.returnItemCollectionMetrics = returnItemCollectionMetrics == null ? null : returnItemCollectionMetrics.toString(); return this; } /** * Whether to return the item collection metrics. * * @see DeleteItemRequest.Builder#returnItemCollectionMetrics(String) */ public Builder returnItemCollectionMetrics(String returnItemCollectionMetrics) { this.returnItemCollectionMetrics = returnItemCollectionMetrics; return this; } public DeleteItemEnhancedRequest build() { return new DeleteItemEnhancedRequest(this); } } }
4,328
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/model/DescribeTableEnhancedResponse.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.model; import java.util.Objects; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbAsyncTable; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.services.dynamodb.model.DescribeTableResponse; import software.amazon.awssdk.services.dynamodb.model.TableDescription; import software.amazon.awssdk.utils.ToString; import software.amazon.awssdk.utils.Validate; /** * Defines the elements returned by DynamoDB from a {@code DescribeTable} operation, such as * {@link DynamoDbTable#describeTable()} and {@link DynamoDbAsyncTable#describeTable()} */ @SdkPublicApi @ThreadSafe public final class DescribeTableEnhancedResponse { private final DescribeTableResponse response; private DescribeTableEnhancedResponse(Builder builder) { this.response = Validate.paramNotNull(builder.response, "response"); } /** * The properties of the table. * * @return The properties of the table. */ public TableDescription table() { return response.table(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DescribeTableEnhancedResponse that = (DescribeTableEnhancedResponse) o; return Objects.equals(response, that.response); } @Override public int hashCode() { return response != null ? response.hashCode() : 0; } @Override public String toString() { return ToString.builder("DescribeTableEnhancedResponse") .add("table", response.table()) .build(); } public static Builder builder() { return new Builder(); } @NotThreadSafe public static final class Builder { private DescribeTableResponse response; public Builder response(DescribeTableResponse response) { this.response = response; return this; } public DescribeTableEnhancedResponse build() { return new DescribeTableEnhancedResponse(this); } } }
4,329
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/model/ConditionCheck.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.model; import java.util.Objects; import java.util.function.Consumer; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClientExtension; import software.amazon.awssdk.enhanced.dynamodb.Expression; import software.amazon.awssdk.enhanced.dynamodb.Key; import software.amazon.awssdk.enhanced.dynamodb.OperationContext; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.TransactableWriteOperation; import software.amazon.awssdk.services.dynamodb.model.ReturnValuesOnConditionCheckFailure; import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem; /** * Use ConditionCheck as a part of the composite operation transactGetItems (for example * {@link DynamoDbEnhancedClient#transactGetItems(TransactGetItemsEnhancedRequest)}) to determine * if the other actions that are part of the same transaction should take effect. * <p> * A valid ConditionCheck object should contain a reference to the primary key of the table that finds items with a matching key, * together with a condition (of type {@link Expression}) to evaluate the primary key. * * @param <T> The type of the modelled object. */ @SdkPublicApi @ThreadSafe public final class ConditionCheck<T> implements TransactableWriteOperation<T> { private final Key key; private final Expression conditionExpression; private final String returnValuesOnConditionCheckFailure; private ConditionCheck(Builder builder) { this.key = builder.key; this.conditionExpression = builder.conditionExpression; this.returnValuesOnConditionCheckFailure = builder.returnValuesOnConditionCheckFailure; } /** * Creates a newly initialized builder for this object. */ public static Builder builder() { return new Builder(); } /** * Returns a builder initialized with all existing values on the object. */ public Builder toBuilder() { return new Builder().key(key) .conditionExpression(conditionExpression) .returnValuesOnConditionCheckFailure(returnValuesOnConditionCheckFailure); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ConditionCheck<?> that = (ConditionCheck<?>) o; if (!Objects.equals(key, that.key)) { return false; } if (!Objects.equals(conditionExpression, that.conditionExpression)) { return false; } return Objects.equals(returnValuesOnConditionCheckFailure, that.returnValuesOnConditionCheckFailure); } @Override public int hashCode() { int result = Objects.hashCode(key); result = 31 * result + Objects.hashCode(conditionExpression); result = 31 * result + Objects.hashCode(returnValuesOnConditionCheckFailure); return result; } /** * Returns the primary {@link Key} that the condition is valid for, or null if it doesn't exist. */ public Key key() { return key; } /** * Returns the condition {@link Expression} set on this object, or null if it doesn't exist. */ public Expression conditionExpression() { return conditionExpression; } /** * Returns what values to return if the condition check fails. * <p> * If the service returns an enum value that is not available in the current SDK version, * {@link #returnValuesOnConditionCheckFailure} will return * {@link ReturnValuesOnConditionCheckFailure#UNKNOWN_TO_SDK_VERSION}. The raw value returned by the service is * available from {@link #returnValuesOnConditionCheckFailureAsString}. * * @return What values to return on condition check failure. */ public ReturnValuesOnConditionCheckFailure returnValuesOnConditionCheckFailure() { return ReturnValuesOnConditionCheckFailure.fromValue(returnValuesOnConditionCheckFailure); } /** * Returns what values to return if the condition check fails. * <p> * If the service returns an enum value that is not available in the current SDK version, * {@link #returnValuesOnConditionCheckFailure} will return * {@link ReturnValuesOnConditionCheckFailure#UNKNOWN_TO_SDK_VERSION}. The raw value returned by the service is * available from {@link #returnValuesOnConditionCheckFailureAsString}. * * @return What values to return on condition check failure. */ public String returnValuesOnConditionCheckFailureAsString() { return returnValuesOnConditionCheckFailure; } @Override public TransactWriteItem generateTransactWriteItem(TableSchema<T> tableSchema, OperationContext operationContext, DynamoDbEnhancedClientExtension dynamoDbEnhancedClientExtension) { software.amazon.awssdk.services.dynamodb.model.ConditionCheck conditionCheck = software.amazon.awssdk.services.dynamodb.model.ConditionCheck .builder() .tableName(operationContext.tableName()) .key(key.keyMap(tableSchema, operationContext.indexName())) .conditionExpression(conditionExpression.expression()) .expressionAttributeNames(conditionExpression.expressionNames()) .expressionAttributeValues(conditionExpression.expressionValues()) .returnValuesOnConditionCheckFailure(returnValuesOnConditionCheckFailure) .build(); return TransactWriteItem.builder() .conditionCheck(conditionCheck) .build(); } /** * A builder that is used to create a condition check with the desired parameters. * <p> * A valid builder must define both a {@link Key} and an {@link Expression}. */ @NotThreadSafe public static final class Builder { private Key key; private Expression conditionExpression; private String returnValuesOnConditionCheckFailure; private Builder() { } /** * Sets the primary {@link Key} that will be used together with the condition expression. * * @param key the primary key to use in the operation. * @return a builder of this type */ public Builder key(Key key) { this.key = key; return this; } /** * Sets the primary {@link Key} that will be used together with the condition expression * on the builder by accepting a consumer of {@link Key.Builder}. * * @param keyConsumer a {@link Consumer} of {@link Key} * @return a builder of this type */ public Builder key(Consumer<Key.Builder> keyConsumer) { Key.Builder builder = Key.builder(); keyConsumer.accept(builder); return key(builder.build()); } /** * Defines a logical expression on the attributes of table items that match the supplied primary key value(s). * If the expression evaluates to true, the transaction operation succeeds. If the expression evaluates to false, * the transaction will not succeed. * <p> * See {@link Expression} for condition syntax and examples. * * @param conditionExpression a condition written as an {@link Expression} * @return a builder of this type */ public Builder conditionExpression(Expression conditionExpression) { this.conditionExpression = conditionExpression; return this; } /** * Use <code>ReturnValuesOnConditionCheckFailure</code> to get the item attributes if the <code>ConditionCheck</code> * condition fails. For <code>ReturnValuesOnConditionCheckFailure</code>, the valid values are: NONE and * ALL_OLD. * * @param returnValuesOnConditionCheckFailure What values to return on condition check failure. * @return a builder of this type */ public Builder returnValuesOnConditionCheckFailure( ReturnValuesOnConditionCheckFailure returnValuesOnConditionCheckFailure) { this.returnValuesOnConditionCheckFailure = returnValuesOnConditionCheckFailure == null ? null : returnValuesOnConditionCheckFailure.toString(); return this; } /** * Use <code>ReturnValuesOnConditionCheckFailure</code> to get the item attributes if the <code>ConditionCheck</code> * condition fails. For <code>ReturnValuesOnConditionCheckFailure</code>, the valid values are: NONE and * ALL_OLD. * * @param returnValuesOnConditionCheckFailure What values to return on condition check failure. * @return a builder of this type */ public Builder returnValuesOnConditionCheckFailure(String returnValuesOnConditionCheckFailure) { this.returnValuesOnConditionCheckFailure = returnValuesOnConditionCheckFailure; return this; } public <T> ConditionCheck<T> build() { return new ConditionCheck<T>(this); } } }
4,330
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/model/BatchWriteItemEnhancedRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.model; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; /** * Defines parameters used for the batchWriteItem() operation (such as * {@link DynamoDbEnhancedClient#batchWriteItem(BatchWriteItemEnhancedRequest)}). * <p> * A request contains references to keys for delete actions and items for put actions, * organized into one {@link WriteBatch} object per accessed table. */ @SdkPublicApi @ThreadSafe public final class BatchWriteItemEnhancedRequest { private final List<WriteBatch> writeBatches; private BatchWriteItemEnhancedRequest(Builder builder) { this.writeBatches = getListIfExist(builder.writeBatches); } /** * Creates a newly initialized builder for a request object. */ public static Builder builder() { return new Builder(); } /** * Returns a builder initialized with all existing values on the request object. */ public Builder toBuilder() { return new Builder().writeBatches(writeBatches); } /** * Returns the collection of {@link WriteBatch} in this request object. */ public Collection<WriteBatch> writeBatches() { return writeBatches; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } BatchWriteItemEnhancedRequest that = (BatchWriteItemEnhancedRequest) o; return writeBatches != null ? writeBatches.equals(that.writeBatches) : that.writeBatches == null; } @Override public int hashCode() { return writeBatches != null ? writeBatches.hashCode() : 0; } private static List<WriteBatch> getListIfExist(List<WriteBatch> writeBatches) { return writeBatches != null ? Collections.unmodifiableList(writeBatches) : null; } /** * A builder that is used to create a request with the desired parameters. */ @NotThreadSafe public static final class Builder { private List<WriteBatch> writeBatches; private Builder() { } /** * Sets a collection of write batches to use in the batchWriteItem operation. * * @param writeBatches the collection of write batches * @return a builder of this type */ public Builder writeBatches(Collection<WriteBatch> writeBatches) { this.writeBatches = writeBatches != null ? new ArrayList<>(writeBatches) : null; return this; } /** * Sets one or more write batches to use in the batchWriteItem operation. * * @param writeBatches one or more {@link WriteBatch}, separated by comma. * @return a builder of this type */ public Builder writeBatches(WriteBatch... writeBatches) { this.writeBatches = Arrays.asList(writeBatches); return this; } /** * Adds a write batch to the collection of batches on this builder. * If this is the first batch, the method creates a new list. * * @param writeBatch a single write batch * @return a builder of this type */ public Builder addWriteBatch(WriteBatch writeBatch) { if (writeBatches == null) { writeBatches = new ArrayList<>(); } writeBatches.add(writeBatch); return this; } public BatchWriteItemEnhancedRequest build() { return new BatchWriteItemEnhancedRequest(this); } } }
4,331
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/model/CreateTableEnhancedRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.model; import java.util.Arrays; import java.util.Collection; import java.util.function.Consumer; 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.DynamoDbAsyncTable; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughput; import software.amazon.awssdk.services.dynamodb.model.StreamSpecification; /** * Defines parameters used to create a DynamoDb table using the createTable() operation (such as * {@link DynamoDbTable#createTable(CreateTableEnhancedRequest)} or * {@link DynamoDbAsyncTable#createTable(CreateTableEnhancedRequest)}). * <p> * All parameters are optional. */ @SdkPublicApi @ThreadSafe public final class CreateTableEnhancedRequest { private final ProvisionedThroughput provisionedThroughput; private final StreamSpecification streamSpecification; private final Collection<EnhancedLocalSecondaryIndex> localSecondaryIndices; private final Collection<EnhancedGlobalSecondaryIndex> globalSecondaryIndices; private CreateTableEnhancedRequest(Builder builder) { this.provisionedThroughput = builder.provisionedThroughput; this.streamSpecification = builder.streamSpecification; this.localSecondaryIndices = builder.localSecondaryIndices; this.globalSecondaryIndices = builder.globalSecondaryIndices; } /** * Creates a newly initialized builder for a request object. */ public static Builder builder() { return new Builder(); } /** * Returns a builder initialized with all existing values on the request object. */ public Builder toBuilder() { return builder().provisionedThroughput(provisionedThroughput) .streamSpecification(streamSpecification) .localSecondaryIndices(localSecondaryIndices) .globalSecondaryIndices(globalSecondaryIndices); } /** * Returns the provisioned throughput value set on this request object, or null if it has not been set. */ public ProvisionedThroughput provisionedThroughput() { return provisionedThroughput; } /** * Returns the stream specification value set on this request object, or null if it has not been set. */ public StreamSpecification streamSpecification() { return streamSpecification; } /** * Returns the local secondary index set on this request object, or null if it has not been set. */ public Collection<EnhancedLocalSecondaryIndex> localSecondaryIndices() { return localSecondaryIndices; } /** * Returns the global secondary index set on this request object, or null if it has not been set. */ public Collection<EnhancedGlobalSecondaryIndex> globalSecondaryIndices() { return globalSecondaryIndices; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CreateTableEnhancedRequest that = (CreateTableEnhancedRequest) o; if (provisionedThroughput != null ? ! provisionedThroughput.equals(that.provisionedThroughput) : that.provisionedThroughput != null) { return false; } if (streamSpecification != null ? ! streamSpecification.equals(that.streamSpecification) : that.streamSpecification != null) { return false; } if (localSecondaryIndices != null ? ! localSecondaryIndices.equals(that.localSecondaryIndices) : that.localSecondaryIndices != null) { return false; } return globalSecondaryIndices != null ? globalSecondaryIndices.equals(that.globalSecondaryIndices) : that.globalSecondaryIndices == null; } @Override public int hashCode() { int result = provisionedThroughput != null ? provisionedThroughput.hashCode() : 0; result = 31 * result + (streamSpecification != null ? streamSpecification.hashCode() : 0); result = 31 * result + (localSecondaryIndices != null ? localSecondaryIndices.hashCode() : 0); result = 31 * result + (globalSecondaryIndices != null ? globalSecondaryIndices.hashCode() : 0); return result; } /** * A builder that is used to create a request with the desired parameters. */ @NotThreadSafe public static final class Builder { private ProvisionedThroughput provisionedThroughput; private StreamSpecification streamSpecification; private Collection<EnhancedLocalSecondaryIndex> localSecondaryIndices; private Collection<EnhancedGlobalSecondaryIndex> globalSecondaryIndices; private Builder() { } /** * Sets the provisioned throughput for this table. Use this parameter to set the table's * read and write capacity units. * <p> * See the DynamoDb documentation for more information on default throughput values. */ public Builder provisionedThroughput(ProvisionedThroughput provisionedThroughput) { this.provisionedThroughput = provisionedThroughput; return this; } /** * This is a convenience method for {@link #provisionedThroughput(ProvisionedThroughput)} that creates an instance of the * {@link ProvisionedThroughput.Builder} for you, avoiding the need to create one manually via * {@link ProvisionedThroughput#builder()}. */ public Builder provisionedThroughput(Consumer<ProvisionedThroughput.Builder> provisionedThroughput) { ProvisionedThroughput.Builder builder = ProvisionedThroughput.builder(); provisionedThroughput.accept(builder); return provisionedThroughput(builder.build()); } /** * Sets the {@link StreamSpecification} for this table. * <p> * See the DynamoDb documentation for more information on stream specification values. */ public Builder streamSpecification(StreamSpecification streamSpecification) { this.streamSpecification = streamSpecification; return this; } /** * This is a convenience method for {@link #streamSpecification(StreamSpecification)} that creates an instance of the * {@link StreamSpecification.Builder} for you, avoiding the need to create one manually via * {@link StreamSpecification#builder()}. */ public Builder streamSpecification(Consumer<StreamSpecification.Builder> streamSpecification) { StreamSpecification.Builder builder = StreamSpecification.builder(); streamSpecification.accept(builder); return streamSpecification(builder.build()); } /** * Defines a local secondary index for this table. * <p> * See {@link EnhancedLocalSecondaryIndex} for more information on creating and using a local secondary index. */ public Builder localSecondaryIndices(Collection<EnhancedLocalSecondaryIndex> localSecondaryIndices) { this.localSecondaryIndices = localSecondaryIndices; return this; } /** * Defines a local secondary index for this table. * <p> * See {@link EnhancedLocalSecondaryIndex} for more information on creating and using a local secondary index. */ public Builder localSecondaryIndices(EnhancedLocalSecondaryIndex... localSecondaryIndices) { this.localSecondaryIndices = Arrays.asList(localSecondaryIndices); return this; } /** * This is a convenience method for {@link #localSecondaryIndices(Collection)} that creates instances of the * {@link EnhancedLocalSecondaryIndex.Builder} for you, avoiding the need to create them manually via * {@link EnhancedLocalSecondaryIndex#builder()}. */ @SafeVarargs public final Builder localSecondaryIndices(Consumer<EnhancedLocalSecondaryIndex.Builder>... localSecondaryIndices) { return localSecondaryIndices(Stream.of(localSecondaryIndices).map(lsi -> { EnhancedLocalSecondaryIndex.Builder builder = EnhancedLocalSecondaryIndex.builder(); lsi.accept(builder); return builder.build(); }).collect(Collectors.toList())); } /** * Defines a global secondary index for this table. * <p> * See {@link EnhancedGlobalSecondaryIndex} for more information on creating and using a global secondary index. */ public Builder globalSecondaryIndices(Collection<EnhancedGlobalSecondaryIndex> globalSecondaryIndices) { this.globalSecondaryIndices = globalSecondaryIndices; return this; } /** * Defines a global secondary index for this table. * <p> * See {@link EnhancedGlobalSecondaryIndex} for more information on creating and using a global secondary index. */ public Builder globalSecondaryIndices(EnhancedGlobalSecondaryIndex... globalSecondaryIndices) { this.globalSecondaryIndices = Arrays.asList(globalSecondaryIndices); return this; } /** * This is a convenience method for {@link #globalSecondaryIndices(Collection)} that creates instances of the * {@link EnhancedGlobalSecondaryIndex.Builder} for you, avoiding the need to create them manually via * {@link EnhancedGlobalSecondaryIndex#builder()}. */ @SafeVarargs public final Builder globalSecondaryIndices(Consumer<EnhancedGlobalSecondaryIndex.Builder>... globalSecondaryIndices) { return globalSecondaryIndices(Stream.of(globalSecondaryIndices).map(gsi -> { EnhancedGlobalSecondaryIndex.Builder builder = EnhancedGlobalSecondaryIndex.builder(); gsi.accept(builder); return builder.build(); }).collect(Collectors.toList())); } public CreateTableEnhancedRequest build() { return new CreateTableEnhancedRequest(this); } } }
4,332
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/model/BatchGetItemEnhancedRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.model; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Objects; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.services.dynamodb.model.BatchGetItemRequest; import software.amazon.awssdk.services.dynamodb.model.GetItemRequest; import software.amazon.awssdk.services.dynamodb.model.ReturnConsumedCapacity; /** * Defines parameters used for the batchGetItem() operation (such as * {@link DynamoDbEnhancedClient#batchGetItem(BatchGetItemEnhancedRequest)}). * <p> * A request contains references to keys and tables organized into one {@link ReadBatch} object per queried table. */ @SdkPublicApi @ThreadSafe public final class BatchGetItemEnhancedRequest { private final List<ReadBatch> readBatches; private final String returnConsumedCapacity; private BatchGetItemEnhancedRequest(Builder builder) { this.readBatches = getListIfExist(builder.readBatches); this.returnConsumedCapacity = builder.returnConsumedCapacity; } /** * Creates a newly initialized builder for a request object. */ public static Builder builder() { return new Builder(); } /** * Returns a builder initialized with all existing values on the request object. */ public Builder toBuilder() { return new Builder().readBatches(readBatches).returnConsumedCapacity(this.returnConsumedCapacity); } /** * Returns the collection of {@link ReadBatch} in this request object. */ public Collection<ReadBatch> readBatches() { return readBatches; } /** * Whether to return the capacity consumed by this operation. * * @see GetItemRequest#returnConsumedCapacity() */ public ReturnConsumedCapacity returnConsumedCapacity() { return ReturnConsumedCapacity.fromValue(returnConsumedCapacity); } /** * Whether to return the capacity consumed by this operation. * <p> * Similar to {@link #returnConsumedCapacity()} but return the value as a string. This is useful in situations where the * value is not defined in {@link ReturnConsumedCapacity}. */ public String returnConsumedCapacityAsString() { return returnConsumedCapacity; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } BatchGetItemEnhancedRequest that = (BatchGetItemEnhancedRequest) o; return Objects.equals(this.readBatches, that.readBatches) && Objects.equals(this.returnConsumedCapacity, that.returnConsumedCapacity); } @Override public int hashCode() { int hc = readBatches != null ? readBatches.hashCode() : 0; hc = 31 * hc + (returnConsumedCapacity != null ? returnConsumedCapacity.hashCode() : 0); return hc; } private static List<ReadBatch> getListIfExist(List<ReadBatch> readBatches) { return readBatches != null ? Collections.unmodifiableList(readBatches) : null; } /** * A builder that is used to create a request with the desired parameters. */ @NotThreadSafe public static final class Builder { private List<ReadBatch> readBatches; private String returnConsumedCapacity; private Builder() { } /** * Sets a collection of read batches to use in the batchGetItem operation. * * @param readBatches the collection of read batches * @return a builder of this type */ public Builder readBatches(Collection<ReadBatch> readBatches) { this.readBatches = readBatches != null ? new ArrayList<>(readBatches) : null; return this; } /** * Sets one or more read batches to use in the batchGetItem operation. * * @param readBatches one or more {@link ReadBatch}, separated by comma. * @return a builder of this type */ public Builder readBatches(ReadBatch... readBatches) { this.readBatches = Arrays.asList(readBatches); return this; } /** * Adds a read batch to the collection of batches on this builder. * If this is the first batch, the method creates a new list. * * @param readBatch a single read batch * @return a builder of this type */ public Builder addReadBatch(ReadBatch readBatch) { if (readBatches == null) { readBatches = new ArrayList<>(); } readBatches.add(readBatch); return this; } /** * Whether to return the capacity consumed by this operation. * * @see BatchGetItemRequest.Builder#returnConsumedCapacity(ReturnConsumedCapacity) * @return a builder of this type */ public Builder returnConsumedCapacity(ReturnConsumedCapacity returnConsumedCapacity) { this.returnConsumedCapacity = returnConsumedCapacity == null ? null : returnConsumedCapacity.toString(); return this; } /** * Whether to return the capacity consumed by this operation. * * @see BatchGetItemRequest.Builder#returnConsumedCapacity(String) * @return a builder of this type */ public Builder returnConsumedCapacity(String returnConsumedCapacity) { this.returnConsumedCapacity = returnConsumedCapacity; return this; } public BatchGetItemEnhancedRequest build() { return new BatchGetItemEnhancedRequest(this); } } }
4,333
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/model/TransactUpdateItemEnhancedRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.model; import java.util.Objects; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedAsyncClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.Expression; import software.amazon.awssdk.services.dynamodb.model.ReturnValuesOnConditionCheckFailure; /** * Defines parameters used to update an item to a DynamoDb table using the * {@link DynamoDbEnhancedClient#transactWriteItems(TransactWriteItemsEnhancedRequest)} or * {@link DynamoDbEnhancedAsyncClient#transactWriteItems(TransactWriteItemsEnhancedRequest)} * operation. * <p> * A valid request object must contain the item that should be written to the table. * * @param <T> The type of the modelled object. */ @SdkPublicApi @ThreadSafe public class TransactUpdateItemEnhancedRequest<T> { private final T item; private final Boolean ignoreNulls; private final Expression conditionExpression; private final String returnValuesOnConditionCheckFailure; private TransactUpdateItemEnhancedRequest(Builder<T> builder) { this.item = builder.item; this.ignoreNulls = builder.ignoreNulls; this.conditionExpression = builder.conditionExpression; this.returnValuesOnConditionCheckFailure = builder.returnValuesOnConditionCheckFailure; } /** * Creates a newly initialized builder for the request object. * * @param itemClass the class that items in this table map to * @param <T> The type of the modelled object, corresponding to itemClass * @return a UpdateItemEnhancedRequest builder */ public static <T> Builder<T> builder(Class<? extends T> itemClass) { return new Builder<>(); } /** * Returns a builder initialized with all existing values on the request object. */ public Builder<T> toBuilder() { return new Builder<T>().item(item) .ignoreNulls(ignoreNulls) .conditionExpression(conditionExpression) .returnValuesOnConditionCheckFailure(returnValuesOnConditionCheckFailure); } /** * Returns the item for this update operation request. */ public T item() { return item; } /** * Returns if the update operation should ignore attributes with null values, or false if it has not been set. */ public Boolean ignoreNulls() { return ignoreNulls; } /** * Returns the condition {@link Expression} set on this request object, or null if it doesn't exist. */ public Expression conditionExpression() { return conditionExpression; } /** * Returns what values to return if the condition check fails. * <p> * If the service returns an enum value that is not available in the current SDK version, * {@link #returnValuesOnConditionCheckFailure} will return * {@link ReturnValuesOnConditionCheckFailure#UNKNOWN_TO_SDK_VERSION}. The raw value returned by the service is * available from {@link #returnValuesOnConditionCheckFailureAsString}. * * @return What values to return on condition check failure. */ public ReturnValuesOnConditionCheckFailure returnValuesOnConditionCheckFailure() { return ReturnValuesOnConditionCheckFailure.fromValue(returnValuesOnConditionCheckFailure); } /** * Returns what values to return if the condition check fails. * <p> * If the service returns an enum value that is not available in the current SDK version, * {@link #returnValuesOnConditionCheckFailure} will return * {@link ReturnValuesOnConditionCheckFailure#UNKNOWN_TO_SDK_VERSION}. The raw value returned by the service is * available from {@link #returnValuesOnConditionCheckFailureAsString}. * * @return What values to return on condition check failure. */ public String returnValuesOnConditionCheckFailureAsString() { return returnValuesOnConditionCheckFailure; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } TransactUpdateItemEnhancedRequest<?> that = (TransactUpdateItemEnhancedRequest<?>) o; if (!Objects.equals(item, that.item)) { return false; } if (!Objects.equals(ignoreNulls, that.ignoreNulls)) { return false; } if (!Objects.equals(conditionExpression, that.conditionExpression)) { return false; } return Objects.equals(returnValuesOnConditionCheckFailure, that.returnValuesOnConditionCheckFailure); } @Override public int hashCode() { int result = Objects.hashCode(item); result = 31 * result + Objects.hashCode(ignoreNulls); result = 31 * result + Objects.hashCode(conditionExpression); result = 31 * result + Objects.hashCode(returnValuesOnConditionCheckFailure); return result; } /** * A builder that is used to create a request with the desired parameters. * <p> * <b>Note</b>: A valid request builder must define an item. */ @NotThreadSafe public static final class Builder<T> { private T item; private Boolean ignoreNulls; private Expression conditionExpression; private String returnValuesOnConditionCheckFailure; private Builder() { } /** * Sets if the update operation should ignore attributes with null values. By default, the value is false. * <p> * If set to true, any null values in the Java object will be ignored and not be updated on the persisted * record. This is commonly referred to as a 'partial update'. * If set to false, null values in the Java object will cause those attributes to be removed from the persisted * record on update. * * @param ignoreNulls the boolean value * @return a builder of this type */ public Builder<T> ignoreNulls(Boolean ignoreNulls) { this.ignoreNulls = ignoreNulls; return this; } /** * Defines a logical expression on an item's attribute values which, if evaluating to true, * will allow the update operation to succeed. If evaluating to false, the operation will not succeed. * <p> * See {@link Expression} for condition syntax and examples. * * @param conditionExpression a condition written as an {@link Expression} * @return a builder of this type */ public Builder<T> conditionExpression(Expression conditionExpression) { this.conditionExpression = conditionExpression; return this; } /** * Sets the item to write to DynamoDb. Required. * * @param item the item to write * @return a builder of this type */ public Builder<T> item(T item) { this.item = item; return this; } /** * Use <code>ReturnValuesOnConditionCheckFailure</code> to get the item attributes if the <code>ConditionCheck</code> * condition fails. For <code>ReturnValuesOnConditionCheckFailure</code>, the valid values are: NONE and * ALL_OLD. * * @param returnValuesOnConditionCheckFailure What values to return on condition check failure. * @return a builder of this type */ public Builder<T> returnValuesOnConditionCheckFailure( ReturnValuesOnConditionCheckFailure returnValuesOnConditionCheckFailure) { this.returnValuesOnConditionCheckFailure = returnValuesOnConditionCheckFailure == null ? null : returnValuesOnConditionCheckFailure.toString(); return this; } /** * Use <code>ReturnValuesOnConditionCheckFailure</code> to get the item attributes if the <code>ConditionCheck</code> * condition fails. For <code>ReturnValuesOnConditionCheckFailure</code>, the valid values are: NONE and * ALL_OLD. * * @param returnValuesOnConditionCheckFailure What values to return on condition check failure. * @return a builder of this type */ public Builder<T> returnValuesOnConditionCheckFailure(String returnValuesOnConditionCheckFailure) { this.returnValuesOnConditionCheckFailure = returnValuesOnConditionCheckFailure; return this; } public TransactUpdateItemEnhancedRequest<T> build() { return new TransactUpdateItemEnhancedRequest<>(this); } } }
4,334
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/model/PageIterable.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.model; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.core.pagination.sync.PaginatedItemsIterable; import software.amazon.awssdk.core.pagination.sync.SdkIterable; /** * Page iterable represents the result from paginated operations such as scan and query. * * <p> * The result can be accessed either through iterable {@link Page}s or flattened items across <b>all</b> pages via * {@link #items()} * * <p> * Example: * <p> * 1) Iterating through pages * * <pre> * {@code * PageIterable<MyItem> results = table.scan(); * results.stream().forEach(p -> p.items().forEach(item -> System.out.println(item))) * } * </pre> * * 2) Iterating through items * * <pre> * {@code * PageIterable<MyItem> results = table.scan(); * results.items().stream().forEach(item -> System.out.println(item)); * } * </pre> * @param <T> The modelled type of the object in a page. */ @SdkPublicApi @ThreadSafe public interface PageIterable<T> extends SdkIterable<Page<T>> { static <T> PageIterable<T> create(SdkIterable<Page<T>> pageIterable) { return pageIterable::iterator; } /** * Returns an iterable to iterate through the paginated {@link Page#items()} across <b>all</b> response pages. * * <p> * This method is useful if you are interested in iterating over the items in the response pages * instead of the top level pages. */ default SdkIterable<T> items() { return PaginatedItemsIterable.<Page<T>, T>builder() .pagesIterable(this) .itemIteratorFunction(page -> page.items().iterator()) .build(); } }
4,335
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/model/ReadBatch.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.model; import static java.util.Objects.requireNonNull; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.function.Consumer; import java.util.stream.Collectors; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.Key; import software.amazon.awssdk.enhanced.dynamodb.MappedTableResource; import software.amazon.awssdk.enhanced.dynamodb.TableMetadata; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.KeysAndAttributes; /** * Defines a collection of primary keys for items in a table, stored as {@link KeysAndAttributes}, and * used for the batchGetItem() operation (such as * {@link DynamoDbEnhancedClient#batchGetItem(BatchGetItemEnhancedRequest)}) as part of a * {@link BatchGetItemEnhancedRequest}. * <p> * A valid request object should contain one or more primary keys. */ @SdkPublicApi @ThreadSafe public final class ReadBatch { private final String tableName; private final KeysAndAttributes keysAndAttributes; private ReadBatch(BuilderImpl<?> builder) { this.tableName = builder.mappedTableResource != null ? builder.mappedTableResource.tableName() : null; this.keysAndAttributes = generateKeysAndAttributes(builder.requests, builder.mappedTableResource); } /** * Creates a newly initialized builder for a read batch. * * @param itemClass the class that items in this table map to * @param <T> The type of the modelled object, corresponding to itemClass * @return a ReadBatch builder */ public static <T> Builder<T> builder(Class<? extends T> itemClass) { return new BuilderImpl<>(); } /** * Returns the table name associated with this batch. */ public String tableName() { return tableName; } /** * Returns the collection of keys and attributes, see {@link KeysAndAttributes}, in this read batch. */ public KeysAndAttributes keysAndAttributes() { return keysAndAttributes; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ReadBatch readBatch = (ReadBatch) o; if (tableName != null ? !tableName.equals(readBatch.tableName) : readBatch.tableName != null) { return false; } return keysAndAttributes != null ? keysAndAttributes.equals(readBatch.keysAndAttributes) : readBatch.keysAndAttributes == null; } @Override public int hashCode() { int result = tableName != null ? tableName.hashCode() : 0; result = 31 * result + (keysAndAttributes != null ? keysAndAttributes.hashCode() : 0); return result; } /** * A builder that is used to create a request with the desired parameters. * <p> * A valid builder must define a {@link MappedTableResource} and add at least one * {@link GetItemEnhancedRequest}. * * @param <T> the type that items in this table map to */ @NotThreadSafe public interface Builder<T> { /** * Sets the mapped table resource (table) that the items in this read batch should come from. * * @param mappedTableResource the table reference * @return a builder of this type */ Builder<T> mappedTableResource(MappedTableResource<T> mappedTableResource); /** * Adds a {@link GetItemEnhancedRequest} with a primary {@link Key} to the builder. * * @param request A {@link GetItemEnhancedRequest} * @return a builder of this type */ Builder<T> addGetItem(GetItemEnhancedRequest request); /** * Adds a {@link GetItemEnhancedRequest} with a primary {@link Key} to the builder by accepting a consumer of * {@link GetItemEnhancedRequest.Builder}. * * @param requestConsumer a {@link Consumer} of {@link GetItemEnhancedRequest} * @return a builder of this type */ Builder<T> addGetItem(Consumer<GetItemEnhancedRequest.Builder> requestConsumer); /** * Adds a GetItem request with a primary {@link Key} to the builder. * * @param key A {@link Key} to match the record retrieved from the database. * @return a builder of this type */ Builder<T> addGetItem(Key key); /** * Adds a GetItem request to the builder. * * @param keyItem an item that will have its key fields used to match a record to retrieve from the database. * @return a builder of this type */ Builder<T> addGetItem(T keyItem); ReadBatch build(); } private static <T> KeysAndAttributes generateKeysAndAttributes(List<GetItemEnhancedRequest> readRequests, MappedTableResource<T> mappedTableResource) { if (readRequests == null || readRequests.isEmpty()) { return null; } Boolean firstRecordConsistentRead = validateAndGetConsistentRead(readRequests); requireNonNull(mappedTableResource, "A mappedTableResource (table) is required when generating the read requests for " + "ReadBatch"); List<Map<String, AttributeValue>> keys = readRequests.stream() .map(GetItemEnhancedRequest::key) .map(key -> key.keyMap(mappedTableResource.tableSchema(), TableMetadata.primaryIndexName())) .collect(Collectors.toList()); return KeysAndAttributes.builder() .keys(keys) .consistentRead(firstRecordConsistentRead) .build(); } private static Boolean validateAndGetConsistentRead(List<GetItemEnhancedRequest> readRequests) { Boolean firstRecordConsistentRead = null; boolean isFirstRecord = true; for (GetItemEnhancedRequest request : readRequests) { if (isFirstRecord) { isFirstRecord = false; firstRecordConsistentRead = request.consistentRead(); } else { if (!compareNullableBooleans(firstRecordConsistentRead, request.consistentRead())) { throw new IllegalArgumentException("All batchable read requests for the same " + "table must have the same 'consistentRead' " + "setting."); } } } return firstRecordConsistentRead; } private static boolean compareNullableBooleans(Boolean one, Boolean two) { if (one == null && two == null) { return true; } if (one != null) { return one.equals(two); } else { return false; } } @NotThreadSafe private static final class BuilderImpl<T> implements Builder<T> { private MappedTableResource<T> mappedTableResource; private List<GetItemEnhancedRequest> requests = new ArrayList<>(); private BuilderImpl() { } @Override public Builder<T> mappedTableResource(MappedTableResource<T> mappedTableResource) { this.mappedTableResource = mappedTableResource; return this; } @Override public Builder<T> addGetItem(GetItemEnhancedRequest request) { requests.add(request); return this; } @Override public Builder<T> addGetItem(Consumer<GetItemEnhancedRequest.Builder> requestConsumer) { GetItemEnhancedRequest.Builder builder = GetItemEnhancedRequest.builder(); requestConsumer.accept(builder); return addGetItem(builder.build()); } @Override public Builder<T> addGetItem(Key key) { return addGetItem(r -> r.key(key)); } @Override public Builder<T> addGetItem(T keyItem) { requireNonNull(mappedTableResource, "A mappedTableResource is required to derive a key from the given keyItem"); return addGetItem(this.mappedTableResource.keyFrom(keyItem)); } @Override public ReadBatch build() { return new ReadBatch(this); } } }
4,336
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/model/GetItemEnhancedResponse.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.model; import java.util.Objects; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbAsyncTable; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.services.dynamodb.model.ConsumedCapacity; import software.amazon.awssdk.services.dynamodb.model.GetItemResponse; /** * Defines the elements returned by DynamoDB from a {@code GetItem} operation, such as * {@link DynamoDbTable#getItemWithResponse(GetItemEnhancedRequest)} and * {@link DynamoDbAsyncTable#getItemWithResponse(GetItemEnhancedRequest)}. * * @param <T> The type of the item. */ @SdkPublicApi @ThreadSafe public final class GetItemEnhancedResponse<T> { private final T attributes; private final ConsumedCapacity consumedCapacity; private GetItemEnhancedResponse(GetItemEnhancedResponse.Builder<T> builder) { this.attributes = builder.attributes; this.consumedCapacity = builder.consumedCapacity; } /** * The attribute values returned by {@code GetItem} operation. */ public T attributes() { return attributes; } /** * The capacity units consumed by the {@code GetItem} operation. * * @see GetItemResponse#consumedCapacity() for more information. */ public ConsumedCapacity consumedCapacity() { return consumedCapacity; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } GetItemEnhancedResponse<?> that = (GetItemEnhancedResponse<?>) o; return Objects.equals(attributes, that.attributes) && Objects.equals(consumedCapacity, that.consumedCapacity); } @Override public int hashCode() { int result = Objects.hashCode(attributes); result = 31 * result + Objects.hashCode(consumedCapacity); return result; } public static <T> GetItemEnhancedResponse.Builder<T> builder() { return new GetItemEnhancedResponse.Builder<>(); } @NotThreadSafe public static final class Builder<T> { private T attributes; private ConsumedCapacity consumedCapacity; public GetItemEnhancedResponse.Builder<T> attributes(T attributes) { this.attributes = attributes; return this; } public GetItemEnhancedResponse.Builder<T> consumedCapacity(ConsumedCapacity consumedCapacity) { this.consumedCapacity = consumedCapacity; return this; } public GetItemEnhancedResponse<T> build() { return new GetItemEnhancedResponse<>(this); } } }
4,337
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/model/TransactPutItemEnhancedRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.model; import java.util.Objects; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedAsyncClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.Expression; import software.amazon.awssdk.services.dynamodb.model.ReturnValuesOnConditionCheckFailure; /** * Defines parameters used to write an item to a DynamoDb table using * {@link DynamoDbEnhancedClient#transactWriteItems(TransactWriteItemsEnhancedRequest)} and * {@link DynamoDbEnhancedAsyncClient#transactWriteItems(TransactWriteItemsEnhancedRequest)}. * <p> * A valid request object must contain the item that should be written to the table. * * @param <T> The type of the modelled object. */ @SdkPublicApi @ThreadSafe public final class TransactPutItemEnhancedRequest<T> { private final T item; private final Expression conditionExpression; private final String returnValuesOnConditionCheckFailure; private TransactPutItemEnhancedRequest(Builder<T> builder) { this.item = builder.item; this.conditionExpression = builder.conditionExpression; this.returnValuesOnConditionCheckFailure = builder.returnValuesOnConditionCheckFailure; } /** * Creates a newly initialized builder for the request object. * * @param itemClass the class that items in this table map to * @param <T> The type of the modelled object, corresponding to itemClass * @return a PutItemEnhancedRequest builder */ public static <T> Builder<T> builder(Class<? extends T> itemClass) { return new Builder<>(); } /** * Returns a builder initialized with all existing values on the request object. */ public Builder<T> toBuilder() { return new Builder<T>().item(item) .conditionExpression(conditionExpression) .returnValuesOnConditionCheckFailure(returnValuesOnConditionCheckFailureAsString()); } /** * Returns the item for this put operation request. */ public T item() { return item; } /** * Returns the condition {@link Expression} set on this request object, or null if it doesn't exist. */ public Expression conditionExpression() { return conditionExpression; } /** * Returns what values to return if the condition check fails. * <p> * If the service returns an enum value that is not available in the current SDK version, * {@link #returnValuesOnConditionCheckFailure} will return * {@link ReturnValuesOnConditionCheckFailure#UNKNOWN_TO_SDK_VERSION}. The raw value returned by the service is * available from {@link #returnValuesOnConditionCheckFailureAsString}. * * @return What values to return on condition check failure. */ public ReturnValuesOnConditionCheckFailure returnValuesOnConditionCheckFailure() { return ReturnValuesOnConditionCheckFailure.fromValue(returnValuesOnConditionCheckFailure); } /** * Returns what values to return if the condition check fails. * <p> * If the service returns an enum value that is not available in the current SDK version, * {@link #returnValuesOnConditionCheckFailure} will return * {@link ReturnValuesOnConditionCheckFailure#UNKNOWN_TO_SDK_VERSION}. The raw value returned by the service is * available from {@link #returnValuesOnConditionCheckFailureAsString}. * * @return What values to return on condition check failure. */ public String returnValuesOnConditionCheckFailureAsString() { return returnValuesOnConditionCheckFailure; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } TransactPutItemEnhancedRequest<?> that = (TransactPutItemEnhancedRequest<?>) o; if (!Objects.equals(item, that.item)) { return false; } if (!Objects.equals(conditionExpression, that.conditionExpression)) { return false; } return Objects.equals(returnValuesOnConditionCheckFailure, that.returnValuesOnConditionCheckFailure); } @Override public int hashCode() { int result = Objects.hashCode(item); result = 31 * result + Objects.hashCode(conditionExpression); result = 31 * result + Objects.hashCode(returnValuesOnConditionCheckFailure); return result; } /** * A builder that is used to create a request with the desired parameters. * <p> * <b>Note</b>: A valid request builder must define an item. */ @NotThreadSafe public static final class Builder<T> { private T item; private Expression conditionExpression; private String returnValuesOnConditionCheckFailure; private Builder() { } /** * Sets the item to write to DynamoDb. Required. * * @param item the item to write * @return a builder of this type */ public Builder<T> item(T item) { this.item = item; return this; } /** * Defines a logical expression on an item's attribute values which, if evaluating to true, * will allow the put operation to succeed. If evaluating to false, the operation will not succeed. * <p> * See {@link Expression} for condition syntax and examples. * * @param conditionExpression a condition written as an {@link Expression} * @return a builder of this type */ public Builder<T> conditionExpression(Expression conditionExpression) { this.conditionExpression = conditionExpression; return this; } /** * Use <code>ReturnValuesOnConditionCheckFailure</code> to get the item attributes if the <code>PutItem</code> * condition fails. For <code>ReturnValuesOnConditionCheckFailure</code>, the valid values are: NONE and * ALL_OLD. * * @param returnValuesOnConditionCheckFailure What values to return on condition check failure. * @return a builder of this type */ public Builder<T> returnValuesOnConditionCheckFailure( ReturnValuesOnConditionCheckFailure returnValuesOnConditionCheckFailure) { this.returnValuesOnConditionCheckFailure = returnValuesOnConditionCheckFailure == null ? null : returnValuesOnConditionCheckFailure.toString(); return this; } /** * Use <code>ReturnValuesOnConditionCheckFailure</code> to get the item attributes if the <code>PutItem</code> * condition fails. For <code>ReturnValuesOnConditionCheckFailure</code>, the valid values are: NONE and * ALL_OLD. * * @param returnValuesOnConditionCheckFailure What values to return on condition check failure. * @return a builder of this type */ public Builder<T> returnValuesOnConditionCheckFailure(String returnValuesOnConditionCheckFailure) { this.returnValuesOnConditionCheckFailure = returnValuesOnConditionCheckFailure; return this; } public TransactPutItemEnhancedRequest<T> build() { return new TransactPutItemEnhancedRequest<>(this); } } }
4,338
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/model/WriteBatch.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.model; import static java.util.Objects.requireNonNull; import static software.amazon.awssdk.enhanced.dynamodb.internal.EnhancedClientUtils.getItemsFromSupplier; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.function.Consumer; import java.util.function.Supplier; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.Key; import software.amazon.awssdk.enhanced.dynamodb.MappedTableResource; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.BatchableWriteOperation; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.DefaultOperationContext; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.DeleteItemOperation; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.PutItemOperation; import software.amazon.awssdk.services.dynamodb.model.WriteRequest; /** * Defines a collection of references to keys for delete actions and items for put actions * for one specific table. A WriteBatch is part of a {@link BatchWriteItemEnhancedRequest} * and used in a batchWriteItem() operation (such as * {@link DynamoDbEnhancedClient#batchWriteItem(BatchWriteItemEnhancedRequest)}). * <p> * A valid write batch should contain one or more delete or put action reference. */ @SdkPublicApi @ThreadSafe public final class WriteBatch { private final String tableName; private final List<WriteRequest> writeRequests; private WriteBatch(BuilderImpl<?> builder) { this.tableName = builder.mappedTableResource != null ? builder.mappedTableResource.tableName() : null; this.writeRequests = getItemsFromSupplier(builder.itemSupplierList); } /** * Creates a newly initialized builder for a write batch. * * @param itemClass the class that items in this table map to * @param <T> The type of the modelled object, corresponding to itemClass * @return a WriteBatch builder */ public static <T> Builder<T> builder(Class<? extends T> itemClass) { return new BuilderImpl<>(itemClass); } /** * Returns the table name associated with this batch. */ public String tableName() { return tableName; } /** * Returns the collection of write requests in this writek batch. */ public Collection<WriteRequest> writeRequests() { return writeRequests; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } WriteBatch that = (WriteBatch) o; if (tableName != null ? !tableName.equals(that.tableName) : that.tableName != null) { return false; } return writeRequests != null ? writeRequests.equals(that.writeRequests) : that.writeRequests == null; } @Override public int hashCode() { int result = tableName != null ? tableName.hashCode() : 0; result = 31 * result + (writeRequests != null ? writeRequests.hashCode() : 0); return result; } /** * A builder that is used to create a request with the desired parameters. * <p> * A valid builder must define a {@link MappedTableResource} and add at least one * {@link DeleteItemEnhancedRequest} or {@link PutItemEnhancedRequest}. * * @param <T> the type that items in this table map to */ @NotThreadSafe public interface Builder<T> { /** * Sets the mapped table resource (table) that the items in this write batch should come from. * * @param mappedTableResource the table reference * @return a builder of this type */ Builder<T> mappedTableResource(MappedTableResource<T> mappedTableResource); /** * Adds a {@link DeleteItemEnhancedRequest} to the builder, this request should contain * the primary {@link Key} to an item to be deleted. * * @param request A {@link DeleteItemEnhancedRequest} * @return a builder of this type */ Builder<T> addDeleteItem(DeleteItemEnhancedRequest request); /** * Adds a {@link DeleteItemEnhancedRequest} to the builder, this request should contain * the primary {@link Key} to an item to be deleted. * * @param requestConsumer a {@link Consumer} of {@link DeleteItemEnhancedRequest} * @return a builder of this type */ Builder<T> addDeleteItem(Consumer<DeleteItemEnhancedRequest.Builder> requestConsumer); /** * Adds a DeleteItem request to the builder. * * @param key a {@link Key} to match the item to be deleted from the database. * @return a builder of this type */ Builder<T> addDeleteItem(Key key); /** * Adds a DeleteItem request to the builder. * * @param keyItem an item that will have its key fields used to match a record to delete from the database. * @return a builder of this type */ Builder<T> addDeleteItem(T keyItem); /** * Adds a {@link PutItemEnhancedRequest} to the builder, this request should contain the item * to be written. * * @param request A {@link PutItemEnhancedRequest} * @return a builder of this type */ Builder<T> addPutItem(PutItemEnhancedRequest<T> request); /** * Adds a {@link PutItemEnhancedRequest} to the builder, this request should contain the item * to be written. * * @param requestConsumer a {@link Consumer} of {@link PutItemEnhancedRequest} * @return a builder of this type */ Builder<T> addPutItem(Consumer<PutItemEnhancedRequest.Builder<T>> requestConsumer); /** * Adds a PutItem request to the builder. * * @param item the item to insert or overwrite in the database. * @return a builder of this type */ Builder<T> addPutItem(T item); WriteBatch build(); } private static final class BuilderImpl<T> implements Builder<T> { private Class<? extends T> itemClass; private List<Supplier<WriteRequest>> itemSupplierList = new ArrayList<>(); private MappedTableResource<T> mappedTableResource; private BuilderImpl(Class<? extends T> itemClass) { this.itemClass = itemClass; } @Override public Builder<T> mappedTableResource(MappedTableResource<T> mappedTableResource) { this.mappedTableResource = mappedTableResource; return this; } @Override public Builder<T> addDeleteItem(DeleteItemEnhancedRequest request) { itemSupplierList.add(() -> generateWriteRequest(() -> mappedTableResource, DeleteItemOperation.create(request))); return this; } @Override public Builder<T> addDeleteItem(Consumer<DeleteItemEnhancedRequest.Builder> requestConsumer) { DeleteItemEnhancedRequest.Builder builder = DeleteItemEnhancedRequest.builder(); requestConsumer.accept(builder); return addDeleteItem(builder.build()); } @Override public Builder<T> addDeleteItem(Key key) { return addDeleteItem(r -> r.key(key)); } @Override public Builder<T> addDeleteItem(T keyItem) { requireNonNull(mappedTableResource, "A mappedTableResource is required to derive a key from the given keyItem"); return addDeleteItem(this.mappedTableResource.keyFrom(keyItem)); } @Override public Builder<T> addPutItem(PutItemEnhancedRequest<T> request) { itemSupplierList.add(() -> generateWriteRequest(() -> mappedTableResource, PutItemOperation.create(request))); return this; } @Override public Builder<T> addPutItem(Consumer<PutItemEnhancedRequest.Builder<T>> requestConsumer) { PutItemEnhancedRequest.Builder<T> builder = PutItemEnhancedRequest.builder(this.itemClass); requestConsumer.accept(builder); return addPutItem(builder.build()); } @Override public Builder<T> addPutItem(T item) { return addPutItem(r -> r.item(item)); } @Override public WriteBatch build() { return new WriteBatch(this); } private WriteRequest generateWriteRequest(Supplier<MappedTableResource<T>> mappedTableResourceSupplier, BatchableWriteOperation<T> operation) { MappedTableResource<T> mappedTableResource = mappedTableResourceSupplier.get(); requireNonNull(mappedTableResource, "A mappedTableResource (table) is required when generating the write requests for WriteBatch"); return operation.generateWriteRequest(mappedTableResource.tableSchema(), DefaultOperationContext.create(mappedTableResource.tableName()), mappedTableResource.mapperExtension()); } } }
4,339
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/model/BatchWriteResult.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.model; import static software.amazon.awssdk.enhanced.dynamodb.internal.EnhancedClientUtils.createKeyFromMap; import static software.amazon.awssdk.enhanced.dynamodb.internal.EnhancedClientUtils.readAndTransformSingleItem; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.Key; import software.amazon.awssdk.enhanced.dynamodb.MappedTableResource; import software.amazon.awssdk.enhanced.dynamodb.TableMetadata; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.DefaultOperationContext; import software.amazon.awssdk.services.dynamodb.model.DeleteRequest; import software.amazon.awssdk.services.dynamodb.model.PutRequest; import software.amazon.awssdk.services.dynamodb.model.WriteRequest; /** * Defines the result of the batchWriteItem() operation, such as * {@link DynamoDbEnhancedClient#batchWriteItem(BatchWriteItemEnhancedRequest)}. The result describes any unprocessed items * after the operation completes. * <ul> * <li>Use the {@link #unprocessedPutItemsForTable(MappedTableResource)} method once for each table present in the request * to get any unprocessed items from a put action on that table.</li> * <li>Use the {@link #unprocessedDeleteItemsForTable(MappedTableResource)} method once for each table present in the request * to get any unprocessed items from a delete action on that table.</li> * </ul> * */ @SdkPublicApi @ThreadSafe public final class BatchWriteResult { private final Map<String, List<WriteRequest>> unprocessedRequests; private BatchWriteResult(Builder builder) { this.unprocessedRequests = Collections.unmodifiableMap(builder.unprocessedRequests); } /** * Creates a newly initialized builder for a request object. */ public static Builder builder() { return new Builder(); } /** * Retrieve any unprocessed put action items belonging to the supplied table from the result . * Call this method once for each table present in the batch request. * * @param mappedTable the table to retrieve unprocessed items for * @param <T> the type of the table items * @return a list of items */ public <T> List<T> unprocessedPutItemsForTable(MappedTableResource<T> mappedTable) { List<WriteRequest> writeRequests = unprocessedRequests.getOrDefault(mappedTable.tableName(), Collections.emptyList()); return writeRequests.stream() .filter(writeRequest -> writeRequest.putRequest() != null) .map(WriteRequest::putRequest) .map(PutRequest::item) .map(item -> readAndTransformSingleItem(item, mappedTable.tableSchema(), DefaultOperationContext.create(mappedTable.tableName()), mappedTable.mapperExtension())) .collect(Collectors.toList()); } /** * Retrieve any unprocessed delete action keys belonging to the supplied table from the result. * Call this method once for each table present in the batch request. * * @param mappedTable the table to retrieve unprocessed items for. * @return a list of keys that were not processed as part of the batch request. */ public List<Key> unprocessedDeleteItemsForTable(MappedTableResource<?> mappedTable) { List<WriteRequest> writeRequests = unprocessedRequests.getOrDefault(mappedTable.tableName(), Collections.emptyList()); return writeRequests.stream() .filter(writeRequest -> writeRequest.deleteRequest() != null) .map(WriteRequest::deleteRequest) .map(DeleteRequest::key) .map(itemMap -> createKeyFromMap(itemMap, mappedTable.tableSchema(), TableMetadata.primaryIndexName())) .collect(Collectors.toList()); } /** * A builder that is used to create a result with the desired parameters. */ @NotThreadSafe public static final class Builder { private Map<String, List<WriteRequest>> unprocessedRequests; private Builder() { } /** * Add a map of unprocessed requests to this result object. * * @param unprocessedRequests the map of table to write request representing the unprocessed requests * @return a builder of this type */ public Builder unprocessedRequests(Map<String, List<WriteRequest>> unprocessedRequests) { this.unprocessedRequests = unprocessedRequests.entrySet() .stream() .collect(Collectors.toMap( Map.Entry::getKey, entry -> Collections.unmodifiableList(entry.getValue()))); return this; } public BatchWriteResult build() { return new BatchWriteResult(this); } } }
4,340
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/model/ScanEnhancedRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.model; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.Expression; import software.amazon.awssdk.enhanced.dynamodb.NestedAttributeName; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.ReturnConsumedCapacity; import software.amazon.awssdk.services.dynamodb.model.ScanRequest; import software.amazon.awssdk.utils.Validate; /** * Defines parameters used to when scanning a DynamoDb table or index using the scan() operation (such as * {@link DynamoDbTable#scan(ScanEnhancedRequest)}). * <p> * All parameters are optional. */ @SdkPublicApi @ThreadSafe public final class ScanEnhancedRequest { private final Map<String, AttributeValue> exclusiveStartKey; private final Integer limit; private final Boolean consistentRead; private final Expression filterExpression; private final List<NestedAttributeName> attributesToProject; private final Integer segment; private final Integer totalSegments; private final String returnConsumedCapacity; private ScanEnhancedRequest(Builder builder) { this.exclusiveStartKey = builder.exclusiveStartKey; this.limit = builder.limit; this.segment = builder.segment; this.totalSegments = builder.totalSegments; this.consistentRead = builder.consistentRead; this.filterExpression = builder.filterExpression; this.returnConsumedCapacity = builder.returnConsumedCapacity; this.attributesToProject = builder.attributesToProject != null ? Collections.unmodifiableList(builder.attributesToProject) : null; } /** * Creates a newly initialized builder for a request object. */ public static Builder builder() { return new Builder(); } /** * Returns a builder initialized with all existing values on the request object. */ public Builder toBuilder() { return builder().exclusiveStartKey(exclusiveStartKey) .limit(limit) .segment(segment) .totalSegments(totalSegments) .consistentRead(consistentRead) .filterExpression(filterExpression) .returnConsumedCapacity(returnConsumedCapacity) .addNestedAttributesToProject(attributesToProject); } /** * Returns the value of the exclusive start key set on this request object, or null if it doesn't exist. */ public Map<String, AttributeValue> exclusiveStartKey() { return exclusiveStartKey; } /** * Returns the value of limit set on this request object, or null if it doesn't exist. */ public Integer limit() { return limit; } /** * Returns the value of segment set on this request object, or null if it doesn't exist. */ public Integer segment() { return segment; } /** * Returns the value of totalSegments set on this request object, or null if it doesn't exist. */ public Integer totalSegments() { return totalSegments; } /** * Returns the value of consistent read, or false if it has not been set. */ public Boolean consistentRead() { return consistentRead; } /** * Returns the return result filter {@link Expression} set on this request object, or null if it doesn't exist. */ public Expression filterExpression() { return filterExpression; } /** * Returns the list of projected attributes on this request object, or an null if no projection is specified. * Nested attributes are represented using the '.' separator. Example : foo.bar is represented as "foo.bar" which is * indistinguishable from a non-nested attribute with the name "foo.bar". * Use {@link #nestedAttributesToProject} if you have a use-case that requires discrimination between these two cases. */ public List<String> attributesToProject() { return attributesToProject != null ? attributesToProject.stream().map(item -> String.join(".", item.elements())) .collect(Collectors.toList()) : null; } /** * Returns the list of projected attribute names, in the form of {@link NestedAttributeName} objects, * for this request object, or null if no projection is specified. * Refer {@link NestedAttributeName} */ public List<NestedAttributeName> nestedAttributesToProject() { return attributesToProject; } /** * Whether to return the capacity consumed by this operation. * * @see ScanRequest#returnConsumedCapacity() */ public ReturnConsumedCapacity returnConsumedCapacity() { return ReturnConsumedCapacity.fromValue(returnConsumedCapacity); } /** * Whether to return the capacity consumed by this operation. * <p> * Similar to {@link #returnConsumedCapacity()} but return the value as a string. This is useful in situations where the * value is not defined in {@link ReturnConsumedCapacity}. */ public String returnConsumedCapacityAsString() { return returnConsumedCapacity; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ScanEnhancedRequest scan = (ScanEnhancedRequest) o; if (exclusiveStartKey != null ? ! exclusiveStartKey.equals(scan.exclusiveStartKey) : scan.exclusiveStartKey != null) { return false; } if (limit != null ? ! limit.equals(scan.limit) : scan.limit != null) { return false; } if (segment != null ? ! segment.equals(scan.segment) : scan.segment != null) { return false; } if (totalSegments != null ? ! totalSegments.equals(scan.totalSegments) : scan.totalSegments != null) { return false; } if (consistentRead != null ? ! consistentRead.equals(scan.consistentRead) : scan.consistentRead != null) { return false; } if (attributesToProject != null ? !attributesToProject.equals(scan.attributesToProject) : scan.attributesToProject != null) { return false; } if (returnConsumedCapacity != null ? !returnConsumedCapacity.equals(scan.returnConsumedCapacity) : scan.returnConsumedCapacity != null) { return false; } return filterExpression != null ? filterExpression.equals(scan.filterExpression) : scan.filterExpression == null; } @Override public int hashCode() { int result = exclusiveStartKey != null ? exclusiveStartKey.hashCode() : 0; result = 31 * result + (limit != null ? limit.hashCode() : 0); result = 31 * result + (segment != null ? segment.hashCode() : 0); result = 31 * result + (totalSegments != null ? totalSegments.hashCode() : 0); result = 31 * result + (consistentRead != null ? consistentRead.hashCode() : 0); result = 31 * result + (filterExpression != null ? filterExpression.hashCode() : 0); result = 31 * result + (attributesToProject != null ? attributesToProject.hashCode() : 0); result = 31 * result + (returnConsumedCapacity != null ? returnConsumedCapacity.hashCode() : 0); return result; } /** * A builder that is used to create a request with the desired parameters. */ @NotThreadSafe public static final class Builder { private Map<String, AttributeValue> exclusiveStartKey; private Integer limit; private Boolean consistentRead; private Expression filterExpression; private List<NestedAttributeName> attributesToProject; private Integer segment; private Integer totalSegments; private String returnConsumedCapacity; private Builder() { } /** * The primary key of the first item that this operation will evaluate. By default, the operation will evaluate * the whole dataset. If used, normally this parameter is populated with the value that was returned for * {@link Page#lastEvaluatedKey()} in the previous operation. * * @param exclusiveStartKey the primary key value where DynamoDb should start to evaluate items * @return a builder of this type */ public Builder exclusiveStartKey(Map<String, AttributeValue> exclusiveStartKey) { this.exclusiveStartKey = exclusiveStartKey != null ? new HashMap<>(exclusiveStartKey) : null; return this; } /** * Sets a limit on how many items to evaluate in the scan. If not set, the operation uses * the maximum values allowed. * <p> * <b>Note:</b>The limit does not refer to the number of items to return, but how many items * the database should evaluate while executing the scan. Use limit together with {@link Page#lastEvaluatedKey()} * and {@link #exclusiveStartKey} in subsequent scan calls to evaluate <em>limit</em> items per call. * * @param limit the maximum number of items to evalute * @return a builder of this type */ public Builder limit(Integer limit) { this.limit = limit; return this; } /** * For a parallel Scan request, Segment identifies an individual segment to be scanned by an application worker. * <p> * <b>Note:</b>Segment IDs are zero-based, so the first segment is always 0. For example, if you want to use four * application threads to scan a table or an index, then the first thread specifies a Segment value of 0, the second * thread specifies 1, and so on. * * The value for Segment must be greater than or equal to 0, and less than the value provided for TotalSegments. * * If you provide Segment, you must also provide <em>TotalSegments</em>. * * @param segment identifies an individual segment to be scanned * @return a builder of this type */ public Builder segment(Integer segment) { this.segment = segment; return this; } /** * For a parallel Scan request, TotalSegments represents the total number of segments into * which the Scan operation will be divided. * <p> * <b>Note:</b>If you do not specify this value, the TotalSegements is effectively 1 and Scan operation * will be sequential rather than parallel. * * If you specify TotalSegments, you must also specify Segment. * * If you specify TotalSegments of 2 and above, you can create separate thread for each segment and scan items * in parallel across segments from multiple threads. * * @param totalSegments the total number of segments to divide the table. * @return a builder of this type */ public Builder totalSegments(Integer totalSegments) { this.totalSegments = totalSegments; return this; } /** * Determines the read consistency model: If set to true, the operation uses strongly consistent reads; otherwise, * the operation uses eventually consistent reads. * <p> * By default, the value of this property is set to <em>false</em>. * * @param consistentRead sets consistency model of the operation to use strong consistency if true * @return a builder of this type */ public Builder consistentRead(Boolean consistentRead) { this.consistentRead = consistentRead; return this; } /** * Refines the scan results by applying the filter expression on the results returned * from the scan and discards items that do not match. See {@link Expression} for examples * and constraints. * <p> * <b>Note:</b> Using the filter expression does not reduce the cost of the scan, since it is applied * <em>after</em> the database has found matching items. * * @param filterExpression an expression that filters results of evaluating the scan * @return a builder of this type */ public Builder filterExpression(Expression filterExpression) { this.filterExpression = filterExpression; return this; } /** * <p> * Sets a collection of the attribute names to be retrieved from the database. These attributes can include * scalars, sets, or elements of a JSON document. * <p> * If no attribute names are specified, then all attributes will be returned. If any of the requested attributes * are not found, they will not appear in the result. * <p> * If there are nested attributes, use any of the addNestedAttributesToProject methods, such as * {@link #addNestedAttributesToProject(NestedAttributeName...)}. * <p> * For more information, see <a href= * "https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.AccessingItemAttributes.html" * >Accessing Item Attributes</a> in the <i>Amazon DynamoDB Developer Guide</i>. * </p> * * @param attributesToProject A collection of the attributes names to be retrieved from the database. * @return Returns a reference to this object so that method calls can be chained together. */ public Builder attributesToProject(Collection<String> attributesToProject) { if (this.attributesToProject != null) { this.attributesToProject.clear(); } if (attributesToProject != null) { addNestedAttributesToProject(new ArrayList<>(attributesToProject).stream() .map(NestedAttributeName::create).collect(Collectors.toList())); } return this; } /** * <p> * Sets one or more attribute names to be retrieved from the database. These attributes can include * scalars, sets, or elements of a JSON document. * <p> * If no attribute names are specified, then all attributes will be returned. If any of the requested attributes * are not found, they will not appear in the result. * <p> * If there are nested attributes, use any of the addNestedAttributesToProject methods, such as * {@link #addNestedAttributesToProject(NestedAttributeName...)}. * <p> * For more information, see <a href= * "https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.AccessingItemAttributes.html" * >Accessing Item Attributes</a> in the <i>Amazon DynamoDB Developer Guide</i>. * * @param attributesToProject One or more attributes names to be retrieved from the database. * @return Returns a reference to this object so that method calls can be chained together. */ public Builder attributesToProject(String... attributesToProject) { return attributesToProject(Arrays.asList(attributesToProject)); } /** * <p> Adds a single attribute name to be retrieved from the database. This attribute can include * scalars, sets, or elements of a JSON document. * <p> If there are nested attributes, use any of the addNestedAttributesToProject methods, such as * {@link #addNestedAttributesToProject(NestedAttributeName...)}. * * @param attributeToProject An additional single attribute name to be retrieved from the database. * @return Returns a reference to this object so that method calls can be chained together. */ public Builder addAttributeToProject(String attributeToProject) { if (attributeToProject != null) { addNestedAttributesToProject(NestedAttributeName.create(attributeToProject)); } return this; } /** * Adds a collection of nested attributes to be retrieved from the database. These attributes can include * scalars, sets, or elements of a JSON document. * <p> * This method is additive, so calling it multiple times will add to the list of nested attribute names. * @see NestedAttributeName * * @param nestedAttributeNames A collection of attributes to be retrieved from the database. * @return Returns a reference to this object so that method calls can be chained together. */ public Builder addNestedAttributesToProject(Collection<NestedAttributeName> nestedAttributeNames) { if (nestedAttributeNames != null) { Validate.noNullElements(nestedAttributeNames, "nestedAttributeNames list must not contain null elements"); if (attributesToProject == null) { this.attributesToProject = new ArrayList<>(nestedAttributeNames); } else { this.attributesToProject.addAll(nestedAttributeNames); } } return this; } /** * Adds a collection of nested attributes to be retrieved from the database. These attributes can include * scalars, sets, or elements of a JSON document. * <p> * This method is additive, so calling it multiple times will add to the list of nested attribute names. * @see NestedAttributeName * * @param nestedAttributeNames A collection of attributes to be retrieved from the database. * @return Returns a reference to this object so that method calls can be chained together. */ public Builder addNestedAttributesToProject(NestedAttributeName... nestedAttributeNames) { addNestedAttributesToProject(Arrays.asList(nestedAttributeNames)); return this; } /** * Adds a single nested attribute to be retrieved from the database. The attribute can include * scalars, sets, or elements of a JSON document. * <p> * This method is additive, so calling it multiple times will add to the list of nested attribute names. * @see NestedAttributeName * * * @param nestedAttributeName A single attribute name to be retrieved from the database. * @return Returns a reference to this object so that method calls can be chained together. */ public Builder addNestedAttributeToProject(NestedAttributeName nestedAttributeName) { if (nestedAttributeName != null) { addNestedAttributesToProject(Arrays.asList(nestedAttributeName)); } return this; } /** * Whether to return the capacity consumed by this operation. * * @see ScanRequest.Builder#returnConsumedCapacity(ReturnConsumedCapacity) */ public Builder returnConsumedCapacity(ReturnConsumedCapacity returnConsumedCapacity) { this.returnConsumedCapacity = returnConsumedCapacity == null ? null : returnConsumedCapacity.toString(); return this; } /** * Whether to return the capacity consumed by this operation. * * @see ScanRequest.Builder#returnConsumedCapacity(String) */ public Builder returnConsumedCapacity(String returnConsumedCapacity) { this.returnConsumedCapacity = returnConsumedCapacity; return this; } public ScanEnhancedRequest build() { return new ScanEnhancedRequest(this); } } }
4,341
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/model/BatchGetResultPageIterable.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.model; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.core.pagination.sync.PaginatedItemsIterable; import software.amazon.awssdk.core.pagination.sync.SdkIterable; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.MappedTableResource; /** * Defines the result of {@link DynamoDbEnhancedClient#batchGetItem} operation. * * <p> * The result can be accessed either through iterable {@link BatchGetResultPage}s or flattened items * across <b>all</b> pages via {@link #resultsForTable} * * <p> * Example: * <p> * 1) Iterating through pages * * <pre> * {@code * batchResults.forEach(page -> { * page.resultsForTable(firstItemTable).forEach(item -> System.out.println(item)); * page.resultsForTable(secondItemTable).forEach(item -> System.out.println(item)); * }); * } * </pre> * * 2) Iterating through items across all pages * * <pre> * {@code * results.resultsForTable(firstItemTable).forEach(item -> System.out.println(item)); * results.resultsForTable(secondItemTable).forEach(item -> System.out.println(item)); * } * </pre> */ @SdkPublicApi @ThreadSafe public interface BatchGetResultPageIterable extends SdkIterable<BatchGetResultPage> { static BatchGetResultPageIterable create(SdkIterable<BatchGetResultPage> pageIterable) { return pageIterable::iterator; } /** * Retrieve all items belonging to the supplied table across <b>all</b> pages. * * @param mappedTable the table to retrieve items for * @param <T> the type of the table items * @return iterable items */ default <T> SdkIterable<T> resultsForTable(MappedTableResource<T> mappedTable) { return PaginatedItemsIterable.<BatchGetResultPage, T>builder() .pagesIterable(this) .itemIteratorFunction(page -> page.resultsForTable(mappedTable).iterator()) .build(); } }
4,342
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/model/PutItemEnhancedRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.model; import java.util.Objects; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbAsyncTable; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.Expression; import software.amazon.awssdk.services.dynamodb.model.PutItemRequest; import software.amazon.awssdk.services.dynamodb.model.ReturnConsumedCapacity; import software.amazon.awssdk.services.dynamodb.model.ReturnItemCollectionMetrics; import software.amazon.awssdk.services.dynamodb.model.ReturnValue; /** * Defines parameters used to write an item to a DynamoDb table using the putItem() operation (such as * {@link DynamoDbTable#putItem(PutItemEnhancedRequest)} or {@link DynamoDbAsyncTable#putItem(PutItemEnhancedRequest)}). * <p> * A valid request object must contain the item that should be written to the table. * @param <T> The type of the modelled object. */ @SdkPublicApi @ThreadSafe public final class PutItemEnhancedRequest<T> { private final T item; private final Expression conditionExpression; private final String returnValues; private final String returnConsumedCapacity; private final String returnItemCollectionMetrics; private PutItemEnhancedRequest(Builder<T> builder) { this.item = builder.item; this.conditionExpression = builder.conditionExpression; this.returnValues = builder.returnValues; this.returnConsumedCapacity = builder.returnConsumedCapacity; this.returnItemCollectionMetrics = builder.returnItemCollectionMetrics; } /** * Creates a newly initialized builder for the request object. * * @param itemClass the class that items in this table map to * @param <T> The type of the modelled object, corresponding to itemClass * @return a PutItemEnhancedRequest builder */ public static <T> Builder<T> builder(Class<? extends T> itemClass) { return new Builder<>(); } /** * Returns a builder initialized with all existing values on the request object. */ public Builder<T> toBuilder() { return new Builder<T>().item(item) .conditionExpression(conditionExpression) .returnValues(returnValues) .returnConsumedCapacity(returnConsumedCapacity) .returnItemCollectionMetrics(returnItemCollectionMetrics); } /** * Returns the item for this put operation request. */ public T item() { return item; } /** * Returns the condition {@link Expression} set on this request object, or null if it doesn't exist. */ public Expression conditionExpression() { return conditionExpression; } /** * Whether to return the values of the item before this request. * * @see PutItemRequest#returnValues() */ public ReturnValue returnValues() { return ReturnValue.fromValue(returnValues); } /** * Whether to return the values of the item before this request. * <p> * Similar to {@link #returnValues()} but returns the value as a string. This is useful in situations where the value is * not defined in {@link ReturnValue}. */ public String returnValuesAsString() { return returnValues; } /** * Whether to return the capacity consumed by this operation. * * @see PutItemRequest#returnConsumedCapacity() */ public ReturnConsumedCapacity returnConsumedCapacity() { return ReturnConsumedCapacity.fromValue(returnConsumedCapacity); } /** * Whether to return the capacity consumed by this operation. * <p> * Similar to {@link #returnConsumedCapacity()} but return the value as a string. This is useful in situations where the * value is not defined in {@link ReturnConsumedCapacity}. */ public String returnConsumedCapacityAsString() { return returnConsumedCapacity; } /** * Whether to return the item collection metrics. * * @see PutItemRequest#returnItemCollectionMetrics() */ public ReturnItemCollectionMetrics returnItemCollectionMetrics() { return ReturnItemCollectionMetrics.fromValue(returnItemCollectionMetrics); } /** * Whether to return the item collection metrics. * <p> * Similar to {@link #returnItemCollectionMetrics()} but return the value as a string. This is useful in situations * where the * value is not defined in {@link ReturnItemCollectionMetrics}. */ public String returnItemCollectionMetricsAsString() { return returnItemCollectionMetrics; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PutItemEnhancedRequest<?> that = (PutItemEnhancedRequest<?>) o; return Objects.equals(item, that.item) && Objects.equals(conditionExpression, that.conditionExpression) && Objects.equals(returnValues, that.returnValues) && Objects.equals(returnConsumedCapacity, that.returnConsumedCapacity) && Objects.equals(returnItemCollectionMetrics, that.returnItemCollectionMetrics); } @Override public int hashCode() { int result = item != null ? item.hashCode() : 0; result = 31 * result + (conditionExpression != null ? conditionExpression.hashCode() : 0); result = 31 * result + (returnValues != null ? returnValues.hashCode() : 0); result = 31 * result + (returnConsumedCapacity != null ? returnConsumedCapacity.hashCode() : 0); result = 31 * result + (returnItemCollectionMetrics != null ? returnItemCollectionMetrics.hashCode() : 0); return result; } /** * A builder that is used to create a request with the desired parameters. * <p> * <b>Note</b>: A valid request builder must define an item. */ @NotThreadSafe public static final class Builder<T> { private T item; private Expression conditionExpression; private String returnValues; private String returnConsumedCapacity; private String returnItemCollectionMetrics; private Builder() { } /** * Sets the item to write to DynamoDb. Required. * * @param item the item to write * @return a builder of this type */ public Builder<T> item(T item) { this.item = item; return this; } /** * Defines a logical expression on an item's attribute values which, if evaluating to true, * will allow the put operation to succeed. If evaluating to false, the operation will not succeed. * <p> * See {@link Expression} for condition syntax and examples. * * @param conditionExpression a condition written as an {@link Expression} * @return a builder of this type */ public Builder<T> conditionExpression(Expression conditionExpression) { this.conditionExpression = conditionExpression; return this; } /** * Whether to return the values of the item before this request. * * @see PutItemRequest.Builder#returnValues(ReturnValue) */ public Builder<T> returnValues(ReturnValue returnValues) { this.returnValues = returnValues == null ? null : returnValues.toString(); return this; } /** * Whether to return the values of the item before this request. * * @see PutItemRequest.Builder#returnValues(String) */ public Builder<T> returnValues(String returnValues) { this.returnValues = returnValues; return this; } /** * Whether to return the capacity consumed by this operation. * * @see PutItemRequest.Builder#returnConsumedCapacity(ReturnConsumedCapacity) */ public Builder<T> returnConsumedCapacity(ReturnConsumedCapacity returnConsumedCapacity) { this.returnConsumedCapacity = returnConsumedCapacity == null ? null : returnConsumedCapacity.toString(); return this; } /** * Whether to return the capacity consumed by this operation. * * @see PutItemRequest.Builder#returnConsumedCapacity(String) */ public Builder<T> returnConsumedCapacity(String returnConsumedCapacity) { this.returnConsumedCapacity = returnConsumedCapacity; return this; } /** * Whether to return the item collection metrics. * * @see PutItemRequest.Builder#returnItemCollectionMetrics(ReturnItemCollectionMetrics) */ public Builder<T> returnItemCollectionMetrics(ReturnItemCollectionMetrics returnItemCollectionMetrics) { this.returnItemCollectionMetrics = returnItemCollectionMetrics == null ? null : returnItemCollectionMetrics.toString(); return this; } /** * Whether to return the item collection metrics. * * @see PutItemRequest.Builder#returnItemCollectionMetrics(String) */ public Builder<T> returnItemCollectionMetrics(String returnItemCollectionMetrics) { this.returnItemCollectionMetrics = returnItemCollectionMetrics; return this; } public PutItemEnhancedRequest<T> build() { return new PutItemEnhancedRequest<>(this); } } }
4,343
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/model/UpdateItemEnhancedRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.model; import java.util.Objects; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbAsyncTable; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.Expression; import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest; import software.amazon.awssdk.services.dynamodb.model.PutItemRequest; import software.amazon.awssdk.services.dynamodb.model.ReturnConsumedCapacity; import software.amazon.awssdk.services.dynamodb.model.ReturnItemCollectionMetrics; import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest; /** * Defines parameters used to update an item to a DynamoDb table using the updateItem() operation (such as * {@link DynamoDbTable#updateItem(UpdateItemEnhancedRequest)} or * {@link DynamoDbAsyncTable#updateItem(UpdateItemEnhancedRequest)}). * <p> * A valid request object must contain the item that should be written to the table. * * @param <T> The type of the modelled object. */ @SdkPublicApi @ThreadSafe public final class UpdateItemEnhancedRequest<T> { private final T item; private final Boolean ignoreNulls; private final Expression conditionExpression; private final String returnConsumedCapacity; private final String returnItemCollectionMetrics; private UpdateItemEnhancedRequest(Builder<T> builder) { this.item = builder.item; this.ignoreNulls = builder.ignoreNulls; this.conditionExpression = builder.conditionExpression; this.returnConsumedCapacity = builder.returnConsumedCapacity; this.returnItemCollectionMetrics = builder.returnItemCollectionMetrics; } /** * Creates a newly initialized builder for the request object. * * @param itemClass the class that items in this table map to * @param <T> The type of the modelled object, corresponding to itemClass * @return a UpdateItemEnhancedRequest builder */ public static <T> Builder<T> builder(Class<? extends T> itemClass) { return new Builder<>(); } /** * Returns a builder initialized with all existing values on the request object. */ public Builder<T> toBuilder() { return new Builder<T>().item(item) .ignoreNulls(ignoreNulls) .conditionExpression(conditionExpression) .returnConsumedCapacity(returnConsumedCapacity) .returnItemCollectionMetrics(returnItemCollectionMetrics); } /** * Returns the item for this update operation request. */ public T item() { return item; } /** * Returns if the update operation should ignore attributes with null values, or false if it has not been set. */ public Boolean ignoreNulls() { return ignoreNulls; } /** * Returns the condition {@link Expression} set on this request object, or null if it doesn't exist. */ public Expression conditionExpression() { return conditionExpression; } /** * Whether to return the capacity consumed by this operation. * * @see PutItemRequest#returnConsumedCapacity() */ public ReturnConsumedCapacity returnConsumedCapacity() { return ReturnConsumedCapacity.fromValue(returnConsumedCapacity); } /** * Whether to return the capacity consumed by this operation. * <p> * Similar to {@link #returnConsumedCapacity()} but return the value as a string. This is useful in situations where the * value is not defined in {@link ReturnConsumedCapacity}. */ public String returnConsumedCapacityAsString() { return returnConsumedCapacity; } /** * Whether to return the item collection metrics. * * @see DeleteItemRequest#returnItemCollectionMetrics() */ public ReturnItemCollectionMetrics returnItemCollectionMetrics() { return ReturnItemCollectionMetrics.fromValue(returnItemCollectionMetrics); } /** * Whether to return the item collection metrics. * <p> * Similar to {@link #returnItemCollectionMetrics()} but return the value as a string. This is useful in situations * where the * value is not defined in {@link ReturnItemCollectionMetrics}. */ public String returnItemCollectionMetricsAsString() { return returnItemCollectionMetrics; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } UpdateItemEnhancedRequest<?> that = (UpdateItemEnhancedRequest<?>) o; return Objects.equals(item, that.item) && Objects.equals(ignoreNulls, that.ignoreNulls) && Objects.equals(conditionExpression, that.conditionExpression) && Objects.equals(returnConsumedCapacity, that.returnConsumedCapacity) && Objects.equals(returnItemCollectionMetrics, that.returnItemCollectionMetrics); } @Override public int hashCode() { int result = item != null ? item.hashCode() : 0; result = 31 * result + (ignoreNulls != null ? ignoreNulls.hashCode() : 0); result = 31 * result + (conditionExpression != null ? conditionExpression.hashCode() : 0); result = 31 * result + (returnConsumedCapacity != null ? returnConsumedCapacity.hashCode() : 0); result = 31 * result + (returnItemCollectionMetrics != null ? returnItemCollectionMetrics.hashCode() : 0); return result; } /** * A builder that is used to create a request with the desired parameters. * <p> * <b>Note</b>: A valid request builder must define an item. */ @NotThreadSafe public static final class Builder<T> { private T item; private Boolean ignoreNulls; private Expression conditionExpression; private String returnConsumedCapacity; private String returnItemCollectionMetrics; private Builder() { } /** * Sets if the update operation should ignore attributes with null values. By default, the value is false. * <p> * If set to true, any null values in the Java object will be ignored and not be updated on the persisted * record. This is commonly referred to as a 'partial update'. * If set to false, null values in the Java object will cause those attributes to be removed from the persisted * record on update. * @param ignoreNulls the boolean value * @return a builder of this type */ public Builder<T> ignoreNulls(Boolean ignoreNulls) { this.ignoreNulls = ignoreNulls; return this; } /** * Defines a logical expression on an item's attribute values which, if evaluating to true, * will allow the update operation to succeed. If evaluating to false, the operation will not succeed. * <p> * See {@link Expression} for condition syntax and examples. * * @param conditionExpression a condition written as an {@link Expression} * @return a builder of this type */ public Builder<T> conditionExpression(Expression conditionExpression) { this.conditionExpression = conditionExpression; return this; } /** * Sets the item to write to DynamoDb. Required. * * @param item the item to write * @return a builder of this type */ public Builder<T> item(T item) { this.item = item; return this; } /** * Whether to return the capacity consumed by this operation. * * @see UpdateItemRequest.Builder#returnConsumedCapacity(ReturnConsumedCapacity) */ public Builder<T> returnConsumedCapacity(ReturnConsumedCapacity returnConsumedCapacity) { this.returnConsumedCapacity = returnConsumedCapacity == null ? null : returnConsumedCapacity.toString(); return this; } /** * Whether to return the capacity consumed by this operation. * * @see UpdateItemRequest.Builder#returnConsumedCapacity(String) */ public Builder<T> returnConsumedCapacity(String returnConsumedCapacity) { this.returnConsumedCapacity = returnConsumedCapacity; return this; } /** * Whether to return the item collection metrics. * * @see UpdateItemRequest.Builder#returnItemCollectionMetrics(ReturnItemCollectionMetrics) */ public Builder<T> returnItemCollectionMetrics(ReturnItemCollectionMetrics returnItemCollectionMetrics) { this.returnItemCollectionMetrics = returnItemCollectionMetrics == null ? null : returnItemCollectionMetrics.toString(); return this; } /** * Whether to return the item collection metrics. * * @see UpdateItemRequest.Builder#returnItemCollectionMetrics(String) */ public Builder<T> returnItemCollectionMetrics(String returnItemCollectionMetrics) { this.returnItemCollectionMetrics = returnItemCollectionMetrics; return this; } public UpdateItemEnhancedRequest<T> build() { return new UpdateItemEnhancedRequest<>(this); } } }
4,344
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/model/BatchGetResultPagePublisher.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.model; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.core.async.SdkPublisher; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedAsyncClient; import software.amazon.awssdk.enhanced.dynamodb.MappedTableResource; /** * Defines the result of {@link DynamoDbEnhancedAsyncClient#batchGetItem} operation. * * <p> * You can either subscribe to the {@link BatchGetResultPage}s or flattened items across <b>all</b> pages via * {@link #resultsForTable(MappedTableResource)}. * * Example: * <p> * 1) Subscribing to {@link BatchGetResultPage}s * <pre> * {@code * batchGetResultPagePublisher.subscribe(page -> { * page.resultsForTable(firstItemTable).forEach(item -> System.out.println(item)); * page.resultsForTable(secondItemTable).forEach(item -> System.out.println(item)); * }).exceptionally(failure -> { * System.err.println("Failure occurred in subscription."); * failure.printStackTrace(); * return null; * }); * } * </pre> * * <p> * 2) Subscribing to results across all pages. * <pre> * {@code * CompletableFuture<Void> resultFuture1 = * batchGetResultPagePublisher.resultsForTable(firstItemTable) * .subscribe(item -> System.out.println(item)); * * CompletableFuture<Void> resultFuture2 = * batchGetResultPagePublisher.resultsForTable(secondItemTable) * .subscribe(item -> System.out.println(item)); * * resultFuture1.exceptionally(failure -> { * System.err.println("Failure occurred in results for table " + firstItemTable); * failure.printStackTrace(); * return null; * }); * * resultFuture2.exceptionally(failure -> { * System.err.println("Failure occurred in results for table " + secondItemTable); * failure.printStackTrace(); * return null; * }); * } * </pre> */ @SdkPublicApi @ThreadSafe public interface BatchGetResultPagePublisher extends SdkPublisher<BatchGetResultPage> { /** * Creates a flattened items publisher with the underlying page publisher. */ static BatchGetResultPagePublisher create(SdkPublisher<BatchGetResultPage> publisher) { return publisher::subscribe; } /** * Returns a publisher that can be used to request a stream of results belonging to the supplied table across all pages. * * <p> * This method is useful if you are interested in subscribing to the items in all response pages * instead of the top level pages. * * @param mappedTable the table to retrieve items for * @param <T> the type of the table items * @return a {@link SdkPublisher} */ default <T> SdkPublisher<T> resultsForTable(MappedTableResource<T> mappedTable) { return this.flatMapIterable(p -> p.resultsForTable(mappedTable)); } }
4,345
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/model/EnhancedLocalSecondaryIndex.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.model; import java.util.function.Consumer; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.services.dynamodb.model.Projection; import software.amazon.awssdk.utils.Validate; /** * Enhanced model representation of a 'local secondary index' of a DynamoDb table. This is optionally used with the * 'createTable' operation in the enhanced client. */ @SdkPublicApi @ThreadSafe public final class EnhancedLocalSecondaryIndex { private final String indexName; private final Projection projection; private EnhancedLocalSecondaryIndex(Builder builder) { this.indexName = Validate.paramNotBlank(builder.indexName, "indexName"); this.projection = builder.projection; } public static EnhancedLocalSecondaryIndex create(String indexName, Projection projection) { return builder().indexName(indexName).projection(projection).build(); } public static Builder builder() { return new Builder(); } public Builder toBuilder() { return builder().indexName(indexName).projection(projection); } /** * The name of this local secondary index */ public String indexName() { return indexName; } /** * The attribute projection setting for this local secondary index. */ public Projection projection() { return projection; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } EnhancedLocalSecondaryIndex that = (EnhancedLocalSecondaryIndex) o; if (indexName != null ? ! indexName.equals(that.indexName) : that.indexName != null) { return false; } return projection != null ? projection.equals(that.projection) : that.projection == null; } @Override public int hashCode() { int result = indexName != null ? indexName.hashCode() : 0; result = 31 * result + (projection != null ? projection.hashCode() : 0); return result; } /** * A builder for {@link EnhancedLocalSecondaryIndex} */ @NotThreadSafe public static final class Builder { private String indexName; private Projection projection; private Builder() { } /** * The name of this local secondary index */ public Builder indexName(String indexName) { this.indexName = indexName; return this; } /** * The attribute projection setting for this local secondary index. */ public Builder projection(Projection projection) { this.projection = projection; return this; } /** * The attribute projection setting for this local secondary index. */ public Builder projection(Consumer<Projection.Builder> projection) { Projection.Builder builder = Projection.builder(); projection.accept(builder); return projection(builder.build()); } public EnhancedLocalSecondaryIndex build() { return new EnhancedLocalSecondaryIndex(this); } } }
4,346
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/model/TransactDeleteItemEnhancedRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.model; import java.util.Objects; import java.util.function.Consumer; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedAsyncClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.Expression; import software.amazon.awssdk.enhanced.dynamodb.Key; import software.amazon.awssdk.services.dynamodb.model.ReturnValuesOnConditionCheckFailure; /** * Defines parameters used to delete an item from a DynamoDb table using the * {@link DynamoDbEnhancedClient#transactWriteItems(TransactWriteItemsEnhancedRequest)} or * {@link DynamoDbEnhancedAsyncClient#transactWriteItems(TransactWriteItemsEnhancedRequest)} * operation. * <p> * A valid request object must contain a primary {@link Key} to reference the item to delete. * */ @SdkPublicApi @ThreadSafe public final class TransactDeleteItemEnhancedRequest { private final Key key; private final Expression conditionExpression; private final String returnValuesOnConditionCheckFailure; private TransactDeleteItemEnhancedRequest(Builder builder) { this.key = builder.key; this.conditionExpression = builder.conditionExpression; this.returnValuesOnConditionCheckFailure = builder.returnValuesOnConditionCheckFailure; } /** * Creates a newly initialized builder for a request object. */ public static Builder builder() { return new Builder(); } /** * Returns a builder initialized with all existing values on the request object. */ public Builder toBuilder() { return builder().key(key) .conditionExpression(conditionExpression) .returnValuesOnConditionCheckFailure(returnValuesOnConditionCheckFailure); } /** * Returns the primary {@link Key} for the item to delete. */ public Key key() { return key; } /** * Returns the condition {@link Expression} set on this request object, or null if it doesn't exist. */ public Expression conditionExpression() { return conditionExpression; } /** * Returns what values to return if the condition check fails. * <p> * If the service returns an enum value that is not available in the current SDK version, * {@link #returnValuesOnConditionCheckFailure} will return * {@link ReturnValuesOnConditionCheckFailure#UNKNOWN_TO_SDK_VERSION}. The raw value returned by the service is * available from {@link #returnValuesOnConditionCheckFailureAsString}. * * @return What values to return on condition check failure. */ public ReturnValuesOnConditionCheckFailure returnValuesOnConditionCheckFailure() { return ReturnValuesOnConditionCheckFailure.fromValue(returnValuesOnConditionCheckFailure); } /** * Returns what values to return if the condition check fails. * <p> * If the service returns an enum value that is not available in the current SDK version, * {@link #returnValuesOnConditionCheckFailure} will return * {@link ReturnValuesOnConditionCheckFailure#UNKNOWN_TO_SDK_VERSION}. The raw value returned by the service is * available from {@link #returnValuesOnConditionCheckFailureAsString}. * * @return What values to return on condition check failure. */ public String returnValuesOnConditionCheckFailureAsString() { return returnValuesOnConditionCheckFailure; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } TransactDeleteItemEnhancedRequest that = (TransactDeleteItemEnhancedRequest) o; if (!Objects.equals(key, that.key)) { return false; } if (!Objects.equals(conditionExpression, that.conditionExpression)) { return false; } return Objects.equals(returnValuesOnConditionCheckFailure, that.returnValuesOnConditionCheckFailure); } @Override public int hashCode() { int result = Objects.hashCode(key); result = 31 * result + Objects.hashCode(conditionExpression); result = 31 * result + Objects.hashCode(returnValuesOnConditionCheckFailure); return result; } /** * A builder that is used to create a request with the desired parameters. * <p> * <b>Note</b>: A valid request builder must define a {@link Key}. */ @NotThreadSafe public static final class Builder { private Key key; private Expression conditionExpression; private String returnValuesOnConditionCheckFailure; private Builder() { } /** * Sets the primary {@link Key} that will be used to match the item to delete. * * @param key the primary key to use in the request. * @return a builder of this type */ public Builder key(Key key) { this.key = key; return this; } /** * Sets the primary {@link Key} that will be used to match the item to delete * on the builder by accepting a consumer of {@link Key.Builder}. * * @param keyConsumer a {@link Consumer} of {@link Key} * @return a builder of this type */ public Builder key(Consumer<Key.Builder> keyConsumer) { Key.Builder builder = Key.builder(); keyConsumer.accept(builder); return key(builder.build()); } /** * Defines a logical expression on an item's attribute values which, if evaluating to true, * will allow the delete operation to succeed. If evaluating to false, the operation will not succeed. * <p> * See {@link Expression} for condition syntax and examples. * * @param conditionExpression a condition written as an {@link Expression} * @return a builder of this type */ public Builder conditionExpression(Expression conditionExpression) { this.conditionExpression = conditionExpression; return this; } /** * Use <code>ReturnValuesOnConditionCheckFailure</code> to get the item attributes if the <code>Delete</code> * condition fails. For <code>ReturnValuesOnConditionCheckFailure</code>, the valid values are: NONE and * ALL_OLD. * * @param returnValuesOnConditionCheckFailure What values to return on condition check failure. * @return a builder of this type */ public Builder returnValuesOnConditionCheckFailure( ReturnValuesOnConditionCheckFailure returnValuesOnConditionCheckFailure) { this.returnValuesOnConditionCheckFailure = returnValuesOnConditionCheckFailure == null ? null : returnValuesOnConditionCheckFailure.toString(); return this; } /** * Use <code>ReturnValuesOnConditionCheckFailure</code> to get the item attributes if the <code>Delete</code> * condition fails. For <code>ReturnValuesOnConditionCheckFailure</code>, the valid values are: NONE and * ALL_OLD. * * @param returnValuesOnConditionCheckFailure What values to return on condition check failure. * @return a builder of this type */ public Builder returnValuesOnConditionCheckFailure(String returnValuesOnConditionCheckFailure) { this.returnValuesOnConditionCheckFailure = returnValuesOnConditionCheckFailure; return this; } public TransactDeleteItemEnhancedRequest build() { return new TransactDeleteItemEnhancedRequest(this); } } }
4,347
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/model/UpdateItemEnhancedResponse.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.model; import java.util.Objects; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbAsyncTable; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.services.dynamodb.model.ConsumedCapacity; import software.amazon.awssdk.services.dynamodb.model.ItemCollectionMetrics; import software.amazon.awssdk.services.dynamodb.model.ReturnValue; import software.amazon.awssdk.services.dynamodb.model.UpdateItemResponse; /** * Defines the elements returned by DynamoDB from a {@code UpdateItem} operation, such as * {@link DynamoDbTable#updateItemWithResponse(UpdateItemEnhancedRequest)} and * {@link DynamoDbAsyncTable#updateItemWithResponse(UpdateItemEnhancedRequest)}. * * @param <T> The type of the item. */ @SdkPublicApi @ThreadSafe public final class UpdateItemEnhancedResponse<T> { private final T attributes; private final ConsumedCapacity consumedCapacity; private final ItemCollectionMetrics itemCollectionMetrics; private UpdateItemEnhancedResponse(Builder<T> builder) { this.attributes = builder.attributes; this.consumedCapacity = builder.consumedCapacity; this.itemCollectionMetrics = builder.itemCollectionMetrics; } /** * The returned attribute values. These correspond to the DynamoDB {@link ReturnValue} setting. By default, * the attributes reflect the values after the {@code UpdateItem} operation has been applied ({@link ReturnValue#ALL_NEW}). */ public T attributes() { return attributes; } /** * The capacity units consumed by the {@code UpdateItem} operation. * * @see UpdateItemResponse#consumedCapacity() for more information. */ public ConsumedCapacity consumedCapacity() { return consumedCapacity; } /** * Information about item collections, if any, that were affected by the {@code UpdateItem} operation. * * @see UpdateItemResponse#itemCollectionMetrics() for more information. */ public ItemCollectionMetrics itemCollectionMetrics() { return itemCollectionMetrics; } public static <T> Builder<T> builder(Class<? extends T> clzz) { return new Builder<>(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } UpdateItemEnhancedResponse<?> that = (UpdateItemEnhancedResponse<?>) o; return Objects.equals(attributes, that.attributes) && Objects.equals(consumedCapacity, that.consumedCapacity) && Objects.equals(itemCollectionMetrics, that.itemCollectionMetrics); } @Override public int hashCode() { int result = Objects.hashCode(attributes); result = 31 * result + Objects.hashCode(consumedCapacity); result = 31 * result + Objects.hashCode(itemCollectionMetrics); return result; } @NotThreadSafe public static final class Builder<T> { private T attributes; private ConsumedCapacity consumedCapacity; private ItemCollectionMetrics itemCollectionMetrics; public Builder<T> attributes(T attributes) { this.attributes = attributes; return this; } public Builder<T> consumedCapacity(ConsumedCapacity consumedCapacity) { this.consumedCapacity = consumedCapacity; return this; } public Builder<T> itemCollectionMetrics(ItemCollectionMetrics itemCollectionMetrics) { this.itemCollectionMetrics = itemCollectionMetrics; return this; } public UpdateItemEnhancedResponse<T> build() { return new UpdateItemEnhancedResponse<>(this); } } }
4,348
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/model/EnhancedGlobalSecondaryIndex.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.model; import java.util.function.Consumer; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.services.dynamodb.model.Projection; import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughput; import software.amazon.awssdk.utils.Validate; /** * Enhanced model representation of a 'global secondary index' of a DynamoDb table. This is optionally used with the * 'createTable' operation in the enhanced client. */ @SdkPublicApi @ThreadSafe public final class EnhancedGlobalSecondaryIndex { private final String indexName; private final Projection projection; private final ProvisionedThroughput provisionedThroughput; private EnhancedGlobalSecondaryIndex(Builder builder) { this.indexName = Validate.paramNotBlank(builder.indexName, "indexName"); this.projection = builder.projection; this.provisionedThroughput = builder.provisionedThroughput; } /** * Creates a newly initialized builder for an {@link EnhancedLocalSecondaryIndex} * @return A new builder */ public static Builder builder() { return new Builder(); } /** * Creates a builder initialized with the attributes of an existing {@link EnhancedLocalSecondaryIndex} * @return A new builder */ public Builder toBuilder() { return builder().indexName(indexName) .projection(projection) .provisionedThroughput(provisionedThroughput); } /** * The name of the global secondary index */ public String indexName() { return indexName; } /** * The attribute projection setting for this global secondary index. */ public Projection projection() { return projection; } /** * The provisioned throughput setting for this global secondary index. */ public ProvisionedThroughput provisionedThroughput() { return provisionedThroughput; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } EnhancedGlobalSecondaryIndex that = (EnhancedGlobalSecondaryIndex) o; if (indexName != null ? ! indexName.equals(that.indexName) : that.indexName != null) { return false; } if (projection != null ? ! projection.equals(that.projection) : that.projection != null) { return false; } return provisionedThroughput != null ? provisionedThroughput.equals(that.provisionedThroughput) : that.provisionedThroughput == null; } @Override public int hashCode() { int result = indexName != null ? indexName.hashCode() : 0; result = 31 * result + (projection != null ? projection.hashCode() : 0); result = 31 * result + (provisionedThroughput != null ? provisionedThroughput.hashCode() : 0); return result; } /** * A builder for {@link EnhancedGlobalSecondaryIndex} */ @NotThreadSafe public static final class Builder { private String indexName; private Projection projection; private ProvisionedThroughput provisionedThroughput; private Builder() { } /** * The name of the global secondary index */ public Builder indexName(String indexName) { this.indexName = indexName; return this; } /** * The attribute projection setting for this global secondary index. */ public Builder projection(Projection projection) { this.projection = projection; return this; } /** * The attribute projection setting for this global secondary index. */ public Builder projection(Consumer<Projection.Builder> projection) { Projection.Builder builder = Projection.builder(); projection.accept(builder); return projection(builder.build()); } /** * The provisioned throughput setting for this global secondary index. */ public Builder provisionedThroughput(ProvisionedThroughput provisionedThroughput) { this.provisionedThroughput = provisionedThroughput; return this; } /** * The provisioned throughput setting for this global secondary index. */ public Builder provisionedThroughput(Consumer<ProvisionedThroughput.Builder> provisionedThroughput) { ProvisionedThroughput.Builder builder = ProvisionedThroughput.builder(); provisionedThroughput.accept(builder); return provisionedThroughput(builder.build()); } /** * Builds a {@link EnhancedGlobalSecondaryIndex} based on the values stored in this builder */ public EnhancedGlobalSecondaryIndex build() { return new EnhancedGlobalSecondaryIndex(this); } } }
4,349
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/model/DeleteItemEnhancedResponse.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.model; import java.util.Objects; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbAsyncTable; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.services.dynamodb.model.ConsumedCapacity; import software.amazon.awssdk.services.dynamodb.model.DeleteItemResponse; import software.amazon.awssdk.services.dynamodb.model.ItemCollectionMetrics; /** * Defines the elements returned by DynamoDB from a {@code DeleteItem} operation, such as * {@link DynamoDbTable#deleteItemWithResponse(DeleteItemEnhancedRequest)} and * {@link DynamoDbAsyncTable#deleteItemWithResponse(DeleteItemEnhancedRequest)}. * * @param <T> The type of the item. */ @SdkPublicApi @ThreadSafe public final class DeleteItemEnhancedResponse<T> { private final T attributes; private final ConsumedCapacity consumedCapacity; private final ItemCollectionMetrics itemCollectionMetrics; private DeleteItemEnhancedResponse(Builder<T> builder) { this.attributes = builder.attributes; this.consumedCapacity = builder.consumedCapacity; this.itemCollectionMetrics = builder.itemCollectionMetrics; } /** * The attribute values as they appeared before the {@code DeleteItem} operation. */ public T attributes() { return attributes; } /** * The capacity units consumed by the {@code DeleteItem} operation. * * @see DeleteItemResponse#consumedCapacity() for more information. */ public ConsumedCapacity consumedCapacity() { return consumedCapacity; } /** * Information about item collections, if any, that were affected by the {@code DeleteItem} operation. * * @see DeleteItemResponse#itemCollectionMetrics() for more information. */ public ItemCollectionMetrics itemCollectionMetrics() { return itemCollectionMetrics; } public static <T> Builder<T> builder(Class<? extends T> clzz) { return new Builder<>(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DeleteItemEnhancedResponse<?> that = (DeleteItemEnhancedResponse<?>) o; return Objects.equals(attributes, that.attributes) && Objects.equals(consumedCapacity, that.consumedCapacity) && Objects.equals(itemCollectionMetrics, that.itemCollectionMetrics); } @Override public int hashCode() { int result = Objects.hashCode(attributes); result = 31 * result + Objects.hashCode(consumedCapacity); result = 31 * result + Objects.hashCode(itemCollectionMetrics); return result; } @NotThreadSafe public static final class Builder<T> { private T attributes; private ConsumedCapacity consumedCapacity; private ItemCollectionMetrics itemCollectionMetrics; public Builder<T> attributes(T attributes) { this.attributes = attributes; return this; } public Builder<T> consumedCapacity(ConsumedCapacity consumedCapacity) { this.consumedCapacity = consumedCapacity; return this; } public Builder<T> itemCollectionMetrics(ItemCollectionMetrics itemCollectionMetrics) { this.itemCollectionMetrics = itemCollectionMetrics; return this; } public DeleteItemEnhancedResponse<T> build() { return new DeleteItemEnhancedResponse<>(this); } } }
4,350
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/model/PutItemEnhancedResponse.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.model; import java.util.Objects; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbAsyncTable; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.services.dynamodb.model.ConsumedCapacity; import software.amazon.awssdk.services.dynamodb.model.ItemCollectionMetrics; import software.amazon.awssdk.services.dynamodb.model.PutItemResponse; /** * Defines the elements returned by DynamoDB from a {@code PutItem} operation, such as * {@link DynamoDbTable#putItem(PutItemEnhancedRequest)} and {@link DynamoDbAsyncTable#putItem(PutItemEnhancedRequest)}. * * @param <T> The type of the item. */ @SdkPublicApi @ThreadSafe public final class PutItemEnhancedResponse<T> { private final T attributes; private final ConsumedCapacity consumedCapacity; private final ItemCollectionMetrics itemCollectionMetrics; private PutItemEnhancedResponse(Builder<T> builder) { this.attributes = builder.attributes; this.consumedCapacity = builder.consumedCapacity; this.itemCollectionMetrics = builder.itemCollectionMetrics; } /** * The attribute values as they appeared before the {@code PutItem} operation. */ public T attributes() { return attributes; } /** * The capacity units consumed by the {@code PutItem} operation. * * @see PutItemResponse#consumedCapacity() for more information. */ public ConsumedCapacity consumedCapacity() { return consumedCapacity; } /** * Information about item collections, if any, that were affected by the {@code PutItem} operation. * * @see PutItemResponse#itemCollectionMetrics() for more information. */ public ItemCollectionMetrics itemCollectionMetrics() { return itemCollectionMetrics; } public static <T> Builder<T> builder(Class<? extends T> clzz) { return new Builder<>(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PutItemEnhancedResponse<?> that = (PutItemEnhancedResponse<?>) o; return Objects.equals(attributes, that.attributes) && Objects.equals(consumedCapacity, that.consumedCapacity) && Objects.equals(itemCollectionMetrics, that.itemCollectionMetrics); } @Override public int hashCode() { int result = Objects.hashCode(attributes); result = 31 * result + Objects.hashCode(consumedCapacity); result = 31 * result + Objects.hashCode(itemCollectionMetrics); return result; } @NotThreadSafe public static final class Builder<T> { private T attributes; private ConsumedCapacity consumedCapacity; private ItemCollectionMetrics itemCollectionMetrics; public Builder<T> attributes(T attributes) { this.attributes = attributes; return this; } public Builder<T> consumedCapacity(ConsumedCapacity consumedCapacity) { this.consumedCapacity = consumedCapacity; return this; } public Builder<T> itemCollectionMetrics(ItemCollectionMetrics itemCollectionMetrics) { this.itemCollectionMetrics = itemCollectionMetrics; return this; } public PutItemEnhancedResponse<T> build() { return new PutItemEnhancedResponse<>(this); } } }
4,351
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/model/QueryEnhancedRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.model; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbAsyncIndex; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.Expression; import software.amazon.awssdk.enhanced.dynamodb.NestedAttributeName; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.QueryRequest; import software.amazon.awssdk.services.dynamodb.model.ReturnConsumedCapacity; import software.amazon.awssdk.services.dynamodb.model.ScanRequest; import software.amazon.awssdk.utils.Validate; /** * Defines parameters used to when querying a DynamoDb table or index using the query() operation (such as * {@link DynamoDbTable#query(QueryEnhancedRequest)} or {@link DynamoDbAsyncIndex#query(QueryEnhancedRequest)}). * <p> * A valid request object must contain a {@link QueryConditional} condition specifying how DynamoDb * should match items in the table. * <p> * All other parameters are optional. */ @SdkPublicApi @ThreadSafe public final class QueryEnhancedRequest { private final QueryConditional queryConditional; private final Map<String, AttributeValue> exclusiveStartKey; private final Boolean scanIndexForward; private final Integer limit; private final Boolean consistentRead; private final Expression filterExpression; private final List<NestedAttributeName> attributesToProject; private final String returnConsumedCapacity; private QueryEnhancedRequest(Builder builder) { this.queryConditional = builder.queryConditional; this.exclusiveStartKey = builder.exclusiveStartKey; this.scanIndexForward = builder.scanIndexForward; this.limit = builder.limit; this.consistentRead = builder.consistentRead; this.filterExpression = builder.filterExpression; this.returnConsumedCapacity = builder.returnConsumedCapacity; this.attributesToProject = builder.attributesToProject != null ? Collections.unmodifiableList(builder.attributesToProject) : null; } /** * Creates a newly initialized builder for a request object. */ public static Builder builder() { return new Builder(); } /** * Returns a builder initialized with all existing values on the request object. */ public Builder toBuilder() { return builder().queryConditional(queryConditional) .exclusiveStartKey(exclusiveStartKey) .scanIndexForward(scanIndexForward) .limit(limit) .consistentRead(consistentRead) .filterExpression(filterExpression) .returnConsumedCapacity(returnConsumedCapacity) .addNestedAttributesToProject(attributesToProject); } /** * Returns the matching condition of the query. */ public QueryConditional queryConditional() { return queryConditional; } /** * Returns the value of the exclusive start key set on this request object, or null if it doesn't exist. */ public Map<String, AttributeValue> exclusiveStartKey() { return exclusiveStartKey; } /** * Returns the value of scan index forward, meaning an ascending result sort order, or true if it * has not been set. */ public Boolean scanIndexForward() { return scanIndexForward; } /** * Returns the value of limit set on this request object, or null if it doesn't exist. */ public Integer limit() { return limit; } /** * Returns the value of consistent read, or false if it has not been set. */ public Boolean consistentRead() { return consistentRead; } /** * Returns the return result filter {@link Expression} set on this request object, or null if it doesn't exist. */ public Expression filterExpression() { return filterExpression; } /** * Returns the list of projected attributes on this request object, or an null if no projection is specified. * Nested attributes are represented using the '.' separator. Example : foo.bar is represented as "foo.bar" which is * indistinguishable from a non-nested attribute with the name "foo.bar". * Use {@link #nestedAttributesToProject} if you have a use-case that requires discrimination between these two cases. */ public List<String> attributesToProject() { return attributesToProject != null ? attributesToProject.stream() .map(item -> String.join(".", item.elements())).collect(Collectors.toList()) : null; } /** * Returns the list of projected attribute names, in the form of {@link NestedAttributeName} objects, * for this request object, or null if no projection is specified. * Refer {@link NestedAttributeName} . */ public List<NestedAttributeName> nestedAttributesToProject() { return attributesToProject; } /** * Whether to return the capacity consumed by this operation. * * @see ScanRequest#returnConsumedCapacity() */ public ReturnConsumedCapacity returnConsumedCapacity() { return ReturnConsumedCapacity.fromValue(returnConsumedCapacity); } /** * Whether to return the capacity consumed by this operation. * <p> * Similar to {@link #returnConsumedCapacity()} but return the value as a string. This is useful in situations where the * value is not defined in {@link ReturnConsumedCapacity}. */ public String returnConsumedCapacityAsString() { return returnConsumedCapacity; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } QueryEnhancedRequest query = (QueryEnhancedRequest) o; if (queryConditional != null ? ! queryConditional.equals(query.queryConditional) : query.queryConditional != null) { return false; } if (exclusiveStartKey != null ? ! exclusiveStartKey.equals(query.exclusiveStartKey) : query.exclusiveStartKey != null) { return false; } if (scanIndexForward != null ? ! scanIndexForward.equals(query.scanIndexForward) : query.scanIndexForward != null) { return false; } if (limit != null ? ! limit.equals(query.limit) : query.limit != null) { return false; } if (consistentRead != null ? ! consistentRead.equals(query.consistentRead) : query.consistentRead != null) { return false; } if (attributesToProject != null ? !attributesToProject.equals(query.attributesToProject) : query.attributesToProject != null) { return false; } if (returnConsumedCapacity != null ? !returnConsumedCapacity.equals(query.returnConsumedCapacity) : query.returnConsumedCapacity != null) { return false; } return filterExpression != null ? filterExpression.equals(query.filterExpression) : query.filterExpression == null; } @Override public int hashCode() { int result = queryConditional != null ? queryConditional.hashCode() : 0; result = 31 * result + (exclusiveStartKey != null ? exclusiveStartKey.hashCode() : 0); result = 31 * result + (scanIndexForward != null ? scanIndexForward.hashCode() : 0); result = 31 * result + (limit != null ? limit.hashCode() : 0); result = 31 * result + (consistentRead != null ? consistentRead.hashCode() : 0); result = 31 * result + (filterExpression != null ? filterExpression.hashCode() : 0); result = 31 * result + (attributesToProject != null ? attributesToProject.hashCode() : 0); result = 31 * result + (returnConsumedCapacity != null ? returnConsumedCapacity.hashCode() : 0); return result; } /** * A builder that is used to create a request with the desired parameters. * <p> * A valid builder must set the {@link #queryConditional} parameter. Other parameters are optional. */ @NotThreadSafe public static final class Builder { private QueryConditional queryConditional; private Map<String, AttributeValue> exclusiveStartKey; private Boolean scanIndexForward; private Integer limit; private Boolean consistentRead; private Expression filterExpression; private List<NestedAttributeName> attributesToProject; private String returnConsumedCapacity; private Builder() { } /** * Determines the matching conditions for this query request. See {@link QueryConditional} for examples * and constraints. <b>Required</b>. * * @param queryConditional the query conditions * @return a builder of this type */ public Builder queryConditional(QueryConditional queryConditional) { this.queryConditional = queryConditional; return this; } /** * Results are sorted by sort key in ascending order if {@link #scanIndexForward} is true. If its false, the * order is descending. The default value is true. * * @param scanIndexForward the sort order * @return a builder of this type */ public Builder scanIndexForward(Boolean scanIndexForward) { this.scanIndexForward = scanIndexForward; return this; } /** * The primary key of the first item that this operation will evaluate. By default, the operation will evaluate * the whole dataset. If used, normally this parameter is populated with the value that was returned for * {@link Page#lastEvaluatedKey()} in the previous operation. * * @param exclusiveStartKey the primary key value where DynamoDb should start to evaluate items * @return a builder of this type */ public Builder exclusiveStartKey(Map<String, AttributeValue> exclusiveStartKey) { this.exclusiveStartKey = exclusiveStartKey != null ? new HashMap<>(exclusiveStartKey) : null; return this; } /** * Sets a limit on how many items to evaluate in the query. If not set, the operation uses * the maximum values allowed. * <p> * <b>Note:</b>The limit does not refer to the number of items to return, but how many items * the database should evaluate while executing the query. Use limit together with {@link Page#lastEvaluatedKey()} * and {@link #exclusiveStartKey} in subsequent query calls to evaluate <em>limit</em> items per call. * * @param limit the maximum number of items to evalute * @return a builder of this type */ public Builder limit(Integer limit) { this.limit = limit; return this; } /** * Determines the read consistency model: If set to true, the operation uses strongly consistent reads; otherwise, * the operation uses eventually consistent reads. * <p> * By default, the value of this property is set to <em>false</em>. * * @param consistentRead sets consistency model of the operation to use strong consistency * @return a builder of this type */ public Builder consistentRead(Boolean consistentRead) { this.consistentRead = consistentRead; return this; } /** * Refines the query results by applying the filter expression on the results returned * from the query and discards items that do not match. See {@link Expression} for examples * and constraints. * <p> * <b>Note:</b> Using the filter expression does not reduce the cost of the query, since it is applied * <em>after</em> the database has found matching items. * * @param filterExpression an expression that filters results of evaluating the query * @return a builder of this type */ public Builder filterExpression(Expression filterExpression) { this.filterExpression = filterExpression; return this; } /** * <p> * Sets a collection of the attribute names to be retrieved from the database. These attributes can include * scalars, sets, or elements of a JSON document. * <p> * If no attribute names are specified, then all attributes will be returned. If any of the requested attributes * are not found, they will not appear in the result. * <p> If there are nested attributes, use any of the addNestedAttributesToProject methods, such as * {@link #addNestedAttributesToProject(NestedAttributeName...)}. * <p> * For more information, see <a href= * "https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.AccessingItemAttributes.html" * >Accessing Item Attributes</a> in the <i>Amazon DynamoDB Developer Guide</i>. * </p> * * @param attributesToProject A collection of the attributes names to be retrieved from the database. * @return Returns a reference to this object so that method calls can be chained together. */ public Builder attributesToProject(Collection<String> attributesToProject) { if (this.attributesToProject != null) { this.attributesToProject.clear(); } if (attributesToProject != null) { addNestedAttributesToProject(new ArrayList<>(attributesToProject).stream() .map(NestedAttributeName::create).collect(Collectors.toList())); } return this; } /** * <p> * Sets one or more attribute names to be retrieved from the database. These attributes can include * scalars, sets, or elements of a JSON document. * <p> * If no attribute names are specified, then all attributes will be returned. If any of the requested attributes * are not found, they will not appear in the result. * <p> If there are nested attributes, use any of the addNestedAttributesToProject methods, such as * {@link #addNestedAttributesToProject(NestedAttributeName...)}. * <p> * For more information, see <a href= * "https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.AccessingItemAttributes.html" * >Accessing Item Attributes</a> in the <i>Amazon DynamoDB Developer Guide</i>. * * @param attributesToProject One or more attributes names to be retrieved from the database. * @return Returns a reference to this object so that method calls can be chained together. */ public Builder attributesToProject(String... attributesToProject) { return attributesToProject(Arrays.asList(attributesToProject)); } /** * <p> Adds a single attribute name to be retrieved from the database. This attribute can include * scalars, sets, or elements of a JSON document. * <p> If there are nested attributes, use any of the addNestedAttributesToProject methods, such as * {@link #addNestedAttributesToProject(NestedAttributeName...)}. * * @param attributeToProject An additional single attribute name to be retrieved from the database. * @return Returns a reference to this object so that method calls can be chained together. */ public Builder addAttributeToProject(String attributeToProject) { if (attributeToProject != null) { addNestedAttributesToProject(NestedAttributeName.create(attributeToProject)); } return this; } /** * Adds a collection of nested attributes to be retrieved from the database. These attributes can include * scalars, sets, or elements of a JSON document. * <p> * This method is additive, so calling it multiple times will add to the list of nested attribute names. * @see NestedAttributeName * * @param nestedAttributeNames A collection of attributes to be retrieved from the database. * @return Returns a reference to this object so that method calls can be chained together. */ public Builder addNestedAttributesToProject(Collection<NestedAttributeName> nestedAttributeNames) { if (nestedAttributeNames != null) { Validate.noNullElements(nestedAttributeNames, "nestedAttributeNames list must not contain null elements"); if (attributesToProject == null) { this.attributesToProject = new ArrayList<>(nestedAttributeNames); } else { this.attributesToProject.addAll(nestedAttributeNames); } } return this; } /** * Adds a collection of nested attributes to be retrieved from the database. These attributes can include * scalars, sets, or elements of a JSON document. * <p> * This method is additive, so calling it multiple times will add to the list of nested attribute names. * @see NestedAttributeName * * @param nestedAttributeNames A collection of attributes to be retrieved from the database. * @return Returns a reference to this object so that method calls can be chained together. */ public Builder addNestedAttributesToProject(NestedAttributeName... nestedAttributeNames) { return addNestedAttributesToProject(Arrays.asList(nestedAttributeNames)); } /** * Adds a single nested attribute to be retrieved from the database. The attribute can include * scalars, sets, or elements of a JSON document. * <p> * This method is additive, so calling it multiple times will add to the list of nested attribute names. * @see NestedAttributeName * * * @param nestedAttributeName A single attribute name to be retrieved from the database. * @return Returns a reference to this object so that method calls can be chained together. */ public Builder addNestedAttributeToProject(NestedAttributeName nestedAttributeName) { if (nestedAttributeName != null) { addNestedAttributesToProject(Arrays.asList(nestedAttributeName)); } return this; } /** * Whether to return the capacity consumed by this operation. * * @see QueryRequest.Builder#returnConsumedCapacity(ReturnConsumedCapacity) */ public Builder returnConsumedCapacity(ReturnConsumedCapacity returnConsumedCapacity) { this.returnConsumedCapacity = returnConsumedCapacity == null ? null : returnConsumedCapacity.toString(); return this; } /** * Whether to return the capacity consumed by this operation. * * @see QueryRequest.Builder#returnConsumedCapacity(String) */ public Builder returnConsumedCapacity(String returnConsumedCapacity) { this.returnConsumedCapacity = returnConsumedCapacity; return this; } public QueryEnhancedRequest build() { return new QueryEnhancedRequest(this); } } }
4,352
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/model/TransactWriteItemsEnhancedRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.model; import static software.amazon.awssdk.enhanced.dynamodb.internal.EnhancedClientUtils.getItemsFromSupplier; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; import java.util.function.Supplier; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.Key; import software.amazon.awssdk.enhanced.dynamodb.MappedTableResource; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.DefaultOperationContext; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.DeleteItemOperation; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.PutItemOperation; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.TransactableWriteOperation; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.UpdateItemOperation; import software.amazon.awssdk.services.dynamodb.model.TransactWriteItem; /** * Defines parameters used for the transaction operation transactWriteItems() (such as * {@link DynamoDbEnhancedClient#transactWriteItems(TransactWriteItemsEnhancedRequest)}). * <p> * A request contains parameters for the different actions available in the operation: * <ul> * <li>Write/Update items through put and update actions</li> * <li>Delete items</li> * <li>Use a condition check</li> * </ul> * It's populated with one or more low-level requests, such as {@link TransactPutItemEnhancedRequest} and each low-level action * request is associated with the table where the action should be applied. On initialization, these requests are transformed * into {@link TransactWriteItem} and stored in the request. */ @SdkPublicApi @ThreadSafe public final class TransactWriteItemsEnhancedRequest { private final List<TransactWriteItem> transactWriteItems; private final String clientRequestToken; private TransactWriteItemsEnhancedRequest(Builder builder) { this.transactWriteItems = getItemsFromSupplier(builder.itemSupplierList); this.clientRequestToken = builder.clientRequestToken; } /** * Creates a newly initialized builder for a request object. */ public static Builder builder() { return new Builder(); } /** * <p> * Providing a <code>ClientRequestToken</code> makes the call to <code>TransactWriteItems</code> idempotent, meaning * that multiple identical calls have the same effect as one single call. * </p> * <p> * A client request token is valid for 10 minutes after the first request that uses it is completed. After 10 * minutes, any request with the same client token is treated as a new request. Do not resubmit the same request * with the same client token for more than 10 minutes, or the result might not be idempotent. * </p> * <p> * If you submit a request with the same client token but a change in other parameters within the 10-minute * idempotency window, DynamoDB returns an <code>IdempotentParameterMismatch</code> exception. * </p> */ public String clientRequestToken() { return clientRequestToken; } /** * Returns the list of {@link TransactWriteItem} that represents all actions in the request. */ public List<TransactWriteItem> transactWriteItems() { return transactWriteItems; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } TransactWriteItemsEnhancedRequest that = (TransactWriteItemsEnhancedRequest) o; return transactWriteItems != null ? transactWriteItems.equals(that.transactWriteItems) : that.transactWriteItems == null; } @Override public int hashCode() { return transactWriteItems != null ? transactWriteItems.hashCode() : 0; } /** * A builder that is used to create a transaction object with the desired parameters. * <p> * A valid builder should contain at least one low-level request such as {@link DeleteItemEnhancedRequest}. */ @NotThreadSafe public static final class Builder { private List<Supplier<TransactWriteItem>> itemSupplierList = new ArrayList<>(); private String clientRequestToken; private Builder() { } /** * Adds a condition check for a primary key in the associated table to the transaction. * <p> * <b>Note:</b> The condition check should be applied to an item that is not modified by another action in the * same transaction. See {@link ConditionCheck} for more information on how to build a condition check, and the * DynamoDb TransactWriteItems documentation for more information on how a condition check affects the transaction. * * @param mappedTableResource the table on which to apply the condition check * @param request A {@link ConditionCheck} definition * @param <T> the type of modelled objects in the table * @return a builder of this type */ public <T> Builder addConditionCheck(MappedTableResource<T> mappedTableResource, ConditionCheck<T> request) { itemSupplierList.add(() -> generateTransactWriteItem(mappedTableResource, request)); return this; } /** * Adds a condition check for a primary key in the associated table to the transaction by accepting a consumer * of {@link ConditionCheck.Builder}. * <p> * <b>Note:</b> The condition check should be applied to an item that is not modified by another action in the * same transaction. See {@link ConditionCheck} for more information on how to build a condition check, and the * DynamoDb TransactWriteItems documentation for more information on how a condition check affects the transaction. * * @param mappedTableResource the table on which to apply the condition check * @param requestConsumer a {@link Consumer} of {@link DeleteItemEnhancedRequest} * @param <T> the type of modelled objects in the table * @return a builder of this type */ public <T> Builder addConditionCheck(MappedTableResource<T> mappedTableResource, Consumer<ConditionCheck.Builder> requestConsumer) { ConditionCheck.Builder builder = ConditionCheck.builder(); requestConsumer.accept(builder); return addConditionCheck(mappedTableResource, builder.build()); } /** * Adds a primary lookup key for the item to delete, and it's associated table, to the transaction. For more information * on the delete action, see the low-level operation description in for instance * {@link DynamoDbTable#deleteItem(DeleteItemEnhancedRequest)} and how to construct the low-level request in * {@link DeleteItemEnhancedRequest}. * * @param mappedTableResource the table where the key is located * @param request A {@link DeleteItemEnhancedRequest} * @param <T> the type of modelled objects in the table * @return a builder of this type * * @deprecated Use {@link #addDeleteItem(MappedTableResource, TransactDeleteItemEnhancedRequest)} */ @Deprecated public <T> Builder addDeleteItem(MappedTableResource<T> mappedTableResource, DeleteItemEnhancedRequest request) { itemSupplierList.add(() -> generateTransactWriteItem(mappedTableResource, DeleteItemOperation.create(request))); return this; } /** * Adds a primary lookup key for the item to delete, and its associated table, to the transaction. For more information * on the delete action, see the low-level operation description in for instance * {@link DynamoDbTable#deleteItem(DeleteItemEnhancedRequest)} and how to construct the low-level request in * {@link TransactDeleteItemEnhancedRequest}. * * @param mappedTableResource the table where the key is located * @param request A {@link TransactDeleteItemEnhancedRequest} * @param <T> the type of modelled objects in the table * @return a builder of this type */ public <T> Builder addDeleteItem(MappedTableResource<T> mappedTableResource, TransactDeleteItemEnhancedRequest request) { itemSupplierList.add(() -> generateTransactWriteItem(mappedTableResource, DeleteItemOperation.create(request))); return this; } /** * Adds a primary lookup key for the item to delete, and it's associated table, to the transaction. For more * information on the delete action, see the low-level operation description in for instance * {@link DynamoDbTable#deleteItem(DeleteItemEnhancedRequest)}. * * @param mappedTableResource the table where the key is located * @param key a {@link Key} that identifies the record to be deleted as part of the transaction. * @param <T> the type of modelled objects in the table * @return a builder of this type */ public <T> Builder addDeleteItem(MappedTableResource<T> mappedTableResource, Key key) { return addDeleteItem(mappedTableResource, TransactDeleteItemEnhancedRequest.builder().key(key).build()); } /** * Adds a primary lookup key for the item to delete, and it's associated table, to the transaction. For more * information on the delete action, see the low-level operation description in for instance * {@link DynamoDbTable#deleteItem(DeleteItemEnhancedRequest)}. * * @param mappedTableResource the table where the key is located * @param keyItem an item that will have its key fields used to match a record to retrieve from the database * @param <T> the type of modelled objects in the table * @return a builder of this type */ public <T> Builder addDeleteItem(MappedTableResource<T> mappedTableResource, T keyItem) { return addDeleteItem(mappedTableResource, mappedTableResource.keyFrom(keyItem)); } /** * Adds an item to be written, and it's associated table, to the transaction. For more information on the put action, * see the low-level operation description in for instance {@link DynamoDbTable#putItem(PutItemEnhancedRequest)} * and how to construct the low-level request in {@link PutItemEnhancedRequest}. * * @param mappedTableResource the table to write the item to * @param request A {@link PutItemEnhancedRequest} * @param <T> the type of modelled objects in the table * @return a builder of this type * * @deprecated Use {@link #addPutItem(MappedTableResource, TransactPutItemEnhancedRequest)} */ @Deprecated public <T> Builder addPutItem(MappedTableResource<T> mappedTableResource, PutItemEnhancedRequest<T> request) { itemSupplierList.add(() -> generateTransactWriteItem(mappedTableResource, PutItemOperation.create(request))); return this; } /** * Adds an item to be written, and it's associated table, to the transaction. For more information on the put action, * see the low-level operation description in for instance {@link DynamoDbTable#putItem(PutItemEnhancedRequest)} * and how to construct the low-level request in {@link TransactPutItemEnhancedRequest}. * * @param mappedTableResource the table to write the item to * @param request A {@link TransactPutItemEnhancedRequest} * @param <T> the type of modelled objects in the table * @return a builder of this type */ public <T> Builder addPutItem(MappedTableResource<T> mappedTableResource, TransactPutItemEnhancedRequest<T> request) { itemSupplierList.add(() -> generateTransactWriteItem(mappedTableResource, PutItemOperation.create(request))); return this; } /** * Adds an item to be written, and it's associated table, to the transaction. For more information on the put * action, see the low-level operation description in for instance * {@link DynamoDbTable#putItem(PutItemEnhancedRequest)}. * * @param mappedTableResource the table to write the item to * @param item the item to be inserted or overwritten in the database * @param <T> the type of modelled objects in the table * @return a builder of this type */ public <T> Builder addPutItem(MappedTableResource<T> mappedTableResource, T item) { return addPutItem( mappedTableResource, TransactPutItemEnhancedRequest.builder(mappedTableResource.tableSchema().itemType().rawClass()) .item(item) .build()); } /** * Adds an item to be updated, and it's associated table, to the transaction. For more information on the update * action, see the low-level operation description in for instance * {@link DynamoDbTable#updateItem(UpdateItemEnhancedRequest)} and how to construct the low-level request in * {@link UpdateItemEnhancedRequest}. * * @param mappedTableResource the table to write the item to * @param request A {@link UpdateItemEnhancedRequest} * @param <T> the type of modelled objects in the table * @return a builder of this type * * @deprecated Use {@link #addUpdateItem(MappedTableResource, TransactUpdateItemEnhancedRequest)} */ @Deprecated public <T> Builder addUpdateItem(MappedTableResource<T> mappedTableResource, UpdateItemEnhancedRequest<T> request) { itemSupplierList.add(() -> generateTransactWriteItem(mappedTableResource, UpdateItemOperation.create(request))); return this; } /** * Adds an item to be updated, and it's associated table, to the transaction. For more information on the update * action, see the low-level operation description in for instance * {@link DynamoDbTable#updateItem(UpdateItemEnhancedRequest)} and how to construct the low-level request in * {@link TransactUpdateItemEnhancedRequest}. * * @param mappedTableResource the table to write the item to * @param request A {@link UpdateItemEnhancedRequest} * @param <T> the type of modelled objects in the table * @return a builder of this type */ public <T> Builder addUpdateItem(MappedTableResource<T> mappedTableResource, TransactUpdateItemEnhancedRequest<T> request) { itemSupplierList.add(() -> generateTransactWriteItem(mappedTableResource, UpdateItemOperation.create(request))); return this; } /** * Adds an item to be updated, and it's associated table, to the transaction. For more information on the update * action, see the low-level operation description in for instance * {@link DynamoDbTable#updateItem(UpdateItemEnhancedRequest)}. * * @param mappedTableResource the table to write the item to * @param item an item to update or insert into the database as part of this transaction * @param <T> the type of modelled objects in the table * @return a builder of this type */ public <T> Builder addUpdateItem(MappedTableResource<T> mappedTableResource, T item) { return addUpdateItem( mappedTableResource, TransactUpdateItemEnhancedRequest.builder(mappedTableResource.tableSchema().itemType().rawClass()) .item(item) .build()); } /** * Sets the clientRequestToken in this builder. * * @param clientRequestToken the clientRequestToken going to be used for build * @return a builder of this type */ public Builder clientRequestToken(String clientRequestToken) { this.clientRequestToken = clientRequestToken; return this; } /** * Builds a {@link TransactWriteItemsEnhancedRequest} from the values stored in this builder. */ public TransactWriteItemsEnhancedRequest build() { return new TransactWriteItemsEnhancedRequest(this); } private <T> TransactWriteItem generateTransactWriteItem(MappedTableResource<T> mappedTableResource, TransactableWriteOperation<T> generator) { return generator.generateTransactWriteItem(mappedTableResource.tableSchema(), DefaultOperationContext.create(mappedTableResource.tableName()), mappedTableResource.mapperExtension()); } } }
4,353
0
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb
Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/main/java/software/amazon/awssdk/enhanced/dynamodb/model/TransactGetItemsEnhancedRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.enhanced.dynamodb.model; import static software.amazon.awssdk.enhanced.dynamodb.internal.EnhancedClientUtils.getItemsFromSupplier; import java.util.ArrayList; import java.util.List; import java.util.function.Supplier; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.Key; import software.amazon.awssdk.enhanced.dynamodb.MappedTableResource; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.DefaultOperationContext; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.GetItemOperation; import software.amazon.awssdk.enhanced.dynamodb.internal.operations.TransactableReadOperation; import software.amazon.awssdk.services.dynamodb.model.TransactGetItem; /** * Defines parameters used for the transaction operation transactGetItems() (such as * {@link DynamoDbEnhancedClient#transactGetItems(TransactGetItemsEnhancedRequest)}). * <p> * A request contains references to the primary keys for the items this operation will search for. * It's populated with one or more {@link GetItemEnhancedRequest}, each associated with with the table where the item is located. * On initialization, these requests are transformed into {@link TransactGetItem} and stored in the request. * . */ @SdkPublicApi @ThreadSafe public final class TransactGetItemsEnhancedRequest { private final List<TransactGetItem> transactGetItems; private TransactGetItemsEnhancedRequest(Builder builder) { this.transactGetItems = getItemsFromSupplier(builder.itemSupplierList); } /** * Creates a newly initialized builder for a request object. */ public static Builder builder() { return new Builder(); } /** * Returns the list of {@link TransactGetItem} that represents all lookup keys in the request. */ public List<TransactGetItem> transactGetItems() { return transactGetItems; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } TransactGetItemsEnhancedRequest that = (TransactGetItemsEnhancedRequest) o; return transactGetItems != null ? transactGetItems.equals(that.transactGetItems) : that.transactGetItems == null; } @Override public int hashCode() { return transactGetItems != null ? transactGetItems.hashCode() : 0; } /** * A builder that is used to create a transaction object with the desired parameters. * <p> * A valid builder should contain at least one {@link GetItemEnhancedRequest} added through addGetItem(). */ @NotThreadSafe public static final class Builder { private List<Supplier<TransactGetItem>> itemSupplierList = new ArrayList<>(); private Builder() { } /** * Adds a primary lookup key and it's associated table to the transaction. * * @param mappedTableResource the table where the key is located * @param request A {@link GetItemEnhancedRequest} * @return a builder of this type */ public Builder addGetItem(MappedTableResource<?> mappedTableResource, GetItemEnhancedRequest request) { itemSupplierList.add(() -> generateTransactWriteItem(mappedTableResource, GetItemOperation.create(request))); return this; } /** * Adds a primary lookup key and it's associated table to the transaction. * * @param mappedTableResource the table where the key is located * @param key the primary key of an item to retrieve as part of the transaction * @return a builder of this type */ public Builder addGetItem(MappedTableResource<?> mappedTableResource, Key key) { return addGetItem(mappedTableResource, GetItemEnhancedRequest.builder().key(key).build()); } /** * Adds a primary lookup key and it's associated table to the transaction. * * @param mappedTableResource the table where the key is located * @param keyItem an item that will have its key fields used to match a record to retrieve from the database * @param <T> the type of modelled objects in the table * @return a builder of this type */ public <T> Builder addGetItem(MappedTableResource<T> mappedTableResource, T keyItem) { return addGetItem(mappedTableResource, mappedTableResource.keyFrom(keyItem)); } /** * Builds a {@link TransactGetItemsEnhancedRequest} from the values stored in this builder. */ public TransactGetItemsEnhancedRequest build() { return new TransactGetItemsEnhancedRequest(this); } private <T> TransactGetItem generateTransactWriteItem(MappedTableResource<T> mappedTableResource, TransactableReadOperation<T> generator) { return generator.generateTransactGetItem(mappedTableResource.tableSchema(), DefaultOperationContext.create(mappedTableResource.tableName()), mappedTableResource.mapperExtension()); } } }
4,354
0
Create_ds/aws-sdk-java-v2/services/iotdataplane/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/iotdataplane/src/it/java/software/amazon/awssdk/services/iotdataplane/ServiceIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.iotdataplane; import static org.hamcrest.Matchers.greaterThan; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.net.URI; import java.nio.ByteBuffer; import org.junit.Before; import org.junit.Test; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.iot.IotClient; import software.amazon.awssdk.services.iotdataplane.model.DeleteThingShadowRequest; import software.amazon.awssdk.services.iotdataplane.model.DeleteThingShadowResponse; import software.amazon.awssdk.services.iotdataplane.model.GetThingShadowRequest; import software.amazon.awssdk.services.iotdataplane.model.GetThingShadowResponse; import software.amazon.awssdk.services.iotdataplane.model.InvalidRequestException; import software.amazon.awssdk.services.iotdataplane.model.PublishRequest; import software.amazon.awssdk.services.iotdataplane.model.ResourceNotFoundException; import software.amazon.awssdk.services.iotdataplane.model.UpdateThingShadowRequest; import software.amazon.awssdk.services.iotdataplane.model.UpdateThingShadowResponse; import software.amazon.awssdk.testutils.service.AwsIntegrationTestBase; import software.amazon.awssdk.utils.BinaryUtils; public class ServiceIntegrationTest extends AwsIntegrationTestBase { private static final String STATE_FIELD_NAME = "state"; private static final String THING_NAME = "foo"; private static final String INVALID_THING_NAME = "INVALID_THING_NAME"; private IotDataPlaneClient iot; private static JsonNode getPayloadAsJsonNode(ByteBuffer payload) throws IOException { return new ObjectMapper().readTree(BinaryUtils.toStream(payload)); } private static void assertPayloadNonEmpty(SdkBytes payload) { assertThat(payload.asByteBuffer().capacity(), greaterThan(0)); } /** * Asserts that the returned payload has the correct state in the JSON document. It should be * exactly what we sent it plus some additional metadata * * @param originalPayload * ByteBuffer we sent to the service containing just the state * @param returnedPayload * ByteBuffer returned by the service containing the state (which should be the same * as what we sent) plus additional metadata in the JSON document */ private static void assertPayloadIsValid(SdkBytes originalPayload, SdkBytes returnedPayload) throws Exception { JsonNode originalJson = getPayloadAsJsonNode(originalPayload.asByteBuffer()); JsonNode returnedJson = getPayloadAsJsonNode(returnedPayload.asByteBuffer()); assertEquals(originalJson.get(STATE_FIELD_NAME), returnedJson.get(STATE_FIELD_NAME)); } @Before public void setup() throws Exception { IotClient client = IotClient.builder().credentialsProvider(CREDENTIALS_PROVIDER_CHAIN).region(Region.US_EAST_1).build(); String endpoint = client.describeEndpoint(r -> r.endpointType("iot:Data-ATS")).endpointAddress(); iot = IotDataPlaneClient.builder() .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .endpointOverride(URI.create("https://" + endpoint)) .region(Region.US_EAST_1) .build(); } @Test public void publish_ValidTopicAndNonEmptyPayload_DoesNotThrowException() { iot.publish(PublishRequest.builder().topic(THING_NAME).payload(SdkBytes.fromByteArray(new byte[] {1, 2, 3, 4})).build()); } @Test public void publish_WithValidTopicAndEmptyPayload_DoesNotThrowException() { iot.publish(PublishRequest.builder().topic(THING_NAME).payload(null).build()); } @Test(expected = InvalidRequestException.class) public void updateThingShadow_NullPayload_ThrowsServiceException() throws Exception { UpdateThingShadowRequest request = UpdateThingShadowRequest.builder().thingName(THING_NAME).payload(null).build(); iot.updateThingShadow(request); } @Test(expected = InvalidRequestException.class) public void updateThingShadow_MalformedPayload_ThrowsServiceException() throws Exception { SdkBytes payload = SdkBytes.fromUtf8String("{ }"); UpdateThingShadowRequest request = UpdateThingShadowRequest.builder().thingName(THING_NAME).payload(payload).build(); iot.updateThingShadow(request); } @Test(expected = ResourceNotFoundException.class) public void getThingShadow_InvalidThingName_ThrowsException() { iot.getThingShadow(GetThingShadowRequest.builder().thingName(INVALID_THING_NAME).build()); } @Test(expected = ResourceNotFoundException.class) public void deleteThingShadow_InvalidThing_ThrowsException() { DeleteThingShadowResponse result = iot .deleteThingShadow(DeleteThingShadowRequest.builder().thingName(INVALID_THING_NAME).build()); assertPayloadNonEmpty(result.payload()); } @Test public void UpdateReadDeleteThing() throws Exception { updateThingShadow_ValidRequest_ReturnsValidResponse(THING_NAME); getThingShadow_ValidThing_ReturnsThingData(THING_NAME); deleteThingShadow_ValidThing_DeletesSuccessfully(THING_NAME); } private void updateThingShadow_ValidRequest_ReturnsValidResponse(String thingName) throws Exception { SdkBytes originalPayload = SdkBytes.fromUtf8String("{ \"state\": {\"reported\":{ \"r\": {}}}}"); UpdateThingShadowRequest request = UpdateThingShadowRequest.builder().thingName(thingName).payload(originalPayload).build(); UpdateThingShadowResponse result = iot.updateThingShadow(request); // Comes back with some extra metadata so we assert it's bigger than the original assertThat(result.payload().asByteBuffer().capacity(), greaterThan(originalPayload.asByteBuffer().capacity())); assertPayloadIsValid(originalPayload, result.payload()); } private void getThingShadow_ValidThing_ReturnsThingData(String thingName) { GetThingShadowRequest request = GetThingShadowRequest.builder().thingName(thingName).build(); GetThingShadowResponse result = iot.getThingShadow(request); assertPayloadNonEmpty(result.payload()); } private void deleteThingShadow_ValidThing_DeletesSuccessfully(String thingName) { DeleteThingShadowResponse result = iot.deleteThingShadow(DeleteThingShadowRequest.builder().thingName(thingName).build()); assertPayloadNonEmpty(result.payload()); } }
4,355
0
Create_ds/aws-sdk-java-v2/services/kinesis/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/kinesis/src/test/java/software/amazon/awssdk/services/kinesis/SubscribeToShardUnmarshallingTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.kinesis; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.mockito.stubbing.Answer; import org.reactivestreams.Subscription; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.http.AbortableInputStream; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.http.async.AsyncExecuteRequest; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.kinesis.model.KinesisException; import software.amazon.awssdk.services.kinesis.model.Record; import software.amazon.awssdk.services.kinesis.model.ResourceNotFoundException; import software.amazon.awssdk.services.kinesis.model.SubscribeToShardEvent; import software.amazon.awssdk.services.kinesis.model.SubscribeToShardEventStream; import software.amazon.awssdk.services.kinesis.model.SubscribeToShardRequest; import software.amazon.awssdk.services.kinesis.model.SubscribeToShardResponseHandler; import software.amazon.awssdk.utils.BinaryUtils; import software.amazon.awssdk.utils.ImmutableMap; import software.amazon.awssdk.utils.IoUtils; import software.amazon.eventstream.HeaderValue; import software.amazon.eventstream.Message; /** * Functional tests for the SubscribeToShard API. */ @RunWith(MockitoJUnitRunner.class) public class SubscribeToShardUnmarshallingTest { private static final AwsBasicCredentials CREDENTIALS = AwsBasicCredentials.create("akid", "skid"); private static final String REQUEST_ID = "a79394c5-59ee-4b36-8127-880aaefa91fc"; @Mock private SdkAsyncHttpClient sdkHttpClient; private KinesisAsyncClient client; @Before public void setup() { this.client = KinesisAsyncClient.builder() .credentialsProvider(() -> CREDENTIALS) .region(Region.US_EAST_1) .httpClient(sdkHttpClient) .build(); } @Test public void exceptionWithMessage_UnmarshalledCorrectly() throws Throwable { String errorCode = "ResourceNotFoundException"; AbortableInputStream content = new MessageWriter() .writeInitialResponse(new byte[0]) .writeException("{\"message\": \"foo\"}", errorCode) .toInputStream(); stubResponse(SdkHttpFullResponse.builder() .statusCode(200) .content(content) .putHeader("x-amzn-requestid", REQUEST_ID) .build()); try { subscribeToShard(); fail("Expected ResourceNotFoundException exception"); } catch (ResourceNotFoundException e) { assertThat(e.requestId()).isEqualTo(REQUEST_ID); assertThat(e.statusCode()).isEqualTo(500); assertThat(e.awsErrorDetails().errorCode()).isEqualTo(errorCode); assertThat(e.awsErrorDetails().errorMessage()).isEqualTo("foo"); assertThat(e.awsErrorDetails().serviceName()).isEqualTo("kinesis"); } } @Test public void errorWithMessage_UnmarshalledCorrectly() throws Throwable { String errorCode = "InternalError"; String message = "error message"; AbortableInputStream content = new MessageWriter() .writeInitialResponse(new byte[0]) .writeError(errorCode, message) .toInputStream(); stubResponse(SdkHttpFullResponse.builder() .statusCode(200) .content(content) .putHeader("x-amzn-requestid", REQUEST_ID) .build()); try { subscribeToShard(); fail("Expected ResourceNotFoundException exception"); } catch (KinesisException e) { assertThat(e.requestId()).isEqualTo(REQUEST_ID); assertThat(e.statusCode()).isEqualTo(500); assertThat(e.awsErrorDetails().errorCode()).isEqualTo(errorCode); assertThat(e.awsErrorDetails().errorMessage()).isEqualTo(message); assertThat(e.awsErrorDetails().serviceName()).isEqualTo("kinesis"); } } @Test public void eventWithRecords_UnmarshalledCorrectly() throws Throwable { String data = BinaryUtils.toBase64("foobar".getBytes(StandardCharsets.UTF_8)); AbortableInputStream content = new MessageWriter() .writeInitialResponse(new byte[0]) .writeEvent("SubscribeToShardEvent", String.format("{\"ContinuationSequenceNumber\": \"1234\"," + "\"MillisBehindLatest\": 0," + "\"Records\": [{\"Data\": \"%s\"}]" + "}", data)) .toInputStream(); SubscribeToShardEvent event = SubscribeToShardEvent.builder() .continuationSequenceNumber("1234") .millisBehindLatest(0L) .records(Record.builder() .data(SdkBytes.fromUtf8String("foobar")) .build()) .build(); stubResponse(SdkHttpFullResponse.builder() .statusCode(200) .content(content) .build()); List<SubscribeToShardEventStream> events = subscribeToShard(); assertThat(events).containsOnly(event); } @Test public void unknownEventType_UnmarshalledCorrectly() throws Throwable { AbortableInputStream content = new MessageWriter() .writeInitialResponse(new byte[0]) .writeEvent("ExampleUnknownEventType", "{\"Foo\": \"Bar\"}") .toInputStream(); stubResponse(SdkHttpFullResponse.builder() .statusCode(200) .content(content) .build()); AtomicInteger unknownEvents = new AtomicInteger(0); AtomicInteger knownEvents = new AtomicInteger(0); client.subscribeToShard(SubscribeToShardRequest.builder().build(), SubscribeToShardResponseHandler.builder().subscriber(new SubscribeToShardResponseHandler.Visitor() { @Override public void visitDefault(SubscribeToShardEventStream event) { unknownEvents.incrementAndGet(); } @Override public void visit(SubscribeToShardEvent event) { knownEvents.incrementAndGet(); } }).build()) .get(); assertThat(unknownEvents.get()).isEqualTo(1); assertThat(knownEvents.get()).isEqualTo(0); } private List<SubscribeToShardEventStream> subscribeToShard() throws Throwable { try { List<SubscribeToShardEventStream> events = new ArrayList<>(); client.subscribeToShard(SubscribeToShardRequest.builder().build(), SubscribeToShardResponseHandler.builder() .subscriber(events::add) .build()) .get(10, TimeUnit.SECONDS); return events; } catch (ExecutionException e) { throw e.getCause(); } } private void stubResponse(SdkHttpFullResponse response) { when(sdkHttpClient.execute(any(AsyncExecuteRequest.class))).thenAnswer((Answer<CompletableFuture<Void>>) invocationOnMock -> { CompletableFuture<Void> cf = new CompletableFuture<>(); AsyncExecuteRequest req = invocationOnMock.getArgument(0, AsyncExecuteRequest.class); SdkAsyncHttpResponseHandler value = req.responseHandler(); value.onHeaders(response); value.onStream(subscriber -> subscriber.onSubscribe(new Subscription() { @Override public void request(long l) { try { response.content().ifPresent(c -> { byte[] bytes = invokeSafely(() -> IoUtils.toByteArray(c)); subscriber.onNext(ByteBuffer.wrap(bytes)); }); subscriber.onComplete(); cf.complete(null); } catch (Throwable e) { subscriber.onError(e); value.onError(e); cf.completeExceptionally(e); } } @Override public void cancel() { } })); return cf; }); } public static class MessageWriter { private final ByteArrayOutputStream baos = new ByteArrayOutputStream(); public MessageWriter writeInitialResponse(byte[] payload) { new Message(ImmutableMap.of(":message-type", HeaderValue.fromString("event"), ":event-type", HeaderValue.fromString("initial-response")), payload).encode(baos); return this; } public MessageWriter writeException(String payload, String modeledExceptionName) { new Message(ImmutableMap.of(":message-type", HeaderValue.fromString("exception"), ":exception-type", HeaderValue.fromString(modeledExceptionName)), payload.getBytes(StandardCharsets.UTF_8)).encode(baos); return this; } public MessageWriter writeError(String errorCode, String errorMessage) { new Message(ImmutableMap.of(":message-type", HeaderValue.fromString("error"), ":error-code", HeaderValue.fromString(errorCode), ":error-message", HeaderValue.fromString(errorMessage)), new byte[0]).encode(baos); return this; } public MessageWriter writeEvent(String eventType, String payload) { new Message(ImmutableMap.of(":message-type", HeaderValue.fromString("event"), ":event-type", HeaderValue.fromString(eventType)), payload.getBytes(StandardCharsets.UTF_8)).encode(baos); return this; } public AbortableInputStream toInputStream() { return AbortableInputStream.create(new ByteArrayInputStream(baos.toByteArray())); } } }
4,356
0
Create_ds/aws-sdk-java-v2/services/kinesis/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/kinesis/src/test/java/software/amazon/awssdk/services/kinesis/DateTimeUnmarshallingTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.kinesis; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.core.SdkSystemSetting.CBOR_ENABLED; import com.github.tomakehurst.wiremock.junit.WireMockRule; import java.net.URI; import java.time.Instant; import java.util.List; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.kinesis.model.Record; @RunWith(MockitoJUnitRunner.class) public class DateTimeUnmarshallingTest { private KinesisClient client; @Rule public WireMockRule wireMock = new WireMockRule(0); @Before public void setup() { System.setProperty(CBOR_ENABLED.property(), "false"); client = KinesisClient.builder() .endpointOverride(URI.create("http://localhost:" + wireMock.port())) .credentialsProvider(() -> AwsBasicCredentials.create("test", "test")) .region(Region.US_EAST_1) .build(); } @Test public void cborDisabled_dateUnmarshalling_shouldSucceed() { String content = content(); int length = content.getBytes().length; Instant instant = Instant.ofEpochMilli(1548118964772L); stubFor(post(anyUrl()) .willReturn(aResponse().withStatus(200) .withHeader("Content-Length", String.valueOf(length)) .withBody(content))); List<Record> records = client.getRecords(b -> b.shardIterator("test")).records(); assertThat(records).isNotEmpty(); assertThat(records.get(0).approximateArrivalTimestamp()).isEqualTo(instant); } private String content() { return "{\n" + " \"MillisBehindLatest\": 0,\n" + " \"NextShardIterator\": \"test\",\n" + " \"Records\": [{\n" + " \"ApproximateArrivalTimestamp\": 1.548118964772E9,\n" + " \"Data\": \"U2VlIE5vIEV2aWw=\",\n" + " \"PartitionKey\": \"foobar\",\n" + " \"SequenceNumber\": \"12345678\"\n" + " }]\n" + "}"; } }
4,357
0
Create_ds/aws-sdk-java-v2/services/kinesis/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/kinesis/src/it/java/software/amazon/awssdk/services/kinesis/KinesisResponseMetadataIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.kinesis; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import software.amazon.awssdk.services.kinesis.model.DescribeLimitsResponse; import software.amazon.awssdk.services.kinesis.model.KinesisResponse; public class KinesisResponseMetadataIntegrationTest extends AbstractTestCase { @Test public void sync_shouldContainResponseMetadata() { DescribeLimitsResponse response = client.describeLimits(); verifyResponseMetadata(response); } @Test public void async_shouldContainResponseMetadata() { DescribeLimitsResponse response = asyncClient.describeLimits().join(); verifyResponseMetadata(response); } private void verifyResponseMetadata(KinesisResponse response) { assertThat(response.responseMetadata().requestId()).isNotEqualTo("UNKNOWN"); assertThat(response.responseMetadata().extendedRequestId()).isNotEqualTo("UNKNOWN"); } }
4,358
0
Create_ds/aws-sdk-java-v2/services/kinesis/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/kinesis/src/it/java/software/amazon/awssdk/services/kinesis/SubscribeToShardIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.kinesis; import static org.assertj.core.api.Assertions.assertThat; import io.reactivex.Flowable; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.UUID; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Consumer; import java.util.stream.Collectors; import org.apache.commons.lang3.RandomUtils; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.async.SdkPublisher; import software.amazon.awssdk.http.SdkHttpResponse; import software.amazon.awssdk.http.nio.netty.Http2Configuration; import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient; import software.amazon.awssdk.services.kinesis.model.ConsumerStatus; import software.amazon.awssdk.services.kinesis.model.PutRecordRequest; import software.amazon.awssdk.services.kinesis.model.Record; import software.amazon.awssdk.services.kinesis.model.ShardIteratorType; import software.amazon.awssdk.services.kinesis.model.StreamStatus; import software.amazon.awssdk.services.kinesis.model.SubscribeToShardEvent; import software.amazon.awssdk.services.kinesis.model.SubscribeToShardEventStream; import software.amazon.awssdk.services.kinesis.model.SubscribeToShardResponse; import software.amazon.awssdk.services.kinesis.model.SubscribeToShardResponseHandler; import software.amazon.awssdk.testutils.Waiter; public class SubscribeToShardIntegrationTest extends AbstractTestCase { public static final int WAIT_TIME_FOR_SUBSCRIPTION_COMPLETION = 300; private String streamName; private static final String CONSUMER_NAME = "subscribe-to-shard-consumer"; private static String consumerArn; private static String shardId; @Before public void setup() throws InterruptedException { streamName = "subscribe-to-shard-integ-test-" + System.currentTimeMillis(); asyncClient.createStream(r -> r.streamName(streamName) .shardCount(1)).join(); waitForStreamToBeActive(); String streamARN = asyncClient.describeStream(r -> r.streamName(streamName)).join() .streamDescription() .streamARN(); this.shardId = asyncClient.listShards(r -> r.streamName(streamName)) .join() .shards().get(0).shardId(); this.consumerArn = asyncClient.registerStreamConsumer(r -> r.streamARN(streamARN) .consumerName(CONSUMER_NAME)).join() .consumer() .consumerARN(); waitForConsumerToBeActive(); } @After public void tearDown() { asyncClient.deleteStream(r -> r.streamName(streamName) .enforceConsumerDeletion(true)).join(); } @Test public void subscribeToShard_smallWindow_doesNotTimeOutReads() { // We want sufficiently large records (relative to the initial window // size we're choosing) so the client has to send multiple // WINDOW_UPDATEs to receive them for (int i = 0; i < 16; ++i) { putRecord(64 * 1024); } KinesisAsyncClient smallWindowAsyncClient = KinesisAsyncClient.builder() .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .httpClientBuilder(NettyNioAsyncHttpClient.builder() .http2Configuration(Http2Configuration.builder() .initialWindowSize(16384) .build())) .build(); try { smallWindowAsyncClient.subscribeToShard(r -> r.consumerARN(consumerArn) .shardId(shardId) .startingPosition(s -> s.type(ShardIteratorType.TRIM_HORIZON)), SubscribeToShardResponseHandler.builder() .onEventStream(es -> Flowable.fromPublisher(es).forEach(e -> {})) .onResponse(this::verifyHttpMetadata) .build()) .join(); } finally { smallWindowAsyncClient.close(); } } @Test public void subscribeToShard_ReceivesAllData() { List<SdkBytes> producedData = new ArrayList<>(); ScheduledExecutorService producer = Executors.newScheduledThreadPool(1); // Delay it a bit to allow us to subscribe first producer.scheduleAtFixedRate(() -> putRecord().ifPresent(producedData::add), 10, 1, TimeUnit.SECONDS); List<SdkBytes> receivedData = new ArrayList<>(); // Add every event's data to the receivedData list Consumer<SubscribeToShardEvent> eventConsumer = s -> receivedData.addAll( s.records().stream() .map(Record::data) .collect(Collectors.toList())); asyncClient.subscribeToShard(r -> r.consumerARN(consumerArn) .shardId(shardId) .startingPosition(s -> s.type(ShardIteratorType.LATEST)), SubscribeToShardResponseHandler.builder() .onEventStream(p -> p.filter(SubscribeToShardEvent.class) .subscribe(eventConsumer)) .onResponse(this::verifyHttpMetadata) .build()) .join(); producer.shutdown(); // Make sure we all the data we received was data we published, we may have published more // if the producer isn't shutdown immediately after we finish subscribing. assertThat(producedData).containsSequence(receivedData); } @Test public void limitedSubscription_callCompleteMethodOfSubs_whenLimitsReached() { AtomicBoolean onCompleteSubsMethodsCalled = new AtomicBoolean(false); AtomicBoolean completeMethodOfHandlerCalled = new AtomicBoolean(false); AtomicBoolean errorOccurred = new AtomicBoolean(false); List<SubscribeToShardEventStream> events = new ArrayList<>(); asyncClient.subscribeToShard(r -> r.consumerARN(consumerArn) .shardId(shardId) .startingPosition(s -> s.type(ShardIteratorType.LATEST)), new SubscribeToShardResponseHandler() { @Override public void responseReceived(SubscribeToShardResponse response) { verifyHttpMetadata(response); } @Override public void onEventStream(SdkPublisher<SubscribeToShardEventStream> publisher) { publisher.limit(3).subscribe(new Subscriber<SubscribeToShardEventStream>() { private Subscription subscription; @Override public void onSubscribe(Subscription subscription) { this.subscription = subscription; subscription.request(10); } @Override public void onNext(SubscribeToShardEventStream subscribeToShardEventStream) { events.add(subscribeToShardEventStream); } @Override public void onError(Throwable throwable) { errorOccurred.set(true); } @Override public void onComplete() { onCompleteSubsMethodsCalled.set(true); } }); } @Override public void exceptionOccurred(Throwable throwable) { errorOccurred.set(true); } @Override public void complete() { completeMethodOfHandlerCalled.set(true); } }).join(); try { Thread.sleep(WAIT_TIME_FOR_SUBSCRIPTION_COMPLETION); } catch (InterruptedException e) { e.printStackTrace(); } assertThat(onCompleteSubsMethodsCalled).isTrue(); assertThat(completeMethodOfHandlerCalled).isFalse(); assertThat(errorOccurred).isFalse(); assertThat(events.size()).isEqualTo(3); } @Test public void cancelledSubscription_doesNotCallCompleteMethodOfHandler() { AtomicBoolean onCompleteSubsMethodsCalled = new AtomicBoolean(false); AtomicBoolean completeMethodOfHandlerCalled = new AtomicBoolean(false); AtomicBoolean errorOccurred = new AtomicBoolean(false); List<SubscribeToShardEventStream> events = new ArrayList<>(); asyncClient.subscribeToShard(r -> r.consumerARN(consumerArn) .shardId(shardId) .startingPosition(s -> s.type(ShardIteratorType.LATEST)), new SubscribeToShardResponseHandler() { @Override public void responseReceived(SubscribeToShardResponse response) { verifyHttpMetadata(response); } @Override public void onEventStream(SdkPublisher<SubscribeToShardEventStream> publisher) { publisher.limit(3).subscribe(new Subscriber<SubscribeToShardEventStream>() { private Subscription subscription; @Override public void onSubscribe(Subscription subscription) { this.subscription = subscription; subscription.request(10); } @Override public void onNext(SubscribeToShardEventStream subscribeToShardEventStream) { events.add(subscribeToShardEventStream); //Cancel on first event. subscription.cancel(); } @Override public void onError(Throwable throwable) { errorOccurred.set(true); } @Override public void onComplete() { onCompleteSubsMethodsCalled.set(true); } }); } @Override public void exceptionOccurred(Throwable throwable) { errorOccurred.set(true); } @Override public void complete() { completeMethodOfHandlerCalled.set(true); } }).join(); try { Thread.sleep(WAIT_TIME_FOR_SUBSCRIPTION_COMPLETION); } catch (InterruptedException e) { e.printStackTrace(); } assertThat(completeMethodOfHandlerCalled).isFalse(); assertThat(onCompleteSubsMethodsCalled).isFalse(); assertThat(errorOccurred).isFalse(); assertThat(events.size()).isEqualTo(1); } private static void waitForConsumerToBeActive() { Waiter.run(() -> asyncClient.describeStreamConsumer(r -> r.consumerARN(consumerArn)).join()) .until(b -> b.consumerDescription().consumerStatus().equals(ConsumerStatus.ACTIVE)) .orFailAfter(Duration.ofMinutes(5)); } private void waitForStreamToBeActive() { Waiter.run(() -> asyncClient.describeStream(r -> r.streamName(streamName)).join()) .until(b -> b.streamDescription().streamStatus().equals(StreamStatus.ACTIVE)) .orFailAfter(Duration.ofMinutes(5)); } /** * Puts a random record to the stream. * * @return Record data that was put. */ private Optional<SdkBytes> putRecord() { return putRecord(50); } /** * Puts a random record to the stream. * * @param len The number of bytes to generate for the record. * @return Record data that was put. */ private Optional<SdkBytes> putRecord(int len) { try { SdkBytes data = SdkBytes.fromByteArray(RandomUtils.nextBytes(len)); asyncClient.putRecord(PutRecordRequest.builder() .streamName(streamName) .data(data) .partitionKey(UUID.randomUUID().toString()) .build()) .join(); return Optional.of(data); } catch (Exception e) { e.printStackTrace(); return Optional.empty(); } } private void verifyHttpMetadata(SubscribeToShardResponse response) { SdkHttpResponse sdkHttpResponse = response.sdkHttpResponse(); assertThat(sdkHttpResponse).isNotNull(); assertThat(sdkHttpResponse.isSuccessful()).isTrue(); assertThat(sdkHttpResponse.headers()).isNotEmpty(); assertThat(response.responseMetadata()).isNotNull(); assertThat(response.responseMetadata().extendedRequestId()).isNotEqualTo("UNKNOWN"); assertThat(response.responseMetadata().requestId()).isNotEqualTo("UNKNOWN"); } }
4,359
0
Create_ds/aws-sdk-java-v2/services/kinesis/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/kinesis/src/it/java/software/amazon/awssdk/services/kinesis/AbstractTestCase.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.kinesis; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.URI; import java.util.Properties; import org.junit.BeforeClass; import software.amazon.awssdk.awscore.util.AwsHostNameUtils; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.testutils.service.AwsTestBase; public class AbstractTestCase extends AwsTestBase { protected static KinesisClient client; protected static KinesisAsyncClient asyncClient; @BeforeClass public static void init() throws IOException { setUpCredentials(); KinesisClientBuilder builder = KinesisClient.builder().credentialsProvider(CREDENTIALS_PROVIDER_CHAIN); setEndpoint(builder); client = builder.build(); asyncClient = KinesisAsyncClient.builder().credentialsProvider(CREDENTIALS_PROVIDER_CHAIN).build(); } private static void setEndpoint(KinesisClientBuilder builder) throws IOException { File endpointOverrides = new File( new File(System.getProperty("user.home")), ".aws/awsEndpointOverrides.properties" ); if (endpointOverrides.exists()) { Properties properties = new Properties(); properties.load(new FileInputStream(endpointOverrides)); String endpoint = properties.getProperty("kinesis.endpoint"); if (endpoint != null) { Region region = AwsHostNameUtils.parseSigningRegion(endpoint, "kinesis") .orElseThrow(() -> new IllegalArgumentException("Unknown region for endpoint. " + endpoint)); builder.region(region) .endpointOverride(URI.create(endpoint)); } } } }
4,360
0
Create_ds/aws-sdk-java-v2/services/kinesis/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/kinesis/src/it/java/software/amazon/awssdk/services/kinesis/KinesisIntegrationTests.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.kinesis; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import java.math.BigInteger; import java.time.Duration; import java.time.Instant; import java.util.List; import org.hamcrest.Matchers; import org.junit.Assert; import org.junit.Test; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.exception.SdkServiceException; import software.amazon.awssdk.services.kinesis.model.CreateStreamRequest; import software.amazon.awssdk.services.kinesis.model.DeleteStreamRequest; import software.amazon.awssdk.services.kinesis.model.DescribeStreamRequest; import software.amazon.awssdk.services.kinesis.model.DescribeStreamResponse; import software.amazon.awssdk.services.kinesis.model.GetRecordsRequest; import software.amazon.awssdk.services.kinesis.model.GetRecordsResponse; import software.amazon.awssdk.services.kinesis.model.GetShardIteratorRequest; import software.amazon.awssdk.services.kinesis.model.GetShardIteratorResponse; import software.amazon.awssdk.services.kinesis.model.HashKeyRange; import software.amazon.awssdk.services.kinesis.model.InvalidArgumentException; import software.amazon.awssdk.services.kinesis.model.PutRecordRequest; import software.amazon.awssdk.services.kinesis.model.PutRecordResponse; import software.amazon.awssdk.services.kinesis.model.Record; import software.amazon.awssdk.services.kinesis.model.ResourceNotFoundException; import software.amazon.awssdk.services.kinesis.model.SequenceNumberRange; import software.amazon.awssdk.services.kinesis.model.Shard; import software.amazon.awssdk.services.kinesis.model.ShardIteratorType; import software.amazon.awssdk.services.kinesis.model.StreamDescription; import software.amazon.awssdk.services.kinesis.model.StreamStatus; public class KinesisIntegrationTests extends AbstractTestCase { @Test public void testDescribeBogusStream() { try { client.describeStream(DescribeStreamRequest.builder().streamName("bogus-stream-name").build()); Assert.fail("Expected ResourceNotFoundException"); } catch (ResourceNotFoundException exception) { // Ignored or expected. } } @Test public void testDeleteBogusStream() { try { client.deleteStream(DeleteStreamRequest.builder().streamName("bogus-stream-name").build()); Assert.fail("Expected ResourceNotFoundException"); } catch (ResourceNotFoundException exception) { // Ignored or expected. } } @Test public void testGetIteratorForBogusStream() { try { client.getShardIterator(GetShardIteratorRequest.builder() .streamName("bogus-stream-name") .shardId("bogus-shard-id") .shardIteratorType(ShardIteratorType.LATEST) .build()); Assert.fail("Expected ResourceNotFoundException"); } catch (ResourceNotFoundException exception) { // Ignored or expected. } } @Test public void testGetFromNullIterator() { try { client.getRecords(GetRecordsRequest.builder().build()); Assert.fail("Expected InvalidArgumentException"); } catch (SdkServiceException exception) { // Ignored or expected. } } @Test public void testGetFromBogusIterator() { try { client.getRecords(GetRecordsRequest.builder().shardIterator("bogusmonkeys").build()); Assert.fail("Expected InvalidArgumentException"); } catch (InvalidArgumentException exception) { // Ignored or expected. } } @Test public void testCreatePutGetDelete() throws Exception { String streamName = "java-test-stream-" + System.currentTimeMillis(); boolean created = false; try { // Create a stream with one shard. client.createStream(CreateStreamRequest.builder().streamName(streamName).shardCount(1).build()); created = true; // Wait for it to become ACTIVE. List<Shard> shards = waitForStream(streamName); Assert.assertEquals(1, shards.size()); Shard shard = shards.get(0); putRecord(streamName, "See No Evil"); putRecord(streamName, "Hear No Evil"); testGets(streamName, shard); } finally { if (created) { client.deleteStream(DeleteStreamRequest.builder().streamName(streamName).build()); } } } private void testGets(final String streamName, final Shard shard) throws InterruptedException { // Wait for the shard to be in an active state // Get an iterator for the first shard. GetShardIteratorResponse iteratorResult = client.getShardIterator( GetShardIteratorRequest.builder() .streamName(streamName) .shardId(shard.shardId()) .shardIteratorType(ShardIteratorType.AT_SEQUENCE_NUMBER) .startingSequenceNumber(shard.sequenceNumberRange().startingSequenceNumber()) .build()); Assert.assertNotNull(iteratorResult); String iterator = iteratorResult.shardIterator(); Assert.assertNotNull(iterator); GetRecordsResponse result = getOneRecord(iterator); validateRecord(result.records().get(0), "See No Evil"); result = getOneRecord(result.nextShardIterator()); validateRecord(result.records().get(0), "Hear No Evil"); result = client.getRecords(GetRecordsRequest.builder() .shardIterator(result.nextShardIterator()) .build()); assertTrue(result.records().isEmpty()); } private GetRecordsResponse getOneRecord(String iterator) { int tries = 0; GetRecordsResponse result; List<Record> records; // Read the first record from the first shard (looping until it's // available). while (true) { tries += 1; if (tries > 100) { Assert.fail("Failed to read any records after 100 seconds"); } result = client.getRecords(GetRecordsRequest.builder() .shardIterator(iterator) .limit(1) .build()); Assert.assertNotNull(result); Assert.assertNotNull(result.records()); Assert.assertNotNull(result.nextShardIterator()); records = result.records(); if (records.size() > 0) { long arrivalTime = records.get(0).approximateArrivalTimestamp().toEpochMilli(); Long delta = Math.abs(Instant.now().minusMillis(arrivalTime).toEpochMilli()); // Assert that the arrival date is within 5 minutes of the current date to make sure it unmarshalled correctly. assertThat(delta, Matchers.lessThan(60 * 5000L)); break; } try { Thread.sleep(1000); } catch (InterruptedException exception) { throw new RuntimeException(exception); } iterator = result.nextShardIterator(); } return result; } private void validateRecord(final Record record, String data) { Assert.assertNotNull(record); Assert.assertNotNull(record.sequenceNumber()); new BigInteger(record.sequenceNumber()); String value = record.data() == null ? null : record.data().asUtf8String(); Assert.assertEquals(data, value); Assert.assertNotNull(record.partitionKey()); // The timestamp should be relatively recent Assert.assertTrue(Duration.between(record.approximateArrivalTimestamp(), Instant.now()).toMinutes() < 5); } private PutRecordResponse putRecord(final String streamName, final String data) { PutRecordResponse result = client.putRecord( PutRecordRequest.builder() .streamName(streamName) .partitionKey("foobar") .data(SdkBytes.fromUtf8String(data)) .build()); Assert.assertNotNull(result); Assert.assertNotNull(result.shardId()); Assert.assertNotNull(result.sequenceNumber()); return result; } private List<Shard> waitForStream(final String streamName) throws InterruptedException { while (true) { DescribeStreamResponse result = client.describeStream(DescribeStreamRequest.builder().streamName(streamName).build()); Assert.assertNotNull(result); StreamDescription description = result.streamDescription(); Assert.assertNotNull(description); Assert.assertEquals(streamName, description.streamName()); Assert.assertNotNull(description.streamARN()); Assert.assertFalse(description.hasMoreShards()); StreamStatus status = description.streamStatus(); Assert.assertNotNull(status); if (status == StreamStatus.ACTIVE) { List<Shard> shards = description.shards(); validateShards(shards); return shards; } if (!(status == StreamStatus.CREATING || status == StreamStatus.UPDATING)) { Assert.fail("Unexpected status '" + status + "'"); } Thread.sleep(1000); } } private void validateShards(final List<Shard> shards) { Assert.assertNotNull(shards); Assert.assertFalse(shards.isEmpty()); for (Shard shard : shards) { Assert.assertNotNull(shard); Assert.assertNotNull(shard.shardId()); validateHashKeyRange(shard.hashKeyRange()); validateSQNRange(shard.sequenceNumberRange()); } } private void validateHashKeyRange(final HashKeyRange range) { Assert.assertNotNull(range); Assert.assertNotNull(range.startingHashKey()); Assert.assertNotNull(range.endingHashKey()); BigInteger start = new BigInteger(range.startingHashKey()); BigInteger end = new BigInteger(range.endingHashKey()); Assert.assertTrue(start.compareTo(end) <= 0); } private void validateSQNRange(final SequenceNumberRange range) { Assert.assertNotNull(range); Assert.assertNotNull(range.startingSequenceNumber()); BigInteger start = new BigInteger(range.startingSequenceNumber()); if (range.endingSequenceNumber() != null) { BigInteger end = new BigInteger(range.endingSequenceNumber()); Assert.assertTrue(start.compareTo(end) <= 0); } } }
4,361
0
Create_ds/aws-sdk-java-v2/services/kinesis/src/main/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/kinesis/src/main/java/software/amazon/awssdk/services/kinesis/KinesisRetryPolicy.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.kinesis; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.awscore.retry.AwsRetryPolicy; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.client.config.SdkClientOption; import software.amazon.awssdk.core.retry.RetryMode; import software.amazon.awssdk.core.retry.RetryPolicy; import software.amazon.awssdk.core.retry.RetryPolicyContext; import software.amazon.awssdk.core.retry.conditions.AndRetryCondition; import software.amazon.awssdk.services.kinesis.model.SubscribeToShardRequest; /** * Default retry policy for the Kinesis Client. Disables retries on subscribe-to-shard. */ @SdkInternalApi final class KinesisRetryPolicy { private KinesisRetryPolicy() { } public static RetryPolicy resolveRetryPolicy(SdkClientConfiguration config) { RetryPolicy configuredRetryPolicy = config.option(SdkClientOption.RETRY_POLICY); if (configuredRetryPolicy != null) { return addRetryConditions(configuredRetryPolicy); } RetryMode retryMode = RetryMode.resolver() .profileFile(config.option(SdkClientOption.PROFILE_FILE_SUPPLIER)) .profileName(config.option(SdkClientOption.PROFILE_NAME)) .defaultRetryMode(config.option(SdkClientOption.DEFAULT_RETRY_MODE)) .resolve(); return AwsRetryPolicy.forRetryMode(retryMode) .toBuilder() .applyMutation(KinesisRetryPolicy::addRetryConditions) .additionalRetryConditionsAllowed(false) .build(); } public static RetryPolicy addRetryConditions(RetryPolicy policy) { if (!policy.additionalRetryConditionsAllowed()) { return policy; } return policy.toBuilder() .applyMutation(KinesisRetryPolicy::addRetryConditions) .build(); } public static void addRetryConditions(RetryPolicy.Builder policy) { policy.retryCondition(AndRetryCondition.create(KinesisRetryPolicy::isNotSubscribeToShard, policy.retryCondition())); } private static boolean isNotSubscribeToShard(RetryPolicyContext context) { return !(context.originalRequest() instanceof SubscribeToShardRequest); } }
4,362
0
Create_ds/aws-sdk-java-v2/services/kinesis/src/main/java/software/amazon/awssdk/services/kinesis
Create_ds/aws-sdk-java-v2/services/kinesis/src/main/java/software/amazon/awssdk/services/kinesis/internal/KinesisHttpConfigurationOptions.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.kinesis.internal; import java.time.Duration; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.SdkHttpConfigurationOption; import software.amazon.awssdk.utils.AttributeMap; /** * Kinesis specific http configurations */ @SdkInternalApi public final class KinesisHttpConfigurationOptions { private static final AttributeMap OPTIONS = AttributeMap .builder() .put(SdkHttpConfigurationOption.READ_TIMEOUT, Duration.ofSeconds(10)) .put(SdkHttpConfigurationOption.WRITE_TIMEOUT, Duration.ofSeconds(10)) .build(); private KinesisHttpConfigurationOptions() { } public static AttributeMap defaultHttpConfig() { return OPTIONS; } }
4,363
0
Create_ds/aws-sdk-java-v2/services/pinpoint/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/pinpoint/src/it/java/software/amazon/awssdk/services/pinpoint/PinpointIntegTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.pinpoint; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.testutils.service.AwsTestBase; import software.amazon.awssdk.utils.builder.SdkBuilder; public class PinpointIntegTest extends AwsTestBase { protected static PinpointAsyncClient pinpointAsyncClient; @BeforeAll public static void setup() { pinpointAsyncClient = PinpointAsyncClient.builder() .region(Region.US_WEST_2) .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .build(); } @Test public void getApps() { assertThat(pinpointAsyncClient.getApps(SdkBuilder::build).join()).isNotNull(); } }
4,364
0
Create_ds/aws-sdk-java-v2/services/ssm/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/ssm/src/it/java/software/amazon/awssdk/services/ssm/IntegrationTestBase.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.ssm; import org.junit.BeforeClass; import software.amazon.awssdk.testutils.service.AwsTestBase; public class IntegrationTestBase extends AwsTestBase { protected static SsmClient ssm; @BeforeClass public static void setup() throws Exception { setUpCredentials(); ssm = SsmClient.builder().credentialsProvider(CREDENTIALS_PROVIDER_CHAIN).build(); } }
4,365
0
Create_ds/aws-sdk-java-v2/services/ssm/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/ssm/src/it/java/software/amazon/awssdk/services/ssm/SSMServiceIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.ssm; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import org.junit.AfterClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.amazon.awssdk.services.ssm.model.CreateDocumentRequest; import software.amazon.awssdk.services.ssm.model.CreateDocumentResponse; import software.amazon.awssdk.services.ssm.model.DeleteDocumentRequest; import software.amazon.awssdk.services.ssm.model.DescribeDocumentRequest; import software.amazon.awssdk.services.ssm.model.DescribeDocumentResponse; import software.amazon.awssdk.services.ssm.model.DocumentDescription; import software.amazon.awssdk.services.ssm.model.GetDocumentRequest; import software.amazon.awssdk.services.ssm.model.GetDocumentResponse; import software.amazon.awssdk.services.ssm.model.ListDocumentsRequest; import software.amazon.awssdk.services.ssm.model.ListDocumentsResponse; import software.amazon.awssdk.utils.IoUtils; public class SSMServiceIntegrationTest extends IntegrationTestBase { private static final Logger log = LoggerFactory.getLogger(SSMServiceIntegrationTest.class); private static final String DOCUMENT_LOCATION = "documentContent.json"; private static final String DOCUMENT_NAME = "my-document-" + System.currentTimeMillis(); @AfterClass public static void tearDown() { try { ssm.deleteDocument(DeleteDocumentRequest.builder().name(DOCUMENT_NAME).build()); } catch (Exception e) { log.error("Failed to delete config document.", e); } } @Test public void testAll() throws Exception { String documentContent = IoUtils.toUtf8String(getClass().getResourceAsStream(DOCUMENT_LOCATION)); testCreateDocument(DOCUMENT_NAME, documentContent); testDescribeDocument(); } private void testDescribeDocument() { DescribeDocumentResponse result = ssm.describeDocument(DescribeDocumentRequest.builder().name(DOCUMENT_NAME).build()); assertNotNull(result.document()); } private void testCreateDocument(String docName, String docContent) { CreateDocumentResponse createResult = ssm .createDocument(CreateDocumentRequest.builder().name(docName).content(docContent).build()); DocumentDescription description = createResult.documentDescription(); assertEquals(docName, description.name()); assertNotNull(description.status()); assertNotNull(description.createdDate()); GetDocumentResponse getResult = ssm.getDocument(GetDocumentRequest.builder().name(docName).build()); assertEquals(DOCUMENT_NAME, getResult.name()); assertEquals(docContent, getResult.content()); ListDocumentsResponse listResult = ssm.listDocuments(ListDocumentsRequest.builder().build()); assertFalse("ListDocuments should at least returns one element", listResult.documentIdentifiers().isEmpty()); } }
4,366
0
Create_ds/aws-sdk-java-v2/services/mediastoredata/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/mediastoredata/src/it/java/software/amazon/awssdk/services/mediastoredata/RequestCompressionStreamingIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.mediastoredata; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import java.io.IOException; import java.nio.charset.StandardCharsets; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.CompressionConfiguration; import software.amazon.awssdk.core.ResponseInputStream; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.async.AsyncRequestBody; 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.core.interceptor.SdkInternalExecutionAttribute; import software.amazon.awssdk.core.internal.compression.Compressor; import software.amazon.awssdk.core.internal.compression.GzipCompressor; import software.amazon.awssdk.core.internal.interceptor.trait.RequestCompression; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.http.apache.ApacheHttpClient; import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient; import software.amazon.awssdk.services.mediastoredata.model.DeleteObjectRequest; import software.amazon.awssdk.services.mediastoredata.model.GetObjectRequest; import software.amazon.awssdk.services.mediastoredata.model.GetObjectResponse; import software.amazon.awssdk.services.mediastoredata.model.PutObjectRequest; /** * Integration test to verify Request Compression functionalities for streaming operations. Do not delete. */ public class RequestCompressionStreamingIntegrationTest extends MediaStoreDataIntegrationTestBase { private static final String UNCOMPRESSED_BODY = "RequestCompressionTest-RequestCompressionTest-RequestCompressionTest-RequestCompressionTest-RequestCompressionTest"; private static String compressedBody; private static MediaStoreDataClient syncClient; private static MediaStoreDataAsyncClient asyncClient; private static PutObjectRequest putObjectRequest; private static DeleteObjectRequest deleteObjectRequest; private static GetObjectRequest getObjectRequest; @BeforeAll public static void setup() { CompressionConfiguration compressionConfiguration = CompressionConfiguration.builder() .minimumCompressionThresholdInBytes(1) .requestCompressionEnabled(true) .build(); RequestCompression requestCompressionTrait = RequestCompression.builder() .encodings("gzip") .isStreaming(true) .build(); syncClient = MediaStoreDataClient.builder() .endpointOverride(uri) .credentialsProvider(credentialsProvider) .httpClient(ApacheHttpClient.builder().build()) .overrideConfiguration(o -> o.addExecutionInterceptor(new CaptureTransferEncodingHeaderInterceptor()) .addExecutionInterceptor(new CaptureContentEncodingHeaderInterceptor()) .putExecutionAttribute(SdkInternalExecutionAttribute.REQUEST_COMPRESSION, requestCompressionTrait) .compressionConfiguration(compressionConfiguration)) .build(); asyncClient = MediaStoreDataAsyncClient.builder() .endpointOverride(uri) .credentialsProvider(credentialsProvider) .httpClient(NettyNioAsyncHttpClient.create()) .overrideConfiguration(o -> o.addExecutionInterceptor(new CaptureTransferEncodingHeaderInterceptor()) .addExecutionInterceptor(new CaptureContentEncodingHeaderInterceptor()) .putExecutionAttribute(SdkInternalExecutionAttribute.REQUEST_COMPRESSION, requestCompressionTrait) .compressionConfiguration(compressionConfiguration)) .build(); putObjectRequest = PutObjectRequest.builder() .contentType("application/octet-stream") .path("/foo") .overrideConfiguration( o -> o.compressionConfiguration( c -> c.requestCompressionEnabled(true))) .build(); deleteObjectRequest = DeleteObjectRequest.builder().path("/foo").build(); getObjectRequest = GetObjectRequest.builder().path("/foo").build(); Compressor compressor = new GzipCompressor(); byte[] compressedBodyBytes = compressor.compress(SdkBytes.fromUtf8String(UNCOMPRESSED_BODY)).asByteArray(); compressedBody = new String(compressedBodyBytes); } @AfterAll public static void tearDown() { syncClient.deleteObject(deleteObjectRequest); } @AfterEach public void cleanUp() { CaptureContentEncodingHeaderInterceptor.reset(); } @Test public void putObject_withSyncStreamingRequestCompression_compressesPayloadAndSendsCorrectly() throws IOException { TestContentProvider provider = new TestContentProvider(UNCOMPRESSED_BODY.getBytes(StandardCharsets.UTF_8)); syncClient.putObject(putObjectRequest, RequestBody.fromContentProvider(provider, "binary/octet-stream")); assertThat(CaptureTransferEncodingHeaderInterceptor.isChunked).isTrue(); assertThat(CaptureContentEncodingHeaderInterceptor.isGzip).isTrue(); ResponseInputStream<GetObjectResponse> response = syncClient.getObject(getObjectRequest); byte[] buffer = new byte[UNCOMPRESSED_BODY.getBytes().length]; response.read(buffer); String retrievedContent = new String(buffer); assertThat(retrievedContent).isEqualTo(UNCOMPRESSED_BODY); } @Test public void putObject_withAsyncStreamingRequestCompression_compressesPayloadAndSendsCorrectly() throws IOException { AsyncRequestBody asyncRequestBody = customAsyncRequestBodyWithoutContentLength(UNCOMPRESSED_BODY.getBytes()); asyncClient.putObject(putObjectRequest, asyncRequestBody).join(); assertThat(CaptureTransferEncodingHeaderInterceptor.isChunked).isTrue(); assertThat(CaptureContentEncodingHeaderInterceptor.isGzip).isTrue(); ResponseInputStream<GetObjectResponse> response = syncClient.getObject(getObjectRequest); byte[] buffer = new byte[UNCOMPRESSED_BODY.getBytes().length]; response.read(buffer); String retrievedContent = new String(buffer); assertThat(retrievedContent).isEqualTo(UNCOMPRESSED_BODY); } private static class CaptureContentEncodingHeaderInterceptor implements ExecutionInterceptor { public static boolean isGzip; public static void reset() { isGzip = false; } @Override public void beforeTransmission(Context.BeforeTransmission context, ExecutionAttributes executionAttributes) { isGzip = context.httpRequest().matchingHeaders("Content-Encoding").contains("gzip"); } } }
4,367
0
Create_ds/aws-sdk-java-v2/services/mediastoredata/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/mediastoredata/src/it/java/software/amazon/awssdk/services/mediastoredata/MediaStoreDataIntegrationTestBase.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.mediastoredata; import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely; import io.reactivex.Flowable; import java.io.ByteArrayInputStream; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.nio.ByteBuffer; import java.time.Duration; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.reactivestreams.Subscriber; import software.amazon.awssdk.core.async.AsyncRequestBody; 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.http.ContentStreamProvider; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.http.apache.ApacheHttpClient; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.mediastore.MediaStoreClient; import software.amazon.awssdk.services.mediastore.model.ContainerInUseException; import software.amazon.awssdk.services.mediastore.model.ContainerStatus; import software.amazon.awssdk.services.mediastore.model.DescribeContainerResponse; import software.amazon.awssdk.services.sts.StsClient; import software.amazon.awssdk.testutils.Waiter; import software.amazon.awssdk.testutils.service.AwsIntegrationTestBase; /** * Base class for MediaStoreData integration tests. Used for Transfer-Encoding and Request Compression testing. */ public class MediaStoreDataIntegrationTestBase extends AwsIntegrationTestBase { protected static IdentityProvider<AwsCredentialsIdentity> credentialsProvider; protected static MediaStoreClient mediaStoreClient; protected static URI uri; @BeforeAll public static void init() { credentialsProvider = getCredentialsProvider(); SdkHttpClient sdkHttpClient = ApacheHttpClient.builder().build(); mediaStoreClient = MediaStoreClient.builder() .credentialsProvider(credentialsProvider) .httpClient(sdkHttpClient) .build(); StsClient stsClient = StsClient.builder() .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .region(Region.US_WEST_2) .httpClient(sdkHttpClient) .build(); String accountId = stsClient.getCallerIdentity().account(); String containerName = "do-not-delete-mediastoredata-tests-container-" + accountId; uri = URI.create(createContainerIfNotExistAndGetEndpoint(containerName)); } @AfterEach public void reset() { CaptureTransferEncodingHeaderInterceptor.reset(); } protected static String createContainerIfNotExistAndGetEndpoint(String containerName) { try { mediaStoreClient.createContainer(r -> r.containerName(containerName)); DescribeContainerResponse response = waitContainerToBeActive(containerName); return response.container().endpoint(); } catch (ContainerInUseException e) { return mediaStoreClient.describeContainer(r -> r.containerName(containerName)).container().endpoint(); } } private static DescribeContainerResponse waitContainerToBeActive(String containerName) { return Waiter.run(() -> mediaStoreClient.describeContainer(r -> r.containerName(containerName))) .until(r -> r.container().status() == ContainerStatus.ACTIVE) .orFailAfter(Duration.ofMinutes(3)); } protected AsyncRequestBody customAsyncRequestBodyWithoutContentLength(byte[] body) { return new AsyncRequestBody() { @Override public Optional<Long> contentLength() { return Optional.empty(); } @Override public void subscribe(Subscriber<? super ByteBuffer> s) { Flowable.fromPublisher(AsyncRequestBody.fromBytes(body)) .subscribe(s); } }; } protected static class CaptureTransferEncodingHeaderInterceptor implements ExecutionInterceptor { public static boolean isChunked; public static void reset() { isChunked = false; } @Override public void beforeTransmission(Context.BeforeTransmission context, ExecutionAttributes executionAttributes) { isChunked = context.httpRequest().matchingHeaders("Transfer-Encoding").contains("chunked"); } } protected static class TestContentProvider implements ContentStreamProvider { private final byte[] content; private final List<CloseTrackingInputStream> createdStreams = new ArrayList<>(); private CloseTrackingInputStream currentStream; protected TestContentProvider(byte[] content) { this.content = content.clone(); } @Override public InputStream newStream() { if (currentStream != null) { invokeSafely(currentStream::close); } currentStream = new CloseTrackingInputStream(new ByteArrayInputStream(content)); createdStreams.add(currentStream); return currentStream; } List<CloseTrackingInputStream> getCreatedStreams() { return Collections.unmodifiableList(createdStreams); } } protected static class CloseTrackingInputStream extends FilterInputStream { private boolean isClosed = false; CloseTrackingInputStream(InputStream in) { super(in); } @Override public void close() throws IOException { super.close(); isClosed = true; } boolean isClosed() { return isClosed; } } }
4,368
0
Create_ds/aws-sdk-java-v2/services/mediastoredata/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/mediastoredata/src/it/java/software/amazon/awssdk/services/mediastoredata/TransferEncodingChunkedIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.mediastoredata; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import java.nio.charset.StandardCharsets; import org.apache.commons.lang3.RandomStringUtils; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.http.apache.ApacheHttpClient; import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient; import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient; import software.amazon.awssdk.services.mediastoredata.model.DeleteObjectRequest; import software.amazon.awssdk.services.mediastoredata.model.PutObjectRequest; /** * Integration test to verify Transfer-Encoding:chunked functionalities for all supported HTTP clients. Do not delete. */ public class TransferEncodingChunkedIntegrationTest extends MediaStoreDataIntegrationTestBase { private static MediaStoreDataClient syncClientWithApache; private static MediaStoreDataClient syncClientWithUrlConnection; private static MediaStoreDataAsyncClient asyncClientWithNetty; private static PutObjectRequest putObjectRequest; private static DeleteObjectRequest deleteObjectRequest; @BeforeAll public static void setup() { syncClientWithApache = MediaStoreDataClient.builder() .endpointOverride(uri) .credentialsProvider(credentialsProvider) .httpClient(ApacheHttpClient.builder().build()) .overrideConfiguration(o -> o.addExecutionInterceptor(new CaptureTransferEncodingHeaderInterceptor())) .build(); syncClientWithUrlConnection= MediaStoreDataClient.builder() .endpointOverride(uri) .credentialsProvider(credentialsProvider) .httpClient(UrlConnectionHttpClient.create()) .overrideConfiguration(o -> o.addExecutionInterceptor(new CaptureTransferEncodingHeaderInterceptor())) .build(); asyncClientWithNetty = MediaStoreDataAsyncClient.builder() .endpointOverride(uri) .credentialsProvider(getCredentialsProvider()) .httpClient(NettyNioAsyncHttpClient.create()) .overrideConfiguration(o -> o.addExecutionInterceptor(new CaptureTransferEncodingHeaderInterceptor())) .build(); putObjectRequest = PutObjectRequest.builder() .contentType("application/octet-stream") .path("/foo") .build(); deleteObjectRequest = DeleteObjectRequest.builder() .path("/foo") .build(); } @AfterAll public static void tearDown() { syncClientWithApache.deleteObject(deleteObjectRequest); } @Test public void apacheClientPutObject_withoutContentLength_sendsSuccessfully() { TestContentProvider provider = new TestContentProvider(RandomStringUtils.random(1000).getBytes(StandardCharsets.UTF_8)); syncClientWithApache.putObject(putObjectRequest, RequestBody.fromContentProvider(provider, "binary/octet-stream")); assertThat(CaptureTransferEncodingHeaderInterceptor.isChunked).isTrue(); } @Test public void urlConnectionClientPutObject_withoutContentLength_sendsSuccessfully() { TestContentProvider provider = new TestContentProvider(RandomStringUtils.random(1000).getBytes(StandardCharsets.UTF_8)); syncClientWithUrlConnection.putObject(putObjectRequest, RequestBody.fromContentProvider(provider, "binary/octet-stream")); assertThat(CaptureTransferEncodingHeaderInterceptor.isChunked).isTrue(); } @Test public void nettyClientPutObject_withoutContentLength_sendsSuccessfully() { asyncClientWithNetty.putObject(putObjectRequest, customAsyncRequestBodyWithoutContentLength("TestBody".getBytes())).join(); assertThat(CaptureTransferEncodingHeaderInterceptor.isChunked).isTrue(); } }
4,369
0
Create_ds/aws-sdk-java-v2/services/servicecatalog/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/servicecatalog/src/it/java/software/amazon/awssdk/services/servicecatalog/ServiceCatalogIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.servicecatalog; import java.util.List; import junit.framework.Assert; import org.junit.Before; import org.junit.Test; import software.amazon.awssdk.services.servicecatalog.model.ListRecordHistoryRequest; import software.amazon.awssdk.services.servicecatalog.model.RecordDetail; import software.amazon.awssdk.testutils.service.AwsIntegrationTestBase; public class ServiceCatalogIntegrationTest extends AwsIntegrationTestBase { private static ServiceCatalogClient serviceCatalog; @Before public void setUp() throws Exception { serviceCatalog = ServiceCatalogClient.builder().credentialsProvider(CREDENTIALS_PROVIDER_CHAIN).build(); } @Test public void testList() { List<RecordDetail> recordDetails = serviceCatalog.listRecordHistory(ListRecordHistoryRequest.builder().build()) .recordDetails(); Assert.assertNotNull(recordDetails); Assert.assertTrue(recordDetails.isEmpty()); } }
4,370
0
Create_ds/aws-sdk-java-v2/services/kms/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/kms/src/it/java/software/amazon/awssdk/services/kms/IntegrationTestBase.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.kms; import org.junit.BeforeClass; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.testutils.service.AwsTestBase; public class IntegrationTestBase extends AwsTestBase { protected static KmsClient kms; @BeforeClass public static void setup() throws Exception { setUpCredentials(); kms = KmsClient.builder().region(Region.US_EAST_1).credentialsProvider(CREDENTIALS_PROVIDER_CHAIN).build(); } }
4,371
0
Create_ds/aws-sdk-java-v2/services/kms/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/kms/src/it/java/software/amazon/awssdk/services/kms/ServiceIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.kms; import junit.framework.Assert; import org.junit.Test; import software.amazon.awssdk.services.kms.model.CreateAliasRequest; import software.amazon.awssdk.services.kms.model.CreateKeyRequest; import software.amazon.awssdk.services.kms.model.CreateKeyResponse; import software.amazon.awssdk.services.kms.model.DescribeKeyRequest; import software.amazon.awssdk.services.kms.model.DescribeKeyResponse; import software.amazon.awssdk.services.kms.model.DisableKeyRequest; import software.amazon.awssdk.services.kms.model.EnableKeyRequest; import software.amazon.awssdk.services.kms.model.GetKeyPolicyRequest; import software.amazon.awssdk.services.kms.model.GetKeyPolicyResponse; import software.amazon.awssdk.services.kms.model.KeyMetadata; import software.amazon.awssdk.services.kms.model.KeyUsageType; import software.amazon.awssdk.services.kms.model.ListKeysRequest; import software.amazon.awssdk.services.kms.model.ListKeysResponse; public class ServiceIntegrationTest extends IntegrationTestBase { private static void checkValid_KeyMetadata(KeyMetadata kmd) { Assert.assertNotNull(kmd); Assert.assertNotNull(kmd.arn()); Assert.assertNotNull(kmd.awsAccountId()); Assert.assertNotNull(kmd.description()); Assert.assertNotNull(kmd.keyId()); Assert.assertNotNull(kmd.keyUsage()); Assert.assertNotNull(kmd.creationDate()); Assert.assertNotNull(kmd.enabled()); } @Test public void testKeyOperations() { // CreateKey CreateKeyResponse createKeyResult = kms.createKey(CreateKeyRequest.builder() .description("My KMS Key") .keyUsage(KeyUsageType.ENCRYPT_DECRYPT) .build()); try { checkValid_KeyMetadata(createKeyResult.keyMetadata()); final String keyId = createKeyResult.keyMetadata().keyId(); // DescribeKey DescribeKeyResponse describeKeyResult = kms.describeKey(DescribeKeyRequest.builder().keyId(keyId).build()); checkValid_KeyMetadata(describeKeyResult.keyMetadata()); // Enable/DisableKey kms.enableKey(EnableKeyRequest.builder().keyId(keyId).build()); kms.disableKey(DisableKeyRequest.builder().keyId(keyId).build()); // ListKeys ListKeysResponse listKeysResult = kms.listKeys(ListKeysRequest.builder().build()); Assert.assertFalse(listKeysResult.keys().isEmpty()); // CreateAlias kms.createAlias(CreateAliasRequest.builder() .aliasName("alias/my_key" + System.currentTimeMillis()) .targetKeyId(keyId) .build()); GetKeyPolicyResponse getKeyPolicyResult = kms.getKeyPolicy(GetKeyPolicyRequest.builder() .keyId(keyId) .policyName("default") .build()); Assert.assertNotNull(getKeyPolicyResult.policy()); } finally { kms.scheduleKeyDeletion(r -> r.keyId(createKeyResult.keyMetadata().keyId()) .pendingWindowInDays(7)); } } }
4,372
0
Create_ds/aws-sdk-java-v2/services/eventbridge/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/eventbridge/src/it/java/software/amazon/awssdk/services/eventbridge/EventBridgeMultiRegionEndpointIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.eventbridge; import static org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely; import java.io.UncheckedIOException; import java.net.InetAddress; import java.net.URI; import java.time.Duration; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; 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.http.SdkHttpRequest; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.eventbridge.model.DescribeEndpointResponse; import software.amazon.awssdk.services.eventbridge.model.EndpointState; import software.amazon.awssdk.services.eventbridge.model.PutEventsResponse; import software.amazon.awssdk.services.eventbridge.model.ReplicationState; import software.amazon.awssdk.services.eventbridge.model.ResourceAlreadyExistsException; import software.amazon.awssdk.services.route53.Route53Client; import software.amazon.awssdk.services.route53.model.CreateHealthCheckResponse; import software.amazon.awssdk.services.route53.model.HealthCheckType; import software.amazon.awssdk.testutils.Waiter; import software.amazon.awssdk.testutils.service.AwsIntegrationTestBase; import software.amazon.awssdk.utils.Logger; class EventBridgeMultiRegionEndpointIntegrationTest extends AwsIntegrationTestBase { private static final Logger log = Logger.loggerFor(EventBridgeMultiRegionEndpointIntegrationTest.class); private static final String RESOURCE_PREFIX = "java-sdk-integ-test-eb-mrep-"; private static final Region PRIMARY_REGION = Region.US_EAST_1; private static final Region FAILOVER_REGION = Region.US_WEST_2; private CapturingExecutionInterceptor interceptor; private Route53Client route53; private EventBridgeClient primaryEventBridge; private EventBridgeClient failoverEventBridge; @BeforeEach public void setup() { interceptor = new CapturingExecutionInterceptor(); route53 = Route53Client.builder() .credentialsProvider(getCredentialsProvider()) .region(Region.AWS_GLOBAL) .build(); primaryEventBridge = createEventBridgeClient(PRIMARY_REGION); failoverEventBridge = createEventBridgeClient(FAILOVER_REGION); } private EventBridgeClient createEventBridgeClient(Region region) { return EventBridgeClient.builder() .region(region) .credentialsProvider(getCredentialsProvider()) .overrideConfiguration(ClientOverrideConfiguration .builder() .addExecutionInterceptor(interceptor) .build()) .build(); } @Test void testPutEventsToMultiRegionEndpoint() { String endpointId = prepareEndpoint(); PutEventsResponse putEventsResponse = putEvents(endpointId); // Assert the endpointId parameter was used to infer the request endpoint assertThat(lastRequest().host()).isEqualTo(endpointId + ".endpoint.events.amazonaws.com"); // Assert the request was signed with SigV4a assertThat(lastRequest().firstMatchingHeader("Authorization").get()).contains("AWS4-ECDSA-P256-SHA256"); assertThat(lastRequest().firstMatchingHeader("X-Amz-Region-Set")).hasValue("*"); // Assert the request succeeded normally if (putEventsResponse.failedEntryCount() != 0) { throw new AssertionError("Failed to put events: " + putEventsResponse); } } /** * Execute all the steps needed to prepare a global endpoint, creating the relevant resources if needed. */ private String prepareEndpoint() { String healthCheckId = getOrCreateHealthCheck(); log.info(() -> "healthCheckId: " + healthCheckId); String primaryEventBusArn = getOrCreateEventBus(primaryEventBridge); log.info(() -> "primaryEventBusArn: " + primaryEventBusArn); String failoverEventBusArn = getOrCreateEventBus(failoverEventBridge); log.info(() -> "failoverEventBusArn: " + failoverEventBusArn); String endpointName = getOrCreateMultiRegionEndpoint(healthCheckId, primaryEventBusArn, failoverEventBusArn); log.info(() -> "endpointName: " + endpointName); String endpointId = getOrAwaitEndpointId(endpointName); log.info(() -> "endpointId: " + endpointId); assertThat(endpointId).isNotBlank(); return endpointId; } /** * Returns the Route 53 healthcheck ID used for testing, creating a healthcheck if needed. * <p> * The healthcheck is created as {@code DISABLED}, meaning it always reports as healthy. * <p> * (A healthcheck is required to create an EventBridge multi-region endpoint.) */ private String getOrCreateHealthCheck() { URI primaryEndpoint = EventBridgeClient.serviceMetadata().endpointFor(PRIMARY_REGION); CreateHealthCheckResponse createHealthCheckResponse = route53.createHealthCheck(r -> r .callerReference(resourceName("monitor")) .healthCheckConfig(hcc -> hcc .type(HealthCheckType.TCP) .port(443) .fullyQualifiedDomainName(primaryEndpoint.toString()) .disabled(true))); return createHealthCheckResponse.healthCheck().id(); } /** * Returns the event bus ARN used for testing, creating an event bus if needed. * <p> * (An event bus is required to create an EventBridge multi-region endpoint.) */ private String getOrCreateEventBus(EventBridgeClient eventBridge) { String eventBusName = resourceName("eventBus"); try { return eventBridge.createEventBus(r -> r.name(eventBusName)) .eventBusArn(); } catch (ResourceAlreadyExistsException ignored) { log.debug(() -> "Event bus " + eventBusName + " already exists"); return eventBridge.describeEventBus(r -> r.name(eventBusName)) .arn(); } } /** * Returns the name of the multi-region endpoint used for testing, creating an endpoint if needed. */ private String getOrCreateMultiRegionEndpoint(String healthCheckId, String primaryEventBusArn, String failoverEventBusArn) { String endpointName = resourceName("endpoint"); try { primaryEventBridge.createEndpoint(r -> r .name(endpointName) .description("Used for SDK Acceptance Testing") .eventBuses(eb -> eb.eventBusArn(primaryEventBusArn), eb -> eb.eventBusArn(failoverEventBusArn)) .routingConfig(rc -> rc .failoverConfig(fc -> fc .primary(p -> p.healthCheck("arn:aws:route53:::healthcheck/" + healthCheckId)) .secondary(s -> s.route(FAILOVER_REGION.id())))) .replicationConfig(rc -> rc.state(ReplicationState.DISABLED))); } catch (ResourceAlreadyExistsException ignored) { log.debug(() -> "Endpoint " + endpointName + " already exists"); } return endpointName; } /** * Returns the endpoint ID associated with the given endpoint name, waiting for the endpoint to finish creating if needed. */ private String getOrAwaitEndpointId(String endpointName) { DescribeEndpointResponse response = Waiter.run(() -> primaryEventBridge.describeEndpoint(r -> r.name(endpointName))) .until(ep -> ep.state() != EndpointState.CREATING) .orFailAfter(Duration.ofMinutes(2)); assertThat(response.state()).isEqualTo(EndpointState.ACTIVE); log.info(() -> "Endpoint ID is active. Waiting until we can resolve the endpoint. This will take a some time if the " + "endpoint was just created."); URI endpointUri = URI.create(response.endpointUrl()); Waiter.run(() -> invokeSafely(() -> InetAddress.getByName(endpointUri.getHost()))) .ignoringException(UncheckedIOException.class) .orFailAfter(Duration.ofMinutes(10)); return response.endpointId(); } /** * Put test events to the given endpoint ID, which is expected to override the request's endpoint and to sign the request with * SigV4a. */ private PutEventsResponse putEvents(String endpointId) { return primaryEventBridge.putEvents(r -> r .endpointId(endpointId) .entries(e -> e .eventBusName(resourceName("eventBus")) .resources("resource1", "resource2") .source("com.mycompany.myapp") .detailType("myDetailType") .detail("{ \"key1\": \"value1\", \"key2\": \"value2\" }"))); } /** * Return a test-friendly name for a given named resource. */ private String resourceName(String suffix) { return RESOURCE_PREFIX + suffix; } /** * Get the last request that was sent with the {@link EventBridgeClient}. */ private SdkHttpRequest lastRequest() { return interceptor.beforeTransmission; } /** * Captures {@link SdkHttpRequest}s and saves them to then assert against. */ public static class CapturingExecutionInterceptor implements ExecutionInterceptor { private SdkHttpRequest beforeTransmission; @Override public void beforeTransmission(Context.BeforeTransmission context, ExecutionAttributes executionAttributes) { this.beforeTransmission = context.httpRequest(); } } }
4,373
0
Create_ds/aws-sdk-java-v2/services/cloudwatch/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/cloudwatch/src/it/java/software/amazon/awssdk/services/cloudwatch/CloudWatchIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.cloudwatch; import static java.util.stream.Collectors.toList; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.isIn; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static software.amazon.awssdk.testutils.service.AwsTestBase.isValidSdkServiceException; import java.io.IOException; import java.time.Duration; import java.time.Instant; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedList; import java.util.List; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.core.CompressionConfiguration; import software.amazon.awssdk.core.SdkGlobalTime; import software.amazon.awssdk.core.exception.SdkServiceException; import software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute; import software.amazon.awssdk.core.internal.interceptor.trait.RequestCompression; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.cloudwatch.model.Datapoint; import software.amazon.awssdk.services.cloudwatch.model.DeleteAlarmsRequest; import software.amazon.awssdk.services.cloudwatch.model.DescribeAlarmsForMetricResponse; import software.amazon.awssdk.services.cloudwatch.model.DescribeAlarmsRequest; import software.amazon.awssdk.services.cloudwatch.model.DescribeAlarmsResponse; import software.amazon.awssdk.services.cloudwatch.model.Dimension; import software.amazon.awssdk.services.cloudwatch.model.GetMetricStatisticsRequest; import software.amazon.awssdk.services.cloudwatch.model.GetMetricStatisticsResponse; import software.amazon.awssdk.services.cloudwatch.model.HistoryItemType; import software.amazon.awssdk.services.cloudwatch.model.ListMetricsRequest; import software.amazon.awssdk.services.cloudwatch.model.ListMetricsResponse; import software.amazon.awssdk.services.cloudwatch.model.Metric; import software.amazon.awssdk.services.cloudwatch.model.MetricAlarm; import software.amazon.awssdk.services.cloudwatch.model.MetricDatum; import software.amazon.awssdk.services.cloudwatch.model.PutMetricAlarmRequest; import software.amazon.awssdk.services.cloudwatch.model.PutMetricDataRequest; import software.amazon.awssdk.services.cloudwatch.model.StateValue; import software.amazon.awssdk.testutils.Waiter; import software.amazon.awssdk.testutils.service.AwsIntegrationTestBase; /** * Integration tests for the AWS CloudWatch service. */ public class CloudWatchIntegrationTest extends AwsIntegrationTestBase { private static final int ONE_WEEK_IN_MILLISECONDS = 1000 * 60 * 60 * 24 * 7; private static final int ONE_HOUR_IN_MILLISECONDS = 1000 * 60 * 60; /** The CloudWatch client for all tests to use. */ private static CloudWatchClient cloudwatch; /** * Loads the AWS account info for the integration tests and creates a * CloudWatch client for tests to use. */ @BeforeClass public static void setUp() throws IOException { cloudwatch = CloudWatchClient.builder() .credentialsProvider(getCredentialsProvider()) .region(Region.US_WEST_2) .build(); } /** * Cleans up any existing alarms before and after running the test suite */ @AfterClass public static void cleanupAlarms() { if (cloudwatch != null) { DescribeAlarmsResponse describeResult = cloudwatch.describeAlarms(DescribeAlarmsRequest.builder().build()); Collection<String> toDelete = new LinkedList<>(); for (MetricAlarm alarm : describeResult.metricAlarms()) { if (alarm.metricName().startsWith(CloudWatchIntegrationTest.class.getName())) { toDelete.add(alarm.alarmName()); } } if (!toDelete.isEmpty()) { DeleteAlarmsRequest delete = DeleteAlarmsRequest.builder().alarmNames(toDelete).build(); cloudwatch.deleteAlarms(delete); } } } /** * Tests putting metrics and then getting them back. */ @Test public void put_get_metricdata_list_metric_returns_success() throws InterruptedException { String measureName = this.getClass().getName() + System.currentTimeMillis(); MetricDatum datum = MetricDatum.builder().dimensions( Dimension.builder().name("InstanceType").value("m1.small").build()) .metricName(measureName).timestamp(Instant.now()) .unit("Count").value(42.0).build(); cloudwatch.putMetricData(PutMetricDataRequest.builder() .namespace("AWS.EC2").metricData(datum).build()); GetMetricStatisticsResponse result = Waiter.run(() -> cloudwatch.getMetricStatistics(r -> r.startTime(Instant.now().minus(Duration.ofDays(7))) .namespace("AWS.EC2") .period(60 * 60) .dimensions(Dimension.builder().name("InstanceType") .value("m1.small").build()) .metricName(measureName) .statisticsWithStrings("Average", "Maximum", "Minimum", "Sum") .endTime(Instant.now()))) .until(r -> r.datapoints().size() == 1) .orFailAfter(Duration.ofMinutes(2)); assertNotNull(result.label()); assertEquals(measureName, result.label()); assertEquals(1, result.datapoints().size()); for (Datapoint datapoint : result.datapoints()) { assertEquals(datum.value(), datapoint.average()); assertEquals(datum.value(), datapoint.maximum()); assertEquals(datum.value(), datapoint.minimum()); assertEquals(datum.value(), datapoint.sum()); assertNotNull(datapoint.timestamp()); assertEquals(datum.unit(), datapoint.unit()); } ListMetricsResponse listResult = cloudwatch.listMetrics(ListMetricsRequest.builder().build()); boolean seenDimensions = false; assertTrue(listResult.metrics().size() > 0); for (Metric metric : listResult.metrics()) { assertNotNull(metric.metricName()); assertNotNull(metric.namespace()); for (Dimension dimension : metric.dimensions()) { seenDimensions = true; assertNotNull(dimension.name()); assertNotNull(dimension.value()); } } assertTrue(seenDimensions); } /** * Tests putting metrics with request compression and then getting them back. * TODO: We can remove this test once CloudWatch adds "RequestCompression" trait to PutMetricData */ @Test public void put_get_metricdata_list_metric_withRequestCompression_returns_success() { RequestCompression requestCompressionTrait = RequestCompression.builder() .encodings("gzip") .isStreaming(false) .build(); CompressionConfiguration compressionConfiguration = CompressionConfiguration.builder() // uncompressed payload is 404 bytes .minimumCompressionThresholdInBytes(100) .build(); CloudWatchClient requestCompressionClient = CloudWatchClient.builder() .credentialsProvider(getCredentialsProvider()) .region(Region.US_WEST_2) .overrideConfiguration(c -> c.putExecutionAttribute(SdkInternalExecutionAttribute.REQUEST_COMPRESSION, requestCompressionTrait)) .build(); String measureName = this.getClass().getName() + System.currentTimeMillis(); MetricDatum datum = MetricDatum.builder().dimensions( Dimension.builder().name("InstanceType").value("m1.small").build()) .metricName(measureName).timestamp(Instant.now()) .unit("Count").value(42.0).build(); requestCompressionClient.putMetricData(PutMetricDataRequest.builder() .namespace("AWS.EC2") .metricData(datum) .overrideConfiguration(c -> c.compressionConfiguration(compressionConfiguration)) .build()); GetMetricStatisticsResponse result = Waiter.run(() -> requestCompressionClient .getMetricStatistics(r -> r.startTime(Instant.now().minus(Duration.ofDays(7))) .namespace("AWS.EC2") .period(60 * 60) .dimensions(Dimension.builder().name("InstanceType") .value("m1.small").build()) .metricName(measureName) .statisticsWithStrings("Average", "Maximum", "Minimum", "Sum") .endTime(Instant.now()))) .until(r -> r.datapoints().size() == 1) .orFailAfter(Duration.ofMinutes(2)); assertNotNull(result.label()); assertEquals(measureName, result.label()); assertEquals(1, result.datapoints().size()); for (Datapoint datapoint : result.datapoints()) { assertEquals(datum.value(), datapoint.average()); assertEquals(datum.value(), datapoint.maximum()); assertEquals(datum.value(), datapoint.minimum()); assertEquals(datum.value(), datapoint.sum()); assertNotNull(datapoint.timestamp()); assertEquals(datum.unit(), datapoint.unit()); } ListMetricsResponse listResult = requestCompressionClient.listMetrics(ListMetricsRequest.builder().build()); boolean seenDimensions = false; assertTrue(listResult.metrics().size() > 0); for (Metric metric : listResult.metrics()) { assertNotNull(metric.metricName()); assertNotNull(metric.namespace()); for (Dimension dimension : metric.dimensions()) { seenDimensions = true; assertNotNull(dimension.name()); assertNotNull(dimension.value()); } } assertTrue(seenDimensions); } /** * Tests setting the state for an alarm and reading its history. */ @Test public void describe_alarms_returns_values_set() { String metricName = this.getClass().getName() + System.currentTimeMillis(); List<PutMetricAlarmRequest> rqs = createTwoNewAlarms(metricName); rqs.forEach(rq -> cloudwatch.setAlarmState(r -> r.alarmName(rq.alarmName()).stateValue("ALARM").stateReason("manual"))); DescribeAlarmsForMetricResponse describeResult = describeAlarmsForMetric(rqs); assertThat(describeResult.metricAlarms(), hasSize(2)); //check the state is correct describeResult.metricAlarms().forEach(alarm -> { assertThat(alarm.alarmName(), isIn(rqs.stream().map(PutMetricAlarmRequest::alarmName).collect(toList()))); assertThat(alarm.stateValue(), equalTo(StateValue.ALARM)); assertThat(alarm.stateReason(), equalTo("manual")); }); //check the state history has been recorded rqs.stream().map(alarm -> cloudwatch.describeAlarmHistory(r -> r.alarmName(alarm.alarmName()) .historyItemType(HistoryItemType.STATE_UPDATE))) .forEach(history -> assertThat(history.alarmHistoryItems(), hasSize(greaterThan(0)))); } /** * Tests disabling and enabling alarm actions */ @Test public void disable_enable_alarms_returns_success() { String metricName = this.getClass().getName() + System.currentTimeMillis(); List<PutMetricAlarmRequest> rqs = createTwoNewAlarms(metricName); List<String> alarmNames = rqs.stream().map(PutMetricAlarmRequest::alarmName).collect(toList()); PutMetricAlarmRequest rq1 = rqs.get(0); PutMetricAlarmRequest rq2 = rqs.get(1); /* * Disable */ cloudwatch.disableAlarmActions(r -> r.alarmNames(alarmNames)); DescribeAlarmsForMetricResponse describeDisabledResult = describeAlarmsForMetric(rqs); assertThat(describeDisabledResult.metricAlarms(), hasSize(2)); describeDisabledResult.metricAlarms().forEach(alarm -> { assertThat(alarm.alarmName(), isIn(alarmNames)); assertThat(alarm.actionsEnabled(), is(false)); }); /* * Enable */ cloudwatch.enableAlarmActions(r -> r.alarmNames(alarmNames)); DescribeAlarmsForMetricResponse describeEnabledResult = describeAlarmsForMetric(rqs); assertThat(describeEnabledResult.metricAlarms(), hasSize(2)); describeEnabledResult.metricAlarms().forEach(alarm -> { assertThat(alarm.alarmName(), isIn(alarmNames)); assertThat(alarm.actionsEnabled(), is(true)); }); } private DescribeAlarmsForMetricResponse describeAlarmsForMetric(List<PutMetricAlarmRequest> rqs) { return cloudwatch.describeAlarmsForMetric(r -> r.dimensions(rqs.get(0).dimensions()) .metricName(rqs.get(0).metricName()) .namespace(rqs.get(0).namespace())); } /** * Creates two alarms on the metric name given and returns the two requests * as an array. */ private List<PutMetricAlarmRequest> createTwoNewAlarms(String metricName) { List<PutMetricAlarmRequest> rqs = new ArrayList<>(); /* * Create & put two metric alarms */ rqs.add(PutMetricAlarmRequest.builder().actionsEnabled(true) .alarmDescription("Some alarm description").alarmName( "An Alarm Name" + metricName).comparisonOperator( "GreaterThanThreshold").dimensions( Dimension.builder().name("InstanceType").value( "m1.small").build()).evaluationPeriods(1) .metricName(metricName).namespace("AWS/EC2") .period(60).statistic("Average").threshold(1.0) .unit("Count") .build()); rqs.add(PutMetricAlarmRequest.builder().actionsEnabled(true) .alarmDescription("Some alarm description 2") .alarmName("An Alarm Name 2" + metricName) .comparisonOperator("GreaterThanThreshold").dimensions( Dimension.builder().name("InstanceType").value( "m1.small").build()).evaluationPeriods(1) .metricName(metricName).namespace("AWS/EC2") .period(60).statistic("Average").threshold(2.0) .unit("Count") .build()); rqs.forEach(cloudwatch::putMetricAlarm); return rqs; } /** * Tests that an error response from CloudWatch is correctly unmarshalled * into an SdkServiceException object. */ @Test public void testExceptionHandling() throws Exception { try { cloudwatch.getMetricStatistics(GetMetricStatisticsRequest.builder() .namespace("fake-namespace").build()); fail("Expected an SdkServiceException, but wasn't thrown"); } catch (SdkServiceException e) { assertThat(e, isValidSdkServiceException()); } } /** * In the following test, we purposely setting the time offset to trigger a clock skew error. * The time offset must be fixed and then we validate the global value for time offset has been * update. */ @Test public void testClockSkew() { SdkGlobalTime.setGlobalTimeOffset(3600); CloudWatchClient cloudwatch = CloudWatchClient.builder() .credentialsProvider(StaticCredentialsProvider.create(getCredentials())) .build(); cloudwatch.listMetrics(ListMetricsRequest.builder().build()); assertTrue(SdkGlobalTime.getGlobalTimeOffset() < 3600); // subsequent changes to the global time offset won't affect existing client SdkGlobalTime.setGlobalTimeOffset(3600); cloudwatch.listMetrics(ListMetricsRequest.builder().build()); assertTrue(SdkGlobalTime.getGlobalTimeOffset() == 3600); } }
4,374
0
Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/PayloadSigningDisabledTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.auth.signer.S3SignerExecutionAttribute; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.http.HttpExecuteResponse; import software.amazon.awssdk.http.SdkHttpResponse; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.testutils.service.http.MockAsyncHttpClient; import software.amazon.awssdk.testutils.service.http.MockSyncHttpClient; /** * Ensure that payload signing is disabled for S3 operations. */ public class PayloadSigningDisabledTest { private static final AwsCredentialsProvider CREDENTIALS = () -> AwsBasicCredentials.create("akid", "skid"); private static final ClientOverrideConfiguration ENABLE_PAYLOAD_SIGNING_CONFIG = ClientOverrideConfiguration.builder() .putExecutionAttribute(S3SignerExecutionAttribute.ENABLE_PAYLOAD_SIGNING, true) .build(); @Test public void syncPayloadSigningIsDisabled() { try (MockSyncHttpClient httpClient = new MockSyncHttpClient(); S3Client s3 = S3Client.builder() .region(Region.US_WEST_2) .credentialsProvider(CREDENTIALS) .httpClient(httpClient) .build()) { httpClient.stubNextResponse(HttpExecuteResponse.builder() .response(SdkHttpResponse.builder().statusCode(200).build()) .build()); s3.createBucket(r -> r.bucket("foo")); assertThat(httpClient.getLastRequest().firstMatchingHeader("x-amz-content-sha256")) .hasValue("UNSIGNED-PAYLOAD"); } } @Test public void asyncPayloadSigningIsDisabled() { try (MockAsyncHttpClient httpClient = new MockAsyncHttpClient(); S3AsyncClient s3 = S3AsyncClient.builder() .region(Region.US_WEST_2) .credentialsProvider(CREDENTIALS) .httpClient(httpClient) .build()) { httpClient.stubNextResponse(HttpExecuteResponse.builder() .response(SdkHttpResponse.builder().statusCode(200).build()) .build()); s3.createBucket(r -> r.bucket("foo")).join(); assertThat(httpClient.getLastRequest().firstMatchingHeader("x-amz-content-sha256")) .hasValue("UNSIGNED-PAYLOAD"); } } @Test public void syncPayloadSigningCanBeEnabled() { try (MockSyncHttpClient httpClient = new MockSyncHttpClient(); S3Client s3 = S3Client.builder() .region(Region.US_WEST_2) .credentialsProvider(CREDENTIALS) .httpClient(httpClient) .overrideConfiguration(ENABLE_PAYLOAD_SIGNING_CONFIG) .build()) { httpClient.stubNextResponse(HttpExecuteResponse.builder() .response(SdkHttpResponse.builder().statusCode(200).build()) .build()); s3.createBucket(r -> r.bucket("foo")); assertThat(httpClient.getLastRequest().firstMatchingHeader("x-amz-content-sha256")) .hasValue("a40ef303139635de59992f34c1c7da763f89200f2d55b71016f7c156527d63a0"); } } @Test public void asyncPayloadSigningCanBeEnabled() { try (MockAsyncHttpClient httpClient = new MockAsyncHttpClient(); S3AsyncClient s3 = S3AsyncClient.builder() .region(Region.US_WEST_2) .credentialsProvider(CREDENTIALS) .httpClient(httpClient) .overrideConfiguration(ENABLE_PAYLOAD_SIGNING_CONFIG) .build()) { httpClient.stubNextResponse(HttpExecuteResponse.builder() .response(SdkHttpResponse.builder().statusCode(200).build()) .build()); s3.createBucket(r -> r.bucket("foo")).join(); assertThat(httpClient.getLastRequest().firstMatchingHeader("x-amz-content-sha256")) .hasValue("a40ef303139635de59992f34c1c7da763f89200f2d55b71016f7c156527d63a0"); } } }
4,375
0
Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/S3ConfigurationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3; import static org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.profiles.ProfileFileSystemSetting.AWS_CONFIG_FILE; import static software.amazon.awssdk.services.s3.S3SystemSetting.AWS_S3_DISABLE_MULTIREGION_ACCESS_POINTS; import static software.amazon.awssdk.services.s3.S3SystemSetting.AWS_S3_USE_ARN_REGION; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import software.amazon.awssdk.testutils.EnvironmentVariableHelper; public class S3ConfigurationTest { private final EnvironmentVariableHelper helper = new EnvironmentVariableHelper(); @AfterEach public void clearSystemProperty() { System.clearProperty(AWS_S3_USE_ARN_REGION.property()); System.clearProperty(AWS_S3_DISABLE_MULTIREGION_ACCESS_POINTS.property()); System.clearProperty(AWS_CONFIG_FILE.property()); helper.reset(); } @Test public void createConfiguration_minimal() { S3Configuration config = S3Configuration.builder().build(); assertThat(config.accelerateModeEnabled()).isEqualTo(false); assertThat(config.checksumValidationEnabled()).isEqualTo(true); assertThat(config.chunkedEncodingEnabled()).isEqualTo(true); assertThat(config.dualstackEnabled()).isEqualTo(false); assertThat(config.multiRegionEnabled()).isEqualTo(true); assertThat(config.pathStyleAccessEnabled()).isEqualTo(false); assertThat(config.useArnRegionEnabled()).isEqualTo(false); } @Test public void multiRegionEnabled_enabledInConfigOnly_shouldResolveCorrectly() { S3Configuration config = S3Configuration.builder().multiRegionEnabled(true).build(); assertThat(config.multiRegionEnabled()).isEqualTo(true); } @Test public void multiRegionEnabled_disabledInConfigOnly_shouldResolveCorrectly() { S3Configuration config = S3Configuration.builder().multiRegionEnabled(false).build(); assertThat(config.multiRegionEnabled()).isEqualTo(false); } @Test public void multiRegionEnabled_enabledInConfig_shouldResolveToConfigCorrectly() { System.setProperty(AWS_S3_DISABLE_MULTIREGION_ACCESS_POINTS.property(), "true"); String trueProfileConfig = getClass().getResource("internal/settingproviders/ProfileFile_true").getFile(); System.setProperty(AWS_CONFIG_FILE.property(), trueProfileConfig); S3Configuration config = S3Configuration.builder().multiRegionEnabled(true).build(); assertThat(config.multiRegionEnabled()).isEqualTo(true); } @Test public void multiRegionEnabled_disabledInProviders_shouldResolveToFalse() { System.setProperty(AWS_S3_DISABLE_MULTIREGION_ACCESS_POINTS.property(), "true"); String profileConfig = getClass().getResource("internal/settingproviders/ProfileFile_true").getFile(); System.setProperty(AWS_CONFIG_FILE.property(), profileConfig); S3Configuration config = S3Configuration.builder().build(); assertThat(config.multiRegionEnabled()).isEqualTo(false); } @Test public void multiRegionEnabled_notDisabledInProviders_shouldResolveToTrue() { System.setProperty(AWS_S3_DISABLE_MULTIREGION_ACCESS_POINTS.property(), "false"); String profileConfig = getClass().getResource("internal/settingproviders/ProfileFile_false").getFile(); System.setProperty(AWS_CONFIG_FILE.property(), profileConfig); S3Configuration config = S3Configuration.builder().build(); assertThat(config.multiRegionEnabled()).isEqualTo(true); } @Test public void multiRegionEnabled_enabledInCProfile_shouldResolveToConfigCorrectlyOncePerCall() { S3Configuration config = S3Configuration.builder().build(); String trueProfileConfig = getClass().getResource("internal/settingproviders/ProfileFile_true").getFile(); System.setProperty(AWS_CONFIG_FILE.property(), trueProfileConfig); assertThat(config.multiRegionEnabled()).isEqualTo(false); System.clearProperty(AWS_CONFIG_FILE.property()); String falseProfileConfig = getClass().getResource("internal/settingproviders/ProfileFile_false").getFile(); System.setProperty(AWS_CONFIG_FILE.property(), falseProfileConfig); assertThat(config.multiRegionEnabled()).isEqualTo(true); } @Test public void useArnRegionEnabled_enabledInCProfile_shouldResolveToConfigCorrectlyOncePerCall() { S3Configuration config = S3Configuration.builder().build(); String trueProfileConfig = getClass().getResource("internal/settingproviders/ProfileFile_true").getFile(); System.setProperty(AWS_CONFIG_FILE.property(), trueProfileConfig); assertThat(config.useArnRegionEnabled()).isEqualTo(true); System.clearProperty(AWS_CONFIG_FILE.property()); String falseProfileConfig = getClass().getResource("internal/settingproviders/ProfileFile_false").getFile(); System.setProperty(AWS_CONFIG_FILE.property(), falseProfileConfig); assertThat(config.useArnRegionEnabled()).isEqualTo(false); } }
4,376
0
Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/EndpointOverrideTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static org.assertj.core.api.Assertions.assertThat; import com.github.tomakehurst.wiremock.junit.WireMockRule; import java.io.IOException; import java.net.URI; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.core.async.AsyncResponseTransformer; import software.amazon.awssdk.regions.Region; public class EndpointOverrideTest { @Rule public WireMockRule mockServer = new WireMockRule(0); private S3Client s3Client; private S3AsyncClient s3AsyncClient; @Before public void setup() { s3Client = S3Client.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid"))) .region(Region.US_WEST_2) .endpointOverride(URI.create(getEndpoint())) .serviceConfiguration(c -> c.pathStyleAccessEnabled(true)) .build(); s3AsyncClient = S3AsyncClient.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid"))) .region(Region.US_WEST_2) .endpointOverride(URI.create(getEndpoint())) .serviceConfiguration(c -> c.pathStyleAccessEnabled(true)) .build(); } private String getEndpoint() { return "http://localhost:" + mockServer.port(); } //https://github.com/aws/aws-sdk-java-v2/issues/437 @Test public void getObjectAsync_shouldNotThrowNPE() throws IOException { stubFor(get(anyUrl()) .willReturn(aResponse() .withStatus(200) .withBody("<?xml version=\"1.0\"?><GetObjectResult xmlns=\"http://s3" + ".amazonaws.com/doc/2006-03-01\"></GetObjectResult>"))); assertThat(s3AsyncClient.getObject(b -> b.bucket("test").key("test").build(), AsyncResponseTransformer.toBytes()).join()).isNotNull(); } @Test public void getObject_shouldNotThrowNPE() { stubFor(get(anyUrl()) .willReturn(aResponse() .withStatus(200).withBody("<?xml version=\"1.0\"?><GetObjectResult xmlns=\"http://s3" + ".amazonaws.com/doc/2006-03-01\"></GetObjectResult>"))); assertThat(s3Client.listObjectVersions(b -> b.bucket("test"))).isNotNull(); } }
4,377
0
Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/AclTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.anyRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.put; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.verify; import static org.assertj.core.api.Assertions.assertThat; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.github.tomakehurst.wiremock.matching.ContainsPattern; import java.net.URI; import java.util.ArrayList; import java.util.List; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.model.GetBucketAclResponse; import software.amazon.awssdk.services.s3.model.Grant; import software.amazon.awssdk.services.s3.model.Permission; import software.amazon.awssdk.services.s3.model.PutBucketAclRequest; import software.amazon.awssdk.services.s3.model.Type; public class AclTest { private static final String OWNER_ID = "123456"; private static final String OWNER_DISPLAY_NAME = "foobar"; private static final String READ_ONLY_USER_ID = "7891011"; private static final String READ_ONLY_USER_DISPLAY_NAME = "helloworld"; private static final String MOCK_ACL_RESPONSE = String.format("<?xml version=\"1.0\" encoding=\"UTF-8\"?><AccessControlPolicy xmlns=\"http://s3.amazonaws" + ".com/doc/2006-03-01/\"><AccessControlList><Grant><Grantee xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"CanonicalUser\"><DisplayName>%s</DisplayName><ID>%s</ID></Grantee><Permission>FULL_CONTROL</Permission></Grant><Grant><Grantee xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"CanonicalUser\"><DisplayName>%s</DisplayName><ID>%s</ID></Grantee><Permission>READ</Permission></Grant></AccessControlList><Owner><DisplayName>%s</DisplayName><ID>%s</ID></Owner></AccessControlPolicy>", OWNER_DISPLAY_NAME,OWNER_ID, READ_ONLY_USER_DISPLAY_NAME, READ_ONLY_USER_ID, OWNER_DISPLAY_NAME, OWNER_ID); @Rule public WireMockRule mockServer = new WireMockRule(0); private S3Client s3Client; @Before public void setup() { URI endpoint = URI.create("http://localhost:" + mockServer.port()); s3Client = S3Client.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid"))) .region(Region.US_WEST_2) .endpointOverride(endpoint) .serviceConfiguration(c -> c.pathStyleAccessEnabled(true)) .build(); } @Test public void putBucketAcl_marshalling() { stubFor(put(anyUrl()) .willReturn(aResponse().withStatus(200))); s3Client.putBucketAcl(request()); verify(anyRequestedFor(anyUrl()).withRequestBody(new ContainsPattern(MOCK_ACL_RESPONSE))); } @Test public void getBucketAcl_shouldUnmarshallCorrectly() { stubFor(get(anyUrl()) .willReturn(aResponse().withBody(MOCK_ACL_RESPONSE).withStatus(200))); GetBucketAclResponse bucketAcl = s3Client.getBucketAcl(b -> b.bucket("test")); assertThat(bucketAcl.owner()).isEqualTo(request().accessControlPolicy().owner()); assertThat(bucketAcl.grants()).isEqualTo(request().accessControlPolicy().grants()); } private PutBucketAclRequest request() { List<Grant> grants = new ArrayList<>(); grants.add(Grant.builder() .grantee(g -> g.type(Type.CANONICAL_USER).id(OWNER_ID).displayName(OWNER_DISPLAY_NAME)) .permission(Permission.FULL_CONTROL) .build()); grants.add(Grant.builder() .grantee(g -> g.type(Type.CANONICAL_USER).id(READ_ONLY_USER_ID).displayName(READ_ONLY_USER_DISPLAY_NAME)) .permission(Permission.READ) .build()); return PutBucketAclRequest.builder() .bucket("bucket") .accessControlPolicy(b -> b.grants(grants) .owner(o -> o.id(OWNER_ID).displayName(OWNER_DISPLAY_NAME)) .build()).build(); } }
4,378
0
Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/MultipartUploadTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.any; import static com.github.tomakehurst.wiremock.client.WireMock.anyRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl; import static com.github.tomakehurst.wiremock.client.WireMock.containing; import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; import static com.github.tomakehurst.wiremock.client.WireMock.verify; import static software.amazon.awssdk.http.Header.CONTENT_TYPE; import com.github.tomakehurst.wiremock.junit.WireMockRule; import java.net.URI; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.regions.Region; public class MultipartUploadTest { @Rule public WireMockRule mockServer = new WireMockRule(0); private S3Client s3Client; private S3AsyncClient s3AsyncClient; @Before public void setup() { s3Client = S3Client.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid"))) .region(Region.US_WEST_2).endpointOverride(URI.create("http://localhost:" + mockServer.port())) .serviceConfiguration(S3Configuration.builder().checksumValidationEnabled(false).pathStyleAccessEnabled(true).build()) .build(); s3AsyncClient = S3AsyncClient.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid"))) .region(Region.US_WEST_2).endpointOverride(URI.create("http://localhost:" + mockServer.port())) .serviceConfiguration(S3Configuration.builder().checksumValidationEnabled(false).pathStyleAccessEnabled(true).build()) .build(); } @Test public void syncCreateMultipartUpload_shouldHaveUploadsQueryParam() { stubFor(any(urlMatching(".*")) .willReturn(aResponse().withStatus(200).withBody("<xml></xml>"))); s3Client.createMultipartUpload(b -> b.key("key").bucket("bucket")); verify(anyRequestedFor(anyUrl()).withQueryParam("uploads", containing(""))); verify(anyRequestedFor(anyUrl()).withHeader(CONTENT_TYPE, equalTo("binary/octet-stream"))); } @Test public void asyncCreateMultipartUpload_shouldHaveUploadsQueryParam() { stubFor(any(urlMatching(".*")) .willReturn(aResponse().withStatus(200).withBody("<xml></xml>"))); s3AsyncClient.createMultipartUpload(b -> b.key("key").bucket("bucket")).join(); verify(anyRequestedFor(anyUrl()).withQueryParam("uploads", containing(""))); verify(anyRequestedFor(anyUrl()).withHeader(CONTENT_TYPE, equalTo("binary/octet-stream"))); } @Test public void createMultipartUpload_overrideContentType() { String overrideContentType = "application/html"; stubFor(any(urlMatching(".*")) .willReturn(aResponse().withStatus(200).withBody("<xml></xml>"))); s3Client.createMultipartUpload(b -> b.key("key") .bucket("bucket") .overrideConfiguration(c -> c.putHeader(CONTENT_TYPE, overrideContentType))); verify(anyRequestedFor(anyUrl()).withQueryParam("uploads", containing(""))); verify(anyRequestedFor(anyUrl()).withHeader(CONTENT_TYPE, equalTo(overrideContentType))); } }
4,379
0
Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/S3MockUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3; import java.io.UnsupportedEncodingException; import software.amazon.awssdk.http.AbortableInputStream; import software.amazon.awssdk.http.HttpExecuteResponse; import software.amazon.awssdk.http.SdkHttpResponse; import software.amazon.awssdk.utils.StringInputStream; /** * Various utility methods for mocking the S3Client at the HTTP layer. */ public final class S3MockUtils { private S3MockUtils() { } /** * @return A mocked result for the ListObjects operation. */ public static HttpExecuteResponse mockListObjectsResponse() throws UnsupportedEncodingException { return HttpExecuteResponse.builder().response(SdkHttpResponse.builder().statusCode(200).build()).responseBody( AbortableInputStream.create(new StringInputStream( "<ListBucketResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">\n" + " <Name>example-bucket</Name>\n" + " <Prefix>photos/2006/</Prefix>\n" + " <Marker></Marker>\n" + " <MaxKeys>1000</MaxKeys>\n" + " <Delimiter>/</Delimiter>\n" + " <IsTruncated>false</IsTruncated>\n" + "\n" + " <CommonPrefixes>\n" + " <Prefix>photos/2006/February/</Prefix>\n" + " </CommonPrefixes>\n" + " <CommonPrefixes>\n" + " <Prefix>photos/2006/January/</Prefix>\n" + " </CommonPrefixes>\n" + "</ListBucketResult>"))) .build(); } /** * @return A mocked result for the ListBuckets operation. */ public static HttpExecuteResponse mockListBucketsResponse() throws UnsupportedEncodingException { return HttpExecuteResponse.builder().response(SdkHttpResponse.builder().statusCode(200).build()).responseBody( AbortableInputStream.create(new StringInputStream( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<ListAllMyBucketsResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01\">\n" + " <Owner>\n" + " <ID>bcaf1ffd86f461ca5fb16fd081034f</ID>\n" + " <DisplayName>webfile</DisplayName>\n" + " </Owner>\n" + " <Buckets>\n" + " <Bucket>\n" + " <Name>quotes</Name>\n" + " <CreationDate>2006-02-03T16:45:09.000Z</CreationDate>\n" + " </Bucket>\n" + " </Buckets>\n" + "</ListAllMyBucketsResult>"))) .build(); } }
4,380
0
Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/InvalidRegionTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.time.Duration; import org.junit.jupiter.api.Test; import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.model.HeadBucketRequest; import software.amazon.awssdk.services.s3.presigner.S3Presigner; public class InvalidRegionTest { @Test public void invalidS3UtilitiesRegionAtClientGivesHelpfulMessage() { S3Utilities utilities = S3Utilities.builder().region(Region.of("US_EAST_1")).build(); assertThatThrownBy(() -> utilities.getUrl(r -> r.bucket("foo").key("bar"))) .isInstanceOf(SdkClientException.class) .hasMessageContaining("US_EAST_1") .hasMessageContaining("region") .hasMessageContaining("us-east-1"); } @Test public void invalidS3UtilitiesRegionAtRequestGivesHelpfulMessage() { S3Utilities utilities = S3Utilities.builder().region(Region.of("us-east-1")).build(); assertThatThrownBy(() -> utilities.getUrl(r -> r.bucket("foo").key("bar").region(Region.of("US_WEST_2")))) .isInstanceOf(SdkClientException.class) .hasMessageContaining("US_WEST_2") .hasMessageContaining("region") .hasMessageContaining("us-west-2"); } @Test public void nonExistentRegionGivesHelpfulMessage() { S3Client s3Client = S3Client.builder() .region(Region.of("does-not-exist")) .credentialsProvider(AnonymousCredentialsProvider.create()) .build(); assertThatThrownBy(() -> s3Client.headBucket(HeadBucketRequest.builder().bucket("myBucket").build())) .isInstanceOf(SdkClientException.class) .hasMessageContaining("UnknownHostException"); } @Test public void invalidS3ArnRegionAtRequestGivesHelpfulMessage() { S3Client client = S3Client.builder() .region(Region.of("us-east-1")) .credentialsProvider(AnonymousCredentialsProvider.create()) .serviceConfiguration(c -> c.useArnRegionEnabled(true)) .build(); assertThatThrownBy(() -> client.getObject(r -> r.bucket("arn:aws:s3:US_EAST_1:123456789012:accesspoint/test") .key("test"))) .isInstanceOf(SdkClientException.class) .hasMessageContaining("Invalid region in ARN: `US_EAST_1` (invalid DNS name)"); } @Test public void invalidS3PresignerRegionAtClientGivesHelpfulMessage() { assertThatThrownBy(() -> S3Presigner.builder().region(Region.of("US_EAST_1")).build()) .isInstanceOf(SdkClientException.class) .hasMessageContaining("Configured region (US_EAST_1) and tags ([]) resulted in an invalid URI"); } @Test public void invalidS3PresignerArnRegionAtRequestGivesHelpfulMessage() { S3Presigner presigner = S3Presigner.builder() .region(Region.of("us-east-1")) .credentialsProvider(AnonymousCredentialsProvider.create()) .serviceConfiguration(S3Configuration.builder().useArnRegionEnabled(true).build()) .build(); String arn = "arn:aws:s3:US_EAST_1:123456789012:accesspoint/test"; assertThatThrownBy(() -> presigner.presignGetObject(r -> r.getObjectRequest(g -> g.bucket(arn).key("test")) .signatureDuration(Duration.ofMinutes(15)))) .isInstanceOf(SdkClientException.class) .hasMessageContaining("Invalid region in ARN: `US_EAST_1` (invalid DNS name)"); } }
4,381
0
Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/S3SignerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.any; import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl; import static com.github.tomakehurst.wiremock.client.WireMock.containing; import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; import static com.github.tomakehurst.wiremock.client.WireMock.matching; import static com.github.tomakehurst.wiremock.client.WireMock.notMatching; import static com.github.tomakehurst.wiremock.client.WireMock.putRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; import static com.github.tomakehurst.wiremock.client.WireMock.verify; import static software.amazon.awssdk.http.Header.CONTENT_LENGTH; import static software.amazon.awssdk.http.Header.CONTENT_TYPE; import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder; import com.github.tomakehurst.wiremock.junit.WireMockRule; import java.net.URI; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.auth.signer.AwsS3V4Signer; import software.amazon.awssdk.auth.signer.S3SignerExecutionAttribute; import software.amazon.awssdk.core.checksums.Algorithm; import software.amazon.awssdk.core.checksums.ChecksumSpecs; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.core.client.config.SdkAdvancedClientOption; import software.amazon.awssdk.core.internal.util.Mimetype; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.model.ChecksumAlgorithm; import software.amazon.awssdk.services.s3.model.PutObjectRequest; @RunWith(MockitoJUnitRunner.class) public class S3SignerTest { public static final ChecksumSpecs CRC32_TRAILER = ChecksumSpecs.builder().algorithm(Algorithm.CRC32) .isRequestStreaming(true) .headerName("x-amz-checksum-crc32").build(); public static final ChecksumSpecs SHA256_HEADER = ChecksumSpecs.builder().algorithm(Algorithm.SHA256) .isRequestStreaming(false) .headerName("x-amz-checksum-sha256").build(); @Rule public WireMockRule mockServer = new WireMockRule(0); private String getEndpoint() { return "http://localhost:" + mockServer.port(); } private S3Client getS3Client(boolean chunkedEncoding, boolean payloadSigning, URI endpoint) { return S3Client.builder() .overrideConfiguration(ClientOverrideConfiguration.builder() .putExecutionAttribute(S3SignerExecutionAttribute.ENABLE_CHUNKED_ENCODING, chunkedEncoding) .putExecutionAttribute(S3SignerExecutionAttribute.ENABLE_PAYLOAD_SIGNING, payloadSigning) .putAdvancedOption(SdkAdvancedClientOption.SIGNER, AwsS3V4Signer.create()).build()) .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid"))) .region(Region.US_EAST_2).endpointOverride(endpoint) .serviceConfiguration(c -> c.checksumValidationEnabled(false).pathStyleAccessEnabled(true)) .build(); } @Test public void payloadSigningWithChecksum() { S3Client s3Client = getS3Client(true, true, URI.create(getEndpoint())); stubFor(any(urlMatching(".*")) .willReturn(response())); s3Client.putObject(PutObjectRequest.builder() .checksumAlgorithm(ChecksumAlgorithm.CRC32) .bucket("test").key("test").build(), RequestBody.fromBytes("abc".getBytes())); verify(putRequestedFor(anyUrl()).withHeader(CONTENT_TYPE, equalTo(Mimetype.MIMETYPE_OCTET_STREAM))); verify(putRequestedFor(anyUrl()).withHeader(CONTENT_LENGTH, equalTo("296"))); verify(putRequestedFor(anyUrl()).withHeader("x-amz-trailer", equalTo(CRC32_TRAILER.headerName()))); verify(putRequestedFor(anyUrl()).withHeader("x-amz-decoded-content-length", equalTo("3"))); verify(putRequestedFor(anyUrl()).withHeader("x-amz-content-sha256", equalTo("STREAMING-AWS4-HMAC-SHA256-PAYLOAD-TRAILER" ))); verify(putRequestedFor(anyUrl()).withHeader("Content-Encoding", equalTo("aws-chunked"))); verify(putRequestedFor(anyUrl()).withRequestBody(containing("x-amz-checksum-crc32:NSRBwg==")) .withRequestBody(containing("x-amz-trailer-signature:")) .withRequestBody(containing("0;"))); } @Test public void payloadSigningWithChecksumWithContentEncodingSuppliedByUser() { S3Client s3Client = getS3Client(true, true, URI.create(getEndpoint())); stubFor(any(urlMatching(".*")) .willReturn(response())); s3Client.putObject(PutObjectRequest.builder() .checksumAlgorithm(ChecksumAlgorithm.CRC32).contentEncoding("deflate") .bucket("test").key("test").build(), RequestBody.fromBytes("abc".getBytes())); verify(putRequestedFor(anyUrl()).withHeader(CONTENT_TYPE, equalTo(Mimetype.MIMETYPE_OCTET_STREAM))); verify(putRequestedFor(anyUrl()).withHeader(CONTENT_LENGTH, equalTo("296"))); verify(putRequestedFor(anyUrl()).withHeader("x-amz-trailer", equalTo(CRC32_TRAILER.headerName()))); verify(putRequestedFor(anyUrl()).withHeader("x-amz-decoded-content-length", equalTo("3"))); verify(putRequestedFor(anyUrl()).withHeader("x-amz-content-sha256", equalTo("STREAMING-AWS4-HMAC-SHA256-PAYLOAD-TRAILER" ))); verify(putRequestedFor(anyUrl()).withHeader("Content-Encoding", equalTo("aws-chunked"))); verify(putRequestedFor(anyUrl()).withHeader("Content-Encoding", equalTo("deflate"))); verify(putRequestedFor(anyUrl()).withRequestBody(containing("x-amz-checksum-crc32:NSRBwg==")) .withRequestBody(containing("x-amz-trailer-signature:")) .withRequestBody(containing("0;"))); } @Test public void payloadSigningWithNoChecksum() { S3Client s3Client = getS3Client(true, true, URI.create(getEndpoint())); stubFor(any(urlMatching(".*")) .willReturn(response())); s3Client.putObject(PutObjectRequest.builder() .bucket("test").key("test").build(), RequestBody.fromBytes("abc".getBytes())); verify(putRequestedFor(anyUrl()).withHeader(CONTENT_TYPE, equalTo(Mimetype.MIMETYPE_OCTET_STREAM))); verify(putRequestedFor(anyUrl()).withHeader(CONTENT_LENGTH, equalTo("175"))); verify(putRequestedFor(anyUrl()).withoutHeader("x-amz-trailer")); verify(putRequestedFor(anyUrl()).withHeader("x-amz-decoded-content-length", equalTo("3"))); verify(putRequestedFor(anyUrl()).withHeader("x-amz-content-sha256", equalTo("STREAMING-AWS4-HMAC-SHA256-PAYLOAD" ))); verify(putRequestedFor(anyUrl()).withoutHeader("Content-Encoding")); verify(putRequestedFor(anyUrl()).withRequestBody(notMatching("x-amz-checksum-crc32:NSRBwg==")) .withRequestBody(notMatching("x-amz-trailer-signature:")) .withRequestBody(notMatching("0;"))); } @Test public void headerBasedSignedPayload() { S3Client s3Client = getS3Client(false, false, URI.create(getEndpoint())); stubFor(any(urlMatching(".*")) .willReturn(response())); s3Client.putObject(PutObjectRequest.builder() .checksumAlgorithm(ChecksumAlgorithm.SHA256) .bucket("test").key("test").build(), RequestBody.fromBytes("abc".getBytes())); verify(putRequestedFor(anyUrl()).withHeader(CONTENT_TYPE, equalTo(Mimetype.MIMETYPE_OCTET_STREAM))); verify(putRequestedFor(anyUrl()).withHeader(CONTENT_LENGTH, equalTo("3"))); verify(putRequestedFor(anyUrl()).withHeader(SHA256_HEADER.headerName(), equalTo("ungWv48Bz+pBQUDeXa4iI7ADYaOWF3qctBD" + "/YfIAFa0="))); verify(putRequestedFor(anyUrl()).withHeader("x-amz-content-sha256", notMatching("STREAMING-AWS4-HMAC-SHA256-PAYLOAD" + "-TRAILER"))); // This keeps changing based on time so matching if a valid string exist as signature. // TODO : mock the clock and make the signature static for given time. verify(putRequestedFor(anyUrl()).withHeader("x-amz-content-sha256", matching("\\w+"))); verify(putRequestedFor(anyUrl()).withoutHeader("x-amz-trailer")); verify(putRequestedFor(anyUrl()).withoutHeader("Content-Encoding")); } private ResponseDefinitionBuilder response() { return aResponse().withStatus(200).withHeader(CONTENT_LENGTH, "0").withBody(""); } }
4,382
0
Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/ExecutionAttributeBackwardsCompatibilityTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3; import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; import java.util.function.Function; import org.junit.jupiter.api.Test; import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.AwsCredentials; import software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute; import software.amazon.awssdk.auth.signer.S3SignerExecutionAttribute; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttribute; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.http.HttpExecuteResponse; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.http.SdkHttpResponse; import software.amazon.awssdk.http.auth.aws.scheme.AwsV4AuthScheme; import software.amazon.awssdk.http.auth.aws.signer.AwsV4FamilyHttpSigner; import software.amazon.awssdk.http.auth.aws.signer.AwsV4HttpSigner; import software.amazon.awssdk.http.auth.spi.scheme.AuthScheme; import software.amazon.awssdk.http.auth.spi.signer.AsyncSignRequest; import software.amazon.awssdk.http.auth.spi.signer.AsyncSignedRequest; import software.amazon.awssdk.http.auth.spi.signer.BaseSignRequest; import software.amazon.awssdk.http.auth.spi.signer.HttpSigner; import software.amazon.awssdk.http.auth.spi.signer.SignRequest; import software.amazon.awssdk.http.auth.spi.signer.SignedRequest; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.identity.spi.IdentityProviders; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.model.ChecksumAlgorithm; import software.amazon.awssdk.testutils.service.http.MockAsyncHttpClient; import software.amazon.awssdk.testutils.service.http.MockSyncHttpClient; /** * Validate that values set to {@link AwsSignerExecutionAttribute}s and {@link S3SignerExecutionAttribute}s from execution * interceptors are visible to {@link HttpSigner}s. */ public class ExecutionAttributeBackwardsCompatibilityTest { private static final AwsCredentials CREDS = AwsBasicCredentials.create("akid", "skid"); @Test public void canSetSignerExecutionAttributes_beforeExecution() { test(attributeModifications -> new ExecutionInterceptor() { @Override public void beforeExecution(Context.BeforeExecution context, ExecutionAttributes executionAttributes) { attributeModifications.accept(executionAttributes); } }, AwsSignerExecutionAttribute.SERVICE_SIGNING_NAME, // Endpoint rules override signing name AwsSignerExecutionAttribute.SIGNING_REGION, // Endpoint rules override signing region AwsSignerExecutionAttribute.AWS_CREDENTIALS, // Legacy auth strategy overrides credentials AwsSignerExecutionAttribute.SIGNER_DOUBLE_URL_ENCODE); // Endpoint rules override double-url-encode } @Test public void canSetSignerExecutionAttributes_modifyRequest() { test(attributeModifications -> new ExecutionInterceptor() { @Override public SdkRequest modifyRequest(Context.ModifyRequest context, ExecutionAttributes executionAttributes) { attributeModifications.accept(executionAttributes); return context.request(); } }, AwsSignerExecutionAttribute.AWS_CREDENTIALS); // Legacy auth strategy overrides credentials } @Test public void canSetSignerExecutionAttributes_beforeMarshalling() { test(attributeModifications -> new ExecutionInterceptor() { @Override public void beforeMarshalling(Context.BeforeMarshalling context, ExecutionAttributes executionAttributes) { attributeModifications.accept(executionAttributes); } }); } @Test public void canSetSignerExecutionAttributes_afterMarshalling() { test(attributeModifications -> new ExecutionInterceptor() { @Override public void afterMarshalling(Context.AfterMarshalling context, ExecutionAttributes executionAttributes) { attributeModifications.accept(executionAttributes); } }); } @Test public void canSetSignerExecutionAttributes_modifyHttpRequest() { test(attributeModifications -> new ExecutionInterceptor() { @Override public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { attributeModifications.accept(executionAttributes); return context.httpRequest(); } }); } private void test(Function<Consumer<ExecutionAttributes>, ExecutionInterceptor> interceptorFactory, ExecutionAttribute<?>... attributesToExcludeFromTest) { Set<ExecutionAttribute<?>> attributesToExclude = new HashSet<>(Arrays.asList(attributesToExcludeFromTest)); ExecutionInterceptor interceptor = interceptorFactory.apply(executionAttributes -> { executionAttributes.putAttribute(AwsSignerExecutionAttribute.SERVICE_SIGNING_NAME, "signing-name"); executionAttributes.putAttribute(AwsSignerExecutionAttribute.SIGNING_REGION, Region.of("signing-region")); executionAttributes.putAttribute(AwsSignerExecutionAttribute.AWS_CREDENTIALS, CREDS); executionAttributes.putAttribute(AwsSignerExecutionAttribute.SIGNER_DOUBLE_URL_ENCODE, true); executionAttributes.putAttribute(AwsSignerExecutionAttribute.SIGNER_NORMALIZE_PATH, true); executionAttributes.putAttribute(S3SignerExecutionAttribute.ENABLE_CHUNKED_ENCODING, true); executionAttributes.putAttribute(S3SignerExecutionAttribute.ENABLE_PAYLOAD_SIGNING, true); }); ClientOverrideConfiguration.Builder configBuilder = ClientOverrideConfiguration.builder() .addExecutionInterceptor(interceptor); try (MockSyncHttpClient httpClient = new MockSyncHttpClient(); MockAsyncHttpClient asyncHttpClient = new MockAsyncHttpClient()) { stub200Responses(httpClient, asyncHttpClient); S3ClientBuilder s3Builder = createS3Builder(configBuilder, httpClient); S3AsyncClientBuilder s3AsyncBuilder = createS3AsyncBuilder(configBuilder, asyncHttpClient); CapturingAuthScheme authScheme1 = new CapturingAuthScheme(); try (S3Client s3 = s3Builder.putAuthScheme(authScheme1) .build()) { callS3(s3); validateSignRequest(attributesToExclude, authScheme1); } CapturingAuthScheme authScheme2 = new CapturingAuthScheme(); try (S3AsyncClient s3 = s3AsyncBuilder.putAuthScheme(authScheme2) .build()) { callS3(s3); validateSignRequest(attributesToExclude, authScheme2); } } } private static void stub200Responses(MockSyncHttpClient httpClient, MockAsyncHttpClient asyncHttpClient) { HttpExecuteResponse response = HttpExecuteResponse.builder() .response(SdkHttpResponse.builder() .statusCode(200) .build()) .build(); httpClient.stubResponses(response); asyncHttpClient.stubResponses(response); } private static S3ClientBuilder createS3Builder(ClientOverrideConfiguration.Builder configBuilder, MockSyncHttpClient httpClient) { return S3Client.builder() .region(Region.US_WEST_2) .credentialsProvider(AnonymousCredentialsProvider.create()) .httpClient(httpClient) .overrideConfiguration(configBuilder.build()); } private static S3AsyncClientBuilder createS3AsyncBuilder(ClientOverrideConfiguration.Builder configBuilder, MockAsyncHttpClient asyncHttpClient) { return S3AsyncClient.builder() .region(Region.US_WEST_2) .credentialsProvider(AnonymousCredentialsProvider.create()) .httpClient(asyncHttpClient) .overrideConfiguration(configBuilder.build()); } private static void callS3(S3Client s3) { s3.putObject(r -> r.bucket("foo") .key("bar") .checksumAlgorithm(ChecksumAlgorithm.CRC32), RequestBody.fromString("text")); } private void callS3(S3AsyncClient s3) { s3.putObject(r -> r.bucket("foo") .key("bar") .checksumAlgorithm(ChecksumAlgorithm.CRC32), AsyncRequestBody.fromString("text")) .join(); } private void validateSignRequest(Set<ExecutionAttribute<?>> attributesToExclude, CapturingAuthScheme authScheme) { if (!attributesToExclude.contains(AwsSignerExecutionAttribute.SERVICE_SIGNING_NAME)) { assertThat(authScheme.signer.signRequest.property(AwsV4FamilyHttpSigner.SERVICE_SIGNING_NAME)) .isEqualTo("signing-name"); } if (!attributesToExclude.contains(AwsSignerExecutionAttribute.SIGNING_REGION)) { assertThat(authScheme.signer.signRequest.property(AwsV4HttpSigner.REGION_NAME)) .isEqualTo("signing-region"); } if (!attributesToExclude.contains(AwsSignerExecutionAttribute.AWS_CREDENTIALS)) { assertThat(authScheme.signer.signRequest.identity()) .isEqualTo(CREDS); } if (!attributesToExclude.contains(AwsSignerExecutionAttribute.SIGNER_DOUBLE_URL_ENCODE)) { assertThat(authScheme.signer.signRequest.property(AwsV4FamilyHttpSigner.DOUBLE_URL_ENCODE)) .isEqualTo(true); } if (!attributesToExclude.contains(AwsSignerExecutionAttribute.SIGNER_NORMALIZE_PATH)) { assertThat(authScheme.signer.signRequest.property(AwsV4FamilyHttpSigner.NORMALIZE_PATH)) .isEqualTo(true); } if (!attributesToExclude.contains(S3SignerExecutionAttribute.ENABLE_CHUNKED_ENCODING)) { assertThat(authScheme.signer.signRequest.property(AwsV4FamilyHttpSigner.CHUNK_ENCODING_ENABLED)) .isEqualTo(true); } if (!attributesToExclude.contains(S3SignerExecutionAttribute.ENABLE_PAYLOAD_SIGNING)) { assertThat(authScheme.signer.signRequest.property(AwsV4FamilyHttpSigner.PAYLOAD_SIGNING_ENABLED)) .isEqualTo(true); } } private static class CapturingAuthScheme implements AuthScheme<AwsCredentialsIdentity> { private final CapturingHttpSigner signer = new CapturingHttpSigner(); @Override public String schemeId() { return AwsV4AuthScheme.SCHEME_ID; } @Override public IdentityProvider<AwsCredentialsIdentity> identityProvider(IdentityProviders providers) { return providers.identityProvider(AwsCredentialsIdentity.class); } @Override public HttpSigner<AwsCredentialsIdentity> signer() { return signer; } } private static class CapturingHttpSigner implements HttpSigner<AwsCredentialsIdentity> { private BaseSignRequest<?, ? extends AwsCredentialsIdentity> signRequest; @Override public SignedRequest sign(SignRequest<? extends AwsCredentialsIdentity> request) { this.signRequest = request; return SignedRequest.builder() .request(request.request()) .payload(request.payload().orElse(null)) .build(); } @Override public CompletableFuture<AsyncSignedRequest> signAsync(AsyncSignRequest<? extends AwsCredentialsIdentity> request) { this.signRequest = request; return CompletableFuture.completedFuture(AsyncSignedRequest.builder() .request(request.request()) .payload(request.payload().orElse(null)) .build()); } } }
4,383
0
Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/S3UtilitiesTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; import java.net.MalformedURLException; import java.net.URI; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.model.GetUrlRequest; public class S3UtilitiesTest { private static final URI US_EAST_1_URI = URI.create("https://s3.amazonaws.com"); private static final S3Configuration ACCELERATE_AND_DUALSTACK_ENABLED = S3Configuration.builder() .accelerateModeEnabled(true) .dualstackEnabled(true) .checksumValidationEnabled(true) .build(); private static final S3Configuration PATH_STYLE_CONFIG = S3Configuration.builder() .pathStyleAccessEnabled(true) .build(); private static S3Client defaultClient; private static S3Utilities defaultUtilities; private static S3AsyncClient asyncClient; private static S3Utilities utilitiesFromAsyncClient; @BeforeClass public static void setup() { defaultClient = S3Client.builder() .credentialsProvider(dummyCreds()) .region(Region.US_WEST_2) .build(); defaultUtilities = defaultClient.utilities(); asyncClient = S3AsyncClient.builder() .credentialsProvider(dummyCreds()) .region(Region.AP_NORTHEAST_2) .build(); utilitiesFromAsyncClient = asyncClient.utilities(); } @AfterClass public static void cleanup() { defaultClient.close(); asyncClient.close(); } @Test public void test_utilities_createdThroughS3Client() throws MalformedURLException { assertThat(defaultUtilities.getUrl(requestWithoutSpaces()) .toExternalForm()) .isEqualTo("https://foo-bucket.s3.us-west-2.amazonaws.com/key-without-spaces"); assertThat(defaultUtilities.getUrl(requestWithSpecialCharacters()) .toExternalForm()) .isEqualTo("https://foo-bucket.s3.us-west-2.amazonaws.com/key%20with%40spaces"); } @Test public void test_utilities_withPathStyleAccessEnabled() throws MalformedURLException { S3Utilities pathStyleUtilities = S3Utilities.builder() .region(Region.US_WEST_2) .s3Configuration(PATH_STYLE_CONFIG) .build(); assertThat(pathStyleUtilities.getUrl(requestWithoutSpaces()) .toExternalForm()) .isEqualTo("https://s3.us-west-2.amazonaws.com/foo-bucket/key-without-spaces"); assertThat(pathStyleUtilities.getUrl(requestWithSpecialCharacters()) .toExternalForm()) .isEqualTo("https://s3.us-west-2.amazonaws.com/foo-bucket/key%20with%40spaces"); } @Test public void test_withUsEast1Region() throws MalformedURLException { S3Utilities usEastUtilities = S3Utilities.builder().region(Region.US_EAST_1).build(); assertThat(usEastUtilities.getUrl(requestWithoutSpaces()) .toExternalForm()) .isEqualTo("https://foo-bucket.s3.amazonaws.com/key-without-spaces"); assertThat(usEastUtilities.getUrl(requestWithSpecialCharacters()).toExternalForm()) .isEqualTo("https://foo-bucket.s3.amazonaws.com/key%20with%40spaces"); } @Test public void test_RegionOnRequestTakesPrecendence() throws MalformedURLException { S3Utilities utilities = S3Utilities.builder().region(Region.US_WEST_2).build(); assertThat(utilities.getUrl(b -> b.bucket("foo-bucket") .key("key-without-spaces") .region(Region.US_EAST_1)) .toExternalForm()) .isEqualTo("https://foo-bucket.s3.amazonaws.com/key-without-spaces"); } @Test public void test_EndpointOnRequestTakesPrecendence() throws MalformedURLException { assertThat(defaultUtilities.getUrl(GetUrlRequest.builder() .bucket("foo-bucket") .key("key-without-spaces") .endpoint(US_EAST_1_URI) .build()) .toExternalForm()) .isEqualTo("https://foo-bucket.s3.amazonaws.com/key-without-spaces"); } @Test public void test_EndpointOverrideOnClientWorks() { S3Utilities customizeUtilities = S3Client.builder() .endpointOverride(URI.create("https://s3.custom.host")) .build() .utilities(); assertThat(customizeUtilities.getUrl(GetUrlRequest.builder() .bucket("foo-bucket") .key("key-without-spaces") .build()) .toExternalForm()) .isEqualTo("https://foo-bucket.s3.custom.host/key-without-spaces"); } @Test public void testWithAccelerateAndDualStackEnabled() throws MalformedURLException { S3Utilities utilities = S3Client.builder() .credentialsProvider(dummyCreds()) .region(Region.US_WEST_2) .serviceConfiguration(ACCELERATE_AND_DUALSTACK_ENABLED) .build() .utilities(); assertThat(utilities.getUrl(requestWithSpecialCharacters()) .toExternalForm()) .isEqualTo("https://foo-bucket.s3-accelerate.dualstack.amazonaws.com/key%20with%40spaces"); } @Test public void testWithAccelerateAndDualStackViaClientEnabled() throws MalformedURLException { S3Utilities utilities = S3Client.builder() .credentialsProvider(dummyCreds()) .region(Region.US_WEST_2) .serviceConfiguration(S3Configuration.builder() .accelerateModeEnabled(true) .build()) .dualstackEnabled(true) .build() .utilities(); assertThat(utilities.getUrl(requestWithSpecialCharacters()) .toExternalForm()) .isEqualTo("https://foo-bucket.s3-accelerate.dualstack.amazonaws.com/key%20with%40spaces"); } @Test public void testWithDualStackViaUtilitiesBuilderEnabled() throws MalformedURLException { S3Utilities utilities = S3Utilities.builder() .region(Region.US_WEST_2) .dualstackEnabled(true) .build(); assertThat(utilities.getUrl(requestWithSpecialCharacters()) .toExternalForm()) .isEqualTo("https://foo-bucket.s3.dualstack.us-west-2.amazonaws.com/key%20with%40spaces"); } @Test public void testAsync() throws MalformedURLException { assertThat(utilitiesFromAsyncClient.getUrl(requestWithoutSpaces()) .toExternalForm()) .isEqualTo("https://foo-bucket.s3.ap-northeast-2.amazonaws.com/key-without-spaces"); assertThat(utilitiesFromAsyncClient.getUrl(requestWithSpecialCharacters()) .toExternalForm()) .isEqualTo("https://foo-bucket.s3.ap-northeast-2.amazonaws.com/key%20with%40spaces"); } @Test (expected = NullPointerException.class) public void failIfRegionIsNotSetOnS3UtilitiesObject() throws MalformedURLException { S3Utilities.builder().build(); } @Test public void getUrlWithVersionId() { S3Utilities utilities = S3Utilities.builder().region(Region.US_WEST_2).build(); assertThat(utilities.getUrl(b -> b.bucket("foo").key("bar").versionId("1")) .toExternalForm()) .isEqualTo("https://foo.s3.us-west-2.amazonaws.com/bar?versionId=1"); assertThat(utilities.getUrl(b -> b.bucket("foo").key("bar").versionId("@1")) .toExternalForm()) .isEqualTo("https://foo.s3.us-west-2.amazonaws.com/bar?versionId=%401"); } @Test public void parseS3Uri_rootUri_shouldParseCorrectly() { String uriString = "https://s3.amazonaws.com"; URI uri = URI.create(uriString); S3Uri s3Uri = defaultUtilities.parseUri(uri); assertThat(s3Uri.uri()).isEqualTo(uri); assertThat(s3Uri.bucket()).isEmpty(); assertThat(s3Uri.key()).isEmpty(); assertThat(s3Uri.region()).isEmpty(); assertThat(s3Uri.isPathStyle()).isTrue(); assertThat(s3Uri.rawQueryParameters()).isEmpty(); } @Test public void parseS3Uri_rootUriTrailingSlash_shouldParseCorrectly() { String uriString = "https://s3.amazonaws.com/"; URI uri = URI.create(uriString); S3Uri s3Uri = defaultUtilities.parseUri(uri); assertThat(s3Uri.uri()).isEqualTo(uri); assertThat(s3Uri.bucket()).isEmpty(); assertThat(s3Uri.key()).isEmpty(); assertThat(s3Uri.region()).isEmpty(); assertThat(s3Uri.isPathStyle()).isTrue(); assertThat(s3Uri.rawQueryParameters()).isEmpty(); } @Test public void parseS3Uri_pathStyleTrailingSlash_shouldParseCorrectly() { String uriString = "https://s3.us-east-1.amazonaws.com/myBucket/"; URI uri = URI.create(uriString); S3Uri s3Uri = defaultUtilities.parseUri(uri); assertThat(s3Uri.uri()).isEqualTo(uri); assertThat(s3Uri.bucket()).contains("myBucket"); assertThat(s3Uri.key()).isEmpty(); assertThat(s3Uri.region()).contains(Region.US_EAST_1); assertThat(s3Uri.isPathStyle()).isTrue(); assertThat(s3Uri.rawQueryParameters()).isEmpty(); } @Test public void parseS3Uri_pathStyleGlobalEndpoint_shouldParseCorrectly() { String uriString = "https://s3.amazonaws.com/myBucket/resources/image1.png"; URI uri = URI.create(uriString); S3Uri s3Uri = defaultUtilities.parseUri(uri); assertThat(s3Uri.uri()).isEqualTo(uri); assertThat(s3Uri.bucket()).contains("myBucket"); assertThat(s3Uri.key()).contains("resources/image1.png"); assertThat(s3Uri.region()).isEmpty(); assertThat(s3Uri.isPathStyle()).isTrue(); assertThat(s3Uri.rawQueryParameters()).isEmpty(); } @Test public void parseS3Uri_virtualStyleGlobalEndpoint_shouldParseCorrectly() { String uriString = "https://myBucket.s3.amazonaws.com/resources/image1.png"; URI uri = URI.create(uriString); S3Uri s3Uri = defaultUtilities.parseUri(uri); assertThat(s3Uri.uri()).isEqualTo(uri); assertThat(s3Uri.bucket()).contains("myBucket"); assertThat(s3Uri.key()).contains("resources/image1.png"); assertThat(s3Uri.region()).isEmpty(); assertThat(s3Uri.isPathStyle()).isFalse(); assertThat(s3Uri.rawQueryParameters()).isEmpty(); } @Test public void parseS3Uri_pathStyleWithDot_shouldParseCorrectly() { String uriString = "https://s3.eu-west-2.amazonaws.com/myBucket/resources/image1.png"; URI uri = URI.create(uriString); S3Uri s3Uri = defaultUtilities.parseUri(uri); assertThat(s3Uri.uri()).isEqualTo(uri); assertThat(s3Uri.bucket()).contains("myBucket"); assertThat(s3Uri.key()).contains("resources/image1.png"); assertThat(s3Uri.region()).contains(Region.EU_WEST_2); assertThat(s3Uri.isPathStyle()).isTrue(); assertThat(s3Uri.rawQueryParameters()).isEmpty(); } @Test public void parseS3Uri_pathStyleWithDash_shouldParseCorrectly() { String uriString = "https://s3-eu-west-2.amazonaws.com/myBucket/resources/image1.png"; URI uri = URI.create(uriString); S3Uri s3Uri = defaultUtilities.parseUri(uri); assertThat(s3Uri.uri()).isEqualTo(uri); assertThat(s3Uri.bucket()).contains("myBucket"); assertThat(s3Uri.key()).contains("resources/image1.png"); assertThat(s3Uri.region()).contains(Region.EU_WEST_2); assertThat(s3Uri.isPathStyle()).isTrue(); assertThat(s3Uri.rawQueryParameters()).isEmpty(); } @Test public void parseS3Uri_virtualHostedStyleWithDot_shouldParseCorrectly() { String uriString = "https://myBucket.s3.us-east-2.amazonaws.com/image.png"; URI uri = URI.create(uriString); S3Uri s3Uri = defaultUtilities.parseUri(uri); assertThat(s3Uri.uri()).isEqualTo(uri); assertThat(s3Uri.bucket()).contains("myBucket"); assertThat(s3Uri.key()).contains("image.png"); assertThat(s3Uri.region()).contains(Region.US_EAST_2); assertThat(s3Uri.isPathStyle()).isFalse(); assertThat(s3Uri.rawQueryParameters()).isEmpty(); } @Test public void parseS3Uri_virtualHostedStyleWithDash_shouldParseCorrectly() { String uriString = "https://myBucket.s3-us-east-2.amazonaws.com/image.png"; URI uri = URI.create(uriString); S3Uri s3Uri = defaultUtilities.parseUri(uri); assertThat(s3Uri.uri()).isEqualTo(uri); assertThat(s3Uri.bucket()).contains("myBucket"); assertThat(s3Uri.key()).contains("image.png"); assertThat(s3Uri.region()).contains(Region.US_EAST_2); assertThat(s3Uri.isPathStyle()).isFalse(); assertThat(s3Uri.rawQueryParameters()).isEmpty(); } @Test public void parseS3Uri_pathStyleWithQuery_shouldParseCorrectly() { String uriString = "https://s3.us-west-1.amazonaws.com/myBucket/doc.txt?versionId=abc123"; URI uri = URI.create(uriString); S3Uri s3Uri = defaultUtilities.parseUri(uri); assertThat(s3Uri.uri()).isEqualTo(uri); assertThat(s3Uri.bucket()).contains("myBucket"); assertThat(s3Uri.key()).contains("doc.txt"); assertThat(s3Uri.region()).contains(Region.US_WEST_1); assertThat(s3Uri.isPathStyle()).isTrue(); assertThat(s3Uri.firstMatchingRawQueryParameter("versionId")).contains("abc123"); } @Test public void parseS3Uri_pathStyleWithQueryMultipleValues_shouldParseCorrectly() { String uriString = "https://s3.us-west-1.amazonaws.com/myBucket/doc.txt?versionId=abc123&versionId=def456"; URI uri = URI.create(uriString); S3Uri s3Uri = defaultUtilities.parseUri(uri); assertThat(s3Uri.uri()).isEqualTo(uri); assertThat(s3Uri.bucket()).contains("myBucket"); assertThat(s3Uri.key()).contains("doc.txt"); assertThat(s3Uri.region()).contains(Region.US_WEST_1); assertThat(s3Uri.isPathStyle()).isTrue(); assertThat(s3Uri.firstMatchingRawQueryParameter("versionId")).contains("abc123"); assertThat(s3Uri.firstMatchingRawQueryParameters("versionId")).contains("def456"); } @Test public void parseS3Uri_pathStyleWithMultipleQueries_shouldParseCorrectly() { String uriString = "https://s3.us-west-1.amazonaws.com/myBucket/doc.txt?versionId=abc123&partNumber=77"; URI uri = URI.create(uriString); S3Uri s3Uri = defaultUtilities.parseUri(uri); assertThat(s3Uri.uri()).isEqualTo(uri); assertThat(s3Uri.bucket()).contains("myBucket"); assertThat(s3Uri.key()).contains("doc.txt"); assertThat(s3Uri.region()).contains(Region.US_WEST_1); assertThat(s3Uri.isPathStyle()).isTrue(); assertThat(s3Uri.firstMatchingRawQueryParameter("versionId")).contains("abc123"); assertThat(s3Uri.firstMatchingRawQueryParameter("partNumber")).contains("77"); } @Test public void parseS3Uri_pathStyleWithEncoding_shouldParseCorrectly() { String uriString = "https://s3.us-west-1.amazonaws.com/my%40Bucket/object%20key?versionId=%61%62%63%31%32%33"; URI uri = URI.create(uriString); S3Uri s3Uri = defaultUtilities.parseUri(uri); assertThat(s3Uri.uri()).isEqualTo(uri); assertThat(s3Uri.bucket()).contains("my@Bucket"); assertThat(s3Uri.key()).contains("object key"); assertThat(s3Uri.region()).contains(Region.US_WEST_1); assertThat(s3Uri.isPathStyle()).isTrue(); assertThat(s3Uri.firstMatchingRawQueryParameter("versionId")).contains("abc123"); } @Test public void parseS3Uri_virtualStyleWithQuery_shouldParseCorrectly() { String uriString= "https://myBucket.s3.us-west-1.amazonaws.com/doc.txt?versionId=abc123"; URI uri = URI.create(uriString); S3Uri s3Uri = defaultUtilities.parseUri(uri); assertThat(s3Uri.uri()).isEqualTo(uri); assertThat(s3Uri.bucket()).contains("myBucket"); assertThat(s3Uri.key()).contains("doc.txt"); assertThat(s3Uri.region()).contains(Region.US_WEST_1); assertThat(s3Uri.isPathStyle()).isFalse(); assertThat(s3Uri.firstMatchingRawQueryParameter("versionId")).contains("abc123"); } @Test public void parseS3Uri_virtualStyleWithQueryMultipleValues_shouldParseCorrectly() { String uriString = "https://myBucket.s3.us-west-1.amazonaws.com/doc.txt?versionId=abc123&versionId=def456"; URI uri = URI.create(uriString); S3Uri s3Uri = defaultUtilities.parseUri(uri); assertThat(s3Uri.uri()).isEqualTo(uri); assertThat(s3Uri.bucket()).contains("myBucket"); assertThat(s3Uri.key()).contains("doc.txt"); assertThat(s3Uri.region()).contains(Region.US_WEST_1); assertThat(s3Uri.isPathStyle()).isFalse(); assertThat(s3Uri.firstMatchingRawQueryParameter("versionId")).contains("abc123"); assertThat(s3Uri.firstMatchingRawQueryParameters("versionId")).contains("def456"); } @Test public void parseS3Uri_virtualStyleWithMultipleQueries_shouldParseCorrectly() { String uriString = "https://myBucket.s3.us-west-1.amazonaws.com/doc.txt?versionId=abc123&partNumber=77"; URI uri = URI.create(uriString); S3Uri s3Uri = defaultUtilities.parseUri(uri); assertThat(s3Uri.uri()).isEqualTo(uri); assertThat(s3Uri.bucket()).contains("myBucket"); assertThat(s3Uri.key()).contains("doc.txt"); assertThat(s3Uri.region()).contains(Region.US_WEST_1); assertThat(s3Uri.isPathStyle()).isFalse(); assertThat(s3Uri.firstMatchingRawQueryParameter("versionId")).contains("abc123"); assertThat(s3Uri.firstMatchingRawQueryParameter("partNumber")).contains("77"); } @Test public void parseS3Uri_virtualStyleWithEncoding_shouldParseCorrectly() { String uriString = "https://myBucket.s3.us-west-1.amazonaws.com/object%20key?versionId=%61%62%63%31%32%33"; URI uri = URI.create(uriString); S3Uri s3Uri = defaultUtilities.parseUri(uri); assertThat(s3Uri.uri()).isEqualTo(uri); assertThat(s3Uri.bucket()).contains("myBucket"); assertThat(s3Uri.key()).contains("object key"); assertThat(s3Uri.region()).contains(Region.US_WEST_1); assertThat(s3Uri.isPathStyle()).isFalse(); assertThat(s3Uri.firstMatchingRawQueryParameter("versionId")).contains("abc123"); } @Test public void parseS3Uri_cliStyleWithoutKey_shouldParseCorrectly() { String uriString = "s3://myBucket"; URI uri = URI.create(uriString); S3Uri s3Uri = defaultUtilities.parseUri(uri); assertThat(s3Uri.uri()).isEqualTo(uri); assertThat(s3Uri.bucket()).contains("myBucket"); assertThat(s3Uri.key()).isEmpty(); assertThat(s3Uri.region()).isEmpty(); assertThat(s3Uri.isPathStyle()).isFalse(); } @Test public void parseS3Uri_cliStyleWithoutKeyWithTrailingSlash_shouldParseCorrectly() { String uriString = "s3://myBucket/"; URI uri = URI.create(uriString); S3Uri s3Uri = defaultUtilities.parseUri(uri); assertThat(s3Uri.uri()).isEqualTo(uri); assertThat(s3Uri.bucket()).contains("myBucket"); assertThat(s3Uri.key()).isEmpty(); assertThat(s3Uri.region()).isEmpty(); assertThat(s3Uri.isPathStyle()).isFalse(); } @Test public void parseS3Uri_cliStyleWithKey_shouldParseCorrectly() { String uriString = "s3://myBucket/resources/key"; URI uri = URI.create(uriString); S3Uri s3Uri = defaultUtilities.parseUri(uri); assertThat(s3Uri.uri()).isEqualTo(uri); assertThat(s3Uri.bucket()).contains("myBucket"); assertThat(s3Uri.key()).contains("resources/key"); assertThat(s3Uri.region()).isEmpty(); assertThat(s3Uri.isPathStyle()).isFalse(); } @Test public void parseS3Uri_cliStyleWithEncoding_shouldParseCorrectly() { String uriString = "s3://my%40Bucket/object%20key"; URI uri = URI.create(uriString); S3Uri s3Uri = defaultUtilities.parseUri(uri); assertThat(s3Uri.uri()).isEqualTo(uri); assertThat(s3Uri.bucket()).contains("my@Bucket"); assertThat(s3Uri.key()).contains("object key"); assertThat(s3Uri.region()).isEmpty(); assertThat(s3Uri.isPathStyle()).isFalse(); } @Test public void parseS3Uri_accessPointUri_shouldThrowProperErrorMessage() { String accessPointUriString = "myendpoint-123456789012.s3-accesspoint.us-east-1.amazonaws.com"; URI accessPointUri = URI.create(accessPointUriString); Exception exception = assertThrows(IllegalArgumentException.class, () -> { defaultUtilities.parseUri(accessPointUri); }); assertThat(exception.getMessage()).isEqualTo("AccessPoints URI parsing is not supported: " + "myendpoint-123456789012.s3-accesspoint.us-east-1.amazonaws.com"); } @Test public void parseS3Uri_accessPointUriWithFipsDualstack_shouldThrowProperErrorMessage() { String accessPointUriString = "myendpoint-123456789012.s3-accesspoint-fips.dualstack.us-gov-east-1.amazonaws.com"; URI accessPointUri = URI.create(accessPointUriString); Exception exception = assertThrows(IllegalArgumentException.class, () -> { defaultUtilities.parseUri(accessPointUri); }); assertThat(exception.getMessage()).isEqualTo("AccessPoints URI parsing is not supported: " + "myendpoint-123456789012.s3-accesspoint-fips.dualstack.us-gov-east-1.amazonaws.com"); } @Test public void parseS3Uri_outpostsUri_shouldThrowProperErrorMessage() { String outpostsUriString = "myaccesspoint-123456789012.op-01234567890123456.s3-outposts.us-west-2.amazonaws.com"; URI outpostsUri = URI.create(outpostsUriString); Exception exception = assertThrows(IllegalArgumentException.class, () -> { defaultUtilities.parseUri(outpostsUri); }); assertThat(exception.getMessage()).isEqualTo("Outposts URI parsing is not supported: " + "myaccesspoint-123456789012.op-01234567890123456.s3-outposts.us-west-2.amazonaws.com"); } @Test public void parseS3Uri_outpostsUriWithChinaPartition_shouldThrowProperErrorMessage() { String outpostsUriString = "myaccesspoint-123456789012.op-01234567890123456.s3-outposts.cn-north-1.amazonaws.com.cn"; URI outpostsUri = URI.create(outpostsUriString); Exception exception = assertThrows(IllegalArgumentException.class, () -> { defaultUtilities.parseUri(outpostsUri); }); assertThat(exception.getMessage()).isEqualTo("Outposts URI parsing is not supported: " + "myaccesspoint-123456789012.op-01234567890123456.s3-outposts.cn-north-1.amazonaws.com.cn"); } @Test public void parseS3Uri_withNonS3Uri_shouldThrowProperErrorMessage() { String nonS3UriString = "https://www.amazon.com/"; URI nonS3Uri = URI.create(nonS3UriString); Exception exception = assertThrows(IllegalArgumentException.class, () -> { defaultUtilities.parseUri(nonS3Uri); }); assertThat(exception.getMessage()).isEqualTo("Invalid S3 URI: hostname does not appear to be a valid S3 endpoint: " + "https://www.amazon.com/"); } @Test public void S3Uri_toString_printsCorrectOutput() { String uriString = "https://myBucket.s3.us-west-1.amazonaws.com/doc.txt?versionId=abc123&partNumber=77"; URI uri = URI.create(uriString); S3Uri s3Uri = defaultUtilities.parseUri(uri); assertThat(s3Uri.toString()).isEqualTo("S3Uri(uri=https://myBucket.s3.us-west-1.amazonaws.com/doc.txt?" + "versionId=abc123&partNumber=77, bucket=myBucket, key=doc.txt, region=us-west-1," + " isPathStyle=false, queryParams={versionId=[abc123], partNumber=[77]})"); } @Test public void S3Uri_testEqualsAndHashCodeContract() { EqualsVerifier.forClass(S3Uri.class).verify(); } private static GetUrlRequest requestWithoutSpaces() { return GetUrlRequest.builder() .bucket("foo-bucket") .key("key-without-spaces") .build(); } private static GetUrlRequest requestWithSpecialCharacters() { return GetUrlRequest.builder() .bucket("foo-bucket") .key("key with@spaces") .build(); } private static AwsCredentialsProvider dummyCreds() { return StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid")); } }
4,384
0
Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/BuilderClientContextParamsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.mockito.ArgumentCaptor; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute; import software.amazon.awssdk.services.s3.endpoints.S3ClientContextParams; import software.amazon.awssdk.utils.AttributeMap; public class BuilderClientContextParamsTest { private ExecutionInterceptor mockInterceptor; private static AttributeMap baseExpectedParams; @BeforeAll public static void setup() { // This is the set of client context params with their values the same as default values in S3Configuration baseExpectedParams = AttributeMap.builder() .put(S3ClientContextParams.USE_ARN_REGION, false) .put(S3ClientContextParams.DISABLE_MULTI_REGION_ACCESS_POINTS, false) .put(S3ClientContextParams.ACCELERATE, false) .put(S3ClientContextParams.FORCE_PATH_STYLE, false) .build(); } @BeforeEach public void methodSetup() { mockInterceptor = mock(ExecutionInterceptor.class); when(mockInterceptor.modifyRequest(any(), any())).thenThrow(new RuntimeException("Oops")); } @MethodSource("testCases") @ParameterizedTest public void verifyParams(TestCase tc) { S3ClientBuilder builder = S3Client.builder() .overrideConfiguration(o -> o.addExecutionInterceptor(mockInterceptor)); if (tc.config() != null) { builder.serviceConfiguration(tc.config()); } if (tc.builderModifier() != null) { tc.builderModifier().accept(builder); } if (tc.exception != null) { assertThatThrownBy(builder::build) .isInstanceOf(tc.exception) .hasMessageContaining(tc.exceptionMessage); } else { assertThatThrownBy(() -> { S3Client s3 = builder.build(); s3.listBuckets(); }).hasMessageContaining("Oops"); ArgumentCaptor<ExecutionAttributes> executionAttrsCaptor = ArgumentCaptor.forClass(ExecutionAttributes.class); verify(mockInterceptor).modifyRequest(any(), executionAttrsCaptor.capture()); AttributeMap clientContextParams = executionAttrsCaptor.getValue().getAttribute(SdkInternalExecutionAttribute.CLIENT_CONTEXT_PARAMS); assertThat(clientContextParams).isEqualTo(tc.expectedParams().merge(baseExpectedParams)); } } public static List<TestCase> testCases() { List<TestCase> testCases = new ArrayList<>(); // UseArnRegion on config testCases.add( TestCase.builder() .config(S3Configuration.builder() .useArnRegionEnabled(true) .build()) .expectedParams(AttributeMap.builder() .put(S3ClientContextParams.USE_ARN_REGION, true) .build()) .build() ); // UseArnRegion on builder testCases.add( TestCase.builder() .builderModifier(b -> b.useArnRegion(true)) .expectedParams(AttributeMap.builder() .put(S3ClientContextParams.USE_ARN_REGION, true) .build()) .build() ); // UseArnRegion on config and builder testCases.add( TestCase.builder() .config(S3Configuration.builder() .useArnRegionEnabled(true) .build()) .builderModifier(b -> b.useArnRegion(true)) .exception(IllegalStateException.class) .exceptionMessage("UseArnRegion") .build() ); // DisableMultiRegionAccessPoints on config testCases.add( TestCase.builder() .config(S3Configuration.builder() .multiRegionEnabled(false) .build()) .expectedParams(AttributeMap.builder() .put(S3ClientContextParams.DISABLE_MULTI_REGION_ACCESS_POINTS, true) .build()) .build() ); // DisableMultiRegionAccessPoints on builder testCases.add( TestCase.builder() .builderModifier(b -> b.disableMultiRegionAccessPoints(true)) .expectedParams(AttributeMap.builder() .put(S3ClientContextParams.DISABLE_MULTI_REGION_ACCESS_POINTS, true) .build()) .build() ); // DisableMultiRegionAccessPoints on config and builder testCases.add( TestCase.builder() .config(S3Configuration.builder() .multiRegionEnabled(false) .build()) .builderModifier(b -> b.disableMultiRegionAccessPoints(true)) .exception(IllegalStateException.class) .exceptionMessage("DisableMultiRegionAccessPoints") .build() ); // Accelerate on config testCases.add( TestCase.builder() .config(S3Configuration.builder() .accelerateModeEnabled(true) .build()) .expectedParams(AttributeMap.builder() .put(S3ClientContextParams.ACCELERATE, true) .build()) .build() ); // Accelerate on builder testCases.add( TestCase.builder() .builderModifier(b -> b.accelerate(true)) .expectedParams(AttributeMap.builder() .put(S3ClientContextParams.ACCELERATE, true) .build()) .build() ); // Accelerate on config and builder testCases.add( TestCase.builder() .config(S3Configuration.builder() .accelerateModeEnabled(true) .build()) .builderModifier(b -> b.accelerate(true)) .exception(IllegalStateException.class) .exceptionMessage("Accelerate") .build() ); // ForcePathStyle on config testCases.add( TestCase.builder() .config(S3Configuration.builder() .pathStyleAccessEnabled(true) .build()) .expectedParams(AttributeMap.builder() .put(S3ClientContextParams.FORCE_PATH_STYLE, true) .build()) .build() ); // ForcePathStyle on builder testCases.add( TestCase.builder() .builderModifier(b -> b.forcePathStyle(true)) .expectedParams(AttributeMap.builder() .put(S3ClientContextParams.FORCE_PATH_STYLE, true) .build()) .build() ); // ForcePathStyle on config and builder testCases.add( TestCase.builder() .config(S3Configuration.builder() .pathStyleAccessEnabled(true) .build()) .builderModifier(b -> b.forcePathStyle(true)) .exception(IllegalStateException.class) .exceptionMessage("ForcePathStyle") .build() ); return testCases; } public static class TestCase { private final S3Configuration config; private final Consumer<S3ClientBuilder> builderModifier; private final Class<?> exception; private final String exceptionMessage; private final AttributeMap expectedParams; private TestCase(Builder b) { this.config = b.config; this.builderModifier = b.builderModifier; this.exception = b.exception; this.exceptionMessage = b.exceptionMessage; this.expectedParams = b.expectedParams; } public S3Configuration config() { return config; } public Consumer<S3ClientBuilder> builderModifier() { return builderModifier; } public Class<?> exception() { return exception; } public String exceptionMessage() { return exceptionMessage; } public AttributeMap expectedParams() { return expectedParams; } public static Builder builder() { return new Builder(); } public static class Builder { private S3Configuration config; private Consumer<S3ClientBuilder> builderModifier; private Class<?> exception; private String exceptionMessage; private AttributeMap expectedParams; public Builder config(S3Configuration config) { this.config = config; return this; } public Builder builderModifier(Consumer<S3ClientBuilder> builderModifier) { this.builderModifier = builderModifier; return this; } public Builder exception(Class<?> exception) { this.exception = exception; return this; } public Builder exceptionMessage(String exceptionMessage) { this.exceptionMessage = exceptionMessage; return this; } private Builder expectedParams(AttributeMap expectedParams) { this.expectedParams = expectedParams; return this; } public TestCase build() { return new TestCase(this); } } } }
4,385
0
Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/EndpointOverrideEndpointResolutionTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.time.Duration; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.function.Consumer; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute; import software.amazon.awssdk.core.client.config.SdkAdvancedClientOption; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.signer.Presigner; import software.amazon.awssdk.core.signer.Signer; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.model.GetObjectRequest; import software.amazon.awssdk.services.s3.presigner.S3Presigner; import software.amazon.awssdk.services.s3.presigner.model.PresignedGetObjectRequest; import software.amazon.awssdk.testutils.service.http.MockSyncHttpClient; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; @RunWith(Parameterized.class) public class EndpointOverrideEndpointResolutionTest { private final TestCase testCase; private final SignerAndPresigner mockSigner; private final MockSyncHttpClient mockHttpClient; private final S3Client s3Client; private final S3Presigner s3Presigner; private final GetObjectRequest getObjectRequest; private final S3Utilities s3Utilities; public interface SignerAndPresigner extends Signer, Presigner {} public EndpointOverrideEndpointResolutionTest(TestCase testCase) throws UnsupportedEncodingException { this.testCase = testCase; this.mockSigner = Mockito.mock(SignerAndPresigner.class); this.mockHttpClient = new MockSyncHttpClient(); this.s3Client = S3Client.builder() .region(testCase.clientRegion) .dualstackEnabled(testCase.clientDualstackEnabled) .fipsEnabled(testCase.clientFipsEnabled) .credentialsProvider(StaticCredentialsProvider.create( AwsBasicCredentials.create("dummy-key", "dummy-secret"))) .endpointOverride(testCase.endpointUrl) .serviceConfiguration(testCase.s3Configuration) .httpClient(mockHttpClient) .overrideConfiguration(c -> c.putAdvancedOption(SdkAdvancedClientOption.SIGNER, mockSigner)) .build(); this.s3Presigner = S3Presigner.builder() .region(testCase.clientRegion) .credentialsProvider(StaticCredentialsProvider.create( AwsBasicCredentials.create("dummy-key", "dummy-secret"))) .endpointOverride(testCase.endpointUrl) .serviceConfiguration(testCase.s3Configuration) .dualstackEnabled(testCase.clientDualstackEnabled) .fipsEnabled(testCase.clientFipsEnabled) .build(); this.s3Utilities = S3Utilities.builder() .region(testCase.clientRegion) .s3Configuration(testCase.s3Configuration) .dualstackEnabled(testCase.clientDualstackEnabled) .fipsEnabled(testCase.clientFipsEnabled) .build(); this.getObjectRequest = testCase.getObjectBucketName == null ? null : GetObjectRequest.builder() .bucket(testCase.getObjectBucketName) .key("object") .overrideConfiguration(c -> c.signer(mockSigner)) .build(); mockHttpClient.stubNextResponse(S3MockUtils.mockListObjectsResponse()); Mockito.when(mockSigner.sign(any(), any())).thenAnswer(r -> r.getArgument(0, SdkHttpFullRequest.class)); Mockito.when(mockSigner.presign(any(), any())).thenAnswer(r -> r.getArgument(0, SdkHttpFullRequest.class) .copy(h -> h.putRawQueryParameter("X-Amz-SignedHeaders", "host"))); } @Test public void s3Client_endpointSigningRegionAndServiceNamesAreCorrect() { try { if (getObjectRequest != null) { s3Client.getObject(getObjectRequest); } else { s3Client.listBuckets(); } assertThat(mockHttpClient.getLastRequest().getUri()).isEqualTo(testCase.expectedEndpoint); assertThat(signingRegion()).isEqualTo(testCase.expectedSigningRegion); assertThat(signingServiceName()).isEqualTo(testCase.expectedSigningServiceName); assertThat(testCase.expectedException).isNull(); } catch (RuntimeException e) { if (testCase.expectedException == null) { throw e; } assertThat(e).isInstanceOf(testCase.expectedException); } } @Test public void s3Presigner_endpointSigningRegionAndServiceNamesAreCorrect() { try { if (getObjectRequest != null) { PresignedGetObjectRequest presignedGetObjectRequest = s3Presigner.presignGetObject(r -> r.getObjectRequest(getObjectRequest) .signatureDuration(Duration.ofDays(1))); URI uriWithoutQueryParameters = presignedGetObjectRequest.httpRequest() .copy(r -> r.removeQueryParameter("X-Amz-SignedHeaders")) .getUri(); assertThat(uriWithoutQueryParameters).isEqualTo(testCase.expectedEndpoint); assertThat(signingRegion()).isEqualTo(testCase.expectedSigningRegion); assertThat(signingServiceName()).isEqualTo(testCase.expectedSigningServiceName); } else { System.out.println("There are (currently) no operations which do not take a bucket. Test will be skipped."); } assertThat(testCase.expectedException).isNull(); } catch (RuntimeException e) { if (testCase.expectedException == null) { throw e; } assertThat(e).isInstanceOf(testCase.expectedException); } } @Test public void s3Utilities_endpointSigningRegionAndServiceNamesAreCorrect() throws URISyntaxException { try { if (testCase.getObjectBucketName != null) { URL url = s3Utilities.getUrl(r -> r.bucket(testCase.getObjectBucketName) .key("object") .endpoint(testCase.endpointUrl) .region(testCase.clientRegion)); assertThat(url.toURI()).isEqualTo(testCase.expectedEndpoint); } else { System.out.println("There are (currently) no operations which do not take a bucket. Test will be skipped."); } assertThat(testCase.expectedException).isNull(); } catch (RuntimeException e) { if (testCase.expectedException == null) { throw e; } assertThat(e).isInstanceOf(testCase.expectedException); } } private String signingServiceName() { return attributesPassedToSigner().getAttribute(AwsSignerExecutionAttribute.SERVICE_SIGNING_NAME); } private Region signingRegion() { return attributesPassedToSigner().getAttribute(AwsSignerExecutionAttribute.SIGNING_REGION); } private ExecutionAttributes attributesPassedToSigner() { ArgumentCaptor<ExecutionAttributes> executionAttributes = ArgumentCaptor.forClass(ExecutionAttributes.class); Mockito.verify(mockSigner, Mockito.atLeast(0)).sign(any(), executionAttributes.capture()); if (executionAttributes.getAllValues().isEmpty()) { return attributesPassedToPresigner(); } return executionAttributes.getValue(); } private ExecutionAttributes attributesPassedToPresigner() { ArgumentCaptor<ExecutionAttributes> executionAttributes = ArgumentCaptor.forClass(ExecutionAttributes.class); Mockito.verify(mockSigner).presign(any(), executionAttributes.capture()); return executionAttributes.getValue(); } @Parameterized.Parameters(name = "{0}") public static Collection<TestCase> testCases() { List<TestCase> cases = new ArrayList<>(); cases.add(new TestCase().setCaseName("normal bucket") .setGetObjectBucketName("bucketname") .setEndpointUrl("https://beta.example.com") .setClientRegion(Region.US_WEST_2) .setExpectedEndpoint("https://bucketname.beta.example.com/object") .setExpectedSigningServiceName("s3") .setExpectedSigningRegion(Region.US_WEST_2)); cases.add(new TestCase().setCaseName("normal bucket with http, path, query and port") .setGetObjectBucketName("bucketname") .setEndpointUrl("http://beta.example.com:1234/path?foo=bar") .setClientRegion(Region.US_WEST_2) .setExpectedEndpoint("http://bucketname.beta.example.com:1234/path/object?foo=bar") .setExpectedSigningServiceName("s3") .setExpectedSigningRegion(Region.US_WEST_2)); cases.add(new TestCase().setCaseName("access point") .setGetObjectBucketName("arn:aws:s3:us-west-2:123456789012:accesspoint:myendpoint") .setEndpointUrl("https://beta.example.com") .setClientRegion(Region.US_WEST_2) .setExpectedEndpoint("https://myendpoint-123456789012.beta.example.com/object") .setExpectedSigningServiceName("s3") .setExpectedSigningRegion(Region.US_WEST_2)); cases.add(new TestCase().setCaseName("access point with http, path, query, and port") .setGetObjectBucketName("arn:aws:s3:us-west-2:123456789012:accesspoint:myendpoint") .setEndpointUrl("http://beta.example.com:1234/path?foo=bar") .setClientRegion(Region.US_WEST_2) .setExpectedEndpoint("http://myendpoint-123456789012.beta.example.com:1234/path/object?foo=bar") .setExpectedSigningServiceName("s3") .setExpectedSigningRegion(Region.US_WEST_2)); cases.add(new TestCase().setCaseName("outposts access point") .setGetObjectBucketName("arn:aws:s3-outposts:us-west-2:123456789012:outpost:op-01234567890123456:accesspoint:myaccesspoint") .setEndpointUrl("https://beta.example.com") .setClientRegion(Region.US_WEST_2) .setExpectedEndpoint("https://myaccesspoint-123456789012.op-01234567890123456.beta.example.com/object") .setExpectedSigningServiceName("s3-outposts") .setExpectedSigningRegion(Region.US_WEST_2)); //FIXME: The ruleset is currently broken for this test case. The provider is not preserving the path part // cases.add(new TestCase().setCaseName("outposts access point with http, path, query, and port") // .setGetObjectBucketName("arn:aws:s3-outposts:us-west-2:123456789012:outpost:op-01234567890123456:accesspoint:myaccesspoint") // .setEndpointUrl("http://beta.example.com:1234/path?foo=bar") // .setClientRegion(Region.US_WEST_2) // .setExpectedEndpoint("http://myaccesspoint-123456789012.op-01234567890123456.beta.example.com:1234/path/object?foo=bar") // .setExpectedSigningServiceName("s3-outposts") // .setExpectedSigningRegion(Region.US_WEST_2)); cases.add(new TestCase().setCaseName("list buckets") .setEndpointUrl("https://bucket.vpce-123-abc.s3.us-west-2.vpce.amazonaws.com") .setClientRegion(Region.US_WEST_2) .setExpectedEndpoint("https://bucket.vpce-123-abc.s3.us-west-2.vpce.amazonaws.com/") .setExpectedSigningServiceName("s3") .setExpectedSigningRegion(Region.US_WEST_2)); cases.add(new TestCase().setCaseName("list buckets with http, path, query and port") .setEndpointUrl("http://bucket.vpce-123-abc.s3.us-west-2.vpce.amazonaws.com:1234/path?foo=bar") .setClientRegion(Region.US_WEST_2) .setExpectedEndpoint("http://bucket.vpce-123-abc.s3.us-west-2.vpce.amazonaws.com:1234/path/?foo=bar") .setExpectedSigningServiceName("s3") .setExpectedSigningRegion(Region.US_WEST_2)); cases.add(new TestCase().setCaseName("normal bucket with vpce, path style addressing explicitly enabled") .setGetObjectBucketName("bucketname") .setEndpointUrl("https://bucket.vpce-123-abc.s3.us-west-2.vpce.amazonaws.com") .setS3Configuration(c -> c.pathStyleAccessEnabled(true)) .setClientRegion(Region.US_WEST_2) .setExpectedEndpoint("https://bucket.vpce-123-abc.s3.us-west-2.vpce.amazonaws.com/bucketname/object") .setExpectedSigningServiceName("s3") .setExpectedSigningRegion(Region.US_WEST_2)); cases.add(new TestCase().setCaseName("normal bucket with http, vpce, path, query, port, and path style addressing explicitly enabled") .setGetObjectBucketName("bucketname") .setEndpointUrl("http://bucket.vpce-123-abc.s3.us-west-2.vpce.amazonaws.com:1234/path?foo=bar") .setS3Configuration(c -> c.pathStyleAccessEnabled(true)) .setClientRegion(Region.US_WEST_2) .setExpectedEndpoint("http://bucket.vpce-123-abc.s3.us-west-2.vpce.amazonaws.com:1234/path/bucketname/object?foo=bar") .setExpectedSigningServiceName("s3") .setExpectedSigningRegion(Region.US_WEST_2)); cases.add(new TestCase().setCaseName("normal bucket with vpce") .setGetObjectBucketName("bucketname") .setEndpointUrl("https://bucket.vpce-123-abc.s3.us-west-2.vpce.amazonaws.com") .setClientRegion(Region.US_WEST_2) .setExpectedEndpoint("https://bucketname.bucket.vpce-123-abc.s3.us-west-2.vpce.amazonaws.com/object") .setExpectedSigningServiceName("s3") .setExpectedSigningRegion(Region.US_WEST_2)); cases.add(new TestCase().setCaseName("normal bucket with http, vpce, path, query and port") .setGetObjectBucketName("bucketname") .setEndpointUrl("http://bucket.vpce-123-abc.s3.us-west-2.vpce.amazonaws.com:1234/path?foo=bar") .setClientRegion(Region.US_WEST_2) .setExpectedEndpoint("http://bucketname.bucket.vpce-123-abc.s3.us-west-2.vpce.amazonaws.com:1234/path/object?foo=bar") .setExpectedSigningServiceName("s3") .setExpectedSigningRegion(Region.US_WEST_2)); cases.add(new TestCase().setCaseName("access point with different arn region and arn region enabled") .setGetObjectBucketName("arn:aws:s3:us-west-2:123456789012:accesspoint:myendpoint") .setEndpointUrl("https://accesspoint.vpce-123-abc.s3.us-west-2.vpce.amazonaws.com") .setS3Configuration(c -> c.useArnRegionEnabled(true)) .setClientRegion(Region.EU_WEST_1) .setExpectedEndpoint("https://myendpoint-123456789012.accesspoint.vpce-123-abc.s3.us-west-2.vpce.amazonaws.com/object") .setExpectedSigningServiceName("s3") .setExpectedSigningRegion(Region.US_WEST_2)); cases.add(new TestCase().setCaseName("access point with http, path, query, port, different arn region, and arn region enabled") .setGetObjectBucketName("arn:aws:s3:us-west-2:123456789012:accesspoint:myendpoint") .setEndpointUrl("http://accesspoint.vpce-123-abc.s3.us-west-2.vpce.amazonaws.com:1234/path?foo=bar") .setS3Configuration(c -> c.useArnRegionEnabled(true)) .setClientRegion(Region.EU_WEST_1) .setExpectedEndpoint("http://myendpoint-123456789012.accesspoint.vpce-123-abc.s3.us-west-2.vpce.amazonaws.com:1234/path/object?foo=bar") .setExpectedSigningServiceName("s3") .setExpectedSigningRegion(Region.US_WEST_2)); cases.add(new TestCase().setCaseName("outposts access point with dual stack enabled via s3 config") .setGetObjectBucketName("arn:aws:s3-outposts:us-west-2:123456789012:outpost:op-01234567890123456:accesspoint:myaccesspoint") .setEndpointUrl("https://beta.example.com") .setS3Configuration(c -> c.dualstackEnabled(true)) .setClientRegion(Region.US_WEST_2) .setExpectedException(SdkClientException.class)); cases.add(new TestCase().setCaseName("outposts access point with dual stack enabled via client builder") .setGetObjectBucketName("arn:aws:s3-outposts:us-west-2:123456789012:outpost:op-01234567890123456:accesspoint:myaccesspoint") .setEndpointUrl("https://beta.example.com") .setClientDualstackEnabled(true) .setClientRegion(Region.US_WEST_2) .setExpectedException(SdkClientException.class)); cases.add(new TestCase().setCaseName("outposts access point with fips enabled via client builder calling cross-region") .setGetObjectBucketName("arn:aws:s3-outposts:us-west-2:123456789012:outpost:op-01234567890123456:accesspoint:myaccesspoint") .setClientFipsEnabled(true) .setClientRegion(Region.US_EAST_1) .setExpectedException(SdkClientException.class)); return cases; } private static class TestCase { private String caseName; private URI endpointUrl; private String getObjectBucketName; private S3Configuration s3Configuration = S3Configuration.builder().build(); private Region clientRegion; private URI expectedEndpoint; private String expectedSigningServiceName; private Region expectedSigningRegion; private Class<? extends RuntimeException> expectedException; private Boolean clientDualstackEnabled; private Boolean clientFipsEnabled; public TestCase setCaseName(String caseName) { this.caseName = caseName; return this; } public TestCase setGetObjectBucketName(String getObjectBucketName) { this.getObjectBucketName = getObjectBucketName; return this; } public TestCase setEndpointUrl(String endpointUrl) { this.endpointUrl = URI.create(endpointUrl); return this; } public TestCase setS3Configuration(Consumer<S3Configuration.Builder> s3Configuration) { S3Configuration.Builder configBuilder = S3Configuration.builder(); s3Configuration.accept(configBuilder); this.s3Configuration = configBuilder.build(); return this; } public TestCase setClientRegion(Region clientRegion) { this.clientRegion = clientRegion; return this; } public TestCase setClientDualstackEnabled(Boolean dualstackEnabled) { this.clientDualstackEnabled = dualstackEnabled; return this; } public TestCase setClientFipsEnabled(Boolean fipsEnabled) { this.clientFipsEnabled = fipsEnabled; return this; } public TestCase setExpectedEndpoint(String expectedEndpoint) { this.expectedEndpoint = URI.create(expectedEndpoint); return this; } public TestCase setExpectedSigningServiceName(String expectedSigningServiceName) { this.expectedSigningServiceName = expectedSigningServiceName; return this; } public TestCase setExpectedSigningRegion(Region expectedSigningRegion) { this.expectedSigningRegion = expectedSigningRegion; return this; } public TestCase setExpectedException(Class<? extends RuntimeException> expectedException) { this.expectedException = expectedException; return this; } @Override public String toString() { return this.caseName + (getObjectBucketName == null ? "" : ": " + getObjectBucketName); } } }
4,386
0
Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/S3PresignerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.net.URI; import java.net.URL; import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.time.ZoneId; import java.time.ZonedDateTime; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.AwsCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.auth.signer.internal.AbstractAwsS3V4Signer; import software.amazon.awssdk.auth.signer.internal.SignerConstant; import software.amazon.awssdk.auth.signer.params.Aws4PresignerParams; import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration; import software.amazon.awssdk.core.SdkSystemSetting; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.signer.NoOpSigner; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.model.GetObjectRequest; import software.amazon.awssdk.services.s3.model.RequestPayer; import software.amazon.awssdk.services.s3.presigner.S3Presigner; import software.amazon.awssdk.services.s3.presigner.model.PresignedDeleteObjectRequest; import software.amazon.awssdk.services.s3.presigner.model.PresignedGetObjectRequest; import software.amazon.awssdk.services.s3.presigner.model.PresignedPutObjectRequest; @RunWith(MockitoJUnitRunner.class) public class S3PresignerTest { private static final URI FAKE_URL; private static final String BUCKET = "some-bucket"; private S3Presigner presigner; static { FAKE_URL = URI.create("https://localhost"); } @Before public void setUp() { this.presigner = presignerBuilder().build(); } @After public void tearDown() { this.presigner.close(); } private S3Presigner.Builder presignerBuilder() { return S3Presigner.builder() .region(Region.US_WEST_2) .credentialsProvider(() -> AwsBasicCredentials.create("x", "x")); } private S3Presigner generateMaximal() { return S3Presigner.builder() .serviceConfiguration(S3Configuration.builder() .checksumValidationEnabled(false) .build()) .credentialsProvider(() -> AwsBasicCredentials.create("x", "x")) .region(Region.US_EAST_1) .endpointOverride(FAKE_URL) .build(); } private S3Presigner generateMinimal() { return S3Presigner.builder() .credentialsProvider(() -> AwsBasicCredentials.create("x", "x")) .region(Region.US_EAST_1) .build(); } @Test public void build_allProperties() { generateMaximal(); } @Test public void build_minimalProperties() { generateMinimal(); } @Test public void getObject_SignatureIsUrlCompatible() { PresignedGetObjectRequest presigned = presigner.presignGetObject(r -> r.signatureDuration(Duration.ofMinutes(5)) .getObjectRequest(go -> go.bucket("foo34343434") .key("bar") .responseContentType("text/plain"))); assertThat(presigned.isBrowserExecutable()).isTrue(); assertThat(presigned.signedHeaders().keySet()).containsExactly("host"); assertThat(presigned.signedPayload()).isEmpty(); } @Test public void getObject_RequesterPaysIsNotUrlCompatible() { PresignedGetObjectRequest presigned = presigner.presignGetObject(r -> r.signatureDuration(Duration.ofMinutes(5)) .getObjectRequest(go -> go.bucket("foo34343434") .key("bar") .requestPayer(RequestPayer.REQUESTER))); assertThat(presigned.isBrowserExecutable()).isFalse(); assertThat(presigned.signedHeaders().keySet()).containsExactlyInAnyOrder("host", "x-amz-request-payer"); assertThat(presigned.signedPayload()).isEmpty(); } @Test public void getObject_EndpointOverrideIsIncludedInPresignedUrl() { S3Presigner presigner = presignerBuilder().endpointOverride(URI.create("http://foo.com")).build(); PresignedGetObjectRequest presigned = presigner.presignGetObject(r -> r.signatureDuration(Duration.ofMinutes(5)) .getObjectRequest(go -> go.bucket("foo34343434") .key("bar"))); assertThat(presigned.url().toString()).startsWith("http://foo34343434.foo.com/bar?"); assertThat(presigned.isBrowserExecutable()).isTrue(); assertThat(presigned.signedHeaders().get("host")).containsExactly("foo34343434.foo.com"); assertThat(presigned.signedPayload()).isEmpty(); } @Test public void getObject_CredentialsCanBeOverriddenAtTheRequestLevel() { AwsCredentials clientCredentials = AwsBasicCredentials.create("a", "a"); AwsCredentials requestCredentials = AwsBasicCredentials.create("b", "b"); S3Presigner presigner = presignerBuilder().credentialsProvider(() -> clientCredentials).build(); AwsRequestOverrideConfiguration overrideConfiguration = AwsRequestOverrideConfiguration.builder() .credentialsProvider(() -> requestCredentials) .build(); PresignedGetObjectRequest presignedWithClientCredentials = presigner.presignGetObject(r -> r.signatureDuration(Duration.ofMinutes(5)) .getObjectRequest(go -> go.bucket("foo34343434") .key("bar"))); PresignedGetObjectRequest presignedWithRequestCredentials = presigner.presignGetObject(r -> r.signatureDuration(Duration.ofMinutes(5)) .getObjectRequest(go -> go.bucket("foo34343434") .key("bar") .overrideConfiguration(overrideConfiguration))); assertThat(presignedWithClientCredentials.httpRequest().rawQueryParameters().get("X-Amz-Credential").get(0)) .startsWith("a"); assertThat(presignedWithRequestCredentials.httpRequest().rawQueryParameters().get("X-Amz-Credential").get(0)) .startsWith("b"); } @Test public void getObject_AdditionalHeadersAndQueryStringsCanBeAdded() { AwsRequestOverrideConfiguration override = AwsRequestOverrideConfiguration.builder() .putHeader("X-Amz-AdditionalHeader", "foo1") .putRawQueryParameter("additionalQueryParam", "foo2") .build(); PresignedGetObjectRequest presigned = presigner.presignGetObject(r -> r.signatureDuration(Duration.ofMinutes(5)) .getObjectRequest(go -> go.bucket("foo34343434") .key("bar") .overrideConfiguration(override))); assertThat(presigned.isBrowserExecutable()).isFalse(); assertThat(presigned.signedHeaders()).containsOnlyKeys("host", "x-amz-additionalheader"); assertThat(presigned.signedHeaders().get("x-amz-additionalheader")).containsExactly("foo1"); assertThat(presigned.httpRequest().headers()).containsKeys("x-amz-additionalheader"); assertThat(presigned.httpRequest().rawQueryParameters().get("additionalQueryParam").get(0)).isEqualTo("foo2"); } @Test public void getObject_NonSigV4SignersRaisesException() { AwsRequestOverrideConfiguration override = AwsRequestOverrideConfiguration.builder() .signer(new NoOpSigner()) .build(); assertThatThrownBy(() -> presigner.presignGetObject(r -> r.signatureDuration(Duration.ofMinutes(5)) .getObjectRequest(go -> go.bucket("foo34343434") .key("bar") .overrideConfiguration(override)))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Only SigV4 signers are supported at this time"); } @Test public void getObject_Sigv4PresignerHonorsSignatureDuration() { PresignedGetObjectRequest presigned = presigner.presignGetObject(r -> r.signatureDuration(Duration.ofSeconds(1234)) .getObjectRequest(gor -> gor.bucket("a") .key("b"))); assertThat(presigned.httpRequest().rawQueryParameters().get("X-Amz-Expires").get(0)).satisfies(expires -> { assertThat(expires).containsOnlyDigits(); assertThat(Integer.parseInt(expires)).isEqualTo(1234); }); } @Test public void putObject_IsNotUrlCompatible() { PresignedPutObjectRequest presigned = presigner.presignPutObject(r -> r.signatureDuration(Duration.ofMinutes(5)) .putObjectRequest(go -> go.bucket("foo34343434") .key("bar"))); assertThat(presigned.isBrowserExecutable()).isFalse(); assertThat(presigned.signedHeaders().keySet()).containsExactlyInAnyOrder("host"); assertThat(presigned.signedPayload()).isEmpty(); } @Test public void putObject_EndpointOverrideIsIncludedInPresignedUrl() { S3Presigner presigner = presignerBuilder().endpointOverride(URI.create("http://foo.com")).build(); PresignedPutObjectRequest presigned = presigner.presignPutObject(r -> r.signatureDuration(Duration.ofMinutes(5)) .putObjectRequest(go -> go.bucket("foo34343434") .key("bar"))); assertThat(presigned.url().toString()).startsWith("http://foo34343434.foo.com/bar?"); assertThat(presigned.isBrowserExecutable()).isFalse(); assertThat(presigned.signedHeaders().get("host")).containsExactly("foo34343434.foo.com"); assertThat(presigned.signedPayload()).isEmpty(); } @Test public void putObject_CredentialsCanBeOverriddenAtTheRequestLevel() { AwsCredentials clientCredentials = AwsBasicCredentials.create("a", "a"); AwsCredentials requestCredentials = AwsBasicCredentials.create("b", "b"); S3Presigner presigner = presignerBuilder().credentialsProvider(() -> clientCredentials).build(); AwsRequestOverrideConfiguration overrideConfiguration = AwsRequestOverrideConfiguration.builder() .credentialsProvider(() -> requestCredentials) .build(); PresignedPutObjectRequest presignedWithClientCredentials = presigner.presignPutObject(r -> r.signatureDuration(Duration.ofMinutes(5)) .putObjectRequest(go -> go.bucket("foo34343434") .key("bar"))); PresignedPutObjectRequest presignedWithRequestCredentials = presigner.presignPutObject(r -> r.signatureDuration(Duration.ofMinutes(5)) .putObjectRequest(go -> go.bucket("foo34343434") .key("bar") .overrideConfiguration(overrideConfiguration))); assertThat(presignedWithClientCredentials.httpRequest().rawQueryParameters().get("X-Amz-Credential").get(0)) .startsWith("a"); assertThat(presignedWithRequestCredentials.httpRequest().rawQueryParameters().get("X-Amz-Credential").get(0)) .startsWith("b"); } @Test public void putObject_AdditionalHeadersAndQueryStringsCanBeAdded() { AwsRequestOverrideConfiguration override = AwsRequestOverrideConfiguration.builder() .putHeader("X-Amz-AdditionalHeader", "foo1") .putRawQueryParameter("additionalQueryParam", "foo2") .build(); PresignedPutObjectRequest presigned = presigner.presignPutObject(r -> r.signatureDuration(Duration.ofMinutes(5)) .putObjectRequest(go -> go.bucket("foo34343434") .key("bar") .overrideConfiguration(override))); assertThat(presigned.isBrowserExecutable()).isFalse(); assertThat(presigned.signedHeaders()).containsOnlyKeys("host", "x-amz-additionalheader"); assertThat(presigned.signedHeaders().get("x-amz-additionalheader")).containsExactly("foo1"); assertThat(presigned.httpRequest().headers()).containsKeys("x-amz-additionalheader"); assertThat(presigned.httpRequest().rawQueryParameters().get("additionalQueryParam").get(0)).isEqualTo("foo2"); } @Test public void putObject_NonSigV4SignersRaisesException() { AwsRequestOverrideConfiguration override = AwsRequestOverrideConfiguration.builder() .signer(new NoOpSigner()) .build(); assertThatThrownBy(() -> presigner.presignPutObject(r -> r.signatureDuration(Duration.ofMinutes(5)) .putObjectRequest(go -> go.bucket("foo34343434") .key("bar") .overrideConfiguration(override)))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Only SigV4 signers are supported at this time"); } @Test public void putObject_Sigv4PresignerHonorsSignatureDuration() { PresignedPutObjectRequest presigned = presigner.presignPutObject(r -> r.signatureDuration(Duration.ofSeconds(1234)) .putObjectRequest(gor -> gor.bucket("a") .key("b"))); assertThat(presigned.httpRequest().rawQueryParameters().get("X-Amz-Expires").get(0)).satisfies(expires -> { assertThat(expires).containsOnlyDigits(); assertThat(Integer.parseInt(expires)).isEqualTo(1234); }); } @Test public void deleteObject_IsNotUrlCompatible() { PresignedDeleteObjectRequest presigned = presigner.presignDeleteObject(r -> r.signatureDuration(Duration.ofMinutes(5)) .deleteObjectRequest(delo -> delo.bucket("foo34343434") .key("bar"))); assertThat(presigned.isBrowserExecutable()).isFalse(); assertThat(presigned.signedHeaders().keySet()).containsExactlyInAnyOrder("host"); assertThat(presigned.signedPayload()).isEmpty(); } @Test public void deleteObject_EndpointOverrideIsIncludedInPresignedUrl() { S3Presigner presigner = presignerBuilder().endpointOverride(URI.create("http://foo.com")).build(); PresignedDeleteObjectRequest presigned = presigner.presignDeleteObject(r -> r.signatureDuration(Duration.ofMinutes(5)) .deleteObjectRequest(delo -> delo.bucket("foo34343434") .key("bar"))); assertThat(presigned.url().toString()).startsWith("http://foo34343434.foo.com/bar?"); assertThat(presigned.signedHeaders().get("host")).containsExactly("foo34343434.foo.com"); assertThat(presigned.signedPayload()).isEmpty(); } @Test public void deleteObject_CredentialsCanBeOverriddenAtTheRequestLevel() { AwsCredentials clientCredentials = AwsBasicCredentials.create("a", "a"); AwsCredentials requestCredentials = AwsBasicCredentials.create("b", "b"); S3Presigner presigner = presignerBuilder().credentialsProvider(() -> clientCredentials).build(); AwsRequestOverrideConfiguration overrideConfiguration = AwsRequestOverrideConfiguration.builder() .credentialsProvider(() -> requestCredentials) .build(); PresignedDeleteObjectRequest presignedWithClientCredentials = presigner.presignDeleteObject(r -> r.signatureDuration(Duration.ofMinutes(5)) .deleteObjectRequest(delo -> delo.bucket("foo34343434") .key("bar"))); PresignedDeleteObjectRequest presignedWithRequestCredentials = presigner.presignDeleteObject(r -> r.signatureDuration(Duration.ofMinutes(5)) .deleteObjectRequest(delo -> delo.bucket("foo34343434") .key("bar") .overrideConfiguration(overrideConfiguration))); assertThat(presignedWithClientCredentials.httpRequest().rawQueryParameters().get("X-Amz-Credential").get(0)) .startsWith("a"); assertThat(presignedWithRequestCredentials.httpRequest().rawQueryParameters().get("X-Amz-Credential").get(0)) .startsWith("b"); } @Test public void deleteObject_AdditionalHeadersAndQueryStringsCanBeAdded() { AwsRequestOverrideConfiguration override = AwsRequestOverrideConfiguration.builder() .putHeader("X-Amz-AdditionalHeader", "foo1") .putRawQueryParameter("additionalQueryParam", "foo2") .build(); PresignedDeleteObjectRequest presigned = presigner.presignDeleteObject(r -> r.signatureDuration(Duration.ofMinutes(5)) .deleteObjectRequest(delo -> delo.bucket("foo34343434") .key("bar") .overrideConfiguration(override))); assertThat(presigned.isBrowserExecutable()).isFalse(); assertThat(presigned.signedHeaders()).containsOnlyKeys("host", "x-amz-additionalheader"); assertThat(presigned.signedHeaders().get("x-amz-additionalheader")).containsExactly("foo1"); assertThat(presigned.httpRequest().headers()).containsKeys("x-amz-additionalheader"); assertThat(presigned.httpRequest().rawQueryParameters().get("additionalQueryParam").get(0)).isEqualTo("foo2"); } @Test public void deleteObject_NonSigV4SignersRaisesException() { AwsRequestOverrideConfiguration override = AwsRequestOverrideConfiguration.builder() .signer(new NoOpSigner()) .build(); assertThatThrownBy(() -> presigner.presignDeleteObject(r -> r.signatureDuration(Duration.ofMinutes(5)) .deleteObjectRequest(delo -> delo.bucket("foo34343434") .key("bar") .overrideConfiguration(override)))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Only SigV4 signers are supported at this time"); } @Test public void deleteObject_Sigv4PresignerHonorsSignatureDuration() { PresignedDeleteObjectRequest presigned = presigner.presignDeleteObject(r -> r.signatureDuration(Duration.ofSeconds(1234)) .deleteObjectRequest(delo -> delo.bucket("a") .key("b"))); assertThat(presigned.httpRequest().rawQueryParameters().get("X-Amz-Expires").get(0)).satisfies(expires -> { assertThat(expires).containsOnlyDigits(); assertThat(Integer.parseInt(expires)).isEqualTo(1234); }); } @Test public void getObject_S3ConfigurationCanBeOverriddenToLeverageTransferAcceleration() { S3Presigner presigner = presignerBuilder().serviceConfiguration(S3Configuration.builder() .accelerateModeEnabled(true) .build()) .build(); PresignedGetObjectRequest presignedRequest = presigner.presignGetObject(r -> r.signatureDuration(Duration.ofMinutes(5)) .getObjectRequest(go -> go.bucket("foo34343434") .key("bar"))); assertThat(presignedRequest.httpRequest().host()).contains(".s3-accelerate."); } @Test public void accelerateEnabled_UsesVirtualAddressingWithAccelerateEndpoint() { S3Presigner presigner = presignerBuilder().serviceConfiguration(S3Configuration.builder() .accelerateModeEnabled(true) .build()) .build(); PresignedGetObjectRequest presignedRequest = presigner.presignGetObject(r -> r.signatureDuration(Duration.ofMinutes(5)) .getObjectRequest(go -> go.bucket(BUCKET) .key("bar"))); assertThat(presignedRequest.httpRequest().host()).isEqualTo(String.format("%s.s3-accelerate.amazonaws.com", BUCKET)); } /** * Dualstack uses regional endpoints that support virtual addressing. */ @Test public void dualstackEnabled_UsesVirtualAddressingWithDualstackEndpoint() throws Exception { S3Presigner presigner = presignerBuilder().serviceConfiguration(S3Configuration.builder() .dualstackEnabled(true) .build()) .build(); PresignedGetObjectRequest presignedRequest = presigner.presignGetObject(r -> r.signatureDuration(Duration.ofMinutes(5)) .getObjectRequest(go -> go.bucket(BUCKET) .key("bar"))); assertThat(presignedRequest.httpRequest().host()).contains(String.format("%s.s3.dualstack.us-west-2.amazonaws.com", BUCKET)); } /** * Dualstack uses regional endpoints that support virtual addressing. */ @Test public void dualstackEnabledViaBuilder_UsesVirtualAddressingWithDualstackEndpoint() throws Exception { S3Presigner presigner = presignerBuilder().dualstackEnabled(true).build(); PresignedGetObjectRequest presignedRequest = presigner.presignGetObject(r -> r.signatureDuration(Duration.ofMinutes(5)) .getObjectRequest(go -> go.bucket(BUCKET) .key("bar"))); assertThat(presignedRequest.httpRequest().host()).contains(String.format("%s.s3.dualstack.us-west-2.amazonaws.com", BUCKET)); } /** * Dualstack also supports path style endpoints just like the normal endpoints. */ @Test public void dualstackAndPathStyleEnabled_UsesPathStyleAddressingWithDualstackEndpoint() throws Exception { S3Presigner presigner = presignerBuilder().serviceConfiguration(S3Configuration.builder() .dualstackEnabled(true) .pathStyleAccessEnabled(true) .build()) .build(); PresignedGetObjectRequest presignedRequest = presigner.presignGetObject(r -> r.signatureDuration(Duration.ofMinutes(5)) .getObjectRequest(go -> go.bucket(BUCKET) .key("bar"))); assertThat(presignedRequest.httpRequest().host()).isEqualTo("s3.dualstack.us-west-2.amazonaws.com"); assertThat(presignedRequest.url().toString()).startsWith(String.format("https://s3.dualstack.us-west-2.amazonaws.com/%s/%s?", BUCKET, "bar")); } /** * When dualstack and accelerate are both enabled there is a special, global dualstack endpoint we must use. */ @Test public void dualstackAndAccelerateEnabled_UsesDualstackAccelerateEndpoint() throws Exception { S3Presigner presigner = presignerBuilder().serviceConfiguration(S3Configuration.builder() .dualstackEnabled(true) .accelerateModeEnabled(true) .build()) .build(); PresignedGetObjectRequest presignedRequest = presigner.presignGetObject(r -> r.signatureDuration(Duration.ofMinutes(5)) .getObjectRequest(go -> go.bucket(BUCKET) .key("bar"))); assertThat(presignedRequest.httpRequest().host()).isEqualTo(String.format("%s.s3-accelerate.dualstack.amazonaws.com", BUCKET)); } @Test public void accessPointArn_differentRegion_useArnRegionTrue() throws Exception { String customEndpoint = "https://foobar-12345678910.s3-accesspoint.us-west-2.amazonaws.com"; String accessPointArn = "arn:aws:s3:us-west-2:12345678910:accesspoint:foobar"; S3Presigner presigner = presignerBuilder().serviceConfiguration(S3Configuration.builder() .useArnRegionEnabled(true) .build()) .build(); PresignedGetObjectRequest presignedRequest = presigner.presignGetObject(r -> r.signatureDuration(Duration.ofMinutes(5)) .getObjectRequest(go -> go.bucket(accessPointArn) .key("bar"))); assertThat(presignedRequest.url().toString()).startsWith(customEndpoint); assertThat(presignedRequest.httpRequest().rawQueryParameters().get("X-Amz-Algorithm").get(0)) .isEqualTo(SignerConstant.AWS4_SIGNING_ALGORITHM); } @Test public void accessPointArn_differentRegion_useArnRegionFalse_throwsIllegalArgumentException() throws Exception { String accessPointArn = "arn:aws:s3:us-east-1:12345678910:accesspoint:foobar"; S3Presigner presigner = presignerBuilder().serviceConfiguration(S3Configuration.builder() .useArnRegionEnabled(false) .build()) .build(); assertThatThrownBy(() -> presigner.presignGetObject(r -> r.signatureDuration(Duration.ofMinutes(5)) .getObjectRequest(go -> go.bucket(accessPointArn).key("bar")))) .isInstanceOf(SdkClientException.class) .hasMessageContaining("Invalid configuration: region from ARN `us-east-1` does not match client region `us-west-2` and UseArnRegion is `false`"); } @Test public void accessPointArn_outpost_correctEndpoint() { String customEndpoint = "https://myaccesspoint-123456789012.op-01234567890123456.s3-outposts.us-west-2.amazonaws.com"; String accessPointArn = "arn:aws:s3-outposts:us-west-2:123456789012:outpost:op-01234567890123456:accesspoint:myaccesspoint"; S3Presigner presigner = presignerBuilder().serviceConfiguration(S3Configuration.builder() .useArnRegionEnabled(true) .build()) .build(); PresignedGetObjectRequest presignedRequest = presigner.presignGetObject(r -> r.signatureDuration(Duration.ofMinutes(5)) .getObjectRequest(go -> go.bucket(accessPointArn) .key("bar"))); assertThat(presignedRequest.url().toString()).startsWith(customEndpoint); } @Test public void accessPointArn_outpost_differentRegion_useArnRegionTrue_correctEndpoint() { String customEndpoint = "https://myaccesspoint-123456789012.op-01234567890123456.s3-outposts.us-east-1.amazonaws.com"; String accessPointArn = "arn:aws:s3-outposts:us-east-1:123456789012:outpost:op-01234567890123456:accesspoint:myaccesspoint"; S3Presigner presigner = presignerBuilder().serviceConfiguration(S3Configuration.builder() .useArnRegionEnabled(true) .build()) .build(); PresignedGetObjectRequest presignedRequest = presigner.presignGetObject(r -> r.signatureDuration(Duration.ofMinutes(5)) .getObjectRequest(go -> go.bucket(accessPointArn) .key("bar"))); assertThat(presignedRequest.url().toString()).startsWith(customEndpoint); } @Test public void accessPointArn_outpost_differentRegion_useArnRegionFalse_throwsIllegalArgumentException() { String accessPointArn = "arn:aws:s3-outposts:us-east-1:123456789012:outpost:op-01234567890123456:accesspoint:myaccesspoint"; S3Presigner presigner = presignerBuilder().serviceConfiguration(S3Configuration.builder() .useArnRegionEnabled(false) .build()) .build(); assertThatThrownBy(() -> presigner.presignGetObject(r -> r.signatureDuration(Duration.ofMinutes(5)) .getObjectRequest(go -> go.bucket(accessPointArn) .key("bar")))) .isInstanceOf(SdkClientException.class) .hasMessageContaining("Invalid configuration: region from ARN `us-east-1` does not match client region `us-west-2` and UseArnRegion is `false`"); } @Test public void accessPointArn_multiRegion_useArnRegionTrue_correctEndpointAndSigner() { String customEndpoint = "https://mfzwi23gnjvgw.mrap.accesspoint.s3-global.amazonaws.com"; String accessPointArn = "arn:aws:s3::12345678910:accesspoint:mfzwi23gnjvgw.mrap"; S3Presigner presigner = presignerBuilder().serviceConfiguration(S3Configuration.builder() .useArnRegionEnabled(true) .build()) .build(); PresignedGetObjectRequest presignedRequest = presigner.presignGetObject(r -> r.signatureDuration(Duration.ofMinutes(5)) .getObjectRequest(go -> go.bucket(accessPointArn) .key("bar"))); assertThat(presignedRequest.httpRequest().rawQueryParameters().get("X-Amz-Algorithm").get(0)) .isEqualTo("AWS4-ECDSA-P256-SHA256"); assertThat(presignedRequest.url().toString()).startsWith(customEndpoint); } @Test public void outpostArn_usWest_calculatesCorrectSignature() { StaticCredentialsProvider credentials = StaticCredentialsProvider.create(AwsBasicCredentials.create( "ACCESS_KEY_ID", "SECRET_ACCESS_KEY")); String outpostArn = "arn:aws:s3-outposts:us-west-2:123456789012:outpost:op-01234567890123456:accesspoint:myaccesspoint"; S3Presigner presigner = S3Presigner.builder() .region(Region.of("us-west-2")) .credentialsProvider(credentials) .serviceConfiguration(S3Configuration.builder() .useArnRegionEnabled(true) // Explicitly disable this because not doing so // will add a new header to the signature // calculation and it won't match the expected // signature .checksumValidationEnabled(false) .build()) .build(); Duration urlDuration = Duration.ofSeconds(900); ZonedDateTime signingDate = ZonedDateTime.of(2021, 8, 27, 0, 0, 0, 0, ZoneId.of("UTC")); Clock signingClock = Clock.fixed(signingDate.toInstant(), ZoneId.of("UTC")); Instant expirationTime = signingDate.toInstant().plus(urlDuration); GetObjectRequest getObject = GetObjectRequest.builder() .bucket(outpostArn) .key("obj") .overrideConfiguration(o -> o.signer(new TestS3V4Signer(signingClock, expirationTime))) .build(); PresignedGetObjectRequest presigned = presigner.presignGetObject(r -> r.getObjectRequest(getObject) // doesn't really do anything in this case since // we set it in TestSigner .signatureDuration(urlDuration)); String expectedSignature = "a944fbe2bfbae429f922746546d1c6f890649c88ba7826bd1d258ac13f327e09"; assertThat(presigned.url().toString()).contains("X-Amz-Signature=" + expectedSignature); } @Test public void outpostArn_usEast_calculatesCorrectSignature() { StaticCredentialsProvider credentials = StaticCredentialsProvider.create(AwsBasicCredentials.create( "ACCESS_KEY_ID", "SECRET_ACCESS_KEY")); String outpostArn = "arn:aws:s3-outposts:us-east-1:123456789012:outpost:op-01234567890123456:accesspoint:myaccesspoint"; S3Presigner presigner = S3Presigner.builder() .region(Region.of("us-west-2")) .credentialsProvider(credentials) .serviceConfiguration(S3Configuration.builder() .useArnRegionEnabled(true) // Explicitly disable this because not doing so // will add a new header to the signature // calculation and it won't match the expected // signature .checksumValidationEnabled(false) .build()) .build(); Duration urlDuration = Duration.ofSeconds(900); ZonedDateTime signingDate = ZonedDateTime.of(2021, 8, 27, 0, 0, 0, 0, ZoneId.of("UTC")); Clock signingClock = Clock.fixed(signingDate.toInstant(), ZoneId.of("UTC")); Instant expirationTime = signingDate.toInstant().plus(urlDuration); GetObjectRequest getObject = GetObjectRequest.builder() .bucket(outpostArn) .key("obj") .overrideConfiguration(o -> o.signer(new TestS3V4Signer(signingClock, expirationTime))) .build(); PresignedGetObjectRequest presigned = presigner.presignGetObject(r -> r.getObjectRequest(getObject) // doesn't really do anything in this case since // we set it in TestSigner .signatureDuration(urlDuration)); String expectedSignature = "7f93df0b81f80e590d95442d579bd6cf749a35ff4bbdc6373fa669b89c7fce4e"; assertThat(presigned.url().toString()).contains("X-Amz-Signature=" + expectedSignature); } @Test(expected = IllegalStateException.class) public void dualstackInConfigAndPresignerBuilder_throwsException() throws Exception { presignerBuilder().serviceConfiguration(S3Configuration.builder() .dualstackEnabled(true) .build()) .dualstackEnabled(true) .build(); } @Test public void getObject_useEast1_regionalEndpointDisabled_usesGlobalEndpoint() { String settingSaveValue = System.getProperty(SdkSystemSetting.AWS_S3_US_EAST_1_REGIONAL_ENDPOINT.property()); System.setProperty(SdkSystemSetting.AWS_S3_US_EAST_1_REGIONAL_ENDPOINT.property(), "global"); try { S3Presigner usEast1Presigner = presignerBuilder().region(Region.US_EAST_1).build(); URL presigned = usEast1Presigner.presignGetObject(r -> r.getObjectRequest(getRequest -> getRequest.bucket("foo").key("bar")) .signatureDuration(Duration.ofHours(1))) .url(); assertThat(presigned.getHost()).isEqualTo("foo.s3.amazonaws.com"); } finally { if (settingSaveValue != null) { System.setProperty(SdkSystemSetting.AWS_S3_US_EAST_1_REGIONAL_ENDPOINT.property(), settingSaveValue); } else { System.clearProperty(SdkSystemSetting.AWS_S3_US_EAST_1_REGIONAL_ENDPOINT.property()); } } } @Test public void getObject_useEast1_regionalEndpointEnabled_usesRegionalEndpoint() { String settingSaveValue = System.getProperty(SdkSystemSetting.AWS_S3_US_EAST_1_REGIONAL_ENDPOINT.property()); System.setProperty(SdkSystemSetting.AWS_S3_US_EAST_1_REGIONAL_ENDPOINT.property(), "regional"); try { S3Presigner usEast1Presigner = presignerBuilder().region(Region.US_EAST_1).build(); URL presigned = usEast1Presigner.presignGetObject(r -> r.getObjectRequest(getRequest -> getRequest.bucket("foo").key("bar")) .signatureDuration(Duration.ofHours(1))) .url(); assertThat(presigned.getHost()).isEqualTo("foo.s3.us-east-1.amazonaws.com"); } finally { if (settingSaveValue != null) { System.setProperty(SdkSystemSetting.AWS_S3_US_EAST_1_REGIONAL_ENDPOINT.property(), settingSaveValue); } else { System.clearProperty(SdkSystemSetting.AWS_S3_US_EAST_1_REGIONAL_ENDPOINT.property()); } } } // Variant of AwsS3V4Signer that allows for changing the signing clock and expiration time public static class TestS3V4Signer extends AbstractAwsS3V4Signer { private final Clock signingClock; private final Instant expirationTime; public TestS3V4Signer(Clock signingClock, Instant expirationTime) { this.signingClock = signingClock; this.expirationTime = expirationTime; } // Intercept the presign() method so we can change the expiration @Override public SdkHttpFullRequest presign(SdkHttpFullRequest request, Aws4PresignerParams signingParams) { Aws4PresignerParams.Builder newSignerParamsBuilder = Aws4PresignerParams.builder(); newSignerParamsBuilder.expirationTime(expirationTime); newSignerParamsBuilder.signingClockOverride(signingClock); newSignerParamsBuilder.signingRegion(signingParams.signingRegion()); newSignerParamsBuilder.signingName(signingParams.signingName()); newSignerParamsBuilder.awsCredentials(signingParams.awsCredentials()); newSignerParamsBuilder.doubleUrlEncode(signingParams.doubleUrlEncode()); return super.presign(request, newSignerParamsBuilder.build()); } } }
4,387
0
Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3
Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/functionaltests/GetObjectWithChecksumTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.functionaltests; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.any; import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static org.assertj.core.api.Assertions.assertThat; import com.github.tomakehurst.wiremock.junit5.WireMockRuntimeInfo; import com.github.tomakehurst.wiremock.junit5.WireMockTest; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.function.Function; import java.util.stream.Collectors; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.core.ResponseInputStream; import software.amazon.awssdk.core.async.AsyncResponseTransformer; import software.amazon.awssdk.core.checksums.Algorithm; import software.amazon.awssdk.core.checksums.ChecksumValidation; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3AsyncClient; import software.amazon.awssdk.services.s3.S3AsyncClientBuilder; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.S3ClientBuilder; import software.amazon.awssdk.services.s3.model.ChecksumMode; import software.amazon.awssdk.services.s3.model.GetObjectResponse; import software.amazon.awssdk.services.s3.utils.CaptureChecksumValidationInterceptor; @WireMockTest public class GetObjectWithChecksumTest { public static final Function<InputStream, String> stringFromStream = inputStream -> new BufferedReader( new InputStreamReader(inputStream, StandardCharsets.UTF_8)).lines().collect(Collectors.joining("\n")); private static final String EXAMPLE_BUCKET = "Example-Bucket"; private static final String EXAMPLE_RESPONSE_BODY = "Hello world"; private static final CaptureChecksumValidationInterceptor captureChecksumValidationInterceptor = new CaptureChecksumValidationInterceptor(); private S3ClientBuilder getSyncClientBuilder(WireMockRuntimeInfo wm) { return S3Client.builder() .region(Region.US_EAST_1) .endpointOverride(URI.create(wm.getHttpBaseUrl())) .credentialsProvider( StaticCredentialsProvider.create(AwsBasicCredentials.create("key", "secret"))); } @AfterEach public void reset() { captureChecksumValidationInterceptor.reset(); } private S3AsyncClientBuilder getAsyncClientBuilder(WireMockRuntimeInfo wm) { return S3AsyncClient.builder() .region(Region.US_EAST_1) .endpointOverride(URI.create(wm.getHttpBaseUrl())) .credentialsProvider( StaticCredentialsProvider.create(AwsBasicCredentials.create("key", "secret"))); } @Test public void async_getObject_with_correct_http_checksum(WireMockRuntimeInfo wm) { stubFor(any(anyUrl()).willReturn(aResponse().withStatus(200) .withHeader("x-amz-checksum-crc32", "i9aeUg==") .withBody(EXAMPLE_RESPONSE_BODY))); S3AsyncClient s3Client = getAsyncClientBuilder(wm).overrideConfiguration(o -> o.addExecutionInterceptor(captureChecksumValidationInterceptor)).build(); String response = s3Client.getObject(r -> r.bucket(EXAMPLE_BUCKET).key("key").checksumMode(ChecksumMode.ENABLED), AsyncResponseTransformer.toBytes()).join().asUtf8String(); assertThat(response).isEqualTo("Hello world"); assertThat(captureChecksumValidationInterceptor.responseValidation()).isEqualTo(ChecksumValidation.VALIDATED); assertThat(captureChecksumValidationInterceptor.validationAlgorithm()).isEqualTo(Algorithm.CRC32); } @Test public void async_getObject_with_validation_enabled_no_http_checksum(WireMockRuntimeInfo wm) { stubFor(any(anyUrl()).willReturn(aResponse().withStatus(200) .withBody(EXAMPLE_RESPONSE_BODY))); S3AsyncClient s3Client = getAsyncClientBuilder(wm).overrideConfiguration(o -> o.addExecutionInterceptor(captureChecksumValidationInterceptor)).build(); String response = s3Client.getObject(r -> r.bucket(EXAMPLE_BUCKET).key("key").checksumMode(ChecksumMode.ENABLED), AsyncResponseTransformer.toBytes()).join().asUtf8String(); assertThat(response).isEqualTo("Hello world"); assertThat(captureChecksumValidationInterceptor.responseValidation()).isEqualTo(ChecksumValidation.CHECKSUM_ALGORITHM_NOT_FOUND); assertThat(captureChecksumValidationInterceptor.validationAlgorithm()).isNull(); } @Test public void async_getObject_with_validation_not_enabled_incorrect_http_checksum(WireMockRuntimeInfo wm) { stubFor(any(anyUrl()).willReturn(aResponse().withStatus(200) .withHeader("x-amz-checksum-crc32", "incorrect") .withBody(EXAMPLE_RESPONSE_BODY))); S3AsyncClient s3Client = getAsyncClientBuilder(wm).overrideConfiguration(o -> o.addExecutionInterceptor(captureChecksumValidationInterceptor)).build(); String response = s3Client.getObject(r -> r.bucket(EXAMPLE_BUCKET).key("key"), AsyncResponseTransformer.toBytes()).join().asUtf8String(); assertThat(response).isEqualTo("Hello world"); assertThat(captureChecksumValidationInterceptor.responseValidation()).isNull(); assertThat(captureChecksumValidationInterceptor.validationAlgorithm()).isNull(); } @Test public void async_getObject_with_customized_multipart_checksum(WireMockRuntimeInfo wm) { stubFor(any(anyUrl()).willReturn(aResponse().withStatus(200) .withHeader("x-amz-checksum-crc32", "abcdef==-12") .withBody(EXAMPLE_RESPONSE_BODY))); S3AsyncClient s3Client = getAsyncClientBuilder(wm).overrideConfiguration(o -> o.addExecutionInterceptor(captureChecksumValidationInterceptor)).build(); String response = s3Client.getObject(r -> r.bucket(EXAMPLE_BUCKET).key("key").checksumMode(ChecksumMode.ENABLED), AsyncResponseTransformer.toBytes()).join().asUtf8String(); assertThat(response).isEqualTo("Hello world"); assertThat(captureChecksumValidationInterceptor.responseValidation()).isEqualTo(ChecksumValidation.FORCE_SKIP); assertThat(captureChecksumValidationInterceptor.validationAlgorithm()).isNull(); } @Test public void sync_getObject_with_correct_http_checksum(WireMockRuntimeInfo wm) { stubFor(any(anyUrl()).willReturn(aResponse().withStatus(200) .withHeader("x-amz-checksum-crc32", "i9aeUg==") .withBody(EXAMPLE_RESPONSE_BODY))); S3Client s3Client = getSyncClientBuilder(wm).overrideConfiguration(o -> o.addExecutionInterceptor(captureChecksumValidationInterceptor)).build(); ResponseInputStream<GetObjectResponse> getObject = s3Client.getObject(r -> r.bucket(EXAMPLE_BUCKET).key("key").checksumMode(ChecksumMode.ENABLED)); assertThat(stringFromStream.apply(getObject)).isEqualTo("Hello world"); assertThat(captureChecksumValidationInterceptor.responseValidation()).isEqualTo(ChecksumValidation.VALIDATED); assertThat(captureChecksumValidationInterceptor.validationAlgorithm()).isEqualTo(Algorithm.CRC32); } @Test public void sync_getObject_with_validation_enabled_no_http_checksum(WireMockRuntimeInfo wm) { stubFor(any(anyUrl()).willReturn(aResponse().withStatus(200) .withBody(EXAMPLE_RESPONSE_BODY))); S3Client s3Client = getSyncClientBuilder(wm).overrideConfiguration(o -> o.addExecutionInterceptor(captureChecksumValidationInterceptor)).build(); ResponseInputStream<GetObjectResponse> getObject = s3Client.getObject(r -> r.bucket(EXAMPLE_BUCKET).key("key").checksumMode(ChecksumMode.ENABLED)); assertThat(stringFromStream.apply(getObject)).isEqualTo("Hello world"); assertThat(captureChecksumValidationInterceptor.responseValidation()).isEqualTo(ChecksumValidation.CHECKSUM_ALGORITHM_NOT_FOUND); assertThat(captureChecksumValidationInterceptor.validationAlgorithm()).isNull(); } @Test public void sync_getObject_with_validation_not_enabled_incorrect_http_checksum(WireMockRuntimeInfo wm) { stubFor(any(anyUrl()).willReturn(aResponse().withStatus(200) .withHeader("x-amz-checksum-crc32", "incorrect") .withBody(EXAMPLE_RESPONSE_BODY))); S3Client s3Client = getSyncClientBuilder(wm).overrideConfiguration(o -> o.addExecutionInterceptor(captureChecksumValidationInterceptor)).build(); ResponseInputStream<GetObjectResponse> getObject = s3Client.getObject(r -> r.bucket(EXAMPLE_BUCKET).key("key")); assertThat(stringFromStream.apply(getObject)).isEqualTo("Hello world"); assertThat(captureChecksumValidationInterceptor.responseValidation()).isNull(); assertThat(captureChecksumValidationInterceptor.validationAlgorithm()).isNull(); } @Test public void sync_getObject_with_customized_multipart_checksum(WireMockRuntimeInfo wm) { stubFor(any(anyUrl()).willReturn(aResponse().withStatus(200) .withHeader("x-amz-checksum-crc32", "i9aeUg==-12") .withBody(EXAMPLE_RESPONSE_BODY))); S3Client s3Client = getSyncClientBuilder(wm).overrideConfiguration(o -> o.addExecutionInterceptor(captureChecksumValidationInterceptor)).build(); ResponseInputStream<GetObjectResponse> getObject = s3Client.getObject(r -> r.bucket(EXAMPLE_BUCKET).key("key").checksumMode(ChecksumMode.ENABLED)); assertThat(stringFromStream.apply(getObject)).isEqualTo("Hello world"); assertThat(captureChecksumValidationInterceptor.responseValidation()).isEqualTo(ChecksumValidation.FORCE_SKIP); assertThat(captureChecksumValidationInterceptor.validationAlgorithm()).isNull(); } }
4,388
0
Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3
Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/functionaltests/GetBucketPolicyFunctionalTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.functionaltests; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.any; import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static org.assertj.core.api.Assertions.assertThat; import com.github.tomakehurst.wiremock.junit.WireMockRule; import java.net.URI; import org.junit.Rule; import org.junit.Test; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.crt.Log; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3AsyncClient; import software.amazon.awssdk.services.s3.S3AsyncClientBuilder; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.S3ClientBuilder; import software.amazon.awssdk.services.s3.S3CrtAsyncClientBuilder; import software.amazon.awssdk.services.s3.model.GetBucketPolicyResponse; public class GetBucketPolicyFunctionalTest { private static final String EXAMPLE_BUCKET = "Example-Bucket"; private static final String EXAMPLE_POLICY = "{\"Version\":\"2012-10-17\",\"Id\":\"Policy1234\"," + "\"Statement\":[{\"Sid\":\"Stmt1578431058575\",\"Effect\":\"Allow\"," + "\"Principal\":{\"AWS\":\"arn:aws:iam::1234567890:root\"},\"Action\":\"s3:*\"," + "\"Resource\":\"arn:aws:s3:::dummy-resource/*\"}]}"; @Rule public WireMockRule wireMock = new WireMockRule(0); private URI endpoint() { return URI.create("http://localhost:" + wireMock.port()); } private S3ClientBuilder getSyncClientBuilder() { return S3Client.builder() .region(Region.US_EAST_1) .endpointOverride(endpoint()) .credentialsProvider( StaticCredentialsProvider.create(AwsBasicCredentials.create("key", "secret"))); } private S3AsyncClientBuilder getAsyncClientBuilder() { return S3AsyncClient.builder() .region(Region.US_EAST_1) .endpointOverride(endpoint()) .credentialsProvider( StaticCredentialsProvider.create(AwsBasicCredentials.create("key", "secret"))); } private S3CrtAsyncClientBuilder getS3CrtAsyncClientBuilder() { return S3AsyncClient.crtBuilder() .region(Region.US_EAST_1) .endpointOverride(endpoint()) .credentialsProvider( StaticCredentialsProvider.create(AwsBasicCredentials.create("key", "secret"))); } @Test public void getBucketPolicy_syncClient() { stubFor(any(anyUrl()).willReturn(aResponse().withStatus(200).withBody(EXAMPLE_POLICY))); S3Client s3Client = getSyncClientBuilder().build(); GetBucketPolicyResponse response = s3Client.getBucketPolicy(r -> r.bucket(EXAMPLE_BUCKET)); assertThat(response.policy()).isEqualTo(EXAMPLE_POLICY); } @Test public void getBucketPolicy_asyncClient() { stubFor(any(anyUrl()).willReturn(aResponse().withStatus(200).withBody(EXAMPLE_POLICY))); S3AsyncClient s3Client = getAsyncClientBuilder().build(); GetBucketPolicyResponse response = s3Client.getBucketPolicy(r -> r.bucket(EXAMPLE_BUCKET)).join(); assertThat(response.policy()).isEqualTo(EXAMPLE_POLICY); } @Test public void getBucketPolicy_crtClient() { stubFor(any(anyUrl()).willReturn(aResponse().withStatus(200).withBody(EXAMPLE_POLICY))); try(S3AsyncClient s3Client = getS3CrtAsyncClientBuilder().build()) { GetBucketPolicyResponse response = s3Client.getBucketPolicy(r -> r.bucket(EXAMPLE_BUCKET)).join(); assertThat(response.policy()).isEqualTo(EXAMPLE_POLICY); } } }
4,389
0
Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3
Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/functionaltests/EmptyResponseTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.functionaltests; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import com.github.tomakehurst.wiremock.junit.WireMockRule; import java.net.URI; import org.junit.Rule; import org.junit.Test; import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3Client; public class EmptyResponseTest { @Rule public WireMockRule mockServer = new WireMockRule(0); @Test public void emptyChunkedEncodingResponseWorks() { stubFor(get(anyUrl()) .willReturn(aResponse().withStatus(200) .withHeader("Transfer-Encoding", "chunked"))); S3Client client = S3Client.builder() .endpointOverride(URI.create("http://localhost:" + mockServer.port())) .region(Region.US_WEST_2) .credentialsProvider(AnonymousCredentialsProvider.create()) .build(); client.listBuckets(); // Should not fail } }
4,390
0
Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3
Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/functionaltests/AsyncResponseTransformerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.functionaltests; import static org.assertj.core.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import java.util.concurrent.CompletionException; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.auth.credentials.AwsCredentialsProviderChain; import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; import software.amazon.awssdk.core.async.AsyncResponseTransformer; import software.amazon.awssdk.services.s3.S3AsyncClient; @RunWith(MockitoJUnitRunner.class) public class AsyncResponseTransformerTest { @Mock private AsyncResponseTransformer asyncResponseTransformer; @Test public void AsyncResponseTransformerPrepareCalled_BeforeCredentialsResolution() { S3AsyncClient client = S3AsyncClient.builder() .credentialsProvider(AwsCredentialsProviderChain.of( ProfileCredentialsProvider.create("dummyprofile"))) .build(); try { client.getObject(b -> b.bucket("dummy").key("key"), asyncResponseTransformer).join(); fail("Expected an exception during credential resolution"); } catch (CompletionException e) { } verify(asyncResponseTransformer, times(1)).prepare(); verify(asyncResponseTransformer, times(1)).exceptionOccurred(any()); } }
4,391
0
Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3
Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/functionaltests/RetriesOn200Test.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.functionaltests; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl; import static com.github.tomakehurst.wiremock.client.WireMock.put; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import com.github.tomakehurst.wiremock.junit.WireMockRule; import java.net.URI; import org.junit.Rule; import org.junit.Test; import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider; 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.core.retry.RetryMode; import software.amazon.awssdk.core.retry.RetryPolicy; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.S3Exception; public class RetriesOn200Test { public static final String ERROR_CODE = "InternalError"; public static final String ERROR_MESSAGE = "We encountered an internal error. Please try again."; public static final String ERROR_BODY = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<Error>\n" + " <Code>" + ERROR_CODE + "</Code>\n" + " <Message>" + ERROR_MESSAGE + "</Message>\n" + "</Error>"; @Rule public WireMockRule mockServer = new WireMockRule(0); @Test public void copyObjectRetriesOn200InternalErrorFailures() { AttemptCountingInterceptor countingInterceptor = new AttemptCountingInterceptor(); S3Client client = S3Client.builder() .endpointOverride(URI.create("http://localhost:" + mockServer.port())) .region(Region.US_WEST_2) .credentialsProvider(AnonymousCredentialsProvider.create()) .overrideConfiguration(c -> c.retryPolicy(RetryMode.STANDARD) .addExecutionInterceptor(countingInterceptor)) .serviceConfiguration(c -> c.pathStyleAccessEnabled(true)) .build(); stubFor(put(anyUrl()) .willReturn(aResponse().withStatus(200) .withBody(ERROR_BODY))); assertThatThrownBy(() -> client.copyObject(r -> r.sourceBucket("foo").sourceKey("foo") .destinationBucket("bar").destinationKey("bar"))) .isInstanceOfSatisfying(S3Exception.class, e -> { assertThat(e.statusCode()).isEqualTo(200); assertThat(e.awsErrorDetails().errorCode()).isEqualTo(ERROR_CODE); assertThat(e.awsErrorDetails().errorMessage()).isEqualTo(ERROR_MESSAGE); }); assertThat(countingInterceptor.attemptCount).isEqualTo(RetryPolicy.forRetryMode(RetryMode.STANDARD).numRetries() + 1); } private static final class AttemptCountingInterceptor implements ExecutionInterceptor { private long attemptCount = 0; @Override public void beforeTransmission(Context.BeforeTransmission context, ExecutionAttributes executionAttributes) { ++attemptCount; } } }
4,392
0
Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3
Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/functionaltests/MultiRegionAccessPointSigningFunctionalTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.functionaltests; import static org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.services.s3.S3MockUtils.mockListObjectsResponse; import java.io.UnsupportedEncodingException; import java.util.List; import java.util.Map; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.auth.signer.AwsS3V4Signer; import software.amazon.awssdk.auth.signer.internal.SignerConstant; import software.amazon.awssdk.authcrt.signer.internal.DefaultAwsCrtS3V4aSigner; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.core.client.config.SdkAdvancedClientOption; import software.amazon.awssdk.core.signer.Signer; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.S3ClientBuilder; import software.amazon.awssdk.services.s3.S3Configuration; import software.amazon.awssdk.services.s3.model.ListObjectsRequest; import software.amazon.awssdk.testutils.service.http.MockHttpClient; import software.amazon.awssdk.testutils.service.http.MockSyncHttpClient; /** * Functional tests for multi-region access point ARN signing */ public class MultiRegionAccessPointSigningFunctionalTest { private static final String MRAP_SIGNING_SCOPE = "*"; private static final String MRAP_ARN = "arn:aws:s3::123456789012:accesspoint:mfzwi23gnjvgw.mrap"; private static final String AWS4A_SIGNING_ALGORITHM = "AWS4-ECDSA-P256-SHA256"; private MockHttpClient mockHttpClient; @BeforeEach public void setup() throws UnsupportedEncodingException { mockHttpClient = new MockSyncHttpClient(); mockHttpClient.stubNextResponse(mockListObjectsResponse()); } @Test public void multiRegionArn_noSignerOverride_usesInterceptorSigner() { S3Client s3Client = clientBuilder().build(); s3Client.listObjects(ListObjectsRequest.builder() .bucket(MRAP_ARN) .build()); verifyRequest(AWS4A_SIGNING_ALGORITHM); } @Test public void multiRegionArn_clientSignerOverride_usesOverrideSigner() { S3Client s3Client = clientBuilderWithOverrideSigner(AwsS3V4Signer.create()).build(); s3Client.listObjects(ListObjectsRequest.builder() .bucket(MRAP_ARN) .build()); verifyRequest(SignerConstant.AWS4_SIGNING_ALGORITHM); } @Test public void multiRegionArn_requestSignerOverride_usesOverrideSigner() { S3Client s3Client = clientBuilder().build(); s3Client.listObjects(ListObjectsRequest.builder() .bucket(MRAP_ARN) .overrideConfiguration(s -> s.signer(AwsS3V4Signer.create())) .build()); verifyRequest(SignerConstant.AWS4_SIGNING_ALGORITHM); } @Test public void multiRegionArn_requestAndClientSignerOverride_usesRequestOverrideSigner() { S3Client s3Client = clientBuilderWithOverrideSigner(DefaultAwsCrtS3V4aSigner.create()).build(); s3Client.listObjects(ListObjectsRequest.builder() .bucket(MRAP_ARN) .overrideConfiguration(s -> s.signer(AwsS3V4Signer.create())) .build()); verifyRequest(SignerConstant.AWS4_SIGNING_ALGORITHM); } private void verifyRequest(String signingAlgorithm) { Map<String, List<String>> headers = mockHttpClient.getLastRequest().headers(); assertThat(headers.get("Authorization").get(0)).contains(signingAlgorithm); if (signingAlgorithm.equals(AWS4A_SIGNING_ALGORITHM)) { assertThat(headers.get("X-Amz-Region-Set").get(0)).isEqualTo(MRAP_SIGNING_SCOPE); } else { assertThat(headers.get("Authorization").get(0)).contains(Region.AP_SOUTH_1.id()); } } private S3ClientBuilder clientBuilder() { return S3Client.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid"))) .region(Region.AP_SOUTH_1) .httpClient((MockSyncHttpClient) mockHttpClient) .serviceConfiguration(S3Configuration.builder() .useArnRegionEnabled(true) .build()); } private S3ClientBuilder clientBuilderWithOverrideSigner(Signer signer) { return clientBuilder().overrideConfiguration(ClientOverrideConfiguration.builder() .putAdvancedOption(SdkAdvancedClientOption.SIGNER, signer) .build()); } }
4,393
0
Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3
Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/functionaltests/CompleteMultipartUploadFunctionalTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.functionaltests; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.any; import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import com.github.tomakehurst.wiremock.junit.WireMockRule; import java.net.URI; import java.util.concurrent.CompletionException; import org.junit.Rule; import org.junit.Test; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3AsyncClient; import software.amazon.awssdk.services.s3.S3AsyncClientBuilder; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.S3ClientBuilder; import software.amazon.awssdk.services.s3.model.CompleteMultipartUploadResponse; import software.amazon.awssdk.services.s3.model.S3Exception; public class CompleteMultipartUploadFunctionalTest { @Rule public WireMockRule wireMock = new WireMockRule(0); private S3ClientBuilder getSyncClientBuilder() { return S3Client.builder() .region(Region.US_EAST_1) .endpointOverride(URI.create("http://localhost:" + wireMock.port())) .credentialsProvider( StaticCredentialsProvider.create(AwsBasicCredentials.create("key", "secret"))); } private S3AsyncClientBuilder getAsyncClientBuilder() { return S3AsyncClient.builder() .region(Region.US_EAST_1) .endpointOverride(URI.create("http://localhost:" + wireMock.port())) .credentialsProvider( StaticCredentialsProvider.create(AwsBasicCredentials.create("key", "secret"))); } @Test public void completeMultipartUpload_syncClient_completeResponse() { String location = "http://Example-Bucket.s3.amazonaws.com/Example-Object"; String bucket = "Example-Bucket"; String key = "Example-Object"; String eTag = "\"3858f62230ac3c915f300c664312c11f-9\""; String xmlResponseBody = String.format( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<CompleteMultipartUploadResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">\n" + "<Location>%s</Location>\n" + "<Bucket>%s</Bucket>\n" + "<Key>%s</Key>\n" + "<ETag>%s</ETag>\n" + "</CompleteMultipartUploadResult>", location, bucket, key, eTag); stubFor(any(anyUrl()).willReturn(aResponse().withStatus(200).withBody(xmlResponseBody))); S3Client s3Client = getSyncClientBuilder().build(); CompleteMultipartUploadResponse response = s3Client.completeMultipartUpload( r -> r.bucket(bucket).key(key).uploadId("upload-id")); assertThat(response.location()).isEqualTo(location); assertThat(response.bucket()).isEqualTo(bucket); assertThat(response.key()).isEqualTo(key); assertThat(response.eTag()).isEqualTo(eTag); } @Test public void completeMultipartUpload_asyncClient_completeResponse() { String location = "http://Example-Bucket.s3.amazonaws.com/Example-Object"; String bucket = "Example-Bucket"; String key = "Example-Object"; String eTag = "\"3858f62230ac3c915f300c664312c11f-9\""; String xmlResponseBody = String.format( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<CompleteMultipartUploadResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">\n" + "<Location>%s</Location>\n" + "<Bucket>%s</Bucket>\n" + "<Key>%s</Key>\n" + "<ETag>%s</ETag>\n" + "</CompleteMultipartUploadResult>", location, bucket, key, eTag); stubFor(any(anyUrl()).willReturn(aResponse().withStatus(200).withBody(xmlResponseBody))); S3AsyncClient s3Client = getAsyncClientBuilder().build(); CompleteMultipartUploadResponse response = s3Client.completeMultipartUpload( r -> r.bucket(bucket).key(key).uploadId("upload-id")).join(); assertThat(response.location()).isEqualTo(location); assertThat(response.bucket()).isEqualTo(bucket); assertThat(response.key()).isEqualTo(key); assertThat(response.eTag()).isEqualTo(eTag); } @Test public void completeMultipartUpload_syncClient_errorInResponseBody_correctType() { String bucket = "Example-Bucket"; String key = "Example-Object"; String xmlResponseBody = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<Error>\n" + "<Code>InternalError</Code>\n" + "<Message>We encountered an internal error. Please try again.</Message>\n" + "<RequestId>656c76696e6727732072657175657374</RequestId>\n" + "<HostId>Uuag1LuByRx9e6j5Onimru9pO4ZVKnJ2Qz7/C1NPcfTWAtRPfTaOFg==</HostId>\n" + "</Error>"; stubFor(any(anyUrl()).willReturn(aResponse().withStatus(200).withBody(xmlResponseBody))); S3Client s3Client = getSyncClientBuilder().build(); assertThatThrownBy(() -> s3Client.completeMultipartUpload(r -> r.bucket(bucket) .key(key) .uploadId("upload-id"))) .isInstanceOf(S3Exception.class); } @Test public void completeMultipartUpload_asyncClient_errorInResponseBody_correctType() { String bucket = "Example-Bucket"; String key = "Example-Object"; String xmlResponseBody = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<Error>\n" + "<Code>InternalError</Code>\n" + "<Message>We encountered an internal error. Please try again.</Message>\n" + "<RequestId>656c76696e6727732072657175657374</RequestId>\n" + "<HostId>Uuag1LuByRx9e6j5Onimru9pO4ZVKnJ2Qz7/C1NPcfTWAtRPfTaOFg==</HostId>\n" + "</Error>"; stubFor(any(anyUrl()).willReturn(aResponse().withStatus(200).withBody(xmlResponseBody))); S3AsyncClient s3Client = getAsyncClientBuilder().build(); assertThatThrownBy(() -> s3Client.completeMultipartUpload(r -> r.bucket(bucket) .key(key) .uploadId("upload-id")) .join()) .isInstanceOf(CompletionException.class) .hasCauseInstanceOf(S3Exception.class); } @Test public void completeMultipartUpload_syncClient_errorInResponseBody_correctCode() { String bucket = "Example-Bucket"; String key = "Example-Object"; String xmlResponseBody = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<Error>\n" + "<Code>CustomError</Code>\n" + "<Message>We encountered an internal error. Please try again.</Message>\n" + "<RequestId>656c76696e6727732072657175657374</RequestId>\n" + "<HostId>Uuag1LuByRx9e6j5Onimru9pO4ZVKnJ2Qz7/C1NPcfTWAtRPfTaOFg==</HostId>\n" + "</Error>"; stubFor(any(anyUrl()).willReturn(aResponse().withStatus(200).withBody(xmlResponseBody))); S3Client s3Client = getSyncClientBuilder().build(); assertThatThrownBy(() -> s3Client.completeMultipartUpload(r -> r.bucket(bucket) .key(key) .uploadId("upload-id"))) .satisfies(e -> assertThat(((S3Exception)e).awsErrorDetails().errorCode()).isEqualTo("CustomError")); } @Test public void completeMultipartUpload_asyncClient_errorInResponseBody_correctCode() { String bucket = "Example-Bucket"; String key = "Example-Object"; String xmlResponseBody = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<Error>\n" + "<Code>CustomError</Code>\n" + "<Message>We encountered an internal error. Please try again.</Message>\n" + "<RequestId>656c76696e6727732072657175657374</RequestId>\n" + "<HostId>Uuag1LuByRx9e6j5Onimru9pO4ZVKnJ2Qz7/C1NPcfTWAtRPfTaOFg==</HostId>\n" + "</Error>"; stubFor(any(anyUrl()).willReturn(aResponse().withStatus(200).withBody(xmlResponseBody))); S3AsyncClient s3Client = getAsyncClientBuilder().build(); assertThatThrownBy(() -> s3Client.completeMultipartUpload(r -> r.bucket(bucket) .key(key) .uploadId("upload-id")) .join()) .satisfies(e -> { S3Exception s3Exception = (S3Exception) e.getCause(); assertThat(s3Exception.awsErrorDetails().errorCode()).isEqualTo("CustomError"); }); } @Test public void completeMultipartUpload_syncClient_errorInResponseBody_correctMessage() { String bucket = "Example-Bucket"; String key = "Example-Object"; String xmlResponseBody = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<Error>\n" + "<Code>CustomError</Code>\n" + "<Message>Foo bar</Message>\n" + "<RequestId>656c76696e6727732072657175657374</RequestId>\n" + "<HostId>Uuag1LuByRx9e6j5Onimru9pO4ZVKnJ2Qz7/C1NPcfTWAtRPfTaOFg==</HostId>\n" + "</Error>"; stubFor(any(anyUrl()).willReturn(aResponse().withStatus(200).withBody(xmlResponseBody))); S3Client s3Client = getSyncClientBuilder().build(); assertThatThrownBy(() -> s3Client.completeMultipartUpload(r -> r.bucket(bucket) .key(key) .uploadId("upload-id"))) .satisfies(e -> assertThat(((S3Exception)e).awsErrorDetails().errorMessage()).isEqualTo("Foo bar")); } @Test public void completeMultipartUpload_asyncClient_errorInResponseBody_correctMessage() { String bucket = "Example-Bucket"; String key = "Example-Object"; String xmlResponseBody = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<Error>\n" + "<Code>CustomError</Code>\n" + "<Message>Foo bar</Message>\n" + "<RequestId>656c76696e6727732072657175657374</RequestId>\n" + "<HostId>Uuag1LuByRx9e6j5Onimru9pO4ZVKnJ2Qz7/C1NPcfTWAtRPfTaOFg==</HostId>\n" + "</Error>"; stubFor(any(anyUrl()).willReturn(aResponse().withStatus(200).withBody(xmlResponseBody))); S3AsyncClient s3Client = getAsyncClientBuilder().build(); assertThatThrownBy(() -> s3Client.completeMultipartUpload(r -> r.bucket(bucket) .key(key) .uploadId("upload-id")) .join()) .satisfies(e -> { S3Exception s3Exception = (S3Exception) e.getCause(); assertThat(s3Exception.awsErrorDetails().errorMessage()).isEqualTo("Foo bar"); }); } @Test public void completeMultipartUpload_syncClient_errorInResponseBody_invalidErrorXml() { String bucket = "Example-Bucket"; String key = "Example-Object"; String xmlResponseBody = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<Error>\n" + "<SomethingWeird></SomethingWeird>" + "</Error>"; stubFor(any(anyUrl()).willReturn(aResponse().withStatus(200).withBody(xmlResponseBody))); S3Client s3Client = getSyncClientBuilder().build(); assertThatThrownBy(() -> s3Client.completeMultipartUpload(r -> r.bucket(bucket) .key(key) .uploadId("upload-id"))) .isInstanceOf(S3Exception.class); } @Test public void completeMultipartUpload_asyncClient_errorInResponseBody_invalidErrorXml() { String bucket = "Example-Bucket"; String key = "Example-Object"; String xmlResponseBody = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<Error>\n" + "<SomethingWeird></SomethingWeird>" + "</Error>"; stubFor(any(anyUrl()).willReturn(aResponse().withStatus(200).withBody(xmlResponseBody))); S3AsyncClient s3Client = getAsyncClientBuilder().build(); assertThatThrownBy(() -> s3Client.completeMultipartUpload(r -> r.bucket(bucket) .key(key) .uploadId("upload-id")) .join()) .isInstanceOf(CompletionException.class) .hasCauseInstanceOf(S3Exception.class); } }
4,394
0
Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3
Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/functionaltests/SelectObjectContentTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.functionaltests; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.any; import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static org.assertj.core.api.Assertions.assertThat; import com.github.tomakehurst.wiremock.junit.WireMockRule; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.UncheckedIOException; import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.async.SdkPublisher; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3AsyncClient; import software.amazon.awssdk.services.s3.model.CSVInput; import software.amazon.awssdk.services.s3.model.CSVOutput; import software.amazon.awssdk.services.s3.model.CompressionType; import software.amazon.awssdk.services.s3.model.ContinuationEvent; import software.amazon.awssdk.services.s3.model.EndEvent; import software.amazon.awssdk.services.s3.model.ExpressionType; import software.amazon.awssdk.services.s3.model.InputSerialization; import software.amazon.awssdk.services.s3.model.OutputSerialization; import software.amazon.awssdk.services.s3.model.Progress; import software.amazon.awssdk.services.s3.model.ProgressEvent; import software.amazon.awssdk.services.s3.model.RecordsEvent; import software.amazon.awssdk.services.s3.model.SelectObjectContentEventStream; import software.amazon.awssdk.services.s3.model.SelectObjectContentRequest; import software.amazon.awssdk.services.s3.model.SelectObjectContentResponse; import software.amazon.awssdk.services.s3.model.SelectObjectContentResponseHandler; import software.amazon.awssdk.services.s3.model.Stats; import software.amazon.awssdk.services.s3.model.StatsEvent; import software.amazon.eventstream.HeaderValue; import software.amazon.eventstream.Message; public class SelectObjectContentTest { private static final AwsCredentialsProvider TEST_CREDENTIALS = StaticCredentialsProvider.create(AwsBasicCredentials.create( "akid", "skid")); private static final Region TEST_REGION = Region.US_WEST_2; private S3AsyncClient s3; @Rule public WireMockRule wireMock = new WireMockRule(0); @Before public void setup() { s3 = S3AsyncClient.builder() .endpointOverride(URI.create("http://localhost:" + wireMock.port())) .serviceConfiguration(c -> c.pathStyleAccessEnabled(true)) .region(TEST_REGION) .credentialsProvider(TEST_CREDENTIALS) .build(); } @After public void teardown() { s3.close(); } @Test public void selectObjectContent_canUnmarshallAllEvents() { List<SelectObjectContentEventStream> events = Arrays.asList( SelectObjectContentEventStream.recordsBuilder().payload(SdkBytes.fromUtf8String("abc")).build(), SelectObjectContentEventStream.contBuilder().build(), SelectObjectContentEventStream.statsBuilder() .details(Stats.builder() .bytesProcessed(1L) .bytesScanned(2L) .bytesReturned(3L) .build() ).build(), SelectObjectContentEventStream.progressBuilder() .details(Progress.builder() .bytesProcessed(1L) .bytesScanned(2L) .bytesReturned(3L) .build() ).build(), SelectObjectContentEventStream.endBuilder().build() ); byte[] eventStream = encodedEvents(events); stubFor(any(anyUrl()).willReturn(aResponse().withStatus(200).withBody(eventStream))); TestHandler testHandler = new TestHandler(); runSimpleQuery(s3, testHandler).join(); assertThat(testHandler.receivedEvents).isEqualTo(events); } private byte[] encodedEvents(List<SelectObjectContentEventStream> events) { ByteArrayOutputStream eventStreamBytes = new ByteArrayOutputStream(); MarshallingVisitor marshaller = new MarshallingVisitor(); events.stream() .map(e -> { marshaller.reset(); e.accept(marshaller); Map<String, HeaderValue> headers = new HashMap<>(); headers.put(":message-type", HeaderValue.fromString("event")); headers.put(":event-type", HeaderValue.fromString(e.sdkEventType().toString())); return new Message(headers, marshaller.marshalledBytes()); }) .forEach(m -> m.encode(eventStreamBytes)); return eventStreamBytes.toByteArray(); } private static class MarshallingVisitor implements SelectObjectContentResponseHandler.Visitor { private final ByteArrayOutputStream baos = new ByteArrayOutputStream(); @Override public void visitEnd(EndEvent event) { // no payload } @Override public void visitCont(ContinuationEvent event) { // no payload } @Override public void visitRecords(RecordsEvent event) { writeUnchecked(event.payload().asByteArray()); } @Override public void visitStats(StatsEvent event) { Stats details = event.details(); writeUnchecked(bytes("<Details>")); writeUnchecked(bytes("<BytesScanned>")); writeUnchecked(bytes(details.bytesScanned().toString())); writeUnchecked(bytes("</BytesScanned>")); writeUnchecked(bytes("<BytesProcessed>")); writeUnchecked(bytes(details.bytesProcessed().toString())); writeUnchecked(bytes("</BytesProcessed>")); writeUnchecked(bytes("<BytesReturned>")); writeUnchecked(bytes(details.bytesReturned().toString())); writeUnchecked(bytes("</BytesReturned>")); writeUnchecked(bytes("</Details>")); } @Override public void visitProgress(ProgressEvent event) { Progress details = event.details(); writeUnchecked(bytes("<Details>")); writeUnchecked(bytes("<BytesScanned>")); writeUnchecked(bytes(details.bytesScanned().toString())); writeUnchecked(bytes("</BytesScanned>")); writeUnchecked(bytes("<BytesProcessed>")); writeUnchecked(bytes(details.bytesProcessed().toString())); writeUnchecked(bytes("</BytesProcessed>")); writeUnchecked(bytes("<BytesReturned>")); writeUnchecked(bytes(details.bytesReturned().toString())); writeUnchecked(bytes("</BytesReturned>")); writeUnchecked(bytes("</Details>")); } public byte[] marshalledBytes() { return baos.toByteArray(); } public void reset() { baos.reset(); } private void writeUnchecked(byte[] data) { try { baos.write(data); } catch (IOException e) { throw new UncheckedIOException(e); } } } private static byte[] bytes(String s) { return s.getBytes(StandardCharsets.UTF_8); } private static CompletableFuture<Void> runSimpleQuery(S3AsyncClient s3, SelectObjectContentResponseHandler handler) { InputSerialization inputSerialization = InputSerialization.builder() .csv(CSVInput.builder().build()) .compressionType(CompressionType.NONE) .build(); OutputSerialization outputSerialization = OutputSerialization.builder() .csv(CSVOutput.builder().build()) .build(); SelectObjectContentRequest select = SelectObjectContentRequest.builder() .bucket("test-bucket") .key("test-key") .expression("test-query") .expressionType(ExpressionType.SQL) .inputSerialization(inputSerialization) .outputSerialization(outputSerialization) .build(); return s3.selectObjectContent(select, handler); } private static class TestHandler implements SelectObjectContentResponseHandler { private List<SelectObjectContentEventStream> receivedEvents = new ArrayList<>(); @Override public void responseReceived(SelectObjectContentResponse response) { } @Override public void onEventStream(SdkPublisher<SelectObjectContentEventStream> publisher) { publisher.subscribe(receivedEvents::add); } @Override public void exceptionOccurred(Throwable throwable) { } @Override public void complete() { } } }
4,395
0
Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3
Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/functionaltests/PutObjectWithChecksumTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.functionaltests; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.any; import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl; import static com.github.tomakehurst.wiremock.client.WireMock.containing; import static com.github.tomakehurst.wiremock.client.WireMock.putRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.verify; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import com.github.tomakehurst.wiremock.junit5.WireMockRuntimeInfo; import com.github.tomakehurst.wiremock.junit5.WireMockTest; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.function.Function; import java.util.stream.Collectors; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.core.exception.RetryableException; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3AsyncClient; import software.amazon.awssdk.services.s3.S3AsyncClientBuilder; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.S3ClientBuilder; import software.amazon.awssdk.services.s3.model.ChecksumAlgorithm; import software.amazon.awssdk.services.s3.model.PutObjectRequest; import software.amazon.awssdk.services.s3.model.PutObjectResponse; import software.amazon.awssdk.services.s3.utils.CaptureChecksumValidationInterceptor; @WireMockTest public class PutObjectWithChecksumTest { String CONTENT = "Hello, World!"; String INCORRECT_ETAG = "65A8E27D8879283831B664BD8B7F0AD5"; String ETAG = "65A8E27D8879283831B664BD8B7F0AD4"; public static final Function<InputStream, String> stringFromStream = inputStream -> new BufferedReader( new InputStreamReader(inputStream, StandardCharsets.UTF_8)).lines().collect(Collectors.joining("\n")); private static final String BUCKET = "Example-Bucket"; private static final String EXAMPLE_RESPONSE_BODY = "Hello world"; private final CaptureChecksumValidationInterceptor captureChecksumValidationInterceptor = new CaptureChecksumValidationInterceptor(); private S3ClientBuilder getSyncClientBuilder(WireMockRuntimeInfo wm) { return S3Client.builder() .region(Region.US_EAST_1) .endpointOverride(URI.create(wm.getHttpBaseUrl())) .credentialsProvider( StaticCredentialsProvider.create(AwsBasicCredentials.create("key", "secret"))); } @AfterEach public void reset() { captureChecksumValidationInterceptor.reset(); } private S3AsyncClientBuilder getAsyncClientBuilder(WireMockRuntimeInfo wm) { return S3AsyncClient.builder() .region(Region.US_EAST_1) .endpointOverride(URI.create(wm.getHttpBaseUrl())) .credentialsProvider( StaticCredentialsProvider.create(AwsBasicCredentials.create("key", "secret"))); } // Exception is thrown means the default Md5 validation has taken place. @Test void sync_putObject_default_MD5_validation_withIncorrectChecksum(WireMockRuntimeInfo wm) { stubFor(any(anyUrl()).willReturn(aResponse().withStatus(200) .withHeader("x-amz-checksum-crc32", "i9aeUg==") .withHeader("etag", INCORRECT_ETAG))); S3Client s3Client = getSyncClientBuilder(wm).overrideConfiguration(o -> o.addExecutionInterceptor(captureChecksumValidationInterceptor)).build(); PutObjectRequest putObjectRequest = PutObjectRequest.builder().bucket(BUCKET).key("KEY").build(); RequestBody requestBody = RequestBody.fromBytes(CONTENT.getBytes()); assertThatExceptionOfType(RetryableException.class) .isThrownBy(() -> s3Client.putObject(putObjectRequest, requestBody)) .withMessage("Data read has a different checksum than expected. Was 0x" + ETAG.toLowerCase() + ", but expected 0x" + INCORRECT_ETAG.toLowerCase() + ". This commonly means that the data was corrupted between the client " + "and service. Note: Despite this error, the upload still completed and was persisted in S3."); assertThat(captureChecksumValidationInterceptor.validationAlgorithm()).isNull(); } @Test void sync_putObject_default_MD5_validation_withCorrectChecksum(WireMockRuntimeInfo wm) { stubFor(any(anyUrl()).willReturn(aResponse().withStatus(200) .withHeader("x-amz-checksum-crc32", "WRONG_CHECKSUM") .withHeader("etag", ETAG))); S3Client s3Client = getSyncClientBuilder(wm).overrideConfiguration(o -> o.addExecutionInterceptor(captureChecksumValidationInterceptor)) .build(); PutObjectResponse putObjectResponse = s3Client.putObject(b -> b.bucket(BUCKET) .key("KEY"), RequestBody.fromBytes(CONTENT.getBytes())); assertThat(putObjectResponse.eTag()).isEqualTo(ETAG); assertThat(captureChecksumValidationInterceptor.validationAlgorithm()).isNull(); } // Exception is thrown means the default Md5 validation has taken place. @Test void async_putObject_default_MD5_validation_withIncorrectChecksum(WireMockRuntimeInfo wm) { stubFor(any(anyUrl()).willReturn(aResponse().withStatus(200) .withHeader("x-amz-checksum-crc32", "i9aeUg==") .withHeader("etag", INCORRECT_ETAG))); S3Client s3Client = getSyncClientBuilder(wm).overrideConfiguration(o -> o.addExecutionInterceptor(captureChecksumValidationInterceptor)).build(); PutObjectRequest putObjectRequest = PutObjectRequest.builder().bucket(BUCKET).key("KEY").build(); RequestBody requestBody = RequestBody.fromBytes(CONTENT.getBytes()); assertThatExceptionOfType(RetryableException.class) .isThrownBy(() -> s3Client.putObject(putObjectRequest, requestBody)) .withMessage("Data read has a different checksum than expected. Was 0x" + ETAG.toLowerCase() + ", but expected 0x" + INCORRECT_ETAG.toLowerCase() + ". This commonly means that the data was corrupted between the client " + "and service. Note: Despite this error, the upload still completed and was persisted in S3."); assertThat(captureChecksumValidationInterceptor.validationAlgorithm()).isNull(); } @Test void async_putObject_default_MD5_validation_withCorrectChecksum(WireMockRuntimeInfo wm) { stubFor(any(anyUrl()).willReturn(aResponse().withStatus(200) .withHeader("x-amz-checksum-crc32", "WRONG_CHECKSUM") .withHeader("etag", ETAG))); S3AsyncClient s3Async = getAsyncClientBuilder(wm).overrideConfiguration(o -> o.addExecutionInterceptor(captureChecksumValidationInterceptor)).build(); PutObjectResponse putObjectResponse = s3Async.putObject(PutObjectRequest.builder() .bucket(BUCKET) .key("KEY") .build(), AsyncRequestBody.fromString(CONTENT)).join(); assertThat(putObjectResponse.eTag()).isEqualTo(ETAG); assertThat(captureChecksumValidationInterceptor.requestChecksumInTrailer()).isNull(); } // Even with incorrect Etag, exception is not thrown because default check is skipped when checksumAlgorithm is set @Test void sync_putObject_httpChecksumValidation_withIncorrectChecksum(WireMockRuntimeInfo wm) { stubFor(any(anyUrl()).willReturn(aResponse().withStatus(200) .withHeader("x-amz-checksum-crc32", "7ErD0A==") .withHeader("etag", INCORRECT_ETAG))); S3Client s3Client = getSyncClientBuilder(wm).overrideConfiguration(o -> o.addExecutionInterceptor(captureChecksumValidationInterceptor)).build(); s3Client.putObject(b -> b.bucket(BUCKET).key("KEY").checksumAlgorithm(ChecksumAlgorithm.CRC32), RequestBody.fromBytes(CONTENT.getBytes())); assertThat(captureChecksumValidationInterceptor.validationAlgorithm()).isNull(); assertThat(captureChecksumValidationInterceptor.requestChecksumInTrailer()).isEqualTo("x-amz-checksum-crc32"); verify(putRequestedFor(anyUrl()).withRequestBody(containing("Hello, World!")) .withRequestBody(containing("x-amz-checksum-crc32:7ErD0A==")) .withRequestBody(containing("0;"))); } // Even with incorrect Etag, exception is not thrown because default check is skipped when checksumAlgorithm is set @Test void async_putObject_httpChecksumValidation_withIncorrectChecksum(WireMockRuntimeInfo wm) { stubFor(any(anyUrl()).willReturn(aResponse().withStatus(200) .withHeader("x-amz-checksum-crc32", "7ErD0A==") .withHeader("etag", INCORRECT_ETAG))); S3AsyncClient s3Async = getAsyncClientBuilder(wm).overrideConfiguration(o -> o.addExecutionInterceptor(captureChecksumValidationInterceptor)).build(); s3Async.putObject(PutObjectRequest.builder().bucket(BUCKET).checksumAlgorithm(ChecksumAlgorithm.CRC32).key("KEY").build(), AsyncRequestBody.fromString(CONTENT)).join(); assertThat(captureChecksumValidationInterceptor.validationAlgorithm()).isNull(); assertThat(captureChecksumValidationInterceptor.requestChecksumInTrailer()).isEqualTo("x-amz-checksum-crc32"); verify(putRequestedFor(anyUrl()).withRequestBody(containing("x-amz-checksum-crc32:7ErD0A==")) .withRequestBody(containing("Hello, World!"))); } }
4,396
0
Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3
Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/functionaltests/ContentLengthMismatchTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.functionaltests; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.any; import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl; import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; import static com.github.tomakehurst.wiremock.client.WireMock.putRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.verify; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import com.github.tomakehurst.wiremock.junit.WireMockRule; import java.net.URI; import java.nio.ByteBuffer; import java.util.Optional; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import org.junit.Rule; import org.junit.Test; import org.reactivestreams.Subscriber; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3AsyncClient; import software.amazon.awssdk.services.s3.S3AsyncClientBuilder; import software.amazon.awssdk.services.s3.model.PutObjectResponse; public class ContentLengthMismatchTest { @Rule public WireMockRule wireMock = new WireMockRule(0); private S3AsyncClientBuilder getAsyncClientBuilder() { return S3AsyncClient.builder() .region(Region.US_EAST_1) .endpointOverride(endpoint()) .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("key", "secret"))); } private URI endpoint() { return URI.create("http://localhost:" + wireMock.port()); } @Test public void checksumDoesNotExceedContentLengthHeaderForPuts() { String bucket = "Example-Bucket"; String key = "Example-Object"; String content = "Hello, World!"; String eTag = "65A8E27D8879283831B664BD8B7F0AD4"; stubFor(any(anyUrl()).willReturn(aResponse().withStatus(200).withHeader("ETag", eTag))); S3AsyncClient s3Client = getAsyncClientBuilder().build(); PutObjectResponse response = s3Client.putObject(r -> r.bucket(bucket).key(key).contentLength((long) content.length()), AsyncRequestBody.fromString(content + " Extra stuff!")) .join(); verify(putRequestedFor(anyUrl()).withRequestBody(equalTo(content))); assertThat(response.eTag()).isEqualTo(eTag); } @Test public void checksumDoesNotExceedAsyncRequestBodyLengthForPuts() { String bucket = "Example-Bucket"; String key = "Example-Object"; String content = "Hello, World!"; String eTag = "65A8E27D8879283831B664BD8B7F0AD4"; stubFor(any(anyUrl()).willReturn(aResponse().withStatus(200).withHeader("ETag", eTag))); S3AsyncClient s3Client = getAsyncClientBuilder().build(); PutObjectResponse response = s3Client.putObject(r -> r.bucket(bucket).key(key), new AsyncRequestBody() { @Override public Optional<Long> contentLength() { return Optional.of((long) content.length()); } @Override public void subscribe(Subscriber<? super ByteBuffer> subscriber) { AsyncRequestBody.fromString(content + " Extra stuff!").subscribe(subscriber); } }) .join(); verify(putRequestedFor(anyUrl()).withRequestBody(equalTo(content))); assertThat(response.eTag()).isEqualTo(eTag); } @Test public void contentShorterThanContentLengthHeaderFails() { String bucket = "Example-Bucket"; String key = "Example-Object"; S3AsyncClient s3Client = getAsyncClientBuilder().build(); AsyncRequestBody requestBody = new AsyncRequestBody() { @Override public Optional<Long> contentLength() { return Optional.empty(); } @Override public void subscribe(Subscriber<? super ByteBuffer> subscriber) { AsyncRequestBody.fromString("A").subscribe(subscriber); } }; assertThatThrownBy(() -> s3Client.putObject(r -> r.bucket(bucket).key(key).contentLength(2L), requestBody) .get(10, TimeUnit.SECONDS)) .isInstanceOf(ExecutionException.class) .hasMessageContaining("content-length"); } @Test public void contentShorterThanRequestBodyLengthFails() { String bucket = "Example-Bucket"; String key = "Example-Object"; S3AsyncClient s3Client = getAsyncClientBuilder().build(); AsyncRequestBody requestBody = new AsyncRequestBody() { @Override public Optional<Long> contentLength() { return Optional.of(2L); } @Override public void subscribe(Subscriber<? super ByteBuffer> subscriber) { AsyncRequestBody.fromString("A").subscribe(subscriber); } }; assertThatThrownBy(() -> s3Client.putObject(r -> r.bucket(bucket).key(key), requestBody) .get(10, TimeUnit.SECONDS)) .isInstanceOf(ExecutionException.class) .hasMessageContaining("content-length"); } }
4,397
0
Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3
Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal/ClientDecorationFactoryTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal; import static org.assertj.core.api.Assertions.assertThat; import java.util.function.Consumer; import java.util.stream.Stream; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import software.amazon.awssdk.services.s3.S3AsyncClient; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.endpoints.S3ClientContextParams; import software.amazon.awssdk.services.s3.internal.client.S3AsyncClientDecorator; import software.amazon.awssdk.services.s3.internal.client.S3SyncClientDecorator; import software.amazon.awssdk.services.s3.internal.crossregion.S3CrossRegionAsyncClient; import software.amazon.awssdk.services.s3.internal.crossregion.S3CrossRegionSyncClient; import software.amazon.awssdk.utils.AttributeMap; public class ClientDecorationFactoryTest { AttributeMap.Builder clientContextParams = AttributeMap.builder(); @ParameterizedTest @MethodSource("syncTestCases") void syncClientTest(AttributeMap clientContextParams, Class<Object> clazz, boolean isClass) { S3SyncClientDecorator decorator = new S3SyncClientDecorator(); S3Client decorateClient = decorator.decorate(S3Client.create(), null, clientContextParams); if (isClass) { assertThat(decorateClient).isInstanceOf(clazz); } else { assertThat(decorateClient).isNotInstanceOf(clazz); } } @ParameterizedTest @MethodSource("asyncTestCases") void asyncClientTest(AttributeMap clientContextParams, Class<Object> clazz, boolean isClass) { S3AsyncClientDecorator decorator = new S3AsyncClientDecorator(); S3AsyncClient decoratedClient = decorator.decorate(S3AsyncClient.create(), null ,clientContextParams); if (isClass) { assertThat(decoratedClient).isInstanceOf(clazz); } else { assertThat(decoratedClient).isNotInstanceOf(clazz); } } private static Stream<Arguments> syncTestCases() { return Stream.of( Arguments.of(AttributeMap.builder().build(), S3CrossRegionSyncClient.class, false), Arguments.of(AttributeMap.builder().put(S3ClientContextParams.CROSS_REGION_ACCESS_ENABLED, false).build(), S3CrossRegionSyncClient.class, false), Arguments.of(AttributeMap.builder().put(S3ClientContextParams.CROSS_REGION_ACCESS_ENABLED, true).build(), S3CrossRegionSyncClient.class, true) ); } private static Stream<Arguments> asyncTestCases() { return Stream.of( Arguments.of(AttributeMap.builder().build(), S3CrossRegionAsyncClient.class, false), Arguments.of(AttributeMap.builder().put(S3ClientContextParams.CROSS_REGION_ACCESS_ENABLED, false).build(), S3CrossRegionAsyncClient.class, false), Arguments.of(AttributeMap.builder().put(S3ClientContextParams.CROSS_REGION_ACCESS_ENABLED, true).build() , S3CrossRegionAsyncClient.class, true) ); } }
4,398
0
Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal/endpoints/S3EndpointUtilsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.endpoints; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import java.net.URI; import org.junit.jupiter.api.Test; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.services.s3.S3Configuration; import software.amazon.awssdk.services.s3.model.ListBucketsRequest; import software.amazon.awssdk.services.s3.model.PutObjectRequest; public class S3EndpointUtilsTest { @Test public void removesFipsIfNeeded() { assertThat(S3EndpointUtils.removeFipsIfNeeded("fips-us-east-1")).isEqualTo("us-east-1"); assertThat(S3EndpointUtils.removeFipsIfNeeded("us-east-1-fips")).isEqualTo("us-east-1"); } @Test public void isFipsRegion() { assertTrue(S3EndpointUtils.isFipsRegion("fips-us-east-1")); assertTrue(S3EndpointUtils.isFipsRegion("us-east-1-fips")); assertFalse(S3EndpointUtils.isFipsRegion("us-fips-1")); } @Test public void isAccelerateEnabled() { assertFalse(S3EndpointUtils.isAccelerateEnabled(S3Configuration.builder().build())); assertFalse(S3EndpointUtils.isAccelerateEnabled(null)); assertFalse(S3EndpointUtils.isAccelerateEnabled(S3Configuration.builder().accelerateModeEnabled(false).build())); assertTrue(S3EndpointUtils.isAccelerateEnabled(S3Configuration.builder().accelerateModeEnabled(true).build())); } @Test public void isAccelerateSupported() { assertFalse(S3EndpointUtils.isAccelerateSupported(ListBucketsRequest.builder().build())); assertTrue(S3EndpointUtils.isAccelerateSupported(PutObjectRequest.builder().build())); } @Test public void accelerateEndpoint() { assertThat(S3EndpointUtils.accelerateEndpoint("domain", "https")) .isEqualTo(URI.create("https://s3-accelerate.domain")); assertThat(S3EndpointUtils.accelerateDualstackEndpoint("domain", "https")) .isEqualTo(URI.create("https://s3-accelerate.dualstack.domain")); } @Test public void isDualstackEnabled() { assertFalse(S3EndpointUtils.isDualstackEnabled(S3Configuration.builder().build())); assertFalse(S3EndpointUtils.isDualstackEnabled(null)); assertFalse(S3EndpointUtils.isDualstackEnabled(S3Configuration.builder().dualstackEnabled(false).build())); assertTrue(S3EndpointUtils.isDualstackEnabled(S3Configuration.builder().dualstackEnabled(true).build())); } @Test public void dualStackEndpoint() { assertThat(S3EndpointUtils.dualstackEndpoint("id", "domain", "https")) .isEqualTo(URI.create("https://s3.dualstack.id.domain")); } @Test public void isPathstyleAccessEnabled() { assertFalse(S3EndpointUtils.isPathStyleAccessEnabled(S3Configuration.builder().build())); assertFalse(S3EndpointUtils.isPathStyleAccessEnabled(null)); assertFalse(S3EndpointUtils.isPathStyleAccessEnabled(S3Configuration.builder().pathStyleAccessEnabled(false).build())); assertTrue(S3EndpointUtils.isPathStyleAccessEnabled(S3Configuration.builder().pathStyleAccessEnabled(true).build())); } @Test public void isArnRegionEnabled() { assertFalse(S3EndpointUtils.isArnRegionEnabled(S3Configuration.builder().build())); assertFalse(S3EndpointUtils.isArnRegionEnabled(null)); assertFalse(S3EndpointUtils.isArnRegionEnabled(S3Configuration.builder().useArnRegionEnabled(false).build())); assertTrue(S3EndpointUtils.isArnRegionEnabled(S3Configuration.builder().useArnRegionEnabled(true).build())); } @Test public void changeToDnsEndpoint() { SdkHttpRequest.Builder mutableRequest = SdkHttpFullRequest.builder().host("s3").encodedPath("/test-bucket"); S3EndpointUtils.changeToDnsEndpoint(mutableRequest, "test-bucket"); assertThat(mutableRequest.host()).isEqualTo("test-bucket.s3"); assertThat(mutableRequest.encodedPath()).isEqualTo(""); } @Test public void isArn() { assertFalse(S3EndpointUtils.isArn("bucketName")); assertFalse(S3EndpointUtils.isArn("test:arn:")); assertTrue(S3EndpointUtils.isArn("arn:test")); } }
4,399