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/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/CopyRequest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.transfer.s3.model;
import static software.amazon.awssdk.utils.Validate.paramNotNull;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
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.services.s3.model.CopyObjectRequest;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.transfer.s3.progress.TransferListener;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* Creates a copy of an object that is already stored in S3.
*
* @see S3TransferManager#copy(CopyRequest)
*/
@SdkPublicApi
public final class CopyRequest
implements TransferObjectRequest,
ToCopyableBuilder<CopyRequest.Builder, CopyRequest> {
private final CopyObjectRequest copyObjectRequest;
private final List<TransferListener> transferListeners;
private CopyRequest(DefaultBuilder builder) {
this.copyObjectRequest = paramNotNull(builder.copyObjectRequest, "copyObjectRequest");
this.transferListeners = builder.transferListeners;
}
/**
* @return The {@link CopyObjectRequest} request that should be used for the copy
*/
public CopyObjectRequest copyObjectRequest() {
return copyObjectRequest;
}
/**
* @return the List of transferListener.
* @see Builder#transferListeners(Collection)
*/
@Override
public List<TransferListener> transferListeners() {
return transferListeners;
}
/**
* Creates a builder that can be used to create a {@link CopyRequest}.
*
* @see S3TransferManager#copy(CopyRequest)
*/
public static Builder builder() {
return new DefaultBuilder();
}
public static Class<? extends Builder> serializableBuilderClass() {
return DefaultBuilder.class;
}
@Override
public Builder toBuilder() {
return new DefaultBuilder(this);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CopyRequest that = (CopyRequest) o;
if (!Objects.equals(copyObjectRequest, that.copyObjectRequest)) {
return false;
}
return Objects.equals(transferListeners, that.transferListeners);
}
@Override
public int hashCode() {
int result = copyObjectRequest != null ? copyObjectRequest.hashCode() : 0;
result = 31 * result + (transferListeners != null ? transferListeners.hashCode() : 0);
return result;
}
@Override
public String toString() {
return ToString.builder("CopyRequest")
.add("copyRequest", copyObjectRequest)
.add("transferListeners", transferListeners)
.build();
}
/**
* A builder for a {@link CopyRequest}, created with {@link #builder()}
*/
@SdkPublicApi
@NotThreadSafe
public interface Builder extends CopyableBuilder<Builder, CopyRequest> {
/**
* Configures the {@link CopyRequest} that should be used for the copy
*
* @param copyRequest the copyRequest
* @return Returns a reference to this object so that method calls can be chained together.
* @see #copyObjectRequest(Consumer)
*/
Builder copyObjectRequest(CopyObjectRequest copyRequest);
/**
* Configures the {@link CopyRequest} that should be used for the copy
*
* <p>
* This is a convenience method that creates an instance of the {@link CopyRequest} builder avoiding the need to create
* one manually via {@link CopyRequest#builder()}.
*
* @param copyRequestBuilder the copyRequest consumer builder
* @return Returns a reference to this object so that method calls can be chained together.
* @see #copyObjectRequest(CopyObjectRequest)
*/
default Builder copyObjectRequest(Consumer<CopyObjectRequest.Builder> copyRequestBuilder) {
return copyObjectRequest(CopyObjectRequest.builder()
.applyMutation(copyRequestBuilder)
.build());
}
/**
* The {@link TransferListener}s that will be notified as part of this request. This method overrides and replaces any
* transferListeners that have already been set. Add an optional request override configuration.
*
* @param transferListeners the collection of transferListeners
* @return Returns a reference to this object so that method calls can be chained together.
* @return This builder for method chaining.
* @see TransferListener
*/
Builder transferListeners(Collection<TransferListener> transferListeners);
/**
* Adds a {@link TransferListener} that will be notified as part of this request.
*
* @param transferListener the transferListener to add
* @return Returns a reference to this object so that method calls can be chained together.
* @see TransferListener
*/
Builder addTransferListener(TransferListener transferListener);
/**
* @return The built request.
*/
@Override
CopyRequest build();
}
private static class DefaultBuilder implements Builder {
private CopyObjectRequest copyObjectRequest;
private List<TransferListener> transferListeners;
private DefaultBuilder() {
}
private DefaultBuilder(CopyRequest copyRequest) {
this.copyObjectRequest = copyRequest.copyObjectRequest;
this.transferListeners = copyRequest.transferListeners;
}
@Override
public Builder copyObjectRequest(CopyObjectRequest copyRequest) {
this.copyObjectRequest = copyRequest;
return this;
}
public CopyObjectRequest getCopyObjectRequest() {
return copyObjectRequest;
}
public void setCopyObjectRequest(CopyObjectRequest copyObjectRequest) {
copyObjectRequest(copyObjectRequest);
}
@Override
public DefaultBuilder transferListeners(Collection<TransferListener> transferListeners) {
this.transferListeners = transferListeners != null ? new ArrayList<>(transferListeners) : null;
return this;
}
@Override
public DefaultBuilder addTransferListener(TransferListener transferListener) {
if (transferListeners == null) {
transferListeners = new ArrayList<>();
}
transferListeners.add(transferListener);
return this;
}
public List<TransferListener> getTransferListeners() {
return transferListeners;
}
public void setTransferListeners(Collection<TransferListener> transferListeners) {
transferListeners(transferListeners);
}
@Override
public CopyRequest build() {
return new CopyRequest(this);
}
}
}
| 3,800 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/DownloadRequest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.transfer.s3.model;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.async.AsyncResponseTransformer;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.transfer.s3.model.DownloadRequest.TypedBuilder;
import software.amazon.awssdk.transfer.s3.progress.TransferListener;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* Represents the request to download an object identified by the bucket and key from S3 through the given
* {@link AsyncResponseTransformer}. For
* downloading to a file, you may use {@link DownloadFileRequest} instead.
*
* @see S3TransferManager#download(DownloadRequest)
*/
@SdkPublicApi
public final class DownloadRequest<ReturnT>
implements TransferObjectRequest,
ToCopyableBuilder<TypedBuilder<ReturnT>, DownloadRequest<ReturnT>> {
private final AsyncResponseTransformer<GetObjectResponse, ReturnT> responseTransformer;
private final GetObjectRequest getObjectRequest;
private final List<TransferListener> transferListeners;
private DownloadRequest(DefaultTypedBuilder<ReturnT> builder) {
this.responseTransformer = Validate.paramNotNull(builder.responseTransformer, "responseTransformer");
this.getObjectRequest = Validate.paramNotNull(builder.getObjectRequest, "getObjectRequest");
this.transferListeners = builder.transferListeners;
}
/**
* Creates a builder that can be used to create a {@link DownloadRequest}.
*
* @see UntypedBuilder
*/
public static UntypedBuilder builder() {
return new DefaultUntypedBuilder();
}
@Override
public TypedBuilder<ReturnT> toBuilder() {
return new DefaultTypedBuilder<>(this);
}
/**
* The {@link Path} to file that response contents will be written to. The file must not exist or this method will throw an
* exception. If the file is not writable by the current user then an exception will be thrown.
*
* @return the destination path
*/
public AsyncResponseTransformer<GetObjectResponse, ReturnT> responseTransformer() {
return responseTransformer;
}
/**
* @return The {@link GetObjectRequest} request that should be used for the download
*/
public GetObjectRequest getObjectRequest() {
return getObjectRequest;
}
/**
* @return the List of transferListeners.
* @see TypedBuilder#transferListeners(Collection)
*/
@Override
public List<TransferListener> transferListeners() {
return transferListeners;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DownloadRequest<?> that = (DownloadRequest<?>) o;
if (!Objects.equals(responseTransformer, that.responseTransformer)) {
return false;
}
if (!Objects.equals(getObjectRequest, that.getObjectRequest)) {
return false;
}
return Objects.equals(transferListeners, that.transferListeners);
}
@Override
public int hashCode() {
int result = responseTransformer != null ? responseTransformer.hashCode() : 0;
result = 31 * result + (getObjectRequest != null ? getObjectRequest.hashCode() : 0);
result = 31 * result + (transferListeners != null ? transferListeners.hashCode() : 0);
return result;
}
@Override
public String toString() {
return ToString.builder("DownloadRequest")
.add("responseTransformer", responseTransformer)
.add("getObjectRequest", getObjectRequest)
.add("transferListeners", transferListeners)
.build();
}
/**
* Initial calls to {@link DownloadRequest#builder()} return an {@link UntypedBuilder}, where the builder is not yet
* parameterized with the generic type associated with {@link DownloadRequest}. This prevents the otherwise awkward syntax of
* having to explicitly cast the builder type, e.g.,
* <pre>
* {@code DownloadRequest.<ResponseBytes<GetObjectResponse>>builder()}
* </pre>
* Instead, the type may be inferred as part of specifying the {@link #responseTransformer(AsyncResponseTransformer)}
* parameter, at which point the builder chain will return a new {@link TypedBuilder}.
*/
public interface UntypedBuilder {
/**
* The {@link GetObjectRequest} request that should be used for the download
*
* @param getObjectRequest the getObject request
* @return a reference to this object so that method calls can be chained together.
* @see #getObjectRequest(Consumer)
*/
UntypedBuilder getObjectRequest(GetObjectRequest getObjectRequest);
/**
* The {@link GetObjectRequest} request that should be used for the download
* <p>
* This is a convenience method that creates an instance of the {@link GetObjectRequest} builder, avoiding the need to
* create one manually via {@link GetObjectRequest#builder()}.
*
* @param getObjectRequestBuilder the getObject request
* @return a reference to this object so that method calls can be chained together.
* @see #getObjectRequest(GetObjectRequest)
*/
default UntypedBuilder getObjectRequest(Consumer<GetObjectRequest.Builder> getObjectRequestBuilder) {
GetObjectRequest request = GetObjectRequest.builder()
.applyMutation(getObjectRequestBuilder)
.build();
getObjectRequest(request);
return this;
}
/**
* The {@link TransferListener}s that will be notified as part of this request. This method overrides and replaces any
* transferListeners that have already been set. Add an optional request override configuration.
*
* @param transferListeners the collection of transferListeners
* @return Returns a reference to this object so that method calls can be chained together.
* @return This builder for method chaining.
* @see TransferListener
*/
UntypedBuilder transferListeners(Collection<TransferListener> transferListeners);
/**
* Adds a {@link TransferListener} that will be notified as part of this request.
*
* @param transferListener the transferListener to add
* @return Returns a reference to this object so that method calls can be chained together.
* @see TransferListener
*/
UntypedBuilder addTransferListener(TransferListener transferListener);
/**
* Specifies the {@link AsyncResponseTransformer} that should be used for the download. This method also infers the
* generic type of {@link DownloadRequest} to create, inferred from the second type parameter of the provided {@link
* AsyncResponseTransformer}. E.g, specifying {@link AsyncResponseTransformer#toBytes()} would result in inferring the
* type of the {@link DownloadRequest} to be of {@code ResponseBytes<GetObjectResponse>}. See the static factory methods
* available in {@link AsyncResponseTransformer}.
*
* @param responseTransformer the AsyncResponseTransformer
* @param <T> the type of {@link DownloadRequest} to create
* @return a reference to this object so that method calls can be chained together.
* @see AsyncResponseTransformer
*/
<T> TypedBuilder<T> responseTransformer(AsyncResponseTransformer<GetObjectResponse, T> responseTransformer);
}
private static final class DefaultUntypedBuilder implements UntypedBuilder {
private GetObjectRequest getObjectRequest;
private List<TransferListener> transferListeners;
private DefaultUntypedBuilder() {
}
@Override
public UntypedBuilder getObjectRequest(GetObjectRequest getObjectRequest) {
this.getObjectRequest = getObjectRequest;
return this;
}
@Override
public UntypedBuilder transferListeners(Collection<TransferListener> transferListeners) {
this.transferListeners = transferListeners != null ? new ArrayList<>(transferListeners) : null;
return this;
}
@Override
public UntypedBuilder addTransferListener(TransferListener transferListener) {
if (transferListeners == null) {
transferListeners = new ArrayList<>();
}
transferListeners.add(transferListener);
return this;
}
public List<TransferListener> getTransferListeners() {
return transferListeners;
}
public void setTransferListeners(Collection<TransferListener> transferListeners) {
transferListeners(transferListeners);
}
@Override
public <T> TypedBuilder<T> responseTransformer(AsyncResponseTransformer<GetObjectResponse, T> responseTransformer) {
return new DefaultTypedBuilder<T>()
.getObjectRequest(getObjectRequest)
.transferListeners(transferListeners)
.responseTransformer(responseTransformer);
}
}
/**
* The type-parameterized version of {@link UntypedBuilder}. This builder's type is inferred as part of specifying {@link
* UntypedBuilder#responseTransformer(AsyncResponseTransformer)}, after which this builder can be used to construct a {@link
* DownloadRequest} with the same generic type.
*/
public interface TypedBuilder<T> extends CopyableBuilder<TypedBuilder<T>, DownloadRequest<T>> {
/**
* The {@link GetObjectRequest} request that should be used for the download
*
* @param getObjectRequest the getObject request
* @return a reference to this object so that method calls can be chained together.
* @see #getObjectRequest(Consumer)
*/
TypedBuilder<T> getObjectRequest(GetObjectRequest getObjectRequest);
/**
* The {@link GetObjectRequest} request that should be used for the download
* <p>
* This is a convenience method that creates an instance of the {@link GetObjectRequest} builder, avoiding the need to
* create one manually via {@link GetObjectRequest#builder()}.
*
* @param getObjectRequestBuilder the getObject request
* @return a reference to this object so that method calls can be chained together.
* @see #getObjectRequest(GetObjectRequest)
*/
default TypedBuilder<T> getObjectRequest(Consumer<GetObjectRequest.Builder> getObjectRequestBuilder) {
GetObjectRequest request = GetObjectRequest.builder()
.applyMutation(getObjectRequestBuilder)
.build();
getObjectRequest(request);
return this;
}
/**
* The {@link TransferListener}s that will be notified as part of this request. This method overrides and replaces any
* transferListeners that have already been set. Add an optional request override configuration.
*
* @param transferListeners the collection of transferListeners
* @return Returns a reference to this object so that method calls can be chained together.
* @return This builder for method chaining.
* @see TransferListener
*/
TypedBuilder<T> transferListeners(Collection<TransferListener> transferListeners);
/**
* Add a {@link TransferListener} that will be notified as part of this request.
*
* @param transferListener the transferListener to add
* @return Returns a reference to this object so that method calls can be chained together.
* @see TransferListener
*/
TypedBuilder<T> addTransferListener(TransferListener transferListener);
/**
* Specifies the {@link AsyncResponseTransformer} that should be used for the download. The generic type used is
* constrained by the {@link UntypedBuilder#responseTransformer(AsyncResponseTransformer)} that was previously used to
* create this {@link TypedBuilder}.
*
* @param responseTransformer the AsyncResponseTransformer
* @return a reference to this object so that method calls can be chained together.
* @see AsyncResponseTransformer
*/
TypedBuilder<T> responseTransformer(AsyncResponseTransformer<GetObjectResponse, T> responseTransformer);
}
private static class DefaultTypedBuilder<T> implements TypedBuilder<T> {
private GetObjectRequest getObjectRequest;
private List<TransferListener> transferListeners;
private AsyncResponseTransformer<GetObjectResponse, T> responseTransformer;
private DefaultTypedBuilder() {
}
private DefaultTypedBuilder(DownloadRequest<T> request) {
this.getObjectRequest = request.getObjectRequest;
this.responseTransformer = request.responseTransformer;
this.transferListeners = request.transferListeners;
}
@Override
public TypedBuilder<T> getObjectRequest(GetObjectRequest getObjectRequest) {
this.getObjectRequest = getObjectRequest;
return this;
}
@Override
public TypedBuilder<T> responseTransformer(AsyncResponseTransformer<GetObjectResponse, T> responseTransformer) {
this.responseTransformer = responseTransformer;
return this;
}
@Override
public TypedBuilder<T> transferListeners(Collection<TransferListener> transferListeners) {
this.transferListeners = transferListeners != null ? new ArrayList<>(transferListeners) : null;
return this;
}
@Override
public TypedBuilder<T> addTransferListener(TransferListener transferListener) {
if (transferListeners == null) {
transferListeners = new ArrayList<>();
}
transferListeners.add(transferListener);
return this;
}
public List<TransferListener> getTransferListeners() {
return transferListeners;
}
public void setTransferListeners(Collection<TransferListener> transferListeners) {
transferListeners(transferListeners);
}
@Override
public DownloadRequest<T> build() {
return new DownloadRequest<>(this);
}
}
}
| 3,801 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/FailedFileDownload.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.transfer.s3.model;
import java.util.Objects;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* Represents a failed single file download from {@link S3TransferManager#downloadDirectory(DownloadDirectoryRequest)}. It
* has a detailed description of the result.
*/
@SdkPublicApi
public final class FailedFileDownload
implements FailedObjectTransfer,
ToCopyableBuilder<FailedFileDownload.Builder, FailedFileDownload> {
private final DownloadFileRequest request;
private final Throwable exception;
private FailedFileDownload(DefaultBuilder builder) {
this.exception = Validate.paramNotNull(builder.exception, "exception");
this.request = Validate.paramNotNull(builder.request, "request");
}
@Override
public Throwable exception() {
return exception;
}
@Override
public DownloadFileRequest request() {
return request;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
FailedFileDownload that = (FailedFileDownload) o;
if (!Objects.equals(request, that.request)) {
return false;
}
return Objects.equals(exception, that.exception);
}
@Override
public int hashCode() {
int result = request != null ? request.hashCode() : 0;
result = 31 * result + (exception != null ? exception.hashCode() : 0);
return result;
}
@Override
public String toString() {
return ToString.builder("FailedFileDownload")
.add("request", request)
.add("exception", exception)
.build();
}
public static Builder builder() {
return new DefaultBuilder();
}
public static Class<? extends Builder> serializableBuilderClass() {
return DefaultBuilder.class;
}
@Override
public Builder toBuilder() {
return new DefaultBuilder(this);
}
public interface Builder extends CopyableBuilder<Builder, FailedFileDownload> {
Builder exception(Throwable exception);
Builder request(DownloadFileRequest request);
}
private static final class DefaultBuilder implements Builder {
private DownloadFileRequest request;
private Throwable exception;
private DefaultBuilder(FailedFileDownload failedFileDownload) {
this.request = failedFileDownload.request;
this.exception = failedFileDownload.exception;
}
private DefaultBuilder() {
}
@Override
public Builder exception(Throwable exception) {
this.exception = exception;
return this;
}
public void setException(Throwable exception) {
exception(exception);
}
public Throwable getException() {
return exception;
}
@Override
public Builder request(DownloadFileRequest request) {
this.request = request;
return this;
}
public void setRequest(DownloadFileRequest request) {
request(request);
}
public DownloadFileRequest getRequest() {
return request;
}
@Override
public FailedFileDownload build() {
return new FailedFileDownload(this);
}
}
}
| 3,802 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/CompletedCopy.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.transfer.s3.model;
import java.util.Objects;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.model.CopyObjectResponse;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
/**
* Represents a completed copy transfer to Amazon S3. It can be used to track the underlying {@link CopyObjectResponse}
*
* @see S3TransferManager#copy(CopyRequest)
*/
@SdkPublicApi
public final class CompletedCopy implements CompletedObjectTransfer {
private final CopyObjectResponse response;
private CompletedCopy(DefaultBuilder builder) {
this.response = Validate.paramNotNull(builder.response, "response");
}
/**
* Returns the {@link CopyObjectResponse}.
*/
@Override
public CopyObjectResponse response() {
return response;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CompletedCopy that = (CompletedCopy) o;
return Objects.equals(response, that.response);
}
@Override
public int hashCode() {
return response.hashCode();
}
@Override
public String toString() {
return ToString.builder("CompletedCopy")
.add("response", response)
.build();
}
public static Class<? extends Builder> serializableBuilderClass() {
return DefaultBuilder.class;
}
/**
* Creates a default builder for {@link CompletedCopy}.
*/
public static Builder builder() {
return new DefaultBuilder();
}
public interface Builder {
/**
* Specifies the {@link CopyObjectResponse} from {@link S3AsyncClient#putObject}
*
* @param response the response
* @return This builder for method chaining.
*/
Builder response(CopyObjectResponse response);
/**
* Builds a {@link CompletedCopy} based on the properties supplied to this builder
*
* @return An initialized {@link CompletedCopy}
*/
CompletedCopy build();
}
private static class DefaultBuilder implements Builder {
private CopyObjectResponse response;
private DefaultBuilder() {
}
@Override
public Builder response(CopyObjectResponse response) {
this.response = response;
return this;
}
@Override
public CompletedCopy build() {
return new CompletedCopy(this);
}
}
}
| 3,803 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/CompletedDirectoryDownload.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.transfer.s3.model;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* Represents a completed download directory transfer to Amazon S3. It can be used to track
* failed single file downloads.
*
* @see S3TransferManager#downloadDirectory(DownloadDirectoryRequest)
*/
@SdkPublicApi
public final class CompletedDirectoryDownload implements CompletedDirectoryTransfer,
ToCopyableBuilder<CompletedDirectoryDownload.Builder,
CompletedDirectoryDownload> {
private final List<FailedFileDownload> failedTransfers;
private CompletedDirectoryDownload(DefaultBuilder builder) {
this.failedTransfers = Collections.unmodifiableList(
new ArrayList<>(Validate.paramNotNull(builder.failedTransfers, "failedTransfers")));
}
@Override
public List<FailedFileDownload> failedTransfers() {
return failedTransfers;
}
/**
* Creates a default builder for {@link CompletedDirectoryDownload}.
*/
public static Builder builder() {
return new DefaultBuilder();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CompletedDirectoryDownload that = (CompletedDirectoryDownload) o;
return Objects.equals(failedTransfers, that.failedTransfers);
}
@Override
public int hashCode() {
return failedTransfers != null ? failedTransfers.hashCode() : 0;
}
@Override
public String toString() {
return ToString.builder("CompletedDirectoryDownload")
.add("failedTransfers", failedTransfers)
.build();
}
public static Class<? extends Builder> serializableBuilderClass() {
return DefaultBuilder.class;
}
@Override
public Builder toBuilder() {
return new DefaultBuilder(this);
}
public interface Builder extends CopyableBuilder<CompletedDirectoryDownload.Builder,
CompletedDirectoryDownload> {
/**
* Sets a collection of {@link FailedFileDownload}s
*
* @param failedTransfers failed download
* @return This builder for method chaining.
*/
Builder failedTransfers(Collection<FailedFileDownload> failedTransfers);
/**
* Adds a {@link FailedFileDownload}
*
* @param failedTransfer failed download
* @return This builder for method chaining.
*/
Builder addFailedTransfer(FailedFileDownload failedTransfer);
/**
* Builds a {@link CompletedDirectoryDownload} based on the properties supplied to this builder
* @return An initialized {@link CompletedDirectoryDownload}
*/
CompletedDirectoryDownload build();
}
private static final class DefaultBuilder implements Builder {
private Collection<FailedFileDownload> failedTransfers = new ArrayList<>();
private DefaultBuilder() {
}
private DefaultBuilder(CompletedDirectoryDownload completedDirectoryDownload) {
this.failedTransfers = new ArrayList<>(completedDirectoryDownload.failedTransfers);
}
@Override
public Builder failedTransfers(Collection<FailedFileDownload> failedTransfers) {
this.failedTransfers = new ArrayList<>(failedTransfers);
return this;
}
@Override
public Builder addFailedTransfer(FailedFileDownload failedTransfer) {
failedTransfers.add(failedTransfer);
return this;
}
public Collection<FailedFileDownload> getFailedTransfers() {
return Collections.unmodifiableCollection(failedTransfers);
}
public void setFailedTransfers(Collection<FailedFileDownload> failedTransfers) {
failedTransfers(failedTransfers);
}
@Override
public CompletedDirectoryDownload build() {
return new CompletedDirectoryDownload(this);
}
}
}
| 3,804 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/CompletedDirectoryTransfer.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.transfer.s3.model;
import java.util.List;
import software.amazon.awssdk.annotations.SdkPublicApi;
/**
* A completed directory-based transfer.
*
* @see CompletedDirectoryUpload
*/
@SdkPublicApi
public interface CompletedDirectoryTransfer extends CompletedTransfer {
/**
* A list of failed transfer details, including the {@link FailedObjectTransfer#exception()} responsible for the failure and
* the {@link FailedObjectTransfer#request()} that initiated the transfer.
*
* @return an immutable list of failed transfers
*/
List<? extends FailedObjectTransfer> failedTransfers();
}
| 3,805 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/DownloadFileRequest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.transfer.s3.model;
import java.io.File;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
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.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.transfer.s3.progress.TransferListener;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* Download an object identified by the bucket and key from S3 to a local file. For non-file-based downloads, you may use {@link
* DownloadRequest} instead.
*
* @see S3TransferManager#downloadFile(DownloadFileRequest)
*/
@SdkPublicApi
public final class DownloadFileRequest
implements TransferObjectRequest, ToCopyableBuilder<DownloadFileRequest.Builder, DownloadFileRequest> {
private final Path destination;
private final GetObjectRequest getObjectRequest;
private final List<TransferListener> transferListeners;
private DownloadFileRequest(DefaultBuilder builder) {
this.destination = Validate.paramNotNull(builder.destination, "destination");
this.getObjectRequest = Validate.paramNotNull(builder.getObjectRequest, "getObjectRequest");
this.transferListeners = builder.transferListeners;
}
/**
* Creates a builder that can be used to create a {@link DownloadFileRequest}.
*
* @see S3TransferManager#downloadFile(DownloadFileRequest)
*/
public static Builder builder() {
return new DefaultBuilder();
}
@Override
public Builder toBuilder() {
return new DefaultBuilder(this);
}
/**
* The {@link Path} to file that response contents will be written to. The file must not exist or this method
* will throw an exception. If the file is not writable by the current user then an exception will be thrown.
*
* @return the destination path
*/
public Path destination() {
return destination;
}
/**
* @return The {@link GetObjectRequest} request that should be used for the download
*/
public GetObjectRequest getObjectRequest() {
return getObjectRequest;
}
/**
*
* @return List of {@link TransferListener}s that will be notified as part of this request.
*/
@Override
public List<TransferListener> transferListeners() {
return transferListeners;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DownloadFileRequest that = (DownloadFileRequest) o;
if (!Objects.equals(destination, that.destination)) {
return false;
}
if (!Objects.equals(getObjectRequest, that.getObjectRequest)) {
return false;
}
return Objects.equals(transferListeners, that.transferListeners);
}
@Override
public int hashCode() {
int result = destination != null ? destination.hashCode() : 0;
result = 31 * result + (getObjectRequest != null ? getObjectRequest.hashCode() : 0);
result = 31 * result + (transferListeners != null ? transferListeners.hashCode() : 0);
return result;
}
@Override
public String toString() {
return ToString.builder("DownloadFileRequest")
.add("destination", destination)
.add("getObjectRequest", getObjectRequest)
.add("transferListeners", transferListeners)
.build();
}
public static Class<? extends Builder> serializableBuilderClass() {
return DefaultBuilder.class;
}
/**
* A builder for a {@link DownloadFileRequest}, created with {@link #builder()}
*/
@SdkPublicApi
@NotThreadSafe
public interface Builder extends CopyableBuilder<Builder, DownloadFileRequest> {
/**
* The {@link Path} to file that response contents will be written to. The file must not exist or this method
* will throw an exception. If the file is not writable by the current user then an exception will be thrown.
*
* @param destination the destination path
* @return Returns a reference to this object so that method calls can be chained together.
*/
Builder destination(Path destination);
/**
* The file that response contents will be written to. The file must not exist or this method
* will throw an exception. If the file is not writable by the current user then an exception will be thrown.
*
* @param destination the destination path
* @return Returns a reference to this object so that method calls can be chained together.
*/
default Builder destination(File destination) {
Validate.paramNotNull(destination, "destination");
return destination(destination.toPath());
}
/**
* The {@link GetObjectRequest} request that should be used for the download
*
* @param getObjectRequest the getObject request
* @return a reference to this object so that method calls can be chained together.
* @see #getObjectRequest(Consumer)
*/
Builder getObjectRequest(GetObjectRequest getObjectRequest);
/**
* The {@link GetObjectRequest} request that should be used for the download
*
* <p>
* This is a convenience method that creates an instance of the {@link GetObjectRequest} builder avoiding the
* need to create one manually via {@link GetObjectRequest#builder()}.
*
* @param getObjectRequestBuilder the getObject request
* @return a reference to this object so that method calls can be chained together.
* @see #getObjectRequest(GetObjectRequest)
*/
default Builder getObjectRequest(Consumer<GetObjectRequest.Builder> getObjectRequestBuilder) {
GetObjectRequest request = GetObjectRequest.builder()
.applyMutation(getObjectRequestBuilder)
.build();
getObjectRequest(request);
return this;
}
/**
* The {@link TransferListener}s that will be notified as part of this request. This method overrides and replaces any
* transferListeners that have already been set. Add an optional request override configuration.
*
* @param transferListeners the collection of transferListeners
* @return Returns a reference to this object so that method calls can be chained together.
* @return This builder for method chaining.
* @see TransferListener
*/
Builder transferListeners(Collection<TransferListener> transferListeners);
/**
* Add a {@link TransferListener} that will be notified as part of this request.
*
* @param transferListener the transferListener to add
* @return Returns a reference to this object so that method calls can be chained together.
* @see TransferListener
*/
Builder addTransferListener(TransferListener transferListener);
}
private static final class DefaultBuilder implements Builder {
private Path destination;
private GetObjectRequest getObjectRequest;
private List<TransferListener> transferListeners;
private DefaultBuilder() {
}
private DefaultBuilder(DownloadFileRequest downloadFileRequest) {
this.destination = downloadFileRequest.destination;
this.getObjectRequest = downloadFileRequest.getObjectRequest;
this.transferListeners = downloadFileRequest.transferListeners;
}
@Override
public Builder destination(Path destination) {
this.destination = Validate.paramNotNull(destination, "destination");
return this;
}
public Path getDestination() {
return destination;
}
public void setDestination(Path destination) {
destination(destination);
}
@Override
public DefaultBuilder getObjectRequest(GetObjectRequest getObjectRequest) {
this.getObjectRequest = getObjectRequest;
return this;
}
public GetObjectRequest getGetObjectRequest() {
return getObjectRequest;
}
public void setGetObjectRequest(GetObjectRequest getObjectRequest) {
getObjectRequest(getObjectRequest);
}
@Override
public DefaultBuilder transferListeners(Collection<TransferListener> transferListeners) {
this.transferListeners = transferListeners != null ? new ArrayList<>(transferListeners) : null;
return this;
}
@Override
public Builder addTransferListener(TransferListener transferListener) {
if (transferListeners == null) {
transferListeners = new ArrayList<>();
}
transferListeners.add(transferListener);
return this;
}
public List<TransferListener> getTransferListeners() {
return transferListeners;
}
public void setTransferListeners(Collection<TransferListener> transferListeners) {
transferListeners(transferListeners);
}
@Override
public DownloadFileRequest build() {
return new DownloadFileRequest(this);
}
}
}
| 3,806 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/TransferDirectoryRequest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.transfer.s3.model;
import software.amazon.awssdk.annotations.SdkPublicApi;
/**
* Interface for all transfer directory requests.
*
* @see UploadDirectoryRequest
*/
@SdkPublicApi
public interface TransferDirectoryRequest extends TransferRequest {
}
| 3,807 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/ResumableFileDownload.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.transfer.s3.model;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Instant;
import java.util.Objects;
import java.util.Optional;
import java.util.OptionalLong;
import java.util.function.Consumer;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.transfer.s3.config.TransferRequestOverrideConfiguration;
import software.amazon.awssdk.transfer.s3.internal.serialization.ResumableFileDownloadSerializer;
import software.amazon.awssdk.utils.IoUtils;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* An opaque token that holds the state and can be used to resume a paused download operation.
* <p>
* <b>Serialization: </b>When serializing this token, the following structures will not be preserved/persisted:
* <ul>
* <li>{@link TransferRequestOverrideConfiguration}</li>
* <li>{@link AwsRequestOverrideConfiguration} (from {@link GetObjectRequest})</li>
* </ul>
*
* @see S3TransferManager#downloadFile(DownloadFileRequest)
*/
@SdkPublicApi
public final class ResumableFileDownload implements ResumableTransfer,
ToCopyableBuilder<ResumableFileDownload.Builder, ResumableFileDownload> {
private final DownloadFileRequest downloadFileRequest;
private final long bytesTransferred;
private final Instant s3ObjectLastModified;
private final Long totalSizeInBytes;
private final Instant fileLastModified;
private ResumableFileDownload(DefaultBuilder builder) {
this.downloadFileRequest = Validate.paramNotNull(builder.downloadFileRequest, "downloadFileRequest");
this.bytesTransferred = builder.bytesTransferred == null ? 0 : Validate.isNotNegative(builder.bytesTransferred,
"bytesTransferred");
this.s3ObjectLastModified = builder.s3ObjectLastModified;
this.totalSizeInBytes = Validate.isPositiveOrNull(builder.totalSizeInBytes, "totalSizeInBytes");
this.fileLastModified = builder.fileLastModified;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ResumableFileDownload that = (ResumableFileDownload) o;
if (bytesTransferred != that.bytesTransferred) {
return false;
}
if (!downloadFileRequest.equals(that.downloadFileRequest)) {
return false;
}
if (!Objects.equals(s3ObjectLastModified, that.s3ObjectLastModified)) {
return false;
}
if (!Objects.equals(fileLastModified, that.fileLastModified)) {
return false;
}
return Objects.equals(totalSizeInBytes, that.totalSizeInBytes);
}
@Override
public int hashCode() {
int result = downloadFileRequest.hashCode();
result = 31 * result + (int) (bytesTransferred ^ (bytesTransferred >>> 32));
result = 31 * result + (s3ObjectLastModified != null ? s3ObjectLastModified.hashCode() : 0);
result = 31 * result + (fileLastModified != null ? fileLastModified.hashCode() : 0);
result = 31 * result + (totalSizeInBytes != null ? totalSizeInBytes.hashCode() : 0);
return result;
}
public static Builder builder() {
return new DefaultBuilder();
}
/**
* @return the {@link DownloadFileRequest} to resume
*/
public DownloadFileRequest downloadFileRequest() {
return downloadFileRequest;
}
/**
* Retrieve the number of bytes that have been transferred.
* @return the number of bytes
*/
public long bytesTransferred() {
return bytesTransferred;
}
/**
* Last modified time of the S3 object since last pause, or {@link Optional#empty()} if unknown
*/
public Optional<Instant> s3ObjectLastModified() {
return Optional.ofNullable(s3ObjectLastModified);
}
/**
* Last modified time of the file since last pause
*/
public Instant fileLastModified() {
return fileLastModified;
}
/**
* The total size of the transfer in bytes or {@link OptionalLong#empty()} if unknown
*
* @return the optional total size of the transfer.
*/
public OptionalLong totalSizeInBytes() {
return totalSizeInBytes == null ? OptionalLong.empty() : OptionalLong.of(totalSizeInBytes);
}
@Override
public String toString() {
return ToString.builder("ResumableFileDownload")
.add("bytesTransferred", bytesTransferred)
.add("fileLastModified", fileLastModified)
.add("s3ObjectLastModified", s3ObjectLastModified)
.add("totalSizeInBytes", totalSizeInBytes)
.add("downloadFileRequest", downloadFileRequest)
.build();
}
/**
* Persists this download object to a file in Base64-encoded JSON format.
*
* @param path The path to the file to which you want to write the serialized download object.
*/
@Override
public void serializeToFile(Path path) {
try {
Files.write(path, ResumableFileDownloadSerializer.toJson(this));
} catch (IOException e) {
throw SdkClientException.create("Failed to write to " + path, e);
}
}
/**
* Writes the serialized JSON data representing this object to an output stream.
* Note that the {@link OutputStream} is not closed or flushed after writing.
*
* @param outputStream The output stream to write the serialized object to.
*/
@Override
public void serializeToOutputStream(OutputStream outputStream) {
byte[] bytes = ResumableFileDownloadSerializer.toJson(this);
try {
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
IoUtils.copy(byteArrayInputStream, outputStream);
} catch (IOException e) {
throw SdkClientException.create("Failed to write this download object to the given OutputStream", e);
}
}
/**
* Returns the serialized JSON data representing this object as a string.
*/
@Override
public String serializeToString() {
return new String(ResumableFileDownloadSerializer.toJson(this), StandardCharsets.UTF_8);
}
/**
* Returns the serialized JSON data representing this object as an {@link SdkBytes} object.
*
* @return the serialized JSON as {@link SdkBytes}
*/
@Override
public SdkBytes serializeToBytes() {
return SdkBytes.fromByteArrayUnsafe(ResumableFileDownloadSerializer.toJson(this));
}
/**
* Returns the serialized JSON data representing this object as an {@link InputStream}.
*
* @return the serialized JSON input stream
*/
@Override
public InputStream serializeToInputStream() {
return new ByteArrayInputStream(ResumableFileDownloadSerializer.toJson(this));
}
/**
* Deserialize data at the given path into a {@link ResumableFileDownload}.
*
* @param path The {@link Path} to the file with serialized data
* @return the deserialized {@link ResumableFileDownload}
*/
public static ResumableFileDownload fromFile(Path path) {
try (InputStream stream = Files.newInputStream(path)) {
return ResumableFileDownloadSerializer.fromJson(stream);
} catch (IOException e) {
throw SdkClientException.create("Failed to create a ResumableFileDownload from " + path, e);
}
}
/**
* Deserialize bytes with JSON data into a {@link ResumableFileDownload}.
*
* @param bytes the serialized data
* @return the deserialized {@link ResumableFileDownload}
*/
public static ResumableFileDownload fromBytes(SdkBytes bytes) {
return ResumableFileDownloadSerializer.fromJson(bytes.asByteArrayUnsafe());
}
/**
* Deserialize a string with JSON data into a {@link ResumableFileDownload}.
*
* @param contents the serialized data
* @return the deserialized {@link ResumableFileDownload}
*/
public static ResumableFileDownload fromString(String contents) {
return ResumableFileDownloadSerializer.fromJson(contents);
}
@Override
public Builder toBuilder() {
return new DefaultBuilder(this);
}
public interface Builder extends CopyableBuilder<Builder, ResumableFileDownload> {
/**
* Sets the download file request
*
* @param downloadFileRequest the download file request
* @return a reference to this object so that method calls can be chained together.
*/
Builder downloadFileRequest(DownloadFileRequest downloadFileRequest);
/**
* The {@link DownloadFileRequest} request
*
* <p>
* This is a convenience method that creates an instance of the {@link DownloadFileRequest} builder avoiding the
* need to create one manually via {@link DownloadFileRequest#builder()}.
*
* @param downloadFileRequestBuilder the download file request builder
* @return a reference to this object so that method calls can be chained together.
* @see #downloadFileRequest(DownloadFileRequest)
*/
default ResumableFileDownload.Builder downloadFileRequest(Consumer<DownloadFileRequest.Builder>
downloadFileRequestBuilder) {
DownloadFileRequest request = DownloadFileRequest.builder()
.applyMutation(downloadFileRequestBuilder)
.build();
downloadFileRequest(request);
return this;
}
/**
* Sets the number of bytes transferred
*
* @param bytesTransferred the number of bytes transferred
* @return a reference to this object so that method calls can be chained together.
*/
Builder bytesTransferred(Long bytesTransferred);
/**
* Sets the total transfer size in bytes
* @param totalSizeInBytes the transfer size in bytes
* @return a reference to this object so that method calls can be chained together.
*/
Builder totalSizeInBytes(Long totalSizeInBytes);
/**
* Sets the last modified time of the object
*
* @param s3ObjectLastModified the last modified time of the object
* @return a reference to this object so that method calls can be chained together.
*/
Builder s3ObjectLastModified(Instant s3ObjectLastModified);
/**
* Sets the last modified time of the object
*
* @param lastModified the last modified time of the object
* @return a reference to this object so that method calls can be chained together.
*/
Builder fileLastModified(Instant lastModified);
}
private static final class DefaultBuilder implements Builder {
private DownloadFileRequest downloadFileRequest;
private Long bytesTransferred;
private Instant s3ObjectLastModified;
private Long totalSizeInBytes;
private Instant fileLastModified;
private DefaultBuilder() {
}
private DefaultBuilder(ResumableFileDownload persistableFileDownload) {
this.downloadFileRequest = persistableFileDownload.downloadFileRequest;
this.bytesTransferred = persistableFileDownload.bytesTransferred;
this.totalSizeInBytes = persistableFileDownload.totalSizeInBytes;
this.fileLastModified = persistableFileDownload.fileLastModified;
this.s3ObjectLastModified = persistableFileDownload.s3ObjectLastModified;
}
@Override
public Builder downloadFileRequest(DownloadFileRequest downloadFileRequest) {
this.downloadFileRequest = downloadFileRequest;
return this;
}
@Override
public Builder bytesTransferred(Long bytesTransferred) {
this.bytesTransferred = bytesTransferred;
return this;
}
@Override
public Builder totalSizeInBytes(Long totalSizeInBytes) {
this.totalSizeInBytes = totalSizeInBytes;
return this;
}
@Override
public Builder s3ObjectLastModified(Instant s3ObjectLastModified) {
this.s3ObjectLastModified = s3ObjectLastModified;
return this;
}
@Override
public Builder fileLastModified(Instant fileLastModified) {
this.fileLastModified = fileLastModified;
return this;
}
@Override
public ResumableFileDownload build() {
return new ResumableFileDownload(this);
}
}
}
| 3,808 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/UploadRequest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.transfer.s3.model;
import static software.amazon.awssdk.utils.Validate.paramNotNull;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
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.core.async.AsyncRequestBody;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.transfer.s3.progress.TransferListener;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* Upload the given {@link AsyncRequestBody} to an object in S3. For file-based uploads, you may use {@link UploadFileRequest}
* instead.
*
* @see S3TransferManager#upload(UploadRequest)
*/
@SdkPublicApi
public final class UploadRequest
implements TransferObjectRequest,
ToCopyableBuilder<UploadRequest.Builder, UploadRequest> {
private final PutObjectRequest putObjectRequest;
private final AsyncRequestBody requestBody;
private final List<TransferListener> listeners;
private UploadRequest(DefaultBuilder builder) {
this.putObjectRequest = paramNotNull(builder.putObjectRequest, "putObjectRequest");
this.requestBody = paramNotNull(builder.requestBody, "requestBody");
this.listeners = builder.listeners;
}
/**
* @return The {@link PutObjectRequest} request that should be used for the upload
*/
public PutObjectRequest putObjectRequest() {
return putObjectRequest;
}
/**
* The {@link AsyncRequestBody} containing data to send to the service.
*
* @return the request body
*/
public AsyncRequestBody requestBody() {
return requestBody;
}
/**
* @return the List of {@link TransferListener}s that will be notified as part of this request.
*/
@Override
public List<TransferListener> transferListeners() {
return listeners;
}
/**
* Creates a builder that can be used to create a {@link UploadRequest}.
*
* @see S3TransferManager#upload(UploadRequest)
*/
public static Builder builder() {
return new DefaultBuilder();
}
public static Class<? extends Builder> serializableBuilderClass() {
return DefaultBuilder.class;
}
@Override
public Builder toBuilder() {
return new DefaultBuilder(this);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
UploadRequest that = (UploadRequest) o;
if (!Objects.equals(putObjectRequest, that.putObjectRequest)) {
return false;
}
if (!Objects.equals(requestBody, that.requestBody)) {
return false;
}
return Objects.equals(listeners, that.listeners);
}
@Override
public int hashCode() {
int result = putObjectRequest != null ? putObjectRequest.hashCode() : 0;
result = 31 * result + (requestBody != null ? requestBody.hashCode() : 0);
result = 31 * result + (listeners != null ? listeners.hashCode() : 0);
return result;
}
@Override
public String toString() {
return ToString.builder("UploadRequest")
.add("putObjectRequest", putObjectRequest)
.add("requestBody", requestBody)
.add("configuration", listeners)
.build();
}
/**
* A builder for a {@link UploadRequest}, created with {@link #builder()}
*/
@SdkPublicApi
@NotThreadSafe
public interface Builder extends CopyableBuilder<Builder, UploadRequest> {
/**
* The {@link AsyncRequestBody} containing the data to send to the service. Request bodies may be declared using one of
* the static factory methods in the {@link AsyncRequestBody} class.
*
* @param requestBody the request body
* @return Returns a reference to this object so that method calls can be chained together.
* @see AsyncRequestBody
*/
Builder requestBody(AsyncRequestBody requestBody);
/**
* Configure the {@link PutObjectRequest} that should be used for the upload
*
* @param putObjectRequest the putObjectRequest
* @return Returns a reference to this object so that method calls can be chained together.
* @see #putObjectRequest(Consumer)
*/
Builder putObjectRequest(PutObjectRequest putObjectRequest);
/**
* Configure the {@link PutObjectRequest} that should be used for the upload
*
* <p>
* This is a convenience method that creates an instance of the {@link PutObjectRequest} builder avoiding the
* need to create one manually via {@link PutObjectRequest#builder()}.
*
* @param putObjectRequestBuilder the putObjectRequest consumer builder
* @return Returns a reference to this object so that method calls can be chained together.
* @see #putObjectRequest(PutObjectRequest)
*/
default Builder putObjectRequest(Consumer<PutObjectRequest.Builder> putObjectRequestBuilder) {
return putObjectRequest(PutObjectRequest.builder()
.applyMutation(putObjectRequestBuilder)
.build());
}
/**
* The {@link TransferListener}s that will be notified as part of this request. This method overrides and replaces any
* transferListeners that have already been set. Add an optional request override configuration.
*
* @param transferListeners the collection of transferListeners
* @return Returns a reference to this object so that method calls can be chained together.
* @return This builder for method chaining.
* @see TransferListener
*/
Builder transferListeners(Collection<TransferListener> transferListeners);
/**
* Add a {@link TransferListener} that will be notified as part of this request.
*
* @param transferListener the transferListener to add
* @return Returns a reference to this object so that method calls can be chained together.
* @see TransferListener
*/
Builder addTransferListener(TransferListener transferListener);
/**
* @return The built request.
*/
@Override
UploadRequest build();
}
private static class DefaultBuilder implements Builder {
private PutObjectRequest putObjectRequest;
private AsyncRequestBody requestBody;
private List<TransferListener> listeners;
private DefaultBuilder() {
}
private DefaultBuilder(UploadRequest uploadRequest) {
this.putObjectRequest = uploadRequest.putObjectRequest;
this.requestBody = uploadRequest.requestBody;
this.listeners = uploadRequest.listeners;
}
@Override
public Builder requestBody(AsyncRequestBody requestBody) {
this.requestBody = Validate.paramNotNull(requestBody, "requestBody");
return this;
}
public AsyncRequestBody getRequestBody() {
return requestBody;
}
public void setRequestBody(AsyncRequestBody requestBody) {
requestBody(requestBody);
}
@Override
public Builder putObjectRequest(PutObjectRequest putObjectRequest) {
this.putObjectRequest = putObjectRequest;
return this;
}
public PutObjectRequest getPutObjectRequest() {
return putObjectRequest;
}
public void setPutObjectRequest(PutObjectRequest putObjectRequest) {
putObjectRequest(putObjectRequest);
}
@Override
public Builder transferListeners(Collection<TransferListener> transferListeners) {
this.listeners = transferListeners != null ? new ArrayList<>(transferListeners) : null;
return this;
}
@Override
public Builder addTransferListener(TransferListener transferListener) {
if (listeners == null) {
listeners = new ArrayList<>();
}
listeners.add(transferListener);
return this;
}
public List<TransferListener> getListeners() {
return listeners;
}
public void setListeners(Collection<TransferListener> listeners) {
transferListeners(listeners);
}
@Override
public UploadRequest build() {
return new UploadRequest(this);
}
}
}
| 3,809 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/TransferRequest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.transfer.s3.model;
import software.amazon.awssdk.annotations.SdkPublicApi;
/**
* The parent interface for all transfer requests.
*
* @see TransferObjectRequest
* @see TransferDirectoryRequest
*/
@SdkPublicApi
public interface TransferRequest {
}
| 3,810 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/FailedObjectTransfer.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.transfer.s3.model;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
/**
* Represents a failed single file transfer in a multi-file transfer operation such as
* {@link S3TransferManager#uploadDirectory}
*/
@SdkPublicApi
public interface FailedObjectTransfer {
/**
* The exception thrown from a specific single file transfer
*
* @return the exception thrown
*/
Throwable exception();
/**
* The failed {@link TransferObjectRequest}.
*
* @return the failed request
*/
TransferObjectRequest request();
}
| 3,811 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/DownloadDirectoryRequest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.transfer.s3.model;
import java.nio.file.Path;
import java.util.Objects;
import java.util.function.Consumer;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.ListObjectsV2Request;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.transfer.s3.config.DownloadFilter;
import software.amazon.awssdk.transfer.s3.config.TransferRequestOverrideConfiguration;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* Request object to download the objects in the provided S3 bucket to a local directory using the Transfer Manager.
*
* @see S3TransferManager#downloadDirectory(DownloadDirectoryRequest)
*/
@SdkPublicApi
public final class DownloadDirectoryRequest
implements TransferDirectoryRequest, ToCopyableBuilder<DownloadDirectoryRequest.Builder, DownloadDirectoryRequest> {
private final Path destination;
private final String bucket;
private final DownloadFilter filter;
private final Consumer<DownloadFileRequest.Builder> downloadFileRequestTransformer;
private final Consumer<ListObjectsV2Request.Builder> listObjectsRequestTransformer;
public DownloadDirectoryRequest(DefaultBuilder builder) {
this.destination = Validate.paramNotNull(builder.destination, "destination");
this.bucket = Validate.paramNotNull(builder.bucket, "bucket");
this.filter = builder.filter;
this.downloadFileRequestTransformer = builder.downloadFileRequestTransformer;
this.listObjectsRequestTransformer = builder.listObjectsRequestTransformer;
}
/**
* The destination directory to which files should be downloaded.
*
* @return the destination directory
* @see Builder#destination(Path)
*/
public Path destination() {
return destination;
}
/**
* The name of the bucket
*
* @return bucket name
* @see Builder#bucket(String)
*/
public String bucket() {
return bucket;
}
/**
* @return the optional filter, or {@link DownloadFilter#allObjects()} if no filter was provided
* @see Builder#filter(DownloadFilter)
*/
public DownloadFilter filter() {
return filter == null ? DownloadFilter.allObjects() : filter;
}
/**
* @return the {@link ListObjectsV2Request} transformer if not null, otherwise no-op
* @see Builder#listObjectsV2RequestTransformer(Consumer)
*/
public Consumer<ListObjectsV2Request.Builder> listObjectsRequestTransformer() {
return listObjectsRequestTransformer == null ? ignore -> { } : listObjectsRequestTransformer;
}
/**
* @return the upload request transformer if not null, otherwise no-op
* @see Builder#listObjectsV2RequestTransformer(Consumer)
*/
public Consumer<DownloadFileRequest.Builder> downloadFileRequestTransformer() {
return downloadFileRequestTransformer == null ? ignore -> { } : downloadFileRequestTransformer;
}
public static Builder builder() {
return new DefaultBuilder();
}
public static Class<? extends Builder> serializableBuilderClass() {
return DefaultBuilder.class;
}
@Override
public Builder toBuilder() {
return new DefaultBuilder(this);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DownloadDirectoryRequest that = (DownloadDirectoryRequest) o;
if (!Objects.equals(destination, that.destination)) {
return false;
}
if (!Objects.equals(bucket, that.bucket)) {
return false;
}
if (!Objects.equals(downloadFileRequestTransformer, that.downloadFileRequestTransformer)) {
return false;
}
if (!Objects.equals(listObjectsRequestTransformer, that.listObjectsRequestTransformer)) {
return false;
}
return Objects.equals(filter, that.filter);
}
@Override
public int hashCode() {
int result = destination != null ? destination.hashCode() : 0;
result = 31 * result + (bucket != null ? bucket.hashCode() : 0);
result = 31 * result + (filter != null ? filter.hashCode() : 0);
result = 31 * result + (downloadFileRequestTransformer != null ? downloadFileRequestTransformer.hashCode() : 0);
result = 31 * result + (listObjectsRequestTransformer != null ? listObjectsRequestTransformer.hashCode() : 0);
return result;
}
@Override
public String toString() {
return ToString.builder("DownloadDirectoryRequest")
.add("destination", destination)
.add("bucket", bucket)
.add("filter", filter)
.add("downloadFileRequestTransformer", downloadFileRequestTransformer)
.add("listObjectsRequestTransformer", listObjectsRequestTransformer)
.build();
}
public interface Builder extends CopyableBuilder<Builder, DownloadDirectoryRequest> {
/**
* Specifies the destination directory to which files should be downloaded.
*
* @param destination the destination directorÏy
* @return This builder for method chaining.
*/
Builder destination(Path destination);
/**
* The name of the bucket to download objects from.
*
* @param bucket the bucket name
* @return This builder for method chaining.
*/
Builder bucket(String bucket);
/**
* Specifies a filter that will be used to evaluate which objects should be downloaded from the target directory.
* <p>
* You can use a filter, for example, to only download objects of a given size, of a given file extension, of a given
* last-modified date, etc. See {@link DownloadFilter} for some ready-made implementations. Multiple {@link
* DownloadFilter}s can be composed together via the {@code and} and {@code or} methods.
* <p>
* By default, if no filter is specified, all objects will be downloaded.
*
* @param filter the filter
* @return This builder for method chaining.
* @see DownloadFilter
*/
Builder filter(DownloadFilter filter);
/**
* Specifies a function used to transform the {@link DownloadFileRequest}s generated by this
* {@link DownloadDirectoryRequest}. The provided function is called once for each file that is downloaded, allowing
* you to modify the paths resolved by TransferManager on a per-file basis, modify the created {@link GetObjectRequest}
* before it is passed to S3, or configure a {@link TransferRequestOverrideConfiguration}.
*
* <p>The factory receives the {@link DownloadFileRequest}s created by Transfer Manager for each S3 Object in the
* S3 bucket being downloaded and returns a (potentially modified) {@code DownloadFileRequest}.
*
* <p>
* <b>Usage Example:</b>
* {@snippet :
* // Add a LoggingTransferListener to every transfer within the download directory request
*
* DownloadDirectoryRequest request =
* DownloadDirectoryRequest.builder()
* .destination(Paths.get("."))
* .bucket("bucket")
* .downloadFileRequestTransformer(request -> request.addTransferListener(LoggingTransferListener.create()))
* .build();
*
* DownloadDirectoryTransfer downloadDirectory = transferManager.downloadDirectory(request);
*
* // Wait for the transfer to complete
* CompletedDownloadDirectory completedDownloadDirectory = downloadDirectory.completionFuture().join();
*
* // Print out the failed downloads
* completedDownloadDirectory.failedDownloads().forEach(System.out::println);
* }
*
* @param downloadFileRequestTransformer A transformer to use for modifying the file-level download requests
* before execution
* @return This builder for method chaining
*/
Builder downloadFileRequestTransformer(Consumer<DownloadFileRequest.Builder> downloadFileRequestTransformer);
/**
* Specifies a function used to transform the {@link ListObjectsV2Request}s generated by this
* {@link DownloadDirectoryRequest}. The provided function is called once, allowing you to modify
* {@link ListObjectsV2Request} before it is passed to S3.
*
* <p>The factory receives the {@link ListObjectsV2Request}s created by Transfer Manager and
* returns a (potentially modified) {@code ListObjectsV2Request}.
*
* <p>
* <b>Usage Example:</b>
* {@snippet :
*
* DownloadDirectoryRequest request =
* DownloadDirectoryRequest.builder()
* .destination(Paths.get("."))
* .bucket("bucket")
* .listObjectsV2RequestTransformer(request -> request.encodingType(newEncodingType))
* .build();
*
* DownloadDirectoryTransfer downloadDirectory = transferManager.downloadDirectory(request);
*
* // Wait for the transfer to complete
* CompletedDownloadDirectory completedDownloadDirectory = downloadDirectory.completionFuture().join();
*
* // Print out the failed downloads
* completedDownloadDirectory.failedDownloads().forEach(System.out::println);
* }
*
* <p>
* <b>Prefix:</b>
* {@code ListObjectsV2Request}'s {@code prefix} specifies the key prefix for the virtual directory. If not provided,
* all subdirectories will be downloaded recursively
* <p>
* See <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-prefixes.html">Organizing objects using
* prefixes</a>
*
* <p>
* When a non-empty prefix is provided, the prefix is stripped from the directory structure of the files.
* <p>
* For example, assume that you have the following keys in your bucket:
* <ul>
* <li>sample.jpg</li>
* <li>photos/2022/January/sample.jpg</li>
* <li>photos/2022/February/sample1.jpg</li>
* <li>photos/2022/February/sample2.jpg</li>
* <li>photos/2022/February/sample3.jpg</li>
* </ul>
*
* Given a request to download the bucket to a destination with a prefix of "/photos" and destination path of "test", the
* downloaded directory would like this
*
* <pre>
* {@code
* |- test
* |- 2022
* |- January
* |- sample.jpg
* |- February
* |- sample1.jpg
* |- sample2.jpg
* |- sample3.jpg
* }
* </pre>
*
* <p>
* <b>Delimiter:</b>
* {@code ListObjectsV2Request}'s {@code delimiter} specifies the delimiter that will be used to retrieve the objects
* within the provided bucket. A delimiter causes a list operation to roll up all the keys that share a common prefix
* into a single summary list result. It's null by default.
*
* For example, assume that you have the following keys in your bucket:
*
* <ul>
* <li>sample.jpg</li>
* <li>photos-2022-January-sample.jpg</li>
* <li>photos-2022-February-sample1.jpg</li>
* <li>photos-2022-February-sample2.jpg</li>
* <li>photos-2022-February-sample3.jpg</li>
* </ul>
*
* Given a request to download the bucket to a destination with delimiter of "-", the downloaded directory would look
* like this
*
* <pre>
* {@code
* |- test
* |- sample.jpg
* |- photos
* |- 2022
* |- January
* |- sample.jpg
* |- February
* |- sample1.jpg
* |- sample2.jpg
* |- sample3.jpg
* }
* </pre>
*
* @param listObjectsV2RequestTransformer A transformer to use for modifying ListObjectsV2Request before execution
* @return This builder for method chaining
*/
Builder listObjectsV2RequestTransformer(Consumer<ListObjectsV2Request.Builder> listObjectsV2RequestTransformer);
}
private static final class DefaultBuilder implements Builder {
private Path destination;
private String bucket;
private DownloadFilter filter;
private Consumer<DownloadFileRequest.Builder> downloadFileRequestTransformer;
private Consumer<ListObjectsV2Request.Builder> listObjectsRequestTransformer;
private DefaultBuilder() {
}
private DefaultBuilder(DownloadDirectoryRequest request) {
this.destination = request.destination;
this.bucket = request.bucket;
this.filter = request.filter;
this.downloadFileRequestTransformer = request.downloadFileRequestTransformer;
this.listObjectsRequestTransformer = request.listObjectsRequestTransformer;
}
@Override
public Builder destination(Path destination) {
this.destination = destination;
return this;
}
public void setDestination(Path destination) {
destination(destination);
}
public Path getDestination() {
return destination;
}
@Override
public Builder bucket(String bucket) {
this.bucket = bucket;
return this;
}
public void setBucket(String bucket) {
bucket(bucket);
}
public String getBucket() {
return bucket;
}
@Override
public Builder filter(DownloadFilter filter) {
this.filter = filter;
return this;
}
@Override
public Builder downloadFileRequestTransformer(Consumer<DownloadFileRequest.Builder> downloadFileRequestTransformer) {
this.downloadFileRequestTransformer = downloadFileRequestTransformer;
return this;
}
@Override
public Builder listObjectsV2RequestTransformer(Consumer<ListObjectsV2Request.Builder> listObjectsRequestTransformer) {
this.listObjectsRequestTransformer = listObjectsRequestTransformer;
return this;
}
public void setFilter(DownloadFilter filter) {
filter(filter);
}
public DownloadFilter getFilter() {
return filter;
}
@Override
public DownloadDirectoryRequest build() {
return new DownloadDirectoryRequest(this);
}
}
}
| 3,812 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/CompletedObjectTransfer.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.transfer.s3.model;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.SdkResponse;
/**
* A completed single object transfer.
*
* @see CompletedFileUpload
* @see CompletedFileDownload
* @see CompletedUpload
* @see CompletedDownload
*/
@SdkPublicApi
public interface CompletedObjectTransfer extends CompletedTransfer {
/**
* Return the {@link SdkResponse} associated with this transfer
*/
default SdkResponse response() {
throw new UnsupportedOperationException();
}
}
| 3,813 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/TransferObjectRequest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.transfer.s3.model;
import java.util.List;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.transfer.s3.progress.TransferListener;
/**
* Interface for all single object transfer requests.
*
* @see UploadFileRequest
* @see DownloadFileRequest
* @see UploadRequest
* @see DownloadRequest
*/
@SdkPublicApi
public interface TransferObjectRequest extends TransferRequest {
List<TransferListener> transferListeners();
}
| 3,814 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/UploadDirectoryRequest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.transfer.s3.model;
import java.nio.file.Path;
import java.util.Objects;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.function.Consumer;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.transfer.s3.config.TransferRequestOverrideConfiguration;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* Request object to upload a local directory to S3 using the Transfer Manager.
*
* @see S3TransferManager#uploadDirectory(UploadDirectoryRequest)
*/
@SdkPublicApi
public final class UploadDirectoryRequest
implements TransferDirectoryRequest, ToCopyableBuilder<UploadDirectoryRequest.Builder, UploadDirectoryRequest> {
private final Path source;
private final String bucket;
private final String s3Prefix;
private final String s3Delimiter;
private final Boolean followSymbolicLinks;
private final Integer maxDepth;
private final Consumer<UploadFileRequest.Builder> uploadFileRequestTransformer;
public UploadDirectoryRequest(DefaultBuilder builder) {
this.source = Validate.paramNotNull(builder.source, "source");
this.bucket = Validate.paramNotNull(builder.bucket, "bucket");
this.s3Prefix = builder.s3Prefix;
this.s3Delimiter = builder.s3Delimiter;
this.followSymbolicLinks = builder.followSymbolicLinks;
this.maxDepth = builder.maxDepth;
this.uploadFileRequestTransformer = builder.uploadFileRequestTransformer;
}
/**
* The source directory to upload
*
* @return the source directory
* @see Builder#source(Path)
*/
public Path source() {
return source;
}
/**
* The name of the bucket to upload objects to.
*
* @return bucket name
* @see Builder#bucket(String)
*/
public String bucket() {
return bucket;
}
/**
* @return the optional key prefix
* @see Builder#s3Prefix(String)
*/
public Optional<String> s3Prefix() {
return Optional.ofNullable(s3Prefix);
}
/**
* @return the optional delimiter
* @see Builder#s3Delimiter(String)
*/
public Optional<String> s3Delimiter() {
return Optional.ofNullable(s3Delimiter);
}
/**
* @return whether to follow symbolic links
* @see Builder#followSymbolicLinks(Boolean)
*/
public Optional<Boolean> followSymbolicLinks() {
return Optional.ofNullable(followSymbolicLinks);
}
/**
* @return the maximum number of directory levels to traverse
* @see Builder#maxDepth(Integer)
*/
public OptionalInt maxDepth() {
return maxDepth == null ? OptionalInt.empty() : OptionalInt.of(maxDepth);
}
/**
* @return the upload request transformer if not null, otherwise no-op
* @see Builder#uploadFileRequestTransformer(Consumer)
*/
public Consumer<UploadFileRequest.Builder> uploadFileRequestTransformer() {
return uploadFileRequestTransformer == null ? ignore -> { } : uploadFileRequestTransformer;
}
public static Builder builder() {
return new DefaultBuilder();
}
public static Class<? extends Builder> serializableBuilderClass() {
return DefaultBuilder.class;
}
@Override
public Builder toBuilder() {
return new DefaultBuilder(this);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
UploadDirectoryRequest that = (UploadDirectoryRequest) o;
if (!Objects.equals(source, that.source)) {
return false;
}
if (!Objects.equals(bucket, that.bucket)) {
return false;
}
if (!Objects.equals(s3Prefix, that.s3Prefix)) {
return false;
}
if (!Objects.equals(followSymbolicLinks, that.followSymbolicLinks)) {
return false;
}
if (!Objects.equals(maxDepth, that.maxDepth)) {
return false;
}
if (!Objects.equals(uploadFileRequestTransformer, that.uploadFileRequestTransformer)) {
return false;
}
return Objects.equals(s3Delimiter, that.s3Delimiter);
}
@Override
public int hashCode() {
int result = source != null ? source.hashCode() : 0;
result = 31 * result + (bucket != null ? bucket.hashCode() : 0);
result = 31 * result + (s3Prefix != null ? s3Prefix.hashCode() : 0);
result = 31 * result + (s3Delimiter != null ? s3Delimiter.hashCode() : 0);
result = 31 * result + (followSymbolicLinks != null ? followSymbolicLinks.hashCode() : 0);
result = 31 * result + (maxDepth != null ? maxDepth.hashCode() : 0);
result = 31 * result + (uploadFileRequestTransformer != null ? uploadFileRequestTransformer.hashCode() : 0);
return result;
}
@Override
public String toString() {
return ToString.builder("UploadDirectoryRequest")
.add("source", source)
.add("bucket", bucket)
.add("s3Prefix", s3Prefix)
.add("s3Delimiter", s3Delimiter)
.add("followSymbolicLinks", followSymbolicLinks)
.add("maxDepth", maxDepth)
.add("uploadFileRequestTransformer", uploadFileRequestTransformer)
.build();
}
public interface Builder extends CopyableBuilder<Builder, UploadDirectoryRequest> {
/**
* Specifies the source directory to upload. The source directory must exist.
* Fle wildcards are not supported and treated literally. Hidden files/directories are visited.
*
* <p>
* Note that the current user must have read access to all directories and files,
* otherwise {@link SecurityException} will be thrown.
*
* @param source the source directory
* @return This builder for method chaining.
*/
Builder source(Path source);
/**
* The name of the bucket to upload objects to.
*
* @param bucket the bucket name
* @return This builder for method chaining.
*/
Builder bucket(String bucket);
/**
* Specifies the key prefix to use for the objects. If not provided, files will be uploaded to the root of the bucket
* <p>
* See <a
* href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-prefixes.html">Organizing objects using
* prefixes</a>
*
* <p>
* Note: if the provided prefix ends with the same string as delimiter, it will get "normalized" when generating the key
* name. For example, assuming the prefix provided is "foo/" and the delimiter is "/" and the source directory has the
* following structure:
*
* <pre>
* |- test
* |- obj1.txt
* |- obj2.txt
* </pre>
*
* the object keys will be "foo/obj1.txt" and "foo/obj2.txt" as apposed to "foo//obj1.txt" and "foo//obj2.txt"
*
* @param s3Prefix the key prefix
* @return This builder for method chaining.
* @see #s3Delimiter(String)
*/
Builder s3Prefix(String s3Prefix);
/**
* Specifies the delimiter. A delimiter causes a list operation to roll up all the keys that share a common prefix into a
* single summary list result. If not provided, {@code "/"} will be used.
*
* See <a
* href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-prefixes.html">Organizing objects using
* prefixes</a>
*
* <p>
* Note: if the provided prefix ends with the same string as delimiter, it will get "normalized" when generating the key
* name. For example, assuming the prefix provided is "foo/" and the delimiter is "/" and the source directory has the
* following structure:
*
* <pre>
* |- test
* |- obj1.txt
* |- obj2.txt
* </pre>
*
* the object keys will be "foo/obj1.txt" and "foo/obj2.txt" as apposed to "foo//obj1.txt" and "foo//obj2.txt"
*
* @param s3Delimiter the delimiter
* @return This builder for method chaining.
* @see #s3Prefix(String)
*/
Builder s3Delimiter(String s3Delimiter);
/**
* Specifies whether to follow symbolic links when traversing the file tree in
* {@link S3TransferManager#downloadDirectory} operation
* <p>
* Default to false
*
* @param followSymbolicLinks whether to follow symbolic links
* @return This builder for method chaining.
*/
Builder followSymbolicLinks(Boolean followSymbolicLinks);
/**
* Specifies the maximum number of levels of directories to visit. Must be positive.
* 1 means only the files directly within the provided source directory are visited.
*
* <p>
* Default to {@code Integer.MAX_VALUE}
*
* @param maxDepth the maximum number of directory levels to visit
* @return This builder for method chaining.
*/
Builder maxDepth(Integer maxDepth);
/**
* Specifies a function used to transform the {@link UploadFileRequest}s generated by this {@link UploadDirectoryRequest}.
* The provided function is called once for each file that is uploaded, allowing you to modify the paths resolved by
* TransferManager on a per-file basis, modify the created {@link PutObjectRequest} before it is passed to S3, or
* configure a {@link TransferRequestOverrideConfiguration}.
*
* <p>The factory receives the {@link UploadFileRequest}s created by Transfer Manager for each file in the directory
* being uploaded, and returns a (potentially modified) {@code UploadFileRequest}.
*
* <p>
* <b>Usage Example:</b>
* <pre>
* {@code
* // Add a LoggingTransferListener to every transfer within the upload directory request
*
* UploadDirectoryOverrideConfiguration directoryUploadConfiguration =
* UploadDirectoryOverrideConfiguration.builder()
* .uploadFileRequestTransformer(request -> request.addTransferListenerf(LoggingTransferListener.create())
* .build();
*
* UploadDirectoryRequest request =
* UploadDirectoryRequest.builder()
* .source(Paths.get("."))
* .bucket("bucket")
* .prefix("prefix")
* .overrideConfiguration(directoryUploadConfiguration)
* .build()
*
* UploadDirectoryTransfer uploadDirectory = transferManager.uploadDirectory(request);
*
* // Wait for the transfer to complete
* CompletedUploadDirectory completedUploadDirectory = uploadDirectory.completionFuture().join();
*
* // Print out the failed uploads
* completedUploadDirectory.failedUploads().forEach(System.out::println);
* }
* </pre>
*
* @param uploadFileRequestTransformer A transformer to use for modifying the file-level upload requests before execution
* @return This builder for method chaining
*/
Builder uploadFileRequestTransformer(Consumer<UploadFileRequest.Builder> uploadFileRequestTransformer);
@Override
UploadDirectoryRequest build();
}
private static final class DefaultBuilder implements Builder {
private Path source;
private String bucket;
private String s3Prefix;
private String s3Delimiter;
private Boolean followSymbolicLinks;
private Integer maxDepth;
private Consumer<UploadFileRequest.Builder> uploadFileRequestTransformer;
private DefaultBuilder() {
}
private DefaultBuilder(UploadDirectoryRequest request) {
this.source = request.source;
this.bucket = request.bucket;
this.s3Prefix = request.s3Prefix;
this.s3Delimiter = request.s3Delimiter;
this.followSymbolicLinks = request.followSymbolicLinks;
this.maxDepth = request.maxDepth;
this.uploadFileRequestTransformer = request.uploadFileRequestTransformer;
}
@Override
public Builder source(Path source) {
this.source = source;
return this;
}
public void setSource(Path source) {
source(source);
}
public Path getSource() {
return source;
}
@Override
public Builder bucket(String bucket) {
this.bucket = bucket;
return this;
}
public void setBucket(String bucket) {
bucket(bucket);
}
public String getBucket() {
return bucket;
}
@Override
public Builder s3Prefix(String s3Prefix) {
this.s3Prefix = s3Prefix;
return this;
}
public void setS3Prefix(String s3Prefix) {
s3Prefix(s3Prefix);
}
public String getS3Prefix() {
return s3Prefix;
}
@Override
public Builder s3Delimiter(String s3Delimiter) {
this.s3Delimiter = s3Delimiter;
return this;
}
public void setS3Delimiter(String s3Delimiter) {
s3Delimiter(s3Delimiter);
}
public String getS3Delimiter() {
return s3Delimiter;
}
@Override
public Builder followSymbolicLinks(Boolean followSymbolicLinks) {
this.followSymbolicLinks = followSymbolicLinks;
return this;
}
public void setFollowSymbolicLinks(Boolean followSymbolicLinks) {
followSymbolicLinks(followSymbolicLinks);
}
public Boolean getFollowSymbolicLinks() {
return followSymbolicLinks;
}
@Override
public Builder maxDepth(Integer maxDepth) {
this.maxDepth = maxDepth;
return this;
}
public void setMaxDepth(Integer maxDepth) {
maxDepth(maxDepth);
}
public Integer getMaxDepth() {
return maxDepth;
}
@Override
public Builder uploadFileRequestTransformer(Consumer<UploadFileRequest.Builder> uploadFileRequestTransformer) {
this.uploadFileRequestTransformer = uploadFileRequestTransformer;
return this;
}
public Consumer<UploadFileRequest.Builder> getUploadFileRequestTransformer() {
return uploadFileRequestTransformer;
}
public void setUploadFileRequestTransformer(Consumer<UploadFileRequest.Builder> uploadFileRequestTransformer) {
this.uploadFileRequestTransformer = uploadFileRequestTransformer;
}
@Override
public UploadDirectoryRequest build() {
return new UploadDirectoryRequest(this);
}
}
}
| 3,815 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/UploadFileRequest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.transfer.s3.model;
import static software.amazon.awssdk.utils.Validate.paramNotNull;
import java.io.File;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
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.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.transfer.s3.progress.TransferListener;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* Represents the request to upload a local file to an object in S3. For non-file-based uploads, you may use {@link UploadRequest}
* instead.
*
* @see S3TransferManager#uploadFile(UploadFileRequest)
*/
@SdkPublicApi
public final class UploadFileRequest
implements TransferObjectRequest,
ToCopyableBuilder<UploadFileRequest.Builder, UploadFileRequest> {
private final PutObjectRequest putObjectRequest;
private final Path source;
private final List<TransferListener> listeners;
private UploadFileRequest(DefaultBuilder builder) {
this.putObjectRequest = paramNotNull(builder.putObjectRequest, "putObjectRequest");
this.source = paramNotNull(builder.source, "source");
this.listeners = builder.listeners;
}
/**
* @return The {@link PutObjectRequest} request that should be used for the upload
*/
public PutObjectRequest putObjectRequest() {
return putObjectRequest;
}
/**
* The {@link Path} containing data to send to the service.
*
* @return the request body
*/
public Path source() {
return source;
}
/**
* @return the List of transferListeners.
*/
@Override
public List<TransferListener> transferListeners() {
return listeners;
}
/**
* Creates a builder that can be used to create a {@link UploadFileRequest}.
*
* @see S3TransferManager#uploadFile(UploadFileRequest)
*/
public static Builder builder() {
return new DefaultBuilder();
}
public static Class<? extends Builder> serializableBuilderClass() {
return DefaultBuilder.class;
}
@Override
public Builder toBuilder() {
return new DefaultBuilder(this);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
UploadFileRequest that = (UploadFileRequest) o;
if (!Objects.equals(putObjectRequest, that.putObjectRequest)) {
return false;
}
if (!Objects.equals(source, that.source)) {
return false;
}
return Objects.equals(listeners, that.listeners);
}
@Override
public int hashCode() {
int result = putObjectRequest != null ? putObjectRequest.hashCode() : 0;
result = 31 * result + (source != null ? source.hashCode() : 0);
result = 31 * result + (listeners != null ? listeners.hashCode() : 0);
return result;
}
@Override
public String toString() {
return ToString.builder("UploadFileRequest")
.add("putObjectRequest", putObjectRequest)
.add("source", source)
.add("configuration", listeners)
.build();
}
/**
* A builder for a {@link UploadFileRequest}, created with {@link #builder()}
*/
@SdkPublicApi
@NotThreadSafe
public interface Builder extends CopyableBuilder<Builder, UploadFileRequest> {
/**
* The {@link Path} to file containing data to send to the service. File will be read entirely and may be read
* multiple times in the event of a retry. If the file does not exist or the current user does not have
* access to read it then an exception will be thrown.
*
* @param source the source path
* @return Returns a reference to this object so that method calls can be chained together.
*/
Builder source(Path source);
/**
* The file containing data to send to the service. File will be read entirely and may be read
* multiple times in the event of a retry. If the file does not exist or the current user does not have
* access to read it then an exception will be thrown.
*
* @param source the source path
* @return Returns a reference to this object so that method calls can be chained together.
*/
default Builder source(File source) {
Validate.paramNotNull(source, "source");
return this.source(source.toPath());
}
/**
* Configure the {@link PutObjectRequest} that should be used for the upload
*
* @param putObjectRequest the putObjectRequest
* @return Returns a reference to this object so that method calls can be chained together.
* @see #putObjectRequest(Consumer)
*/
Builder putObjectRequest(PutObjectRequest putObjectRequest);
/**
* Configure the {@link PutObjectRequest} that should be used for the upload
*
* <p>
* This is a convenience method that creates an instance of the {@link PutObjectRequest} builder avoiding the
* need to create one manually via {@link PutObjectRequest#builder()}.
*
* @param putObjectRequestBuilder the putObjectRequest consumer builder
* @return Returns a reference to this object so that method calls can be chained together.
* @see #putObjectRequest(PutObjectRequest)
*/
default Builder putObjectRequest(Consumer<PutObjectRequest.Builder> putObjectRequestBuilder) {
return putObjectRequest(PutObjectRequest.builder()
.applyMutation(putObjectRequestBuilder)
.build());
}
/**
* The {@link TransferListener}s that will be notified as part of this request. This method overrides and replaces any
* transferListeners that have already been set. Add an optional request override configuration.
*
* @param transferListeners the collection of transferListeners
* @return Returns a reference to this object so that method calls can be chained together.
* @return This builder for method chaining.
* @see TransferListener
*/
Builder transferListeners(Collection<TransferListener> transferListeners);
/**
* Add a {@link TransferListener} that will be notified as part of this request.
*
* @param transferListener the transferListener to add
* @return Returns a reference to this object so that method calls can be chained together.
* @see TransferListener
*/
Builder addTransferListener(TransferListener transferListener);
}
private static class DefaultBuilder implements Builder {
private PutObjectRequest putObjectRequest;
private Path source;
private List<TransferListener> listeners;
private DefaultBuilder() {
}
private DefaultBuilder(UploadFileRequest uploadFileRequest) {
this.source = uploadFileRequest.source;
this.putObjectRequest = uploadFileRequest.putObjectRequest;
this.listeners = uploadFileRequest.listeners;
}
@Override
public Builder source(Path source) {
this.source = Validate.paramNotNull(source, "source");
return this;
}
public Path getSource() {
return source;
}
public void setSource(Path source) {
source(source);
}
@Override
public Builder putObjectRequest(PutObjectRequest putObjectRequest) {
this.putObjectRequest = putObjectRequest;
return this;
}
public PutObjectRequest getPutObjectRequest() {
return putObjectRequest;
}
public void setPutObjectRequest(PutObjectRequest putObjectRequest) {
putObjectRequest(putObjectRequest);
}
@Override
public Builder transferListeners(Collection<TransferListener> transferListeners) {
this.listeners = transferListeners != null ? new ArrayList<>(transferListeners) : null;
return this;
}
@Override
public Builder addTransferListener(TransferListener transferListener) {
if (listeners == null) {
listeners = new ArrayList<>();
}
listeners.add(transferListener);
return this;
}
public List<TransferListener> getListeners() {
return listeners;
}
public void setListeners(Collection<TransferListener> listeners) {
transferListeners(listeners);
}
@Override
public UploadFileRequest build() {
return new UploadFileRequest(this);
}
}
}
| 3,816 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/Download.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.transfer.s3.model;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.annotations.SdkPublicApi;
/**
* A download transfer of a single object from S3.
*/
@SdkPublicApi
public interface Download<ResultT> extends ObjectTransfer {
@Override
CompletableFuture<CompletedDownload<ResultT>> completionFuture();
}
| 3,817 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/Transfer.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.transfer.s3.model;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.annotations.SdkPublicApi;
/**
* Represents the upload or download of one or more objects to or from S3.
*
* @see ObjectTransfer
* @see DirectoryTransfer
*/
@SdkPublicApi
public interface Transfer {
/**
* @return The future that will be completed when this transfer is complete.
*/
CompletableFuture<? extends CompletedTransfer> completionFuture();
}
| 3,818 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/CompletedUpload.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.transfer.s3.model;
import java.util.Objects;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.model.PutObjectResponse;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
/**
* Represents a completed upload transfer to Amazon S3. It can be used to track
* the underlying {@link PutObjectResponse}
*
* @see S3TransferManager#upload(UploadRequest)
*/
@SdkPublicApi
public final class CompletedUpload implements CompletedObjectTransfer {
private final PutObjectResponse response;
private CompletedUpload(DefaultBuilder builder) {
this.response = Validate.paramNotNull(builder.response, "response");
}
@Override
public PutObjectResponse response() {
return response;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CompletedUpload that = (CompletedUpload) o;
return Objects.equals(response, that.response);
}
@Override
public int hashCode() {
return response.hashCode();
}
@Override
public String toString() {
return ToString.builder("CompletedUpload")
.add("response", response)
.build();
}
public static Class<? extends Builder> serializableBuilderClass() {
return DefaultBuilder.class;
}
/**
* Creates a default builder for {@link CompletedUpload}.
*/
public static Builder builder() {
return new DefaultBuilder();
}
public interface Builder {
/**
* Specifies the {@link PutObjectResponse} from {@link S3AsyncClient#putObject}
*
* @param response the response
* @return This builder for method chaining.
*/
Builder response(PutObjectResponse response);
/**
* Builds a {@link CompletedUpload} based on the properties supplied to this builder
* @return An initialized {@link CompletedUpload}
*/
CompletedUpload build();
}
private static class DefaultBuilder implements Builder {
private PutObjectResponse response;
private DefaultBuilder() {
}
@Override
public Builder response(PutObjectResponse response) {
this.response = response;
return this;
}
@Override
public CompletedUpload build() {
return new CompletedUpload(this);
}
}
}
| 3,819 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/Copy.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.transfer.s3.model;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.annotations.SdkPublicApi;
/**
* A copy transfer of an object that is already stored in S3.
*/
@SdkPublicApi
public interface Copy extends ObjectTransfer {
@Override
CompletableFuture<CompletedCopy> completionFuture();
}
| 3,820 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/CompletedFileDownload.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.transfer.s3.model;
import java.util.Objects;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
/**
* Represents a completed download transfer from Amazon S3. It can be used to track
* the underlying {@link GetObjectResponse}
*
* @see S3TransferManager#downloadFile(DownloadFileRequest)
*/
@SdkPublicApi
public final class CompletedFileDownload implements CompletedObjectTransfer {
private final GetObjectResponse response;
private CompletedFileDownload(DefaultBuilder builder) {
this.response = Validate.paramNotNull(builder.response, "response");
}
@Override
public GetObjectResponse response() {
return response;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CompletedFileDownload that = (CompletedFileDownload) o;
return Objects.equals(response, that.response);
}
@Override
public int hashCode() {
return response != null ? response.hashCode() : 0;
}
@Override
public String toString() {
return ToString.builder("CompletedFileDownload")
.add("response", response)
.build();
}
public static Builder builder() {
return new DefaultBuilder();
}
public interface Builder {
/**
* Specifies the {@link GetObjectResponse} from {@link S3AsyncClient#getObject}
*
* @param response the response
* @return This builder for method chaining.
*/
Builder response(GetObjectResponse response);
/**
* Builds a {@link CompletedFileUpload} based on the properties supplied to this builder
* @return An initialized {@link CompletedFileDownload}
*/
CompletedFileDownload build();
}
private static final class DefaultBuilder implements Builder {
private GetObjectResponse response;
private DefaultBuilder() {
}
@Override
public Builder response(GetObjectResponse response) {
this.response = response;
return this;
}
public void setResponse(GetObjectResponse response) {
response(response);
}
public GetObjectResponse getResponse() {
return response;
}
@Override
public CompletedFileDownload build() {
return new CompletedFileDownload(this);
}
}
}
| 3,821 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/DirectoryUpload.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.transfer.s3.model;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.annotations.SdkPublicApi;
/**
* An upload transfer of a single object to S3.
*/
@SdkPublicApi
public interface DirectoryUpload extends DirectoryTransfer {
@Override
CompletableFuture<CompletedDirectoryUpload> completionFuture();
}
| 3,822 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/FailedFileUpload.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.transfer.s3.model;
import java.util.Objects;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* Represents a failed single file upload from {@link S3TransferManager#uploadDirectory}. It
* has a detailed description of the result.
*/
@SdkPublicApi
public final class FailedFileUpload
implements FailedObjectTransfer,
ToCopyableBuilder<FailedFileUpload.Builder, FailedFileUpload> {
private final UploadFileRequest request;
private final Throwable exception;
private FailedFileUpload(DefaultBuilder builder) {
this.exception = Validate.paramNotNull(builder.exception, "exception");
this.request = Validate.paramNotNull(builder.request, "request");
}
@Override
public Throwable exception() {
return exception;
}
@Override
public UploadFileRequest request() {
return request;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
FailedFileUpload that = (FailedFileUpload) o;
if (!Objects.equals(request, that.request)) {
return false;
}
return Objects.equals(exception, that.exception);
}
@Override
public int hashCode() {
int result = request != null ? request.hashCode() : 0;
result = 31 * result + (exception != null ? exception.hashCode() : 0);
return result;
}
@Override
public String toString() {
return ToString.builder("FailedFileUpload")
.add("request", request)
.add("exception", exception)
.build();
}
public static Builder builder() {
return new DefaultBuilder();
}
public static Class<? extends Builder> serializableBuilderClass() {
return DefaultBuilder.class;
}
@Override
public Builder toBuilder() {
return new DefaultBuilder(this);
}
public interface Builder extends CopyableBuilder<Builder, FailedFileUpload> {
Builder exception(Throwable exception);
Builder request(UploadFileRequest request);
}
private static final class DefaultBuilder implements Builder {
private UploadFileRequest request;
private Throwable exception;
private DefaultBuilder(FailedFileUpload failedFileUpload) {
this.request = failedFileUpload.request;
this.exception = failedFileUpload.exception;
}
private DefaultBuilder() {
}
@Override
public Builder exception(Throwable exception) {
this.exception = exception;
return this;
}
public void setException(Throwable exception) {
exception(exception);
}
public Throwable getException() {
return exception;
}
@Override
public Builder request(UploadFileRequest request) {
this.request = request;
return this;
}
public void setRequest(UploadFileRequest request) {
request(request);
}
public UploadFileRequest getRequest() {
return request;
}
@Override
public FailedFileUpload build() {
return new FailedFileUpload(this);
}
}
}
| 3,823 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/ResumableFileUpload.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.transfer.s3.model;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Instant;
import java.util.Objects;
import java.util.Optional;
import java.util.OptionalLong;
import java.util.function.Consumer;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.transfer.s3.config.TransferRequestOverrideConfiguration;
import software.amazon.awssdk.transfer.s3.internal.serialization.ResumableFileUploadSerializer;
import software.amazon.awssdk.utils.IoUtils;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* POJO class that holds the state and can be used to resume a paused upload file operation.
* <p>
* <b>Serialization: </b>When serializing this token, the following structures will not be preserved/persisted:
* <ul>
* <li>{@link TransferRequestOverrideConfiguration}</li>
* <li>{@link AwsRequestOverrideConfiguration} (from {@link PutObjectRequest})</li>
* </ul>
*
* @see S3TransferManager#uploadFile(UploadFileRequest)
* @see S3TransferManager#resumeUploadFile(ResumableFileUpload)
*/
@SdkPublicApi
public final class ResumableFileUpload implements ResumableTransfer,
ToCopyableBuilder<ResumableFileUpload.Builder, ResumableFileUpload> {
private final UploadFileRequest uploadFileRequest;
private final Instant fileLastModified;
private final String multipartUploadId;
private final Long partSizeInBytes;
private final Long totalParts;
private final long fileLength;
private final Long transferredParts;
private ResumableFileUpload(DefaultBuilder builder) {
this.uploadFileRequest = Validate.paramNotNull(builder.uploadFileRequest, "uploadFileRequest");
this.fileLastModified = Validate.paramNotNull(builder.fileLastModified, "fileLastModified");
this.fileLength = Validate.paramNotNull(builder.fileLength, "fileLength");
this.multipartUploadId = builder.multipartUploadId;
this.totalParts = builder.totalParts;
this.partSizeInBytes = builder.partSizeInBytes;
this.transferredParts = builder.transferredParts;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ResumableFileUpload that = (ResumableFileUpload) o;
if (fileLength != that.fileLength) {
return false;
}
if (!uploadFileRequest.equals(that.uploadFileRequest)) {
return false;
}
if (!fileLastModified.equals(that.fileLastModified)) {
return false;
}
if (!Objects.equals(multipartUploadId, that.multipartUploadId)) {
return false;
}
if (!Objects.equals(partSizeInBytes, that.partSizeInBytes)) {
return false;
}
if (!Objects.equals(transferredParts, that.transferredParts)) {
return false;
}
return Objects.equals(totalParts, that.totalParts);
}
@Override
public int hashCode() {
int result = uploadFileRequest.hashCode();
result = 31 * result + fileLastModified.hashCode();
result = 31 * result + (multipartUploadId != null ? multipartUploadId.hashCode() : 0);
result = 31 * result + (partSizeInBytes != null ? partSizeInBytes.hashCode() : 0);
result = 31 * result + (totalParts != null ? totalParts.hashCode() : 0);
result = 31 * result + (transferredParts != null ? transferredParts.hashCode() : 0);
result = 31 * result + (int) (fileLength ^ (fileLength >>> 32));
return result;
}
public static Builder builder() {
return new DefaultBuilder();
}
/**
* @return the {@link UploadFileRequest} to resume
*/
public UploadFileRequest uploadFileRequest() {
return uploadFileRequest;
}
/**
* Last modified time of the file since last pause
*/
public Instant fileLastModified() {
return fileLastModified;
}
/**
* File length since last pause
*/
public long fileLength() {
return fileLength;
}
/**
* Return the part size in bytes or {@link OptionalLong#empty()} if unknown
*/
public OptionalLong partSizeInBytes() {
return partSizeInBytes == null ? OptionalLong.empty() : OptionalLong.of(partSizeInBytes);
}
/**
* Return the total number of parts associated with this transfer or {@link OptionalLong#empty()} if unknown
*/
public OptionalLong totalParts() {
return totalParts == null ? OptionalLong.empty() : OptionalLong.of(totalParts);
}
/**
* The multipart upload ID, or {@link Optional#empty()} if unknown
*
* @return the optional total size of the transfer.
*/
public Optional<String> multipartUploadId() {
return Optional.ofNullable(multipartUploadId);
}
/**
* Return the total number of parts completed with this transfer or {@link OptionalLong#empty()} if unknown
*/
public OptionalLong transferredParts() {
return transferredParts == null ? OptionalLong.empty() : OptionalLong.of(transferredParts);
}
@Override
public void serializeToFile(Path path) {
try {
Files.write(path, ResumableFileUploadSerializer.toJson(this));
} catch (IOException e) {
throw SdkClientException.create("Failed to write to " + path, e);
}
}
@Override
public void serializeToOutputStream(OutputStream outputStream) {
byte[] bytes = ResumableFileUploadSerializer.toJson(this);
try {
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
IoUtils.copy(byteArrayInputStream, outputStream);
} catch (IOException e) {
throw SdkClientException.create("Failed to write this download object to the given OutputStream", e);
}
}
@Override
public String serializeToString() {
return new String(ResumableFileUploadSerializer.toJson(this), StandardCharsets.UTF_8);
}
@Override
public SdkBytes serializeToBytes() {
return SdkBytes.fromByteArrayUnsafe(ResumableFileUploadSerializer.toJson(this));
}
@Override
public InputStream serializeToInputStream() {
return new ByteArrayInputStream(ResumableFileUploadSerializer.toJson(this));
}
/**
* Deserializes data at the given path into a {@link ResumableFileUpload}.
*
* @param path The {@link Path} to the file with serialized data
* @return the deserialized {@link ResumableFileUpload}
*/
public static ResumableFileUpload fromFile(Path path) {
try (InputStream stream = Files.newInputStream(path)) {
return ResumableFileUploadSerializer.fromJson(stream);
} catch (IOException e) {
throw SdkClientException.create("Failed to create a ResumableFileUpload from " + path, e);
}
}
/**
* Deserializes bytes with JSON data into a {@link ResumableFileUpload}.
*
* @param bytes the serialized data
* @return the deserialized {@link ResumableFileUpload}
*/
public static ResumableFileUpload fromBytes(SdkBytes bytes) {
return ResumableFileUploadSerializer.fromJson(bytes.asByteArrayUnsafe());
}
/**
* Deserializes a string with JSON data into a {@link ResumableFileUpload}.
*
* @param contents the serialized data
* @return the deserialized {@link ResumableFileUpload}
*/
public static ResumableFileUpload fromString(String contents) {
return ResumableFileUploadSerializer.fromJson(contents);
}
@Override
public String toString() {
return ToString.builder("ResumableFileUpload")
.add("fileLastModified", fileLastModified)
.add("multipartUploadId", multipartUploadId)
.add("uploadFileRequest", uploadFileRequest)
.add("fileLength", fileLength)
.add("totalParts", totalParts)
.add("partSizeInBytes", partSizeInBytes)
.add("transferredParts", transferredParts)
.build();
}
@Override
public Builder toBuilder() {
return new DefaultBuilder(this);
}
public interface Builder extends CopyableBuilder<Builder, ResumableFileUpload> {
/**
* Sets the upload file request
*
* @param uploadFileRequest the upload file request
* @return a reference to this object so that method calls can be chained together.
*/
Builder uploadFileRequest(UploadFileRequest uploadFileRequest);
/**
* The {@link UploadFileRequest} request
*
* <p>
* This is a convenience method that creates an instance of the {@link UploadFileRequest} builder avoiding the
* need to create one manually via {@link UploadFileRequest#builder()}.
*
* @param uploadFileRequestBuilder the upload file request builder
* @return a reference to this object so that method calls can be chained together.
* @see #uploadFileRequest(UploadFileRequest)
*/
default ResumableFileUpload.Builder uploadFileRequest(Consumer<UploadFileRequest.Builder>
uploadFileRequestBuilder) {
UploadFileRequest request = UploadFileRequest.builder()
.applyMutation(uploadFileRequestBuilder)
.build();
uploadFileRequest(request);
return this;
}
/**
* Sets multipart ID associated with this transfer
*
* @param multipartUploadId the multipart ID
* @return a reference to this object so that method calls can be chained together.
*/
Builder multipartUploadId(String multipartUploadId);
/**
* Sets the last modified time of the object
*
* @param fileLastModified the last modified time of the file
* @return a reference to this object so that method calls can be chained together.
*/
Builder fileLastModified(Instant fileLastModified);
/**
* Sets the file length
*
* @param fileLength the last modified time of the object
* @return a reference to this object so that method calls can be chained together.
*/
Builder fileLength(Long fileLength);
/**
* Sets the total number of parts
*
* @param totalParts the total number of parts
* @return a reference to this object so that method calls can be chained together.
*/
Builder totalParts(Long totalParts);
/**
* Set the total number of parts transferred
*
* @param transferredParts the number of parts completed
* @return a reference to this object so that method calls can be chained together.
*/
Builder transferredParts(Long transferredParts);
/**
* The part size associated with this transfer
* @param partSizeInBytes the part size in bytes
* @return a reference to this object so that method calls can be chained together.
*/
Builder partSizeInBytes(Long partSizeInBytes);
}
private static final class DefaultBuilder implements Builder {
private String multipartUploadId;
private UploadFileRequest uploadFileRequest;
private Long partSizeInBytes;
private Long totalParts;
private Instant fileLastModified;
private Long fileLength;
private Long transferredParts;
private DefaultBuilder() {
}
private DefaultBuilder(ResumableFileUpload persistableFileUpload) {
this.multipartUploadId = persistableFileUpload.multipartUploadId;
this.uploadFileRequest = persistableFileUpload.uploadFileRequest;
this.partSizeInBytes = persistableFileUpload.partSizeInBytes;
this.fileLastModified = persistableFileUpload.fileLastModified;
this.totalParts = persistableFileUpload.totalParts;
this.fileLength = persistableFileUpload.fileLength;
this.transferredParts = persistableFileUpload.transferredParts;
}
@Override
public Builder uploadFileRequest(UploadFileRequest uploadFileRequest) {
this.uploadFileRequest = uploadFileRequest;
return this;
}
@Override
public Builder multipartUploadId(String mutipartUploadId) {
this.multipartUploadId = mutipartUploadId;
return this;
}
@Override
public Builder fileLastModified(Instant fileLastModified) {
this.fileLastModified = fileLastModified;
return this;
}
@Override
public Builder fileLength(Long fileLength) {
this.fileLength = fileLength;
return this;
}
@Override
public Builder totalParts(Long totalParts) {
this.totalParts = totalParts;
return this;
}
@Override
public Builder transferredParts(Long transferredParts) {
this.transferredParts = transferredParts;
return this;
}
@Override
public Builder partSizeInBytes(Long partSizeInBytes) {
this.partSizeInBytes = partSizeInBytes;
return this;
}
@Override
public ResumableFileUpload build() {
return new ResumableFileUpload(this);
}
}
}
| 3,824 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/ResumableTransfer.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.transfer.s3.model;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Path;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.SdkBytes;
/**
* Contains the information of a pausible upload or download; such
* information can be used to resume the upload or download later on
*
* @see FileDownload#pause()
*/
@SdkPublicApi
public interface ResumableTransfer {
/**
* Persists this download object to a file in Base64-encoded JSON format.
*
* @param path The path to the file to which you want to write the serialized download object.
*/
default void serializeToFile(Path path) {
throw new UnsupportedOperationException();
}
/**
* Writes the serialized JSON data representing this object to an output stream.
* Note that the {@link OutputStream} is not closed or flushed after writing.
*
* @param outputStream The output stream to write the serialized object to.
*/
default void serializeToOutputStream(OutputStream outputStream) {
throw new UnsupportedOperationException();
}
/**
* Returns the serialized JSON data representing this object as a string.
*/
default String serializeToString() {
throw new UnsupportedOperationException();
}
/**
* Returns the serialized JSON data representing this object as an {@link SdkBytes} object.
*
* @return the serialized JSON as {@link SdkBytes}
*/
default SdkBytes serializeToBytes() {
throw new UnsupportedOperationException();
}
/**
* Returns the serialized JSON data representing this object as an {@link InputStream}.
*
* @return the serialized JSON input stream
*/
default InputStream serializeToInputStream() {
throw new UnsupportedOperationException();
}
}
| 3,825 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/Upload.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.transfer.s3.model;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.annotations.SdkPublicApi;
/**
* An upload transfer of a single object to S3.
*/
@SdkPublicApi
public interface Upload extends ObjectTransfer {
@Override
CompletableFuture<CompletedUpload> completionFuture();
}
| 3,826 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/FileUpload.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.transfer.s3.model;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
/**
* An upload transfer of a single object to S3.
*/
@SdkPublicApi
public interface FileUpload extends ObjectTransfer {
/**
* Pauses the current upload operation and return the information that can
* be used to resume the upload at a later time.
* <p>
* The information object is serializable for persistent storage until it should be resumed.
* See {@link ResumableFileUpload} for supported formats.
*
* <p>
* Currently, it's only supported if the underlying {@link S3AsyncClient} is CRT-based (created via
* {@link S3AsyncClient#crtBuilder()} or {@link S3AsyncClient#crtCreate()}).
* It will throw {@link UnsupportedOperationException} if the {@link S3TransferManager} is created
* with a non CRT-based S3 client (created via {@link S3AsyncClient#builder()}).
*
* @return A {@link ResumableFileUpload} that can be used to resume the upload.
*/
ResumableFileUpload pause();
@Override
CompletableFuture<CompletedFileUpload> completionFuture();
}
| 3,827 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/CompletedDirectoryUpload.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.transfer.s3.model;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* Represents a completed upload directory transfer to Amazon S3. It can be used to track
* failed single file uploads.
*
* @see S3TransferManager#uploadDirectory(UploadDirectoryRequest)
*/
@SdkPublicApi
public final class CompletedDirectoryUpload implements CompletedDirectoryTransfer,
ToCopyableBuilder<CompletedDirectoryUpload.Builder,
CompletedDirectoryUpload> {
private final List<FailedFileUpload> failedTransfers;
private CompletedDirectoryUpload(DefaultBuilder builder) {
this.failedTransfers = Collections.unmodifiableList(
new ArrayList<>(Validate.paramNotNull(builder.failedTransfers, "failedTransfers")));
}
@Override
public List<FailedFileUpload> failedTransfers() {
return failedTransfers;
}
/**
* Creates a default builder for {@link CompletedDirectoryUpload}.
*/
public static Builder builder() {
return new DefaultBuilder();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CompletedDirectoryUpload that = (CompletedDirectoryUpload) o;
return Objects.equals(failedTransfers, that.failedTransfers);
}
@Override
public int hashCode() {
return failedTransfers != null ? failedTransfers.hashCode() : 0;
}
@Override
public String toString() {
return ToString.builder("CompletedDirectoryUpload")
.add("failedTransfers", failedTransfers)
.build();
}
public static Class<? extends Builder> serializableBuilderClass() {
return DefaultBuilder.class;
}
@Override
public Builder toBuilder() {
return new DefaultBuilder(this);
}
public interface Builder extends CopyableBuilder<CompletedDirectoryUpload.Builder,
CompletedDirectoryUpload> {
/**
* Sets a collection of {@link FailedFileUpload}s
*
* @param failedTransfers failed uploads
* @return This builder for method chaining.
*/
Builder failedTransfers(Collection<FailedFileUpload> failedTransfers);
/**
* Adds a {@link FailedFileUpload}
*
* @param failedTransfer failed upload
* @return This builder for method chaining.
*/
Builder addFailedTransfer(FailedFileUpload failedTransfer);
/**
* Builds a {@link CompletedDirectoryUpload} based on the properties supplied to this builder
* @return An initialized {@link CompletedDirectoryUpload}
*/
CompletedDirectoryUpload build();
}
private static final class DefaultBuilder implements Builder {
private Collection<FailedFileUpload> failedTransfers = new ArrayList<>();
private DefaultBuilder() {
}
private DefaultBuilder(CompletedDirectoryUpload completedDirectoryUpload) {
this.failedTransfers = new ArrayList<>(completedDirectoryUpload.failedTransfers);
}
@Override
public Builder failedTransfers(Collection<FailedFileUpload> failedTransfers) {
this.failedTransfers = new ArrayList<>(failedTransfers);
return this;
}
@Override
public Builder addFailedTransfer(FailedFileUpload failedTransfer) {
failedTransfers.add(failedTransfer);
return this;
}
public Collection<FailedFileUpload> getFailedTransfers() {
return Collections.unmodifiableCollection(failedTransfers);
}
public void setFailedTransfers(Collection<FailedFileUpload> failedTransfers) {
failedTransfers(failedTransfers);
}
@Override
public CompletedDirectoryUpload build() {
return new CompletedDirectoryUpload(this);
}
}
}
| 3,828 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/FileDownload.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.transfer.s3.model;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.ThreadSafe;
/**
* A download transfer of a single object from S3.
*/
@SdkPublicApi
@ThreadSafe
public interface FileDownload extends ObjectTransfer {
/**
* Pause the current download operation and returns the information that can
* be used to resume the download at a later time.
* <p>
* The information object is serializable for persistent storage until it should be resumed.
* See {@link ResumableFileDownload} for supported formats.
*
* @return A {@link ResumableFileDownload} that can be used to resume the download.
*/
ResumableFileDownload pause();
@Override
CompletableFuture<CompletedFileDownload> completionFuture();
}
| 3,829 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/NestedAttributeNameTest.java | package software.amazon.awssdk.enhanced.dynamodb;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.util.Collections;
import org.junit.jupiter.api.Test;
public class NestedAttributeNameTest {
private static final String ATTRIBUTE_NAME = "attributeName";
@Test
public void testNullAttributeNames_fails() {
assertThatThrownBy(() -> NestedAttributeName.builder().build())
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("nestedAttributeNames must not be null");
assertThatThrownBy(() -> NestedAttributeName.builder().addElement(null).build())
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("nestedAttributeNames must not contain null values");
assertThatThrownBy(() -> NestedAttributeName.builder().elements(ATTRIBUTE_NAME).addElement(null).build())
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("nestedAttributeNames must not contain null values");
assertThatThrownBy(() -> NestedAttributeName.create())
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("nestedAttributeNames must not be empty");
}
@Test
public void testEmptyAttributeNameList_fails() {
assertThatThrownBy(() -> NestedAttributeName.builder().elements(Collections.emptyList()).build())
.isInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(() -> NestedAttributeName.create(Collections.emptyList()))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
public void testEmptyAttributeNames_allowed() {
NestedAttributeName.builder().elements(Collections.singletonList("")).build();
NestedAttributeName.create(Collections.singletonList(""));
}
@Test
public void testEmptyAttributeNames_toString() {
NestedAttributeName nestedAttribute = NestedAttributeName.create("Attribute1", "Attribute*2", "Attribute-3");
assertThat(nestedAttribute.toString()).isEqualTo("Attribute1.Attribute*2.Attribute-3");
}
@Test
public void toBuilder() {
NestedAttributeName builtObject = NestedAttributeName.builder().addElement(ATTRIBUTE_NAME).build();
NestedAttributeName copiedObject = builtObject.toBuilder().build();
assertThat(copiedObject).isEqualTo(builtObject);
}
}
| 3,830 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/KeyTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItemWithIndices;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
public class KeyTest {
private final Key key = Key.builder().partitionValue("id123").sortValue("id456").build();
private final Key partitionOnlyKey = Key.builder().partitionValue("id123").build();
@Test
public void getKeyMap() {
Map<String, AttributeValue> expectedResult = new HashMap<>();
expectedResult.put("gsi_id", AttributeValue.builder().s("id123").build());
expectedResult.put("gsi_sort", AttributeValue.builder().s("id456").build());
assertThat(key.keyMap(FakeItemWithIndices.getTableSchema(), "gsi_1"), is(expectedResult));
}
@Test
public void getPrimaryKeyMap() {
Map<String, AttributeValue> expectedResult = new HashMap<>();
expectedResult.put("id", AttributeValue.builder().s("id123").build());
expectedResult.put("sort", AttributeValue.builder().s("id456").build());
assertThat(key.primaryKeyMap(FakeItemWithIndices.getTableSchema()), is(expectedResult));
}
@Test
public void getPartitionKeyValue() {
assertThat(key.partitionKeyValue(),
is(AttributeValue.builder().s("id123").build()));
}
@Test
public void getSortKeyValue() {
assertThat(key.sortKeyValue(), is(Optional.of(AttributeValue.builder().s("id456").build())));
}
@Test
public void getKeyMap_partitionOnly() {
Map<String, AttributeValue> expectedResult = new HashMap<>();
expectedResult.put("gsi_id", AttributeValue.builder().s("id123").build());
assertThat(partitionOnlyKey.keyMap(FakeItemWithIndices.getTableSchema(), "gsi_1"), is(expectedResult));
}
@Test
public void getPrimaryKeyMap_partitionOnly() {
Map<String, AttributeValue> expectedResult = new HashMap<>();
expectedResult.put("id", AttributeValue.builder().s("id123").build());
assertThat(partitionOnlyKey.primaryKeyMap(FakeItemWithIndices.getTableSchema()), is(expectedResult));
}
@Test
public void getPartitionKeyValue_partitionOnly() {
assertThat(partitionOnlyKey.partitionKeyValue(),
is(AttributeValue.builder().s("id123").build()));
}
@Test
public void getSortKeyValue_partitionOnly() {
assertThat(partitionOnlyKey.sortKeyValue(), is(Optional.empty()));
}
@Test
public void numericKeys_convertsToCorrectAttributeValue() {
Key key = Key.builder().partitionValue(123).sortValue(45.6).build();
assertThat(key.partitionKeyValue(), is(AttributeValue.builder().n("123").build()));
assertThat(key.sortKeyValue(), is(Optional.of(AttributeValue.builder().n("45.6").build())));
}
@Test
public void stringKeys_convertsToCorrectAttributeValue() {
Key key = Key.builder().partitionValue("one").sortValue("two").build();
assertThat(key.partitionKeyValue(), is(AttributeValue.builder().s("one").build()));
assertThat(key.sortKeyValue(), is(Optional.of(AttributeValue.builder().s("two").build())));
}
@Test
public void binaryKeys_convertsToCorrectAttributeValue() {
SdkBytes partition = SdkBytes.fromString("one", StandardCharsets.UTF_8);
SdkBytes sort = SdkBytes.fromString("two", StandardCharsets.UTF_8);
Key key = Key.builder().partitionValue(partition).sortValue(sort).build();
assertThat(key.partitionKeyValue(), is(AttributeValue.builder().b(partition).build()));
assertThat(key.sortKeyValue(), is(Optional.of(AttributeValue.builder().b(sort).build())));
}
@Test
public void toBuilder() {
Key keyClone = key.toBuilder().build();
assertThat(key, is(equalTo(keyClone)));
}
@Test
public void nullPartitionKey_shouldThrowException() {
AttributeValue attributeValue = null;
assertThatThrownBy(() -> Key.builder().partitionValue(attributeValue).build())
.isInstanceOf(IllegalArgumentException.class).hasMessageContaining("partitionValue should not be null");
assertThatThrownBy(() -> Key.builder().partitionValue(AttributeValue.builder().nul(true).build()).build())
.isInstanceOf(IllegalArgumentException.class).hasMessageContaining("partitionValue should not be null");
}
}
| 3,831 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/ProjectionExpressionTest.java | package software.amazon.awssdk.enhanced.dynamodb;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.enhanced.dynamodb.internal.ProjectionExpression;
public class ProjectionExpressionTest {
private static final String NESTING_SEPARATOR = ".";
private static final String PROJ_EXP_SEPARATOR = ",";
private static final Map<String, String> EXPECTED_ATTRIBUTE_NAMES = new HashMap<>();
static {
EXPECTED_ATTRIBUTE_NAMES.put("#AMZN_MAPPED_attribute", "attribute");
EXPECTED_ATTRIBUTE_NAMES.put("#AMZN_MAPPED_Attribute", "Attribute");
EXPECTED_ATTRIBUTE_NAMES.put("#AMZN_MAPPED_firstiteminlist[0]", "firstiteminlist[0]");
EXPECTED_ATTRIBUTE_NAMES.put("#AMZN_MAPPED_March_2021", "March-2021");
EXPECTED_ATTRIBUTE_NAMES.put("#AMZN_MAPPED_Why_Make_This_An_Attribute_Name", "Why.Make-This*An:Attribute:Name");
}
@Test
public void nullInputSetsStateCorrectly() {
ProjectionExpression projectionExpression = ProjectionExpression.create(null);
assertThat(projectionExpression.expressionAttributeNames()).isEmpty();
assertThat(projectionExpression.projectionExpressionAsString()).isEmpty();
}
@Test
public void emptyInputSetsStateCorrectly() {
ProjectionExpression projectionExpression = ProjectionExpression.create(new ArrayList<>());
assertThat(projectionExpression.expressionAttributeNames()).isEmpty();
assertThat(projectionExpression.projectionExpressionAsString()).isEmpty();
}
@Test
public void severalTopLevelAttributes_handledCorrectly() {
List<NestedAttributeName> attributeNames = EXPECTED_ATTRIBUTE_NAMES.values()
.stream()
.map(NestedAttributeName::create)
.collect(Collectors.toList());
String expectedProjectionExpression = EXPECTED_ATTRIBUTE_NAMES.keySet()
.stream()
.collect(Collectors.joining(PROJ_EXP_SEPARATOR));
assertProjectionExpression(attributeNames, EXPECTED_ATTRIBUTE_NAMES, expectedProjectionExpression);
}
@Test
public void severalNestedAttributes_handledCorrectly() {
List<NestedAttributeName> attributeNames = Arrays.asList(NestedAttributeName.create(
EXPECTED_ATTRIBUTE_NAMES.values()
.stream()
.collect(Collectors.toList())));
String expectedProjectionExpression = EXPECTED_ATTRIBUTE_NAMES.keySet()
.stream()
.collect(Collectors.joining(NESTING_SEPARATOR));
assertProjectionExpression(attributeNames, EXPECTED_ATTRIBUTE_NAMES, expectedProjectionExpression);
}
@Test
public void nonUniqueAttributeNames_AreCollapsed() {
Map<String, String> expectedAttributeNames = new HashMap<>();
expectedAttributeNames.put("#AMZN_MAPPED_attribute", "attribute");
List<NestedAttributeName> attributeNames = Arrays.asList(
NestedAttributeName.create("attribute", "attribute"),
NestedAttributeName.create("attribute")
);
String expectedProjectionExpression = "#AMZN_MAPPED_attribute.#AMZN_MAPPED_attribute,#AMZN_MAPPED_attribute";
assertProjectionExpression(attributeNames, expectedAttributeNames, expectedProjectionExpression);
}
@Test
public void nonUniquePlaceholders_AreDisambiguated() {
Map<String, String> expectedAttributeNames = new HashMap<>();
expectedAttributeNames.put("#AMZN_MAPPED_0_attribute_03", "attribute-03");
expectedAttributeNames.put("#AMZN_MAPPED_1_attribute_03", "attribute.03");
expectedAttributeNames.put("#AMZN_MAPPED_2_attribute_03", "attribute:03");
List<NestedAttributeName> attributeNames = Arrays.asList(
NestedAttributeName.create("attribute-03", "attribute.03"),
NestedAttributeName.create("attribute:03")
);
String expectedProjectionExpression = "#AMZN_MAPPED_0_attribute_03.#AMZN_MAPPED_1_attribute_03,"
+ "#AMZN_MAPPED_2_attribute_03";
assertProjectionExpression(attributeNames, expectedAttributeNames, expectedProjectionExpression);
}
private void assertProjectionExpression(List<NestedAttributeName> attributeNames,
Map<String, String> expectedAttributeNames,
String expectedProjectionExpression) {
ProjectionExpression projectionExpression = ProjectionExpression.create(attributeNames);
Map<String, String> expressionAttributeNames = projectionExpression.expressionAttributeNames();
Optional<String> projectionExpressionString = projectionExpression.projectionExpressionAsString();
assertThat(projectionExpressionString.get()).isEqualTo(expectedProjectionExpression);
assertThat(expressionAttributeNames).isEqualTo(expectedAttributeNames);
}
}
| 3,832 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/ExpressionTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasEntry;
import static org.hamcrest.Matchers.is;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import software.amazon.awssdk.enhanced.dynamodb.internal.converter.attribute.EnhancedAttributeValue;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
public class ExpressionTest {
@Rule
public ExpectedException exception = ExpectedException.none();
@Test
public void join_correctlyWrapsExpressions() {
Expression expression1 = Expression.builder().expression("one").build();
Expression expression2 = Expression.builder().expression("two").build();
Expression expression3 = Expression.builder().expression("three").build();
Expression coalescedExpression = Expression.join(Expression.join(expression1, expression2, " AND "),
expression3, " AND ");
String expectedExpression = "((one) AND (two)) AND (three)";
assertThat(coalescedExpression.expression(), is(expectedExpression));
}
@Test
public void joinExpressions_correctlyJoins() {
String result = Expression.joinExpressions("one", "two", " AND ");
assertThat(result, is("(one) AND (two)"));
}
@Test
public void joinNames_correctlyJoins() {
Map<String, String> names1 = new HashMap<>();
names1.put("one", "1");
names1.put("two", "2");
Map<String, String> names2 = new HashMap<>();
names2.put("three", "3");
names2.put("four", "4");
Map<String, String> result = Expression.joinNames(names1, names2);
assertThat(result.size(), is(4));
assertThat(result, hasEntry("one", "1"));
assertThat(result, hasEntry("two", "2"));
assertThat(result, hasEntry("three", "3"));
assertThat(result, hasEntry("four", "4"));
}
@Test
public void joinNames_correctlyJoinsEmpty() {
Map<String, String> names1 = new HashMap<>();
names1.put("one", "1");
names1.put("two", "2");
Map<String, String> names2 = new HashMap<>();
names2.put("three", "3");
names2.put("four", "4");
Map<String, String> result = Expression.joinNames(names1, null);
assertThat(result.size(), is(2));
assertThat(result, hasEntry("one", "1"));
assertThat(result, hasEntry("two", "2"));
result = Expression.joinNames(null, names2);
assertThat(result.size(), is(2));
assertThat(result, hasEntry("three", "3"));
assertThat(result, hasEntry("four", "4"));
result = Expression.joinNames(names1, Collections.emptyMap());
assertThat(result.size(), is(2));
assertThat(result, hasEntry("one", "1"));
assertThat(result, hasEntry("two", "2"));
result = Expression.joinNames(Collections.emptyMap(), names2);
assertThat(result.size(), is(2));
assertThat(result, hasEntry("three", "3"));
assertThat(result, hasEntry("four", "4"));
}
@Test
public void joinNames_conflictingKey() {
Map<String, String> names1 = new HashMap<>();
names1.put("one", "1");
names1.put("two", "2");
Map<String, String> names2 = new HashMap<>();
names2.put("three", "3");
names2.put("two", "4");
exception.expect(IllegalArgumentException.class);
exception.expectMessage("two");
Expression.joinNames(names1, names2);
}
@Test
public void joinValues_correctlyJoins() {
Map<String, AttributeValue> values1 = new HashMap<>();
values1.put("one", EnhancedAttributeValue.fromString("1").toAttributeValue());
values1.put("two", EnhancedAttributeValue.fromString("2").toAttributeValue());
Map<String, AttributeValue> values2 = new HashMap<>();
values2.put("three", EnhancedAttributeValue.fromString("3").toAttributeValue());
values2.put("four", EnhancedAttributeValue.fromString("4").toAttributeValue());
Map<String, AttributeValue> result = Expression.joinValues(values1, values2);
assertThat(result.size(), is(4));
assertThat(result, hasEntry("one", EnhancedAttributeValue.fromString("1").toAttributeValue()));
assertThat(result, hasEntry("two", EnhancedAttributeValue.fromString("2").toAttributeValue()));
assertThat(result, hasEntry("three", EnhancedAttributeValue.fromString("3").toAttributeValue()));
assertThat(result, hasEntry("four", EnhancedAttributeValue.fromString("4").toAttributeValue()));
}
@Test
public void joinValues_conflictingKey() {
Map<String, AttributeValue> values1 = new HashMap<>();
values1.put("one", EnhancedAttributeValue.fromString("1").toAttributeValue());
values1.put("two", EnhancedAttributeValue.fromString("2").toAttributeValue());
Map<String, AttributeValue> values2 = new HashMap<>();
values2.put("three", EnhancedAttributeValue.fromString("3").toAttributeValue());
values2.put("two", EnhancedAttributeValue.fromString("4").toAttributeValue());
exception.expect(IllegalArgumentException.class);
exception.expectMessage("two");
Expression.joinValues(values1, values2);
}
}
| 3,833 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/EnhancedTypeDocumentationConfigurationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
public class EnhancedTypeDocumentationConfigurationTest {
@Test
public void defaultBuilder_defaultToFalse() {
EnhancedTypeDocumentConfiguration configuration =
EnhancedTypeDocumentConfiguration.builder().build();
assertThat(configuration.ignoreNulls()).isFalse();
assertThat(configuration.preserveEmptyObject()).isFalse();
}
@Test
public void equalsHashCode() {
EnhancedTypeDocumentConfiguration configuration =
EnhancedTypeDocumentConfiguration.builder()
.preserveEmptyObject(true)
.ignoreNulls(false)
.build();
EnhancedTypeDocumentConfiguration another =
EnhancedTypeDocumentConfiguration.builder()
.preserveEmptyObject(true)
.ignoreNulls(false)
.build();
EnhancedTypeDocumentConfiguration different =
EnhancedTypeDocumentConfiguration.builder()
.preserveEmptyObject(false)
.ignoreNulls(true)
.build();
assertThat(configuration).isEqualTo(another);
assertThat(configuration.hashCode()).isEqualTo(another.hashCode());
assertThat(configuration).isNotEqualTo(different);
assertThat(configuration.hashCode()).isNotEqualTo(different.hashCode());
}
}
| 3,834 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/TableSchemaTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeItem;
import software.amazon.awssdk.enhanced.dynamodb.mapper.BeanTableSchema;
import software.amazon.awssdk.enhanced.dynamodb.mapper.ImmutableTableSchema;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticImmutableTableSchema;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema;
import software.amazon.awssdk.enhanced.dynamodb.mapper.testbeans.InvalidBean;
import software.amazon.awssdk.enhanced.dynamodb.mapper.testbeans.SimpleBean;
import software.amazon.awssdk.enhanced.dynamodb.mapper.testbeans.SimpleImmutable;
public class TableSchemaTest {
@Rule
public ExpectedException exception = ExpectedException.none();
@Test
public void builder_constructsStaticTableSchemaBuilder_fromClass() {
StaticTableSchema.Builder<FakeItem> builder = TableSchema.builder(FakeItem.class);
assertThat(builder).isNotNull();
}
@Test
public void builder_constructsStaticTableSchemaBuilder_fromEnhancedType() {
StaticTableSchema.Builder<FakeItem> builder = TableSchema.builder(EnhancedType.of(FakeItem.class));
assertThat(builder).isNotNull();
}
@Test
public void builder_constructsStaticImmutableTableSchemaBuilder_fromClass() {
StaticImmutableTableSchema.Builder<SimpleImmutable, SimpleImmutable.Builder> builder =
TableSchema.builder(SimpleImmutable.class, SimpleImmutable.Builder.class);
assertThat(builder).isNotNull();
}
@Test
public void builder_constructsStaticImmutableTableSchemaBuilder_fromEnhancedType() {
StaticImmutableTableSchema.Builder<SimpleImmutable, SimpleImmutable.Builder> builder =
TableSchema.builder(EnhancedType.of(SimpleImmutable.class), EnhancedType.of(SimpleImmutable.Builder.class));
assertThat(builder).isNotNull();
}
@Test
public void fromBean_constructsBeanTableSchema() {
BeanTableSchema<SimpleBean> beanBeanTableSchema = TableSchema.fromBean(SimpleBean.class);
assertThat(beanBeanTableSchema).isNotNull();
}
@Test
public void fromImmutable_constructsImmutableTableSchema() {
ImmutableTableSchema<SimpleImmutable> immutableTableSchema =
TableSchema.fromImmutableClass(SimpleImmutable.class);
assertThat(immutableTableSchema).isNotNull();
}
@Test
public void fromClass_constructsBeanTableSchema() {
TableSchema<SimpleBean> tableSchema = TableSchema.fromClass(SimpleBean.class);
assertThat(tableSchema).isInstanceOf(BeanTableSchema.class);
}
@Test
public void fromClass_constructsImmutableTableSchema() {
TableSchema<SimpleImmutable> tableSchema = TableSchema.fromClass(SimpleImmutable.class);
assertThat(tableSchema).isInstanceOf(ImmutableTableSchema.class);
}
@Test
public void fromClass_invalidClassThrowsException() {
exception.expect(IllegalArgumentException.class);
exception.expectMessage("InvalidBean");
TableSchema.fromClass(InvalidBean.class);
}
}
| 3,835 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/EnhancedTypeTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.util.Collection;
import java.util.Deque;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
import java.util.NavigableSet;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.concurrent.ConcurrentMap;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema;
public class EnhancedTypeTest {
@Test
public void anonymousCreationCapturesComplexTypeArguments() {
EnhancedType<Map<String, List<List<String>>>> enhancedType = new EnhancedType<Map<String, List<List<String>>>>(){};
assertThat(enhancedType.rawClass()).isEqualTo(Map.class);
assertThat(enhancedType.rawClassParameters().get(0).rawClass()).isEqualTo(String.class);
assertThat(enhancedType.rawClassParameters().get(1).rawClass()).isEqualTo(List.class);
assertThat(enhancedType.rawClassParameters().get(1).rawClassParameters().get(0).rawClass()).isEqualTo(List.class);
assertThat(enhancedType.rawClassParameters().get(1).rawClassParameters().get(0).rawClassParameters().get(0).rawClass())
.isEqualTo(String.class);
}
@Test
public void customTypesWork() {
EnhancedType<EnhancedTypeTest> enhancedType = new EnhancedType<EnhancedTypeTest>(){};
assertThat(enhancedType.rawClass()).isEqualTo(EnhancedTypeTest.class);
}
@Test
public void nonStaticInnerTypesWork() {
EnhancedType<InnerType> enhancedType = new EnhancedType<InnerType>(){};
assertThat(enhancedType.rawClass()).isEqualTo(InnerType.class);
}
@Test
public void staticInnerTypesWork() {
EnhancedType<InnerStaticType> enhancedType = new EnhancedType<InnerStaticType>(){};
assertThat(enhancedType.rawClass()).isEqualTo(InnerStaticType.class);
}
@Test
public <T> void genericParameterTypesDontWork() {
assertThatThrownBy(() -> new EnhancedType<List<T>>(){}).isInstanceOf(IllegalStateException.class);
}
@Test
public void helperCreationMethodsWork() {
assertThat(EnhancedType.of(String.class).rawClass()).isEqualTo(String.class);
assertThat(EnhancedType.listOf(String.class)).satisfies(v -> {
assertThat(v.rawClass()).isEqualTo(List.class);
assertThat(v.rawClassParameters()).hasSize(1);
assertThat(v.rawClassParameters().get(0).rawClass()).isEqualTo(String.class);
});
assertThat(EnhancedType.mapOf(String.class, Integer.class)).satisfies(v -> {
assertThat(v.rawClass()).isEqualTo(Map.class);
assertThat(v.rawClassParameters()).hasSize(2);
assertThat(v.rawClassParameters().get(0).rawClass()).isEqualTo(String.class);
assertThat(v.rawClassParameters().get(1).rawClass()).isEqualTo(Integer.class);
});
}
@Test
public void equalityIsBasedOnInnerEquality() {
verifyEquals(EnhancedType.of(String.class), EnhancedType.of(String.class));
verifyNotEquals(EnhancedType.of(String.class), EnhancedType.of(Integer.class));
verifyEquals(new EnhancedType<Map<String, List<String>>>(){}, new EnhancedType<Map<String, List<String>>>(){});
verifyNotEquals(new EnhancedType<Map<String, List<String>>>(){}, new EnhancedType<Map<String,
List<Integer>>>(){});
TableSchema<String> tableSchema = StaticTableSchema.builder(String.class).build();
verifyNotEquals(EnhancedType.documentOf(String.class,
tableSchema,
b -> b.ignoreNulls(false)), EnhancedType.documentOf(String.class,
tableSchema,
b -> b.ignoreNulls(true)));
verifyEquals(EnhancedType.documentOf(String.class,
tableSchema,
b -> b.ignoreNulls(false).preserveEmptyObject(true)),
EnhancedType.documentOf(String.class,
tableSchema,
b -> b.ignoreNulls(false).preserveEmptyObject(true)));
}
@Test
public void dequeOf_ReturnsRawClassOfDeque_WhenSpecifyingClass() {
EnhancedType<Deque<String>> type = EnhancedType.dequeOf(String.class);
assertThat(type.rawClass()).isEqualTo(Deque.class);
assertThat(type.rawClassParameters()).containsExactly(EnhancedType.of(String.class));
}
@Test
public void dequeOf_ReturnsRawClassOfDeque_WhenSpecifyingEnhancedType() {
EnhancedType<Deque<String>> type = EnhancedType.dequeOf(EnhancedType.of(String.class));
assertThat(type.rawClass()).isEqualTo(Deque.class);
assertThat(type.rawClassParameters()).containsExactly(EnhancedType.of(String.class));
}
@Test
public void sortedSetOf_ReturnsRawClassOfDeque_WhenSpecifyingClass() {
EnhancedType<SortedSet<String>> type = EnhancedType.sortedSetOf(String.class);
assertThat(type.rawClass()).isEqualTo(SortedSet.class);
assertThat(type.rawClassParameters()).containsExactly(EnhancedType.of(String.class));
}
@Test
public void sortedSetOf_ReturnsRawClassOfDeque_WhenSpecifyingEnhancedType() {
EnhancedType<SortedSet<String>> type = EnhancedType.sortedSetOf(EnhancedType.of(String.class));
assertThat(type.rawClass()).isEqualTo(SortedSet.class);
assertThat(type.rawClassParameters()).containsExactly(EnhancedType.of(String.class));
}
@Test
public void navigableSetOf_ReturnsRawClassOfNavigableSet_WhenSpecifyingClass() {
EnhancedType<NavigableSet<String>> type = EnhancedType.navigableSetOf(String.class);
assertThat(type.rawClass()).isEqualTo(NavigableSet.class);
assertThat(type.rawClassParameters()).containsExactly(EnhancedType.of(String.class));
}
@Test
public void navigableSetOf_ReturnsRawClassOfNavigableSet_WhenSpecifyingEnhancedType() {
EnhancedType<NavigableSet<String>> type = EnhancedType.navigableSetOf(EnhancedType.of(String.class));
assertThat(type.rawClass()).isEqualTo(NavigableSet.class);
assertThat(type.rawClassParameters()).containsExactly(EnhancedType.of(String.class));
}
@Test
public void collectionOf_ReturnsRawClassOfCollection_WhenSpecifyingClass() {
EnhancedType<Collection<String>> type = EnhancedType.collectionOf(String.class);
assertThat(type.rawClass()).isEqualTo(Collection.class);
assertThat(type.rawClassParameters()).containsExactly(EnhancedType.of(String.class));
}
@Test
public void collectionOf_ReturnsRawClassOfCollection_WhenSpecifyingEnhancedType() {
EnhancedType<Collection<String>> type = EnhancedType.collectionOf(EnhancedType.of(String.class));
assertThat(type.rawClass()).isEqualTo(Collection.class);
assertThat(type.rawClassParameters()).containsExactly(EnhancedType.of(String.class));
}
@Test
public void sortedMapOf_ReturnsRawClassOfSortedMap_WhenSpecifyingClass() {
EnhancedType<SortedMap<String, Integer>> type = EnhancedType.sortedMapOf(String.class, Integer.class);
assertThat(type.rawClass()).isEqualTo(SortedMap.class);
assertThat(type.rawClassParameters()).containsExactly(EnhancedType.of(String.class), EnhancedType.of(Integer.class));
}
@Test
public void sortedMapOf_ReturnsRawClassOfSortedMap_WhenSpecifyingEnhancedType() {
EnhancedType<SortedMap<String, Integer>> type =
EnhancedType.sortedMapOf(EnhancedType.of(String.class), EnhancedType.of(Integer.class));
assertThat(type.rawClass()).isEqualTo(SortedMap.class);
assertThat(type.rawClassParameters()).containsExactly(EnhancedType.of(String.class), EnhancedType.of(Integer.class));
}
@Test
public void concurrentMapOf_ReturnsRawClassOfConcurrentMap_WhenSpecifyingClass() {
EnhancedType<ConcurrentMap<String, Integer>> type = EnhancedType.concurrentMapOf(String.class, Integer.class);
assertThat(type.rawClass()).isEqualTo(ConcurrentMap.class);
assertThat(type.rawClassParameters()).containsExactly(EnhancedType.of(String.class), EnhancedType.of(Integer.class));
}
@Test
public void concurrentMapOf_ReturnsRawClassOfConcurrentMap_WhenSpecifyingEnhancedType() {
EnhancedType<ConcurrentMap<String, Integer>> type =
EnhancedType.concurrentMapOf(EnhancedType.of(String.class), EnhancedType.of(Integer.class));
assertThat(type.rawClass()).isEqualTo(ConcurrentMap.class);
assertThat(type.rawClassParameters()).containsExactly(EnhancedType.of(String.class), EnhancedType.of(Integer.class));
}
@Test
public void navigableMapOf_ReturnsRawClassOfNavigableMap_WhenSpecifyingClass() {
EnhancedType<NavigableMap<String, Integer>> type = EnhancedType.navigableMapOf(String.class, Integer.class);
assertThat(type.rawClass()).isEqualTo(NavigableMap.class);
assertThat(type.rawClassParameters()).containsExactly(EnhancedType.of(String.class), EnhancedType.of(Integer.class));
}
@Test
public void navigableMapOf_ReturnsRawClassOfNavigableMap_WhenSpecifyingEnhancedType() {
EnhancedType<NavigableMap<String, Integer>> type =
EnhancedType.navigableMapOf(EnhancedType.of(String.class), EnhancedType.of(Integer.class));
assertThat(type.rawClass()).isEqualTo(NavigableMap.class);
assertThat(type.rawClassParameters()).containsExactly(EnhancedType.of(String.class), EnhancedType.of(Integer.class));
}
@Test
public void documentOf_toString_doesNotRaiseNPE() {
TableSchema<String> tableSchema = StaticTableSchema.builder(String.class).build();
EnhancedType<String> type = EnhancedType.documentOf(String.class, tableSchema);
assertThatCode(() -> type.toString()).doesNotThrowAnyException();
}
@Test
public void documentOf_withEnhancedTypeConfiguration() {
TableSchema<String> tableSchema = StaticTableSchema.builder(String.class).build();
EnhancedType<String> type = EnhancedType.documentOf(String.class, tableSchema, b -> b.preserveEmptyObject(true));
assertThat(type.documentConfiguration()).isPresent();
assertThat(type.documentConfiguration().get().preserveEmptyObject()).isTrue();
}
public class InnerType {
}
public static class InnerStaticType {
}
private void verifyEquals(Object obj1, Object obj2) {
assertThat(obj1).isEqualTo(obj2);
assertThat(obj1.hashCode()).isEqualTo(obj2.hashCode());
}
private void verifyNotEquals(Object obj1, Object obj2) {
assertThat(obj1).isNotEqualTo(obj2);
assertThat(obj1.hashCode()).isNotEqualTo(obj2.hashCode());
}
} | 3,836 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/update/DeleteActionTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.update;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Collections;
import nl.jqno.equalsverifier.EqualsVerifier;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
class DeleteActionTest {
private static final String PATH = "path string";
private static final String VALUE = "value string";
private static final String VALUE_TOKEN = ":valueToken";
private static final String ATTRIBUTE_TOKEN = "#attributeToken";
private static final String ATTRIBUTE_NAME = "attribute1";
private static final AttributeValue NUMERIC_VALUE = AttributeValue.builder().n("5").build();
@Test
void equalsHashcode() {
EqualsVerifier.forClass(DeleteAction.class)
.usingGetClass()
.withPrefabValues(AttributeValue.class,
AttributeValue.builder().s("1").build(),
AttributeValue.builder().s("2").build())
.verify();
}
@Test
void build_minimal() {
DeleteAction action = DeleteAction.builder()
.path(PATH)
.value(VALUE)
.putExpressionValue(VALUE_TOKEN, NUMERIC_VALUE)
.build();
assertThat(action.path()).isEqualTo(PATH);
assertThat(action.value()).isEqualTo(VALUE);
assertThat(action.expressionValues()).containsEntry(VALUE_TOKEN, NUMERIC_VALUE);
assertThat(action.expressionNames()).isEmpty();
}
@Test
void build_maximal() {
DeleteAction action = DeleteAction.builder()
.path(PATH)
.value(VALUE)
.expressionValues(Collections.singletonMap(VALUE_TOKEN, NUMERIC_VALUE))
.expressionNames(Collections.singletonMap(ATTRIBUTE_TOKEN, ATTRIBUTE_NAME))
.build();
assertThat(action.path()).isEqualTo(PATH);
assertThat(action.value()).isEqualTo(VALUE);
assertThat(action.expressionValues()).containsEntry(VALUE_TOKEN, NUMERIC_VALUE);
assertThat(action.expressionNames()).containsEntry(ATTRIBUTE_TOKEN, ATTRIBUTE_NAME);
}
@Test
void copy() {
DeleteAction action = DeleteAction.builder()
.path(PATH)
.value(VALUE)
.expressionValues(Collections.singletonMap(VALUE_TOKEN, NUMERIC_VALUE))
.expressionNames(Collections.singletonMap(ATTRIBUTE_TOKEN, ATTRIBUTE_NAME))
.build();
DeleteAction copy = action.toBuilder().build();
assertThat(action).isEqualTo(copy);
}
} | 3,837 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/update/UpdateExpressionTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.update;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.util.Arrays;
import java.util.List;
import nl.jqno.equalsverifier.EqualsVerifier;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
class UpdateExpressionTest {
private static final AttributeValue VAL = AttributeValue.builder().n("5").build();
private static final RemoveAction removeAction = RemoveAction.builder().path("").build();
private static final SetAction setAction = SetAction.builder()
.path("")
.value("")
.putExpressionValue("", VAL)
.build();
private static final DeleteAction deleteAction = DeleteAction.builder()
.path("")
.value("")
.putExpressionValue("", VAL)
.build();
private static final AddAction addAction = AddAction.builder()
.path("")
.value("")
.putExpressionValue("", VAL)
.build();
@Test
void equalsHashcode() {
EqualsVerifier.forClass(UpdateExpression.class)
.withPrefabValues(AttributeValue.class,
AttributeValue.builder().s("1").build(),
AttributeValue.builder().s("2").build())
.verify();
}
@Test
void build_minimal() {
UpdateExpression updateExpression = UpdateExpression.builder().build();
assertThat(updateExpression.removeActions()).isEmpty();
assertThat(updateExpression.setActions()).isEmpty();
assertThat(updateExpression.deleteActions()).isEmpty();
assertThat(updateExpression.addActions()).isEmpty();
}
@Test
void build_maximal_single() {
UpdateExpression updateExpression = UpdateExpression.builder()
.addAction(removeAction)
.addAction(setAction)
.addAction(deleteAction)
.addAction(addAction)
.build();
assertThat(updateExpression.removeActions()).containsExactly(removeAction);
assertThat(updateExpression.setActions()).containsExactly(setAction);
assertThat(updateExpression.deleteActions()).containsExactly(deleteAction);
assertThat(updateExpression.addActions()).containsExactly(addAction);
}
@Test
void build_maximal_plural() {
UpdateExpression updateExpression = UpdateExpression.builder()
.actions(removeAction, setAction, deleteAction, addAction)
.build();
assertThat(updateExpression.removeActions()).containsExactly(removeAction);
assertThat(updateExpression.setActions()).containsExactly(setAction);
assertThat(updateExpression.deleteActions()).containsExactly(deleteAction);
assertThat(updateExpression.addActions()).containsExactly(addAction);
}
@Test
void build_plural_is_not_additive() {
List<RemoveAction> removeActions = Arrays.asList(removeAction, removeAction);
UpdateExpression updateExpression = UpdateExpression.builder()
.actions(removeActions)
.actions(setAction, deleteAction, addAction)
.build();
assertThat(updateExpression.removeActions()).isEmpty();
assertThat(updateExpression.setActions()).containsExactly(setAction);
assertThat(updateExpression.deleteActions()).containsExactly(deleteAction);
assertThat(updateExpression.addActions()).containsExactly(addAction);
}
@Test
void unknown_action_generates_error() {
assertThatThrownBy(() -> UpdateExpression.builder().actions(new UnknownUpdateAction()).build())
.hasMessageContaining("Do not recognize UpdateAction")
.hasMessageContaining("UnknownUpdateAction");
}
@Test
void merge_null_expression() {
UpdateExpression updateExpression = UpdateExpression.builder()
.actions(removeAction, setAction, deleteAction, addAction)
.build();
UpdateExpression result = UpdateExpression.mergeExpressions(updateExpression, null);
assertThat(result.removeActions()).containsExactly(removeAction);
assertThat(result.setActions()).containsExactly(setAction);
assertThat(result.deleteActions()).containsExactly(deleteAction);
assertThat(result.addActions()).containsExactly(addAction);
}
@Test
void merge_empty_expression() {
UpdateExpression updateExpression = UpdateExpression.builder()
.actions(removeAction, setAction, deleteAction, addAction)
.build();
UpdateExpression result = UpdateExpression.mergeExpressions(updateExpression, UpdateExpression.builder().build());
assertThat(result.removeActions()).containsExactly(removeAction);
assertThat(result.setActions()).containsExactly(setAction);
assertThat(result.deleteActions()).containsExactly(deleteAction);
assertThat(result.addActions()).containsExactly(addAction);
}
@Test
void merge_expression_with_one_action_type() {
UpdateExpression updateExpression = UpdateExpression.builder()
.actions(removeAction, setAction, deleteAction, addAction)
.build();
RemoveAction extraRemoveAction = RemoveAction.builder().path("a").build();
UpdateExpression additionalExpression = UpdateExpression.builder()
.addAction(extraRemoveAction)
.build();
UpdateExpression result = UpdateExpression.mergeExpressions(updateExpression, additionalExpression);
assertThat(result.removeActions()).containsExactly(removeAction, extraRemoveAction);
assertThat(result.setActions()).containsExactly(setAction);
assertThat(result.deleteActions()).containsExactly(deleteAction);
assertThat(result.addActions()).containsExactly(addAction);
}
@Test
void merge_expression_with_all_action_types() {
UpdateExpression updateExpression = UpdateExpression.builder()
.actions(removeAction, setAction, deleteAction, addAction)
.build();
RemoveAction extraRemoveAction = RemoveAction.builder().path("a").build();
SetAction extraSetAction = SetAction.builder().path("").value("").putExpressionValue("", VAL).build();
DeleteAction extraDeleteAction = DeleteAction.builder().path("").value("").putExpressionValue("", VAL).build();
AddAction extraAddAction = AddAction.builder().path("").value("").putExpressionValue("", VAL).build();
UpdateExpression additionalExpression = UpdateExpression.builder()
.actions(extraRemoveAction, extraSetAction, extraDeleteAction, extraAddAction)
.build();
UpdateExpression result = UpdateExpression.mergeExpressions(updateExpression, additionalExpression);
assertThat(result.removeActions()).containsExactly(removeAction, extraRemoveAction);
assertThat(result.setActions()).containsExactly(setAction, extraSetAction);
assertThat(result.deleteActions()).containsExactly(deleteAction, extraDeleteAction);
assertThat(result.addActions()).containsExactly(addAction, extraAddAction);
}
private static final class UnknownUpdateAction implements UpdateAction {
}
} | 3,838 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/update/AddActionTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.update;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Collections;
import nl.jqno.equalsverifier.EqualsVerifier;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
class AddActionTest {
private static final String PATH = "path string";
private static final String VALUE = "value string";
private static final String VALUE_TOKEN = ":valueToken";
private static final String ATTRIBUTE_TOKEN = "#attributeToken";
private static final String ATTRIBUTE_NAME = "attribute1";
private static final AttributeValue NUMERIC_VALUE = AttributeValue.builder().n("5").build();
@Test
void equalsHashcode() {
EqualsVerifier.forClass(AddAction.class)
.usingGetClass()
.withPrefabValues(AttributeValue.class,
AttributeValue.builder().s("1").build(),
AttributeValue.builder().s("2").build())
.verify();
}
@Test
void build_minimal() {
AddAction action = AddAction.builder()
.path(PATH)
.value(VALUE)
.putExpressionValue(VALUE_TOKEN, NUMERIC_VALUE)
.build();
assertThat(action.path()).isEqualTo(PATH);
assertThat(action.value()).isEqualTo(VALUE);
assertThat(action.expressionValues()).containsEntry(VALUE_TOKEN, NUMERIC_VALUE);
assertThat(action.expressionNames()).isEmpty();
}
@Test
void build_maximal() {
AddAction action = AddAction.builder()
.path(PATH)
.value(VALUE)
.expressionValues(Collections.singletonMap(VALUE_TOKEN, NUMERIC_VALUE))
.expressionNames(Collections.singletonMap(ATTRIBUTE_TOKEN, ATTRIBUTE_NAME))
.build();
assertThat(action.path()).isEqualTo(PATH);
assertThat(action.value()).isEqualTo(VALUE);
assertThat(action.expressionValues()).containsEntry(VALUE_TOKEN, NUMERIC_VALUE);
assertThat(action.expressionNames()).containsEntry(ATTRIBUTE_TOKEN, ATTRIBUTE_NAME);
}
@Test
void copy() {
AddAction action = AddAction.builder()
.path(PATH)
.value(VALUE)
.expressionValues(Collections.singletonMap(VALUE_TOKEN, NUMERIC_VALUE))
.expressionNames(Collections.singletonMap(ATTRIBUTE_TOKEN, ATTRIBUTE_NAME))
.build();
AddAction copy = action.toBuilder().build();
assertThat(action).isEqualTo(copy);
}
} | 3,839 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/update/SetActionTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.update;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Collections;
import nl.jqno.equalsverifier.EqualsVerifier;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
class SetActionTest {
private static final String PATH = "path string";
private static final String VALUE = "value string";
private static final String VALUE_TOKEN = ":valueToken";
private static final String ATTRIBUTE_TOKEN = "#attributeToken";
private static final String ATTRIBUTE_NAME = "attribute1";
private static final AttributeValue NUMERIC_VALUE = AttributeValue.builder().n("5").build();
@Test
void equalsHashcode() {
EqualsVerifier.forClass(SetAction.class)
.usingGetClass()
.withPrefabValues(AttributeValue.class,
AttributeValue.builder().s("1").build(),
AttributeValue.builder().s("2").build())
.verify();
}
@Test
void build_minimal() {
SetAction action = SetAction.builder()
.path(PATH)
.value(VALUE)
.putExpressionValue(VALUE_TOKEN, NUMERIC_VALUE)
.build();
assertThat(action.path()).isEqualTo(PATH);
assertThat(action.value()).isEqualTo(VALUE);
assertThat(action.expressionValues()).containsEntry(VALUE_TOKEN, NUMERIC_VALUE);
assertThat(action.expressionNames()).isEmpty();
}
@Test
void build_maximal() {
SetAction action = SetAction.builder()
.path(PATH)
.value(VALUE)
.expressionValues(Collections.singletonMap(VALUE_TOKEN, NUMERIC_VALUE))
.expressionNames(Collections.singletonMap(ATTRIBUTE_TOKEN, ATTRIBUTE_NAME))
.build();
assertThat(action.path()).isEqualTo(PATH);
assertThat(action.value()).isEqualTo(VALUE);
assertThat(action.expressionValues()).containsEntry(VALUE_TOKEN, NUMERIC_VALUE);
assertThat(action.expressionNames()).containsEntry(ATTRIBUTE_TOKEN, ATTRIBUTE_NAME);
}
@Test
void copy() {
SetAction action = SetAction.builder()
.path(PATH)
.value(VALUE)
.expressionValues(Collections.singletonMap(VALUE_TOKEN, NUMERIC_VALUE))
.expressionNames(Collections.singletonMap(ATTRIBUTE_TOKEN, ATTRIBUTE_NAME))
.build();
SetAction copy = action.toBuilder().build();
assertThat(action).isEqualTo(copy);
}
} | 3,840 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/update/RemoveActionTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.update;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Collections;
import nl.jqno.equalsverifier.EqualsVerifier;
import org.junit.jupiter.api.Test;
class RemoveActionTest {
private static final String PATH = "path string";
private static final String ATTRIBUTE_TOKEN = "#attributeToken";
private static final String ATTRIBUTE_NAME = "attribute1";
@Test
void equalsHashcode() {
EqualsVerifier.forClass(RemoveAction.class)
.usingGetClass()
.verify();
}
@Test
void build_minimal() {
RemoveAction action = RemoveAction.builder()
.path(PATH)
.build();
assertThat(action.path()).isEqualTo(PATH);
assertThat(action.expressionNames()).isEmpty();
}
@Test
void build_maximal() {
RemoveAction action = RemoveAction.builder()
.path(PATH)
.expressionNames(Collections.singletonMap(ATTRIBUTE_TOKEN, ATTRIBUTE_NAME))
.build();
assertThat(action.path()).isEqualTo(PATH);
assertThat(action.expressionNames()).containsEntry(ATTRIBUTE_TOKEN, ATTRIBUTE_NAME);
}
@Test
void copy() {
RemoveAction action = RemoveAction.builder()
.path(PATH)
.expressionNames(Collections.singletonMap(ATTRIBUTE_TOKEN, ATTRIBUTE_NAME))
.build();
RemoveAction copy = action.toBuilder().build();
assertThat(action).isEqualTo(copy);
}
} | 3,841 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/AsyncUpdateItemWithResponseTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.functionaltests;
import static org.assertj.core.api.Assertions.assertThat;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey;
import java.util.Objects;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbAsyncTable;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedAsyncClient;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema;
import software.amazon.awssdk.enhanced.dynamodb.model.UpdateItemEnhancedResponse;
import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest;
import software.amazon.awssdk.services.dynamodb.model.ReturnConsumedCapacity;
public class AsyncUpdateItemWithResponseTest extends LocalDynamoDbAsyncTestBase {
private static class Record {
private Integer id;
private String stringAttr1;
private Integer getId() {
return id;
}
private Record setId(Integer id) {
this.id = id;
return this;
}
private String getStringAttr1() {
return stringAttr1;
}
private Record setStringAttr1(String stringAttr1) {
this.stringAttr1 = stringAttr1;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Record record = (Record) o;
return Objects.equals(id, record.id) && Objects.equals(stringAttr1, record.stringAttr1);
}
@Override
public int hashCode() {
return Objects.hash(id, stringAttr1);
}
}
private static final TableSchema<Record> TABLE_SCHEMA =
StaticTableSchema.builder(Record.class)
.newItemSupplier(Record::new)
.addAttribute(Integer.class, a -> a.name("id_1")
.getter(Record::getId)
.setter(Record::setId)
.tags(primaryPartitionKey()))
.addAttribute(String.class, a -> a.name("stringAttr1")
.getter(Record::getStringAttr1)
.setter(Record::setStringAttr1))
.build();
private DynamoDbEnhancedAsyncClient enhancedClient;
private DynamoDbAsyncTable<Record> mappedTable1;
@Before
public void createTable() {
enhancedClient = DynamoDbEnhancedAsyncClient.builder()
.dynamoDbClient(getDynamoDbAsyncClient())
.build();
mappedTable1 = enhancedClient.table(getConcreteTableName("table-name-1"), TABLE_SCHEMA);
mappedTable1.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput())).join();
}
@After
public void deleteTable() {
getDynamoDbAsyncClient().deleteTable(DeleteTableRequest.builder()
.tableName(getConcreteTableName("table-name-1"))
.build())
.join();
}
@Test
public void newValuesMapped() {
Record original = new Record().setId(1).setStringAttr1("attr");
mappedTable1.putItem(original).join();
Record updated = new Record().setId(1).setStringAttr1("attr2");
UpdateItemEnhancedResponse<Record> response = mappedTable1.updateItemWithResponse(r -> r.item(updated)).join();
assertThat(response.attributes()).isEqualTo(updated);
}
@Test
public void returnConsumedCapacity_unset_consumedCapacityNull() {
Record original = new Record().setId(1).setStringAttr1("attr");
mappedTable1.putItem(original).join();
Record updated = new Record().setId(1).setStringAttr1("attr2");
UpdateItemEnhancedResponse<Record> response = mappedTable1.updateItemWithResponse(r -> r.item(updated)).join();
assertThat(response.consumedCapacity()).isNull();
}
@Test
public void returnConsumedCapacity_set_consumedCapacityNotNull() {
Record original = new Record().setId(1).setStringAttr1("attr");
mappedTable1.putItem(original).join();
Record updated = new Record().setId(1).setStringAttr1("attr2");
UpdateItemEnhancedResponse<Record> response = mappedTable1.updateItemWithResponse(r -> r.item(updated)
.returnConsumedCapacity(ReturnConsumedCapacity.TOTAL))
.join();
assertThat(response.consumedCapacity()).isNotNull();
}
@Test
public void returnItemCollectionMetrics_unset_itemCollectionMetricsNull() {
Record original = new Record().setId(1).setStringAttr1("attr");
mappedTable1.putItem(original).join();
Record updated = new Record().setId(1).setStringAttr1("attr2");
UpdateItemEnhancedResponse<Record> response = mappedTable1.updateItemWithResponse(r -> r.item(updated)).join();
assertThat(response.itemCollectionMetrics()).isNull();
}
}
| 3,842 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/AsyncBasicQueryTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.functionaltests;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.numberValue;
import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.stringValue;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primarySortKey;
import static software.amazon.awssdk.enhanced.dynamodb.model.QueryConditional.keyEqualTo;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import software.amazon.awssdk.core.async.SdkPublisher;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbAsyncTable;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedAsyncClient;
import software.amazon.awssdk.enhanced.dynamodb.Expression;
import software.amazon.awssdk.enhanced.dynamodb.Key;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.internal.client.DefaultDynamoDbEnhancedAsyncClient;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema;
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.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest;
public class AsyncBasicQueryTest extends LocalDynamoDbAsyncTestBase {
private static class Record {
private String id;
private Integer sort;
private Integer value;
public String getId() {
return id;
}
public Record setId(String id) {
this.id = id;
return this;
}
public Integer getSort() {
return sort;
}
public Record setSort(Integer sort) {
this.sort = sort;
return this;
}
public Integer getValue() {
return value;
}
public Record setValue(Integer value) {
this.value = value;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Record record = (Record) o;
return Objects.equals(id, record.id) &&
Objects.equals(sort, record.sort) &&
Objects.equals(value, record.value);
}
@Override
public int hashCode() {
return Objects.hash(id, sort, value);
}
}
private static final TableSchema<Record> TABLE_SCHEMA =
StaticTableSchema.builder(Record.class)
.newItemSupplier(Record::new)
.addAttribute(String.class, a -> a.name("id")
.getter(Record::getId)
.setter(Record::setId)
.tags(primaryPartitionKey()))
.addAttribute(Integer.class, a -> a.name("sort")
.getter(Record::getSort)
.setter(Record::setSort)
.tags(primarySortKey()))
.addAttribute(Integer.class, a -> a.name("value")
.getter(Record::getValue)
.setter(Record::setValue))
.build();
private static final List<Record> RECORDS =
IntStream.range(0, 10)
.mapToObj(i -> new Record().setId("id-value").setSort(i).setValue(i))
.collect(Collectors.toList());
private DynamoDbEnhancedAsyncClient enhancedAsyncClient = DefaultDynamoDbEnhancedAsyncClient.builder()
.dynamoDbClient(getDynamoDbAsyncClient())
.build();
private DynamoDbAsyncTable<Record> mappedTable = enhancedAsyncClient.table(getConcreteTableName("table-name"), TABLE_SCHEMA);
private void insertRecords() {
RECORDS.forEach(record -> mappedTable.putItem(r -> r.item(record)).join());
}
@Before
public void createTable() {
mappedTable.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput())).join();
}
@After
public void deleteTable() {
getDynamoDbAsyncClient().deleteTable(DeleteTableRequest.builder()
.tableName(getConcreteTableName("table-name"))
.build())
.join();
}
@Test
public void queryAllRecordsDefaultSettings_usingShortcutForm() {
insertRecords();
SdkPublisher<Page<Record>> publisher =
mappedTable.query(keyEqualTo(k -> k.partitionValue("id-value")));
List<Page<Record>> results = drainPublisher(publisher, 1);
Page<Record> page = results.get(0);
assertThat(page.items(), is(RECORDS));
assertThat(page.lastEvaluatedKey(), is(nullValue()));
}
@Test
public void queryAllRecordsWithFilter() {
insertRecords();
Map<String, AttributeValue> expressionValues = new HashMap<>();
expressionValues.put(":min_value", numberValue(3));
expressionValues.put(":max_value", numberValue(5));
Expression expression = Expression.builder()
.expression("#value >= :min_value AND #value <= :max_value")
.expressionValues(expressionValues)
.expressionNames(Collections.singletonMap("#value", "value"))
.build();
SdkPublisher<Page<Record>> publisher =
mappedTable.query(QueryEnhancedRequest.builder()
.queryConditional(keyEqualTo(k -> k.partitionValue("id-value")))
.filterExpression(expression)
.build());
List<Page<Record>> results = drainPublisher(publisher, 1);
Page<Record> page = results.get(0);
assertThat(page.items(),
is(RECORDS.stream().filter(r -> r.sort >= 3 && r.sort <= 5).collect(Collectors.toList())));
assertThat(page.lastEvaluatedKey(), is(nullValue()));
}
@Test
public void queryAllRecordsWithFilter_viaItems() {
insertRecords();
Map<String, AttributeValue> expressionValues = new HashMap<>();
expressionValues.put(":min_value", numberValue(3));
expressionValues.put(":max_value", numberValue(5));
Expression expression = Expression.builder()
.expression("#value >= :min_value AND #value <= :max_value")
.expressionValues(expressionValues)
.expressionNames(Collections.singletonMap("#value", "value"))
.build();
SdkPublisher<Record> publisher =
mappedTable.query(QueryEnhancedRequest.builder()
.queryConditional(keyEqualTo(k -> k.partitionValue("id-value")))
.filterExpression(expression)
.build()).items();
List<Record> results = drainPublisher(publisher, 3);
assertThat(results,
is(RECORDS.stream().filter(r -> r.sort >= 3 && r.sort <= 5).collect(Collectors.toList())));
}
@Test
public void queryBetween() {
insertRecords();
Key fromKey = Key.builder().partitionValue("id-value").sortValue(3).build();
Key toKey = Key.builder().partitionValue("id-value").sortValue(5).build();
SdkPublisher<Page<Record>> publisher = mappedTable.query(r -> r.queryConditional(QueryConditional.sortBetween(fromKey, toKey)));
List<Page<Record>> results = drainPublisher(publisher, 1);
Page<Record> page = results.get(0);
assertThat(page.items(),
is(RECORDS.stream().filter(r -> r.sort >= 3 && r.sort <= 5).collect(Collectors.toList())));
assertThat(page.lastEvaluatedKey(), is(nullValue()));
}
@Test
public void queryBetween_viaItems() {
insertRecords();
Key fromKey = Key.builder().partitionValue("id-value").sortValue(3).build();
Key toKey = Key.builder().partitionValue("id-value").sortValue(5).build();
SdkPublisher<Record> publisher = mappedTable.query(r -> r.queryConditional(QueryConditional.sortBetween(fromKey, toKey))).items();
List<Record> results = drainPublisher(publisher, 3);
assertThat(results,
is(RECORDS.stream().filter(r -> r.sort >= 3 && r.sort <= 5).collect(Collectors.toList())));
}
@Test
public void queryLimit() {
insertRecords();
SdkPublisher<Page<Record>> publisher =
mappedTable.query(QueryEnhancedRequest.builder()
.queryConditional(keyEqualTo(k -> k.partitionValue("id-value")))
.limit(5)
.build());
List<Page<Record>> results = drainPublisher(publisher, 3);
Page<Record> page1 = results.get(0);
Page<Record> page2 = results.get(1);
Page<Record> page3 = results.get(2);
Map<String, AttributeValue> expectedLastEvaluatedKey1 = new HashMap<>();
expectedLastEvaluatedKey1.put("id", stringValue("id-value"));
expectedLastEvaluatedKey1.put("sort", numberValue(4));
Map<String, AttributeValue> expectedLastEvaluatedKey2 = new HashMap<>();
expectedLastEvaluatedKey2.put("id", stringValue("id-value"));
expectedLastEvaluatedKey2.put("sort", numberValue(9));
assertThat(page1.items(), is(RECORDS.subList(0, 5)));
assertThat(page1.lastEvaluatedKey(), is(expectedLastEvaluatedKey1));
assertThat(page2.items(), is(RECORDS.subList(5, 10)));
assertThat(page2.lastEvaluatedKey(), is(expectedLastEvaluatedKey2));
assertThat(page3.items(), is(empty()));
assertThat(page3.lastEvaluatedKey(), is(nullValue()));
}
@Test
public void queryLimit_viaItems() {
insertRecords();
SdkPublisher<Record> publisher =
mappedTable.query(QueryEnhancedRequest.builder()
.queryConditional(keyEqualTo(k -> k.partitionValue("id-value")))
.limit(5)
.build())
.items();
List<Record> results = drainPublisher(publisher, 10);
assertThat(results, is(RECORDS));
}
@Test
public void queryEmpty() {
SdkPublisher<Page<Record>> publisher =
mappedTable.query(r -> r.queryConditional(keyEqualTo(k -> k.partitionValue("id-value"))));
List<Page<Record>> results = drainPublisher(publisher, 1);
Page<Record> page = results.get(0);
assertThat(page.items(), is(empty()));
assertThat(page.lastEvaluatedKey(), is(nullValue()));
}
@Test
public void queryEmpty_viaItems() {
SdkPublisher<Record> publisher =
mappedTable.query(r -> r.queryConditional(keyEqualTo(k -> k.partitionValue("id-value")))).items();
List<Record> results = drainPublisher(publisher, 0);
assertThat(results, is(empty()));
}
@Test
public void queryExclusiveStartKey() {
Map<String, AttributeValue> exclusiveStartKey = new HashMap<>();
exclusiveStartKey.put("id", stringValue("id-value"));
exclusiveStartKey.put("sort", numberValue(7));
insertRecords();
SdkPublisher<Page<Record>> publisher =
mappedTable.query(QueryEnhancedRequest.builder()
.queryConditional(keyEqualTo(k -> k.partitionValue("id-value")))
.exclusiveStartKey(exclusiveStartKey)
.build());
List<Page<Record>> results = drainPublisher(publisher, 1);
Page<Record> page = results.get(0);
assertThat(page.items(), is(RECORDS.subList(8, 10)));
assertThat(page.lastEvaluatedKey(), is(nullValue()));
}
}
| 3,843 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/EmptyBinaryTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.functionaltests;
import static java.util.Collections.singletonMap;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.HashMap;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable;
import software.amazon.awssdk.enhanced.dynamodb.Expression;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
import software.amazon.awssdk.services.dynamodb.model.GetItemResponse;
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
import software.amazon.awssdk.services.dynamodb.model.PutItemResponse;
import software.amazon.awssdk.services.dynamodb.model.ReturnValue;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemResponse;
@RunWith(MockitoJUnitRunner.class)
public class EmptyBinaryTest {
private static final String TABLE_NAME = "TEST_TABLE";
private static final SdkBytes EMPTY_BYTES = SdkBytes.fromUtf8String("");
private static final AttributeValue EMPTY_BINARY = AttributeValue.builder().b(EMPTY_BYTES).build();
@Mock
private DynamoDbClient mockDynamoDbClient;
private DynamoDbTable<TestBean> dynamoDbTable;
@DynamoDbBean
public static class TestBean {
private String id;
private SdkBytes b;
@DynamoDbPartitionKey
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public SdkBytes getB() {
return b;
}
public void setB(SdkBytes b) {
this.b = b;
}
}
private static final TableSchema<TestBean> TABLE_SCHEMA = TableSchema.fromClass(TestBean.class);
@Before
public void initializeTable() {
DynamoDbEnhancedClient dynamoDbEnhancedClient = DynamoDbEnhancedClient.builder()
.dynamoDbClient(mockDynamoDbClient)
.build();
this.dynamoDbTable = dynamoDbEnhancedClient.table(TABLE_NAME, TABLE_SCHEMA);
}
@Test
public void putEmptyBytes() {
TestBean testBean = new TestBean();
testBean.setId("id123");
testBean.setB(EMPTY_BYTES);
PutItemResponse response = PutItemResponse.builder().build();
when(mockDynamoDbClient.putItem(any(PutItemRequest.class))).thenReturn(response);
dynamoDbTable.putItem(testBean);
Map<String, AttributeValue> expectedItemMap = new HashMap<>();
expectedItemMap.put("id", AttributeValue.builder().s("id123").build());
expectedItemMap.put("b", EMPTY_BINARY);
PutItemRequest expectedRequest = PutItemRequest.builder()
.tableName(TABLE_NAME)
.item(expectedItemMap)
.build();
verify(mockDynamoDbClient).putItem(expectedRequest);
}
@Test
public void getEmptyBytes() {
Map<String, AttributeValue> itemMap = new HashMap<>();
itemMap.put("id", AttributeValue.builder().s("id123").build());
itemMap.put("b", EMPTY_BINARY);
GetItemResponse response = GetItemResponse.builder()
.item(itemMap)
.build();
when(mockDynamoDbClient.getItem(any(GetItemRequest.class))).thenReturn(response);
TestBean result = dynamoDbTable.getItem(r -> r.key(k -> k.partitionValue("id123")));
assertThat(result.getId()).isEqualTo("id123");
assertThat(result.getB()).isEqualTo(EMPTY_BYTES);
}
@Test
public void updateEmptyBytesWithCondition() {
Map<String, AttributeValue> expectedItemMap = new HashMap<>();
expectedItemMap.put("id", AttributeValue.builder().s("id123").build());
expectedItemMap.put("b", EMPTY_BINARY);
TestBean testBean = new TestBean();
testBean.setId("id123");
testBean.setB(EMPTY_BYTES);
UpdateItemResponse response = UpdateItemResponse.builder()
.attributes(expectedItemMap)
.build();
when(mockDynamoDbClient.updateItem(any(UpdateItemRequest.class))).thenReturn(response);
Expression conditionExpression = Expression.builder()
.expression("#attr = :val")
.expressionNames(singletonMap("#attr", "b"))
.expressionValues(singletonMap(":val", EMPTY_BINARY))
.build();
TestBean result = dynamoDbTable.updateItem(r -> r.item(testBean).conditionExpression(conditionExpression));
Map<String, String> expectedExpressionAttributeNames = new HashMap<>();
expectedExpressionAttributeNames.put("#AMZN_MAPPED_b", "b");
expectedExpressionAttributeNames.put("#attr", "b");
Map<String, AttributeValue> expectedExpressionAttributeValues = new HashMap<>();
expectedExpressionAttributeValues.put(":AMZN_MAPPED_b", EMPTY_BINARY);
expectedExpressionAttributeValues.put(":val", EMPTY_BINARY);
Map<String, AttributeValue> expectedKeyMap = new HashMap<>();
expectedKeyMap.put("id", AttributeValue.builder().s("id123").build());
UpdateItemRequest expectedRequest =
UpdateItemRequest.builder()
.tableName(TABLE_NAME)
.key(expectedKeyMap)
.returnValues(ReturnValue.ALL_NEW)
.updateExpression("SET #AMZN_MAPPED_b = :AMZN_MAPPED_b")
.conditionExpression("#attr = :val")
.expressionAttributeNames(expectedExpressionAttributeNames)
.expressionAttributeValues(expectedExpressionAttributeValues)
.build();
verify(mockDynamoDbClient).updateItem(expectedRequest);
assertThat(result.getId()).isEqualTo("id123");
assertThat(result.getB()).isEqualTo(EMPTY_BYTES);
}
}
| 3,844 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/IndexScanTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.functionaltests;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.numberValue;
import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.stringValue;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primarySortKey;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.secondaryPartitionKey;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.secondarySortKey;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbIndex;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable;
import software.amazon.awssdk.enhanced.dynamodb.Expression;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema;
import software.amazon.awssdk.enhanced.dynamodb.model.EnhancedGlobalSecondaryIndex;
import software.amazon.awssdk.enhanced.dynamodb.model.Page;
import software.amazon.awssdk.enhanced.dynamodb.model.ScanEnhancedRequest;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest;
import software.amazon.awssdk.services.dynamodb.model.ProjectionType;
import software.amazon.awssdk.services.dynamodb.model.ReturnConsumedCapacity;
public class IndexScanTest extends LocalDynamoDbSyncTestBase {
private static class Record {
private String id;
private Integer sort;
private Integer value;
private String gsiId;
private Integer gsiSort;
private String getId() {
return id;
}
private Record setId(String id) {
this.id = id;
return this;
}
private Integer getSort() {
return sort;
}
private Record setSort(Integer sort) {
this.sort = sort;
return this;
}
private Integer getValue() {
return value;
}
private Record setValue(Integer value) {
this.value = value;
return this;
}
private String getGsiId() {
return gsiId;
}
private Record setGsiId(String gsiId) {
this.gsiId = gsiId;
return this;
}
private Integer getGsiSort() {
return gsiSort;
}
private Record setGsiSort(Integer gsiSort) {
this.gsiSort = gsiSort;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Record record = (Record) o;
return Objects.equals(id, record.id) &&
Objects.equals(sort, record.sort) &&
Objects.equals(value, record.value) &&
Objects.equals(gsiId, record.gsiId) &&
Objects.equals(gsiSort, record.gsiSort);
}
@Override
public int hashCode() {
return Objects.hash(id, sort, value, gsiId, gsiSort);
}
}
private static final TableSchema<Record> TABLE_SCHEMA =
StaticTableSchema.builder(Record.class)
.newItemSupplier(Record::new)
.addAttribute(String.class, a -> a.name("id")
.getter(Record::getId)
.setter(Record::setId)
.tags(primaryPartitionKey()))
.addAttribute(Integer.class, a -> a.name("sort")
.getter(Record::getSort)
.setter(Record::setSort)
.tags(primarySortKey()))
.addAttribute(Integer.class, a -> a.name("value")
.getter(Record::getValue)
.setter(Record::setValue))
.addAttribute(String.class, a -> a.name("gsi_id")
.getter(Record::getGsiId)
.setter(Record::setGsiId)
.tags(secondaryPartitionKey("gsi_keys_only")))
.addAttribute(Integer.class, a -> a.name("gsi_sort")
.getter(Record::getGsiSort)
.setter(Record::setGsiSort)
.tags(secondarySortKey("gsi_keys_only")))
.build();
private static final List<Record> RECORDS =
IntStream.range(0, 10)
.mapToObj(i -> new Record()
.setId("id-value")
.setSort(i)
.setValue(i)
.setGsiId("gsi-id-value")
.setGsiSort(i))
.collect(Collectors.toList());
private static final List<Record> KEYS_ONLY_RECORDS =
RECORDS.stream()
.map(record -> new Record()
.setId(record.id)
.setSort(record.sort)
.setGsiId(record.gsiId)
.setGsiSort(record.gsiSort))
.collect(Collectors.toList());
private DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder()
.dynamoDbClient(getDynamoDbClient())
.build();
private DynamoDbTable<Record> mappedTable = enhancedClient.table(getConcreteTableName("table-name"), TABLE_SCHEMA);
private DynamoDbIndex<Record> keysOnlyMappedIndex = mappedTable.index("gsi_keys_only");
private void insertRecords() {
RECORDS.forEach(record -> mappedTable.putItem(r -> r.item(record)));
}
@Before
public void createTable() {
mappedTable.createTable(
r -> r.provisionedThroughput(getDefaultProvisionedThroughput())
.globalSecondaryIndices(
EnhancedGlobalSecondaryIndex.builder()
.indexName("gsi_keys_only")
.projection(p -> p.projectionType(ProjectionType.KEYS_ONLY))
.provisionedThroughput(getDefaultProvisionedThroughput())
.build()));
}
@After
public void deleteTable() {
getDynamoDbClient().deleteTable(DeleteTableRequest.builder()
.tableName(getConcreteTableName("table-name"))
.build());
}
@Test
public void scanAllRecordsDefaultSettings() {
insertRecords();
Iterator<Page<Record>> results = keysOnlyMappedIndex.scan(r -> r.returnConsumedCapacity(ReturnConsumedCapacity.INDEXES))
.iterator();
assertThat(results.hasNext(), is(true));
Page<Record> page = results.next();
assertThat(results.hasNext(), is(false));
assertThat(page.items(), is(KEYS_ONLY_RECORDS));
assertThat(page.lastEvaluatedKey(), is(nullValue()));
assertThat(page.consumedCapacity(), is(notNullValue()));
assertThat(page.consumedCapacity().capacityUnits(), is(notNullValue()));
assertThat(page.consumedCapacity().globalSecondaryIndexes(), is(notNullValue()));
assertThat(page.count(), equalTo(10));
assertThat(page.scannedCount(), equalTo(10));
}
@Test
public void scanAllRecordsWithFilter() {
insertRecords();
Map<String, AttributeValue> expressionValues = new HashMap<>();
expressionValues.put(":min_value", numberValue(3));
expressionValues.put(":max_value", numberValue(5));
Expression expression = Expression.builder()
.expression("sort >= :min_value AND sort <= :max_value")
.expressionValues(expressionValues)
.build();
Iterator<Page<Record>> results =
keysOnlyMappedIndex.scan(ScanEnhancedRequest.builder().filterExpression(expression)
.returnConsumedCapacity(ReturnConsumedCapacity.INDEXES).build())
.iterator();
assertThat(results.hasNext(), is(true));
Page<Record> page = results.next();
assertThat(results.hasNext(), is(false));
assertThat(page.items(),
is(KEYS_ONLY_RECORDS.stream().filter(r -> r.sort >= 3 && r.sort <= 5).collect(Collectors.toList())));
assertThat(page.lastEvaluatedKey(), is(nullValue()));
assertThat(page.consumedCapacity(), is(notNullValue()));
assertThat(page.consumedCapacity().capacityUnits(), is(notNullValue()));
assertThat(page.consumedCapacity().globalSecondaryIndexes(), is(notNullValue()));
assertThat(page.count(), equalTo(3));
assertThat(page.scannedCount(), equalTo(10));
}
@Test
public void scanLimit() {
insertRecords();
Iterator<Page<Record>> results = keysOnlyMappedIndex.scan(r -> r.limit(5)).iterator();
assertThat(results.hasNext(), is(true));
Page<Record> page1 = results.next();
assertThat(results.hasNext(), is(true));
Page<Record> page2 = results.next();
assertThat(results.hasNext(), is(true));
Page<Record> page3 = results.next();
assertThat(results.hasNext(), is(false));
assertThat(page1.items(), is(KEYS_ONLY_RECORDS.subList(0, 5)));
assertThat(page1.consumedCapacity(), is(nullValue()));
assertThat(page1.lastEvaluatedKey(), is(getKeyMap(4)));
assertThat(page1.count(), equalTo(5));
assertThat(page1.scannedCount(), equalTo(5));
assertThat(page2.items(), is(KEYS_ONLY_RECORDS.subList(5, 10)));
assertThat(page2.lastEvaluatedKey(), is(getKeyMap(9)));
assertThat(page2.count(), equalTo(5));
assertThat(page2.scannedCount(), equalTo(5));
assertThat(page3.items(), is(empty()));
assertThat(page3.lastEvaluatedKey(), is(nullValue()));
assertThat(page3.count(), equalTo(0));
assertThat(page3.scannedCount(), equalTo(0));
}
@Test
public void scanEmpty() {
Iterator<Page<Record>> results = keysOnlyMappedIndex.scan().iterator();
assertThat(results.hasNext(), is(true));
Page<Record> page = results.next();
assertThat(results.hasNext(), is(false));
assertThat(page.items(), is(empty()));
assertThat(page.lastEvaluatedKey(), is(nullValue()));
assertThat(page.count(), equalTo(0));
assertThat(page.scannedCount(), equalTo(0));
}
@Test
public void scanExclusiveStartKey() {
insertRecords();
Iterator<Page<Record>> results =
keysOnlyMappedIndex.scan(r -> r.exclusiveStartKey(getKeyMap(7))).iterator();
assertThat(results.hasNext(), is(true));
Page<Record> page = results.next();
assertThat(results.hasNext(), is(false));
assertThat(page.items(), is(KEYS_ONLY_RECORDS.subList(8, 10)));
assertThat(page.lastEvaluatedKey(), is(nullValue()));
assertThat(page.count(), equalTo(2));
assertThat(page.scannedCount(), equalTo(2));
}
private Map<String, AttributeValue> getKeyMap(int sort) {
Map<String, AttributeValue> result = new HashMap<>();
result.put("id", stringValue(KEYS_ONLY_RECORDS.get(sort).getId()));
result.put("sort", numberValue(KEYS_ONLY_RECORDS.get(sort).getSort()));
result.put("gsi_id", stringValue(KEYS_ONLY_RECORDS.get(sort).getGsiId()));
result.put("gsi_sort", numberValue(KEYS_ONLY_RECORDS.get(sort).getGsiSort()));
return Collections.unmodifiableMap(result);
}
}
| 3,845 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/AsyncBasicCrudTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.functionaltests;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.stringValue;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primarySortKey;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.secondaryPartitionKey;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.secondarySortKey;
import java.util.Objects;
import java.util.concurrent.CompletionException;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbAsyncTable;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedAsyncClient;
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.client.DefaultDynamoDbEnhancedAsyncClient;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema;
import software.amazon.awssdk.enhanced.dynamodb.model.DeleteItemEnhancedRequest;
import software.amazon.awssdk.enhanced.dynamodb.model.EnhancedGlobalSecondaryIndex;
import software.amazon.awssdk.enhanced.dynamodb.model.PutItemEnhancedRequest;
import software.amazon.awssdk.enhanced.dynamodb.model.UpdateItemEnhancedRequest;
import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException;
import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest;
import software.amazon.awssdk.services.dynamodb.model.ProjectionType;
public class AsyncBasicCrudTest extends LocalDynamoDbAsyncTestBase {
private static class Record {
private String id;
private String sort;
private String attribute;
private String attribute2;
private String attribute3;
private String getId() {
return id;
}
private Record setId(String id) {
this.id = id;
return this;
}
private String getSort() {
return sort;
}
private Record setSort(String sort) {
this.sort = sort;
return this;
}
private String getAttribute() {
return attribute;
}
private Record setAttribute(String attribute) {
this.attribute = attribute;
return this;
}
private String getAttribute2() {
return attribute2;
}
private Record setAttribute2(String attribute2) {
this.attribute2 = attribute2;
return this;
}
private String getAttribute3() {
return attribute3;
}
private Record setAttribute3(String attribute3) {
this.attribute3 = attribute3;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Record record = (Record) o;
return Objects.equals(id, record.id) &&
Objects.equals(sort, record.sort) &&
Objects.equals(attribute, record.attribute) &&
Objects.equals(attribute2, record.attribute2) &&
Objects.equals(attribute3, record.attribute3);
}
@Override
public int hashCode() {
return Objects.hash(id, sort, attribute, attribute2, attribute3);
}
}
private static class ShortRecord {
private String id;
private String sort;
private String attribute;
private String getId() {
return id;
}
private ShortRecord setId(String id) {
this.id = id;
return this;
}
private String getSort() {
return sort;
}
private ShortRecord setSort(String sort) {
this.sort = sort;
return this;
}
private String getAttribute() {
return attribute;
}
private ShortRecord setAttribute(String attribute) {
this.attribute = attribute;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ShortRecord that = (ShortRecord) o;
return Objects.equals(id, that.id) &&
Objects.equals(sort, that.sort) &&
Objects.equals(attribute, that.attribute);
}
@Override
public int hashCode() {
return Objects.hash(id, sort, attribute);
}
}
private static final TableSchema<Record> TABLE_SCHEMA =
StaticTableSchema.builder(Record.class)
.newItemSupplier(Record::new)
.addAttribute(String.class, a -> a.name("id")
.getter(Record::getId)
.setter(Record::setId)
.tags(primaryPartitionKey()))
.addAttribute(String.class, a -> a.name("sort")
.getter(Record::getSort)
.setter(Record::setSort)
.tags(primarySortKey()))
.addAttribute(String.class, a -> a.name("attribute")
.getter(Record::getAttribute)
.setter(Record::setAttribute))
.addAttribute(String.class, a -> a.name("attribute2*")
.getter(Record::getAttribute2)
.setter(Record::setAttribute2)
.tags(secondaryPartitionKey("gsi_1")))
.addAttribute(String.class, a -> a.name("attribute3")
.getter(Record::getAttribute3)
.setter(Record::setAttribute3)
.tags(secondarySortKey("gsi_1")))
.build();
private static final TableSchema<ShortRecord> SHORT_TABLE_SCHEMA =
StaticTableSchema.builder(ShortRecord.class)
.newItemSupplier(ShortRecord::new)
.addAttribute(String.class, a -> a.name("id")
.getter(ShortRecord::getId)
.setter(ShortRecord::setId)
.tags(primaryPartitionKey()))
.addAttribute(String.class, a -> a.name("sort")
.getter(ShortRecord::getSort)
.setter(ShortRecord::setSort)
.tags(primarySortKey()))
.addAttribute(String.class, a -> a.name("attribute")
.getter(ShortRecord::getAttribute)
.setter(ShortRecord::setAttribute))
.build();
private DynamoDbEnhancedAsyncClient enhancedAsyncClient =
DefaultDynamoDbEnhancedAsyncClient.builder()
.dynamoDbClient(getDynamoDbAsyncClient())
.build();
private DynamoDbAsyncTable<Record> mappedTable = enhancedAsyncClient.table(getConcreteTableName("table-name"),
TABLE_SCHEMA);
private DynamoDbAsyncTable<ShortRecord> mappedShortTable = enhancedAsyncClient.table(getConcreteTableName("table-name"),
SHORT_TABLE_SCHEMA);
@Rule
public ExpectedException exception = ExpectedException.none();
@Before
public void createTable() {
mappedTable.createTable(
r -> r.provisionedThroughput(getDefaultProvisionedThroughput())
.globalSecondaryIndices(
EnhancedGlobalSecondaryIndex.builder()
.indexName("gsi_1")
.projection(p -> p.projectionType(ProjectionType.ALL))
.provisionedThroughput(getDefaultProvisionedThroughput())
.build()))
.join();
}
@After
public void deleteTable() {
getDynamoDbAsyncClient().deleteTable(DeleteTableRequest.builder()
.tableName(getConcreteTableName("table-name"))
.build())
.join();
}
@Test
public void putThenGetItemUsingKey() {
Record record = new Record()
.setId("id-value")
.setSort("sort-value")
.setAttribute("one")
.setAttribute2("two")
.setAttribute3("three");
mappedTable.putItem(r -> r.item(record)).join();
Record result = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id-value").sortValue("sort-value"))).join();
assertThat(result, is(record));
}
@Test
public void putThenGetItemUsingKeyItem() {
Record record = new Record()
.setId("id-value")
.setSort("sort-value")
.setAttribute("one")
.setAttribute2("two")
.setAttribute3("three");
mappedTable.putItem(r -> r.item(record)).join();
Record keyItem = new Record();
keyItem.setId("id-value");
keyItem.setSort("sort-value");
Record result = mappedTable.getItem(keyItem).join();
assertThat(result, is(record));
}
@Test
public void getNonExistentItem() {
Record result = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id-value").sortValue("sort-value"))).join();
assertThat(result, is(nullValue()));
}
@Test
public void putTwiceThenGetItem() {
Record record = new Record()
.setId("id-value")
.setSort("sort-value")
.setAttribute("one")
.setAttribute2("two")
.setAttribute3("three");
mappedTable.putItem(r -> r.item(record)).join();
Record record2 = new Record()
.setId("id-value")
.setSort("sort-value")
.setAttribute("four")
.setAttribute2("five")
.setAttribute3("six");
mappedTable.putItem(r -> r.item(record2)).join();
Record result = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id-value").sortValue("sort-value"))).join();
assertThat(result, is(record2));
}
@Test
public void putThenDeleteItem_usingShortcutForm() {
Record record = new Record()
.setId("id-value")
.setSort("sort-value")
.setAttribute("one")
.setAttribute2("two")
.setAttribute3("three");
mappedTable.putItem(record).join();
Record beforeDeleteResult =
mappedTable.deleteItem(Key.builder().partitionValue("id-value").sortValue("sort-value").build()).join();
Record afterDeleteResult =
mappedTable.getItem(Key.builder().partitionValue("id-value").sortValue("sort-value").build()).join();
assertThat(beforeDeleteResult, is(record));
assertThat(afterDeleteResult, is(nullValue()));
}
@Test
public void putThenDeleteItem_usingKeyItemForm() {
Record record = new Record()
.setId("id-value")
.setSort("sort-value")
.setAttribute("one")
.setAttribute2("two")
.setAttribute3("three");
mappedTable.putItem(record).join();
Record beforeDeleteResult =
mappedTable.deleteItem(record).join();
Record afterDeleteResult =
mappedTable.getItem(Key.builder().partitionValue("id-value").sortValue("sort-value").build()).join();
assertThat(beforeDeleteResult, is(record));
assertThat(afterDeleteResult, is(nullValue()));
}
@Test
public void putWithConditionThatSucceeds() {
Record record = new Record()
.setId("id-value")
.setSort("sort-value")
.setAttribute("one")
.setAttribute2("two")
.setAttribute3("three");
mappedTable.putItem(r -> r.item(record)).join();
record.setAttribute("four");
Expression conditionExpression = Expression.builder()
.expression("#key = :value OR #key1 = :value1")
.putExpressionName("#key", "attribute")
.putExpressionName("#key1", "attribute3")
.putExpressionValue(":value", stringValue("wrong"))
.putExpressionValue(":value1", stringValue("three"))
.build();
mappedTable.putItem(PutItemEnhancedRequest.builder(Record.class)
.item(record)
.conditionExpression(conditionExpression)
.build()).join();
Record result = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id-value").sortValue("sort-value"))).join();
assertThat(result, is(record));
}
@Test
public void putWithConditionThatFails() {
Record record = new Record()
.setId("id-value")
.setSort("sort-value")
.setAttribute("one")
.setAttribute2("two")
.setAttribute3("three");
mappedTable.putItem(r -> r.item(record)).join();
record.setAttribute("four");
Expression conditionExpression = Expression.builder()
.expression("#key = :value OR #key1 = :value1")
.putExpressionName("#key", "attribute")
.putExpressionName("#key1", "attribute3")
.putExpressionValue(":value", stringValue("wrong"))
.putExpressionValue(":value1", stringValue("wrong"))
.build();
exception.expect(CompletionException.class);
exception.expectCause(instanceOf(ConditionalCheckFailedException.class));
mappedTable.putItem(PutItemEnhancedRequest.builder(Record.class)
.item(record)
.conditionExpression(conditionExpression)
.build())
.join();
}
@Test
public void deleteNonExistentItem() {
Record result = mappedTable.deleteItem(r -> r.key(k -> k.partitionValue("id-value").sortValue("sort-value"))).join();
assertThat(result, is(nullValue()));
}
@Test
public void deleteWithConditionThatSucceeds() {
Record record = new Record()
.setId("id-value")
.setSort("sort-value")
.setAttribute("one")
.setAttribute2("two")
.setAttribute3("three");
mappedTable.putItem(r -> r.item(record)).join();
Expression conditionExpression = Expression.builder()
.expression("#key = :value OR #key1 = :value1")
.putExpressionName("#key", "attribute")
.putExpressionName("#key1", "attribute3")
.putExpressionValue(":value", stringValue("wrong"))
.putExpressionValue(":value1", stringValue("three"))
.build();
Key key = mappedTable.keyFrom(record);
mappedTable.deleteItem(DeleteItemEnhancedRequest.builder()
.key(key)
.conditionExpression(conditionExpression)
.build())
.join();
Record result = mappedTable.getItem(r -> r.key(key)).join();
assertThat(result, is(nullValue()));
}
@Test
public void deleteWithConditionThatFails() {
Record record = new Record()
.setId("id-value")
.setSort("sort-value")
.setAttribute("one")
.setAttribute2("two")
.setAttribute3("three");
mappedTable.putItem(r -> r.item(record)).join();
Expression conditionExpression = Expression.builder()
.expression("#key = :value OR #key1 = :value1")
.putExpressionName("#key", "attribute")
.putExpressionName("#key1", "attribute3")
.putExpressionValue(":value", stringValue("wrong"))
.putExpressionValue(":value1", stringValue("wrong"))
.build();
exception.expect(CompletionException.class);
exception.expectCause(instanceOf(ConditionalCheckFailedException.class));
mappedTable.deleteItem(DeleteItemEnhancedRequest.builder().key(mappedTable.keyFrom(record))
.conditionExpression(conditionExpression)
.build()).join();
}
@Test
public void updateOverwriteCompleteRecord_usingShortcutForm() {
Record record = new Record()
.setId("id-value")
.setSort("sort-value")
.setAttribute("one")
.setAttribute2("two")
.setAttribute3("three");
mappedTable.putItem(record).join();
Record record2 = new Record()
.setId("id-value")
.setSort("sort-value")
.setAttribute("four")
.setAttribute2("five")
.setAttribute3("six");
Record result = mappedTable.updateItem(record2).join();
assertThat(result, is(record2));
}
@Test
public void updateCreatePartialRecord() {
Record record = new Record()
.setId("id-value")
.setSort("sort-value")
.setAttribute("one");
Record result = mappedTable.updateItem(r -> r.item(record)).join();
assertThat(result, is(record));
}
@Test
public void updateCreateKeyOnlyRecord() {
Record record = new Record()
.setId("id-value")
.setSort("sort-value");
Record result = mappedTable.updateItem(r -> r.item(record)).join();
assertThat(result, is(record));
}
@Test
public void updateOverwriteModelledNulls() {
Record record = new Record()
.setId("id-value")
.setSort("sort-value")
.setAttribute("one")
.setAttribute2("two")
.setAttribute3("three");
mappedTable.putItem(r -> r.item(record)).join();
Record record2 = new Record()
.setId("id-value")
.setSort("sort-value")
.setAttribute("four");
Record result = mappedTable.updateItem(r -> r.item(record2)).join();
assertThat(result, is(record2));
}
@Test
public void updateCanIgnoreNullsAndDoPartialUpdate() {
Record record = new Record()
.setId("id-value")
.setSort("sort-value")
.setAttribute("one")
.setAttribute2("two")
.setAttribute3("three");
mappedTable.putItem(r -> r.item(record)).join();
Record record2 = new Record()
.setId("id-value")
.setSort("sort-value")
.setAttribute("four");
Record result = mappedTable.updateItem(UpdateItemEnhancedRequest.builder(Record.class)
.item(record2)
.ignoreNulls(true)
.build())
.join();
Record expectedResult = new Record()
.setId("id-value")
.setSort("sort-value")
.setAttribute("four")
.setAttribute2("two")
.setAttribute3("three");
assertThat(result, is(expectedResult));
}
@Test
public void updateShortRecordDoesPartialUpdate() {
Record record = new Record()
.setId("id-value")
.setSort("sort-value")
.setAttribute("one")
.setAttribute2("two")
.setAttribute3("three");
mappedTable.putItem(r -> r.item(record)).join();
ShortRecord record2 = new ShortRecord()
.setId("id-value")
.setSort("sort-value")
.setAttribute("four");
ShortRecord shortResult = mappedShortTable.updateItem(r -> r.item(record2)).join();
Record result = mappedTable.getItem(r -> r.key(k -> k.partitionValue(record.getId())
.sortValue(record.getSort()))).join();
Record expectedResult = new Record()
.setId("id-value")
.setSort("sort-value")
.setAttribute("four")
.setAttribute2("two")
.setAttribute3("three");
assertThat(result, is(expectedResult));
assertThat(shortResult, is(record2));
}
@Test
public void updateKeyOnlyExistingRecordDoesNothing() {
Record record = new Record()
.setId("id-value")
.setSort("sort-value")
.setAttribute("one")
.setAttribute2("two")
.setAttribute3("three");
mappedTable.putItem(r -> r.item(record)).join();
Record updateRecord = new Record().setId("id-value").setSort("sort-value");
Record result = mappedTable.updateItem(UpdateItemEnhancedRequest.builder(Record.class)
.item(updateRecord)
.ignoreNulls(true)
.build())
.join();
assertThat(result, is(record));
}
@Test
public void updateWithConditionThatSucceeds() {
Record record = new Record()
.setId("id-value")
.setSort("sort-value")
.setAttribute("one")
.setAttribute2("two")
.setAttribute3("three");
mappedTable.putItem(r -> r.item(record)).join();
record.setAttribute("four");
Expression conditionExpression = Expression.builder()
.expression("#key = :value OR #key1 = :value1")
.putExpressionName("#key", "attribute")
.putExpressionName("#key1", "attribute3")
.putExpressionValue(":value", stringValue("wrong"))
.putExpressionValue(":value1", stringValue("three"))
.build();
mappedTable.updateItem(UpdateItemEnhancedRequest.builder(Record.class)
.item(record)
.conditionExpression(conditionExpression)
.build())
.join();
Record result = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id-value").sortValue("sort-value"))).join();
assertThat(result, is(record));
}
@Test
public void updateWithConditionThatFails() {
Record record = new Record()
.setId("id-value")
.setSort("sort-value")
.setAttribute("one")
.setAttribute2("two")
.setAttribute3("three");
mappedTable.putItem(r -> r.item(record)).join();
record.setAttribute("four");
Expression conditionExpression = Expression.builder()
.expression("#key = :value OR #key1 = :value1")
.putExpressionName("#key", "attribute")
.putExpressionName("#key1", "attribute3")
.putExpressionValue(":value", stringValue("wrong"))
.putExpressionValue(":value1", stringValue("wrong"))
.build();
exception.expect(CompletionException.class);
exception.expectCause(instanceOf(ConditionalCheckFailedException.class));
mappedTable.updateItem(UpdateItemEnhancedRequest.builder(Record.class)
.item(record)
.conditionExpression(conditionExpression)
.build())
.join();
}
@Test
public void getAShortRecordWithNewModelledFields() {
ShortRecord shortRecord = new ShortRecord()
.setId("id-value")
.setSort("sort-value")
.setAttribute("one");
mappedShortTable.putItem(r -> r.item(shortRecord)).join();
Record expectedRecord = new Record()
.setId("id-value")
.setSort("sort-value")
.setAttribute("one");
Record result = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id-value").sortValue("sort-value"))).join();
assertThat(result, is(expectedRecord));
}
}
| 3,846 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/BatchWriteItemTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.functionaltests;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema;
import software.amazon.awssdk.enhanced.dynamodb.model.BatchWriteItemEnhancedRequest;
import software.amazon.awssdk.enhanced.dynamodb.model.WriteBatch;
import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest;
public class BatchWriteItemTest extends LocalDynamoDbSyncTestBase {
private static class Record1 {
private Integer id;
private String attribute;
private Integer getId() {
return id;
}
private Record1 setId(Integer id) {
this.id = id;
return this;
}
private String getAttribute() {
return attribute;
}
private Record1 setAttribute(String attribute) {
this.attribute = attribute;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Record1 record1 = (Record1) o;
return Objects.equals(id, record1.id) &&
Objects.equals(attribute, record1.attribute);
}
@Override
public int hashCode() {
return Objects.hash(id, attribute);
}
}
private static class Record2 {
private Integer id;
private String attribute;
private Integer getId() {
return id;
}
private Record2 setId(Integer id) {
this.id = id;
return this;
}
private String getAttribute() {
return attribute;
}
private Record2 setAttribute(String attribute) {
this.attribute = attribute;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Record2 record2 = (Record2) o;
return Objects.equals(id, record2.id) &&
Objects.equals(attribute, record2.attribute);
}
@Override
public int hashCode() {
return Objects.hash(id, attribute);
}
}
private static final TableSchema<Record1> TABLE_SCHEMA_1 =
StaticTableSchema.builder(Record1.class)
.newItemSupplier(Record1::new)
.addAttribute(Integer.class, a -> a.name("id_1")
.getter(Record1::getId)
.setter(Record1::setId)
.tags(primaryPartitionKey()))
.addAttribute(String.class, a -> a.name("attribute")
.getter(Record1::getAttribute)
.setter(Record1::setAttribute))
.build();
private static final TableSchema<Record2> TABLE_SCHEMA_2 =
StaticTableSchema.builder(Record2.class)
.newItemSupplier(Record2::new)
.addAttribute(Integer.class, a -> a.name("id_2")
.getter(Record2::getId)
.setter(Record2::setId)
.tags(primaryPartitionKey()))
.addAttribute(String.class, a -> a.name("attribute")
.getter(Record2::getAttribute)
.setter(Record2::setAttribute))
.build();
private DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder()
.dynamoDbClient(getDynamoDbClient())
.build();
private DynamoDbTable<Record1> mappedTable1 = enhancedClient.table(getConcreteTableName("table-name-1"), TABLE_SCHEMA_1);
private DynamoDbTable<Record2> mappedTable2 = enhancedClient.table(getConcreteTableName("table-name-2"), TABLE_SCHEMA_2);
private static final List<Record1> RECORDS_1 =
IntStream.range(0, 2)
.mapToObj(i -> new Record1().setId(i).setAttribute(Integer.toString(i)))
.collect(Collectors.toList());
private static final List<Record2> RECORDS_2 =
IntStream.range(0, 2)
.mapToObj(i -> new Record2().setId(i).setAttribute(Integer.toString(i)))
.collect(Collectors.toList());
@Before
public void createTable() {
mappedTable1.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput()));
mappedTable2.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput()));
}
@After
public void deleteTable() {
getDynamoDbClient().deleteTable(DeleteTableRequest.builder()
.tableName(getConcreteTableName("table-name-1"))
.build());
getDynamoDbClient().deleteTable(DeleteTableRequest.builder()
.tableName(getConcreteTableName("table-name-2"))
.build());
}
@Test
public void singlePut() {
BatchWriteItemEnhancedRequest batchWriteItemEnhancedRequest =
BatchWriteItemEnhancedRequest.builder()
.addWriteBatch(
WriteBatch.builder(Record1.class)
.mappedTableResource(mappedTable1)
.addPutItem(r -> r.item(RECORDS_1.get(0)))
.build())
.build();
enhancedClient.batchWriteItem(batchWriteItemEnhancedRequest);
Record1 record = mappedTable1.getItem(r -> r.key(k -> k.partitionValue(0)));
assertThat(record, is(RECORDS_1.get(0)));
}
@Test
public void multiplePut() {
BatchWriteItemEnhancedRequest batchWriteItemEnhancedRequest =
BatchWriteItemEnhancedRequest.builder()
.writeBatches(
WriteBatch.builder(Record1.class)
.mappedTableResource(mappedTable1)
.addPutItem(r -> r.item(RECORDS_1.get(0)))
.build(),
WriteBatch.builder(Record2.class)
.mappedTableResource(mappedTable2)
.addPutItem(r -> r.item(RECORDS_2.get(0)))
.build())
.build();
enhancedClient.batchWriteItem(batchWriteItemEnhancedRequest);
Record1 record1 = mappedTable1.getItem(r -> r.key(k -> k.partitionValue(0)));
Record2 record2 = mappedTable2.getItem(r -> r.key(k -> k.partitionValue(0)));
assertThat(record1, is(RECORDS_1.get(0)));
assertThat(record2, is(RECORDS_2.get(0)));
}
@Test
public void singleDelete() {
mappedTable1.putItem(r -> r.item(RECORDS_1.get(0)));
WriteBatch singleDeleteBatch = WriteBatch.builder(Record1.class)
.mappedTableResource(mappedTable1)
.addDeleteItem(r -> r.key(k -> k.partitionValue(0)))
.build();
BatchWriteItemEnhancedRequest batchWriteItemEnhancedRequest =
BatchWriteItemEnhancedRequest.builder()
.addWriteBatch(singleDeleteBatch)
.build();
enhancedClient.batchWriteItem(batchWriteItemEnhancedRequest);
Record1 record = mappedTable1.getItem(r -> r.key(k -> k.partitionValue(0)));
assertThat(record, is(nullValue()));
}
@Test
public void multipleDelete() {
mappedTable1.putItem(r -> r.item(RECORDS_1.get(0)));
mappedTable2.putItem(r -> r.item(RECORDS_2.get(0)));
BatchWriteItemEnhancedRequest batchWriteItemEnhancedRequest =
BatchWriteItemEnhancedRequest.builder()
.writeBatches(
WriteBatch.builder(Record1.class)
.mappedTableResource(mappedTable1)
.addDeleteItem(r -> r.key(k -> k.partitionValue(0)))
.build(),
WriteBatch.builder(Record2.class)
.mappedTableResource(mappedTable2)
.addDeleteItem(r -> r.key(k -> k.partitionValue(0)))
.build())
.build();
enhancedClient.batchWriteItem(batchWriteItemEnhancedRequest);
Record1 record1 = mappedTable1.getItem(r -> r.key(k -> k.partitionValue(0)));
Record2 record2 = mappedTable2.getItem(r -> r.key(k -> k.partitionValue(0)));
assertThat(record1, is(nullValue()));
assertThat(record2, is(nullValue()));
}
@Test
public void mixedCommands() {
mappedTable1.putItem(r -> r.item(RECORDS_1.get(0)));
mappedTable2.putItem(r -> r.item(RECORDS_2.get(0)));
enhancedClient.batchWriteItem(r -> r.writeBatches(
WriteBatch.builder(Record1.class)
.mappedTableResource(mappedTable1)
.addPutItem(i -> i.item(RECORDS_1.get(1)))
.build(),
WriteBatch.builder(Record2.class)
.mappedTableResource(mappedTable2)
.addDeleteItem(i -> i.key(k -> k.partitionValue(0)))
.build()));
assertThat(mappedTable1.getItem(r -> r.key(k -> k.partitionValue(0))), is(RECORDS_1.get(0)));
assertThat(mappedTable1.getItem(r -> r.key(k -> k.partitionValue(1))), is(RECORDS_1.get(1)));
assertThat(mappedTable2.getItem(r -> r.key(k -> k.partitionValue(0))), is(nullValue()));
}
}
| 3,847 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/AsyncDeleteItemWithResponseTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.functionaltests;
import static org.assertj.core.api.Assertions.assertThat;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey;
import java.util.Objects;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbAsyncTable;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedAsyncClient;
import software.amazon.awssdk.enhanced.dynamodb.Key;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema;
import software.amazon.awssdk.enhanced.dynamodb.model.DeleteItemEnhancedResponse;
import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest;
import software.amazon.awssdk.services.dynamodb.model.ReturnConsumedCapacity;
public class AsyncDeleteItemWithResponseTest extends LocalDynamoDbAsyncTestBase {
private static class Record {
private Integer id;
private String stringAttr1;
private Integer getId() {
return id;
}
private Record setId(Integer id) {
this.id = id;
return this;
}
private String getStringAttr1() {
return stringAttr1;
}
private Record setStringAttr1(String stringAttr1) {
this.stringAttr1 = stringAttr1;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Record record = (Record) o;
return Objects.equals(id, record.id) && Objects.equals(stringAttr1, record.stringAttr1);
}
@Override
public int hashCode() {
return Objects.hash(id, stringAttr1);
}
}
private static final TableSchema<Record> TABLE_SCHEMA =
StaticTableSchema.builder(Record.class)
.newItemSupplier(Record::new)
.addAttribute(Integer.class, a -> a.name("id_1")
.getter(Record::getId)
.setter(Record::setId)
.tags(primaryPartitionKey()))
.addAttribute(String.class, a -> a.name("stringAttr1")
.getter(Record::getStringAttr1)
.setter(Record::setStringAttr1))
.build();
private DynamoDbEnhancedAsyncClient enhancedClient;
private DynamoDbAsyncTable<Record> mappedTable1;
@Before
public void createTable() {
enhancedClient = DynamoDbEnhancedAsyncClient.builder()
.dynamoDbClient(getDynamoDbAsyncClient())
.build();
mappedTable1 = enhancedClient.table(getConcreteTableName("table-name-1"), TABLE_SCHEMA);
mappedTable1.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput())).join();
}
@After
public void deleteTable() {
getDynamoDbAsyncClient().deleteTable(DeleteTableRequest.builder()
.tableName(getConcreteTableName("table-name-1"))
.build());
}
// Note: DynamoDB local seems to always return the consumed capacity even if not specified on the request. See
// AsyncDeleteItemWithResponseIntegrationTest for additional testing of this field against the actual service.
@Test
public void returnConsumedCapacity_set_consumedCapacityNotNull() {
Key key = Key.builder().partitionValue(1).build();
DeleteItemEnhancedResponse<Record> response = mappedTable1.deleteItemWithResponse(r -> r.key(key)
.returnConsumedCapacity(ReturnConsumedCapacity.TOTAL)).join();
assertThat(response.consumedCapacity()).isNotNull();
}
}
| 3,848 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/AtomicCounterTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.functionaltests;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.util.stream.IntStream;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.AtomicCounterRecord;
import software.amazon.awssdk.enhanced.dynamodb.model.WriteBatch;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
public class AtomicCounterTest extends LocalDynamoDbSyncTestBase {
private static final String STRING_VALUE = "string value";
private static final String RECORD_ID = "id123";
private static final TableSchema<AtomicCounterRecord> TABLE_SCHEMA = TableSchema.fromClass(AtomicCounterRecord.class);
private final DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder()
.dynamoDbClient(getDynamoDbClient())
.build();
private final DynamoDbTable<AtomicCounterRecord> mappedTable =
enhancedClient.table(getConcreteTableName("table-name"), TABLE_SCHEMA);
@Before
public void createTable() {
mappedTable.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput()));
}
@After
public void deleteTable() {
getDynamoDbClient().deleteTable(r -> r.tableName(getConcreteTableName("table-name")));
}
@Test
public void createViaUpdate_incrementsCorrectly() {
AtomicCounterRecord record = new AtomicCounterRecord();
record.setId(RECORD_ID);
record.setAttribute1(STRING_VALUE);
mappedTable.updateItem(record);
AtomicCounterRecord persistedRecord = mappedTable.getItem(record);
assertThat(persistedRecord.getAttribute1()).isEqualTo(STRING_VALUE);
assertThat(persistedRecord.getDefaultCounter()).isEqualTo(0L);
assertThat(persistedRecord.getCustomCounter()).isEqualTo(10L);
assertThat(persistedRecord.getDecreasingCounter()).isEqualTo(-20L);
mappedTable.updateItem(record);
persistedRecord = mappedTable.getItem(record);
assertThat(persistedRecord.getAttribute1()).isEqualTo(STRING_VALUE);
assertThat(persistedRecord.getDefaultCounter()).isEqualTo(1L);
assertThat(persistedRecord.getCustomCounter()).isEqualTo(15L);
assertThat(persistedRecord.getDecreasingCounter()).isEqualTo(-21L);
}
@Test
public void createViaUpdate_multipleUpdates_incrementsCorrectly() {
AtomicCounterRecord record = new AtomicCounterRecord();
record.setId(RECORD_ID);
record.setAttribute1(STRING_VALUE);
mappedTable.updateItem(record);
int numUpdates = 50;
IntStream.range(0, numUpdates).forEach(i -> mappedTable.updateItem(record));
AtomicCounterRecord persistedRecord = mappedTable.getItem(record);
assertThat(persistedRecord.getDefaultCounter()).isEqualTo(numUpdates);
assertThat(persistedRecord.getCustomCounter()).isEqualTo(10 + numUpdates * 5);
assertThat(persistedRecord.getDecreasingCounter()).isEqualTo(-20 + numUpdates * -1);
}
@Test
public void createViaPut_incrementsCorrectly() {
AtomicCounterRecord record = new AtomicCounterRecord();
record.setId(RECORD_ID);
record.setAttribute1(STRING_VALUE);
mappedTable.putItem(record);
AtomicCounterRecord persistedRecord = mappedTable.getItem(record);
assertThat(persistedRecord.getAttribute1()).isEqualTo(STRING_VALUE);
assertThat(persistedRecord.getDefaultCounter()).isEqualTo(0L);
assertThat(persistedRecord.getCustomCounter()).isEqualTo(10L);
assertThat(persistedRecord.getDecreasingCounter()).isEqualTo(-20L);
mappedTable.updateItem(record);
persistedRecord = mappedTable.getItem(record);
assertThat(persistedRecord.getAttribute1()).isEqualTo("string value");
assertThat(persistedRecord.getDefaultCounter()).isEqualTo(1L);
assertThat(persistedRecord.getCustomCounter()).isEqualTo(15L);
assertThat(persistedRecord.getDecreasingCounter()).isEqualTo(-21L);
}
@Test
public void createViaUpdate_settingCounterInPojo_hasNoEffect() {
AtomicCounterRecord record = new AtomicCounterRecord();
record.setId(RECORD_ID);
record.setDefaultCounter(10L);
record.setAttribute1(STRING_VALUE);
mappedTable.updateItem(record);
AtomicCounterRecord persistedRecord = mappedTable.getItem(record);
assertThat(persistedRecord.getAttribute1()).isEqualTo(STRING_VALUE);
assertThat(persistedRecord.getDefaultCounter()).isEqualTo(0L);
assertThat(persistedRecord.getCustomCounter()).isEqualTo(10L);
assertThat(persistedRecord.getDecreasingCounter()).isEqualTo(-20L);
}
@Test
public void updateItem_retrievedFromDb_shouldNotThrowException() {
AtomicCounterRecord record = new AtomicCounterRecord();
record.setId(RECORD_ID);
record.setAttribute1(STRING_VALUE);
mappedTable.updateItem(record);
AtomicCounterRecord retrievedRecord = mappedTable.getItem(record);
retrievedRecord.setAttribute1("ChangingThisAttribute");
retrievedRecord = mappedTable.updateItem(retrievedRecord);
assertThat(retrievedRecord).isNotNull();
assertThat(retrievedRecord.getDefaultCounter()).isEqualTo(1L);
assertThat(retrievedRecord.getCustomCounter()).isEqualTo(15L);
assertThat(retrievedRecord.getDecreasingCounter()).isEqualTo(-21L);
}
@Test
public void createViaPut_settingCounterInPojoHasNoEffect() {
AtomicCounterRecord record = new AtomicCounterRecord();
record.setId(RECORD_ID);
record.setDefaultCounter(10L);
record.setAttribute1(STRING_VALUE);
mappedTable.putItem(record);
AtomicCounterRecord persistedRecord = mappedTable.getItem(record);
assertThat(persistedRecord.getAttribute1()).isEqualTo(STRING_VALUE);
assertThat(persistedRecord.getDefaultCounter()).isEqualTo(0L);
}
@Test
public void transactUpdate_incrementsCorrectly() {
AtomicCounterRecord record = new AtomicCounterRecord();
record.setId(RECORD_ID);
record.setAttribute1(STRING_VALUE);
enhancedClient.transactWriteItems(r -> r.addPutItem(mappedTable, record));
AtomicCounterRecord persistedRecord = mappedTable.getItem(record);
assertThat(persistedRecord.getAttribute1()).isEqualTo(STRING_VALUE);
assertThat(persistedRecord.getDefaultCounter()).isEqualTo(0L);
enhancedClient.transactWriteItems(r -> r.addUpdateItem(mappedTable, record));
persistedRecord = mappedTable.getItem(record);
assertThat(persistedRecord.getAttribute1()).isEqualTo(STRING_VALUE);
assertThat(persistedRecord.getDefaultCounter()).isEqualTo(1L);
}
@Test
public void batchPut_initializesCorrectly() {
AtomicCounterRecord record = new AtomicCounterRecord();
record.setId(RECORD_ID);
record.setAttribute1(STRING_VALUE);
enhancedClient.batchWriteItem(r -> r.addWriteBatch(WriteBatch.builder(AtomicCounterRecord.class)
.mappedTableResource(mappedTable)
.addPutItem(record)
.build()));
AtomicCounterRecord persistedRecord = mappedTable.getItem(record);
assertThat(persistedRecord.getAttribute1()).isEqualTo(STRING_VALUE);
assertThat(persistedRecord.getDefaultCounter()).isEqualTo(0L);
enhancedClient.transactWriteItems(r -> r.addUpdateItem(mappedTable, record));
persistedRecord = mappedTable.getItem(record);
assertThat(persistedRecord.getAttribute1()).isEqualTo(STRING_VALUE);
assertThat(persistedRecord.getDefaultCounter()).isEqualTo(1L);
}
}
| 3,849 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/IndexQueryTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.functionaltests;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.numberValue;
import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.stringValue;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primarySortKey;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.secondaryPartitionKey;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.secondarySortKey;
import static software.amazon.awssdk.enhanced.dynamodb.model.QueryConditional.keyEqualTo;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbIndex;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable;
import software.amazon.awssdk.enhanced.dynamodb.Key;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema;
import software.amazon.awssdk.enhanced.dynamodb.model.CreateTableEnhancedRequest;
import software.amazon.awssdk.enhanced.dynamodb.model.EnhancedGlobalSecondaryIndex;
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.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest;
import software.amazon.awssdk.services.dynamodb.model.ProjectionType;
import software.amazon.awssdk.services.dynamodb.model.ReturnConsumedCapacity;
public class IndexQueryTest extends LocalDynamoDbSyncTestBase {
private static class Record {
private String id;
private Integer sort;
private Integer value;
private String gsiId;
private Integer gsiSort;
private String getId() {
return id;
}
private Record setId(String id) {
this.id = id;
return this;
}
private Integer getSort() {
return sort;
}
private Record setSort(Integer sort) {
this.sort = sort;
return this;
}
private Integer getValue() {
return value;
}
private Record setValue(Integer value) {
this.value = value;
return this;
}
private String getGsiId() {
return gsiId;
}
private Record setGsiId(String gsiId) {
this.gsiId = gsiId;
return this;
}
private Integer getGsiSort() {
return gsiSort;
}
private Record setGsiSort(Integer gsiSort) {
this.gsiSort = gsiSort;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Record record = (Record) o;
return Objects.equals(id, record.id) &&
Objects.equals(sort, record.sort) &&
Objects.equals(value, record.value) &&
Objects.equals(gsiId, record.gsiId) &&
Objects.equals(gsiSort, record.gsiSort);
}
@Override
public int hashCode() {
return Objects.hash(id, sort, value, gsiId, gsiSort);
}
}
private static final TableSchema<Record> TABLE_SCHEMA =
StaticTableSchema.builder(Record.class)
.newItemSupplier(Record::new)
.addAttribute(String.class, a -> a.name("id")
.getter(Record::getId)
.setter(Record::setId)
.tags(primaryPartitionKey()))
.addAttribute(Integer.class, a -> a.name("sort")
.getter(Record::getSort)
.setter(Record::setSort)
.tags(primarySortKey()))
.addAttribute(Integer.class, a -> a.name("value")
.getter(Record::getValue)
.setter(Record::setValue))
.addAttribute(String.class, a -> a.name("gsi_id")
.getter(Record::getGsiId)
.setter(Record::setGsiId)
.tags(secondaryPartitionKey("gsi_keys_only")))
.addAttribute(Integer.class, a -> a.name("gsi_sort")
.getter(Record::getGsiSort)
.setter(Record::setGsiSort)
.tags(secondarySortKey("gsi_keys_only")))
.build();
private static final List<Record> RECORDS =
IntStream.range(0, 10)
.mapToObj(i -> new Record()
.setId("id-value")
.setSort(i)
.setValue(i)
.setGsiId("gsi-id-value")
.setGsiSort(i))
.collect(Collectors.toList());
private static final List<Record> KEYS_ONLY_RECORDS =
RECORDS.stream()
.map(record -> new Record()
.setId(record.id)
.setSort(record.sort)
.setGsiId(record.gsiId)
.setGsiSort(record.gsiSort))
.collect(Collectors.toList());
private DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder()
.dynamoDbClient(getDynamoDbClient())
.build();
private DynamoDbTable<Record> mappedTable = enhancedClient.table(getConcreteTableName("table-name"), TABLE_SCHEMA);
private DynamoDbIndex<Record> keysOnlyMappedIndex = mappedTable.index("gsi_keys_only");
private void insertRecords() {
RECORDS.forEach(record -> mappedTable.putItem(r -> r.item(record)));
}
@Before
public void createTable() {
mappedTable.createTable(
CreateTableEnhancedRequest.builder()
.provisionedThroughput(getDefaultProvisionedThroughput())
.globalSecondaryIndices(
EnhancedGlobalSecondaryIndex.builder()
.indexName("gsi_keys_only")
.projection(p -> p.projectionType(ProjectionType.KEYS_ONLY))
.provisionedThroughput(getDefaultProvisionedThroughput())
.build())
.build());
}
@After
public void deleteTable() {
getDynamoDbClient().deleteTable(DeleteTableRequest.builder()
.tableName(getConcreteTableName("table-name"))
.build());
}
@Test
public void queryAllRecordsDefaultSettings_usingShortcutForm() {
insertRecords();
Iterator<Page<Record>> results =
keysOnlyMappedIndex.query(keyEqualTo(k -> k.partitionValue("gsi-id-value"))).iterator();
assertThat(results.hasNext(), is(true));
Page<Record> page = results.next();
assertThat(results.hasNext(), is(false));
assertThat(page.items(), is(KEYS_ONLY_RECORDS));
assertThat(page.lastEvaluatedKey(), is(nullValue()));
assertThat(page.consumedCapacity(), is(nullValue()));
}
@Test
public void queryBetween() {
insertRecords();
Key fromKey = Key.builder().partitionValue("gsi-id-value").sortValue(3).build();
Key toKey = Key.builder().partitionValue("gsi-id-value").sortValue(5).build();
Iterator<Page<Record>> results =
keysOnlyMappedIndex.query(r -> r.queryConditional(QueryConditional.sortBetween(fromKey, toKey))
.returnConsumedCapacity(ReturnConsumedCapacity.INDEXES))
.iterator();
assertThat(results.hasNext(), is(true));
Page<Record> page = results.next();
assertThat(results.hasNext(), is(false));
assertThat(page.items(),
is(KEYS_ONLY_RECORDS.stream().filter(r -> r.sort >= 3 && r.sort <= 5).collect(Collectors.toList())));
assertThat(page.lastEvaluatedKey(), is(nullValue()));
assertThat(page.consumedCapacity(), is(notNullValue()));
assertThat(page.consumedCapacity().capacityUnits(), is(notNullValue()));
assertThat(page.consumedCapacity().globalSecondaryIndexes(), is(notNullValue()));
assertThat(page.count(), equalTo(3));
assertThat(page.scannedCount(), equalTo(3));
}
@Test
public void queryLimit() {
insertRecords();
Iterator<Page<Record>> results =
keysOnlyMappedIndex.query(QueryEnhancedRequest.builder()
.queryConditional(keyEqualTo(k -> k.partitionValue("gsi-id-value")))
.limit(5)
.build())
.iterator();
assertThat(results.hasNext(), is(true));
Page<Record> page1 = results.next();
assertThat(results.hasNext(), is(true));
Page<Record> page2 = results.next();
assertThat(results.hasNext(), is(true));
Page<Record> page3 = results.next();
assertThat(results.hasNext(), is(false));
Map<String, AttributeValue> expectedLastEvaluatedKey1 = new HashMap<>();
expectedLastEvaluatedKey1.put("id", stringValue(KEYS_ONLY_RECORDS.get(4).getId()));
expectedLastEvaluatedKey1.put("sort", numberValue(KEYS_ONLY_RECORDS.get(4).getSort()));
expectedLastEvaluatedKey1.put("gsi_id", stringValue(KEYS_ONLY_RECORDS.get(4).getGsiId()));
expectedLastEvaluatedKey1.put("gsi_sort", numberValue(KEYS_ONLY_RECORDS.get(4).getGsiSort()));
Map<String, AttributeValue> expectedLastEvaluatedKey2 = new HashMap<>();
expectedLastEvaluatedKey2.put("id", stringValue(KEYS_ONLY_RECORDS.get(9).getId()));
expectedLastEvaluatedKey2.put("sort", numberValue(KEYS_ONLY_RECORDS.get(9).getSort()));
expectedLastEvaluatedKey2.put("gsi_id", stringValue(KEYS_ONLY_RECORDS.get(9).getGsiId()));
expectedLastEvaluatedKey2.put("gsi_sort", numberValue(KEYS_ONLY_RECORDS.get(9).getGsiSort()));
assertThat(page1.items(), is(KEYS_ONLY_RECORDS.subList(0, 5)));
assertThat(page1.lastEvaluatedKey(), is(expectedLastEvaluatedKey1));
assertThat(page1.count(), equalTo(5));
assertThat(page1.scannedCount(), equalTo(5));
assertThat(page2.items(), is(KEYS_ONLY_RECORDS.subList(5, 10)));
assertThat(page2.lastEvaluatedKey(), is(expectedLastEvaluatedKey2));
assertThat(page2.count(), equalTo(5));
assertThat(page2.scannedCount(), equalTo(5));
assertThat(page3.items(), is(empty()));
assertThat(page3.lastEvaluatedKey(), is(nullValue()));
assertThat(page3.count(), equalTo(0));
assertThat(page3.scannedCount(), equalTo(0));
}
@Test
public void queryEmpty() {
Iterator<Page<Record>> results =
keysOnlyMappedIndex.query(r -> r.queryConditional(keyEqualTo(k -> k.partitionValue("gsi-id-value")))).iterator();
assertThat(results.hasNext(), is(true));
Page<Record> page = results.next();
assertThat(results.hasNext(), is(false));
assertThat(page.items(), is(empty()));
assertThat(page.lastEvaluatedKey(), is(nullValue()));
assertThat(page.count(), equalTo(0));
assertThat(page.scannedCount(), equalTo(0));
}
@Test
public void queryExclusiveStartKey() {
insertRecords();
Map<String, AttributeValue> expectedLastEvaluatedKey = new HashMap<>();
expectedLastEvaluatedKey.put("id", stringValue(KEYS_ONLY_RECORDS.get(7).getId()));
expectedLastEvaluatedKey.put("sort", numberValue(KEYS_ONLY_RECORDS.get(7).getSort()));
expectedLastEvaluatedKey.put("gsi_id", stringValue(KEYS_ONLY_RECORDS.get(7).getGsiId()));
expectedLastEvaluatedKey.put("gsi_sort", numberValue(KEYS_ONLY_RECORDS.get(7).getGsiSort()));
Iterator<Page<Record>> results =
keysOnlyMappedIndex.query(QueryEnhancedRequest.builder()
.queryConditional(keyEqualTo(k -> k.partitionValue("gsi-id-value")))
.exclusiveStartKey(expectedLastEvaluatedKey).build())
.iterator();
assertThat(results.hasNext(), is(true));
Page<Record> page = results.next();
assertThat(results.hasNext(), is(false));
assertThat(page.items(), is(KEYS_ONLY_RECORDS.subList(8, 10)));
assertThat(page.lastEvaluatedKey(), is(nullValue()));
assertThat(page.count(), equalTo(2));
assertThat(page.scannedCount(), equalTo(2));
}
}
| 3,850 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/AsyncBatchWriteItemTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.functionaltests;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbAsyncTable;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedAsyncClient;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.internal.client.DefaultDynamoDbEnhancedAsyncClient;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema;
import software.amazon.awssdk.enhanced.dynamodb.model.BatchWriteItemEnhancedRequest;
import software.amazon.awssdk.enhanced.dynamodb.model.DeleteItemEnhancedRequest;
import software.amazon.awssdk.enhanced.dynamodb.model.WriteBatch;
import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest;
public class AsyncBatchWriteItemTest extends LocalDynamoDbAsyncTestBase {
private static class Record1 {
private Integer id;
private String attribute;
private Integer getId() {
return id;
}
private Record1 setId(Integer id) {
this.id = id;
return this;
}
private String getAttribute() {
return attribute;
}
private Record1 setAttribute(String attribute) {
this.attribute = attribute;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Record1 record1 = (Record1) o;
return Objects.equals(id, record1.id) &&
Objects.equals(attribute, record1.attribute);
}
@Override
public int hashCode() {
return Objects.hash(id, attribute);
}
}
private static class Record2 {
private Integer id;
private String attribute;
private Integer getId() {
return id;
}
private Record2 setId(Integer id) {
this.id = id;
return this;
}
private String getAttribute() {
return attribute;
}
private Record2 setAttribute(String attribute) {
this.attribute = attribute;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Record2 record2 = (Record2) o;
return Objects.equals(id, record2.id) &&
Objects.equals(attribute, record2.attribute);
}
@Override
public int hashCode() {
return Objects.hash(id, attribute);
}
}
private static final TableSchema<Record1> TABLE_SCHEMA_1 =
StaticTableSchema.builder(Record1.class)
.newItemSupplier(Record1::new)
.addAttribute(Integer.class, a -> a.name("id_1")
.getter(Record1::getId)
.setter(Record1::setId)
.tags(primaryPartitionKey()))
.addAttribute(String.class, a -> a.name("attribute")
.getter(Record1::getAttribute)
.setter(Record1::setAttribute))
.build();
private static final TableSchema<Record2> TABLE_SCHEMA_2 =
StaticTableSchema.builder(Record2.class)
.newItemSupplier(Record2::new)
.addAttribute(Integer.class, a -> a.name("id_2")
.getter(Record2::getId)
.setter(Record2::setId)
.tags(primaryPartitionKey()))
.addAttribute(String.class, a -> a.name("attribute")
.getter(Record2::getAttribute)
.setter(Record2::setAttribute))
.build();
private DynamoDbEnhancedAsyncClient enhancedAsyncClient =
DefaultDynamoDbEnhancedAsyncClient.builder()
.dynamoDbClient(getDynamoDbAsyncClient())
.build();
private DynamoDbAsyncTable<Record1> mappedTable1 = enhancedAsyncClient.table(getConcreteTableName("table-name-1"),
TABLE_SCHEMA_1);
private DynamoDbAsyncTable<Record2> mappedTable2 = enhancedAsyncClient.table(getConcreteTableName("table-name-2"),
TABLE_SCHEMA_2);
private static final List<Record1> RECORDS_1 =
IntStream.range(0, 2)
.mapToObj(i -> new Record1().setId(i).setAttribute(Integer.toString(i)))
.collect(Collectors.toList());
private static final List<Record2> RECORDS_2 =
IntStream.range(0, 2)
.mapToObj(i -> new Record2().setId(i).setAttribute(Integer.toString(i)))
.collect(Collectors.toList());
@Before
public void createTable() {
mappedTable1.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput())).join();
mappedTable2.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput())).join();
}
@After
public void deleteTable() {
getDynamoDbAsyncClient().deleteTable(DeleteTableRequest.builder()
.tableName(getConcreteTableName("table-name-1"))
.build()).join();
getDynamoDbAsyncClient().deleteTable(DeleteTableRequest.builder()
.tableName(getConcreteTableName("table-name-2"))
.build()).join();
}
@Test
public void singlePut() {
List<WriteBatch> writeBatches =
singletonList(WriteBatch.builder(Record1.class)
.mappedTableResource(mappedTable1)
.addPutItem(r -> r.item(RECORDS_1.get(0)))
.build());
enhancedAsyncClient.batchWriteItem(BatchWriteItemEnhancedRequest.builder().writeBatches(writeBatches).build()).join();
Record1 record = mappedTable1.getItem(r -> r.key(k -> k.partitionValue(0))).join();
assertThat(record, is(RECORDS_1.get(0)));
}
@Test
public void multiplePut() {
List<WriteBatch> writeBatches =
asList(WriteBatch.builder(Record1.class)
.mappedTableResource(mappedTable1)
.addPutItem(r -> r.item(RECORDS_1.get(0)))
.build(),
WriteBatch.builder(Record2.class)
.mappedTableResource(mappedTable2)
.addPutItem(r -> r.item(RECORDS_2.get(0)))
.build());
enhancedAsyncClient.batchWriteItem(BatchWriteItemEnhancedRequest.builder().writeBatches(writeBatches).build()).join();
Record1 record1 = mappedTable1.getItem(r -> r.key(k -> k.partitionValue(0))).join();
Record2 record2 = mappedTable2.getItem(r -> r.key(k -> k.partitionValue(0))).join();
assertThat(record1, is(RECORDS_1.get(0)));
assertThat(record2, is(RECORDS_2.get(0)));
}
@Test
public void singleDelete() {
mappedTable1.putItem(r -> r.item(RECORDS_1.get(0))).join();
List<WriteBatch> writeBatches =
singletonList(WriteBatch.builder(Record1.class)
.mappedTableResource(mappedTable1)
.addDeleteItem(r -> r.key(k -> k.partitionValue(0)))
.build());
enhancedAsyncClient.batchWriteItem(BatchWriteItemEnhancedRequest.builder().writeBatches(writeBatches).build()).join();
Record1 record = mappedTable1.getItem(r -> r.key(k -> k.partitionValue(0))).join();
assertThat(record, is(nullValue()));
}
@Test
public void multipleDelete() {
mappedTable1.putItem(r -> r.item(RECORDS_1.get(0))).join();
mappedTable2.putItem(r -> r.item(RECORDS_2.get(0))).join();
List<WriteBatch> writeBatches =
asList(WriteBatch.builder(Record1.class)
.mappedTableResource(mappedTable1)
.addDeleteItem(DeleteItemEnhancedRequest.builder().key(k -> k.partitionValue(0)).build())
.build(),
WriteBatch.builder(Record2.class)
.mappedTableResource(mappedTable2)
.addDeleteItem(DeleteItemEnhancedRequest.builder().key(k -> k.partitionValue(0)).build())
.build());
enhancedAsyncClient.batchWriteItem(BatchWriteItemEnhancedRequest.builder().writeBatches(writeBatches).build()).join();
Record1 record1 = mappedTable1.getItem(r -> r.key(k -> k.partitionValue(0))).join();
Record2 record2 = mappedTable2.getItem(r -> r.key(k -> k.partitionValue(0))).join();
assertThat(record1, is(nullValue()));
assertThat(record2, is(nullValue()));
}
@Test
public void mixedCommands() {
mappedTable1.putItem(r -> r.item(RECORDS_1.get(0))).join();
mappedTable2.putItem(r -> r.item(RECORDS_2.get(0))).join();
enhancedAsyncClient.batchWriteItem(r -> r.writeBatches(
WriteBatch.builder(Record1.class)
.mappedTableResource(mappedTable1)
.addPutItem(i -> i.item(RECORDS_1.get(1)))
.build(),
WriteBatch.builder(Record2.class)
.mappedTableResource(mappedTable2)
.addDeleteItem(i -> i.key(k -> k.partitionValue(0)))
.build())).join();
assertThat(mappedTable1.getItem(r -> r.key(k -> k.partitionValue(0))).join(), is(RECORDS_1.get(0)));
assertThat(mappedTable1.getItem(r -> r.key(k -> k.partitionValue(1))).join(), is(RECORDS_1.get(1)));
assertThat(mappedTable2.getItem(r -> r.key(k -> k.partitionValue(0))).join(), is(nullValue()));
}
}
| 3,851 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/EmptyStringTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.functionaltests;
import static java.util.Collections.singletonMap;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.HashMap;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable;
import software.amazon.awssdk.enhanced.dynamodb.Expression;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
import software.amazon.awssdk.services.dynamodb.model.GetItemResponse;
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
import software.amazon.awssdk.services.dynamodb.model.PutItemResponse;
import software.amazon.awssdk.services.dynamodb.model.ReturnValue;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemResponse;
@RunWith(MockitoJUnitRunner.class)
public class EmptyStringTest {
private static final String TABLE_NAME = "TEST_TABLE";
private static final AttributeValue EMPTY_STRING = AttributeValue.builder().s("").build();
@Mock
private DynamoDbClient mockDynamoDbClient;
private DynamoDbTable<TestBean> dynamoDbTable;
@DynamoDbBean
public static class TestBean {
private String id;
private String s;
@DynamoDbPartitionKey
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getS() {
return s;
}
public void setS(String s) {
this.s = s;
}
}
private static final TableSchema<TestBean> TABLE_SCHEMA = TableSchema.fromClass(TestBean.class);
@Before
public void initializeTable() {
DynamoDbEnhancedClient dynamoDbEnhancedClient = DynamoDbEnhancedClient.builder()
.dynamoDbClient(mockDynamoDbClient)
.build();
this.dynamoDbTable = dynamoDbEnhancedClient.table(TABLE_NAME, TABLE_SCHEMA);
}
@Test
public void putEmptyString() {
TestBean testBean = new TestBean();
testBean.setId("id123");
testBean.setS("");
PutItemResponse response = PutItemResponse.builder().build();
when(mockDynamoDbClient.putItem(any(PutItemRequest.class))).thenReturn(response);
dynamoDbTable.putItem(testBean);
Map<String, AttributeValue> expectedItemMap = new HashMap<>();
expectedItemMap.put("id", AttributeValue.builder().s("id123").build());
expectedItemMap.put("s", EMPTY_STRING);
PutItemRequest expectedRequest = PutItemRequest.builder()
.tableName(TABLE_NAME)
.item(expectedItemMap)
.build();
verify(mockDynamoDbClient).putItem(expectedRequest);
}
@Test
public void getEmptyString() {
Map<String, AttributeValue> itemMap = new HashMap<>();
itemMap.put("id", AttributeValue.builder().s("id123").build());
itemMap.put("s", EMPTY_STRING);
GetItemResponse response = GetItemResponse.builder()
.item(itemMap)
.build();
when(mockDynamoDbClient.getItem(any(GetItemRequest.class))).thenReturn(response);
TestBean result = dynamoDbTable.getItem(r -> r.key(k -> k.partitionValue("id123")));
assertThat(result.getId()).isEqualTo("id123");
assertThat(result.getS()).isEmpty();
}
@Test
public void updateEmptyStringWithCondition() {
Map<String, AttributeValue> expectedItemMap = new HashMap<>();
expectedItemMap.put("id", AttributeValue.builder().s("id123").build());
expectedItemMap.put("s", EMPTY_STRING);
TestBean testBean = new TestBean();
testBean.setId("id123");
testBean.setS("");
UpdateItemResponse response = UpdateItemResponse.builder()
.attributes(expectedItemMap)
.build();
when(mockDynamoDbClient.updateItem(any(UpdateItemRequest.class))).thenReturn(response);
Expression conditionExpression = Expression.builder()
.expression("#attr = :val")
.expressionNames(singletonMap("#attr", "s"))
.expressionValues(singletonMap(":val", EMPTY_STRING))
.build();
TestBean result = dynamoDbTable.updateItem(r -> r.item(testBean).conditionExpression(conditionExpression));
Map<String, String> expectedExpressionAttributeNames = new HashMap<>();
expectedExpressionAttributeNames.put("#AMZN_MAPPED_s", "s");
expectedExpressionAttributeNames.put("#attr", "s");
Map<String, AttributeValue> expectedExpressionAttributeValues = new HashMap<>();
expectedExpressionAttributeValues.put(":AMZN_MAPPED_s", EMPTY_STRING);
expectedExpressionAttributeValues.put(":val", EMPTY_STRING);
Map<String, AttributeValue> expectedKeyMap = new HashMap<>();
expectedKeyMap.put("id", AttributeValue.builder().s("id123").build());
UpdateItemRequest expectedRequest =
UpdateItemRequest.builder()
.tableName(TABLE_NAME)
.key(expectedKeyMap)
.returnValues(ReturnValue.ALL_NEW)
.updateExpression("SET #AMZN_MAPPED_s = :AMZN_MAPPED_s")
.conditionExpression("#attr = :val")
.expressionAttributeNames(expectedExpressionAttributeNames)
.expressionAttributeValues(expectedExpressionAttributeValues)
.build();
verify(mockDynamoDbClient).updateItem(expectedRequest);
assertThat(result.getId()).isEqualTo("id123");
assertThat(result.getS()).isEmpty();
}
}
| 3,852 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/BasicQueryTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.functionaltests;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.numberValue;
import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.stringValue;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primarySortKey;
import static software.amazon.awssdk.enhanced.dynamodb.model.QueryConditional.keyEqualTo;
import static software.amazon.awssdk.enhanced.dynamodb.model.QueryConditional.sortBetween;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import software.amazon.awssdk.core.pagination.sync.SdkIterable;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable;
import software.amazon.awssdk.enhanced.dynamodb.Expression;
import software.amazon.awssdk.enhanced.dynamodb.Key;
import software.amazon.awssdk.enhanced.dynamodb.NestedAttributeName;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.InnerAttributeRecord;
import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.NestedTestRecord;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema;
import software.amazon.awssdk.enhanced.dynamodb.model.Page;
import software.amazon.awssdk.enhanced.dynamodb.model.PageIterable;
import software.amazon.awssdk.enhanced.dynamodb.model.QueryEnhancedRequest;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest;
public class BasicQueryTest extends LocalDynamoDbSyncTestBase {
private static class Record {
private String id;
private Integer sort;
private Integer value;
public String getId() {
return id;
}
public Record setId(String id) {
this.id = id;
return this;
}
public Integer getSort() {
return sort;
}
public Record setSort(Integer sort) {
this.sort = sort;
return this;
}
public Integer getValue() {
return value;
}
public Record setValue(Integer value) {
this.value = value;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Record record = (Record) o;
return Objects.equals(id, record.id) &&
Objects.equals(sort, record.sort) &&
Objects.equals(value, record.value);
}
@Override
public int hashCode() {
return Objects.hash(id, sort, value);
}
}
private static final TableSchema<Record> TABLE_SCHEMA =
StaticTableSchema.builder(Record.class)
.newItemSupplier(Record::new)
.addAttribute(String.class, a -> a.name("id")
.getter(Record::getId)
.setter(Record::setId)
.tags(primaryPartitionKey()))
.addAttribute(Integer.class, a -> a.name("sort")
.getter(Record::getSort)
.setter(Record::setSort)
.tags(primarySortKey()))
.addAttribute(Integer.class, a -> a.name("value")
.getter(Record::getValue)
.setter(Record::setValue))
.build();
private static final List<Record> RECORDS =
IntStream.range(0, 10)
.mapToObj(i -> new Record().setId("id-value").setSort(i).setValue(i))
.collect(Collectors.toList());
private static final List<NestedTestRecord> NESTED_TEST_RECORDS =
IntStream.range(0, 10)
.mapToObj(i -> {
final NestedTestRecord nestedTestRecord = new NestedTestRecord();
nestedTestRecord.setOuterAttribOne("id-value-" + i);
nestedTestRecord.setSort(i);
final InnerAttributeRecord innerAttributeRecord = new InnerAttributeRecord();
innerAttributeRecord.setAttribOne("attribOne-"+i);
innerAttributeRecord.setAttribTwo(i);
nestedTestRecord.setInnerAttributeRecord(innerAttributeRecord);
nestedTestRecord.setDotVariable("v"+i);
return nestedTestRecord;
})
.collect(Collectors.toList());
private DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder()
.dynamoDbClient(getDynamoDbClient())
.build();
private DynamoDbTable<Record> mappedTable = enhancedClient.table(getConcreteTableName("table-name"), TABLE_SCHEMA);
private DynamoDbTable<NestedTestRecord> mappedNestedTable = enhancedClient.table(getConcreteTableName("nested-table-name"),
TableSchema.fromClass(NestedTestRecord.class));
private void insertRecords() {
RECORDS.forEach(record -> mappedTable.putItem(r -> r.item(record)));
NESTED_TEST_RECORDS.forEach(nestedTestRecord -> mappedNestedTable.putItem(r -> r.item(nestedTestRecord)));
}
private void insertNestedRecords() {
NESTED_TEST_RECORDS.forEach(nestedTestRecord -> mappedNestedTable.putItem(r -> r.item(nestedTestRecord)));
}
@Before
public void createTable() {
mappedTable.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput()));
mappedNestedTable.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput()));
}
@After
public void deleteTable() {
getDynamoDbClient().deleteTable(DeleteTableRequest.builder()
.tableName(getConcreteTableName("table-name"))
.build());
getDynamoDbClient().deleteTable(DeleteTableRequest.builder()
.tableName(getConcreteTableName("nested-table-name"))
.build());
}
@Test
public void queryAllRecordsDefaultSettings_shortcutForm() {
insertRecords();
Iterator<Page<Record>> results =
mappedTable.query(keyEqualTo(k -> k.partitionValue("id-value"))).iterator();
assertThat(results.hasNext(), is(true));
Page<Record> page = results.next();
assertThat(results.hasNext(), is(false));
assertThat(page.items(), is(RECORDS));
assertThat(page.lastEvaluatedKey(), is(nullValue()));
}
@Test
public void queryAllRecordsDefaultSettings_withProjection() {
insertRecords();
Iterator<Page<Record>> results =
mappedTable.query(b -> b
.queryConditional(keyEqualTo(k -> k.partitionValue("id-value")))
.attributesToProject("value")
).iterator();
assertThat(results.hasNext(), is(true));
Page<Record> page = results.next();
assertThat(results.hasNext(), is(false));
assertThat(page.items().size(), is(RECORDS.size()));
Record firstRecord = page.items().get(0);
assertThat(firstRecord.id, is(nullValue()));
assertThat(firstRecord.sort, is(nullValue()));
assertThat(firstRecord.value, is(0));
}
@Test
public void queryAllRecordsDefaultSettings_shortcutForm_viaItems() {
insertRecords();
PageIterable<Record> query = mappedTable.query(keyEqualTo(k -> k.partitionValue("id-value")));
SdkIterable<Record> results = query.items();
assertThat(results.stream().collect(Collectors.toList()), is(RECORDS));
}
@Test
public void queryAllRecordsWithFilter() {
insertRecords();
Map<String, AttributeValue> expressionValues = new HashMap<>();
expressionValues.put(":min_value", numberValue(3));
expressionValues.put(":max_value", numberValue(5));
Expression expression = Expression.builder()
.expression("#value >= :min_value AND #value <= :max_value")
.expressionValues(expressionValues)
.expressionNames(Collections.singletonMap("#value", "value"))
.build();
Iterator<Page<Record>> results =
mappedTable.query(QueryEnhancedRequest.builder()
.queryConditional(keyEqualTo(k -> k.partitionValue("id-value")))
.filterExpression(expression)
.build())
.iterator();
assertThat(results.hasNext(), is(true));
Page<Record> page = results.next();
assertThat(results.hasNext(), is(false));
assertThat(page.items(),
is(RECORDS.stream().filter(r -> r.sort >= 3 && r.sort <= 5).collect(Collectors.toList())));
assertThat(page.lastEvaluatedKey(), is(nullValue()));
}
@Test
public void queryAllRecordsWithFilterAndProjection() {
insertRecords();
Map<String, AttributeValue> expressionValues = new HashMap<>();
expressionValues.put(":min_value", numberValue(3));
expressionValues.put(":max_value", numberValue(5));
Expression expression = Expression.builder()
.expression("#value >= :min_value AND #value <= :max_value")
.expressionValues(expressionValues)
.expressionNames(Collections.singletonMap("#value", "value"))
.build();
Iterator<Page<Record>> results =
mappedTable.query(QueryEnhancedRequest.builder()
.queryConditional(keyEqualTo(k -> k.partitionValue("id-value")))
.filterExpression(expression)
.attributesToProject("value")
.build())
.iterator();
assertThat(results.hasNext(), is(true));
Page<Record> page = results.next();
assertThat(results.hasNext(), is(false));
assertThat(page.items(), hasSize(3));
assertThat(page.lastEvaluatedKey(), is(nullValue()));
Record record = page.items().get(0);
assertThat(record.id, nullValue());
assertThat(record.sort, nullValue());
assertThat(record.value, is(3));
}
@Test
public void queryBetween() {
insertRecords();
Key fromKey = Key.builder().partitionValue("id-value").sortValue(3).build();
Key toKey = Key.builder().partitionValue("id-value").sortValue(5).build();
Iterator<Page<Record>> results = mappedTable.query(r -> r.queryConditional(sortBetween(fromKey, toKey))).iterator();
assertThat(results.hasNext(), is(true));
Page<Record> page = results.next();
assertThat(results.hasNext(), is(false));
assertThat(page.items(),
is(RECORDS.stream().filter(r -> r.sort >= 3 && r.sort <= 5).collect(Collectors.toList())));
assertThat(page.lastEvaluatedKey(), is(nullValue()));
}
@Test
public void queryLimit() {
insertRecords();
Iterator<Page<Record>> results =
mappedTable.query(QueryEnhancedRequest.builder()
.queryConditional(keyEqualTo(k -> k.partitionValue("id-value")))
.limit(5)
.build())
.iterator();
assertThat(results.hasNext(), is(true));
Page<Record> page1 = results.next();
assertThat(results.hasNext(), is(true));
Page<Record> page2 = results.next();
assertThat(results.hasNext(), is(true));
Page<Record> page3 = results.next();
assertThat(results.hasNext(), is(false));
Map<String, AttributeValue> expectedLastEvaluatedKey1 = new HashMap<>();
expectedLastEvaluatedKey1.put("id", stringValue("id-value"));
expectedLastEvaluatedKey1.put("sort", numberValue(4));
Map<String, AttributeValue> expectedLastEvaluatedKey2 = new HashMap<>();
expectedLastEvaluatedKey2.put("id", stringValue("id-value"));
expectedLastEvaluatedKey2.put("sort", numberValue(9));
assertThat(page1.items(), is(RECORDS.subList(0, 5)));
assertThat(page1.lastEvaluatedKey(), is(expectedLastEvaluatedKey1));
assertThat(page2.items(), is(RECORDS.subList(5, 10)));
assertThat(page2.lastEvaluatedKey(), is(expectedLastEvaluatedKey2));
assertThat(page3.items(), is(empty()));
assertThat(page3.lastEvaluatedKey(), is(nullValue()));
}
@Test
public void queryEmpty() {
Iterator<Page<Record>> results =
mappedTable.query(r -> r.queryConditional(keyEqualTo(k -> k.partitionValue("id-value")))).iterator();
assertThat(results.hasNext(), is(true));
Page<Record> page = results.next();
assertThat(results.hasNext(), is(false));
assertThat(page.items(), is(empty()));
assertThat(page.lastEvaluatedKey(), is(nullValue()));
}
@Test
public void queryEmpty_viaItems() {
PageIterable<Record> query = mappedTable.query(keyEqualTo(k -> k.partitionValue("id-value")));
SdkIterable<Record> results = query.items();
assertThat(results.stream().collect(Collectors.toList()), is(empty()));
}
@Test
public void queryExclusiveStartKey() {
Map<String, AttributeValue> exclusiveStartKey = new HashMap<>();
exclusiveStartKey.put("id", stringValue("id-value"));
exclusiveStartKey.put("sort", numberValue(7));
insertRecords();
Iterator<Page<Record>> results =
mappedTable.query(QueryEnhancedRequest.builder()
.queryConditional(keyEqualTo(k -> k.partitionValue("id-value")))
.exclusiveStartKey(exclusiveStartKey)
.build())
.iterator();
assertThat(results.hasNext(), is(true));
Page<Record> page = results.next();
assertThat(results.hasNext(), is(false));
assertThat(page.items(), is(RECORDS.subList(8, 10)));
assertThat(page.lastEvaluatedKey(), is(nullValue()));
}
@Test
public void queryExclusiveStartKey_viaItems() {
Map<String, AttributeValue> exclusiveStartKey = new HashMap<>();
exclusiveStartKey.put("id", stringValue("id-value"));
exclusiveStartKey.put("sort", numberValue(7));
insertRecords();
SdkIterable<Record> results =
mappedTable.query(QueryEnhancedRequest.builder()
.queryConditional(keyEqualTo(k -> k.partitionValue("id-value")))
.exclusiveStartKey(exclusiveStartKey)
.build())
.items();
assertThat(results.stream().collect(Collectors.toList()), is(RECORDS.subList(8, 10)));
}
@Test
public void queryNestedRecord_SingleAttributeName() {
insertNestedRecords();
Iterator<Page<NestedTestRecord>> results =
mappedNestedTable.query(b -> b
.queryConditional(keyEqualTo(k -> k.partitionValue("id-value-1")))
.addNestedAttributeToProject(NestedAttributeName.builder().addElement("innerAttributeRecord")
.addElement("attribOne").build())).iterator();
assertThat(results.hasNext(), is(true));
Page<NestedTestRecord> page = results.next();
assertThat(results.hasNext(), is(false));
assertThat(page.items().size(), is(1));
NestedTestRecord firstRecord = page.items().get(0);
assertThat(firstRecord.getOuterAttribOne(), is(nullValue()));
assertThat(firstRecord.getSort(), is(nullValue()));
assertThat(firstRecord.getInnerAttributeRecord().getAttribOne(), is("attribOne-1"));
assertThat(firstRecord.getInnerAttributeRecord().getAttribTwo(), is(nullValue()));
results =
mappedNestedTable.query(b -> b
.queryConditional(keyEqualTo(k -> k.partitionValue("id-value-1")))
.addAttributeToProject("sort")).iterator();
assertThat(results.hasNext(), is(true));
page = results.next();
assertThat(results.hasNext(), is(false));
assertThat(page.items().size(), is(1));
firstRecord = page.items().get(0);
assertThat(firstRecord.getOuterAttribOne(), is(nullValue()));
assertThat(firstRecord.getSort(), is(1));
assertThat(firstRecord.getInnerAttributeRecord(), is(nullValue()));
}
@Test
public void queryNestedRecord_withAttributeNameList() {
insertNestedRecords();
Iterator<Page<NestedTestRecord>> results =
mappedNestedTable.query(b -> b
.queryConditional(keyEqualTo(k -> k.partitionValue("id-value-1")))
.addNestedAttributesToProject(Arrays.asList(
NestedAttributeName.builder().elements("innerAttributeRecord", "attribOne").build(),
NestedAttributeName.builder().addElement("outerAttribOne").build()))
.addNestedAttributesToProject(NestedAttributeName.builder()
.addElements(Arrays.asList("innerAttributeRecord",
"attribTwo")).build())).iterator();
assertThat(results.hasNext(), is(true));
Page<NestedTestRecord> page = results.next();
assertThat(results.hasNext(), is(false));
assertThat(page.items().size(), is(1));
NestedTestRecord firstRecord = page.items().get(0);
assertThat(firstRecord.getOuterAttribOne(), is("id-value-1"));
assertThat(firstRecord.getSort(), is(nullValue()));
assertThat(firstRecord.getInnerAttributeRecord().getAttribOne(), is("attribOne-1"));
assertThat(firstRecord.getInnerAttributeRecord().getAttribTwo(), is(1));
}
@Test
public void queryNestedRecord_withAttributeNameListAndStringAttributeToProjectAppended() {
insertNestedRecords();
Iterator<Page<NestedTestRecord>> results =
mappedNestedTable.query(b -> b
.queryConditional(keyEqualTo(k -> k.partitionValue("id-value-1")))
.addNestedAttributesToProject(Arrays.asList(
NestedAttributeName.builder().elements("innerAttributeRecord","attribOne").build()))
.addNestedAttributesToProject(NestedAttributeName.create("innerAttributeRecord","attribTwo"))
.addAttributeToProject("sort")).iterator();
assertThat(results.hasNext(), is(true));
Page<NestedTestRecord> page = results.next();
assertThat(results.hasNext(), is(false));
assertThat(page.items().size(), is(1));
NestedTestRecord firstRecord = page.items().get(0);
assertThat(firstRecord.getOuterAttribOne(), is(is(nullValue())));
assertThat(firstRecord.getSort(), is(1));
assertThat(firstRecord.getInnerAttributeRecord().getAttribOne(), is("attribOne-1"));
assertThat(firstRecord.getInnerAttributeRecord().getAttribTwo(), is(1));
}
@Test
public void queryAllRecordsDefaultSettings_withNestedProjectionNamesNotInNameMap() {
insertNestedRecords();
Iterator<Page<NestedTestRecord>> results =
mappedNestedTable.query(b -> b
.queryConditional(keyEqualTo(k -> k.partitionValue("id-value-1")))
.addNestedAttributeToProject( NestedAttributeName.builder().addElement("nonExistentSlot").build())).iterator();
assertThat(results.hasNext(), is(true));
Page<NestedTestRecord> page = results.next();
assertThat(results.hasNext(), is(false));
assertThat(page.items().size(), is(1));
NestedTestRecord firstRecord = page.items().get(0);
assertThat(firstRecord, is(nullValue()));
}
@Test
public void queryRecordDefaultSettings_withDotInTheName() {
insertNestedRecords();
Iterator<Page<NestedTestRecord>> results =
mappedNestedTable.query(b -> b
.queryConditional(keyEqualTo(k -> k.partitionValue("id-value-7")))
.addNestedAttributeToProject( NestedAttributeName.create("test.com"))).iterator();
assertThat(results.hasNext(), is(true));
Page<NestedTestRecord> page = results.next();
assertThat(results.hasNext(), is(false));
assertThat(page.items().size(), is(1));
NestedTestRecord firstRecord = page.items().get(0);
assertThat(firstRecord.getOuterAttribOne(), is(is(nullValue())));
assertThat(firstRecord.getSort(), is(is(nullValue())));
assertThat(firstRecord.getInnerAttributeRecord() , is(nullValue()));
assertThat(firstRecord.getDotVariable(), is("v7"));
Iterator<Page<NestedTestRecord>> resultWithAttributeToProject =
mappedNestedTable.query(b -> b
.queryConditional(keyEqualTo(k -> k.partitionValue("id-value-7")))
.attributesToProject( "test.com").build()).iterator();
assertThat(resultWithAttributeToProject.hasNext(), is(true));
Page<NestedTestRecord> pageResult = resultWithAttributeToProject.next();
assertThat(resultWithAttributeToProject.hasNext(), is(false));
assertThat(pageResult.items().size(), is(1));
NestedTestRecord record = pageResult.items().get(0);
assertThat(record.getOuterAttribOne(), is(is(nullValue())));
assertThat(record.getSort(), is(is(nullValue())));
assertThat(firstRecord.getInnerAttributeRecord() , is(nullValue()));
assertThat(record.getDotVariable(), is("v7"));
}
@Test
public void queryRecordDefaultSettings_withEmptyAttributeList() {
insertNestedRecords();
Iterator<Page<NestedTestRecord>> results =
mappedNestedTable.query(b -> b
.queryConditional(keyEqualTo(k -> k.partitionValue("id-value-7")))
.attributesToProject(new ArrayList<>()).build()).iterator();
assertThat(results.hasNext(), is(true));
Page<NestedTestRecord> page = results.next();
assertThat(results.hasNext(), is(false));
assertThat(page.items().size(), is(1));
NestedTestRecord firstRecord = page.items().get(0);
assertThat(firstRecord.getOuterAttribOne(), is("id-value-7"));
assertThat(firstRecord.getSort(), is(7));
assertThat(firstRecord.getInnerAttributeRecord().getAttribTwo(), is(7));
assertThat(firstRecord.getDotVariable(), is("v7"));
}
@Test
public void queryRecordDefaultSettings_withNullAttributeList() {
insertNestedRecords();
List<String> backwardCompatibilty = null;
Iterator<Page<NestedTestRecord>> results =
mappedNestedTable.query(b -> b
.queryConditional(keyEqualTo(k -> k.partitionValue("id-value-7")))
.attributesToProject(backwardCompatibilty).build()).iterator();
assertThat(results.hasNext(), is(true));
Page<NestedTestRecord> page = results.next();
assertThat(results.hasNext(), is(false));
assertThat(page.items().size(), is(1));
NestedTestRecord firstRecord = page.items().get(0);
assertThat(firstRecord.getOuterAttribOne(), is("id-value-7"));
assertThat(firstRecord.getSort(), is(7));
assertThat(firstRecord.getInnerAttributeRecord().getAttribTwo(), is(7));
assertThat(firstRecord.getDotVariable(), is("v7"));
}
@Test
public void queryAllRecordsDefaultSettings_withNestedProjectionNameEmptyNameMap() {
insertNestedRecords();
assertThatExceptionOfType(Exception.class).isThrownBy(
() -> {
Iterator<Page<NestedTestRecord>> results = mappedNestedTable.query(b -> b.queryConditional(
keyEqualTo(k -> k.partitionValue("id-value-3")))
.attributesToProject("").build()).iterator();
assertThat(results.hasNext(), is(true));
Page<NestedTestRecord> page = results.next();
});
assertThatExceptionOfType(Exception.class).isThrownBy(
() -> {
Iterator<Page<NestedTestRecord>> results = mappedNestedTable.query(b -> b.queryConditional(
keyEqualTo(k -> k.partitionValue("id-value-3")))
.addNestedAttributeToProject(NestedAttributeName.create("")).build()).iterator();
assertThat(results.hasNext(), is(true));
Page<NestedTestRecord> page = results.next();
});
}
}
| 3,853 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/VersionedRecordTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.functionaltests;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static software.amazon.awssdk.enhanced.dynamodb.extensions.VersionedRecordExtension.AttributeTags.versionAttribute;
import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.stringValue;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey;
import java.util.Objects;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable;
import software.amazon.awssdk.enhanced.dynamodb.Expression;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.extensions.VersionedRecordExtension;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema;
import software.amazon.awssdk.enhanced.dynamodb.model.PutItemEnhancedRequest;
import software.amazon.awssdk.enhanced.dynamodb.model.UpdateItemEnhancedRequest;
import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException;
import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest;
public class VersionedRecordTest extends LocalDynamoDbSyncTestBase {
private static class Record {
private String id;
private String attribute;
private Integer version;
private String getId() {
return id;
}
private Record setId(String id) {
this.id = id;
return this;
}
private String getAttribute() {
return attribute;
}
private Record setAttribute(String attribute) {
this.attribute = attribute;
return this;
}
private Integer getVersion() {
return version;
}
private Record setVersion(Integer version) {
this.version = version;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Record record = (Record) o;
return Objects.equals(id, record.id) &&
Objects.equals(attribute, record.attribute) &&
Objects.equals(version, record.version);
}
@Override
public int hashCode() {
return Objects.hash(id, attribute, version);
}
}
private static final TableSchema<Record> TABLE_SCHEMA =
StaticTableSchema.builder(Record.class)
.newItemSupplier(Record::new)
.addAttribute(String.class, a -> a.name("id")
.getter(Record::getId)
.setter(Record::setId)
.tags(primaryPartitionKey()))
.addAttribute(String.class, a -> a.name("attribute")
.getter(Record::getAttribute)
.setter(Record::setAttribute))
.addAttribute(Integer.class, a -> a.name("version")
.getter(Record::getVersion)
.setter(Record::setVersion)
.tags(versionAttribute()))
.build();
private DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder()
.dynamoDbClient(getDynamoDbClient())
.extensions(VersionedRecordExtension.builder().build())
.build();
private DynamoDbTable<Record> mappedTable = enhancedClient.table(getConcreteTableName("table-name"), TABLE_SCHEMA);
@Rule
public ExpectedException exception = ExpectedException.none();
@Before
public void createTable() {
mappedTable.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput()));
}
@After
public void deleteTable() {
getDynamoDbClient().deleteTable(DeleteTableRequest.builder()
.tableName(getConcreteTableName("table-name"))
.build());
}
@Test
public void putNewRecordSetsInitialVersion() {
mappedTable.putItem(r -> r.item(new Record().setId("id").setAttribute("one")));
Record result = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id")));
Record expectedResult = new Record().setId("id").setAttribute("one").setVersion(1);
assertThat(result, is(expectedResult));
}
@Test
public void updateNewRecordSetsInitialVersion() {
Record result = mappedTable.updateItem(r -> r.item(new Record().setId("id").setAttribute("one")));
Record expectedResult = new Record().setId("id").setAttribute("one").setVersion(1);
assertThat(result, is(expectedResult));
}
@Test
public void putExistingRecordVersionMatches() {
mappedTable.putItem(r -> r.item(new Record().setId("id").setAttribute("one")));
mappedTable.putItem(r -> r.item(new Record().setId("id").setAttribute("one").setVersion(1)));
Record result = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id")));
Record expectedResult = new Record().setId("id").setAttribute("one").setVersion(2);
assertThat(result, is(expectedResult));
}
@Test
public void putExistingRecordVersionMatchesConditionExpressionMatches() {
mappedTable.putItem(r -> r.item(new Record().setId("id").setAttribute("one")));
Expression conditionExpression = Expression.builder()
.expression("#k = :v OR #k = :v1")
.putExpressionName("#k", "attribute")
.putExpressionValue(":v", stringValue("wrong"))
.putExpressionValue(":v1", stringValue("one"))
.build();
mappedTable.putItem(PutItemEnhancedRequest.builder(Record.class)
.item(new Record().setId("id").setAttribute("one").setVersion(1))
.conditionExpression(conditionExpression)
.build());
Record result = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id")));
Record expectedResult = new Record().setId("id").setAttribute("one").setVersion(2);
assertThat(result, is(expectedResult));
}
@Test
public void putExistingRecordVersionDoesNotMatchConditionExpressionMatches() {
mappedTable.putItem(r -> r.item(new Record().setId("id").setAttribute("one")));
Expression conditionExpression = Expression.builder()
.expression("#k = :v OR #k = :v1")
.putExpressionName("#k", "attribute")
.putExpressionValue(":v", stringValue("wrong"))
.putExpressionValue(":v1", stringValue("one"))
.build();
exception.expect(ConditionalCheckFailedException.class);
mappedTable.putItem(PutItemEnhancedRequest.builder(Record.class)
.item(new Record().setId("id").setAttribute("one").setVersion(2))
.conditionExpression(conditionExpression)
.build());
}
@Test
public void putExistingRecordVersionMatchesConditionExpressionDoesNotMatch() {
mappedTable.putItem(r -> r.item(new Record().setId("id").setAttribute("one")));
Expression conditionExpression = Expression.builder()
.expression("#k = :v OR #k = :v1")
.putExpressionName("#k", "attribute")
.putExpressionValue(":v", stringValue("wrong"))
.putExpressionValue(":v1", stringValue("wrong2"))
.build();
exception.expect(ConditionalCheckFailedException.class);
mappedTable.putItem(PutItemEnhancedRequest.builder(Record.class)
.item(new Record().setId("id").setAttribute("one").setVersion(1))
.conditionExpression(conditionExpression)
.build());
}
@Test
public void updateExistingRecordVersionMatchesConditionExpressionMatches() {
mappedTable.putItem(r -> r.item(new Record().setId("id").setAttribute("one")));
Expression conditionExpression = Expression.builder()
.expression("#k = :v OR #k = :v1")
.putExpressionName("#k", "attribute")
.putExpressionValue(":v", stringValue("wrong"))
.putExpressionValue(":v1", stringValue("one"))
.build();
mappedTable.updateItem(UpdateItemEnhancedRequest.builder(Record.class)
.item(new Record().setId("id").setAttribute("one").setVersion(1))
.conditionExpression(conditionExpression)
.build());
Record result = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id")));
Record expectedResult = new Record().setId("id").setAttribute("one").setVersion(2);
assertThat(result, is(expectedResult));
}
@Test
public void updateExistingRecordVersionDoesNotMatchConditionExpressionMatches() {
mappedTable.putItem(r -> r.item(new Record().setId("id").setAttribute("one")));
Expression conditionExpression = Expression.builder()
.expression("#k = :v OR #k = :v1")
.putExpressionName("#k", "attribute")
.putExpressionValue(":v", stringValue("wrong"))
.putExpressionValue(":v1", stringValue("one"))
.build();
exception.expect(ConditionalCheckFailedException.class);
mappedTable.updateItem(UpdateItemEnhancedRequest.builder(Record.class)
.item(new Record().setId("id").setAttribute("one").setVersion(2))
.conditionExpression(conditionExpression)
.build());
}
@Test
public void updateExistingRecordVersionMatchesConditionExpressionDoesNotMatch() {
mappedTable.putItem(r -> r.item(new Record().setId("id").setAttribute("one")));
Expression conditionExpression = Expression.builder()
.expression("#k = :v OR #k = :v1")
.putExpressionName("#k", "attribute")
.putExpressionValue(":v", stringValue("wrong"))
.putExpressionValue(":v1", stringValue("wrong2"))
.build();
exception.expect(ConditionalCheckFailedException.class);
mappedTable.updateItem(UpdateItemEnhancedRequest.builder(Record.class)
.item(new Record().setId("id").setAttribute("one").setVersion(1))
.conditionExpression(conditionExpression)
.build());
}
@Test
public void updateExistingRecordVersionMatches() {
mappedTable.putItem(r -> r.item(new Record().setId("id").setAttribute("one")));
Record result =
mappedTable.updateItem(r -> r.item(new Record().setId("id").setAttribute("one").setVersion(1)));
Record expectedResult = new Record().setId("id").setAttribute("one").setVersion(2);
assertThat(result, is(expectedResult));
}
@Test(expected = ConditionalCheckFailedException.class)
public void putNewRecordTwice() {
mappedTable.putItem(r -> r.item(new Record().setId("id").setAttribute("one")));
mappedTable.putItem(r -> r.item(new Record().setId("id").setAttribute("one")));
}
@Test(expected = ConditionalCheckFailedException.class)
public void updateNewRecordTwice() {
mappedTable.updateItem(r -> r.item(new Record().setId("id").setAttribute("one")));
mappedTable.updateItem(r -> r.item(new Record().setId("id").setAttribute("one")));
}
@Test(expected = ConditionalCheckFailedException.class)
public void putRecordWithWrongVersionNumber() {
mappedTable.putItem(r -> r.item(new Record().setId("id").setAttribute("one")));
mappedTable.putItem(r -> r.item(new Record().setId("id").setAttribute("one").setVersion(2)));
}
}
| 3,854 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/AsyncBasicControlPlaneTableOperationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.functionaltests;
import static org.assertj.core.api.Assertions.assertThat;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primarySortKey;
import java.util.Objects;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbAsyncTable;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedAsyncClient;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.internal.client.DefaultDynamoDbEnhancedAsyncClient;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema;
import software.amazon.awssdk.enhanced.dynamodb.model.CreateTableEnhancedRequest;
import software.amazon.awssdk.enhanced.dynamodb.model.DescribeTableEnhancedResponse;
import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest;
public class AsyncBasicControlPlaneTableOperationTest extends LocalDynamoDbAsyncTestBase {
private static final TableSchema<Record> TABLE_SCHEMA =
StaticTableSchema.builder(Record.class)
.newItemSupplier(Record::new)
.addAttribute(String.class, a -> a.name("id")
.getter(Record::getId)
.setter(Record::setId)
.tags(primaryPartitionKey()))
.addAttribute(Integer.class, a -> a.name("sort")
.getter(Record::getSort)
.setter(Record::setSort)
.tags(primarySortKey()))
.build();
private final String tableName = getConcreteTableName("table-name");
private final DynamoDbEnhancedAsyncClient enhancedAsyncClient = DefaultDynamoDbEnhancedAsyncClient.builder()
.dynamoDbClient(getDynamoDbAsyncClient())
.build();
private final DynamoDbAsyncTable<AsyncBasicControlPlaneTableOperationTest.Record> asyncMappedTable = enhancedAsyncClient.table(tableName, TABLE_SCHEMA);
@Before
public void createTable() {
asyncMappedTable.createTable(
CreateTableEnhancedRequest.builder()
.provisionedThroughput(getDefaultProvisionedThroughput())
.build()).join();
getDynamoDbAsyncClient().waiter().waitUntilTableExists(b -> b.tableName(tableName)).join();
}
@After
public void deleteTable() {
getDynamoDbAsyncClient().deleteTable(DeleteTableRequest.builder()
.tableName(tableName)
.build())
.join();
getDynamoDbAsyncClient().waiter().waitUntilTableNotExists(b -> b.tableName(tableName)).join();
}
@Test
public void describeTable() {
DescribeTableEnhancedResponse describeTableEnhancedResponse = asyncMappedTable.describeTable().join();
assertThat(describeTableEnhancedResponse.table()).isNotNull();
assertThat(describeTableEnhancedResponse.table().tableName()).isEqualTo(tableName);
}
private static class Record {
private String id;
private Integer sort;
private String getId() {
return id;
}
private Record setId(String id) {
this.id = id;
return this;
}
private Integer getSort() {
return sort;
}
private Record setSort(Integer sort) {
this.sort = sort;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Record record = (Record) o;
return Objects.equals(id, record.id) &&
Objects.equals(sort, record.sort);
}
@Override
public int hashCode() {
return Objects.hash(id, sort);
}
}
}
| 3,855 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/AsyncPutItemWithResponseTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.functionaltests;
import static org.assertj.core.api.Assertions.assertThat;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey;
import java.util.Objects;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbAsyncTable;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedAsyncClient;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema;
import software.amazon.awssdk.enhanced.dynamodb.model.PutItemEnhancedResponse;
import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest;
import software.amazon.awssdk.services.dynamodb.model.ReturnConsumedCapacity;
import software.amazon.awssdk.services.dynamodb.model.ReturnValue;
public class AsyncPutItemWithResponseTest extends LocalDynamoDbAsyncTestBase {
private static class Record {
private Integer id;
private String stringAttr1;
private Integer getId() {
return id;
}
private Record setId(Integer id) {
this.id = id;
return this;
}
private String getStringAttr1() {
return stringAttr1;
}
private Record setStringAttr1(String stringAttr1) {
this.stringAttr1 = stringAttr1;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Record record = (Record) o;
return Objects.equals(id, record.id) && Objects.equals(stringAttr1, record.stringAttr1);
}
@Override
public int hashCode() {
return Objects.hash(id, stringAttr1);
}
}
private static final TableSchema<Record> TABLE_SCHEMA =
StaticTableSchema.builder(Record.class)
.newItemSupplier(Record::new)
.addAttribute(Integer.class, a -> a.name("id_1")
.getter(Record::getId)
.setter(Record::setId)
.tags(primaryPartitionKey()))
.addAttribute(String.class, a -> a.name("stringAttr1")
.getter(Record::getStringAttr1)
.setter(Record::setStringAttr1))
.build();
private final DynamoDbEnhancedAsyncClient enhancedClient = DynamoDbEnhancedAsyncClient.builder()
.dynamoDbClient(getDynamoDbAsyncClient())
.build();
private final DynamoDbAsyncTable<Record> mappedTable1 = enhancedClient.table(getConcreteTableName("table-name-1"), TABLE_SCHEMA);
@Before
public void createTable() {
mappedTable1.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput()))
.join();
}
@After
public void deleteTable() {
getDynamoDbAsyncClient().deleteTable(DeleteTableRequest.builder()
.tableName(getConcreteTableName("table-name-1"))
.build())
.join();
}
@Test
public void returnValues_unset_attributesNull() {
Record record = new Record().setId(1).setStringAttr1("a");
mappedTable1.putItem(record).join();
record.setStringAttr1("b");
PutItemEnhancedResponse<Record> response = mappedTable1.putItemWithResponse(r -> r.item(record)).join();
assertThat(response.attributes()).isNull();
}
@Test
public void returnValues_allOld_attributesMapped() {
Record original = new Record().setId(1).setStringAttr1("a");
mappedTable1.putItem(original).join();
Record update = new Record().setId(1).setStringAttr1("b");
PutItemEnhancedResponse<Record> response = mappedTable1.putItemWithResponse(r -> r.returnValues(ReturnValue.ALL_OLD)
.item(update))
.join();
Record returned = response.attributes();
assertThat(returned).isEqualTo(original);
}
@Test
public void returnConsumedCapacity_unset_consumedCapacityNull() {
Record record = new Record().setId(1).setStringAttr1("a");
PutItemEnhancedResponse<Record> response = mappedTable1.putItemWithResponse(r -> r.item(record)).join();
assertThat(response.consumedCapacity()).isNull();
}
@Test
public void returnConsumedCapacity_set_consumedCapacityNotNull() {
Record record = new Record().setId(1).setStringAttr1("a");
PutItemEnhancedResponse<Record> response = mappedTable1.putItemWithResponse(r -> r.item(record)
.returnConsumedCapacity(ReturnConsumedCapacity.TOTAL))
.join();
assertThat(response.consumedCapacity()).isNotNull();
}
// Note: DynamoDB Local does not support returning ItemCollectionMetrics. See AsyncPutItemWithResponseIntegrationTest for
// additional testing for this method.
@Test
public void returnItemCollectionMetrics_unset_itemCollectionMetricsNull() {
Record record = new Record().setId(1);
PutItemEnhancedResponse<Record> response = mappedTable1.putItemWithResponse(r -> r.item(record))
.join();
assertThat(response.consumedCapacity()).isNull();
}
}
| 3,856 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/LocalDynamoDbSyncTestBase.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.functionaltests;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
public class LocalDynamoDbSyncTestBase extends LocalDynamoDbTestBase {
private DynamoDbClient dynamoDbClient = localDynamoDb().createClient();
protected DynamoDbClient getDynamoDbClient() {
return dynamoDbClient;
}
}
| 3,857 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/AutoGeneratedTimestampRecordTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, AutoTimestamp 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.functionaltests;
import static java.util.stream.Collectors.toList;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static software.amazon.awssdk.enhanced.dynamodb.extensions.AutoGeneratedTimestampRecordExtension.AttributeTags.autoGeneratedTimestampAttribute;
import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.stringValue;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.updateBehavior;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.stream.IntStream;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.Mockito;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable;
import software.amazon.awssdk.enhanced.dynamodb.Expression;
import software.amazon.awssdk.enhanced.dynamodb.OperationContext;
import software.amazon.awssdk.enhanced.dynamodb.TableMetadata;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.converters.EpochMillisFormatTestConverter;
import software.amazon.awssdk.enhanced.dynamodb.converters.TimeFormatUpdateTestConverter;
import software.amazon.awssdk.enhanced.dynamodb.extensions.AutoGeneratedTimestampRecordExtension;
import software.amazon.awssdk.enhanced.dynamodb.internal.extensions.DefaultDynamoDbExtensionContext;
import software.amazon.awssdk.enhanced.dynamodb.internal.operations.DefaultOperationContext;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema;
import software.amazon.awssdk.enhanced.dynamodb.mapper.UpdateBehavior;
import software.amazon.awssdk.enhanced.dynamodb.model.PutItemEnhancedRequest;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException;
import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest;
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
import software.amazon.awssdk.services.dynamodb.model.GetItemResponse;
public class AutoGeneratedTimestampRecordTest extends LocalDynamoDbSyncTestBase {
public static final Instant MOCKED_INSTANT_NOW = Instant.now(Clock.fixed(Instant.parse("2019-01-13T14:00:00Z"),
ZoneOffset.UTC));
public static final Instant MOCKED_INSTANT_UPDATE_ONE = Instant.now(Clock.fixed(Instant.parse("2019-01-14T14:00:00Z"),
ZoneOffset.UTC));
public static final Instant MOCKED_INSTANT_UPDATE_TWO = Instant.now(Clock.fixed(Instant.parse("2019-01-15T14:00:00Z"),
ZoneOffset.UTC));
private static final String TABLE_NAME = "table-name";
private static final OperationContext PRIMARY_CONTEXT =
DefaultOperationContext.create(TABLE_NAME, TableMetadata.primaryIndexName());
private static final TableSchema<FlattenedRecord> FLATTENED_TABLE_SCHEMA =
StaticTableSchema.builder(FlattenedRecord.class)
.newItemSupplier(FlattenedRecord::new)
.addAttribute(Instant.class, a -> a.name("generated")
.getter(FlattenedRecord::getGenerated)
.setter(FlattenedRecord::setGenerated)
.tags(autoGeneratedTimestampAttribute()))
.build();
private static final TableSchema<Record> TABLE_SCHEMA =
StaticTableSchema.builder(Record.class)
.newItemSupplier(Record::new)
.addAttribute(String.class, a -> a.name("id")
.getter(Record::getId)
.setter(Record::setId)
.tags(primaryPartitionKey()))
.addAttribute(String.class, a -> a.name("attribute")
.getter(Record::getAttribute)
.setter(Record::setAttribute))
.addAttribute(Instant.class, a -> a.name("lastUpdatedDate")
.getter(Record::getLastUpdatedDate)
.setter(Record::setLastUpdatedDate)
.tags(autoGeneratedTimestampAttribute()))
.addAttribute(Instant.class, a -> a.name("createdDate")
.getter(Record::getCreatedDate)
.setter(Record::setCreatedDate)
.tags(autoGeneratedTimestampAttribute(),
updateBehavior(UpdateBehavior.WRITE_IF_NOT_EXISTS)))
.addAttribute(Instant.class, a -> a.name("lastUpdatedDateInEpochMillis")
.getter(Record::getLastUpdatedDateInEpochMillis)
.setter(Record::setLastUpdatedDateInEpochMillis)
.attributeConverter(EpochMillisFormatTestConverter.create())
.tags(autoGeneratedTimestampAttribute()))
.addAttribute(Instant.class, a -> a.name("convertedLastUpdatedDate")
.getter(Record::getConvertedLastUpdatedDate)
.setter(Record::setConvertedLastUpdatedDate)
.attributeConverter(TimeFormatUpdateTestConverter.create())
.tags(autoGeneratedTimestampAttribute()))
.flatten(FLATTENED_TABLE_SCHEMA, Record::getFlattenedRecord, Record::setFlattenedRecord)
.build();
private final List<Map<String, AttributeValue>> fakeItems =
IntStream.range(0, 4)
.mapToObj($ -> createUniqueFakeItem())
.map(fakeItem -> TABLE_SCHEMA.itemToMap(fakeItem, true))
.collect(toList());
private final DynamoDbTable<Record> mappedTable;
private final Clock mockCLock = Mockito.mock(Clock.class);
private final DynamoDbEnhancedClient enhancedClient =
DynamoDbEnhancedClient.builder()
.dynamoDbClient(getDynamoDbClient())
.extensions(AutoGeneratedTimestampRecordExtension.builder().baseClock(mockCLock).build())
.build();
private final String concreteTableName;
@Rule
public ExpectedException thrown = ExpectedException.none();
{
concreteTableName = getConcreteTableName("table-name");
mappedTable = enhancedClient.table(concreteTableName, TABLE_SCHEMA);
}
public static Record createUniqueFakeItem() {
Record record = new Record();
record.setId(UUID.randomUUID().toString());
return record;
}
@Before
public void createTable() {
Mockito.when(mockCLock.instant()).thenReturn(MOCKED_INSTANT_NOW);
mappedTable.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput()));
}
@After
public void deleteTable() {
getDynamoDbClient().deleteTable(DeleteTableRequest.builder()
.tableName(getConcreteTableName("table-name"))
.build());
}
@Test
public void putNewRecordSetsInitialAutoGeneratedTimestamp() {
Record item = new Record().setId("id").setAttribute("one");
mappedTable.putItem(r -> r.item(item));
Record result = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id")));
GetItemResponse itemAsStoredInDDB = getItemAsStoredFromDDB();
FlattenedRecord flattenedRecord = new FlattenedRecord().setGenerated(MOCKED_INSTANT_NOW);
Record expectedRecord = new Record().setId("id")
.setAttribute("one")
.setLastUpdatedDate(MOCKED_INSTANT_NOW)
.setConvertedLastUpdatedDate(MOCKED_INSTANT_NOW)
.setCreatedDate(MOCKED_INSTANT_NOW)
.setLastUpdatedDateInEpochMillis(MOCKED_INSTANT_NOW)
.setFlattenedRecord(flattenedRecord);
assertThat(result, is(expectedRecord));
// The data in DDB is stored in converted time format
assertThat(itemAsStoredInDDB.item().get("convertedLastUpdatedDate").s(), is("13 01 2019 14:00:00"));
}
@Test
public void updateNewRecordSetsAutoFormattedDate() {
Record result = mappedTable.updateItem(r -> r.item(new Record().setId("id").setAttribute("one")));
GetItemResponse itemAsStoredInDDB = getItemAsStoredFromDDB();
FlattenedRecord flattenedRecord = new FlattenedRecord().setGenerated(MOCKED_INSTANT_NOW);
Record expectedRecord = new Record().setId("id")
.setAttribute("one")
.setLastUpdatedDate(MOCKED_INSTANT_NOW)
.setConvertedLastUpdatedDate(MOCKED_INSTANT_NOW)
.setCreatedDate(MOCKED_INSTANT_NOW)
.setLastUpdatedDateInEpochMillis(MOCKED_INSTANT_NOW)
.setFlattenedRecord(flattenedRecord);
assertThat(result, is(expectedRecord));
// The data in DDB is stored in converted time format
assertThat(itemAsStoredInDDB.item().get("convertedLastUpdatedDate").s(), is("13 01 2019 14:00:00"));
}
@Test
public void putExistingRecordUpdatedWithAutoFormattedTimestamps() {
mappedTable.putItem(r -> r.item(new Record().setId("id").setAttribute("one")));
Record result = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id")));
GetItemResponse itemAsStoredInDDB = getItemAsStoredFromDDB();
FlattenedRecord flattenedRecord = new FlattenedRecord().setGenerated(MOCKED_INSTANT_NOW);
Record expectedRecord = new Record().setId("id")
.setAttribute("one")
.setLastUpdatedDate(MOCKED_INSTANT_NOW)
.setConvertedLastUpdatedDate(MOCKED_INSTANT_NOW)
.setCreatedDate(MOCKED_INSTANT_NOW)
.setLastUpdatedDateInEpochMillis(MOCKED_INSTANT_NOW)
.setFlattenedRecord(flattenedRecord);
assertThat(result, is(expectedRecord));
// The data in DDB is stored in converted time format
assertThat(itemAsStoredInDDB.item().get("convertedLastUpdatedDate").s(), is("13 01 2019 14:00:00"));
Mockito.when(mockCLock.instant()).thenReturn(MOCKED_INSTANT_UPDATE_ONE);
mappedTable.putItem(r -> r.item(new Record().setId("id").setAttribute("one")));
result = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id")));
itemAsStoredInDDB = getItemAsStoredFromDDB();
flattenedRecord = new FlattenedRecord().setGenerated(MOCKED_INSTANT_UPDATE_ONE);
expectedRecord = new Record().setId("id")
.setAttribute("one")
.setLastUpdatedDate(MOCKED_INSTANT_UPDATE_ONE)
.setConvertedLastUpdatedDate(MOCKED_INSTANT_UPDATE_ONE)
// Note : Since we are doing PutItem second time, the createDate gets updated,
.setCreatedDate(MOCKED_INSTANT_UPDATE_ONE)
.setLastUpdatedDateInEpochMillis(MOCKED_INSTANT_UPDATE_ONE)
.setFlattenedRecord(flattenedRecord);
System.out.println("result "+result);
assertThat(result, is(expectedRecord));
// The data in DDB is stored in converted time format
assertThat(itemAsStoredInDDB.item().get("convertedLastUpdatedDate").s(), is("14 01 2019 14:00:00"));
}
@Test
public void putItemFollowedByUpdates() {
mappedTable.putItem(r -> r.item(new Record().setId("id").setAttribute("one")));
Record result = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id")));
GetItemResponse itemAsStoredInDDB = getItemAsStoredFromDDB();
FlattenedRecord flattenedRecord = new FlattenedRecord().setGenerated(MOCKED_INSTANT_NOW);
Record expectedRecord = new Record().setId("id")
.setAttribute("one")
.setLastUpdatedDate(MOCKED_INSTANT_NOW)
.setConvertedLastUpdatedDate(MOCKED_INSTANT_NOW)
.setCreatedDate(MOCKED_INSTANT_NOW)
.setLastUpdatedDateInEpochMillis(MOCKED_INSTANT_NOW)
.setFlattenedRecord(flattenedRecord);
assertThat(result, is(expectedRecord));
// The data in DDB is stored in converted time format
assertThat(itemAsStoredInDDB.item().get("convertedLastUpdatedDate").s(), is("13 01 2019 14:00:00"));
//First Update
Mockito.when(mockCLock.instant()).thenReturn(MOCKED_INSTANT_UPDATE_ONE);
result = mappedTable.updateItem(r -> r.item(new Record().setId("id").setAttribute("one")));
itemAsStoredInDDB = getItemAsStoredFromDDB();
flattenedRecord = new FlattenedRecord().setGenerated(MOCKED_INSTANT_UPDATE_ONE);
expectedRecord = new Record().setId("id")
.setAttribute("one")
.setLastUpdatedDate(MOCKED_INSTANT_UPDATE_ONE)
.setConvertedLastUpdatedDate(MOCKED_INSTANT_UPDATE_ONE)
.setCreatedDate(MOCKED_INSTANT_NOW)
.setLastUpdatedDateInEpochMillis(MOCKED_INSTANT_UPDATE_ONE)
.setFlattenedRecord(flattenedRecord);
assertThat(result, is(expectedRecord));
// The data in DDB is stored in converted time format
assertThat(itemAsStoredInDDB.item().get("convertedLastUpdatedDate").s(), is("14 01 2019 14:00:00"));
//Second Update
Mockito.when(mockCLock.instant()).thenReturn(MOCKED_INSTANT_UPDATE_TWO);
result = mappedTable.updateItem(r -> r.item(new Record().setId("id").setAttribute("one")));
itemAsStoredInDDB = getItemAsStoredFromDDB();
flattenedRecord = new FlattenedRecord().setGenerated(MOCKED_INSTANT_UPDATE_TWO);
expectedRecord = new Record().setId("id")
.setAttribute("one")
.setLastUpdatedDate(MOCKED_INSTANT_UPDATE_TWO)
.setConvertedLastUpdatedDate(MOCKED_INSTANT_UPDATE_TWO)
.setCreatedDate(MOCKED_INSTANT_NOW)
.setLastUpdatedDateInEpochMillis(MOCKED_INSTANT_UPDATE_TWO)
.setFlattenedRecord(flattenedRecord);
assertThat(result, is(expectedRecord));
// The data in DDB is stored in converted time format
assertThat(itemAsStoredInDDB.item().get("convertedLastUpdatedDate").s(), is("15 01 2019 14:00:00"));
System.out.println(Instant.ofEpochMilli(Long.parseLong(itemAsStoredInDDB.item().get("lastUpdatedDateInEpochMillis").n())));
assertThat(Long.parseLong(itemAsStoredInDDB.item().get("lastUpdatedDateInEpochMillis").n()),
is(MOCKED_INSTANT_UPDATE_TWO.toEpochMilli()));
}
@Test
public void putExistingRecordWithConditionExpressions() {
mappedTable.putItem(r -> r.item(new Record().setId("id").setAttribute("one")));
Record result = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id")));
GetItemResponse itemAsStoredInDDB = getItemAsStoredFromDDB();
FlattenedRecord flattenedRecord = new FlattenedRecord().setGenerated(MOCKED_INSTANT_NOW);
Record expectedRecord = new Record().setId("id")
.setAttribute("one")
.setLastUpdatedDate(MOCKED_INSTANT_NOW)
.setConvertedLastUpdatedDate(MOCKED_INSTANT_NOW)
.setCreatedDate(MOCKED_INSTANT_NOW)
.setLastUpdatedDateInEpochMillis(MOCKED_INSTANT_NOW)
.setFlattenedRecord(flattenedRecord);
assertThat(result, is(expectedRecord));
// The data in DDB is stored in converted time format
assertThat(itemAsStoredInDDB.item().get("convertedLastUpdatedDate").s(), is("13 01 2019 14:00:00"));
Expression conditionExpression = Expression.builder()
.expression("#k = :v OR #k = :v1")
.putExpressionName("#k", "attribute")
.putExpressionValue(":v", stringValue("one"))
.putExpressionValue(":v1", stringValue("wrong2"))
.build();
Mockito.when(mockCLock.instant()).thenReturn(MOCKED_INSTANT_UPDATE_ONE);
mappedTable.putItem(PutItemEnhancedRequest.builder(Record.class)
.item(new Record().setId("id").setAttribute("one"))
.conditionExpression(conditionExpression)
.build());
result = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id")));
flattenedRecord = new FlattenedRecord().setGenerated(MOCKED_INSTANT_UPDATE_ONE);
expectedRecord = new Record().setId("id")
.setAttribute("one")
.setLastUpdatedDate(MOCKED_INSTANT_UPDATE_ONE)
.setConvertedLastUpdatedDate(MOCKED_INSTANT_UPDATE_ONE)
// Note that this is a second putItem call so create date is updated.
.setCreatedDate(MOCKED_INSTANT_UPDATE_ONE)
.setLastUpdatedDateInEpochMillis(MOCKED_INSTANT_UPDATE_ONE)
.setFlattenedRecord(flattenedRecord);
assertThat(result, is(expectedRecord));
}
@Test
public void updateExistingRecordWithConditionExpressions() {
mappedTable.updateItem(r -> r.item(new Record().setId("id").setAttribute("one")));
GetItemResponse itemAsStoredInDDB = getItemAsStoredFromDDB();
// The data in DDB is stored in converted time format
assertThat(itemAsStoredInDDB.item().get("convertedLastUpdatedDate").s(), is("13 01 2019 14:00:00"));
Expression conditionExpression = Expression.builder()
.expression("#k = :v OR #k = :v1")
.putExpressionName("#k", "attribute")
.putExpressionValue(":v", stringValue("one"))
.putExpressionValue(":v1", stringValue("wrong2"))
.build();
Mockito.when(mockCLock.instant()).thenReturn(MOCKED_INSTANT_UPDATE_ONE);
mappedTable.updateItem(r -> r.item(new Record().setId("id").setAttribute("one"))
.conditionExpression(conditionExpression));
Record result = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id")));
FlattenedRecord flattenedRecord = new FlattenedRecord().setGenerated(MOCKED_INSTANT_UPDATE_ONE);
Record expectedRecord = new Record().setId("id")
.setAttribute("one")
.setLastUpdatedDate(MOCKED_INSTANT_UPDATE_ONE)
.setConvertedLastUpdatedDate(MOCKED_INSTANT_UPDATE_ONE)
.setCreatedDate(MOCKED_INSTANT_NOW)
.setLastUpdatedDateInEpochMillis(MOCKED_INSTANT_UPDATE_ONE)
.setFlattenedRecord(flattenedRecord);
assertThat(result, is(expectedRecord));
}
@Test
public void putItemConditionTestFailure() {
mappedTable.putItem(r -> r.item(new Record().setId("id").setAttribute("one")));
Expression conditionExpression = Expression.builder()
.expression("#k = :v OR #k = :v1")
.putExpressionName("#k", "attribute")
.putExpressionValue(":v", stringValue("wrong1"))
.putExpressionValue(":v1", stringValue("wrong2"))
.build();
thrown.expect(ConditionalCheckFailedException.class);
mappedTable.putItem(PutItemEnhancedRequest.builder(Record.class)
.item(new Record().setId("id").setAttribute("one"))
.conditionExpression(conditionExpression)
.build());
}
@Test
public void updateItemConditionTestFailure() {
mappedTable.updateItem(r -> r.item(new Record().setId("id").setAttribute("one")));
Expression conditionExpression = Expression.builder()
.expression("#k = :v OR #k = :v1")
.putExpressionName("#k", "attribute")
.putExpressionValue(":v", stringValue("wrong1"))
.putExpressionValue(":v1", stringValue("wrong2"))
.build();
thrown.expect(ConditionalCheckFailedException.class);
mappedTable.putItem(PutItemEnhancedRequest.builder(Record.class)
.item(new Record().setId("id").setAttribute("one"))
.conditionExpression(conditionExpression)
.build());
}
@Test
public void incorrectTypeForAutoUpdateTimestampThrowsException(){
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("Attribute 'lastUpdatedDate' of Class type class java.lang.String is not a suitable "
+ "Java Class type to be used as a Auto Generated Timestamp attribute. Only java.time."
+ "Instant Class type is supported.");
StaticTableSchema.builder(RecordWithStringUpdateDate.class)
.newItemSupplier(RecordWithStringUpdateDate::new)
.addAttribute(String.class, a -> a.name("id")
.getter(RecordWithStringUpdateDate::getId)
.setter(RecordWithStringUpdateDate::setId)
.tags(primaryPartitionKey()))
.addAttribute(String.class, a -> a.name("lastUpdatedDate")
.getter(RecordWithStringUpdateDate::getLastUpdatedDate)
.setter(RecordWithStringUpdateDate::setLastUpdatedDate)
.tags(autoGeneratedTimestampAttribute()))
.build();
}
private DefaultDynamoDbExtensionContext getExtensionContext() {
return DefaultDynamoDbExtensionContext.builder()
.tableMetadata(TABLE_SCHEMA.tableMetadata())
.operationContext(PRIMARY_CONTEXT)
.tableSchema(TABLE_SCHEMA)
.items(fakeItems.get(0)).build();
}
private GetItemResponse getItemAsStoredFromDDB() {
Map<String, AttributeValue> key = new HashMap<>();
key.put("id", AttributeValue.builder().s("id").build());
return getDynamoDbClient().getItem(GetItemRequest
.builder().tableName(concreteTableName)
.key(key)
.consistentRead(true).build());
}
private static class Record {
private String id;
private String attribute;
private Instant createdDate;
private Instant lastUpdatedDate;
private Instant convertedLastUpdatedDate;
private Instant lastUpdatedDateInEpochMillis;
private FlattenedRecord flattenedRecord;
private String getId() {
return id;
}
private Record setId(String id) {
this.id = id;
return this;
}
private String getAttribute() {
return attribute;
}
private Record setAttribute(String attribute) {
this.attribute = attribute;
return this;
}
private Instant getLastUpdatedDate() {
return lastUpdatedDate;
}
private Record setLastUpdatedDate(Instant lastUpdatedDate) {
this.lastUpdatedDate = lastUpdatedDate;
return this;
}
private Instant getCreatedDate() {
return createdDate;
}
private Record setCreatedDate(Instant createdDate) {
this.createdDate = createdDate;
return this;
}
private Instant getConvertedLastUpdatedDate() {
return convertedLastUpdatedDate;
}
private Record setConvertedLastUpdatedDate(Instant convertedLastUpdatedDate) {
this.convertedLastUpdatedDate = convertedLastUpdatedDate;
return this;
}
private Instant getLastUpdatedDateInEpochMillis() {
return lastUpdatedDateInEpochMillis;
}
private Record setLastUpdatedDateInEpochMillis(Instant lastUpdatedDateInEpochMillis) {
this.lastUpdatedDateInEpochMillis = lastUpdatedDateInEpochMillis;
return this;
}
public FlattenedRecord getFlattenedRecord() {
return flattenedRecord;
}
public Record setFlattenedRecord(FlattenedRecord flattenedRecord) {
this.flattenedRecord = flattenedRecord;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Record record = (Record) o;
return Objects.equals(id, record.id) &&
Objects.equals(attribute, record.attribute) &&
Objects.equals(lastUpdatedDate, record.lastUpdatedDate) &&
Objects.equals(createdDate, record.createdDate) &&
Objects.equals(lastUpdatedDateInEpochMillis, record.lastUpdatedDateInEpochMillis) &&
Objects.equals(convertedLastUpdatedDate, record.convertedLastUpdatedDate) &&
Objects.equals(flattenedRecord, record.flattenedRecord);
}
@Override
public int hashCode() {
return Objects.hash(id, attribute, lastUpdatedDate, createdDate, lastUpdatedDateInEpochMillis,
convertedLastUpdatedDate, flattenedRecord);
}
@Override
public String toString() {
return "Record{" +
"id='" + id + '\'' +
", attribute='" + attribute + '\'' +
", createdDate=" + createdDate +
", lastUpdatedDate=" + lastUpdatedDate +
", convertedLastUpdatedDate=" + convertedLastUpdatedDate +
", lastUpdatedDateInEpochMillis=" + lastUpdatedDateInEpochMillis +
", flattenedRecord=" + flattenedRecord +
'}';
}
}
private static class FlattenedRecord {
private Instant generated;
public Instant getGenerated() {
return generated;
}
public FlattenedRecord setGenerated(Instant generated) {
this.generated = generated;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
FlattenedRecord that = (FlattenedRecord) o;
return Objects.equals(generated, that.generated);
}
@Override
public int hashCode() {
return Objects.hash(generated);
}
@Override
public String toString() {
return "FlattenedRecord{" +
"generated=" + generated +
'}';
}
}
private static class RecordWithStringUpdateDate {
private String id;
private String lastUpdatedDate;
private String getId() {
return id;
}
private RecordWithStringUpdateDate setId(String id) {
this.id = id;
return this;
}
private String getLastUpdatedDate() {
return lastUpdatedDate;
}
private RecordWithStringUpdateDate setLastUpdatedDate(String lastUpdatedDate) {
this.lastUpdatedDate = lastUpdatedDate;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
RecordWithStringUpdateDate record = (RecordWithStringUpdateDate) o;
return Objects.equals(id, record.id) &&
Objects.equals(lastUpdatedDate, record.lastUpdatedDate);
}
@Override
public int hashCode() {
return Objects.hash(id, lastUpdatedDate);
}
@Override
public String toString() {
return "RecordWithStringUpdateDate{" +
"id='" + id + '\'' +
", lastUpdatedDate=" + lastUpdatedDate +
'}';
}
}
}
| 3,858 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/AsyncBasicScanTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.functionaltests;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.numberValue;
import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.stringValue;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primarySortKey;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import software.amazon.awssdk.core.async.SdkPublisher;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbAsyncTable;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedAsyncClient;
import software.amazon.awssdk.enhanced.dynamodb.Expression;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.internal.client.DefaultDynamoDbEnhancedAsyncClient;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema;
import software.amazon.awssdk.enhanced.dynamodb.model.Page;
import software.amazon.awssdk.enhanced.dynamodb.model.ScanEnhancedRequest;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest;
public class AsyncBasicScanTest extends LocalDynamoDbAsyncTestBase {
private static class Record {
private String id;
private Integer sort;
private String getId() {
return id;
}
private Record setId(String id) {
this.id = id;
return this;
}
private Integer getSort() {
return sort;
}
private Record setSort(Integer sort) {
this.sort = sort;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Record record = (Record) o;
return Objects.equals(id, record.id) &&
Objects.equals(sort, record.sort);
}
@Override
public int hashCode() {
return Objects.hash(id, sort);
}
}
private static final TableSchema<Record> TABLE_SCHEMA =
StaticTableSchema.builder(Record.class)
.newItemSupplier(Record::new)
.addAttribute(String.class, a -> a.name("id")
.getter(Record::getId)
.setter(Record::setId)
.tags(primaryPartitionKey()))
.addAttribute(Integer.class, a -> a.name("sort")
.getter(Record::getSort)
.setter(Record::setSort)
.tags(primarySortKey()))
.build();
private static final List<Record> RECORDS =
IntStream.range(0, 10)
.mapToObj(i -> new Record().setId("id-value").setSort(i))
.collect(Collectors.toList());
private DynamoDbEnhancedAsyncClient enhancedAsyncClient =
DefaultDynamoDbEnhancedAsyncClient.builder()
.dynamoDbClient(getDynamoDbAsyncClient())
.build();
private DynamoDbAsyncTable<Record> mappedTable = enhancedAsyncClient.table(getConcreteTableName("table-name"), TABLE_SCHEMA);
private void insertRecords() {
RECORDS.forEach(record -> mappedTable.putItem(r -> r.item(record)).join());
}
@Before
public void createTable() {
mappedTable.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput())).join();
}
@After
public void deleteTable() {
getDynamoDbAsyncClient().deleteTable(DeleteTableRequest.builder()
.tableName(getConcreteTableName("table-name"))
.build()).join();
}
@Test
public void scanAllRecordsDefaultSettings() {
insertRecords();
SdkPublisher<Page<Record>> publisher = mappedTable.scan(ScanEnhancedRequest.builder().build());
List<Page<Record>> results = drainPublisher(publisher, 1);
Page<Record> page = results.get(0);
assertThat(page.items(), is(RECORDS));
assertThat(page.lastEvaluatedKey(), is(nullValue()));
}
@Test
public void scanAllRecordsDefaultSettings_viaItems() {
insertRecords();
SdkPublisher<Record> publisher = mappedTable.scan(ScanEnhancedRequest.builder().build()).items();
List<Record> results = drainPublisher(publisher, 10);
assertThat(results, is(RECORDS));
}
@Test
public void scanAllRecordsWithFilter() {
insertRecords();
Map<String, AttributeValue> expressionValues = new HashMap<>();
expressionValues.put(":min_value", numberValue(3));
expressionValues.put(":max_value", numberValue(5));
Expression expression = Expression.builder()
.expression("sort >= :min_value AND sort <= :max_value")
.expressionValues(expressionValues)
.build();
SdkPublisher<Page<Record>> publisher =
mappedTable.scan(ScanEnhancedRequest.builder().filterExpression(expression).build());
List<Page<Record>> results = drainPublisher(publisher, 1);
Page<Record> page = results.get(0);
assertThat(page.items(),
is(RECORDS.stream().filter(r -> r.sort >= 3 && r.sort <= 5).collect(Collectors.toList())));
assertThat(page.lastEvaluatedKey(), is(nullValue()));
}
@Test
public void scanAllRecordsWithFilter_viaItems() {
insertRecords();
Map<String, AttributeValue> expressionValues = new HashMap<>();
expressionValues.put(":min_value", numberValue(3));
expressionValues.put(":max_value", numberValue(5));
Expression expression = Expression.builder()
.expression("sort >= :min_value AND sort <= :max_value")
.expressionValues(expressionValues)
.build();
SdkPublisher<Record> publisher =
mappedTable.scan(ScanEnhancedRequest.builder().filterExpression(expression).build()).items();
List<Record> results = drainPublisher(publisher, 3);
assertThat(results,
is(RECORDS.stream().filter(r -> r.sort >= 3 && r.sort <= 5).collect(Collectors.toList())));
}
@Test
public void scanLimit() {
insertRecords();
SdkPublisher<Page<Record>> publisher = mappedTable.scan(r -> r.limit(5));
publisher.subscribe(page -> page.items().forEach(item -> System.out.println(item)));
List<Page<Record>> results = drainPublisher(publisher, 3);
Page<Record> page1 = results.get(0);
Page<Record> page2 = results.get(1);
Page<Record> page3 = results.get(2);
assertThat(page1.items(), is(RECORDS.subList(0, 5)));
assertThat(page1.lastEvaluatedKey(), is(getKeyMap(4)));
assertThat(page2.items(), is(RECORDS.subList(5, 10)));
assertThat(page2.lastEvaluatedKey(), is(getKeyMap(9)));
assertThat(page3.items(), is(empty()));
assertThat(page3.lastEvaluatedKey(), is(nullValue()));
}
@Test
public void scanLimit_viaItems() {
insertRecords();
SdkPublisher<Record> publisher = mappedTable.scan(r -> r.limit(5)).items();
List<Record> results = drainPublisher(publisher, 10);
assertThat(results, is(RECORDS));
}
@Test
public void scanEmpty() {
SdkPublisher<Page<Record>> publisher = mappedTable.scan();
List<Page<Record>> results = drainPublisher(publisher, 1);
Page<Record> page = results.get(0);
assertThat(page.items(), is(empty()));
assertThat(page.lastEvaluatedKey(), is(nullValue()));
}
@Test
public void scanEmpty_viaItems() {
SdkPublisher<Record> publisher = mappedTable.scan().items();
List<Record> results = drainPublisher(publisher, 0);
assertThat(results, is(empty()));
}
@Test
public void scanExclusiveStartKey() {
insertRecords();
SdkPublisher<Page<Record>> publisher =
mappedTable.scan(ScanEnhancedRequest.builder().exclusiveStartKey(getKeyMap(7)).build());
List<Page<Record>> results = drainPublisher(publisher, 1);
Page<Record> page = results.get(0);
assertThat(page.items(), is(RECORDS.subList(8, 10)));
assertThat(page.lastEvaluatedKey(), is(nullValue()));
}
@Test
public void scanExclusiveStartKey_viaItems() {
insertRecords();
SdkPublisher<Record> publisher =
mappedTable.scan(ScanEnhancedRequest.builder().exclusiveStartKey(getKeyMap(7)).build()).items();
List<Record> results = drainPublisher(publisher, 2);
assertThat(results, is(RECORDS.subList(8, 10)));
}
private Map<String, AttributeValue> getKeyMap(int sort) {
Map<String, AttributeValue> result = new HashMap<>();
result.put("id", stringValue("id-value"));
result.put("sort", numberValue(sort));
return Collections.unmodifiableMap(result);
}
}
| 3,859 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/BeanTableSchemaRecursiveTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.functionaltests;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Collections;
import java.util.Map;
import org.junit.Test;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.RecursiveRecordBean;
import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.RecursiveRecordImmutable;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
public class BeanTableSchemaRecursiveTest {
@Test
public void recursiveRecord_document() {
TableSchema<RecursiveRecordBean> tableSchema = TableSchema.fromClass(RecursiveRecordBean.class);
RecursiveRecordImmutable recursiveRecordImmutable2 = RecursiveRecordImmutable.builder()
.setAttribute(4)
.build();
RecursiveRecordImmutable recursiveRecordImmutable1 =
RecursiveRecordImmutable.builder()
.setAttribute(3)
.setRecursiveRecordImmutable(recursiveRecordImmutable2)
.build();
RecursiveRecordBean recursiveRecordBean2 = new RecursiveRecordBean();
recursiveRecordBean2.setAttribute(2);
recursiveRecordBean2.setRecursiveRecordImmutable(recursiveRecordImmutable1);
RecursiveRecordBean recursiveRecordBean1 = new RecursiveRecordBean();
recursiveRecordBean1.setAttribute(1);
recursiveRecordBean1.setRecursiveRecordBean(recursiveRecordBean2);
Map<String, AttributeValue> itemMap = tableSchema.itemToMap(recursiveRecordBean1, true);
assertThat(itemMap).hasSize(2);
assertThat(itemMap).containsEntry("attribute", AttributeValue.builder().n("1").build());
assertThat(itemMap).hasEntrySatisfying("recursiveRecordBean", av -> {
assertThat(av.hasM()).isTrue();
assertThat(av.m()).containsEntry("attribute", AttributeValue.builder().n("2").build());
assertThat(av.m()).hasEntrySatisfying("recursiveRecordImmutable", iav -> {
assertThat(iav.hasM()).isTrue();
assertThat(iav.m()).containsEntry("attribute", AttributeValue.builder().n("3").build());
assertThat(iav.m()).hasEntrySatisfying("recursiveRecordImmutable", iav2 -> {
assertThat(iav2.hasM()).isTrue();
assertThat(iav2.m()).containsEntry("attribute", AttributeValue.builder().n("4").build());
});
});
});
}
@Test
public void recursiveRecord_list() {
TableSchema<RecursiveRecordBean> tableSchema = TableSchema.fromClass(RecursiveRecordBean.class);
RecursiveRecordBean recursiveRecordBean2 = new RecursiveRecordBean();
recursiveRecordBean2.setAttribute(2);
RecursiveRecordBean recursiveRecordBean1 = new RecursiveRecordBean();
recursiveRecordBean1.setAttribute(1);
recursiveRecordBean1.setRecursiveRecordList(Collections.singletonList(recursiveRecordBean2));
Map<String, AttributeValue> itemMap = tableSchema.itemToMap(recursiveRecordBean1, true);
assertThat(itemMap).hasSize(2);
assertThat(itemMap).containsEntry("attribute", AttributeValue.builder().n("1").build());
assertThat(itemMap).hasEntrySatisfying("recursiveRecordList", av -> {
assertThat(av.hasL()).isTrue();
assertThat(av.l()).hasOnlyOneElementSatisfying(listAv -> {
assertThat(listAv.hasM()).isTrue();
assertThat(listAv.m()).containsEntry("attribute", AttributeValue.builder().n("2").build());
});
});
}
}
| 3,860 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/VersionedRecordWithSpecialCharactersTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.functionaltests;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static software.amazon.awssdk.enhanced.dynamodb.extensions.VersionedRecordExtension.AttributeTags.versionAttribute;
import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.stringValue;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey;
import java.util.Objects;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable;
import software.amazon.awssdk.enhanced.dynamodb.Expression;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.extensions.VersionedRecordExtension;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema;
import software.amazon.awssdk.enhanced.dynamodb.model.PutItemEnhancedRequest;
import software.amazon.awssdk.enhanced.dynamodb.model.UpdateItemEnhancedRequest;
import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException;
import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest;
public class VersionedRecordWithSpecialCharactersTest extends LocalDynamoDbSyncTestBase {
private static class Record {
private String id;
private String _attribute;
private Integer _version;
private String getId() {
return id;
}
private Record setId(String id) {
this.id = id;
return this;
}
private String get_attribute() {
return _attribute;
}
private Record set_attribute(String _attribute) {
this._attribute = _attribute;
return this;
}
private Integer get_version() {
return _version;
}
private Record set_version(Integer _version) {
this._version = _version;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Record record = (Record) o;
return Objects.equals(id, record.id) &&
Objects.equals(_attribute, record._attribute) &&
Objects.equals(_version, record._version);
}
@Override
public int hashCode() {
return Objects.hash(id, _attribute, _version);
}
}
private static final TableSchema<Record> TABLE_SCHEMA =
StaticTableSchema.builder(Record.class)
.newItemSupplier(Record::new)
.addAttribute(String.class, a -> a.name("id")
.getter(Record::getId)
.setter(Record::setId)
.tags(primaryPartitionKey()))
.addAttribute(String.class, a -> a.name("_attribute")
.getter(Record::get_attribute)
.setter(Record::set_attribute))
.addAttribute(Integer.class, a -> a.name("_version")
.getter(Record::get_version)
.setter(Record::set_version)
.tags(versionAttribute()))
.build();
private DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder()
.dynamoDbClient(getDynamoDbClient())
.extensions(VersionedRecordExtension.builder().build())
.build();
private DynamoDbTable<Record> mappedTable = enhancedClient.table(getConcreteTableName("table-name"), TABLE_SCHEMA);
@Rule
public ExpectedException exception = ExpectedException.none();
@Before
public void createTable() {
mappedTable.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput()));
}
@After
public void deleteTable() {
getDynamoDbClient().deleteTable(DeleteTableRequest.builder()
.tableName(getConcreteTableName("table-name"))
.build());
}
@Test
public void putNewRecordSetsInitialVersion() {
mappedTable.putItem(r -> r.item(new Record().setId("id").set_attribute("one")));
Record result = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id")));
Record expectedResult = new Record().setId("id").set_attribute("one").set_version(1);
assertThat(result, is(expectedResult));
}
@Test
public void updateNewRecordSetsInitialVersion() {
Record result = mappedTable.updateItem(r -> r.item(new Record().setId("id").set_attribute("one")));
Record expectedResult = new Record().setId("id").set_attribute("one").set_version(1);
assertThat(result, is(expectedResult));
}
@Test
public void putExistingRecordVersionMatches() {
mappedTable.putItem(r -> r.item(new Record().setId("id").set_attribute("one")));
mappedTable.putItem(r -> r.item(new Record().setId("id").set_attribute("one").set_version(1)));
Record result = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id")));
Record expectedResult = new Record().setId("id").set_attribute("one").set_version(2);
assertThat(result, is(expectedResult));
}
@Test
public void putExistingRecordVersionMatchesConditionExpressionMatches() {
mappedTable.putItem(r -> r.item(new Record().setId("id").set_attribute("one")));
Expression conditionExpression = Expression.builder()
.expression("#k = :v OR #k = :v1")
.putExpressionName("#k", "_attribute")
.putExpressionValue(":v", stringValue("wrong"))
.putExpressionValue(":v1", stringValue("one"))
.build();
mappedTable.putItem(PutItemEnhancedRequest.builder(Record.class)
.item(new Record().setId("id").set_attribute("one").set_version(1))
.conditionExpression(conditionExpression)
.build());
Record result = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id")));
Record expectedResult = new Record().setId("id").set_attribute("one").set_version(2);
assertThat(result, is(expectedResult));
}
@Test
public void putExistingRecordVersionDoesNotMatchConditionExpressionMatches() {
mappedTable.putItem(r -> r.item(new Record().setId("id").set_attribute("one")));
Expression conditionExpression = Expression.builder()
.expression("#k = :v OR #k = :v1")
.putExpressionName("#k", "_attribute")
.putExpressionValue(":v", stringValue("wrong"))
.putExpressionValue(":v1", stringValue("one"))
.build();
exception.expect(ConditionalCheckFailedException.class);
mappedTable.putItem(PutItemEnhancedRequest.builder(Record.class)
.item(new Record().setId("id").set_attribute("one").set_version(2))
.conditionExpression(conditionExpression)
.build());
}
@Test
public void putExistingRecordVersionMatchesConditionExpressionDoesNotMatch() {
mappedTable.putItem(r -> r.item(new Record().setId("id").set_attribute("one")));
Expression conditionExpression = Expression.builder()
.expression("#k = :v OR #k = :v1")
.putExpressionName("#k", "attribute")
.putExpressionValue(":v", stringValue("wrong"))
.putExpressionValue(":v1", stringValue("wrong2"))
.build();
exception.expect(ConditionalCheckFailedException.class);
mappedTable.putItem(PutItemEnhancedRequest.builder(Record.class)
.item(new Record().setId("id").set_attribute("one").set_version(1))
.conditionExpression(conditionExpression)
.build());
}
@Test
public void updateExistingRecordVersionMatchesConditionExpressionMatches() {
mappedTable.putItem(r -> r.item(new Record().setId("id").set_attribute("one")));
Expression conditionExpression = Expression.builder()
.expression("#k = :v OR #k = :v1")
.putExpressionName("#k", "_attribute")
.putExpressionValue(":v", stringValue("wrong"))
.putExpressionValue(":v1", stringValue("one"))
.build();
mappedTable.updateItem(UpdateItemEnhancedRequest.builder(Record.class)
.item(new Record().setId("id").set_attribute("one").set_version(1))
.conditionExpression(conditionExpression)
.build());
Record result = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id")));
Record expectedResult = new Record().setId("id").set_attribute("one").set_version(2);
assertThat(result, is(expectedResult));
}
@Test
public void updateExistingRecordVersionDoesNotMatchConditionExpressionMatches() {
mappedTable.putItem(r -> r.item(new Record().setId("id").set_attribute("one")));
Expression conditionExpression = Expression.builder()
.expression("#k = :v OR #k = :v1")
.putExpressionName("#k", "_attribute")
.putExpressionValue(":v", stringValue("wrong"))
.putExpressionValue(":v1", stringValue("one"))
.build();
exception.expect(ConditionalCheckFailedException.class);
mappedTable.updateItem(UpdateItemEnhancedRequest.builder(Record.class)
.item(new Record().setId("id").set_attribute("one").set_version(2))
.conditionExpression(conditionExpression)
.build());
}
@Test
public void updateExistingRecordVersionMatchesConditionExpressionDoesNotMatch() {
mappedTable.putItem(r -> r.item(new Record().setId("id").set_attribute("one")));
Expression conditionExpression = Expression.builder()
.expression("#k = :v OR #k = :v1")
.putExpressionName("#k", "attribute")
.putExpressionValue(":v", stringValue("wrong"))
.putExpressionValue(":v1", stringValue("wrong2"))
.build();
exception.expect(ConditionalCheckFailedException.class);
mappedTable.updateItem(UpdateItemEnhancedRequest.builder(Record.class)
.item(new Record().setId("id").set_attribute("one").set_version(1))
.conditionExpression(conditionExpression)
.build());
}
@Test
public void updateExistingRecordVersionMatches() {
mappedTable.putItem(r -> r.item(new Record().setId("id").set_attribute("one")));
Record result =
mappedTable.updateItem(r -> r.item(new Record().setId("id").set_attribute("one").set_version(1)));
Record expectedResult = new Record().setId("id").set_attribute("one").set_version(2);
assertThat(result, is(expectedResult));
}
@Test(expected = ConditionalCheckFailedException.class)
public void putRecordWithWrongVersionNumber() {
mappedTable.putItem(r -> r.item(new Record().setId("id").set_attribute("one")));
mappedTable.putItem(r -> r.item(new Record().setId("id").set_attribute("one").set_version(2)));
}
}
| 3,861 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/PutItemWithResponseTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.functionaltests;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey;
import java.util.Objects;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
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.DynamoDbTable;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema;
import software.amazon.awssdk.enhanced.dynamodb.model.PutItemEnhancedResponse;
import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest;
import software.amazon.awssdk.services.dynamodb.model.ReturnConsumedCapacity;
import software.amazon.awssdk.services.dynamodb.model.ReturnValue;
public class PutItemWithResponseTest extends LocalDynamoDbSyncTestBase {
private static class Record {
private Integer id;
private String stringAttr1;
private Integer getId() {
return id;
}
private Record setId(Integer id) {
this.id = id;
return this;
}
private String getStringAttr1() {
return stringAttr1;
}
private Record setStringAttr1(String stringAttr1) {
this.stringAttr1 = stringAttr1;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Record record = (Record) o;
return Objects.equals(id, record.id) && Objects.equals(stringAttr1, record.stringAttr1);
}
@Override
public int hashCode() {
return Objects.hash(id, stringAttr1);
}
}
private static final TableSchema<Record> TABLE_SCHEMA =
StaticTableSchema.builder(Record.class)
.newItemSupplier(Record::new)
.addAttribute(Integer.class, a -> a.name("id_1")
.getter(Record::getId)
.setter(Record::setId)
.tags(primaryPartitionKey()))
.addAttribute(String.class, a -> a.name("stringAttr1")
.getter(Record::getStringAttr1)
.setter(Record::setStringAttr1))
.build();
private DynamoDbEnhancedClient enhancedClient;
private DynamoDbEnhancedClientExtension extension;
private DynamoDbTable<Record> mappedTable1;
@Before
public void createTable() {
extension = Mockito.spy(new NoOpExtension());
enhancedClient = DynamoDbEnhancedClient.builder()
.dynamoDbClient(getDynamoDbClient())
.extensions(extension)
.build();
mappedTable1 = enhancedClient.table(getConcreteTableName("table-name-1"), TABLE_SCHEMA);
mappedTable1.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput()));
}
@After
public void deleteTable() {
getDynamoDbClient().deleteTable(DeleteTableRequest.builder()
.tableName(getConcreteTableName("table-name-1"))
.build());
}
@Test
public void returnValues_unset_attributesNull() {
Record record = new Record().setId(1).setStringAttr1("a");
mappedTable1.putItem(record);
record.setStringAttr1("b");
PutItemEnhancedResponse<Record> response = mappedTable1.putItemWithResponse(r -> r.item(record));
assertThat(response.attributes()).isNull();
}
@Test
public void returnValues_allOld_attributesMapped() {
Record original = new Record().setId(1).setStringAttr1("a");
mappedTable1.putItem(original);
Record update = new Record().setId(1).setStringAttr1("b");
PutItemEnhancedResponse<Record> response = mappedTable1.putItemWithResponse(r -> r.returnValues(ReturnValue.ALL_OLD)
.item(update));
Record returned = response.attributes();
assertThat(returned).isEqualTo(original);
}
@Test
public void returnValues_allOld_extensionInvokedOnReturnedValues() {
Record original = new Record().setId(1).setStringAttr1("a");
mappedTable1.putItem(original);
Record update = new Record().setId(1).setStringAttr1("b");
mappedTable1.putItemWithResponse(r -> r.returnValues(ReturnValue.ALL_OLD)
.item(update));
Mockito.verify(extension).afterRead(any(DynamoDbExtensionContext.AfterRead.class));
Mockito.verify(extension, Mockito.times(2)).beforeWrite(any(DynamoDbExtensionContext.BeforeWrite.class));
}
@Test
public void returnConsumedCapacity_unset_consumedCapacityNull() {
Record record = new Record().setId(1).setStringAttr1("a");
PutItemEnhancedResponse<Record> response = mappedTable1.putItemWithResponse(r -> r.item(record));
assertThat(response.consumedCapacity()).isNull();
}
@Test
public void returnConsumedCapacity_set_consumedCapacityNotNull() {
Record record = new Record().setId(1).setStringAttr1("a");
PutItemEnhancedResponse<Record> response = mappedTable1.putItemWithResponse(r -> r.item(record)
.returnConsumedCapacity(ReturnConsumedCapacity.TOTAL));
assertThat(response.consumedCapacity()).isNotNull();
}
// Note: DynamoDB Local does not support returning ItemCollectionMetrics. See PutItemWithResponseIntegrationTest for
// additional testing for this method.
@Test
public void returnItemCollectionMetrics_unset_itemCollectionMetricsNull() {
Record record = new Record().setId(1);
PutItemEnhancedResponse<Record> response = mappedTable1.putItemWithResponse(r -> r.item(record));
assertThat(response.consumedCapacity()).isNull();
}
private static class NoOpExtension implements DynamoDbEnhancedClientExtension {
}
}
| 3,862 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/ImmutableTableSchemaRecursiveTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.functionaltests;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Collections;
import java.util.Map;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.RecursiveRecordBean;
import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.RecursiveRecordImmutable;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
public class ImmutableTableSchemaRecursiveTest {
@Test
public void recursiveRecord_document() {
TableSchema<RecursiveRecordImmutable> tableSchema = TableSchema.fromClass(RecursiveRecordImmutable.class);
RecursiveRecordBean recursiveRecordBean2 = new RecursiveRecordBean();
recursiveRecordBean2.setAttribute(4);
RecursiveRecordBean recursiveRecordBean1 = new RecursiveRecordBean();
recursiveRecordBean1.setAttribute(3);
recursiveRecordBean1.setRecursiveRecordBean(recursiveRecordBean2);
RecursiveRecordImmutable recursiveRecordImmutable2 =
RecursiveRecordImmutable.builder()
.setAttribute(2)
.setRecursiveRecordBean(recursiveRecordBean1)
.build();
RecursiveRecordImmutable recursiveRecordImmutable1 =
RecursiveRecordImmutable.builder()
.setAttribute(1)
.setRecursiveRecordImmutable(recursiveRecordImmutable2)
.build();
Map<String, AttributeValue> itemMap = tableSchema.itemToMap(recursiveRecordImmutable1, true);
assertThat(itemMap).hasSize(2);
assertThat(itemMap).containsEntry("attribute", AttributeValue.builder().n("1").build());
assertThat(itemMap).hasEntrySatisfying("recursiveRecordImmutable", av -> {
assertThat(av.hasM()).isTrue();
assertThat(av.m()).containsEntry("attribute", AttributeValue.builder().n("2").build());
assertThat(av.m()).hasEntrySatisfying("recursiveRecordBean", bav -> {
assertThat(bav.hasM()).isTrue();
assertThat(bav.m()).containsEntry("attribute", AttributeValue.builder().n("3").build());
assertThat(bav.m()).hasEntrySatisfying("recursiveRecordBean", bav2 -> {
assertThat(bav2.hasM()).isTrue();
assertThat(bav2.m()).containsEntry("attribute", AttributeValue.builder().n("4").build());
});
});
});
}
@Test
public void recursiveRecord_list() {
TableSchema<RecursiveRecordImmutable> tableSchema =
TableSchema.fromClass(RecursiveRecordImmutable.class);
RecursiveRecordImmutable recursiveRecordImmutable2 = RecursiveRecordImmutable.builder()
.setAttribute(2)
.build();
RecursiveRecordImmutable recursiveRecordImmutable1 =
RecursiveRecordImmutable.builder()
.setAttribute(1)
.setRecursiveRecordList(Collections.singletonList(recursiveRecordImmutable2))
.build();
Map<String, AttributeValue> itemMap = tableSchema.itemToMap(recursiveRecordImmutable1, true);
assertThat(itemMap).hasSize(2);
assertThat(itemMap).containsEntry("attribute", AttributeValue.builder().n("1").build());
assertThat(itemMap).hasEntrySatisfying("recursiveRecordList", av -> {
assertThat(av.hasL()).isTrue();
assertThat(av.l()).hasOnlyOneElementSatisfying(listAv -> {
assertThat(listAv.hasM()).isTrue();
assertThat(listAv.m()).containsEntry("attribute", AttributeValue.builder().n("2").build());
});
});
}
}
| 3,863 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/DeleteItemWithResponseTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.functionaltests;
import static org.assertj.core.api.Assertions.assertThat;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey;
import java.util.Objects;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
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.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema;
import software.amazon.awssdk.enhanced.dynamodb.model.DeleteItemEnhancedResponse;
import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest;
import software.amazon.awssdk.services.dynamodb.model.ReturnConsumedCapacity;
public class DeleteItemWithResponseTest extends LocalDynamoDbSyncTestBase {
private static class Record {
private Integer id;
private String stringAttr1;
private Integer getId() {
return id;
}
private Record setId(Integer id) {
this.id = id;
return this;
}
private String getStringAttr1() {
return stringAttr1;
}
private Record setStringAttr1(String stringAttr1) {
this.stringAttr1 = stringAttr1;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Record record = (Record) o;
return Objects.equals(id, record.id) && Objects.equals(stringAttr1, record.stringAttr1);
}
@Override
public int hashCode() {
return Objects.hash(id, stringAttr1);
}
}
private static final TableSchema<Record> TABLE_SCHEMA =
StaticTableSchema.builder(Record.class)
.newItemSupplier(Record::new)
.addAttribute(Integer.class, a -> a.name("id_1")
.getter(Record::getId)
.setter(Record::setId)
.tags(primaryPartitionKey()))
.addAttribute(String.class, a -> a.name("stringAttr1")
.getter(Record::getStringAttr1)
.setter(Record::setStringAttr1))
.build();
private DynamoDbEnhancedClient enhancedClient;
private DynamoDbTable<Record> mappedTable1;
@Before
public void createTable() {
enhancedClient = DynamoDbEnhancedClient.builder()
.dynamoDbClient(getDynamoDbClient())
.build();
mappedTable1 = enhancedClient.table(getConcreteTableName("table-name-1"), TABLE_SCHEMA);
mappedTable1.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput()));
}
@After
public void deleteTable() {
getDynamoDbClient().deleteTable(DeleteTableRequest.builder()
.tableName(getConcreteTableName("table-name-1"))
.build());
}
// Note: DynamoDB local seems to always return the consumed capacity even if not specified on the request. See
// AsyncDeleteItemWithResponseIntegrationTest for additional testing of this field against the actual service.
@Test
public void returnConsumedCapacity_set_consumedCapacityNotNull() {
Key key = Key.builder().partitionValue(1).build();
DeleteItemEnhancedResponse<Record> response = mappedTable1.deleteItemWithResponse(r -> r.key(key)
.returnConsumedCapacity(ReturnConsumedCapacity.TOTAL));
assertThat(response.consumedCapacity()).isNotNull();
}
}
| 3,864 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/AsyncIndexQueryTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.functionaltests;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.numberValue;
import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.stringValue;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primarySortKey;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.secondaryPartitionKey;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.secondarySortKey;
import static software.amazon.awssdk.enhanced.dynamodb.model.QueryConditional.keyEqualTo;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import software.amazon.awssdk.core.async.SdkPublisher;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbAsyncIndex;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbAsyncTable;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedAsyncClient;
import software.amazon.awssdk.enhanced.dynamodb.Key;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.internal.client.DefaultDynamoDbEnhancedAsyncClient;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema;
import software.amazon.awssdk.enhanced.dynamodb.model.CreateTableEnhancedRequest;
import software.amazon.awssdk.enhanced.dynamodb.model.EnhancedGlobalSecondaryIndex;
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.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest;
import software.amazon.awssdk.services.dynamodb.model.ProjectionType;
public class AsyncIndexQueryTest extends LocalDynamoDbAsyncTestBase {
private static class Record {
private String id;
private Integer sort;
private Integer value;
private String gsiId;
private Integer gsiSort;
private String getId() {
return id;
}
private Record setId(String id) {
this.id = id;
return this;
}
private Integer getSort() {
return sort;
}
private Record setSort(Integer sort) {
this.sort = sort;
return this;
}
private Integer getValue() {
return value;
}
private Record setValue(Integer value) {
this.value = value;
return this;
}
private String getGsiId() {
return gsiId;
}
private Record setGsiId(String gsiId) {
this.gsiId = gsiId;
return this;
}
private Integer getGsiSort() {
return gsiSort;
}
private Record setGsiSort(Integer gsiSort) {
this.gsiSort = gsiSort;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Record record = (Record) o;
return Objects.equals(id, record.id) &&
Objects.equals(sort, record.sort) &&
Objects.equals(value, record.value) &&
Objects.equals(gsiId, record.gsiId) &&
Objects.equals(gsiSort, record.gsiSort);
}
@Override
public int hashCode() {
return Objects.hash(id, sort, value, gsiId, gsiSort);
}
}
private static final TableSchema<Record> TABLE_SCHEMA =
StaticTableSchema.builder(Record.class)
.newItemSupplier(Record::new)
.addAttribute(String.class, a -> a.name("id")
.getter(Record::getId)
.setter(Record::setId)
.tags(primaryPartitionKey()))
.addAttribute(Integer.class, a -> a.name("sort")
.getter(Record::getSort)
.setter(Record::setSort)
.tags(primarySortKey()))
.addAttribute(Integer.class, a -> a.name("value")
.getter(Record::getValue)
.setter(Record::setValue))
.addAttribute(String.class, a -> a.name("gsi_id")
.getter(Record::getGsiId)
.setter(Record::setGsiId)
.tags(secondaryPartitionKey("gsi_keys_only")))
.addAttribute(Integer.class, a -> a.name("gsi_sort")
.getter(Record::getGsiSort)
.setter(Record::setGsiSort)
.tags(secondarySortKey("gsi_keys_only")))
.build();
private static final List<Record> RECORDS =
IntStream.range(0, 10)
.mapToObj(i -> new Record()
.setId("id-value")
.setSort(i)
.setValue(i)
.setGsiId("gsi-id-value")
.setGsiSort(i))
.collect(Collectors.toList());
private static final List<Record> KEYS_ONLY_RECORDS =
RECORDS.stream()
.map(record -> new Record()
.setId(record.id)
.setSort(record.sort)
.setGsiId(record.gsiId)
.setGsiSort(record.gsiSort))
.collect(Collectors.toList());
private DynamoDbEnhancedAsyncClient enhancedAsyncClient = DefaultDynamoDbEnhancedAsyncClient.builder()
.dynamoDbClient(getDynamoDbAsyncClient())
.build();
private DynamoDbAsyncTable<Record> mappedTable = enhancedAsyncClient.table(getConcreteTableName("table-name"), TABLE_SCHEMA);
private DynamoDbAsyncIndex<Record> keysOnlyMappedIndex = mappedTable.index("gsi_keys_only");
private void insertRecords() {
RECORDS.forEach(record -> mappedTable.putItem(r -> r.item(record)).join());
}
@Before
public void createTable() {
mappedTable.createTable(
CreateTableEnhancedRequest.builder()
.provisionedThroughput(getDefaultProvisionedThroughput())
.globalSecondaryIndices(EnhancedGlobalSecondaryIndex.builder()
.indexName("gsi_keys_only")
.projection(p -> p.projectionType(ProjectionType.KEYS_ONLY))
.provisionedThroughput(getDefaultProvisionedThroughput())
.build())
.build())
.join();
}
@After
public void deleteTable() {
getDynamoDbAsyncClient().deleteTable(DeleteTableRequest.builder()
.tableName(getConcreteTableName("table-name"))
.build())
.join();
}
@Test
public void queryAllRecordsDefaultSettings_usingShortcutForm() {
insertRecords();
SdkPublisher<Page<Record>> publisher =
keysOnlyMappedIndex.query(keyEqualTo(k -> k.partitionValue("gsi-id-value")));
List<Page<Record>> results = drainPublisher(publisher, 1);
Page<Record> page = results.get(0);
assertThat(page.items(), is(KEYS_ONLY_RECORDS));
assertThat(page.lastEvaluatedKey(), is(nullValue()));
}
@Test
public void queryBetween() {
insertRecords();
Key fromKey = Key.builder().partitionValue("gsi-id-value").sortValue(3).build();
Key toKey = Key.builder().partitionValue("gsi-id-value").sortValue(5).build();
SdkPublisher<Page<Record>> publisher = keysOnlyMappedIndex.query(r -> r.queryConditional(QueryConditional.sortBetween(fromKey, toKey)));
List<Page<Record>> results = drainPublisher(publisher, 1);
Page<Record> page = results.get(0);
assertThat(page.items(),
is(KEYS_ONLY_RECORDS.stream().filter(r -> r.sort >= 3 && r.sort <= 5).collect(Collectors.toList())));
assertThat(page.lastEvaluatedKey(), is(nullValue()));
}
@Test
public void queryLimit() {
insertRecords();
SdkPublisher<Page<Record>> publisher =
keysOnlyMappedIndex.query(QueryEnhancedRequest.builder()
.queryConditional(keyEqualTo(k -> k.partitionValue("gsi-id-value")))
.limit(5)
.build());
List<Page<Record>> results = drainPublisher(publisher, 3);
Page<Record> page1 = results.get(0);
Page<Record> page2 = results.get(1);
Page<Record> page3 = results.get(2);
Map<String, AttributeValue> expectedLastEvaluatedKey1 = new HashMap<>();
expectedLastEvaluatedKey1.put("id", stringValue(KEYS_ONLY_RECORDS.get(4).getId()));
expectedLastEvaluatedKey1.put("sort", numberValue(KEYS_ONLY_RECORDS.get(4).getSort()));
expectedLastEvaluatedKey1.put("gsi_id", stringValue(KEYS_ONLY_RECORDS.get(4).getGsiId()));
expectedLastEvaluatedKey1.put("gsi_sort", numberValue(KEYS_ONLY_RECORDS.get(4).getGsiSort()));
Map<String, AttributeValue> expectedLastEvaluatedKey2 = new HashMap<>();
expectedLastEvaluatedKey2.put("id", stringValue(KEYS_ONLY_RECORDS.get(9).getId()));
expectedLastEvaluatedKey2.put("sort", numberValue(KEYS_ONLY_RECORDS.get(9).getSort()));
expectedLastEvaluatedKey2.put("gsi_id", stringValue(KEYS_ONLY_RECORDS.get(9).getGsiId()));
expectedLastEvaluatedKey2.put("gsi_sort", numberValue(KEYS_ONLY_RECORDS.get(9).getGsiSort()));
assertThat(page1.items(), is(KEYS_ONLY_RECORDS.subList(0, 5)));
assertThat(page1.lastEvaluatedKey(), is(expectedLastEvaluatedKey1));
assertThat(page2.items(), is(KEYS_ONLY_RECORDS.subList(5, 10)));
assertThat(page2.lastEvaluatedKey(), is(expectedLastEvaluatedKey2));
assertThat(page3.items(), is(empty()));
assertThat(page3.lastEvaluatedKey(), is(nullValue()));
}
@Test
public void queryEmpty() {
SdkPublisher<Page<Record>> publisher =
keysOnlyMappedIndex.query(r -> r.queryConditional(keyEqualTo(k -> k.partitionValue("gsi-id-value"))));
List<Page<Record>> results = drainPublisher(publisher, 1);
Page<Record> page = results.get(0);
assertThat(page.items(), is(empty()));
assertThat(page.lastEvaluatedKey(), is(nullValue()));
}
@Test
public void queryExclusiveStartKey() {
insertRecords();
Map<String, AttributeValue> expectedLastEvaluatedKey = new HashMap<>();
expectedLastEvaluatedKey.put("id", stringValue(KEYS_ONLY_RECORDS.get(7).getId()));
expectedLastEvaluatedKey.put("sort", numberValue(KEYS_ONLY_RECORDS.get(7).getSort()));
expectedLastEvaluatedKey.put("gsi_id", stringValue(KEYS_ONLY_RECORDS.get(7).getGsiId()));
expectedLastEvaluatedKey.put("gsi_sort", numberValue(KEYS_ONLY_RECORDS.get(7).getGsiSort()));
SdkPublisher<Page<Record>> publisher =
keysOnlyMappedIndex.query(QueryEnhancedRequest.builder()
.queryConditional(keyEqualTo(k -> k.partitionValue("gsi-id-value")))
.exclusiveStartKey(expectedLastEvaluatedKey)
.build());
List<Page<Record>> results = drainPublisher(publisher, 1);
Page<Record> page = results.get(0);
assertThat(page.items(), is(KEYS_ONLY_RECORDS.subList(8, 10)));
assertThat(page.lastEvaluatedKey(), is(nullValue()));
}
}
| 3,865 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/AsyncBatchGetItemTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.functionaltests;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import software.amazon.awssdk.core.async.SdkPublisher;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbAsyncTable;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedAsyncClient;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.internal.client.DefaultDynamoDbEnhancedAsyncClient;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema;
import software.amazon.awssdk.enhanced.dynamodb.model.BatchGetItemEnhancedRequest;
import software.amazon.awssdk.enhanced.dynamodb.model.BatchGetResultPage;
import software.amazon.awssdk.enhanced.dynamodb.model.BatchGetResultPagePublisher;
import software.amazon.awssdk.enhanced.dynamodb.model.ReadBatch;
import software.amazon.awssdk.services.dynamodb.model.ConsumedCapacity;
import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest;
import software.amazon.awssdk.services.dynamodb.model.ReturnConsumedCapacity;
public class AsyncBatchGetItemTest extends LocalDynamoDbAsyncTestBase {
private static class Record1 {
private Integer id;
private String stringAttr;
private Integer getId() {
return id;
}
private String getStringAttr() {
return stringAttr;
}
private Record1 setId(Integer id) {
this.id = id;
return this;
}
private Record1 setStringAttr(String str) {
this.stringAttr = str;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Record1 record1 = (Record1) o;
return Objects.equals(id, record1.id) && Objects.equals(stringAttr, record1.stringAttr);
}
@Override
public int hashCode() {
return Objects.hash(id, stringAttr);
}
}
private static class Record2 {
private Integer id;
private String stringAttr;
private Integer getId() {
return id;
}
private String getStringAttr() {
return stringAttr;
}
private Record2 setId(Integer id) {
this.id = id;
return this;
}
private Record2 setStringAttr(String str) {
this.stringAttr = str;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Record2 record2 = (Record2) o;
return Objects.equals(id, record2.id) && Objects.equals(stringAttr, record2.stringAttr);
}
@Override
public int hashCode() {
return Objects.hash(id, stringAttr);
}
}
private static final TableSchema<Record1> TABLE_SCHEMA_1 =
StaticTableSchema.builder(Record1.class)
.newItemSupplier(Record1::new)
.addAttribute(Integer.class, a -> a.name("id_1")
.getter(Record1::getId)
.setter(Record1::setId)
.tags(primaryPartitionKey()))
.addAttribute(String.class, a -> a.name("str_1")
.getter(Record1::getStringAttr)
.setter(Record1::setStringAttr))
.build();
private static final TableSchema<Record2> TABLE_SCHEMA_2 =
StaticTableSchema.builder(Record2.class)
.newItemSupplier(Record2::new)
.addAttribute(Integer.class, a -> a.name("id_2")
.getter(Record2::getId)
.setter(Record2::setId)
.tags(primaryPartitionKey()))
.addAttribute(String.class, a -> a.name("str_1")
.getter(Record2::getStringAttr)
.setter(Record2::setStringAttr))
.build();
private final DynamoDbEnhancedAsyncClient enhancedAsyncClient =
DefaultDynamoDbEnhancedAsyncClient.builder()
.dynamoDbClient(getDynamoDbAsyncClient())
.build();
private final String tableName1 = getConcreteTableName("table-name-1");
private final String tableName2 = getConcreteTableName("table-name-2");
private final DynamoDbAsyncTable<Record1> mappedTable1 = enhancedAsyncClient.table(tableName1, TABLE_SCHEMA_1);
private final DynamoDbAsyncTable<Record2> mappedTable2 = enhancedAsyncClient.table(tableName2, TABLE_SCHEMA_2);
private static final List<Record1> RECORDS_1 =
IntStream.range(0, 2)
.mapToObj(i -> new Record1().setId(i).setStringAttr(getStringAttrValue(80_000)))
.collect(Collectors.toList());
private static final List<Record2> RECORDS_2 =
IntStream.range(0, 2)
.mapToObj(i -> new Record2().setId(i).setStringAttr(getStringAttrValue(40_000)))
.collect(Collectors.toList());
@Before
public void createTable() {
mappedTable1.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput())).join();
mappedTable2.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput())).join();
}
@After
public void deleteTable() {
getDynamoDbAsyncClient().deleteTable(DeleteTableRequest.builder()
.tableName(tableName1)
.build()).join();
getDynamoDbAsyncClient().deleteTable(DeleteTableRequest.builder()
.tableName(tableName2)
.build()).join();
}
private void insertRecords() {
RECORDS_1.forEach(record -> mappedTable1.putItem(r -> r.item(record)).join());
RECORDS_2.forEach(record -> mappedTable2.putItem(r -> r.item(record)).join());
}
@Test
public void getRecordsFromMultipleTables() {
insertRecords();
SdkPublisher<BatchGetResultPage> publisher = batchGetResultPageSdkPublisherForBothTables();
List<BatchGetResultPage> results = drainPublisher(publisher, 1);
assertThat(results.size(), is(1));
BatchGetResultPage page = results.get(0);
assertThat(page.consumedCapacity(), empty());
List<Record1> record1List = page.resultsForTable(mappedTable1);
assertThat(record1List.size(), is(2));
assertThat(record1List, containsInAnyOrder(RECORDS_1.get(0), RECORDS_1.get(1)));
List<Record2> record2List = page.resultsForTable(mappedTable2);
assertThat(record2List.size(), is(2));
assertThat(record2List, containsInAnyOrder(RECORDS_2.get(0), RECORDS_2.get(1)));
}
@Test
public void getRecordsFromMultipleTables_viaFlattenedItems() {
insertRecords();
BatchGetResultPagePublisher publisher = batchGetResultPageSdkPublisherForBothTables();
List<Record1> table1Results = drainPublisher(publisher.resultsForTable(mappedTable1), 2);
assertThat(table1Results.size(), is(2));
assertThat(table1Results, containsInAnyOrder(RECORDS_1.toArray()));
List<Record2> table2Results = drainPublisher(publisher.resultsForTable(mappedTable2), 2);
assertThat(table1Results.size(), is(2));
assertThat(table2Results, containsInAnyOrder(RECORDS_2.toArray()));
}
@Test
public void notFoundRecordReturnsNull() {
insertRecords();
BatchGetItemEnhancedRequest batchGetItemEnhancedRequest = requestWithNotFoundRecord();
SdkPublisher<BatchGetResultPage> publisher = enhancedAsyncClient.batchGetItem(batchGetItemEnhancedRequest);
List<BatchGetResultPage> results = drainPublisher(publisher, 1);
assertThat(results.size(), is(1));
BatchGetResultPage page = results.get(0);
List<Record1> record1List = page.resultsForTable(mappedTable1);
assertThat(record1List.size(), is(1));
assertThat(record1List.get(0).getId(), is(0));
List<Record2> record2List = page.resultsForTable(mappedTable2);
assertThat(record2List.size(), is(2));
assertThat(record2List, containsInAnyOrder(RECORDS_2.get(0), RECORDS_2.get(1)));
}
@Test
public void notFoundRecordReturnsNull_viaFlattenedItems() {
insertRecords();
BatchGetItemEnhancedRequest batchGetItemEnhancedRequest = requestWithNotFoundRecord();
BatchGetResultPagePublisher publisher = enhancedAsyncClient.batchGetItem(batchGetItemEnhancedRequest);
List<Record1> resultsForTable1 = drainPublisher(publisher.resultsForTable(mappedTable1), 1);
assertThat(resultsForTable1.size(), is(1));
assertThat(resultsForTable1.get(0).getId(), is(0));
List<Record2> record2List = drainPublisher(publisher.resultsForTable(mappedTable2), 2);
assertThat(record2List.size(), is(2));
assertThat(record2List, containsInAnyOrder(RECORDS_2.toArray()));
}
@Test
public void getRecordsFromMultipleTables_withReturnConsumedCapacity() {
insertRecords();
SdkPublisher<BatchGetResultPage> publisher = batchGetResultPageSdkPublisherForBothTables(ReturnConsumedCapacity.TOTAL);
List<BatchGetResultPage> results = drainPublisher(publisher, 1);
assertThat(results.size(), is(1));
BatchGetResultPage page = results.get(0);
assertThat(page.consumedCapacity(), not(nullValue()));
assertThat(page.consumedCapacity(), hasSize(2));
assertThat(page.consumedCapacity(), containsInAnyOrder(
ConsumedCapacity.builder().tableName(tableName1).capacityUnits(20.0).build(),
ConsumedCapacity.builder().tableName(tableName2).capacityUnits(10.0).build()
));
List<Record1> record1List = page.resultsForTable(mappedTable1);
assertThat(record1List.size(), is(2));
assertThat(record1List, containsInAnyOrder(RECORDS_1.get(0), RECORDS_1.get(1)));
List<Record2> record2List = page.resultsForTable(mappedTable2);
assertThat(record2List.size(), is(2));
assertThat(record2List, containsInAnyOrder(RECORDS_2.get(0), RECORDS_2.get(1)));
}
@Test
public void notFoundRecords_withReturnConsumedCapacity() {
insertRecords();
BatchGetItemEnhancedRequest batchGetItemEnhancedRequest =
requestWithNotFoundRecord().toBuilder()
.returnConsumedCapacity(ReturnConsumedCapacity.TOTAL)
.build();
SdkPublisher<BatchGetResultPage> publisher = enhancedAsyncClient.batchGetItem(batchGetItemEnhancedRequest);
List<BatchGetResultPage> results = drainPublisher(publisher, 1);
assertThat(results.size(), is(1));
BatchGetResultPage page = results.get(0);
assertThat(page.consumedCapacity(), containsInAnyOrder(
ConsumedCapacity.builder().tableName(tableName1).capacityUnits(10.0).build(),
ConsumedCapacity.builder().tableName(tableName2).capacityUnits(10.0).build()
));
List<Record1> record1List = page.resultsForTable(mappedTable1);
assertThat(record1List.size(), is(1));
assertThat(record1List.get(0).getId(), is(0));
List<Record2> record2List = page.resultsForTable(mappedTable2);
assertThat(record2List.size(), is(2));
assertThat(record2List, containsInAnyOrder(RECORDS_2.get(0), RECORDS_2.get(1)));
}
private BatchGetItemEnhancedRequest requestWithNotFoundRecord() {
return BatchGetItemEnhancedRequest.builder()
.readBatches(
ReadBatch.builder(Record1.class)
.mappedTableResource(mappedTable1)
.addGetItem(r -> r.key(k -> k.partitionValue(0)))
.build(),
ReadBatch.builder(Record2.class)
.mappedTableResource(mappedTable2)
.addGetItem(r -> r.key(k -> k.partitionValue(0)))
.build(),
ReadBatch.builder(Record2.class)
.mappedTableResource(mappedTable2)
.addGetItem(r -> r.key(k -> k.partitionValue(1)))
.build(),
ReadBatch.builder(Record1.class)
.mappedTableResource(mappedTable1)
.addGetItem(r -> r.key(k -> k.partitionValue(5)))
.build())
.build();
}
private BatchGetResultPagePublisher batchGetResultPageSdkPublisherForBothTables() {
return batchGetResultPageSdkPublisherForBothTables(null);
}
private BatchGetResultPagePublisher batchGetResultPageSdkPublisherForBothTables(ReturnConsumedCapacity retConsumedCapacity) {
return enhancedAsyncClient.batchGetItem(
r -> r.returnConsumedCapacity(retConsumedCapacity)
.readBatches(
ReadBatch.builder(Record1.class)
.mappedTableResource(mappedTable1)
.addGetItem(i -> i.key(k -> k.partitionValue(0)))
.build(),
ReadBatch.builder(Record2.class)
.mappedTableResource(mappedTable2)
.addGetItem(i -> i.key(k -> k.partitionValue(0)))
.build(),
ReadBatch.builder(Record2.class)
.mappedTableResource(mappedTable2)
.addGetItem(i -> i.key(k -> k.partitionValue(1)))
.build(),
ReadBatch.builder(Record1.class)
.mappedTableResource(mappedTable1)
.addGetItem(i -> i.key(k -> k.partitionValue(1)))
.build()
)
);
}
private static String getStringAttrValue(int nChars) {
char[] bytes = new char[nChars];
Arrays.fill(bytes, 'a');
return new String(bytes);
}
}
| 3,866 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/TransactGetItemsTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.functionaltests;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import software.amazon.awssdk.enhanced.dynamodb.Document;
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.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema;
import software.amazon.awssdk.enhanced.dynamodb.model.TransactGetItemsEnhancedRequest;
import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest;
public class TransactGetItemsTest extends LocalDynamoDbSyncTestBase {
private static class Record1 {
private Integer id;
private Integer getId() {
return id;
}
private Record1 setId(Integer id) {
this.id = id;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Record1 record1 = (Record1) o;
return Objects.equals(id, record1.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}
private static class Record2 {
private Integer id;
private Integer getId() {
return id;
}
private Record2 setId(Integer id) {
this.id = id;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Record2 record2 = (Record2) o;
return Objects.equals(id, record2.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}
private static final TableSchema<Record1> TABLE_SCHEMA_1 =
StaticTableSchema.builder(Record1.class)
.newItemSupplier(Record1::new)
.addAttribute(Integer.class, a -> a.name("id_1")
.getter(Record1::getId)
.setter(Record1::setId)
.tags(primaryPartitionKey()))
.build();
private static final TableSchema<Record2> TABLE_SCHEMA_2 =
StaticTableSchema.builder(Record2.class)
.newItemSupplier(Record2::new)
.addAttribute(Integer.class, a -> a.name("id_2")
.getter(Record2::getId)
.setter(Record2::setId)
.tags(primaryPartitionKey()))
.build();
private DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder()
.dynamoDbClient(getDynamoDbClient())
.build();
private DynamoDbTable<Record1> mappedTable1 = enhancedClient.table(getConcreteTableName("table-name-1"), TABLE_SCHEMA_1);
private DynamoDbTable<Record2> mappedTable2 = enhancedClient.table(getConcreteTableName("table-name-2"), TABLE_SCHEMA_2);
private static final List<Record1> RECORDS_1 =
IntStream.range(0, 2)
.mapToObj(i -> new Record1().setId(i))
.collect(Collectors.toList());
private static final List<Record2> RECORDS_2 =
IntStream.range(0, 2)
.mapToObj(i -> new Record2().setId(i))
.collect(Collectors.toList());
@Before
public void createTable() {
mappedTable1.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput()));
mappedTable2.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput()));
}
@After
public void deleteTable() {
getDynamoDbClient().deleteTable(DeleteTableRequest.builder()
.tableName(getConcreteTableName("table-name-1"))
.build());
getDynamoDbClient().deleteTable(DeleteTableRequest.builder()
.tableName(getConcreteTableName("table-name-2"))
.build());
}
private void insertRecords() {
RECORDS_1.forEach(record -> mappedTable1.putItem(r -> r.item(record)));
RECORDS_2.forEach(record -> mappedTable2.putItem(r -> r.item(record)));
}
@Test
public void getRecordsFromMultipleTables() {
insertRecords();
TransactGetItemsEnhancedRequest transactGetItemsEnhancedRequest =
TransactGetItemsEnhancedRequest.builder()
.addGetItem(mappedTable1, Key.builder().partitionValue(0).build())
.addGetItem(mappedTable2, Key.builder().partitionValue(0).build())
.addGetItem(mappedTable2, Key.builder().partitionValue(1).build())
.addGetItem(mappedTable1, Key.builder().partitionValue(1).build())
.build();
List<Document> results = enhancedClient.transactGetItems(transactGetItemsEnhancedRequest);
assertThat(results.size(), is(4));
assertThat(results.get(0).getItem(mappedTable1), is(RECORDS_1.get(0)));
assertThat(results.get(1).getItem(mappedTable2), is(RECORDS_2.get(0)));
assertThat(results.get(2).getItem(mappedTable2), is(RECORDS_2.get(1)));
assertThat(results.get(3).getItem(mappedTable1), is(RECORDS_1.get(1)));
}
@Test
public void notFoundRecordReturnsNull() {
insertRecords();
TransactGetItemsEnhancedRequest transactGetItemsEnhancedRequest =
TransactGetItemsEnhancedRequest.builder()
.addGetItem(mappedTable1, Key.builder().partitionValue(0).build())
.addGetItem(mappedTable2, Key.builder().partitionValue(0).build())
.addGetItem(mappedTable2, Key.builder().partitionValue(5).build())
.addGetItem(mappedTable1, Key.builder().partitionValue(1).build())
.build();
List<Document> results = enhancedClient.transactGetItems(transactGetItemsEnhancedRequest);
assertThat(results.size(), is(4));
assertThat(results.get(0).getItem(mappedTable1), is(RECORDS_1.get(0)));
assertThat(results.get(1).getItem(mappedTable2), is(RECORDS_2.get(0)));
assertThat(results.get(2).getItem(mappedTable2), is(nullValue()));
assertThat(results.get(3).getItem(mappedTable1), is(RECORDS_1.get(1)));
}
}
| 3,867 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/BatchGetItemTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.functionaltests;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.is;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import software.amazon.awssdk.core.pagination.sync.SdkIterable;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema;
import software.amazon.awssdk.enhanced.dynamodb.model.BatchGetItemEnhancedRequest;
import software.amazon.awssdk.enhanced.dynamodb.model.BatchGetResultPage;
import software.amazon.awssdk.enhanced.dynamodb.model.BatchGetResultPageIterable;
import software.amazon.awssdk.enhanced.dynamodb.model.ReadBatch;
import software.amazon.awssdk.services.dynamodb.model.ConsumedCapacity;
import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest;
import software.amazon.awssdk.services.dynamodb.model.ReturnConsumedCapacity;
public class BatchGetItemTest extends LocalDynamoDbSyncTestBase {
private static class Record1 {
private Integer id;
private String stringAttr;
private Integer getId() {
return id;
}
private String getStringAttr() {
return stringAttr;
}
private Record1 setId(Integer id) {
this.id = id;
return this;
}
private Record1 setStringAttr(String str) {
this.stringAttr = str;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Record1 record1 = (Record1) o;
return Objects.equals(id, record1.id) && Objects.equals(stringAttr, record1.stringAttr);
}
@Override
public int hashCode() {
return Objects.hash(id, stringAttr);
}
}
private static class Record2 {
private Integer id;
private String stringAttr;
private Integer getId() {
return id;
}
private String getStringAttr() {
return stringAttr;
}
private Record2 setId(Integer id) {
this.id = id;
return this;
}
private Record2 setStringAttr(String str) {
this.stringAttr = str;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Record2 record2 = (Record2) o;
return Objects.equals(id, record2.id) && Objects.equals(stringAttr, record2.stringAttr);
}
@Override
public int hashCode() {
return Objects.hash(id, stringAttr);
}
}
private static final TableSchema<Record1> TABLE_SCHEMA_1 =
StaticTableSchema.builder(Record1.class)
.newItemSupplier(Record1::new)
.addAttribute(Integer.class, a -> a.name("id_1")
.getter(Record1::getId)
.setter(Record1::setId)
.tags(primaryPartitionKey()))
.addAttribute(String.class, a -> a.name("str_1")
.getter(Record1::getStringAttr)
.setter(Record1::setStringAttr))
.build();
private static final TableSchema<Record2> TABLE_SCHEMA_2 =
StaticTableSchema.builder(Record2.class)
.newItemSupplier(Record2::new)
.addAttribute(Integer.class, a -> a.name("id_2")
.getter(Record2::getId)
.setter(Record2::setId)
.tags(primaryPartitionKey()))
.addAttribute(String.class, a -> a.name("str_1")
.getter(Record2::getStringAttr)
.setter(Record2::setStringAttr))
.build();
private DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder()
.dynamoDbClient(getDynamoDbClient())
.build();
private final String tableName1 = getConcreteTableName("table-name-1");
private final String tableName2 = getConcreteTableName("table-name-2");
private final DynamoDbTable<Record1> mappedTable1 = enhancedClient.table(tableName1, TABLE_SCHEMA_1);
private final DynamoDbTable<Record2> mappedTable2 = enhancedClient.table(tableName2, TABLE_SCHEMA_2);
private static final List<Record1> RECORDS_1 =
IntStream.range(0, 2)
.mapToObj(i -> new Record1().setId(i).setStringAttr(getStringAttrValue(80_000)))
.collect(Collectors.toList());
private static final List<Record2> RECORDS_2 =
IntStream.range(0, 2)
.mapToObj(i -> new Record2().setId(i).setStringAttr(getStringAttrValue(40_000)))
.collect(Collectors.toList());
@Before
public void createTable() {
mappedTable1.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput()));
mappedTable2.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput()));
}
@After
public void deleteTable() {
getDynamoDbClient().deleteTable(DeleteTableRequest.builder()
.tableName(tableName1)
.build());
getDynamoDbClient().deleteTable(DeleteTableRequest.builder()
.tableName(tableName2)
.build());
}
private void insertRecords() {
RECORDS_1.forEach(record -> mappedTable1.putItem(r -> r.item(record)));
RECORDS_2.forEach(record -> mappedTable2.putItem(r -> r.item(record)));
}
@Test
public void getRecordsFromMultipleTables() {
insertRecords();
SdkIterable<BatchGetResultPage> results = getBatchGetResultPagesForBothTables();
assertThat(results.stream().count(), is(1L));
results.iterator().forEachRemaining(page -> {
assertThat(page.consumedCapacity(), empty());
List<Record1> table1Results = page.resultsForTable(mappedTable1);
assertThat(table1Results.size(), is(2));
assertThat(table1Results.get(0).id, is(0));
assertThat(table1Results.get(1).id, is(1));
assertThat(page.resultsForTable(mappedTable2).size(), is(2));
});
}
@Test
public void getRecordsFromMultipleTables_viaFlattenedItems() {
insertRecords();
BatchGetResultPageIterable results = getBatchGetResultPagesForBothTables();
SdkIterable<Record1> recordsList1 = results.resultsForTable(mappedTable1);
assertThat(recordsList1, containsInAnyOrder(RECORDS_1.toArray()));
SdkIterable<Record2> recordsList2 = results.resultsForTable(mappedTable2);
assertThat(recordsList2, containsInAnyOrder(RECORDS_2.toArray()));
}
@Test
public void notFoundRecordIgnored() {
insertRecords();
BatchGetItemEnhancedRequest batchGetItemEnhancedRequest = batchGetItemEnhancedRequestWithNotFoundRecord();
SdkIterable<BatchGetResultPage> results = enhancedClient.batchGetItem(batchGetItemEnhancedRequest);
assertThat(results.stream().count(), is(1L));
results.iterator().forEachRemaining((page) -> {
assertThat(page.consumedCapacity(), empty());
List<Record1> mappedTable1Results = page.resultsForTable(mappedTable1);
assertThat(mappedTable1Results.size(), is(1));
assertThat(mappedTable1Results.get(0).id, is(0));
assertThat(page.resultsForTable(mappedTable2).size(), is(2));
});
}
@Test
public void notFoundRecordIgnored_viaFlattenedItems() {
insertRecords();
BatchGetItemEnhancedRequest batchGetItemEnhancedRequest = batchGetItemEnhancedRequestWithNotFoundRecord();
BatchGetResultPageIterable pageIterable = enhancedClient.batchGetItem(batchGetItemEnhancedRequest);
assertThat(pageIterable.stream().count(), is(1L));
List<Record1> recordsList1 = pageIterable.resultsForTable(mappedTable1).stream().collect(Collectors.toList());
assertThat(recordsList1, is(RECORDS_1.subList(0, 1)));
SdkIterable<Record2> recordsList2 = pageIterable.resultsForTable(mappedTable2);
assertThat(recordsList2, containsInAnyOrder(RECORDS_2.toArray()));
}
@Test
public void getRecordsFromMultipleTables_withReturnConsumedCapacity() {
insertRecords();
SdkIterable<BatchGetResultPage> results = getBatchGetResultPagesForBothTables(ReturnConsumedCapacity.TOTAL);
assertThat(results.stream().count(), is(1L));
results.iterator().forEachRemaining(page -> {
assertThat(page.consumedCapacity(), containsInAnyOrder(
ConsumedCapacity.builder().tableName(tableName1).capacityUnits(20.0).build(),
ConsumedCapacity.builder().tableName(tableName2).capacityUnits(10.0).build()
));
List<Record1> table1Results = page.resultsForTable(mappedTable1);
assertThat(table1Results.size(), is(2));
assertThat(table1Results.get(0).id, is(0));
assertThat(table1Results.get(1).id, is(1));
assertThat(page.resultsForTable(mappedTable2).size(), is(2));
});
}
@Test
public void notFoundRecordIgnored_withReturnConsumedCapacity() {
insertRecords();
BatchGetItemEnhancedRequest batchGetItemEnhancedRequest = batchGetItemEnhancedRequestWithNotFoundRecord()
.toBuilder()
.returnConsumedCapacity(ReturnConsumedCapacity.TOTAL)
.build();
SdkIterable<BatchGetResultPage> results = enhancedClient.batchGetItem(batchGetItemEnhancedRequest);
assertThat(results.stream().count(), is(1L));
results.iterator().forEachRemaining(page -> {
assertThat(page.consumedCapacity(), containsInAnyOrder(
ConsumedCapacity.builder().tableName(tableName1).capacityUnits(10.0).build(),
ConsumedCapacity.builder().tableName(tableName2).capacityUnits(10.0).build()
));
List<Record1> mappedTable1Results = page.resultsForTable(mappedTable1);
assertThat(mappedTable1Results.size(), is(1));
assertThat(mappedTable1Results.get(0).id, is(0));
assertThat(page.resultsForTable(mappedTable2).size(), is(2));
});
}
private BatchGetItemEnhancedRequest batchGetItemEnhancedRequestWithNotFoundRecord() {
return BatchGetItemEnhancedRequest.builder()
.readBatches(
ReadBatch.builder(Record1.class)
.mappedTableResource(mappedTable1)
.addGetItem(r -> r.key(k -> k.partitionValue(0)))
.build(),
ReadBatch.builder(Record2.class)
.mappedTableResource(mappedTable2)
.addGetItem(r -> r.key(k -> k.partitionValue(0)))
.build(),
ReadBatch.builder(Record2.class)
.mappedTableResource(mappedTable2)
.addGetItem(r -> r.key(k -> k.partitionValue(1)))
.build(),
ReadBatch.builder(Record1.class)
.mappedTableResource(mappedTable1)
.addGetItem(r -> r.key(k -> k.partitionValue(5)))
.build())
.build();
}
private BatchGetResultPageIterable getBatchGetResultPagesForBothTables() {
return getBatchGetResultPagesForBothTables(null);
}
private BatchGetResultPageIterable getBatchGetResultPagesForBothTables(ReturnConsumedCapacity returnConsumedCapacity) {
return enhancedClient.batchGetItem(r -> r.returnConsumedCapacity(returnConsumedCapacity).readBatches(
ReadBatch.builder(Record1.class)
.mappedTableResource(mappedTable1)
.addGetItem(i -> i.key(k -> k.partitionValue(0)))
.build(),
ReadBatch.builder(Record2.class)
.mappedTableResource(mappedTable2)
.addGetItem(i -> i.key(k -> k.partitionValue(0)))
.build(),
ReadBatch.builder(Record2.class)
.mappedTableResource(mappedTable2)
.addGetItem(i -> i.key(k -> k.partitionValue(1)))
.build(),
ReadBatch.builder(Record1.class)
.mappedTableResource(mappedTable1)
.addGetItem(i -> i.key(k -> k.partitionValue(1)))
.build()));
}
private static String getStringAttrValue(int nChars) {
char[] bytes = new char[nChars];
Arrays.fill(bytes, 'a');
return new String(bytes);
}
}
| 3,868 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/AnnotatedImmutableTableSchemaTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.functionaltests;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.After;
import org.junit.Test;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.ImmutableFakeItem;
import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest;
import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughput;
public class AnnotatedImmutableTableSchemaTest extends LocalDynamoDbSyncTestBase {
private static final String TABLE_NAME = "table-name";
private final DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder()
.dynamoDbClient(getDynamoDbClient())
.build();
@After
public void deleteTable() {
getDynamoDbClient().deleteTable(DeleteTableRequest.builder()
.tableName(getConcreteTableName(TABLE_NAME))
.build());
}
@Test
public void simpleItem_putAndGet() {
TableSchema<ImmutableFakeItem> tableSchema =
TableSchema.fromClass(ImmutableFakeItem.class);
DynamoDbTable<ImmutableFakeItem> mappedTable =
enhancedClient.table(getConcreteTableName(TABLE_NAME), tableSchema);
mappedTable.createTable(r -> r.provisionedThroughput(ProvisionedThroughput.builder()
.readCapacityUnits(5L)
.writeCapacityUnits(5L)
.build()));
ImmutableFakeItem immutableFakeItem = ImmutableFakeItem.builder()
.id("id123")
.attribute("test-value")
.build();
mappedTable.putItem(immutableFakeItem);
ImmutableFakeItem readItem = mappedTable.getItem(immutableFakeItem);
assertThat(readItem).isEqualTo(immutableFakeItem);
}
}
| 3,869 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/BufferingSubscriber.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.functionaltests;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
public class BufferingSubscriber<T> implements Subscriber<T> {
private final CountDownLatch latch = new CountDownLatch(1);
private final List<T> bufferedItems = new ArrayList<>();
private volatile Throwable bufferedError = null;
private volatile boolean isCompleted = false;
@Override
public void onSubscribe(Subscription subscription) {
subscription.request(Long.MAX_VALUE);
}
@Override
public void onNext(T t) {
bufferedItems.add(t);
}
@Override
public void onError(Throwable throwable) {
this.bufferedError = throwable;
this.latch.countDown();
}
@Override
public void onComplete() {
this.isCompleted = true;
this.latch.countDown();
}
public void waitForCompletion(long timeoutInMillis) {
try {
this.latch.await(timeoutInMillis, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
public List<T> bufferedItems() {
return bufferedItems;
}
public Throwable bufferedError() {
return bufferedError;
}
public boolean isCompleted() {
return isCompleted;
}
}
| 3,870 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/UpdateItemWithResponseTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.functionaltests;
import static org.assertj.core.api.Assertions.assertThat;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey;
import java.util.Objects;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema;
import software.amazon.awssdk.enhanced.dynamodb.model.UpdateItemEnhancedResponse;
import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest;
import software.amazon.awssdk.services.dynamodb.model.ReturnConsumedCapacity;
public class UpdateItemWithResponseTest extends LocalDynamoDbSyncTestBase {
private static class Record {
private Integer id;
private String stringAttr1;
private Integer getId() {
return id;
}
private Record setId(Integer id) {
this.id = id;
return this;
}
private String getStringAttr1() {
return stringAttr1;
}
private Record setStringAttr1(String stringAttr1) {
this.stringAttr1 = stringAttr1;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Record record = (Record) o;
return Objects.equals(id, record.id) && Objects.equals(stringAttr1, record.stringAttr1);
}
@Override
public int hashCode() {
return Objects.hash(id, stringAttr1);
}
}
private static final TableSchema<Record> TABLE_SCHEMA =
StaticTableSchema.builder(Record.class)
.newItemSupplier(Record::new)
.addAttribute(Integer.class, a -> a.name("id_1")
.getter(Record::getId)
.setter(Record::setId)
.tags(primaryPartitionKey()))
.addAttribute(String.class, a -> a.name("stringAttr1")
.getter(Record::getStringAttr1)
.setter(Record::setStringAttr1))
.build();
private DynamoDbEnhancedClient enhancedClient;
private DynamoDbTable<Record> mappedTable1;
@Before
public void createTable() {
enhancedClient = DynamoDbEnhancedClient.builder()
.dynamoDbClient(getDynamoDbClient())
.build();
mappedTable1 = enhancedClient.table(getConcreteTableName("table-name-1"), TABLE_SCHEMA);
mappedTable1.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput()));
}
@After
public void deleteTable() {
getDynamoDbClient().deleteTable(DeleteTableRequest.builder()
.tableName(getConcreteTableName("table-name-1"))
.build());
}
@Test
public void newValuesMapped() {
Record original = new Record().setId(1).setStringAttr1("attr");
mappedTable1.putItem(original);
Record updated = new Record().setId(1).setStringAttr1("attr2");
UpdateItemEnhancedResponse<Record> response = mappedTable1.updateItemWithResponse(r -> r.item(updated));
assertThat(response.attributes()).isEqualTo(updated);
}
@Test
public void returnConsumedCapacity_unset_consumedCapacityNull() {
Record original = new Record().setId(1).setStringAttr1("attr");
mappedTable1.putItem(original);
Record updated = new Record().setId(1).setStringAttr1("attr2");
UpdateItemEnhancedResponse<Record> response = mappedTable1.updateItemWithResponse(r -> r.item(updated));
assertThat(response.consumedCapacity()).isNull();
}
@Test
public void returnConsumedCapacity_set_consumedCapacityNotNull() {
Record original = new Record().setId(1).setStringAttr1("attr");
mappedTable1.putItem(original);
Record updated = new Record().setId(1).setStringAttr1("attr2");
UpdateItemEnhancedResponse<Record> response = mappedTable1.updateItemWithResponse(r -> r.item(updated)
.returnConsumedCapacity(ReturnConsumedCapacity.TOTAL));
assertThat(response.consumedCapacity()).isNotNull();
}
@Test
public void returnItemCollectionMetrics_unset_itemCollectionMetricsNull() {
Record original = new Record().setId(1).setStringAttr1("attr");
mappedTable1.putItem(original);
Record updated = new Record().setId(1).setStringAttr1("attr2");
UpdateItemEnhancedResponse<Record> response = mappedTable1.updateItemWithResponse(r -> r.item(updated));
assertThat(response.itemCollectionMetrics()).isNull();
}
}
| 3,871 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/UpdateExpressionTest.java | package software.amazon.awssdk.enhanced.dynamodb.functionaltests;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.After;
import org.junit.Test;
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.DynamoDbTable;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.extensions.WriteModification;
import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.RecordForUpdateExpressions;
import software.amazon.awssdk.enhanced.dynamodb.internal.operations.OperationName;
import software.amazon.awssdk.enhanced.dynamodb.internal.operations.UpdateItemOperation;
import software.amazon.awssdk.enhanced.dynamodb.internal.update.UpdateExpressionConverter;
import software.amazon.awssdk.enhanced.dynamodb.update.AddAction;
import software.amazon.awssdk.enhanced.dynamodb.update.DeleteAction;
import software.amazon.awssdk.enhanced.dynamodb.update.UpdateExpression;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.utils.CollectionUtils;
public class UpdateExpressionTest extends LocalDynamoDbSyncTestBase {
private static final Set<String> SET_ATTRIBUTE_INIT_VALUE = Stream.of("YELLOW", "BLUE", "RED", "GREEN")
.collect(Collectors.toSet());
private static final Set<String> SET_ATTRIBUTE_DELETE = Stream.of("YELLOW", "RED").collect(Collectors.toSet());
private static final String NUMBER_ATTRIBUTE_REF = "extensionNumberAttribute";
private static final long NUMBER_ATTRIBUTE_VALUE = 5L;
private static final String NUMBER_ATTRIBUTE_VALUE_REF = ":increment_value_ref";
private static final String SET_ATTRIBUTE_REF = "extensionSetAttribute";
private static final TableSchema<RecordForUpdateExpressions> TABLE_SCHEMA = TableSchema.fromClass(RecordForUpdateExpressions.class);
private DynamoDbTable<RecordForUpdateExpressions> mappedTable;
private void initClientWithExtensions(DynamoDbEnhancedClientExtension... extensions) {
DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder()
.dynamoDbClient(getDynamoDbClient())
.extensions(extensions)
.build();
mappedTable = enhancedClient.table(getConcreteTableName("table-name"), TABLE_SCHEMA);
mappedTable.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput()));
}
@After
public void deleteTable() {
getDynamoDbClient().deleteTable(r -> r.tableName(getConcreteTableName("table-name")));
}
@Test
public void attribute_notInPojo_notFilteredInExtension_ignoresNulls_updatesNormally() {
initClientWithExtensions(new ItemPreservingUpdateExtension());
RecordForUpdateExpressions record = createRecordWithoutExtensionAttributes();
mappedTable.updateItem(r -> r.item(record).ignoreNulls(true));
RecordForUpdateExpressions persistedRecord = mappedTable.getItem(record);
assertThat(persistedRecord.getStringAttribute()).isEqualTo("init");
assertThat(persistedRecord.getExtensionNumberAttribute()).isEqualTo(5L);
}
/**
* This test case represents the most likely extension UpdateExpression use case;
* an attribute is set in the extensions and isn't present in the request POJO item, and there is no change in
* the request to set ignoreNull to true.
* <p>
* By default, ignorNull is false, so attributes that aren't set on the request are deleted from the DDB table through
* the updateItemOperation generating REMOVE actions for those attributes. This is prevented by
* {@link UpdateItemOperation} using {@link UpdateExpressionConverter#findAttributeNames(UpdateExpression)}
* to not create REMOVE actions attributes it finds referenced in an extension UpdateExpression.
* Therefore, this use case updates normally.
*/
@Test
public void attribute_notInPojo_notFilteredInExtension_defaultSetsNull_updatesNormally() {
initClientWithExtensions(new ItemPreservingUpdateExtension());
RecordForUpdateExpressions record = createRecordWithoutExtensionAttributes();
mappedTable.updateItem(r -> r.item(record));
RecordForUpdateExpressions persistedRecord = mappedTable.getItem(record);
assertThat(persistedRecord.getStringAttribute()).isEqualTo("init");
assertThat(persistedRecord.getExtensionNumberAttribute()).isEqualTo(5L);
}
@Test
public void attribute_notInPojo_filteredInExtension_ignoresNulls_updatesNormally() {
initClientWithExtensions(new ItemFilteringUpdateExtension());
RecordForUpdateExpressions record = createRecordWithoutExtensionAttributes();
record.setExtensionSetAttribute(SET_ATTRIBUTE_INIT_VALUE);
mappedTable.putItem(record);
record.setStringAttribute("init");
mappedTable.updateItem(r -> r.item(record).ignoreNulls(true));
verifySetAttribute(record);
}
@Test
public void attribute_notInPojo_filteredInExtension_defaultSetsNull_updatesNormally() {
initClientWithExtensions(new ItemFilteringUpdateExtension());
RecordForUpdateExpressions record = createRecordWithoutExtensionAttributes();
record.setExtensionSetAttribute(SET_ATTRIBUTE_INIT_VALUE);
mappedTable.putItem(record);
record.setStringAttribute("init");
mappedTable.updateItem(r -> r.item(record));
verifySetAttribute(record);
}
/**
* The extension adds an UpdateExpression with the number attribute, and the request
* results in an UpdateExpression with the number attribute. This causes DDB to reject the request.
*/
@Test
public void attribute_inPojo_notFilteredInExtension_ignoresNulls_ddbError() {
initClientWithExtensions(new ItemPreservingUpdateExtension());
RecordForUpdateExpressions record = createRecordWithoutExtensionAttributes();
record.setExtensionNumberAttribute(100L);
verifyDDBError(record, true);
}
@Test
public void attribute_inPojo_notFilteredInExtension_defaultSetsNull_ddbError() {
initClientWithExtensions(new ItemPreservingUpdateExtension());
RecordForUpdateExpressions record = createRecordWithoutExtensionAttributes();
record.setExtensionNumberAttribute(100L);
verifyDDBError(record, false);
}
/**
* When the extension filters the transact item representing the request POJO attributes and removes the attribute
* from the POJO if it's there, only the extension UpdateExpression will reference the attribute and no DDB
* conflict results.
*/
@Test
public void attribute_inPojo_filteredInExtension_ignoresNulls_updatesNormally() {
initClientWithExtensions(new ItemFilteringUpdateExtension());
RecordForUpdateExpressions record = createRecordWithoutExtensionAttributes();
record.setExtensionSetAttribute(SET_ATTRIBUTE_INIT_VALUE);
mappedTable.putItem(record);
record.setStringAttribute("init");
record.setExtensionSetAttribute(Stream.of("PURPLE").collect(Collectors.toSet()));
mappedTable.updateItem(r -> r.item(record).ignoreNulls(true));
verifySetAttribute(record);
}
@Test
public void attribute_inPojo_filteredInExtension_defaultSetsNull_updatesNormally() {
initClientWithExtensions(new ItemFilteringUpdateExtension());
RecordForUpdateExpressions record = createRecordWithoutExtensionAttributes();
record.setExtensionSetAttribute(SET_ATTRIBUTE_INIT_VALUE);
mappedTable.putItem(record);
record.setStringAttribute("init");
record.setExtensionSetAttribute(Stream.of("PURPLE").collect(Collectors.toSet()));
mappedTable.updateItem(r -> r.item(record));
verifySetAttribute(record);
}
@Test
public void chainedExtensions_noDuplicates_ignoresNulls_updatesNormally() {
initClientWithExtensions(new ItemPreservingUpdateExtension(), new ItemFilteringUpdateExtension());
RecordForUpdateExpressions putRecord = createRecordWithoutExtensionAttributes();
putRecord.setExtensionNumberAttribute(11L);
putRecord.setExtensionSetAttribute(SET_ATTRIBUTE_INIT_VALUE);
mappedTable.putItem(putRecord);
RecordForUpdateExpressions updateRecord = createRecordWithoutExtensionAttributes();
updateRecord.setStringAttribute("updated");
mappedTable.updateItem(r -> r.item(updateRecord).ignoreNulls(true));
Set<String> expectedSetExtensionAttribute = Stream.of("BLUE", "GREEN").collect(Collectors.toSet());
RecordForUpdateExpressions persistedRecord = mappedTable.getItem(mappedTable.keyFrom(putRecord));
assertThat(persistedRecord.getExtensionNumberAttribute()).isEqualTo(16L);
assertThat(persistedRecord.getExtensionSetAttribute()).isEqualTo(expectedSetExtensionAttribute);
}
@Test
public void chainedExtensions_duplicateAttributes_sameValue_sameValueRef_ddbError() {
initClientWithExtensions(new ItemPreservingUpdateExtension(), new ItemPreservingUpdateExtension());
verifyDDBError(createRecordWithoutExtensionAttributes(), false);
}
@Test
public void chainedExtensions_duplicateAttributes_sameValue_differentValueRef_ddbError() {
initClientWithExtensions(new ItemPreservingUpdateExtension(), new ItemPreservingUpdateExtension(NUMBER_ATTRIBUTE_VALUE, ":ref"));
verifyDDBError(createRecordWithoutExtensionAttributes(), false);
}
@Test
public void chainedExtensions_duplicateAttributes_differentValue_differentValueRef_ddbError() {
initClientWithExtensions(new ItemPreservingUpdateExtension(), new ItemPreservingUpdateExtension(13L, ":ref"));
verifyDDBError(createRecordWithoutExtensionAttributes(), false);
}
@Test
public void chainedExtensions_duplicateAttributes_differentValue_sameValueRef_operationMergeError() {
initClientWithExtensions(new ItemPreservingUpdateExtension(), new ItemPreservingUpdateExtension(10L, NUMBER_ATTRIBUTE_VALUE_REF));
RecordForUpdateExpressions record = createRecordWithoutExtensionAttributes();
assertThatThrownBy(() ->mappedTable.updateItem(r -> r.item(record)))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Attempt to coalesce two expressions with conflicting expression values")
.hasMessageContaining(NUMBER_ATTRIBUTE_VALUE_REF);
}
@Test
public void chainedExtensions_duplicateAttributes_invalidValueRef_operationMergeError() {
initClientWithExtensions(new ItemPreservingUpdateExtension(), new ItemPreservingUpdateExtension(10L, "illegal"));
RecordForUpdateExpressions record = createRecordWithoutExtensionAttributes();
assertThatThrownBy(() ->mappedTable.updateItem(r -> r.item(record)))
.isInstanceOf(DynamoDbException.class)
.hasMessageContaining("ExpressionAttributeValues contains invalid key")
.hasMessageContaining("illegal");
}
private void verifyDDBError(RecordForUpdateExpressions record, boolean ignoreNulls) {
assertThatThrownBy(() -> mappedTable.updateItem(r -> r.item(record).ignoreNulls(ignoreNulls)))
.isInstanceOf(DynamoDbException.class)
.hasMessageContaining("Two document paths")
.hasMessageContaining(NUMBER_ATTRIBUTE_REF);
}
private void verifySetAttribute(RecordForUpdateExpressions record) {
Set<String> expectedAttribute = Stream.of("BLUE", "GREEN").collect(Collectors.toSet());
RecordForUpdateExpressions persistedRecord = mappedTable.getItem(record);
assertThat(persistedRecord.getStringAttribute()).isEqualTo("init");
assertThat(persistedRecord.getExtensionNumberAttribute()).isNull();
assertThat(persistedRecord.getExtensionSetAttribute()).isEqualTo(expectedAttribute);
}
private RecordForUpdateExpressions createRecordWithoutExtensionAttributes() {
RecordForUpdateExpressions record = new RecordForUpdateExpressions();
record.setId("1");
record.setStringAttribute("init");
return record;
}
private static final class ItemPreservingUpdateExtension implements DynamoDbEnhancedClientExtension {
private long incrementValue;
private String valueRef;
private ItemPreservingUpdateExtension() {
this(NUMBER_ATTRIBUTE_VALUE, NUMBER_ATTRIBUTE_VALUE_REF);
}
private ItemPreservingUpdateExtension(long incrementValue, String valueRef) {
this.incrementValue = incrementValue;
this.valueRef = valueRef;
}
@Override
public WriteModification beforeWrite(DynamoDbExtensionContext.BeforeWrite context) {
UpdateExpression updateExpression =
UpdateExpression.builder().addAction(addToNumericAttribute(NUMBER_ATTRIBUTE_REF)).build();
return WriteModification.builder().updateExpression(updateExpression).build();
}
private AddAction addToNumericAttribute(String attributeName) {
AttributeValue actualValue = AttributeValue.builder().n(Long.toString(incrementValue)).build();
return AddAction.builder()
.path(attributeName)
.value(valueRef)
.putExpressionValue(valueRef, actualValue)
.build();
}
}
private static final class ItemFilteringUpdateExtension implements DynamoDbEnhancedClientExtension {
@Override
public WriteModification beforeWrite(DynamoDbExtensionContext.BeforeWrite context) {
Map<String, AttributeValue> transformedItemMap = context.items();
if ( context.operationName() == OperationName.UPDATE_ITEM) {
List<String> attributesToFilter = Arrays.asList(SET_ATTRIBUTE_REF);
transformedItemMap = CollectionUtils.filterMap(transformedItemMap, e -> !attributesToFilter.contains(e.getKey()));
}
UpdateExpression updateExpression =
UpdateExpression.builder().addAction(deleteFromList(SET_ATTRIBUTE_REF)).build();
return WriteModification.builder()
.updateExpression(updateExpression)
.transformedItem(transformedItemMap)
.build();
}
private DeleteAction deleteFromList(String attributeName) {
AttributeValue actualValue = AttributeValue.builder().ss(SET_ATTRIBUTE_DELETE).build();
String valueName = ":toDelete";
return DeleteAction.builder()
.path(attributeName)
.value(valueName)
.putExpressionValue(valueName, actualValue)
.build();
}
}
}
| 3,872 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/AsyncTransactWriteItemsTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.functionaltests;
import static java.util.Collections.singletonMap;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.fail;
import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.stringValue;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CompletionException;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbAsyncTable;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedAsyncClient;
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.client.DefaultDynamoDbEnhancedAsyncClient;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema;
import software.amazon.awssdk.enhanced.dynamodb.model.ConditionCheck;
import software.amazon.awssdk.enhanced.dynamodb.model.TransactWriteItemsEnhancedRequest;
import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest;
import software.amazon.awssdk.services.dynamodb.model.TransactionCanceledException;
public class AsyncTransactWriteItemsTest extends LocalDynamoDbAsyncTestBase {
private static class Record1 {
private Integer id;
private String attribute;
private Integer getId() {
return id;
}
private Record1 setId(Integer id) {
this.id = id;
return this;
}
private String getAttribute() {
return attribute;
}
private Record1 setAttribute(String attribute) {
this.attribute = attribute;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Record1 record1 = (Record1) o;
return Objects.equals(id, record1.id) &&
Objects.equals(attribute, record1.attribute);
}
@Override
public int hashCode() {
return Objects.hash(id, attribute);
}
}
private static class Record2 {
private Integer id;
private String attribute;
private Integer getId() {
return id;
}
private Record2 setId(Integer id) {
this.id = id;
return this;
}
private String getAttribute() {
return attribute;
}
private Record2 setAttribute(String attribute) {
this.attribute = attribute;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Record2 record2 = (Record2) o;
return Objects.equals(id, record2.id) &&
Objects.equals(attribute, record2.attribute);
}
@Override
public int hashCode() {
return Objects.hash(id, attribute);
}
}
private static final TableSchema<Record1> TABLE_SCHEMA_1 =
StaticTableSchema.builder(Record1.class)
.newItemSupplier(Record1::new)
.addAttribute(Integer.class, a -> a.name("id_1")
.getter(Record1::getId)
.setter(Record1::setId)
.tags(primaryPartitionKey()))
.addAttribute(String.class, a -> a.name("attribute")
.getter(Record1::getAttribute)
.setter(Record1::setAttribute))
.build();
private static final TableSchema<Record2> TABLE_SCHEMA_2 =
StaticTableSchema.builder(Record2.class)
.newItemSupplier(Record2::new)
.addAttribute(Integer.class, a -> a.name("id_2")
.getter(Record2::getId)
.setter(Record2::setId)
.tags(primaryPartitionKey()))
.addAttribute(String.class, a -> a.name("attribute")
.getter(Record2::getAttribute)
.setter(Record2::setAttribute))
.build();
private DynamoDbEnhancedAsyncClient enhancedAsyncClient =
DefaultDynamoDbEnhancedAsyncClient.builder()
.dynamoDbClient(getDynamoDbAsyncClient())
.build();
private DynamoDbAsyncTable<Record1> mappedTable1 = enhancedAsyncClient.table(getConcreteTableName("table-name-1"),
TABLE_SCHEMA_1);
private DynamoDbAsyncTable<Record2> mappedTable2 = enhancedAsyncClient.table(getConcreteTableName("table-name-2"),
TABLE_SCHEMA_2);
private static final List<Record1> RECORDS_1 =
IntStream.range(0, 2)
.mapToObj(i -> new Record1().setId(i).setAttribute(Integer.toString(i)))
.collect(Collectors.toList());
private static final List<Record2> RECORDS_2 =
IntStream.range(0, 2)
.mapToObj(i -> new Record2().setId(i).setAttribute(Integer.toString(i)))
.collect(Collectors.toList());
@Before
public void createTable() {
mappedTable1.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput())).join();
mappedTable2.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput())).join();
}
@After
public void deleteTable() {
getDynamoDbAsyncClient().deleteTable(DeleteTableRequest.builder()
.tableName(getConcreteTableName("table-name-1"))
.build()).join();
getDynamoDbAsyncClient().deleteTable(DeleteTableRequest.builder()
.tableName(getConcreteTableName("table-name-2"))
.build()).join();
}
@Test
public void singlePut() {
enhancedAsyncClient.transactWriteItems(
TransactWriteItemsEnhancedRequest.builder()
.addPutItem(mappedTable1, RECORDS_1.get(0))
.build()).join();
Record1 record = mappedTable1.getItem(r -> r.key(k -> k.partitionValue(0))).join();
assertThat(record, is(RECORDS_1.get(0)));
}
@Test
public void multiplePut() {
enhancedAsyncClient.transactWriteItems(
TransactWriteItemsEnhancedRequest.builder()
.addPutItem(mappedTable1, RECORDS_1.get(0))
.addPutItem(mappedTable2, RECORDS_2.get(0))
.build()).join();
Record1 record1 = mappedTable1.getItem(r -> r.key(k -> k.partitionValue(0))).join();
Record2 record2 = mappedTable2.getItem(r -> r.key(k -> k.partitionValue(0))).join();
assertThat(record1, is(RECORDS_1.get(0)));
assertThat(record2, is(RECORDS_2.get(0)));
}
@Test
public void singleUpdate() {
enhancedAsyncClient.transactWriteItems(
TransactWriteItemsEnhancedRequest.builder()
.addUpdateItem(mappedTable1, RECORDS_1.get(0))
.build()).join();
Record1 record = mappedTable1.getItem(r -> r.key(k -> k.partitionValue(0))).join();
assertThat(record, is(RECORDS_1.get(0)));
}
@Test
public void multipleUpdate() {
enhancedAsyncClient.transactWriteItems(
TransactWriteItemsEnhancedRequest.builder()
.addUpdateItem(mappedTable1, RECORDS_1.get(0))
.addUpdateItem(mappedTable2, RECORDS_2.get(0))
.build()).join();
Record1 record1 = mappedTable1.getItem(r -> r.key(k -> k.partitionValue(0))).join();
Record2 record2 = mappedTable2.getItem(r -> r.key(k -> k.partitionValue(0))).join();
assertThat(record1, is(RECORDS_1.get(0)));
assertThat(record2, is(RECORDS_2.get(0)));
}
@Test
public void singleDelete() {
mappedTable1.putItem(r -> r.item(RECORDS_1.get(0))).join();
enhancedAsyncClient.transactWriteItems(
TransactWriteItemsEnhancedRequest.builder()
.addDeleteItem(mappedTable1, RECORDS_1.get(0))
.build()).join();
Record1 record = mappedTable1.getItem(r -> r.key(k -> k.partitionValue(0))).join();
assertThat(record, is(nullValue()));
}
@Test
public void multipleDelete() {
mappedTable1.putItem(r -> r.item(RECORDS_1.get(0))).join();
mappedTable2.putItem(r -> r.item(RECORDS_2.get(0))).join();
enhancedAsyncClient.transactWriteItems(
TransactWriteItemsEnhancedRequest.builder()
.addDeleteItem(mappedTable1, RECORDS_1.get(0))
.addDeleteItem(mappedTable2, RECORDS_2.get(0))
.build()).join();
Record1 record1 = mappedTable1.getItem(r -> r.key(k -> k.partitionValue(0))).join();
Record2 record2 = mappedTable2.getItem(r -> r.key(k -> k.partitionValue(0))).join();
assertThat(record1, is(nullValue()));
assertThat(record2, is(nullValue()));
}
@Test
public void singleConditionCheck() {
mappedTable1.putItem(r -> r.item(RECORDS_1.get(0))).join();
Expression conditionExpression = Expression.builder()
.expression("#attribute = :attribute")
.expressionValues(singletonMap(":attribute", stringValue("0")))
.expressionNames(singletonMap("#attribute", "attribute"))
.build();
Key key = Key.builder().partitionValue(0).build();
enhancedAsyncClient.transactWriteItems(
TransactWriteItemsEnhancedRequest.builder()
.addConditionCheck(mappedTable1, ConditionCheck.builder()
.key(key)
.conditionExpression(conditionExpression)
.build())
.build()).join();
}
@Test
public void multiConditionCheck() {
mappedTable1.putItem(r -> r.item(RECORDS_1.get(0))).join();
mappedTable2.putItem(r -> r.item(RECORDS_2.get(0))).join();
Expression conditionExpression = Expression.builder()
.expression("#attribute = :attribute")
.expressionValues(singletonMap(":attribute", stringValue("0")))
.expressionNames(singletonMap("#attribute", "attribute"))
.build();
Key key1 = Key.builder().partitionValue(0).build();
Key key2 = Key.builder().partitionValue(0).build();
enhancedAsyncClient.transactWriteItems(
TransactWriteItemsEnhancedRequest.builder()
.addConditionCheck(mappedTable1, ConditionCheck.builder()
.key(key1)
.conditionExpression(conditionExpression)
.build())
.addConditionCheck(mappedTable2, ConditionCheck.builder()
.key(key2)
.conditionExpression(conditionExpression)
.build())
.build()).join();
}
@Test
public void mixedCommands() {
mappedTable1.putItem(r -> r.item(RECORDS_1.get(0))).join();
mappedTable2.putItem(r -> r.item(RECORDS_2.get(0))).join();
Expression conditionExpression = Expression.builder()
.expression("#attribute = :attribute")
.expressionValues(singletonMap(":attribute", stringValue("0")))
.expressionNames(singletonMap("#attribute", "attribute"))
.build();
Key key = Key.builder().partitionValue(0).build();
TransactWriteItemsEnhancedRequest transactWriteItemsEnhancedRequest =
TransactWriteItemsEnhancedRequest.builder()
.addConditionCheck(mappedTable1, ConditionCheck.builder()
.key(key)
.conditionExpression(conditionExpression)
.build())
.addPutItem(mappedTable2, RECORDS_2.get(1))
.addUpdateItem(mappedTable1, RECORDS_1.get(1))
.addDeleteItem(mappedTable2, RECORDS_2.get(0))
.build();
enhancedAsyncClient.transactWriteItems(transactWriteItemsEnhancedRequest).join();
assertThat(mappedTable1.getItem(r -> r.key(k -> k.partitionValue(1))).join(), is(RECORDS_1.get(1)));
assertThat(mappedTable2.getItem(r -> r.key(k -> k.partitionValue(0))).join(), is(nullValue()));
assertThat(mappedTable2.getItem(r -> r.key(k -> k.partitionValue(1))).join(), is(RECORDS_2.get(1)));
}
@Test
public void mixedCommands_conditionCheckFailsTransaction() {
mappedTable1.putItem(r -> r.item(RECORDS_1.get(0))).join();
mappedTable2.putItem(r -> r.item(RECORDS_2.get(0))).join();
Expression conditionExpression = Expression.builder()
.expression("#attribute = :attribute")
.expressionValues(singletonMap(":attribute", stringValue("1")))
.expressionNames(singletonMap("#attribute", "attribute"))
.build();
Key key = Key.builder().partitionValue(0).build();
TransactWriteItemsEnhancedRequest transactWriteItemsEnhancedRequest =
TransactWriteItemsEnhancedRequest.builder()
.addPutItem(mappedTable2, RECORDS_2.get(1))
.addUpdateItem(mappedTable1, RECORDS_1.get(1))
.addConditionCheck(mappedTable1, ConditionCheck.builder()
.key(key)
.conditionExpression(conditionExpression)
.build())
.addDeleteItem(mappedTable2, RECORDS_2.get(0))
.build();
try {
enhancedAsyncClient.transactWriteItems(transactWriteItemsEnhancedRequest).join();
fail("Expected CompletionException to be thrown");
} catch (CompletionException e) {
assertThat(e.getCause(), instanceOf(TransactionCanceledException.class));
}
assertThat(mappedTable1.getItem(r -> r.key(k -> k.partitionValue(1))).join(), is(nullValue()));
assertThat(mappedTable2.getItem(r -> r.key(k -> k.partitionValue(0))).join(), is(RECORDS_2.get(0)));
assertThat(mappedTable2.getItem(r -> r.key(k -> k.partitionValue(1))).join(), is(nullValue()));
}
}
| 3,873 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/FailedConversionSyncTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.functionaltests;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.util.Iterator;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
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.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeEnum;
import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeEnumRecord;
import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeEnumShortenedRecord;
import software.amazon.awssdk.enhanced.dynamodb.model.Page;
import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest;
public class FailedConversionSyncTest extends LocalDynamoDbSyncTestBase {
private static final TableSchema<FakeEnumRecord> TABLE_SCHEMA = TableSchema.fromClass(FakeEnumRecord.class);
private static final TableSchema<FakeEnumShortenedRecord> SHORT_TABLE_SCHEMA =
TableSchema.fromClass(FakeEnumShortenedRecord.class);
private final DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder()
.dynamoDbClient(getDynamoDbClient())
.build();
private final DynamoDbTable<FakeEnumRecord> mappedTable =
enhancedClient.table(getConcreteTableName("table-name"), TABLE_SCHEMA);
private final DynamoDbTable<FakeEnumShortenedRecord> mappedShortTable =
enhancedClient.table(getConcreteTableName("table-name"), SHORT_TABLE_SCHEMA);
@Rule
public ExpectedException exception = ExpectedException.none();
@Before
public void createTable() {
mappedTable.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput()));
}
@After
public void deleteTable() {
getDynamoDbClient().deleteTable(DeleteTableRequest.builder()
.tableName(getConcreteTableName("table-name"))
.build());
}
@Test
public void exceptionOnRead() {
FakeEnumRecord record = new FakeEnumRecord();
record.setId("123");
record.setEnumAttribute(FakeEnum.TWO);
mappedTable.putItem(record);
assertThatThrownBy(() -> mappedShortTable.getItem(Key.builder().partitionValue("123").build()))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("TWO")
.hasMessageContaining("FakeEnumShortened");
}
@Test
public void iterableExceptionOnRead() {
FakeEnumRecord record = new FakeEnumRecord();
record.setId("1");
record.setEnumAttribute(FakeEnum.ONE);
mappedTable.putItem(record);
record.setId("2");
record.setEnumAttribute(FakeEnum.TWO);
mappedTable.putItem(record);
Iterator<Page<FakeEnumShortenedRecord>> results = mappedShortTable.scan(r -> r.limit(1)).iterator();
assertThatThrownBy(() -> {
// We can't guarantee the order they will be returned
results.next();
results.next();
}).isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("TWO")
.hasMessageContaining("FakeEnumShortened");
}
}
| 3,874 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/BasicCrudTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.functionaltests;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.stringValue;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primarySortKey;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.secondaryPartitionKey;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.secondarySortKey;
import java.util.Objects;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable;
import software.amazon.awssdk.enhanced.dynamodb.Expression;
import software.amazon.awssdk.enhanced.dynamodb.Key;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema;
import software.amazon.awssdk.enhanced.dynamodb.model.DeleteItemEnhancedRequest;
import software.amazon.awssdk.enhanced.dynamodb.model.EnhancedGlobalSecondaryIndex;
import software.amazon.awssdk.enhanced.dynamodb.model.PutItemEnhancedRequest;
import software.amazon.awssdk.enhanced.dynamodb.model.UpdateItemEnhancedRequest;
import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException;
import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest;
import software.amazon.awssdk.services.dynamodb.model.ProjectionType;
public class BasicCrudTest extends LocalDynamoDbSyncTestBase {
private static final String ATTRIBUTE_NAME_WITH_SPECIAL_CHARACTERS = "a*t:t.r-i#bute +3/4(&?5=@)<6>!ch$ar%";
private static class Record {
private String id;
private String sort;
private String attribute;
private String attribute2;
private String attribute3;
private String getId() {
return id;
}
private Record setId(String id) {
this.id = id;
return this;
}
private String getSort() {
return sort;
}
private Record setSort(String sort) {
this.sort = sort;
return this;
}
private String getAttribute() {
return attribute;
}
private Record setAttribute(String attribute) {
this.attribute = attribute;
return this;
}
private String getAttribute2() {
return attribute2;
}
private Record setAttribute2(String attribute2) {
this.attribute2 = attribute2;
return this;
}
private String getAttribute3() {
return attribute3;
}
private Record setAttribute3(String attribute3) {
this.attribute3 = attribute3;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Record record = (Record) o;
return Objects.equals(id, record.id) &&
Objects.equals(sort, record.sort) &&
Objects.equals(attribute, record.attribute) &&
Objects.equals(attribute2, record.attribute2) &&
Objects.equals(attribute3, record.attribute3);
}
@Override
public int hashCode() {
return Objects.hash(id, sort, attribute, attribute2, attribute3);
}
}
private static class ShortRecord {
private String id;
private String sort;
private String attribute;
private String getId() {
return id;
}
private ShortRecord setId(String id) {
this.id = id;
return this;
}
private String getSort() {
return sort;
}
private ShortRecord setSort(String sort) {
this.sort = sort;
return this;
}
private String getAttribute() {
return attribute;
}
private ShortRecord setAttribute(String attribute) {
this.attribute = attribute;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ShortRecord that = (ShortRecord) o;
return Objects.equals(id, that.id) &&
Objects.equals(sort, that.sort) &&
Objects.equals(attribute, that.attribute);
}
@Override
public int hashCode() {
return Objects.hash(id, sort, attribute);
}
}
private static final TableSchema<Record> TABLE_SCHEMA =
StaticTableSchema.builder(Record.class)
.newItemSupplier(Record::new)
.addAttribute(String.class, a -> a.name("id")
.getter(Record::getId)
.setter(Record::setId)
.tags(primaryPartitionKey()))
.addAttribute(String.class, a -> a.name("sort")
.getter(Record::getSort)
.setter(Record::setSort)
.tags(primarySortKey()))
.addAttribute(String.class, a -> a.name("attribute")
.getter(Record::getAttribute)
.setter(Record::setAttribute))
.addAttribute(String.class, a -> a.name("attribute2*")
.getter(Record::getAttribute2)
.setter(Record::setAttribute2)
.tags(secondaryPartitionKey("gsi_1")))
.addAttribute(String.class, a -> a.name(ATTRIBUTE_NAME_WITH_SPECIAL_CHARACTERS)
.getter(Record::getAttribute3)
.setter(Record::setAttribute3)
.tags(secondarySortKey("gsi_1")))
.build();
private static final TableSchema<ShortRecord> SHORT_TABLE_SCHEMA =
StaticTableSchema.builder(ShortRecord.class)
.newItemSupplier(ShortRecord::new)
.addAttribute(String.class, a -> a.name("id")
.getter(ShortRecord::getId)
.setter(ShortRecord::setId)
.tags(primaryPartitionKey()))
.addAttribute(String.class, a -> a.name("sort")
.getter(ShortRecord::getSort)
.setter(ShortRecord::setSort)
.tags(primarySortKey()))
.addAttribute(String.class, a -> a.name("attribute")
.getter(ShortRecord::getAttribute)
.setter(ShortRecord::setAttribute))
.build();
private DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder()
.dynamoDbClient(getDynamoDbClient())
.build();
private DynamoDbTable<Record> mappedTable = enhancedClient.table(getConcreteTableName("table-name"), TABLE_SCHEMA);
private DynamoDbTable<ShortRecord> mappedShortTable = enhancedClient.table(getConcreteTableName("table-name"),
SHORT_TABLE_SCHEMA);
@Rule
public ExpectedException exception = ExpectedException.none();
@Before
public void createTable() {
mappedTable.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput())
.globalSecondaryIndices(
EnhancedGlobalSecondaryIndex.builder()
.indexName("gsi_1")
.projection(p -> p.projectionType(ProjectionType.ALL))
.provisionedThroughput(getDefaultProvisionedThroughput())
.build()));
}
@After
public void deleteTable() {
getDynamoDbClient().deleteTable(DeleteTableRequest.builder()
.tableName(getConcreteTableName("table-name"))
.build());
}
@Test
public void putThenGetItemUsingKey() {
Record record = new Record()
.setId("id-value")
.setSort("sort-value")
.setAttribute("one")
.setAttribute2("two")
.setAttribute3("three");
mappedTable.putItem(r -> r.item(record));
Record result = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id-value").sortValue("sort-value")));
assertThat(result, is(record));
}
@Test
public void putThenGetItemUsingKeyItem() {
Record record = new Record()
.setId("id-value")
.setSort("sort-value")
.setAttribute("one")
.setAttribute2("two")
.setAttribute3("three");
mappedTable.putItem(r -> r.item(record));
Record keyItem = new Record();
keyItem.setId("id-value");
keyItem.setSort("sort-value");
Record result = mappedTable.getItem(keyItem);
assertThat(result, is(record));
}
@Test
public void getNonExistentItem() {
Record result = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id-value").sortValue("sort-value")));
assertThat(result, is(nullValue()));
}
@Test
public void putTwiceThenGetItem() {
Record record = new Record()
.setId("id-value")
.setSort("sort-value")
.setAttribute("one")
.setAttribute2("two")
.setAttribute3("three");
mappedTable.putItem(r -> r.item(record));
Record record2 = new Record()
.setId("id-value")
.setSort("sort-value")
.setAttribute("four")
.setAttribute2("five")
.setAttribute3("six");
mappedTable.putItem(r -> r.item(record2));
Record result = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id-value").sortValue("sort-value")));
assertThat(result, is(record2));
}
@Test
public void putThenDeleteItem_usingShortcutForm() {
Record record = new Record()
.setId("id-value")
.setSort("sort-value")
.setAttribute("one")
.setAttribute2("two")
.setAttribute3("three");
mappedTable.putItem(record);
Record beforeDeleteResult =
mappedTable.deleteItem(Key.builder().partitionValue("id-value").sortValue("sort-value").build());
Record afterDeleteResult =
mappedTable.getItem(Key.builder().partitionValue("id-value").sortValue("sort-value").build());
assertThat(beforeDeleteResult, is(record));
assertThat(afterDeleteResult, is(nullValue()));
}
@Test
public void putThenDeleteItem_usingKeyItemForm() {
Record record = new Record()
.setId("id-value")
.setSort("sort-value")
.setAttribute("one")
.setAttribute2("two")
.setAttribute3("three");
mappedTable.putItem(record);
Record beforeDeleteResult =
mappedTable.deleteItem(record);
Record afterDeleteResult =
mappedTable.getItem(Key.builder().partitionValue("id-value").sortValue("sort-value").build());
assertThat(beforeDeleteResult, is(record));
assertThat(afterDeleteResult, is(nullValue()));
}
@Test
public void putWithConditionThatSucceeds() {
Record record = new Record()
.setId("id-value")
.setSort("sort-value")
.setAttribute("one")
.setAttribute2("two")
.setAttribute3("three");
mappedTable.putItem(r -> r.item(record));
record.setAttribute("four");
Expression conditionExpression = Expression.builder()
.expression("#key = :value OR #key1 = :value1")
.putExpressionName("#key", "attribute")
.putExpressionName("#key1", ATTRIBUTE_NAME_WITH_SPECIAL_CHARACTERS)
.putExpressionValue(":value", stringValue("wrong"))
.putExpressionValue(":value1", stringValue("three"))
.build();
mappedTable.putItem(PutItemEnhancedRequest.builder(Record.class)
.item(record)
.conditionExpression(conditionExpression).build());
Record result = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id-value").sortValue("sort-value")));
assertThat(result, is(record));
}
@Test
public void putWithConditionThatFails() {
Record record = new Record()
.setId("id-value")
.setSort("sort-value")
.setAttribute("one")
.setAttribute2("two")
.setAttribute3("three");
mappedTable.putItem(r -> r.item(record));
record.setAttribute("four");
Expression conditionExpression = Expression.builder()
.expression("#key = :value OR #key1 = :value1")
.putExpressionName("#key", "attribute")
.putExpressionName("#key1", ATTRIBUTE_NAME_WITH_SPECIAL_CHARACTERS)
.putExpressionValue(":value", stringValue("wrong"))
.putExpressionValue(":value1", stringValue("wrong"))
.build();
exception.expect(ConditionalCheckFailedException.class);
mappedTable.putItem(PutItemEnhancedRequest.builder(Record.class)
.item(record)
.conditionExpression(conditionExpression).build());
}
@Test
public void deleteNonExistentItem() {
Record result = mappedTable.deleteItem(r -> r.key(k -> k.partitionValue("id-value").sortValue("sort-value")));
assertThat(result, is(nullValue()));
}
@Test
public void deleteWithConditionThatSucceeds() {
Record record = new Record()
.setId("id-value")
.setSort("sort-value")
.setAttribute("one")
.setAttribute2("two")
.setAttribute3("three");
mappedTable.putItem(r -> r.item(record));
Expression conditionExpression = Expression.builder()
.expression("#key = :value OR #key1 = :value1")
.putExpressionName("#key", "attribute")
.putExpressionName("#key1", ATTRIBUTE_NAME_WITH_SPECIAL_CHARACTERS)
.putExpressionValue(":value", stringValue("wrong"))
.putExpressionValue(":value1", stringValue("three"))
.build();
Key key = mappedTable.keyFrom(record);
mappedTable.deleteItem(DeleteItemEnhancedRequest.builder().key(key).conditionExpression(conditionExpression).build());
Record result = mappedTable.getItem(r -> r.key(key));
assertThat(result, is(nullValue()));
}
@Test
public void deleteWithConditionThatFails() {
Record record = new Record()
.setId("id-value")
.setSort("sort-value")
.setAttribute("one")
.setAttribute2("two")
.setAttribute3("three");
mappedTable.putItem(r -> r.item(record));
Expression conditionExpression = Expression.builder()
.expression("#key = :value OR #key1 = :value1")
.putExpressionName("#key", "attribute")
.putExpressionName("#key1", ATTRIBUTE_NAME_WITH_SPECIAL_CHARACTERS)
.putExpressionValue(":value", stringValue("wrong"))
.putExpressionValue(":value1", stringValue("wrong"))
.build();
exception.expect(ConditionalCheckFailedException.class);
mappedTable.deleteItem(DeleteItemEnhancedRequest.builder().key(mappedTable.keyFrom(record))
.conditionExpression(conditionExpression)
.build());
}
@Test
public void updateOverwriteCompleteRecord_usingShortcutForm() {
Record record = new Record()
.setId("id-value")
.setSort("sort-value")
.setAttribute("one")
.setAttribute2("two")
.setAttribute3("three");
mappedTable.putItem(record);
Record record2 = new Record()
.setId("id-value")
.setSort("sort-value")
.setAttribute("four")
.setAttribute2("five")
.setAttribute3("six");
Record result = mappedTable.updateItem(record2);
assertThat(result, is(record2));
}
@Test
public void updateCreatePartialRecord() {
Record record = new Record()
.setId("id-value")
.setSort("sort-value")
.setAttribute("one");
Record result = mappedTable.updateItem(r -> r.item(record));
assertThat(result, is(record));
}
@Test
public void updateCreateKeyOnlyRecord() {
Record record = new Record()
.setId("id-value")
.setSort("sort-value");
Record result = mappedTable.updateItem(r -> r.item(record));
assertThat(result, is(record));
}
@Test
public void updateOverwriteModelledNulls() {
Record record = new Record()
.setId("id-value")
.setSort("sort-value")
.setAttribute("one")
.setAttribute2("two")
.setAttribute3("three");
mappedTable.putItem(r -> r.item(record));
Record record2 = new Record()
.setId("id-value")
.setSort("sort-value")
.setAttribute("four");
Record result = mappedTable.updateItem(r -> r.item(record2));
assertThat(result, is(record2));
}
@Test
public void updateCanIgnoreNullsAndDoPartialUpdate() {
Record record = new Record()
.setId("id-value")
.setSort("sort-value")
.setAttribute("one")
.setAttribute2("two")
.setAttribute3("three");
mappedTable.putItem(r -> r.item(record));
Record record2 = new Record()
.setId("id-value")
.setSort("sort-value")
.setAttribute("four");
Record result = mappedTable.updateItem(UpdateItemEnhancedRequest.builder(Record.class)
.item(record2)
.ignoreNulls(true)
.build());
Record expectedResult = new Record()
.setId("id-value")
.setSort("sort-value")
.setAttribute("four")
.setAttribute2("two")
.setAttribute3("three");
assertThat(result, is(expectedResult));
}
@Test
public void updateShortRecordDoesPartialUpdate() {
Record record = new Record()
.setId("id-value")
.setSort("sort-value")
.setAttribute("one")
.setAttribute2("two")
.setAttribute3("three");
mappedTable.putItem(r -> r.item(record));
ShortRecord record2 = new ShortRecord()
.setId("id-value")
.setSort("sort-value")
.setAttribute("four");
ShortRecord shortResult = mappedShortTable.updateItem(r -> r.item(record2));
Record result = mappedTable.getItem(r -> r.key(k -> k.partitionValue(record.getId()).sortValue(record.getSort())));
Record expectedResult = new Record()
.setId("id-value")
.setSort("sort-value")
.setAttribute("four")
.setAttribute2("two")
.setAttribute3("three");
assertThat(result, is(expectedResult));
assertThat(shortResult, is(record2));
}
@Test
public void updateKeyOnlyExistingRecordDoesNothing() {
Record record = new Record()
.setId("id-value")
.setSort("sort-value")
.setAttribute("one")
.setAttribute2("two")
.setAttribute3("three");
mappedTable.putItem(r -> r.item(record));
Record updateRecord = new Record().setId("id-value").setSort("sort-value");
Record result = mappedTable.updateItem(UpdateItemEnhancedRequest.builder(Record.class)
.item(updateRecord)
.ignoreNulls(true)
.build());
assertThat(result, is(record));
}
@Test
public void updateWithConditionThatSucceeds() {
Record record = new Record()
.setId("id-value")
.setSort("sort-value")
.setAttribute("one")
.setAttribute2("two")
.setAttribute3("three");
mappedTable.putItem(r -> r.item(record));
record.setAttribute("four");
Expression conditionExpression = Expression.builder()
.expression("#key = :value OR #key1 = :value1")
.putExpressionName("#key", "attribute")
.putExpressionName("#key1", ATTRIBUTE_NAME_WITH_SPECIAL_CHARACTERS)
.putExpressionValue(":value", stringValue("wrong"))
.putExpressionValue(":value1", stringValue("three"))
.build();
mappedTable.updateItem(UpdateItemEnhancedRequest.builder(Record.class)
.item(record)
.conditionExpression(conditionExpression)
.build());
Record result = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id-value").sortValue("sort-value")));
assertThat(result, is(record));
}
@Test
public void updateWithConditionThatFails() {
Record record = new Record()
.setId("id-value")
.setSort("sort-value")
.setAttribute("one")
.setAttribute2("two")
.setAttribute3("three");
mappedTable.putItem(r -> r.item(record));
record.setAttribute("four");
Expression conditionExpression = Expression.builder()
.expression("#key = :value OR #key1 = :value1")
.putExpressionName("#key", "attribute")
.putExpressionName("#key1", ATTRIBUTE_NAME_WITH_SPECIAL_CHARACTERS)
.putExpressionValue(":value", stringValue("wrong"))
.putExpressionValue(":value1", stringValue("wrong"))
.build();
exception.expect(ConditionalCheckFailedException.class);
mappedTable.updateItem(UpdateItemEnhancedRequest.builder(Record.class)
.item(record)
.conditionExpression(conditionExpression)
.build());
}
@Test
public void getAShortRecordWithNewModelledFields() {
ShortRecord shortRecord = new ShortRecord()
.setId("id-value")
.setSort("sort-value")
.setAttribute("one");
mappedShortTable.putItem(r -> r.item(shortRecord));
Record expectedRecord = new Record()
.setId("id-value")
.setSort("sort-value")
.setAttribute("one");
Record result = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id-value").sortValue("sort-value")));
assertThat(result, is(expectedRecord));
}
}
| 3,875 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/AsyncIndexScanTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.functionaltests;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.numberValue;
import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.stringValue;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primarySortKey;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.secondaryPartitionKey;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.secondarySortKey;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import software.amazon.awssdk.core.async.SdkPublisher;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbAsyncIndex;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbAsyncTable;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedAsyncClient;
import software.amazon.awssdk.enhanced.dynamodb.Expression;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.internal.client.DefaultDynamoDbEnhancedAsyncClient;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema;
import software.amazon.awssdk.enhanced.dynamodb.model.EnhancedGlobalSecondaryIndex;
import software.amazon.awssdk.enhanced.dynamodb.model.Page;
import software.amazon.awssdk.enhanced.dynamodb.model.ScanEnhancedRequest;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest;
import software.amazon.awssdk.services.dynamodb.model.ProjectionType;
public class AsyncIndexScanTest extends LocalDynamoDbAsyncTestBase {
private static class Record {
private String id;
private Integer sort;
private Integer value;
private String gsiId;
private Integer gsiSort;
private String getId() {
return id;
}
private Record setId(String id) {
this.id = id;
return this;
}
private Integer getSort() {
return sort;
}
private Record setSort(Integer sort) {
this.sort = sort;
return this;
}
private Integer getValue() {
return value;
}
private Record setValue(Integer value) {
this.value = value;
return this;
}
private String getGsiId() {
return gsiId;
}
private Record setGsiId(String gsiId) {
this.gsiId = gsiId;
return this;
}
private Integer getGsiSort() {
return gsiSort;
}
private Record setGsiSort(Integer gsiSort) {
this.gsiSort = gsiSort;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Record record = (Record) o;
return Objects.equals(id, record.id) &&
Objects.equals(sort, record.sort) &&
Objects.equals(value, record.value) &&
Objects.equals(gsiId, record.gsiId) &&
Objects.equals(gsiSort, record.gsiSort);
}
@Override
public int hashCode() {
return Objects.hash(id, sort, value, gsiId, gsiSort);
}
}
private static final TableSchema<Record> TABLE_SCHEMA =
StaticTableSchema.builder(Record.class)
.newItemSupplier(Record::new)
.addAttribute(String.class, a -> a.name("id")
.getter(Record::getId)
.setter(Record::setId)
.tags(primaryPartitionKey()))
.addAttribute(Integer.class, a -> a.name("sort")
.getter(Record::getSort)
.setter(Record::setSort)
.tags(primarySortKey()))
.addAttribute(Integer.class, a -> a.name("value")
.getter(Record::getValue)
.setter(Record::setValue))
.addAttribute(String.class, a -> a.name("gsi_id")
.getter(Record::getGsiId)
.setter(Record::setGsiId)
.tags(secondaryPartitionKey("gsi_keys_only")))
.addAttribute(Integer.class, a -> a.name("gsi_sort")
.getter(Record::getGsiSort)
.setter(Record::setGsiSort)
.tags(secondarySortKey("gsi_keys_only")))
.build();
private static final List<Record> RECORDS =
IntStream.range(0, 10)
.mapToObj(i -> new Record()
.setId("id-value")
.setSort(i)
.setValue(i)
.setGsiId("gsi-id-value")
.setGsiSort(i))
.collect(Collectors.toList());
private static final List<Record> KEYS_ONLY_RECORDS =
RECORDS.stream()
.map(record -> new Record()
.setId(record.id)
.setSort(record.sort)
.setGsiId(record.gsiId)
.setGsiSort(record.gsiSort))
.collect(Collectors.toList());
private DynamoDbEnhancedAsyncClient enhancedAsyncClient =
DefaultDynamoDbEnhancedAsyncClient.builder()
.dynamoDbClient(getDynamoDbAsyncClient())
.build();
private DynamoDbAsyncTable<Record> mappedTable = enhancedAsyncClient.table(getConcreteTableName("table-name"), TABLE_SCHEMA);
private DynamoDbAsyncIndex<Record> keysOnlyMappedIndex = mappedTable.index("gsi_keys_only");
private void insertRecords() {
RECORDS.forEach(record -> mappedTable.putItem(r -> r.item(record)).join());
}
@Before
public void createTable() {
mappedTable.createTable(
r -> r.provisionedThroughput(getDefaultProvisionedThroughput())
.globalSecondaryIndices(
EnhancedGlobalSecondaryIndex.builder()
.indexName("gsi_keys_only")
.projection(p -> p.projectionType(ProjectionType.KEYS_ONLY))
.provisionedThroughput(getDefaultProvisionedThroughput()).build()))
.join();
}
@After
public void deleteTable() {
getDynamoDbAsyncClient().deleteTable(DeleteTableRequest.builder()
.tableName(getConcreteTableName("table-name"))
.build()).join();
}
@Test
public void scanAllRecordsDefaultSettings() {
insertRecords();
SdkPublisher<Page<Record>> publisher = keysOnlyMappedIndex.scan(ScanEnhancedRequest.builder().build());
List<Page<Record>> results = drainPublisher(publisher, 1);
Page<Record> page = results.get(0);
assertThat(page.items(), is(KEYS_ONLY_RECORDS));
assertThat(page.lastEvaluatedKey(), is(nullValue()));
}
@Test
public void scanAllRecordsWithFilter() {
insertRecords();
Map<String, AttributeValue> expressionValues = new HashMap<>();
expressionValues.put(":min_value", numberValue(3));
expressionValues.put(":max_value", numberValue(5));
Expression expression = Expression.builder()
.expression("sort >= :min_value AND sort <= :max_value")
.expressionValues(expressionValues)
.build();
SdkPublisher<Page<Record>> publisher = keysOnlyMappedIndex.scan(ScanEnhancedRequest.builder()
.filterExpression(expression)
.build());
List<Page<Record>> results = drainPublisher(publisher, 1);
Page<Record> page = results.get(0);
assertThat(page.items(),
is(KEYS_ONLY_RECORDS.stream().filter(r -> r.sort >= 3 && r.sort <= 5).collect(Collectors.toList())));
assertThat(page.lastEvaluatedKey(), is(nullValue()));
}
@Test
public void scanLimit() {
insertRecords();
SdkPublisher<Page<Record>> publisher = keysOnlyMappedIndex.scan(r -> r.limit(5));
List<Page<Record>> results = drainPublisher(publisher, 3);
Page<Record> page1 = results.get(0);
Page<Record> page2 = results.get(1);
Page<Record> page3 = results.get(2);
assertThat(page1.items(), is(KEYS_ONLY_RECORDS.subList(0, 5)));
assertThat(page1.lastEvaluatedKey(), is(getKeyMap(4)));
assertThat(page2.items(), is(KEYS_ONLY_RECORDS.subList(5, 10)));
assertThat(page2.lastEvaluatedKey(), is(getKeyMap(9)));
assertThat(page3.items(), is(empty()));
assertThat(page3.lastEvaluatedKey(), is(nullValue()));
}
@Test
public void scanEmpty() {
SdkPublisher<Page<Record>> publisher = keysOnlyMappedIndex.scan();
List<Page<Record>> results = drainPublisher(publisher, 1);
Page<Record> page = results.get(0);
assertThat(page.items(), is(empty()));
assertThat(page.lastEvaluatedKey(), is(nullValue()));
}
@Test
public void scanExclusiveStartKey() {
insertRecords();
SdkPublisher<Page<Record>> publisher =
keysOnlyMappedIndex.scan(ScanEnhancedRequest.builder().exclusiveStartKey(getKeyMap(7)).build());
List<Page<Record>> results = drainPublisher(publisher, 1);
Page<Record> page = results.get(0);
assertThat(page.items(), is(KEYS_ONLY_RECORDS.subList(8, 10)));
assertThat(page.lastEvaluatedKey(), is(nullValue()));
}
private Map<String, AttributeValue> getKeyMap(int sort) {
Map<String, AttributeValue> result = new HashMap<>();
result.put("id", stringValue(KEYS_ONLY_RECORDS.get(sort).getId()));
result.put("sort", numberValue(KEYS_ONLY_RECORDS.get(sort).getSort()));
result.put("gsi_id", stringValue(KEYS_ONLY_RECORDS.get(sort).getGsiId()));
result.put("gsi_sort", numberValue(KEYS_ONLY_RECORDS.get(sort).getGsiSort()));
return Collections.unmodifiableMap(result);
}
}
| 3,876 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/LocalDynamoDb.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.functionaltests;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.URI;
import java.util.Optional;
import com.amazonaws.services.dynamodbv2.local.main.ServerRunner;
import com.amazonaws.services.dynamodbv2.local.server.DynamoDBProxyServer;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
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.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
/**
* Wrapper for a local DynamoDb server used in testing. Each instance of this class will find a new port to run on,
* so multiple instances can be safely run simultaneously. Each instance of this service uses memory as a storage medium
* and is thus completely ephemeral; no data will be persisted between stops and starts.
*
* LocalDynamoDb localDynamoDb = new LocalDynamoDb();
* localDynamoDb.start(); // Start the service running locally on host
* DynamoDbClient dynamoDbClient = localDynamoDb.createClient();
* ... // Do your testing with the client
* localDynamoDb.stop(); // Stop the service and free up resources
*
* If possible it's recommended to keep a single running instance for all your tests, as it can be slow to teardown
* and create new servers for every test, but there have been observed problems when dropping tables between tests for
* this scenario, so it's best to write your tests to be resilient to tables that already have data in them.
*/
class LocalDynamoDb {
private DynamoDBProxyServer server;
private int port;
/**
* Start the local DynamoDb service and run in background
*/
void start() {
port = getFreePort();
String portString = Integer.toString(port);
try {
server = createServer(portString);
server.start();
} catch (Exception e) {
throw propagate(e);
}
}
/**
* Create a standard AWS v2 SDK client pointing to the local DynamoDb instance
* @return A DynamoDbClient pointing to the local DynamoDb instance
*/
DynamoDbClient createClient() {
String endpoint = String.format("http://localhost:%d", port);
return DynamoDbClient.builder()
.endpointOverride(URI.create(endpoint))
// The region is meaningless for local DynamoDb but required for client builder validation
.region(Region.US_EAST_1)
.credentialsProvider(StaticCredentialsProvider.create(
AwsBasicCredentials.create("dummy-key", "dummy-secret")))
.overrideConfiguration(o -> o.addExecutionInterceptor(new VerifyUserAgentInterceptor()))
.build();
}
DynamoDbAsyncClient createAsyncClient() {
String endpoint = String.format("http://localhost:%d", port);
return DynamoDbAsyncClient.builder()
.endpointOverride(URI.create(endpoint))
.region(Region.US_EAST_1)
.credentialsProvider(StaticCredentialsProvider.create(
AwsBasicCredentials.create("dummy-key", "dummy-secret")))
.overrideConfiguration(o -> o.addExecutionInterceptor(new VerifyUserAgentInterceptor()))
.build();
}
/**
* Stops the local DynamoDb service and frees up resources it is using.
*/
void stop() {
try {
server.stop();
} catch (Exception e) {
throw propagate(e);
}
}
private DynamoDBProxyServer createServer(String portString) throws Exception {
return ServerRunner.createServerFromCommandLineArgs(
new String[]{
"-inMemory",
"-port", portString
});
}
private int getFreePort() {
try {
ServerSocket socket = new ServerSocket(0);
int port = socket.getLocalPort();
socket.close();
return port;
} catch (IOException ioe) {
throw propagate(ioe);
}
}
private static RuntimeException propagate(Exception e) {
if (e instanceof RuntimeException) {
throw (RuntimeException)e;
}
throw new RuntimeException(e);
}
private static class VerifyUserAgentInterceptor implements ExecutionInterceptor {
@Override
public void beforeTransmission(Context.BeforeTransmission context, ExecutionAttributes executionAttributes) {
Optional<String> headers = context.httpRequest().firstMatchingHeader("User-agent");
assertThat(headers).isPresent();
assertThat(headers.get()).contains("hll/ddb-enh");
}
}
}
| 3,877 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/LocalDynamoDbAsyncTestBase.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.functionaltests;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import java.util.List;
import software.amazon.awssdk.core.async.SdkPublisher;
import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient;
public class LocalDynamoDbAsyncTestBase extends LocalDynamoDbTestBase {
private DynamoDbAsyncClient dynamoDbAsyncClient = localDynamoDb().createAsyncClient();
protected DynamoDbAsyncClient getDynamoDbAsyncClient() {
return dynamoDbAsyncClient;
}
public static <T> List<T> drainPublisher(SdkPublisher<T> publisher, int expectedNumberOfResults) {
BufferingSubscriber<T> subscriber = new BufferingSubscriber<>();
publisher.subscribe(subscriber);
subscriber.waitForCompletion(5000L);
assertThat(subscriber.isCompleted(), is(true));
assertThat(subscriber.bufferedError(), is(nullValue()));
assertThat(subscriber.bufferedItems().size(), is(expectedNumberOfResults));
return subscriber.bufferedItems();
}
public static <T> List<T> drainPublisherToError(SdkPublisher<T> publisher,
int expectedNumberOfResults,
Class<? extends Throwable> expectedError) {
BufferingSubscriber<T> subscriber = new BufferingSubscriber<>();
publisher.subscribe(subscriber);
subscriber.waitForCompletion(1000L);
assertThat(subscriber.isCompleted(), is(false));
assertThat(subscriber.bufferedError(), instanceOf(expectedError));
assertThat(subscriber.bufferedItems().size(), is(expectedNumberOfResults));
return subscriber.bufferedItems();
}
}
| 3,878 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/FlattenTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.functionaltests;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey;
import java.util.Objects;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema;
import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest;
public class FlattenTest extends LocalDynamoDbSyncTestBase {
private static class Record {
private String id;
private Document document;
private String getId() {
return id;
}
private Record setId(String id) {
this.id = id;
return this;
}
private Document getDocument() {
return document;
}
private Record setDocument(Document document) {
this.document = document;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Record record = (Record) o;
return Objects.equals(id, record.id) &&
Objects.equals(document, record.document);
}
@Override
public int hashCode() {
return Objects.hash(id, document);
}
}
private static class Document {
private String documentAttribute1;
private String documentAttribute2;
private String documentAttribute3;
private String getDocumentAttribute1() {
return documentAttribute1;
}
private Document setDocumentAttribute1(String documentAttribute1) {
this.documentAttribute1 = documentAttribute1;
return this;
}
private String getDocumentAttribute2() {
return documentAttribute2;
}
private Document setDocumentAttribute2(String documentAttribute2) {
this.documentAttribute2 = documentAttribute2;
return this;
}
private String getDocumentAttribute3() {
return documentAttribute3;
}
private Document setDocumentAttribute3(String documentAttribute3) {
this.documentAttribute3 = documentAttribute3;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Document document = (Document) o;
return Objects.equals(documentAttribute1, document.documentAttribute1) &&
Objects.equals(documentAttribute2, document.documentAttribute2) &&
Objects.equals(documentAttribute3, document.documentAttribute3);
}
@Override
public int hashCode() {
return Objects.hash(documentAttribute1, documentAttribute2, documentAttribute3);
}
}
private static final StaticTableSchema<Document> DOCUMENT_SCHEMA =
StaticTableSchema.builder(Document.class)
.newItemSupplier(Document::new)
.addAttribute(String.class, a -> a.name("documentAttribute1")
.getter(Document::getDocumentAttribute1)
.setter(Document::setDocumentAttribute1))
.addAttribute(String.class, a -> a.name("documentAttribute2")
.getter(Document::getDocumentAttribute2)
.setter(Document::setDocumentAttribute2))
.addAttribute(String.class, a -> a.name("documentAttribute3")
.getter(Document::getDocumentAttribute3)
.setter(Document::setDocumentAttribute3))
.build();
private static final TableSchema<Record> TABLE_SCHEMA =
StaticTableSchema.builder(Record.class)
.newItemSupplier(Record::new)
.addAttribute(String.class, a -> a.name("id")
.getter(Record::getId)
.setter(Record::setId)
.tags(primaryPartitionKey()))
.flatten(DOCUMENT_SCHEMA, Record::getDocument, Record::setDocument)
.build();
private DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder()
.dynamoDbClient(getDynamoDbClient())
.build();
private DynamoDbTable<Record> mappedTable = enhancedClient.table(getConcreteTableName("table-name"), TABLE_SCHEMA);
@Before
public void createTable() {
mappedTable.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput()));
}
@After
public void deleteTable() {
getDynamoDbClient().deleteTable(DeleteTableRequest.builder()
.tableName(getConcreteTableName("table-name"))
.build());
}
@Test
public void update_allValues() {
Document document = new Document()
.setDocumentAttribute1("one")
.setDocumentAttribute2("two")
.setDocumentAttribute3("three");
Record record = new Record()
.setId("id-value")
.setDocument(document);
Record updatedRecord = mappedTable.updateItem(r -> r.item(record));
Record fetchedRecord = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id-value")));
assertThat(updatedRecord, is(record));
assertThat(fetchedRecord, is(record));
}
@Test
public void update_someValues() {
Document document = new Document()
.setDocumentAttribute1("one")
.setDocumentAttribute2("two");
Record record = new Record()
.setId("id-value")
.setDocument(document);
Record updatedRecord = mappedTable.updateItem(r -> r.item(record));
Record fetchedRecord = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id-value")));
assertThat(updatedRecord, is(record));
assertThat(fetchedRecord, is(record));
}
@Test
public void update_nullDocument() {
Record record = new Record()
.setId("id-value");
Record updatedRecord = mappedTable.updateItem(r -> r.item(record));
Record fetchedRecord = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id-value")));
assertThat(updatedRecord, is(record));
assertThat(fetchedRecord, is(record));
}
}
| 3,879 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/BasicControlPlaneTableOperationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.functionaltests;
import static org.assertj.core.api.Assertions.assertThat;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primarySortKey;
import java.util.Objects;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema;
import software.amazon.awssdk.enhanced.dynamodb.model.CreateTableEnhancedRequest;
import software.amazon.awssdk.enhanced.dynamodb.model.DescribeTableEnhancedResponse;
import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest;
public class BasicControlPlaneTableOperationTest extends LocalDynamoDbSyncTestBase {
private static final TableSchema<Record> TABLE_SCHEMA =
StaticTableSchema.builder(Record.class)
.newItemSupplier(Record::new)
.addAttribute(String.class, a -> a.name("id")
.getter(Record::getId)
.setter(Record::setId)
.tags(primaryPartitionKey()))
.addAttribute(Integer.class, a -> a.name("sort")
.getter(Record::getSort)
.setter(Record::setSort)
.tags(primarySortKey()))
.build();
private final String tableName = getConcreteTableName("table-name");
private final DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder()
.dynamoDbClient(getDynamoDbClient())
.build();
private final DynamoDbTable<Record> mappedTable = enhancedClient.table(getConcreteTableName("table-name"), TABLE_SCHEMA);
@Before
public void createTable() {
mappedTable.createTable(
CreateTableEnhancedRequest.builder()
.provisionedThroughput(getDefaultProvisionedThroughput())
.build());
getDynamoDbClient().waiter().waitUntilTableExists(b -> b.tableName(tableName));
}
@After
public void deleteTable() {
getDynamoDbClient().deleteTable(DeleteTableRequest.builder()
.tableName(tableName)
.build());
getDynamoDbClient().waiter().waitUntilTableNotExists(b -> b.tableName(tableName));
}
@Test
public void describeTable() {
DescribeTableEnhancedResponse describeTableEnhancedResponse = mappedTable.describeTable();
assertThat(describeTableEnhancedResponse.table()).isNotNull();
assertThat(describeTableEnhancedResponse.table().tableName()).isEqualTo(tableName);
}
private static class Record {
private String id;
private Integer sort;
private String getId() {
return id;
}
private Record setId(String id) {
this.id = id;
return this;
}
private Integer getSort() {
return sort;
}
private Record setSort(Integer sort) {
this.sort = sort;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Record record = (Record) o;
return Objects.equals(id, record.id) &&
Objects.equals(sort, record.sort);
}
@Override
public int hashCode() {
return Objects.hash(id, sort);
}
}
}
| 3,880 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/FailedConversionAsyncTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.functionaltests;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.util.List;
import java.util.concurrent.CompletionException;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbAsyncTable;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedAsyncClient;
import software.amazon.awssdk.enhanced.dynamodb.Key;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeEnum;
import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeEnumRecord;
import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeEnumShortened;
import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.FakeEnumShortenedRecord;
import software.amazon.awssdk.enhanced.dynamodb.model.Page;
import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest;
public class FailedConversionAsyncTest extends LocalDynamoDbAsyncTestBase {
private static final TableSchema<FakeEnumRecord> TABLE_SCHEMA = TableSchema.fromClass(FakeEnumRecord.class);
private static final TableSchema<FakeEnumShortenedRecord> SHORT_TABLE_SCHEMA =
TableSchema.fromClass(FakeEnumShortenedRecord.class);
private final DynamoDbEnhancedAsyncClient enhancedClient =
DynamoDbEnhancedAsyncClient.builder()
.dynamoDbClient(getDynamoDbAsyncClient())
.build();
private final DynamoDbAsyncTable<FakeEnumRecord> mappedTable =
enhancedClient.table(getConcreteTableName("table-name"), TABLE_SCHEMA);
private final DynamoDbAsyncTable<FakeEnumShortenedRecord> mappedShortTable =
enhancedClient.table(getConcreteTableName("table-name"), SHORT_TABLE_SCHEMA);
@Rule
public ExpectedException exception = ExpectedException.none();
@Before
public void createTable() {
mappedTable.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput())).join();
}
@After
public void deleteTable() {
getDynamoDbAsyncClient().deleteTable(DeleteTableRequest.builder()
.tableName(getConcreteTableName("table-name"))
.build()).join();
}
@Test
public void exceptionOnRead() {
FakeEnumRecord record = new FakeEnumRecord();
record.setId("123");
record.setEnumAttribute(FakeEnum.TWO);
mappedTable.putItem(record).join();
assertThatThrownBy(() -> mappedShortTable.getItem(Key.builder().partitionValue("123").build()).join())
.isInstanceOf(CompletionException.class)
.hasCauseInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("TWO")
.hasMessageContaining("FakeEnumShortened");
}
@Test
public void iterableExceptionOnRead() {
FakeEnumRecord record = new FakeEnumRecord();
record.setId("1");
record.setEnumAttribute(FakeEnum.ONE);
mappedTable.putItem(record).join();
record.setId("2");
record.setEnumAttribute(FakeEnum.TWO);
mappedTable.putItem(record).join();
List<Page<FakeEnumShortenedRecord>> results =
drainPublisherToError(mappedShortTable.scan(r -> r.limit(1)), 1, IllegalArgumentException.class);
assertThat(results).hasOnlyOneElementSatisfying(
page -> assertThat(page.items()).hasOnlyOneElementSatisfying(item -> {
assertThat(item.getId()).isEqualTo("1");
assertThat(item.getEnumAttribute()).isEqualTo(FakeEnumShortened.ONE);
}));
}
}
| 3,881 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/BasicScanTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.functionaltests;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.numberValue;
import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.stringValue;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primarySortKey;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import software.amazon.awssdk.core.pagination.sync.SdkIterable;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable;
import software.amazon.awssdk.enhanced.dynamodb.Expression;
import software.amazon.awssdk.enhanced.dynamodb.NestedAttributeName;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.InnerAttributeRecord;
import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.NestedTestRecord;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema;
import software.amazon.awssdk.enhanced.dynamodb.model.Page;
import software.amazon.awssdk.enhanced.dynamodb.model.ScanEnhancedRequest;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest;
public class BasicScanTest extends LocalDynamoDbSyncTestBase {
private static class Record {
private String id;
private Integer sort;
private String getId() {
return id;
}
private Record setId(String id) {
this.id = id;
return this;
}
private Integer getSort() {
return sort;
}
private Record setSort(Integer sort) {
this.sort = sort;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Record record = (Record) o;
return Objects.equals(id, record.id) &&
Objects.equals(sort, record.sort);
}
@Override
public int hashCode() {
return Objects.hash(id, sort);
}
}
private static final TableSchema<Record> TABLE_SCHEMA =
StaticTableSchema.builder(Record.class)
.newItemSupplier(Record::new)
.addAttribute(String.class, a -> a.name("id")
.getter(Record::getId)
.setter(Record::setId)
.tags(primaryPartitionKey()))
.addAttribute(Integer.class, a -> a.name("sort")
.getter(Record::getSort)
.setter(Record::setSort)
.tags(primarySortKey()))
.build();
private static final List<Record> RECORDS =
IntStream.range(0, 10)
.mapToObj(i -> new Record().setId("id-value").setSort(i))
.collect(Collectors.toList());
private static final List<NestedTestRecord> NESTED_TEST_RECORDS =
IntStream.range(0, 10)
.mapToObj(i -> {
final NestedTestRecord nestedTestRecord = new NestedTestRecord();
nestedTestRecord.setOuterAttribOne("id-value-" + i);
nestedTestRecord.setSort(i);
final InnerAttributeRecord innerAttributeRecord = new InnerAttributeRecord();
innerAttributeRecord.setAttribOne("attribOne-"+i);
innerAttributeRecord.setAttribTwo(i);
nestedTestRecord.setInnerAttributeRecord(innerAttributeRecord);
nestedTestRecord.setDotVariable("v"+i);
return nestedTestRecord;
})
.collect(Collectors.toList());
private DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder()
.dynamoDbClient(getDynamoDbClient())
.build();
private DynamoDbTable<Record> mappedTable = enhancedClient.table(getConcreteTableName("table-name"), TABLE_SCHEMA);
private DynamoDbTable<NestedTestRecord> mappedNestedTable = enhancedClient.table(getConcreteTableName("nested-table-name"),
TableSchema.fromClass(NestedTestRecord.class));
private void insertRecords() {
RECORDS.forEach(record -> mappedTable.putItem(r -> r.item(record)));
}
private void insertNestedRecords() {
NESTED_TEST_RECORDS.forEach(nestedTestRecord -> mappedNestedTable.putItem(r -> r.item(nestedTestRecord)));
}
@Before
public void createTable() {
mappedTable.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput()));
mappedNestedTable.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput()));
}
@After
public void deleteTable() {
getDynamoDbClient().deleteTable(DeleteTableRequest.builder()
.tableName(getConcreteTableName("table-name"))
.build());
getDynamoDbClient().deleteTable(DeleteTableRequest.builder()
.tableName(getConcreteTableName("nested-table-name"))
.build());
}
@Test
public void scanAllRecordsDefaultSettings() {
insertRecords();
mappedTable.scan(ScanEnhancedRequest.builder().build())
.forEach(p -> p.items().forEach(item -> System.out.println(item)));
Iterator<Page<Record>> results = mappedTable.scan(ScanEnhancedRequest.builder().build()).iterator();
assertThat(results.hasNext(), is(true));
Page<Record> page = results.next();
assertThat(results.hasNext(), is(false));
assertThat(page.items(), is(RECORDS));
assertThat(page.lastEvaluatedKey(), is(nullValue()));
}
@Test
public void queryAllRecordsDefaultSettings_withProjection() {
insertRecords();
Iterator<Page<Record>> results =
mappedTable.scan(b -> b.attributesToProject("sort")).iterator();
assertThat(results.hasNext(), is(true));
Page<Record> page = results.next();
assertThat(results.hasNext(), is(false));
assertThat(page.items().size(), is(RECORDS.size()));
Record firstRecord = page.items().get(0);
assertThat(firstRecord.id, is(nullValue()));
assertThat(firstRecord.sort, is(0));
}
@Test
public void scanAllRecordsDefaultSettings_viaItems() {
insertRecords();
SdkIterable<Record> items = mappedTable.scan(ScanEnhancedRequest.builder().limit(2).build()).items();
assertThat(items.stream().collect(Collectors.toList()), is(RECORDS));
}
@Test
public void scanAllRecordsWithFilter() {
insertRecords();
Map<String, AttributeValue> expressionValues = new HashMap<>();
expressionValues.put(":min_value", numberValue(3));
expressionValues.put(":max_value", numberValue(5));
Expression expression = Expression.builder()
.expression("sort >= :min_value AND sort <= :max_value")
.expressionValues(expressionValues)
.build();
Iterator<Page<Record>> results =
mappedTable.scan(ScanEnhancedRequest.builder().filterExpression(expression).build()).iterator();
assertThat(results.hasNext(), is(true));
Page<Record> page = results.next();
assertThat(results.hasNext(), is(false));
assertThat(page.items(),
is(RECORDS.stream().filter(r -> r.sort >= 3 && r.sort <= 5).collect(Collectors.toList())));
assertThat(page.lastEvaluatedKey(), is(nullValue()));
}
@Test
public void scanAllRecordsWithFilterAndProjection() {
insertRecords();
Map<String, AttributeValue> expressionValues = new HashMap<>();
expressionValues.put(":min_value", numberValue(3));
expressionValues.put(":max_value", numberValue(5));
Expression expression = Expression.builder()
.expression("#sort >= :min_value AND #sort <= :max_value")
.expressionValues(expressionValues)
.putExpressionName("#sort", "sort")
.build();
Iterator<Page<Record>> results =
mappedTable.scan(
ScanEnhancedRequest.builder()
.attributesToProject("sort")
.filterExpression(expression)
.build()
).iterator();
assertThat(results.hasNext(), is(true));
Page<Record> page = results.next();
assertThat(results.hasNext(), is(false));
assertThat(page.items(), hasSize(3));
Record record = page.items().get(0);
assertThat(record.id, is(nullValue()));
assertThat(record.sort, is(3));
}
@Test
public void scanLimit() {
insertRecords();
Iterator<Page<Record>> results = mappedTable.scan(r -> r.limit(5)).iterator();
assertThat(results.hasNext(), is(true));
Page<Record> page1 = results.next();
assertThat(results.hasNext(), is(true));
Page<Record> page2 = results.next();
assertThat(results.hasNext(), is(true));
Page<Record> page3 = results.next();
assertThat(results.hasNext(), is(false));
assertThat(page1.items(), is(RECORDS.subList(0, 5)));
assertThat(page1.lastEvaluatedKey(), is(getKeyMap(4)));
assertThat(page2.items(), is(RECORDS.subList(5, 10)));
assertThat(page2.lastEvaluatedKey(), is(getKeyMap(9)));
assertThat(page3.items(), is(empty()));
assertThat(page3.lastEvaluatedKey(), is(nullValue()));
}
@Test
public void scanLimit_viaItems() {
insertRecords();
SdkIterable<Record> results = mappedTable.scan(r -> r.limit(5)).items();
assertThat(results.stream().collect(Collectors.toList()), is(RECORDS));
}
@Test
public void scanEmpty() {
Iterator<Page<Record>> results = mappedTable.scan().iterator();
assertThat(results.hasNext(), is(true));
Page<Record> page = results.next();
assertThat(results.hasNext(), is(false));
assertThat(page.items(), is(empty()));
assertThat(page.lastEvaluatedKey(), is(nullValue()));
}
@Test
public void scanEmpty_viaItems() {
Iterator<Record> results = mappedTable.scan().items().iterator();
assertThat(results.hasNext(), is(false));
}
@Test
public void scanExclusiveStartKey() {
insertRecords();
Iterator<Page<Record>> results =
mappedTable.scan(r -> r.exclusiveStartKey(getKeyMap(7))).iterator();
assertThat(results.hasNext(), is(true));
Page<Record> page = results.next();
assertThat(results.hasNext(), is(false));
assertThat(page.items(), is(RECORDS.subList(8, 10)));
assertThat(page.lastEvaluatedKey(), is(nullValue()));
}
@Test
public void scanExclusiveStartKey_viaItems() {
insertRecords();
SdkIterable<Record> results =
mappedTable.scan(r -> r.exclusiveStartKey(getKeyMap(7))).items();
assertThat(results.stream().collect(Collectors.toList()), is(RECORDS.subList(8, 10)));
}
private Map<String, AttributeValue> getKeyMap(int sort) {
Map<String, AttributeValue> result = new HashMap<>();
result.put("id", stringValue("id-value"));
result.put("sort", numberValue(sort));
return Collections.unmodifiableMap(result);
}
@Test
public void scanAllRecordsWithFilterAndNestedProjectionSingleAttribute() {
insertNestedRecords();
Map<String, AttributeValue> expressionValues = new HashMap<>();
expressionValues.put(":min_value", numberValue(3));
expressionValues.put(":max_value", numberValue(5));
Expression expression = Expression.builder()
.expression("#sort >= :min_value AND #sort <= :max_value")
.expressionValues(expressionValues)
.putExpressionName("#sort", "sort")
.build();
Iterator<Page<NestedTestRecord>> results =
mappedNestedTable.scan(
ScanEnhancedRequest.builder()
.filterExpression(expression)
.addNestedAttributesToProject(
NestedAttributeName.create(Arrays.asList("innerAttributeRecord","attribOne")))
.build()
).iterator();
assertThat(results.hasNext(), is(true));
Page<NestedTestRecord> page = results.next();
assertThat(results.hasNext(), is(false));
assertThat(page.items().size(), is(3));
Collections.sort(page.items(), (item1, item2) ->
item1.getInnerAttributeRecord().getAttribOne()
.compareTo(item2.getInnerAttributeRecord().getAttribOne()));
NestedTestRecord firstRecord = page.items().get(0);
assertThat(firstRecord.getOuterAttribOne(), is(nullValue()));
assertThat(firstRecord.getSort(), is(nullValue()));
assertThat(firstRecord.getInnerAttributeRecord().getAttribOne(), is("attribOne-3"));
assertThat(firstRecord.getInnerAttributeRecord().getAttribTwo(), is(nullValue()));
//Attribute repeated with new and old attributeToProject
results =
mappedNestedTable.scan(
ScanEnhancedRequest.builder()
.filterExpression(expression)
.addNestedAttributesToProject(NestedAttributeName.create("sort"))
.addAttributeToProject("sort")
.build()
).iterator();
assertThat(results.hasNext(), is(true));
page = results.next();
assertThat(results.hasNext(), is(false));
assertThat(page.items().size(), is(3));
Collections.sort(page.items(), (item1, item2) ->
item1.getSort()
.compareTo(item2.getSort()));
firstRecord = page.items().get(0);
assertThat(firstRecord.getOuterAttribOne(), is(nullValue()));
assertThat(firstRecord.getSort(), is(3));
assertThat(firstRecord.getInnerAttributeRecord(), is(nullValue()));
assertThat(firstRecord.getInnerAttributeRecord(), is(nullValue()));
results =
mappedNestedTable.scan(
ScanEnhancedRequest.builder()
.filterExpression(expression)
.addNestedAttributeToProject(
NestedAttributeName.create(Arrays.asList("innerAttributeRecord","attribOne")))
.build()
).iterator();
assertThat(results.hasNext(), is(true));
page = results.next();
assertThat(results.hasNext(), is(false));
assertThat(page.items().size(), is(3));
Collections.sort(page.items(), (item1, item2) ->
item1.getInnerAttributeRecord().getAttribOne()
.compareTo(item2.getInnerAttributeRecord().getAttribOne()));
firstRecord = page.items().get(0);
assertThat(firstRecord.getOuterAttribOne(), is(nullValue()));
assertThat(firstRecord.getSort(), is(nullValue()));
assertThat(firstRecord.getInnerAttributeRecord().getAttribOne(), is("attribOne-3"));
assertThat(firstRecord.getInnerAttributeRecord().getAttribTwo(), is(nullValue()));
}
@Test
public void scanAllRecordsWithFilterAndNestedProjectionMultipleAttribute() {
insertNestedRecords();
Map<String, AttributeValue> expressionValues = new HashMap<>();
expressionValues.put(":min_value", numberValue(3));
expressionValues.put(":max_value", numberValue(5));
Expression expression = Expression.builder()
.expression("#sort >= :min_value AND #sort <= :max_value")
.expressionValues(expressionValues)
.putExpressionName("#sort", "sort")
.build();
final ScanEnhancedRequest build = ScanEnhancedRequest.builder()
.filterExpression(expression)
.addAttributeToProject("outerAttribOne")
.addNestedAttributesToProject(Arrays.asList(NestedAttributeName.builder().elements("innerAttributeRecord")
.addElement("attribOne").build()))
.addNestedAttributeToProject(NestedAttributeName.builder()
.elements(Arrays.asList("innerAttributeRecord", "attribTwo")).build())
.build();
Iterator<Page<NestedTestRecord>> results =
mappedNestedTable.scan(
build
).iterator();
assertThat(results.hasNext(), is(true));
Page<NestedTestRecord> page = results.next();
assertThat(results.hasNext(), is(false));
assertThat(page.items().size(), is(3));
Collections.sort(page.items(), (item1, item2) ->
item1.getInnerAttributeRecord().getAttribOne()
.compareTo(item2.getInnerAttributeRecord().getAttribOne()));
NestedTestRecord firstRecord = page.items().get(0);
assertThat(firstRecord.getOuterAttribOne(), is("id-value-3"));
assertThat(firstRecord.getSort(), is(nullValue()));
assertThat(firstRecord.getInnerAttributeRecord().getAttribOne(), is("attribOne-3"));
assertThat(firstRecord.getInnerAttributeRecord().getAttribTwo(), is(3));
}
@Test
public void scanAllRecordsWithNonExistigKeyName() {
insertNestedRecords();
Map<String, AttributeValue> expressionValues = new HashMap<>();
expressionValues.put(":min_value", numberValue(3));
expressionValues.put(":max_value", numberValue(5));
Expression expression = Expression.builder()
.expression("#sort >= :min_value AND #sort <= :max_value")
.expressionValues(expressionValues)
.putExpressionName("#sort", "sort")
.build();
Iterator<Page<NestedTestRecord>> results =
mappedNestedTable.scan(
ScanEnhancedRequest.builder()
.filterExpression(expression)
.addNestedAttributesToProject(NestedAttributeName.builder().addElement("nonExistent").build())
.build()
).iterator();
assertThat(results.hasNext(), is(true));
Page<NestedTestRecord> page = results.next();
assertThat(results.hasNext(), is(false));
assertThat(page.items().size(), is(3));
NestedTestRecord firstRecord = page.items().get(0);
assertThat(firstRecord, is(nullValue()));
}
@Test
public void scanAllRecordsWithDotInAttributeKeyName() {
insertNestedRecords();
Map<String, AttributeValue> expressionValues = new HashMap<>();
expressionValues.put(":min_value", numberValue(3));
expressionValues.put(":max_value", numberValue(5));
Expression expression = Expression.builder()
.expression("#sort >= :min_value AND #sort <= :max_value")
.expressionValues(expressionValues)
.putExpressionName("#sort", "sort")
.build();
Iterator<Page<NestedTestRecord>> results =
mappedNestedTable.scan(
ScanEnhancedRequest.builder()
.filterExpression(expression)
.addNestedAttributesToProject(NestedAttributeName
.create("test.com")).build()
).iterator();
assertThat(results.hasNext(), is(true));
Page<NestedTestRecord> page = results.next();
assertThat(results.hasNext(), is(false));
assertThat(page.items().size(), is(3));
Collections.sort(page.items(), (item1, item2) ->
item1.getDotVariable()
.compareTo(item2.getDotVariable()));
NestedTestRecord firstRecord = page.items().get(0);
assertThat(firstRecord.getOuterAttribOne(), is(nullValue()));
assertThat(firstRecord.getSort(), is(nullValue()));
assertThat(firstRecord.getDotVariable(), is("v3"));
assertThat(firstRecord.getInnerAttributeRecord(), is(nullValue()));
assertThat(firstRecord.getInnerAttributeRecord(), is(nullValue()));
}
@Test
public void scanAllRecordsWithSameNamesRepeated() {
//Attribute repeated with new and old attributeToProject
insertNestedRecords();
Map<String, AttributeValue> expressionValues = new HashMap<>();
expressionValues.put(":min_value", numberValue(3));
expressionValues.put(":max_value", numberValue(5));
Expression expression = Expression.builder()
.expression("#sort >= :min_value AND #sort <= :max_value")
.expressionValues(expressionValues)
.putExpressionName("#sort", "sort")
.build();
Iterator<Page<NestedTestRecord> >results =
mappedNestedTable.scan(
ScanEnhancedRequest.builder()
.filterExpression(expression)
.addNestedAttributesToProject(NestedAttributeName.builder().elements("sort").build())
.addAttributeToProject("sort")
.build()
).iterator();
assertThat(results.hasNext(), is(true));
Page<NestedTestRecord> page = results.next();
assertThat(results.hasNext(), is(false));
assertThat(page.items().size(), is(3));
Collections.sort(page.items(), (item1, item2) ->
item1.getSort()
.compareTo(item2.getSort()));
NestedTestRecord firstRecord = page.items().get(0);
assertThat(firstRecord.getOuterAttribOne(), is(nullValue()));
assertThat(firstRecord.getSort(), is(3));
assertThat(firstRecord.getInnerAttributeRecord(), is(nullValue()));
assertThat(firstRecord.getInnerAttributeRecord(), is(nullValue()));
}
@Test
public void scanAllRecordsWithEmptyList() {
//Attribute repeated with new and old attributeToProject
insertNestedRecords();
Map<String, AttributeValue> expressionValues = new HashMap<>();
expressionValues.put(":min_value", numberValue(3));
expressionValues.put(":max_value", numberValue(5));
Expression expression = Expression.builder()
.expression("#sort >= :min_value AND #sort <= :max_value")
.expressionValues(expressionValues)
.putExpressionName("#sort", "sort")
.build();
Iterator<Page<NestedTestRecord> >results =
mappedNestedTable.scan(
ScanEnhancedRequest.builder()
.filterExpression(expression)
.addNestedAttributesToProject(new ArrayList<>())
.build()
).iterator();
assertThat(results.hasNext(), is(true));
Page<NestedTestRecord> page = results.next();
assertThat(results.hasNext(), is(false));
assertThat(page.items().size(), is(3));
Collections.sort(page.items(), (item1, item2) ->
item1.getSort()
.compareTo(item2.getSort()));
NestedTestRecord firstRecord = page.items().get(0);
assertThat(firstRecord.getOuterAttribOne(), is("id-value-3"));
assertThat(firstRecord.getSort(), is(3));
assertThat(firstRecord.getInnerAttributeRecord().getAttribTwo(), is(3));
assertThat(firstRecord.getInnerAttributeRecord().getAttribOne(), is("attribOne-3"));
}
@Test
public void scanAllRecordsWithNullAttributesToProject() {
//Attribute repeated with new and old attributeToProject
insertNestedRecords();
List<String> backwardCompatibilityNull = null;
Map<String, AttributeValue> expressionValues = new HashMap<>();
expressionValues.put(":min_value", numberValue(3));
expressionValues.put(":max_value", numberValue(5));
Expression expression = Expression.builder()
.expression("#sort >= :min_value AND #sort <= :max_value")
.expressionValues(expressionValues)
.putExpressionName("#sort", "sort")
.build();
Iterator<Page<NestedTestRecord> >results =
mappedNestedTable.scan(
ScanEnhancedRequest.builder()
.filterExpression(expression)
.attributesToProject("test.com")
.attributesToProject(backwardCompatibilityNull)
.build()
).iterator();
assertThat(results.hasNext(), is(true));
Page<NestedTestRecord> page = results.next();
assertThat(results.hasNext(), is(false));
assertThat(page.items().size(), is(3));
Collections.sort(page.items(), (item1, item2) ->
item1.getSort()
.compareTo(item2.getSort()));
NestedTestRecord firstRecord = page.items().get(0);
assertThat(firstRecord.getOuterAttribOne(), is("id-value-3"));
assertThat(firstRecord.getSort(), is(3));
assertThat(firstRecord.getInnerAttributeRecord().getAttribTwo(), is(3));
assertThat(firstRecord.getInnerAttributeRecord().getAttribOne(), is("attribOne-3"));
}
@Test
public void scanAllRecordsWithNestedProjectionNameEmptyNameMap() {
insertNestedRecords();
Map<String, AttributeValue> expressionValues = new HashMap<>();
expressionValues.put(":min_value", numberValue(3));
expressionValues.put(":max_value", numberValue(5));
Expression expression = Expression.builder()
.expression("#sort >= :min_value AND #sort <= :max_value")
.expressionValues(expressionValues)
.putExpressionName("#sort", "sort")
.build();
final Iterator<Page<NestedTestRecord>> results =
mappedNestedTable.scan(
ScanEnhancedRequest.builder()
.filterExpression(expression)
.addNestedAttributesToProject(NestedAttributeName.builder().elements("").build()).build()
).iterator();
assertThatExceptionOfType(Exception.class).isThrownBy(() -> { final boolean b = results.hasNext();
Page<NestedTestRecord> next = results.next(); }).withMessageContaining("ExpressionAttributeNames contains invalid value");
final Iterator<Page<NestedTestRecord>> resultsAttributeToProject =
mappedNestedTable.scan(
ScanEnhancedRequest.builder()
.filterExpression(expression)
.addAttributeToProject("").build()
).iterator();
assertThatExceptionOfType(Exception.class).isThrownBy(() -> {
final boolean b = resultsAttributeToProject.hasNext();
Page<NestedTestRecord> next = resultsAttributeToProject.next();
});
}
}
| 3,882 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/FlattenWithTagsTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.functionaltests;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primarySortKey;
import java.util.Objects;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema;
import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest;
public class FlattenWithTagsTest extends LocalDynamoDbSyncTestBase {
private static class Record {
private String id;
private Document document;
private String getId() {
return id;
}
private Record setId(String id) {
this.id = id;
return this;
}
private Document getDocument() {
return document;
}
private Record setDocument(Document document) {
this.document = document;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Record record = (Record) o;
return Objects.equals(id, record.id) &&
Objects.equals(document, record.document);
}
@Override
public int hashCode() {
return Objects.hash(id, document);
}
}
private static class Document {
private String documentAttribute1;
private String documentAttribute2;
private String documentAttribute3;
private String getDocumentAttribute1() {
return documentAttribute1;
}
private Document setDocumentAttribute1(String documentAttribute1) {
this.documentAttribute1 = documentAttribute1;
return this;
}
private String getDocumentAttribute2() {
return documentAttribute2;
}
private Document setDocumentAttribute2(String documentAttribute2) {
this.documentAttribute2 = documentAttribute2;
return this;
}
private String getDocumentAttribute3() {
return documentAttribute3;
}
private Document setDocumentAttribute3(String documentAttribute3) {
this.documentAttribute3 = documentAttribute3;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Document document = (Document) o;
return Objects.equals(documentAttribute1, document.documentAttribute1) &&
Objects.equals(documentAttribute2, document.documentAttribute2) &&
Objects.equals(documentAttribute3, document.documentAttribute3);
}
@Override
public int hashCode() {
return Objects.hash(documentAttribute1, documentAttribute2, documentAttribute3);
}
}
private static final StaticTableSchema<Document> DOCUMENT_SCHEMA =
StaticTableSchema.builder(Document.class)
.newItemSupplier(Document::new)
.addAttribute(String.class, a -> a.name("documentAttribute1")
.getter(Document::getDocumentAttribute1)
.setter(Document::setDocumentAttribute1)
.addTag(primarySortKey()))
.addAttribute(String.class, a -> a.name("documentAttribute2")
.getter(Document::getDocumentAttribute2)
.setter(Document::setDocumentAttribute2))
.addAttribute(String.class, a -> a.name("documentAttribute3")
.getter(Document::getDocumentAttribute3)
.setter(Document::setDocumentAttribute3))
.build();
private static final TableSchema<Record> TABLE_SCHEMA =
StaticTableSchema.builder(Record.class)
.newItemSupplier(Record::new)
.addAttribute(String.class, a -> a.name("id")
.getter(Record::getId)
.setter(Record::setId)
.tags(primaryPartitionKey()))
.flatten(DOCUMENT_SCHEMA, Record::getDocument, Record::setDocument)
.build();
private DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder()
.dynamoDbClient(getDynamoDbClient())
.build();
private DynamoDbTable<Record> mappedTable = enhancedClient.table(getConcreteTableName("table-name"), TABLE_SCHEMA);
@Before
public void createTable() {
mappedTable.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput()));
}
@After
public void deleteTable() {
getDynamoDbClient().deleteTable(DeleteTableRequest.builder()
.tableName(getConcreteTableName("table-name"))
.build());
}
@Test
public void update_allValues() {
Document document = new Document()
.setDocumentAttribute1("one")
.setDocumentAttribute2("two")
.setDocumentAttribute3("three");
Record record = new Record()
.setId("id-value")
.setDocument(document);
Record updatedRecord = mappedTable.updateItem(r -> r.item(record));
Record fetchedRecord = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id-value").sortValue("one")));
assertThat(updatedRecord, is(record));
assertThat(fetchedRecord, is(record));
}
@Test
public void update_someValues() {
Document document = new Document()
.setDocumentAttribute1("one")
.setDocumentAttribute2("two");
Record record = new Record()
.setId("id-value")
.setDocument(document);
Record updatedRecord = mappedTable.updateItem(r -> r.item(record));
Record fetchedRecord = mappedTable.getItem(r -> r.key(k -> k.partitionValue("id-value").sortValue("one")));
assertThat(updatedRecord, is(record));
assertThat(fetchedRecord, is(record));
}
}
| 3,883 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/AsyncTransactGetItemsTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.functionaltests;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import software.amazon.awssdk.enhanced.dynamodb.Document;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbAsyncTable;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedAsyncClient;
import software.amazon.awssdk.enhanced.dynamodb.Key;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.internal.client.DefaultDynamoDbEnhancedAsyncClient;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema;
import software.amazon.awssdk.enhanced.dynamodb.model.TransactGetItemsEnhancedRequest;
import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest;
public class AsyncTransactGetItemsTest extends LocalDynamoDbAsyncTestBase {
private static class Record1 {
private Integer id;
private Integer getId() {
return id;
}
private Record1 setId(Integer id) {
this.id = id;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Record1 record1 = (Record1) o;
return Objects.equals(id, record1.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}
private static class Record2 {
private Integer id;
private Integer getId() {
return id;
}
private Record2 setId(Integer id) {
this.id = id;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Record2 record2 = (Record2) o;
return Objects.equals(id, record2.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}
private static final TableSchema<Record1> TABLE_SCHEMA_1 =
StaticTableSchema.builder(Record1.class)
.newItemSupplier(Record1::new)
.addAttribute(Integer.class, a -> a.name("id_1")
.getter(Record1::getId)
.setter(Record1::setId)
.tags(primaryPartitionKey()))
.build();
private static final TableSchema<Record2> TABLE_SCHEMA_2 =
StaticTableSchema.builder(Record2.class)
.newItemSupplier(Record2::new)
.addAttribute(Integer.class, a -> a.name("id_2")
.getter(Record2::getId)
.setter(Record2::setId)
.tags(primaryPartitionKey()))
.build();
private DynamoDbEnhancedAsyncClient enhancedAsyncClient =
DefaultDynamoDbEnhancedAsyncClient.builder()
.dynamoDbClient(getDynamoDbAsyncClient())
.build();
private DynamoDbAsyncTable<Record1> mappedTable1 = enhancedAsyncClient.table(getConcreteTableName("table-name-1"),
TABLE_SCHEMA_1);
private DynamoDbAsyncTable<Record2> mappedTable2 = enhancedAsyncClient.table(getConcreteTableName("table-name-2"),
TABLE_SCHEMA_2);
private static final List<Record1> RECORDS_1 =
IntStream.range(0, 2)
.mapToObj(i -> new Record1().setId(i))
.collect(Collectors.toList());
private static final List<Record2> RECORDS_2 =
IntStream.range(0, 2)
.mapToObj(i -> new Record2().setId(i))
.collect(Collectors.toList());
@Before
public void createTable() {
mappedTable1.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput())).join();
mappedTable2.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput())).join();
}
@After
public void deleteTable() {
getDynamoDbAsyncClient().deleteTable(DeleteTableRequest.builder()
.tableName(getConcreteTableName("table-name-1"))
.build()).join();
getDynamoDbAsyncClient().deleteTable(DeleteTableRequest.builder()
.tableName(getConcreteTableName("table-name-2"))
.build()).join();
}
private void insertRecords() {
RECORDS_1.forEach(record -> mappedTable1.putItem(r -> r.item(record)).join());
RECORDS_2.forEach(record -> mappedTable2.putItem(r -> r.item(record)).join());
}
@Test
public void getRecordsFromMultipleTables() {
insertRecords();
TransactGetItemsEnhancedRequest transactGetItemsEnhancedRequest =
TransactGetItemsEnhancedRequest.builder()
.addGetItem(mappedTable1, Key.builder().partitionValue(0).build())
.addGetItem(mappedTable2, Key.builder().partitionValue(0).build())
.addGetItem(mappedTable2, Key.builder().partitionValue(1).build())
.addGetItem(mappedTable1, Key.builder().partitionValue(1).build())
.build();
List<Document> results = enhancedAsyncClient.transactGetItems(transactGetItemsEnhancedRequest).join();
assertThat(results.size(), is(4));
assertThat(results.get(0).getItem(mappedTable1), is(RECORDS_1.get(0)));
assertThat(results.get(1).getItem(mappedTable2), is(RECORDS_2.get(0)));
assertThat(results.get(2).getItem(mappedTable2), is(RECORDS_2.get(1)));
assertThat(results.get(3).getItem(mappedTable1), is(RECORDS_1.get(1)));
}
@Test
public void notFoundRecordReturnsNull() {
insertRecords();
TransactGetItemsEnhancedRequest transactGetItemsEnhancedRequest =
TransactGetItemsEnhancedRequest.builder()
.addGetItem(mappedTable1, Key.builder().partitionValue(0).build())
.addGetItem(mappedTable2, Key.builder().partitionValue(0).build())
.addGetItem(mappedTable2, Key.builder().partitionValue(5).build())
.addGetItem(mappedTable1, Key.builder().partitionValue(1).build())
.build();
List<Document> results = enhancedAsyncClient.transactGetItems(transactGetItemsEnhancedRequest).join();
assertThat(results.size(), is(4));
assertThat(results.get(0).getItem(mappedTable1), is(RECORDS_1.get(0)));
assertThat(results.get(1).getItem(mappedTable2), is(RECORDS_2.get(0)));
assertThat(results.get(2).getItem(mappedTable2), is(nullValue()));
assertThat(results.get(3).getItem(mappedTable1), is(RECORDS_1.get(1)));
}
}
| 3,884 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/GetItemWithResponseTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.functionaltests;
import static org.assertj.core.api.Assertions.assertThat;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey;
import java.util.Arrays;
import java.util.Objects;
import org.assertj.core.data.Offset;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema;
import software.amazon.awssdk.enhanced.dynamodb.model.GetItemEnhancedResponse;
import software.amazon.awssdk.services.dynamodb.model.ConsumedCapacity;
import software.amazon.awssdk.services.dynamodb.model.ReturnConsumedCapacity;
public class GetItemWithResponseTest extends LocalDynamoDbSyncTestBase {
private static final String TEST_TABLE_NAME = "get-item-table-name-2";
private static final TableSchema<Record> TABLE_SCHEMA =
StaticTableSchema.builder(Record.class)
.newItemSupplier(Record::new)
.addAttribute(Integer.class, a -> a.name("id_1")
.getter(Record::getId)
.setter(Record::setId)
.tags(primaryPartitionKey()))
.addAttribute(String.class, a -> a.name("stringAttr1")
.getter(Record::getStringAttr1)
.setter(Record::setStringAttr1))
.build();
private final DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder()
.dynamoDbClient(getDynamoDbClient())
.build();
private final DynamoDbTable<Record> mappedTable1 = enhancedClient.table(
getConcreteTableName(TEST_TABLE_NAME),
TABLE_SCHEMA
);
@Before
public void createTable() {
mappedTable1.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput()));
}
@After
public void deleteTable() {
getDynamoDbClient().deleteTable(r -> r.tableName(getConcreteTableName(TEST_TABLE_NAME)));
}
@Test
public void getItemWithResponse_when_recordIsAbsent() {
GetItemEnhancedResponse<Record> response = mappedTable1.getItemWithResponse(
r -> r.key(k -> k.partitionValue(404))
);
assertThat(response.attributes()).isNull();
assertThat(response.consumedCapacity()).isNull();
}
@Test
public void getItemWithResponse_when_recordIsPresent() {
Record original = new Record().setId(1).setStringAttr1("a");
mappedTable1.putItem(original);
GetItemEnhancedResponse<Record> response = mappedTable1.getItemWithResponse(
r -> r.key(k -> k.partitionValue(original.getId()))
);
assertThat(response.attributes()).isNotNull();
assertThat(response.attributes()).isEqualTo(original);
assertThat(response.consumedCapacity()).isNull();
}
@Test
public void getItemWithResponse_withReturnConsumedCapacity_when_recordIsAbsent_eventuallyConsistent() {
GetItemEnhancedResponse<Record> response = mappedTable1.getItemWithResponse(
r -> r.key(k -> k.partitionValue(404))
.returnConsumedCapacity(ReturnConsumedCapacity.TOTAL)
.consistentRead(false)
);
assertThat(response.attributes()).isNull();
ConsumedCapacity consumedCapacity = response.consumedCapacity();
assertThat(consumedCapacity).isNotNull();
assertThat(consumedCapacity.capacityUnits()).isCloseTo(0.5, Offset.offset(0.01));
}
@Test
public void getItemWithResponse_withReturnConsumedCapacity_when_recordIsAbsent_stronglyConsistent() {
GetItemEnhancedResponse<Record> response = mappedTable1.getItemWithResponse(
r -> r.key(k -> k.partitionValue(404))
.returnConsumedCapacity(ReturnConsumedCapacity.TOTAL)
.consistentRead(true)
);
assertThat(response.attributes()).isNull();
ConsumedCapacity consumedCapacity = response.consumedCapacity();
assertThat(consumedCapacity).isNotNull();
assertThat(consumedCapacity.capacityUnits()).isCloseTo(1.0, Offset.offset(0.01));
}
@Test
public void getItemWithResponse_withReturnConsumedCapacity_when_recordIsPresent_eventuallyConsistent() {
Record original = new Record().setId(126).setStringAttr1(getStringAttrValue(100_000));
mappedTable1.putItem(original);
GetItemEnhancedResponse<Record> response = mappedTable1.getItemWithResponse(
r -> r.key(k -> k.partitionValue(126))
.returnConsumedCapacity(ReturnConsumedCapacity.TOTAL)
.consistentRead(false)
);
assertThat(response.attributes()).isEqualTo(original);
ConsumedCapacity consumedCapacity = response.consumedCapacity();
assertThat(consumedCapacity).isNotNull();
assertThat(consumedCapacity.capacityUnits()).isCloseTo(12.5, Offset.offset(0.01));
}
@Test
public void getItemWithResponse_withReturnConsumedCapacity_when_recordIsPresent_stronglyConsistent() {
Record original = new Record().setId(142).setStringAttr1(getStringAttrValue(100_000));
mappedTable1.putItem(original);
GetItemEnhancedResponse<Record> response = mappedTable1.getItemWithResponse(
r -> r.key(k -> k.partitionValue(142))
.returnConsumedCapacity(ReturnConsumedCapacity.TOTAL)
.consistentRead(true)
);
assertThat(response.attributes()).isEqualTo(original);
ConsumedCapacity consumedCapacity = response.consumedCapacity();
assertThat(consumedCapacity).isNotNull();
assertThat(consumedCapacity.capacityUnits()).isCloseTo(25.0, Offset.offset(0.01));
}
private static String getStringAttrValue(int numChars) {
char[] chars = new char[numChars];
Arrays.fill(chars, 'a');
return new String(chars);
}
private static class Record {
private Integer id;
private String stringAttr1;
private Integer getId() {
return id;
}
private Record setId(Integer id) {
this.id = id;
return this;
}
private String getStringAttr1() {
return stringAttr1;
}
private Record setStringAttr1(String stringAttr1) {
this.stringAttr1 = stringAttr1;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Record record = (Record) o;
return Objects.equals(id, record.id) && Objects.equals(stringAttr1, record.stringAttr1);
}
@Override
public int hashCode() {
return Objects.hash(id, stringAttr1);
}
}
}
| 3,885 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/LocalDynamoDbTestBase.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.functionaltests;
import java.util.UUID;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughput;
public class LocalDynamoDbTestBase {
private static final LocalDynamoDb localDynamoDb = new LocalDynamoDb();
private static final ProvisionedThroughput DEFAULT_PROVISIONED_THROUGHPUT =
ProvisionedThroughput.builder()
.readCapacityUnits(50L)
.writeCapacityUnits(50L)
.build();
private String uniqueTableSuffix = UUID.randomUUID().toString();
@BeforeClass
public static void initializeLocalDynamoDb() {
localDynamoDb.start();
}
@AfterClass
public static void stopLocalDynamoDb() {
localDynamoDb.stop();
}
protected static LocalDynamoDb localDynamoDb() {
return localDynamoDb;
}
protected String getConcreteTableName(String logicalTableName) {
return logicalTableName + "_" + uniqueTableSuffix;
}
protected ProvisionedThroughput getDefaultProvisionedThroughput() {
return DEFAULT_PROVISIONED_THROUGHPUT;
}
}
| 3,886 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/TransactWriteItemsTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.functionaltests;
import static java.util.Collections.singletonMap;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.fail;
import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.stringValue;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable;
import software.amazon.awssdk.enhanced.dynamodb.Expression;
import software.amazon.awssdk.enhanced.dynamodb.Key;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema;
import software.amazon.awssdk.enhanced.dynamodb.model.ConditionCheck;
import software.amazon.awssdk.enhanced.dynamodb.model.TransactDeleteItemEnhancedRequest;
import software.amazon.awssdk.enhanced.dynamodb.model.TransactPutItemEnhancedRequest;
import software.amazon.awssdk.enhanced.dynamodb.model.TransactUpdateItemEnhancedRequest;
import software.amazon.awssdk.enhanced.dynamodb.model.TransactWriteItemsEnhancedRequest;
import software.amazon.awssdk.services.dynamodb.model.CancellationReason;
import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest;
import software.amazon.awssdk.services.dynamodb.model.ReturnValuesOnConditionCheckFailure;
import software.amazon.awssdk.services.dynamodb.model.TransactionCanceledException;
public class TransactWriteItemsTest extends LocalDynamoDbSyncTestBase {
private static class Record1 {
private Integer id;
private String attribute;
private Integer getId() {
return id;
}
private Record1 setId(Integer id) {
this.id = id;
return this;
}
private String getAttribute() {
return attribute;
}
private Record1 setAttribute(String attribute) {
this.attribute = attribute;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Record1 record1 = (Record1) o;
return Objects.equals(id, record1.id) &&
Objects.equals(attribute, record1.attribute);
}
@Override
public int hashCode() {
return Objects.hash(id, attribute);
}
}
private static class Record2 {
private Integer id;
private String attribute;
private Integer getId() {
return id;
}
private Record2 setId(Integer id) {
this.id = id;
return this;
}
private String getAttribute() {
return attribute;
}
private Record2 setAttribute(String attribute) {
this.attribute = attribute;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Record2 record2 = (Record2) o;
return Objects.equals(id, record2.id) &&
Objects.equals(attribute, record2.attribute);
}
@Override
public int hashCode() {
return Objects.hash(id, attribute);
}
}
private static final TableSchema<Record1> TABLE_SCHEMA_1 =
StaticTableSchema.builder(Record1.class)
.newItemSupplier(Record1::new)
.addAttribute(Integer.class, a -> a.name("id_1")
.getter(Record1::getId)
.setter(Record1::setId)
.tags(primaryPartitionKey()))
.addAttribute(String.class, a -> a.name("attribute")
.getter(Record1::getAttribute)
.setter(Record1::setAttribute))
.build();
private static final TableSchema<Record2> TABLE_SCHEMA_2 =
StaticTableSchema.builder(Record2.class)
.newItemSupplier(Record2::new)
.addAttribute(Integer.class, a -> a.name("id_2")
.getter(Record2::getId)
.setter(Record2::setId)
.tags(primaryPartitionKey()))
.addAttribute(String.class, a -> a.name("attribute")
.getter(Record2::getAttribute)
.setter(Record2::setAttribute))
.build();
private DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder()
.dynamoDbClient(getDynamoDbClient())
.build();
private DynamoDbTable<Record1> mappedTable1 = enhancedClient.table(getConcreteTableName("table-name-1"), TABLE_SCHEMA_1);
private DynamoDbTable<Record2> mappedTable2 = enhancedClient.table(getConcreteTableName("table-name-2"), TABLE_SCHEMA_2);
private static final List<Record1> RECORDS_1 =
IntStream.range(0, 2)
.mapToObj(i -> new Record1().setId(i).setAttribute(Integer.toString(i)))
.collect(Collectors.toList());
private static final List<Record2> RECORDS_2 =
IntStream.range(0, 2)
.mapToObj(i -> new Record2().setId(i).setAttribute(Integer.toString(i)))
.collect(Collectors.toList());
@Before
public void createTable() {
mappedTable1.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput()));
mappedTable2.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput()));
}
@After
public void deleteTable() {
getDynamoDbClient().deleteTable(DeleteTableRequest.builder()
.tableName(getConcreteTableName("table-name-1"))
.build());
getDynamoDbClient().deleteTable(DeleteTableRequest.builder()
.tableName(getConcreteTableName("table-name-2"))
.build());
}
@Test
public void singlePut() {
enhancedClient.transactWriteItems(
TransactWriteItemsEnhancedRequest.builder()
.addPutItem(mappedTable1, RECORDS_1.get(0))
.build());
Record1 record = mappedTable1.getItem(r -> r.key(k -> k.partitionValue(0)));
assertThat(record, is(RECORDS_1.get(0)));
}
@Test
public void multiplePut() {
enhancedClient.transactWriteItems(
TransactWriteItemsEnhancedRequest.builder()
.addPutItem(mappedTable1, RECORDS_1.get(0))
.addPutItem(mappedTable2, RECORDS_2.get(0))
.build());
Record1 record1 = mappedTable1.getItem(r -> r.key(k -> k.partitionValue(0)));
Record2 record2 = mappedTable2.getItem(r -> r.key(k -> k.partitionValue(0)));
assertThat(record1, is(RECORDS_1.get(0)));
assertThat(record2, is(RECORDS_2.get(0)));
}
@Test
public void singleUpdate() {
enhancedClient.transactWriteItems(
TransactWriteItemsEnhancedRequest.builder()
.addUpdateItem(mappedTable1, RECORDS_1.get(0))
.build());
Record1 record = mappedTable1.getItem(r -> r.key(k -> k.partitionValue(0)));
assertThat(record, is(RECORDS_1.get(0)));
}
@Test
public void multipleUpdate() {
enhancedClient.transactWriteItems(
TransactWriteItemsEnhancedRequest.builder()
.addUpdateItem(mappedTable1, RECORDS_1.get(0))
.addUpdateItem(mappedTable2, RECORDS_2.get(0))
.build());
Record1 record1 = mappedTable1.getItem(r -> r.key(k -> k.partitionValue(0)));
Record2 record2 = mappedTable2.getItem(r -> r.key(k -> k.partitionValue(0)));
assertThat(record1, is(RECORDS_1.get(0)));
assertThat(record2, is(RECORDS_2.get(0)));
}
@Test
public void singleDelete() {
mappedTable1.putItem(r -> r.item(RECORDS_1.get(0)));
enhancedClient.transactWriteItems(
TransactWriteItemsEnhancedRequest.builder()
.addDeleteItem(mappedTable1, RECORDS_1.get(0))
.build());
Record1 record = mappedTable1.getItem(r -> r.key(k -> k.partitionValue(0)));
assertThat(record, is(nullValue()));
}
@Test
public void multipleDelete() {
mappedTable1.putItem(r -> r.item(RECORDS_1.get(0)));
mappedTable2.putItem(r -> r.item(RECORDS_2.get(0)));
enhancedClient.transactWriteItems(
TransactWriteItemsEnhancedRequest.builder()
.addDeleteItem(mappedTable1, RECORDS_1.get(0))
.addDeleteItem(mappedTable2, RECORDS_2.get(0))
.build());
Record1 record1 = mappedTable1.getItem(r -> r.key(k -> k.partitionValue(0)));
Record2 record2 = mappedTable2.getItem(r -> r.key(k -> k.partitionValue(0)));
assertThat(record1, is(nullValue()));
assertThat(record2, is(nullValue()));
}
@Test
public void singleConditionCheck() {
mappedTable1.putItem(r -> r.item(RECORDS_1.get(0)));
Expression conditionExpression = Expression.builder()
.expression("#attribute = :attribute")
.expressionValues(singletonMap(":attribute", stringValue("0")))
.expressionNames(singletonMap("#attribute", "attribute"))
.build();
Key key = Key.builder().partitionValue(0).build();
enhancedClient.transactWriteItems(
TransactWriteItemsEnhancedRequest.builder()
.addConditionCheck(mappedTable1, ConditionCheck.builder()
.key(key)
.conditionExpression(conditionExpression)
.build())
.build());
}
@Test
public void multiConditionCheck() {
mappedTable1.putItem(r -> r.item(RECORDS_1.get(0)));
mappedTable2.putItem(r -> r.item(RECORDS_2.get(0)));
Expression conditionExpression = Expression.builder()
.expression("#attribute = :attribute")
.expressionValues(singletonMap(":attribute", stringValue("0")))
.expressionNames(singletonMap("#attribute", "attribute"))
.build();
Key key1 = Key.builder().partitionValue(0).build();
Key key2 = Key.builder().partitionValue(0).build();
enhancedClient.transactWriteItems(
TransactWriteItemsEnhancedRequest.builder()
.addConditionCheck(mappedTable1, ConditionCheck.builder()
.key(key1)
.conditionExpression(conditionExpression)
.build())
.addConditionCheck(mappedTable2, ConditionCheck.builder()
.key(key2)
.conditionExpression(conditionExpression)
.build())
.build());
}
@Test
public void mixedCommands() {
mappedTable1.putItem(r -> r.item(RECORDS_1.get(0)));
mappedTable2.putItem(r -> r.item(RECORDS_2.get(0)));
Expression conditionExpression = Expression.builder()
.expression("#attribute = :attribute")
.expressionValues(singletonMap(":attribute", stringValue("0")))
.expressionNames(singletonMap("#attribute", "attribute"))
.build();
Key key = Key.builder().partitionValue(0).build();
TransactWriteItemsEnhancedRequest transactWriteItemsEnhancedRequest =
TransactWriteItemsEnhancedRequest.builder()
.addConditionCheck(mappedTable1, ConditionCheck.builder()
.key(key)
.conditionExpression(conditionExpression)
.build())
.addPutItem(mappedTable2, RECORDS_2.get(1))
.addUpdateItem(mappedTable1,RECORDS_1.get(1))
.addDeleteItem(mappedTable2, RECORDS_2.get(0))
.build();
enhancedClient.transactWriteItems(transactWriteItemsEnhancedRequest);
assertThat(mappedTable1.getItem(r -> r.key(k -> k.partitionValue(1))), is(RECORDS_1.get(1)));
assertThat(mappedTable2.getItem(r -> r.key(k -> k.partitionValue(0))), is(nullValue()));
assertThat(mappedTable2.getItem(r -> r.key(k -> k.partitionValue(1))), is(RECORDS_2.get(1)));
}
@Test
public void mixedCommands_conditionCheckFailsTransaction() {
mappedTable1.putItem(r -> r.item(RECORDS_1.get(0)));
mappedTable2.putItem(r -> r.item(RECORDS_2.get(0)));
Expression conditionExpression = Expression.builder()
.expression("#attribute = :attribute")
.expressionValues(singletonMap(":attribute", stringValue("1")))
.expressionNames(singletonMap("#attribute", "attribute"))
.build();
Key key = Key.builder().partitionValue(0).build();
TransactWriteItemsEnhancedRequest transactWriteItemsEnhancedRequest =
TransactWriteItemsEnhancedRequest.builder()
.addPutItem(mappedTable2, RECORDS_2.get(1))
.addUpdateItem(mappedTable1, RECORDS_1.get(1))
.addConditionCheck(mappedTable1, ConditionCheck.builder()
.key(key)
.conditionExpression(conditionExpression)
.build())
.addDeleteItem(mappedTable2, RECORDS_2.get(0))
.build();
try {
enhancedClient.transactWriteItems(transactWriteItemsEnhancedRequest);
fail("Expected TransactionCanceledException to be thrown");
} catch(TransactionCanceledException ignored) {
}
assertThat(mappedTable1.getItem(r -> r.key(k -> k.partitionValue(1))), is(nullValue()));
assertThat(mappedTable2.getItem(r -> r.key(k -> k.partitionValue(0))), is(RECORDS_2.get(0)));
assertThat(mappedTable2.getItem(r -> r.key(k -> k.partitionValue(1))), is(nullValue()));
}
@Test
public void mixedCommands_returnValuesOnConditionCheckFailureSet_allConditionsFail() {
mappedTable1.putItem(r -> r.item(RECORDS_1.get(0)));
mappedTable1.putItem(r -> r.item(RECORDS_1.get(1)));
mappedTable2.putItem(r -> r.item(RECORDS_2.get(0)));
Expression conditionExpression = Expression.builder()
.expression("#attribute = :attribute")
.expressionValues(singletonMap(":attribute", stringValue("99")))
.expressionNames(singletonMap("#attribute", "attribute"))
.build();
Key key0 = Key.builder().partitionValue(0).build();
Key key1 = Key.builder().partitionValue(1).build();
ReturnValuesOnConditionCheckFailure returnValues = ReturnValuesOnConditionCheckFailure.ALL_OLD;
TransactPutItemEnhancedRequest<Record2> putItemRequest = TransactPutItemEnhancedRequest.builder(Record2.class)
.conditionExpression(conditionExpression)
.item(RECORDS_2.get(0))
.returnValuesOnConditionCheckFailure(returnValues)
.build();
TransactUpdateItemEnhancedRequest<Record1> updateItemRequest = TransactUpdateItemEnhancedRequest.builder(Record1.class)
.conditionExpression(conditionExpression)
.item(RECORDS_1.get(0))
.returnValuesOnConditionCheckFailure(returnValues)
.build();
TransactDeleteItemEnhancedRequest deleteItemRequest = TransactDeleteItemEnhancedRequest.builder()
.key(key1)
.conditionExpression(conditionExpression)
.returnValuesOnConditionCheckFailure(returnValues)
.build();
TransactWriteItemsEnhancedRequest transactWriteItemsEnhancedRequest =
TransactWriteItemsEnhancedRequest.builder()
.addPutItem(mappedTable2, putItemRequest)
.addUpdateItem(mappedTable1, updateItemRequest)
.addConditionCheck(mappedTable1, ConditionCheck.builder()
.key(key0)
.conditionExpression(conditionExpression)
.returnValuesOnConditionCheckFailure(returnValues)
.build())
.addDeleteItem(mappedTable1, deleteItemRequest)
.build();
try {
enhancedClient.transactWriteItems(transactWriteItemsEnhancedRequest);
fail("Expected TransactionCanceledException to be thrown");
} catch(TransactionCanceledException e) {
List<CancellationReason> cancellationReasons = e.cancellationReasons();
assertThat(cancellationReasons.size(), is(4));
cancellationReasons.forEach(r -> assertThat(r.item().isEmpty(), is(false)));
}
}
}
| 3,887 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/AsyncGetItemWithResponseTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.functionaltests;
import static org.assertj.core.api.Assertions.assertThat;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey;
import java.util.Arrays;
import java.util.Objects;
import org.assertj.core.data.Offset;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbAsyncTable;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedAsyncClient;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema;
import software.amazon.awssdk.enhanced.dynamodb.model.GetItemEnhancedResponse;
import software.amazon.awssdk.services.dynamodb.model.ConsumedCapacity;
import software.amazon.awssdk.services.dynamodb.model.ReturnConsumedCapacity;
public class AsyncGetItemWithResponseTest extends LocalDynamoDbAsyncTestBase {
private static final String TEST_TABLE_NAME = "get-item-table-name-2";
private static final TableSchema<Record> TABLE_SCHEMA =
StaticTableSchema.builder(Record.class)
.newItemSupplier(Record::new)
.addAttribute(Integer.class, a -> a.name("id_1")
.getter(Record::getId)
.setter(Record::setId)
.tags(primaryPartitionKey()))
.addAttribute(String.class, a -> a.name("stringAttr1")
.getter(Record::getStringAttr1)
.setter(Record::setStringAttr1))
.build();
private final DynamoDbEnhancedAsyncClient enhancedClient = DynamoDbEnhancedAsyncClient.builder()
.dynamoDbClient(getDynamoDbAsyncClient())
.build();
private final DynamoDbAsyncTable<Record> mappedTable1 = enhancedClient.table(
getConcreteTableName(TEST_TABLE_NAME),
TABLE_SCHEMA
);
@Before
public void createTable() {
mappedTable1.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput())).join();
}
@After
public void deleteTable() {
getDynamoDbAsyncClient().deleteTable(r -> r.tableName(getConcreteTableName(TEST_TABLE_NAME))).join();
}
@Test
public void getItemWithResponse_when_recordIsAbsent() {
GetItemEnhancedResponse<Record> response = mappedTable1.getItemWithResponse(
r -> r.key(k -> k.partitionValue(404))
).join();
assertThat(response.attributes()).isNull();
assertThat(response.consumedCapacity()).isNull();
}
@Test
public void getItemWithResponse_when_recordIsPresent() {
Record original = new Record().setId(1).setStringAttr1("a");
mappedTable1.putItem(original).join();
GetItemEnhancedResponse<Record> response = mappedTable1.getItemWithResponse(
r -> r.key(k -> k.partitionValue(original.getId()))
).join();
assertThat(response.attributes()).isEqualTo(original);
assertThat(response.consumedCapacity()).isNull();
}
@Test
public void getItemWithResponse_withReturnConsumedCapacity_when_recordIsAbsent_eventuallyConsistent() {
GetItemEnhancedResponse<Record> response = mappedTable1.getItemWithResponse(
r -> r.key(k -> k.partitionValue(404))
.returnConsumedCapacity(ReturnConsumedCapacity.TOTAL)
.consistentRead(false)
).join();
assertThat(response.attributes()).isNull();
ConsumedCapacity consumedCapacity = response.consumedCapacity();
assertThat(consumedCapacity).isNotNull();
assertThat(consumedCapacity.capacityUnits()).isCloseTo(0.5, Offset.offset(0.01));
}
@Test
public void getItemWithResponse_withReturnConsumedCapacity_when_recordIsAbsent_stronglyConsistent() {
GetItemEnhancedResponse<Record> response = mappedTable1.getItemWithResponse(
r -> r.key(k -> k.partitionValue(404))
.returnConsumedCapacity(ReturnConsumedCapacity.TOTAL)
.consistentRead(true)
).join();
assertThat(response.attributes()).isNull();
ConsumedCapacity consumedCapacity = response.consumedCapacity();
assertThat(consumedCapacity).isNotNull();
assertThat(consumedCapacity.capacityUnits()).isCloseTo(1.0, Offset.offset(0.01));
}
@Test
public void getItemWithResponse_withReturnConsumedCapacity_when_recordIsPresent_eventuallyConsistent() {
Record original = new Record().setId(126).setStringAttr1(getStringAttrValue(100_000));
mappedTable1.putItem(original).join();
GetItemEnhancedResponse<Record> response = mappedTable1.getItemWithResponse(
r -> r.key(k -> k.partitionValue(126))
.returnConsumedCapacity(ReturnConsumedCapacity.TOTAL)
.consistentRead(false)
).join();
assertThat(response.attributes()).isEqualTo(original);
ConsumedCapacity consumedCapacity = response.consumedCapacity();
assertThat(consumedCapacity).isNotNull();
assertThat(consumedCapacity.capacityUnits()).isCloseTo(12.5, Offset.offset(0.01));
}
@Test
public void getItemWithResponse_withReturnConsumedCapacity_when_recordIsPresent_stronglyConsistent() {
Record original = new Record().setId(142).setStringAttr1(getStringAttrValue(100_000));
mappedTable1.putItem(original).join();
GetItemEnhancedResponse<Record> response = mappedTable1.getItemWithResponse(
r -> r.key(k -> k.partitionValue(142))
.returnConsumedCapacity(ReturnConsumedCapacity.TOTAL)
.consistentRead(true)
).join();
assertThat(response.attributes()).isEqualTo(original);
ConsumedCapacity consumedCapacity = response.consumedCapacity();
assertThat(consumedCapacity).isNotNull();
assertThat(consumedCapacity.capacityUnits()).isCloseTo(25.0, Offset.offset(0.01));
}
private static String getStringAttrValue(int numChars) {
char[] chars = new char[numChars];
Arrays.fill(chars, 'a');
return new String(chars);
}
private static class Record {
private Integer id;
private String stringAttr1;
private Integer getId() {
return id;
}
private Record setId(Integer id) {
this.id = id;
return this;
}
private String getStringAttr1() {
return stringAttr1;
}
private Record setStringAttr1(String stringAttr1) {
this.stringAttr1 = stringAttr1;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Record record = (Record) o;
return Objects.equals(id, record.id) && Objects.equals(stringAttr1, record.stringAttr1);
}
@Override
public int hashCode() {
return Objects.hash(id, stringAttr1);
}
}
}
| 3,888 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/UpdateBehaviorTest.java | package software.amazon.awssdk.enhanced.dynamodb.functionaltests;
import static org.assertj.core.api.Assertions.assertThat;
import java.time.Instant;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.extensions.AutoGeneratedTimestampRecordExtension;
import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.NestedRecordWithUpdateBehavior;
import software.amazon.awssdk.enhanced.dynamodb.functionaltests.models.RecordWithUpdateBehaviors;
import software.amazon.awssdk.enhanced.dynamodb.internal.client.ExtensionResolver;
public class UpdateBehaviorTest extends LocalDynamoDbSyncTestBase {
private static final Instant INSTANT_1 = Instant.parse("2020-05-03T10:00:00Z");
private static final Instant INSTANT_2 = Instant.parse("2020-05-03T10:05:00Z");
private static final Instant FAR_FUTURE_INSTANT = Instant.parse("9999-05-03T10:05:00Z");
private static final TableSchema<RecordWithUpdateBehaviors> TABLE_SCHEMA =
TableSchema.fromClass(RecordWithUpdateBehaviors.class);
private final DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder()
.dynamoDbClient(getDynamoDbClient()).extensions(
Stream.concat(ExtensionResolver.defaultExtensions().stream(),
Stream.of(AutoGeneratedTimestampRecordExtension.create())).collect(Collectors.toList()))
.build();
private final DynamoDbTable<RecordWithUpdateBehaviors> mappedTable =
enhancedClient.table(getConcreteTableName("table-name"), TABLE_SCHEMA);
@Before
public void createTable() {
mappedTable.createTable(r -> r.provisionedThroughput(getDefaultProvisionedThroughput()));
}
@After
public void deleteTable() {
getDynamoDbClient().deleteTable(r -> r.tableName(getConcreteTableName("table-name")));
}
@Test
public void updateBehaviors_firstUpdate() {
Instant currentTime = Instant.now();
RecordWithUpdateBehaviors record = new RecordWithUpdateBehaviors();
record.setId("id123");
record.setCreatedOn(INSTANT_1);
record.setLastUpdatedOn(INSTANT_2);
mappedTable.updateItem(record);
RecordWithUpdateBehaviors persistedRecord = mappedTable.getItem(record);
assertThat(persistedRecord.getVersion()).isEqualTo(1L);
assertThat(persistedRecord.getCreatedOn()).isEqualTo(INSTANT_1);
assertThat(persistedRecord.getLastUpdatedOn()).isEqualTo(INSTANT_2);
assertThat(persistedRecord.getLastAutoUpdatedOn()).isAfterOrEqualTo(currentTime);
assertThat(persistedRecord.getFormattedLastAutoUpdatedOn().getEpochSecond())
.isGreaterThanOrEqualTo(currentTime.getEpochSecond());
assertThat(persistedRecord.getLastAutoUpdatedOnMillis().getEpochSecond()).isGreaterThanOrEqualTo(currentTime.getEpochSecond());
assertThat(persistedRecord.getCreatedAutoUpdateOn()).isAfterOrEqualTo(currentTime);
}
@Test
public void updateBehaviors_secondUpdate() {
Instant beforeUpdateInstant = Instant.now();
RecordWithUpdateBehaviors record = new RecordWithUpdateBehaviors();
record.setId("id123");
record.setCreatedOn(INSTANT_1);
record.setLastUpdatedOn(INSTANT_2);
mappedTable.updateItem(record);
RecordWithUpdateBehaviors persistedRecord = mappedTable.getItem(record);
assertThat(persistedRecord.getVersion()).isEqualTo(1L);
Instant firstUpdatedTime = persistedRecord.getLastAutoUpdatedOn();
Instant createdAutoUpdateOn = persistedRecord.getCreatedAutoUpdateOn();
assertThat(firstUpdatedTime).isAfterOrEqualTo(beforeUpdateInstant);
assertThat(persistedRecord.getFormattedLastAutoUpdatedOn().getEpochSecond())
.isGreaterThanOrEqualTo(beforeUpdateInstant.getEpochSecond());
record.setVersion(1L);
record.setCreatedOn(INSTANT_2);
record.setLastUpdatedOn(INSTANT_2);
mappedTable.updateItem(record);
persistedRecord = mappedTable.getItem(record);
assertThat(persistedRecord.getVersion()).isEqualTo(2L);
assertThat(persistedRecord.getCreatedOn()).isEqualTo(INSTANT_1);
assertThat(persistedRecord.getLastUpdatedOn()).isEqualTo(INSTANT_2);
Instant secondUpdatedTime = persistedRecord.getLastAutoUpdatedOn();
assertThat(secondUpdatedTime).isAfterOrEqualTo(firstUpdatedTime);
assertThat(persistedRecord.getCreatedAutoUpdateOn()).isEqualTo(createdAutoUpdateOn);
}
@Test
public void updateBehaviors_removal() {
RecordWithUpdateBehaviors record = new RecordWithUpdateBehaviors();
record.setId("id123");
record.setCreatedOn(INSTANT_1);
record.setLastUpdatedOn(INSTANT_2);
record.setLastAutoUpdatedOn(FAR_FUTURE_INSTANT);
mappedTable.updateItem(record);
RecordWithUpdateBehaviors persistedRecord = mappedTable.getItem(record);
Instant createdAutoUpdateOn = persistedRecord.getCreatedAutoUpdateOn();
assertThat(persistedRecord.getLastAutoUpdatedOn()).isBefore(FAR_FUTURE_INSTANT);
record.setVersion(1L);
record.setCreatedOn(null);
record.setLastUpdatedOn(null);
record.setLastAutoUpdatedOn(null);
mappedTable.updateItem(record);
persistedRecord = mappedTable.getItem(record);
assertThat(persistedRecord.getCreatedOn()).isNull();
assertThat(persistedRecord.getLastUpdatedOn()).isNull();
assertThat(persistedRecord.getLastAutoUpdatedOn()).isNotNull();
assertThat(persistedRecord.getCreatedAutoUpdateOn()).isEqualTo(createdAutoUpdateOn);
}
@Test
public void updateBehaviors_transactWriteItems_secondUpdate() {
RecordWithUpdateBehaviors record = new RecordWithUpdateBehaviors();
record.setId("id123");
record.setCreatedOn(INSTANT_1);
record.setLastUpdatedOn(INSTANT_2);
record.setLastAutoUpdatedOn(INSTANT_2);
RecordWithUpdateBehaviors firstUpdatedRecord = mappedTable.updateItem(record);
record.setVersion(1L);
record.setCreatedOn(INSTANT_2);
record.setLastUpdatedOn(INSTANT_2);
record.setLastAutoUpdatedOn(INSTANT_2);
enhancedClient.transactWriteItems(r -> r.addUpdateItem(mappedTable, record));
RecordWithUpdateBehaviors persistedRecord = mappedTable.getItem(record);
assertThat(persistedRecord.getCreatedOn()).isEqualTo(INSTANT_1);
assertThat(persistedRecord.getLastUpdatedOn()).isEqualTo(INSTANT_2);
assertThat(persistedRecord.getLastAutoUpdatedOn()).isAfterOrEqualTo(INSTANT_2);
assertThat(persistedRecord.getCreatedAutoUpdateOn()).isEqualTo(firstUpdatedRecord.getCreatedAutoUpdateOn());
}
/**
* Currently, nested records are not updated through extensions.
*/
@Test
public void updateBehaviors_nested() {
NestedRecordWithUpdateBehavior nestedRecord = new NestedRecordWithUpdateBehavior();
nestedRecord.setId("id456");
RecordWithUpdateBehaviors record = new RecordWithUpdateBehaviors();
record.setId("id123");
record.setCreatedOn(INSTANT_1);
record.setLastUpdatedOn(INSTANT_2);
record.setNestedRecord(nestedRecord);
mappedTable.updateItem(record);
RecordWithUpdateBehaviors persistedRecord = mappedTable.getItem(record);
assertThat(persistedRecord.getVersion()).isEqualTo(1L);
assertThat(persistedRecord.getNestedRecord()).isNotNull();
assertThat(persistedRecord.getNestedRecord().getNestedVersionedAttribute()).isNull();
assertThat(persistedRecord.getNestedRecord().getNestedCounter()).isNull();
assertThat(persistedRecord.getNestedRecord().getNestedUpdateBehaviorAttribute()).isNull();
assertThat(persistedRecord.getNestedRecord().getNestedTimeAttribute()).isNull();
}
}
| 3,889 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/models/RecordWithUpdateBehaviors.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.functionaltests.models;
import java.time.Instant;
import software.amazon.awssdk.enhanced.dynamodb.converters.EpochMillisFormatTestConverter;
import software.amazon.awssdk.enhanced.dynamodb.converters.TimeFormatUpdateTestConverter;
import software.amazon.awssdk.enhanced.dynamodb.extensions.annotations.DynamoDbAutoGeneratedTimestampAttribute;
import software.amazon.awssdk.enhanced.dynamodb.extensions.annotations.DynamoDbVersionAttribute;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbAttribute;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbConvertedBy;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbUpdateBehavior;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.UpdateBehavior.WRITE_IF_NOT_EXISTS;
@DynamoDbBean
public class RecordWithUpdateBehaviors {
private String id;
private Instant createdOn;
private Instant lastUpdatedOn;
private Instant createdAutoUpdateOn;
private Instant lastAutoUpdatedOn;
private Long version;
private Instant lastAutoUpdatedOnMillis;
private Instant formattedLastAutoUpdatedOn;
private NestedRecordWithUpdateBehavior nestedRecord;
@DynamoDbPartitionKey
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@DynamoDbUpdateBehavior(WRITE_IF_NOT_EXISTS)
@DynamoDbAttribute("created-on") // Forces a test on attribute name cleaning
public Instant getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Instant createdOn) {
this.createdOn = createdOn;
}
public Instant getLastUpdatedOn() {
return lastUpdatedOn;
}
public void setLastUpdatedOn(Instant lastUpdatedOn) {
this.lastUpdatedOn = lastUpdatedOn;
}
@DynamoDbUpdateBehavior(WRITE_IF_NOT_EXISTS)
@DynamoDbAutoGeneratedTimestampAttribute
public Instant getCreatedAutoUpdateOn() {
return createdAutoUpdateOn;
}
public void setCreatedAutoUpdateOn(Instant createdAutoUpdateOn) {
this.createdAutoUpdateOn = createdAutoUpdateOn;
}
@DynamoDbAutoGeneratedTimestampAttribute
public Instant getLastAutoUpdatedOn() {
return lastAutoUpdatedOn;
}
public void setLastAutoUpdatedOn(Instant lastAutoUpdatedOn) {
this.lastAutoUpdatedOn = lastAutoUpdatedOn;
}
@DynamoDbVersionAttribute
public Long getVersion() {
return version;
}
public void setVersion(Long version) {
this.version = version;
}
@DynamoDbConvertedBy(EpochMillisFormatTestConverter.class)
@DynamoDbAutoGeneratedTimestampAttribute
public Instant getLastAutoUpdatedOnMillis() {
return lastAutoUpdatedOnMillis;
}
public void setLastAutoUpdatedOnMillis(Instant lastAutoUpdatedOnMillis) {
this.lastAutoUpdatedOnMillis = lastAutoUpdatedOnMillis;
}
@DynamoDbConvertedBy(TimeFormatUpdateTestConverter.class)
@DynamoDbAutoGeneratedTimestampAttribute
public Instant getFormattedLastAutoUpdatedOn() {
return formattedLastAutoUpdatedOn;
}
public void setFormattedLastAutoUpdatedOn(Instant formattedLastAutoUpdatedOn) {
this.formattedLastAutoUpdatedOn = formattedLastAutoUpdatedOn;
}
public NestedRecordWithUpdateBehavior getNestedRecord() {
return nestedRecord;
}
public void setNestedRecord(NestedRecordWithUpdateBehavior nestedRecord) {
this.nestedRecord = nestedRecord;
}
}
| 3,890 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/models/FakeItemWithBinaryKey.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.functionaltests.models;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey;
import java.util.Objects;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema;
public class FakeItemWithBinaryKey {
private static final StaticTableSchema<FakeItemWithBinaryKey> FAKE_ITEM_WITH_BINARY_KEY_SCHEMA =
StaticTableSchema.builder(FakeItemWithBinaryKey.class)
.newItemSupplier(FakeItemWithBinaryKey::new)
.addAttribute(SdkBytes.class, a -> a.name("id")
.getter(FakeItemWithBinaryKey::getId)
.setter(FakeItemWithBinaryKey::setId)
.tags(primaryPartitionKey()))
.build();
private SdkBytes id;
public static StaticTableSchema<FakeItemWithBinaryKey> getTableSchema() {
return FAKE_ITEM_WITH_BINARY_KEY_SCHEMA;
}
public SdkBytes getId() {
return id;
}
public void setId(SdkBytes id) {
this.id = id;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
FakeItemWithBinaryKey that = (FakeItemWithBinaryKey) o;
return Objects.equals(id, that.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}
| 3,891 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/models/FakeItemAbstractSubclass2.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.functionaltests.models;
import java.util.Objects;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema;
abstract class FakeItemAbstractSubclass2 {
private static final StaticTableSchema<FakeItemAbstractSubclass2> FAKE_ITEM_MAPPER =
StaticTableSchema.builder(FakeItemAbstractSubclass2.class)
.addAttribute(String.class,
a -> a.name("abstract_subclass_2")
.getter(FakeItemAbstractSubclass2::getSubclassAttribute2)
.setter(FakeItemAbstractSubclass2::setSubclassAttribute2))
.flatten(FakeItemComposedSubclass2.getTableSchema(),
FakeItemAbstractSubclass2::getComposedAttribute2,
FakeItemAbstractSubclass2::setComposedAttribute2)
.build();
private String subclassAttribute2;
private FakeItemComposedSubclass2 composedAttribute2;
static StaticTableSchema<FakeItemAbstractSubclass2> getSubclass2TableSchema() {
return FAKE_ITEM_MAPPER;
}
FakeItemAbstractSubclass2() {
composedAttribute2 = new FakeItemComposedSubclass2();
}
public String getSubclassAttribute2() {
return subclassAttribute2;
}
public void setSubclassAttribute2(String subclassAttribute2) {
this.subclassAttribute2 = subclassAttribute2;
}
public FakeItemComposedSubclass2 getComposedAttribute2() {
return composedAttribute2;
}
public void setComposedAttribute2(FakeItemComposedSubclass2 composedAttribute2) {
this.composedAttribute2 = composedAttribute2;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
FakeItemAbstractSubclass2 that = (FakeItemAbstractSubclass2) o;
return Objects.equals(subclassAttribute2, that.subclassAttribute2) &&
Objects.equals(composedAttribute2, that.composedAttribute2);
}
@Override
public int hashCode() {
return Objects.hash(subclassAttribute2, composedAttribute2);
}
}
| 3,892 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/models/InnerAttribConverter.java | package software.amazon.awssdk.enhanced.dynamodb.functionaltests.models;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import software.amazon.awssdk.enhanced.dynamodb.AttributeConverter;
import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType;
import software.amazon.awssdk.enhanced.dynamodb.EnhancedType;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import java.util.HashMap;
import java.util.Map;
import static software.amazon.awssdk.enhanced.dynamodb.internal.AttributeValues.stringValue;
/**
* Event Payload Converter to save the record on the class
*/
public class InnerAttribConverter<T> implements AttributeConverter<T> {
private final ObjectMapper objectMapper;
/**
* This No Args constuctor is needed by the DynamoDbConvertedBy annotation
*/
public InnerAttribConverter() {
this.objectMapper = new ObjectMapper();
this.objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
final AttributeValue dd = stringValue("dd");
AttributeConverter<String> attributeConverter = null;
AttributeValueType attributeValueType = null;
EnhancedType enhancedType = null;
// add this to preserve the same offset (don't convert to UTC)
this.objectMapper.configure(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE, false);
}
@Override
public AttributeValue transformFrom(final T input) {
Map<String, AttributeValue> map = null;
if (input != null) {
map = new HashMap<>();
InnerAttributeRecord innerAttributeRecord = (InnerAttributeRecord) input;
if (innerAttributeRecord.getAttribOne() != null) {
final AttributeValue attributeValue = stringValue(innerAttributeRecord.getAttribOne());
map.put("attribOne", stringValue(innerAttributeRecord.getAttribOne()));
}
if (innerAttributeRecord.getAttribTwo() != null) {
map.put("attribTwo", stringValue(String.valueOf(innerAttributeRecord.getAttribTwo())));
}
}
return AttributeValue.builder().m(map).build();
}
@Override
public T transformTo(final AttributeValue attributeValue) {
InnerAttributeRecord innerMetadata = new InnerAttributeRecord();
if (attributeValue.m().get("attribOne") != null) {
innerMetadata.setAttribOne(attributeValue.m().get("attribOne").s());
}
if (attributeValue.m().get("attribTwo") != null) {
innerMetadata.setAttribTwo(Integer.valueOf(attributeValue.m().get("attribTwo").s()));
}
return (T) innerMetadata;
}
@Override
public EnhancedType<T> type() {
return (EnhancedType<T>) EnhancedType.of(InnerAttributeRecord.class);
}
@Override
public AttributeValueType attributeValueType() {
return AttributeValueType.S;
}
} | 3,893 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/models/FakeEnumShortened.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.functionaltests.models;
public enum FakeEnumShortened {
ONE,
}
| 3,894 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/models/FakeItemWithIndices.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.functionaltests.models;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primarySortKey;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.secondaryPartitionKey;
import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.secondarySortKey;
import java.util.UUID;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema;
public class FakeItemWithIndices {
private static final StaticTableSchema<FakeItemWithIndices> FAKE_ITEM_MAPPER =
StaticTableSchema.builder(FakeItemWithIndices.class)
.newItemSupplier(FakeItemWithIndices::new)
.addAttribute(String.class, a -> a.name("id")
.getter(FakeItemWithIndices::getId)
.setter(FakeItemWithIndices::setId)
.tags(primaryPartitionKey()))
.addAttribute(String.class, a -> a.name("sort")
.getter(FakeItemWithIndices::getSort)
.setter(FakeItemWithIndices::setSort)
.tags(primarySortKey()))
.addAttribute(String.class, a -> a.name("gsi_id")
.getter(FakeItemWithIndices::getGsiId)
.setter(FakeItemWithIndices::setGsiId)
.tags(secondaryPartitionKey("gsi_1"), secondaryPartitionKey("gsi_2")))
.addAttribute(String.class, a -> a.name("gsi_sort")
.getter(FakeItemWithIndices::getGsiSort)
.setter(FakeItemWithIndices::setGsiSort)
.tags(secondarySortKey("gsi_1")))
.addAttribute(String.class, a -> a.name("lsi_sort")
.getter(FakeItemWithIndices::getLsiSort)
.setter(FakeItemWithIndices::setLsiSort)
.tags(secondarySortKey("lsi_1")))
.build();
private String id;
private String sort;
private String gsiId;
private String gsiSort;
private String lsiSort;
public FakeItemWithIndices() {
}
public FakeItemWithIndices(String id, String sort, String gsiId, String gsiSort, String lsiSort) {
this.id = id;
this.sort = sort;
this.gsiId = gsiId;
this.gsiSort = gsiSort;
this.lsiSort = lsiSort;
}
public static Builder builder() {
return new Builder();
}
public static StaticTableSchema<FakeItemWithIndices> getTableSchema() {
return FAKE_ITEM_MAPPER;
}
public static FakeItemWithIndices createUniqueFakeItemWithIndices() {
return FakeItemWithIndices.builder()
.id(UUID.randomUUID().toString())
.sort(UUID.randomUUID().toString())
.gsiId(UUID.randomUUID().toString())
.gsiSort(UUID.randomUUID().toString())
.lsiSort(UUID.randomUUID().toString())
.build();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSort() {
return sort;
}
public void setSort(String sort) {
this.sort = sort;
}
public String getGsiId() {
return gsiId;
}
public void setGsiId(String gsiId) {
this.gsiId = gsiId;
}
public String getGsiSort() {
return gsiSort;
}
public void setGsiSort(String gsiSort) {
this.gsiSort = gsiSort;
}
public String getLsiSort() {
return lsiSort;
}
public void setLsiSort(String lsiSort) {
this.lsiSort = lsiSort;
}
public static class Builder {
private String id;
private String sort;
private String gsiId;
private String gsiSort;
private String lsiSort;
public Builder id(String id) {
this.id = id;
return this;
}
public Builder sort(String sort) {
this.sort = sort;
return this;
}
public Builder gsiId(String gsiId) {
this.gsiId = gsiId;
return this;
}
public Builder gsiSort(String gsiSort) {
this.gsiSort = gsiSort;
return this;
}
public Builder lsiSort(String lsiSort) {
this.lsiSort = lsiSort;
return this;
}
public FakeItemWithIndices build() {
return new FakeItemWithIndices(id, sort, gsiId, gsiSort, lsiSort);
}
}
}
| 3,895 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/models/FakeItemComposedSubclass.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.functionaltests.models;
import java.util.Objects;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema;
public class FakeItemComposedSubclass extends FakeItemComposedAbstractSubclass {
private static final StaticTableSchema<FakeItemComposedSubclass> ITEM_MAPPER =
StaticTableSchema.builder(FakeItemComposedSubclass.class)
.newItemSupplier(FakeItemComposedSubclass::new)
.addAttribute(String.class,
a -> a.name("composed_subclass")
.getter(FakeItemComposedSubclass::getComposedAttribute)
.setter(FakeItemComposedSubclass::setComposedAttribute))
.extend(FakeItemComposedAbstractSubclass.getSubclassTableSchema())
.build();
private String composedAttribute;
public static StaticTableSchema<FakeItemComposedSubclass> getTableSchema() {
return ITEM_MAPPER;
}
public String getComposedAttribute() {
return composedAttribute;
}
public void setComposedAttribute(String composedAttribute) {
this.composedAttribute = composedAttribute;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (! super.equals(o)) return false;
FakeItemComposedSubclass that = (FakeItemComposedSubclass) o;
return Objects.equals(composedAttribute, that.composedAttribute);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), composedAttribute);
}
}
| 3,896 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/models/FakeItemComposedSubclass2.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.functionaltests.models;
import java.util.Objects;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableSchema;
public class FakeItemComposedSubclass2 extends FakeItemComposedAbstractSubclass2 {
private static final StaticTableSchema<FakeItemComposedSubclass2> ITEM_MAPPER =
StaticTableSchema.builder(FakeItemComposedSubclass2.class)
.newItemSupplier(FakeItemComposedSubclass2::new)
.extend(getSubclassTableSchema())
.addAttribute(String.class,
a -> a.name("composed_subclass_2")
.getter(FakeItemComposedSubclass2::getComposedAttribute2)
.setter(FakeItemComposedSubclass2::setComposedAttribute2))
.build();
private String composedAttribute2;
public static StaticTableSchema<FakeItemComposedSubclass2> getTableSchema() {
return ITEM_MAPPER;
}
public String getComposedAttribute2() {
return composedAttribute2;
}
public void setComposedAttribute2(String composedAttribute2) {
this.composedAttribute2 = composedAttribute2;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (! super.equals(o)) return false;
FakeItemComposedSubclass2 that = (FakeItemComposedSubclass2) o;
return Objects.equals(composedAttribute2, that.composedAttribute2);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), composedAttribute2);
}
}
| 3,897 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/models/InnerAttributeRecord.java | package software.amazon.awssdk.enhanced.dynamodb.functionaltests.models;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey;
public class InnerAttributeRecord {
private String attribOne;
private Integer attribTwo;
@DynamoDbPartitionKey
public String getAttribOne() {
return attribOne;
}
public void setAttribOne(String attribOne) {
this.attribOne = attribOne;
}
public Integer getAttribTwo() {
return attribTwo;
}
public void setAttribTwo(Integer attribTwo) {
this.attribTwo = attribTwo;
}
@Override
public String toString() {
return "InnerAttributeRecord{" +
"attribOne='" + attribOne + '\'' +
", attribTwo=" + attribTwo +
'}';
}
}
| 3,898 |
0 | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests | Create_ds/aws-sdk-java-v2/services-custom/dynamodb-enhanced/src/test/java/software/amazon/awssdk/enhanced/dynamodb/functionaltests/models/FakeEnumRecord.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.enhanced.dynamodb.functionaltests.models;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey;
@DynamoDbBean
public class FakeEnumRecord {
private String id;
private FakeEnum enumAttribute;
@DynamoDbPartitionKey
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public FakeEnum getEnumAttribute() {
return enumAttribute;
}
public void setEnumAttribute(FakeEnum enumAttribute) {
this.enumAttribute = enumAttribute;
}
}
| 3,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.