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/test/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal/TransferManagerLoggingTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.core.LogEvent;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.testutils.LogCaptor;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
class TransferManagerLoggingTest {
@Test
void transferManager_withCrtClient_shouldNotLogWarnMessages() {
try (S3AsyncClient s3Crt = S3AsyncClient.crtBuilder()
.region(Region.US_WEST_2)
.credentialsProvider(() -> AwsBasicCredentials.create("foo", "bar"))
.build();
LogCaptor logCaptor = LogCaptor.create(Level.WARN);
S3TransferManager tm = S3TransferManager.builder().s3Client(s3Crt).build()) {
List<LogEvent> events = logCaptor.loggedEvents();
assertThat(events).isEmpty();
}
}
@Test
void transferManager_withJavaClient_shouldLogWarnMessage() {
try (S3AsyncClient s3Crt = S3AsyncClient.builder()
.region(Region.US_WEST_2)
.credentialsProvider(() -> AwsBasicCredentials.create("foo", "bar"))
.build();
LogCaptor logCaptor = LogCaptor.create(Level.WARN);
S3TransferManager tm = S3TransferManager.builder().s3Client(s3Crt).build()) {
List<LogEvent> events = logCaptor.loggedEvents();
assertLogged(events, Level.WARN, "The provided DefaultS3AsyncClient is not an instance of S3CrtAsyncClient, and "
+ "thus multipart upload/download feature is not enabled and resumable file upload"
+ " is "
+ "not supported. To benefit from maximum throughput, consider using "
+ "S3AsyncClient.crtBuilder().build() instead.");
}
}
private static void assertLogged(List<LogEvent> events, org.apache.logging.log4j.Level level, String message) {
assertThat(events).withFailMessage("Expecting events to not be empty").isNotEmpty();
LogEvent event = events.remove(0);
String msg = event.getMessage().getFormattedMessage();
assertThat(msg).isEqualTo(message);
assertThat(event.getLevel()).isEqualTo(level);
}
}
| 3,700 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal/DefaultDownloadTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal;
import nl.jqno.equalsverifier.EqualsVerifier;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.transfer.s3.internal.model.DefaultDownload;
public class DefaultDownloadTest {
@Test
public void equals_hashcode() {
EqualsVerifier.forClass(DefaultDownload.class)
.withNonnullFields("completionFuture", "progress")
.verify();
}
} | 3,701 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal/TransferProgressUpdaterTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal;
import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.when;
import static software.amazon.awssdk.transfer.s3.SizeConstant.MB;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Stream;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.ArgumentMatchers;
import org.mockito.Mockito;
import org.reactivestreams.Subscriber;
import software.amazon.awssdk.core.SdkResponse;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.http.async.SimpleSubscriber;
import software.amazon.awssdk.services.s3.model.PutObjectResponse;
import software.amazon.awssdk.testutils.RandomTempFile;
import software.amazon.awssdk.transfer.s3.CaptureTransferListener;
import software.amazon.awssdk.transfer.s3.internal.progress.TransferProgressUpdater;
import software.amazon.awssdk.transfer.s3.model.CompletedObjectTransfer;
import software.amazon.awssdk.transfer.s3.model.TransferObjectRequest;
import software.amazon.awssdk.transfer.s3.progress.LoggingTransferListener;
import software.amazon.awssdk.transfer.s3.progress.TransferListener;
class TransferProgressUpdaterTest {
private static final long OBJ_SIZE = 16 * MB;
private static File sourceFile;
private CaptureTransferListener captureTransferListener;
private static Stream<Arguments> contentLength() {
return Stream.of(
Arguments.of(OBJ_SIZE, "Total bytes equals transferred, future complete through subscriberOnNext()"),
Arguments.of(OBJ_SIZE / 2, "Total bytes less than transferred, future complete through subscriberOnNext()"),
Arguments.of(OBJ_SIZE * 2, "Total bytes more than transferred, future complete through subscriberOnComplete()"));
}
private static CompletableFuture<CompletedObjectTransfer> completedObjectResponse(long millis) {
return CompletableFuture.supplyAsync(() -> {
quietSleep(millis);
return new CompletedObjectTransfer() {
@Override
public SdkResponse response() {
return PutObjectResponse.builder().eTag("ABCD").build();
}
};
});
}
private static void quietSleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // Restore interrupted status
throw new RuntimeException(e);
}
}
@BeforeEach
void initiate() {
captureTransferListener = new CaptureTransferListener();
}
@ParameterizedTest(name = "{index} - {1}, total bytes = {0}")
@MethodSource("contentLength")
void registerCompletion_differentTransferredByteRatios_alwaysCompletesOnce(Long givenContentLength, String description)
throws Exception {
TransferObjectRequest transferRequest = Mockito.mock(TransferObjectRequest.class);
CaptureTransferListener mockListener = Mockito.mock(CaptureTransferListener.class);
when(transferRequest.transferListeners()).thenReturn(Arrays.asList(LoggingTransferListener.create(), mockListener,
captureTransferListener));
sourceFile = new RandomTempFile(OBJ_SIZE);
AsyncRequestBody requestBody = AsyncRequestBody.fromFile(sourceFile);
TransferProgressUpdater transferProgressUpdater = new TransferProgressUpdater(transferRequest, givenContentLength);
AsyncRequestBody asyncRequestBody = transferProgressUpdater.wrapRequestBody(requestBody);
CompletableFuture<CompletedObjectTransfer> completionFuture = completedObjectResponse(10);
transferProgressUpdater.registerCompletion(completionFuture);
AtomicReference<ByteBuffer> publishedBuffer = new AtomicReference<>();
Subscriber<ByteBuffer> subscriber = new SimpleSubscriber(publishedBuffer::set);
asyncRequestBody.subscribe(subscriber);
captureTransferListener.getCompletionFuture().get(5, TimeUnit.SECONDS);
Mockito.verify(mockListener, never()).transferFailed(ArgumentMatchers.any(TransferListener.Context.TransferFailed.class));
Mockito.verify(mockListener, times(1)).transferComplete(ArgumentMatchers.any(TransferListener.Context.TransferComplete.class));
}
@Test
void transferFailedWhenSubscriptionErrors() throws Exception {
Long contentLength = 51L;
String inputString = RandomStringUtils.randomAlphanumeric(contentLength.intValue());
TransferObjectRequest transferRequest = Mockito.mock(TransferObjectRequest.class);
CaptureTransferListener mockListener = Mockito.mock(CaptureTransferListener.class);
when(transferRequest.transferListeners()).thenReturn(Arrays.asList(LoggingTransferListener.create(),
mockListener,
captureTransferListener));
sourceFile = new RandomTempFile(OBJ_SIZE);
AsyncRequestBody requestFileBody = AsyncRequestBody.fromInputStream(
new ExceptionThrowingByteArrayInputStream(inputString.getBytes(), 3), contentLength,
Executors.newSingleThreadExecutor());
TransferProgressUpdater transferProgressUpdater = new TransferProgressUpdater(transferRequest, contentLength);
AsyncRequestBody asyncRequestBody = transferProgressUpdater.wrapRequestBody(requestFileBody);
CompletableFuture<CompletedObjectTransfer> future = completedObjectResponse(10);
transferProgressUpdater.registerCompletion(future);
AtomicReference<ByteBuffer> publishedBuffer = new AtomicReference<>();
Subscriber<ByteBuffer> subscriber = new SimpleSubscriber(publishedBuffer::set);
asyncRequestBody.subscribe(subscriber);
assertThatExceptionOfType(ExecutionException.class).isThrownBy(
() -> captureTransferListener.getCompletionFuture().get(5, TimeUnit.SECONDS));
Mockito.verify(mockListener, times(1)).transferFailed(ArgumentMatchers.any(TransferListener.Context.TransferFailed.class));
Mockito.verify(mockListener, never()).transferComplete(ArgumentMatchers.any(TransferListener.Context.TransferComplete.class));
}
private static class ExceptionThrowingByteArrayInputStream extends ByteArrayInputStream {
private final int exceptionPosition;
public ExceptionThrowingByteArrayInputStream(byte[] buf, int exceptionPosition) {
super(buf);
this.exceptionPosition = exceptionPosition;
}
@Override
public int read() {
return (exceptionPosition == pos + 1) ? exceptionThrowingRead() : super.read();
}
@Override
public int read(byte[] b, int off, int len) {
return (exceptionPosition >= pos && exceptionPosition < (pos + len)) ?
exceptionThrowingReadByteArr(b, off, len) : super.read(b, off, len);
}
private int exceptionThrowingRead() {
throw new RuntimeException("Exception occurred at position " + (pos + 1));
}
private int exceptionThrowingReadByteArr(byte[] b, int off, int len) {
throw new RuntimeException("Exception occurred in read(byte[]) at position " + exceptionPosition);
}
}
} | 3,702 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal/ApplyUserAgentInterceptorTest.java | /*
* Copyright 2010-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.RequestOverrideConfiguration;
import software.amazon.awssdk.core.SdkField;
import software.amazon.awssdk.core.SdkRequest;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
class ApplyUserAgentInterceptorTest {
private final ApplyUserAgentInterceptor interceptor = new ApplyUserAgentInterceptor();
@Test
void s3Request_shouldModifyRequest() {
GetObjectRequest getItemRequest = GetObjectRequest.builder().build();
SdkRequest sdkRequest = interceptor.modifyRequest(() -> getItemRequest, new ExecutionAttributes());
RequestOverrideConfiguration requestOverrideConfiguration = sdkRequest.overrideConfiguration().get();
assertThat(requestOverrideConfiguration.apiNames().stream().anyMatch(a -> a.name().equals("ft") && a.version().equals(
"s3-transfer"))).isTrue();
}
@Test
void otherRequest_shouldThrowAssertionError() {
SdkRequest someOtherRequest = new SdkRequest() {
@Override
public List<SdkField<?>> sdkFields() {
return null;
}
@Override
public Optional<? extends RequestOverrideConfiguration> overrideConfiguration() {
return Optional.empty();
}
@Override
public Builder toBuilder() {
return null;
}
};
assertThatThrownBy(() -> interceptor.modifyRequest(() -> someOtherRequest, new ExecutionAttributes()))
.isInstanceOf(AssertionError.class);
}
}
| 3,703 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal/S3TransferManagerTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.nio.file.Paths;
import java.util.concurrent.CompletableFuture;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.ResponseBytes;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.core.async.AsyncResponseTransformer;
import software.amazon.awssdk.services.s3.internal.crt.S3CrtAsyncClient;
import software.amazon.awssdk.services.s3.model.CopyObjectRequest;
import software.amazon.awssdk.services.s3.model.CopyObjectResponse;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.PutObjectResponse;
import software.amazon.awssdk.transfer.s3.model.CompletedCopy;
import software.amazon.awssdk.transfer.s3.model.CompletedDownload;
import software.amazon.awssdk.transfer.s3.model.CompletedFileDownload;
import software.amazon.awssdk.transfer.s3.model.CompletedFileUpload;
import software.amazon.awssdk.transfer.s3.model.CompletedUpload;
import software.amazon.awssdk.transfer.s3.model.CopyRequest;
import software.amazon.awssdk.transfer.s3.model.DownloadDirectoryRequest;
import software.amazon.awssdk.transfer.s3.model.DownloadFileRequest;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.transfer.s3.model.DownloadRequest;
import software.amazon.awssdk.transfer.s3.model.UploadDirectoryRequest;
import software.amazon.awssdk.transfer.s3.model.UploadFileRequest;
class S3TransferManagerTest {
private S3CrtAsyncClient mockS3Crt;
private S3TransferManager tm;
private UploadDirectoryHelper uploadDirectoryHelper;
private DownloadDirectoryHelper downloadDirectoryHelper;
private TransferManagerConfiguration configuration;
@BeforeEach
public void methodSetup() {
mockS3Crt = mock(S3CrtAsyncClient.class);
uploadDirectoryHelper = mock(UploadDirectoryHelper.class);
configuration = mock(TransferManagerConfiguration.class);
downloadDirectoryHelper = mock(DownloadDirectoryHelper.class);
tm = new GenericS3TransferManager(mockS3Crt, uploadDirectoryHelper, configuration, downloadDirectoryHelper);
}
@AfterEach
public void methodTeardown() {
tm.close();
}
@Test
void defaultTransferManager_shouldNotThrowException() {
S3TransferManager transferManager = S3TransferManager.create();
transferManager.close();
}
@Test
void uploadFile_returnsResponse() {
PutObjectResponse response = PutObjectResponse.builder().build();
when(mockS3Crt.putObject(any(PutObjectRequest.class), any(AsyncRequestBody.class)))
.thenReturn(CompletableFuture.completedFuture(response));
CompletedFileUpload completedFileUpload = tm.uploadFile(u -> u.putObjectRequest(p -> p.bucket("bucket")
.key("key"))
.source(Paths.get(".")))
.completionFuture()
.join();
assertThat(completedFileUpload.response()).isEqualTo(response);
}
@Test
public void upload_returnsResponse() {
PutObjectResponse response = PutObjectResponse.builder().build();
when(mockS3Crt.putObject(any(PutObjectRequest.class), any(AsyncRequestBody.class)))
.thenReturn(CompletableFuture.completedFuture(response));
CompletedUpload completedUpload = tm.upload(u -> u.putObjectRequest(p -> p.bucket("bucket")
.key("key"))
.requestBody(AsyncRequestBody.fromString("foo")))
.completionFuture()
.join();
assertThat(completedUpload.response()).isEqualTo(response);
}
@Test
public void copy_returnsResponse() {
CopyObjectResponse response = CopyObjectResponse.builder().build();
when(mockS3Crt.copyObject(any(CopyObjectRequest.class)))
.thenReturn(CompletableFuture.completedFuture(response));
CompletedCopy completedCopy = tm.copy(u -> u.copyObjectRequest(p -> p.sourceBucket("bucket")
.sourceKey("sourceKey")
.destinationBucket("bucket")
.destinationKey("destKey")))
.completionFuture()
.join();
assertThat(completedCopy.response()).isEqualTo(response);
}
@Test
void uploadFile_cancel_shouldForwardCancellation() {
CompletableFuture<PutObjectResponse> s3CrtFuture = new CompletableFuture<>();
when(mockS3Crt.putObject(any(PutObjectRequest.class), any(AsyncRequestBody.class)))
.thenReturn(s3CrtFuture);
CompletableFuture<CompletedFileUpload> future = tm.uploadFile(u -> u.putObjectRequest(p -> p.bucket("bucket")
.key("key"))
.source(Paths.get(".")))
.completionFuture();
future.cancel(true);
assertThat(s3CrtFuture).isCancelled();
}
@Test
void upload_cancel_shouldForwardCancellation() {
CompletableFuture<PutObjectResponse> s3CrtFuture = new CompletableFuture<>();
when(mockS3Crt.putObject(any(PutObjectRequest.class), any(AsyncRequestBody.class)))
.thenReturn(s3CrtFuture);
CompletableFuture<CompletedUpload> future = tm.upload(u -> u.putObjectRequest(p -> p.bucket("bucket")
.key("key"))
.requestBody(AsyncRequestBody.fromString("foo")))
.completionFuture();
future.cancel(true);
assertThat(s3CrtFuture).isCancelled();
}
@Test
void copy_cancel_shouldForwardCancellation() {
CompletableFuture<CopyObjectResponse> s3CrtFuture = new CompletableFuture<>();
when(mockS3Crt.copyObject(any(CopyObjectRequest.class)))
.thenReturn(s3CrtFuture);
CompletableFuture<CompletedCopy> future = tm.copy(u -> u.copyObjectRequest(p -> p.sourceBucket("bucket")
.sourceKey("sourceKey")
.destinationBucket("bucket")
.destinationKey("destKey")))
.completionFuture();
future.cancel(true);
assertThat(s3CrtFuture).isCancelled();
}
@Test
void downloadFile_returnsResponse() {
GetObjectResponse response = GetObjectResponse.builder().build();
when(mockS3Crt.getObject(any(GetObjectRequest.class), any(AsyncResponseTransformer.class)))
.thenReturn(CompletableFuture.completedFuture(response));
CompletedFileDownload completedFileDownload = tm.downloadFile(d -> d.getObjectRequest(g -> g.bucket("bucket")
.key("key"))
.destination(Paths.get(".")))
.completionFuture()
.join();
assertThat(completedFileDownload.response()).isEqualTo(response);
}
@Test
void downloadFile_cancel_shouldForwardCancellation() {
CompletableFuture<GetObjectResponse> s3CrtFuture = new CompletableFuture<>();
when(mockS3Crt.getObject(any(GetObjectRequest.class), any(AsyncResponseTransformer.class)))
.thenReturn(s3CrtFuture);
CompletableFuture<CompletedFileDownload> future = tm.downloadFile(d -> d
.getObjectRequest(g -> g.bucket(
"bucket")
.key("key"))
.destination(Paths.get(".")))
.completionFuture();
future.cancel(true);
assertThat(s3CrtFuture).isCancelled();
}
@Test
void download_cancel_shouldForwardCancellation() {
CompletableFuture<GetObjectResponse> s3CrtFuture = new CompletableFuture<>();
when(mockS3Crt.getObject(any(GetObjectRequest.class), any(AsyncResponseTransformer.class)))
.thenReturn(s3CrtFuture);
DownloadRequest<ResponseBytes<GetObjectResponse>> downloadRequest =
DownloadRequest.builder()
.getObjectRequest(g -> g.bucket("bucket").key("key"))
.responseTransformer(AsyncResponseTransformer.toBytes()).build();
CompletableFuture<CompletedDownload<ResponseBytes<GetObjectResponse>>> future =
tm.download(downloadRequest).completionFuture();
future.cancel(true);
assertThat(s3CrtFuture).isCancelled();
}
@Test
void objectLambdaArnBucketProvided_shouldThrowException() {
String objectLambdaArn = "arn:xxx:s3-object-lambda";
assertThatThrownBy(() -> tm.uploadFile(b -> b.putObjectRequest(p -> p.bucket(objectLambdaArn).key("key"))
.source(Paths.get(".")))
.completionFuture().join())
.hasMessageContaining("support S3 Object Lambda resources").hasCauseInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(() -> tm.upload(b -> b.putObjectRequest(p -> p.bucket(objectLambdaArn).key("key"))
.requestBody(AsyncRequestBody.fromString("foo")))
.completionFuture().join())
.hasMessageContaining("support S3 Object Lambda resources").hasCauseInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(() -> tm.downloadFile(b -> b.getObjectRequest(p -> p.bucket(objectLambdaArn).key("key"))
.destination(Paths.get(".")))
.completionFuture().join())
.hasMessageContaining("support S3 Object Lambda resources").hasCauseInstanceOf(IllegalArgumentException.class);
DownloadRequest<ResponseBytes<GetObjectResponse>> downloadRequest =
DownloadRequest.builder()
.getObjectRequest(g -> g.bucket(objectLambdaArn).key("key"))
.responseTransformer(AsyncResponseTransformer.toBytes())
.build();
assertThatThrownBy(() -> tm.download(downloadRequest)
.completionFuture().join())
.hasMessageContaining("support S3 Object Lambda resources").hasCauseInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(() -> tm.uploadDirectory(b -> b.bucket(objectLambdaArn)
.source(Paths.get(".")))
.completionFuture().join())
.hasMessageContaining("support S3 Object Lambda resources").hasCauseInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(() -> tm.copy(b -> b.copyObjectRequest(p -> p.sourceBucket(objectLambdaArn)
.sourceKey("sourceKey")
.destinationBucket("bucket")
.destinationKey("destKey")))
.completionFuture().join())
.hasMessageContaining("support S3 Object Lambda resources").hasCauseInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(() -> tm.copy(b -> b.copyObjectRequest(p -> p.sourceBucket("bucket")
.sourceKey("sourceKey")
.destinationBucket(objectLambdaArn)
.destinationKey("destKey")))
.completionFuture().join())
.hasMessageContaining("support S3 Object Lambda resources").hasCauseInstanceOf(IllegalArgumentException.class);
}
@Test
void mrapArnProvided_shouldThrowException() {
String mrapArn = "arn:aws:s3::123456789012:accesspoint:mfzwi23gnjvgw.mrap";
assertThatThrownBy(() -> tm.uploadFile(b -> b.putObjectRequest(p -> p.bucket(mrapArn).key("key"))
.source(Paths.get(".")))
.completionFuture().join())
.hasMessageContaining("multi-region access point ARN").hasCauseInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(() -> tm.upload(b -> b.putObjectRequest(p -> p.bucket(mrapArn).key("key"))
.requestBody(AsyncRequestBody.fromString("foo")))
.completionFuture().join())
.hasMessageContaining("multi-region access point ARN").hasCauseInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(() -> tm.downloadFile(b -> b.getObjectRequest(p -> p.bucket(mrapArn).key("key"))
.destination(Paths.get(".")))
.completionFuture().join())
.hasMessageContaining("multi-region access point ARN").hasCauseInstanceOf(IllegalArgumentException.class);
DownloadRequest<ResponseBytes<GetObjectResponse>> downloadRequest =
DownloadRequest.builder()
.getObjectRequest(g -> g.bucket(mrapArn).key("key"))
.responseTransformer(AsyncResponseTransformer.toBytes()).build();
assertThatThrownBy(() -> tm.download(downloadRequest).completionFuture().join())
.hasMessageContaining("multi-region access point ARN").hasCauseInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(() -> tm.uploadDirectory(b -> b.bucket(mrapArn)
.source(Paths.get(".")))
.completionFuture().join())
.hasMessageContaining("multi-region access point ARN").hasCauseInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(() -> tm.downloadDirectory(b -> b.bucket(mrapArn)
.destination(Paths.get(".")))
.completionFuture().join())
.hasMessageContaining("multi-region access point ARN").hasCauseInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(() -> tm.copy(b -> b.copyObjectRequest(p -> p.sourceBucket(mrapArn)
.sourceKey("sourceKey")
.destinationBucket("bucket")
.destinationKey("destKey")))
.completionFuture().join())
.hasMessageContaining("multi-region access point ARN").hasCauseInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(() -> tm.copy(b -> b.copyObjectRequest(p -> p.sourceBucket("bucket")
.sourceKey("sourceKey")
.destinationBucket(mrapArn)
.destinationKey("destKey")))
.completionFuture().join())
.hasMessageContaining("multi-region access point ARN").hasCauseInstanceOf(IllegalArgumentException.class);
}
@Test
void uploadDirectory_throwException_shouldCompleteFutureExceptionally() {
RuntimeException exception = new RuntimeException("test");
when(uploadDirectoryHelper.uploadDirectory(any(UploadDirectoryRequest.class))).thenThrow(exception);
assertThatThrownBy(() -> tm.uploadDirectory(u -> u.source(Paths.get("/"))
.bucket("bucketName")).completionFuture().join())
.hasCause(exception);
}
@Test
void downloadDirectory_throwException_shouldCompleteFutureExceptionally() {
RuntimeException exception = new RuntimeException("test");
when(downloadDirectoryHelper.downloadDirectory(any(DownloadDirectoryRequest.class))).thenThrow(exception);
assertThatThrownBy(() -> tm.downloadDirectory(u -> u.destination(Paths.get("/"))
.bucket("bucketName")).completionFuture().join())
.hasCause(exception);
}
@Test
void close_shouldCloseUnderlyingResources() {
S3TransferManager transferManager = new GenericS3TransferManager(mockS3Crt, uploadDirectoryHelper, configuration, downloadDirectoryHelper);
transferManager.close();
verify(mockS3Crt, times(0)).close();
verify(configuration).close();
}
@Test
void close_shouldNotCloseCloseS3AsyncClientPassedInBuilder_when_transferManagerClosed() {
S3TransferManager transferManager =
S3TransferManager.builder().s3Client(mockS3Crt).build();
transferManager.close();
verify(mockS3Crt, times(0)).close();
}
@Test
void uploadDirectory_requestNull_shouldThrowException() {
UploadDirectoryRequest request = null;
assertThatThrownBy(() -> tm.uploadDirectory(request).completionFuture().join())
.isInstanceOf(NullPointerException.class)
.hasMessageContaining("must not be null");
}
@Test
void upload_requestNull_shouldThrowException() {
UploadFileRequest request = null;
assertThatThrownBy(() -> tm.uploadFile(request).completionFuture().join()).isInstanceOf(NullPointerException.class)
.hasMessageContaining("must not be null");
}
@Test
void download_requestNull_shouldThrowException() {
DownloadFileRequest request = null;
assertThatThrownBy(() -> tm.downloadFile(request).completionFuture().join()).isInstanceOf(NullPointerException.class)
.hasMessageContaining("must not be null");
}
@Test
void copy_requestNull_shouldThrowException() {
CopyRequest request = null;
assertThatThrownBy(() -> tm.copy(request).completionFuture().join()).isInstanceOf(NullPointerException.class)
.hasMessageContaining("must not be null");
}
@Test
void downloadDirectory_requestNull_shouldThrowException() {
DownloadDirectoryRequest request = null;
assertThatThrownBy(() -> tm.downloadDirectory(request).completionFuture().join())
.isInstanceOf(NullPointerException.class)
.hasMessageContaining("must not be null");
}
}
| 3,704 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal/CrtFileUploadTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.when;
import static software.amazon.awssdk.transfer.s3.SizeConstant.MB;
import com.google.common.jimfs.Jimfs;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.time.Instant;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import nl.jqno.equalsverifier.EqualsVerifier;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import software.amazon.awssdk.crt.CrtRuntimeException;
import software.amazon.awssdk.crt.s3.ResumeToken;
import software.amazon.awssdk.crt.s3.S3MetaRequest;
import software.amazon.awssdk.services.s3.internal.crt.S3MetaRequestPauseObservable;
import software.amazon.awssdk.services.s3.model.PutObjectResponse;
import software.amazon.awssdk.transfer.s3.internal.model.CrtFileUpload;
import software.amazon.awssdk.transfer.s3.internal.progress.DefaultTransferProgressSnapshot;
import software.amazon.awssdk.transfer.s3.model.CompletedFileUpload;
import software.amazon.awssdk.transfer.s3.model.ResumableFileUpload;
import software.amazon.awssdk.transfer.s3.model.UploadFileRequest;
import software.amazon.awssdk.transfer.s3.progress.TransferProgress;
class CrtFileUploadTest {
private static final int TOTAL_PARTS = 10;
private static final int NUM_OF_PARTS_COMPLETED = 5;
private static final long PART_SIZE_IN_BYTES = 8 * MB;
private static final String MULTIPART_UPLOAD_ID = "someId";
private S3MetaRequest metaRequest;
private static FileSystem fileSystem;
private static File file;
private static ResumeToken token;
@BeforeAll
public static void setUp() throws IOException {
fileSystem = Jimfs.newFileSystem();
file = File.createTempFile("test", UUID.randomUUID().toString());
Files.write(file.toPath(), RandomStringUtils.random(2000).getBytes(StandardCharsets.UTF_8));
token = new ResumeToken(new ResumeToken.PutResumeTokenBuilder()
.withNumPartsCompleted(NUM_OF_PARTS_COMPLETED)
.withTotalNumParts(TOTAL_PARTS)
.withPartSize(PART_SIZE_IN_BYTES)
.withUploadId(MULTIPART_UPLOAD_ID));
}
@AfterAll
public static void tearDown() throws IOException {
file.delete();
}
@BeforeEach
void setUpBeforeEachTest() {
metaRequest = Mockito.mock(S3MetaRequest.class);
}
@Test
void equals_hashcode() {
EqualsVerifier.forClass(CrtFileUpload.class)
.withNonnullFields("completionFuture", "progress", "request", "observable", "resumableFileUpload")
.withPrefabValues(S3MetaRequestPauseObservable.class, new S3MetaRequestPauseObservable(),
new S3MetaRequestPauseObservable())
.verify();
}
@Test
void pause_futureCompleted_shouldReturnNormally() {
PutObjectResponse putObjectResponse = PutObjectResponse.builder()
.build();
CompletableFuture<CompletedFileUpload> future =
CompletableFuture.completedFuture(CompletedFileUpload.builder()
.response(putObjectResponse)
.build());
TransferProgress transferProgress = Mockito.mock(TransferProgress.class);
when(transferProgress.snapshot()).thenReturn(DefaultTransferProgressSnapshot.builder()
.sdkResponse(putObjectResponse)
.transferredBytes(0L)
.build());
S3MetaRequestPauseObservable observable = new S3MetaRequestPauseObservable();
UploadFileRequest request = uploadFileRequest();
CrtFileUpload fileUpload =
new CrtFileUpload(future, transferProgress, observable, request);
observable.subscribe(metaRequest);
ResumableFileUpload resumableFileUpload = fileUpload.pause();
Mockito.verify(metaRequest, Mockito.never()).pause();
assertThat(resumableFileUpload.totalParts()).isEmpty();
assertThat(resumableFileUpload.partSizeInBytes()).isEmpty();
assertThat(resumableFileUpload.multipartUploadId()).isEmpty();
assertThat(resumableFileUpload.fileLength()).isEqualTo(file.length());
assertThat(resumableFileUpload.uploadFileRequest()).isEqualTo(request);
assertThat(resumableFileUpload.fileLastModified()).isEqualTo(Instant.ofEpochMilli(file.lastModified()));
}
@Test
void pauseTwice_shouldReturnTheSame() {
CompletableFuture<CompletedFileUpload> future =
new CompletableFuture<>();
TransferProgress transferProgress = Mockito.mock(TransferProgress.class);
when(transferProgress.snapshot()).thenReturn(DefaultTransferProgressSnapshot.builder()
.transferredBytes(1000L)
.build());
UploadFileRequest request = uploadFileRequest();
S3MetaRequestPauseObservable observable = new S3MetaRequestPauseObservable();
when(metaRequest.pause()).thenReturn(token);
observable.subscribe(metaRequest);
CrtFileUpload fileUpload =
new CrtFileUpload(future, transferProgress, observable, request);
ResumableFileUpload resumableFileUpload = fileUpload.pause();
ResumableFileUpload resumableFileUpload2 = fileUpload.pause();
assertThat(resumableFileUpload).isEqualTo(resumableFileUpload2);
}
@Test
void pause_crtThrowException_shouldPropogate() {
CompletableFuture<CompletedFileUpload> future =
new CompletableFuture<>();
TransferProgress transferProgress = Mockito.mock(TransferProgress.class);
when(transferProgress.snapshot()).thenReturn(DefaultTransferProgressSnapshot.builder()
.transferredBytes(1000L)
.build());
UploadFileRequest request = uploadFileRequest();
S3MetaRequestPauseObservable observable = new S3MetaRequestPauseObservable();
CrtRuntimeException exception = new CrtRuntimeException("exception");
when(metaRequest.pause()).thenThrow(exception);
observable.subscribe(metaRequest);
CrtFileUpload fileUpload =
new CrtFileUpload(future, transferProgress, observable, request);
assertThatThrownBy(() -> fileUpload.pause()).isSameAs(exception);
}
@Test
void pause_futureNotComplete_shouldPause() {
CompletableFuture<CompletedFileUpload> future =
new CompletableFuture<>();
TransferProgress transferProgress = Mockito.mock(TransferProgress.class);
when(transferProgress.snapshot()).thenReturn(DefaultTransferProgressSnapshot.builder()
.transferredBytes(0L)
.build());
S3MetaRequestPauseObservable observable = new S3MetaRequestPauseObservable();
when(metaRequest.pause()).thenReturn(token);
UploadFileRequest request = uploadFileRequest();
CrtFileUpload fileUpload =
new CrtFileUpload(future, transferProgress, observable, request);
observable.subscribe(metaRequest);
ResumableFileUpload resumableFileUpload = fileUpload.pause();
Mockito.verify(metaRequest).pause();
assertThat(resumableFileUpload.totalParts()).hasValue(TOTAL_PARTS);
assertThat(resumableFileUpload.partSizeInBytes()).hasValue(PART_SIZE_IN_BYTES);
assertThat(resumableFileUpload.multipartUploadId()).hasValue(MULTIPART_UPLOAD_ID);
assertThat(resumableFileUpload.transferredParts()).hasValue(NUM_OF_PARTS_COMPLETED);
assertThat(resumableFileUpload.fileLength()).isEqualTo(file.length());
assertThat(resumableFileUpload.uploadFileRequest()).isEqualTo(request);
assertThat(resumableFileUpload.fileLastModified()).isEqualTo(Instant.ofEpochMilli(file.lastModified()));
}
@Test
void pause_singlePart_shouldPause() {
PutObjectResponse putObjectResponse = PutObjectResponse.builder()
.build();
CompletableFuture<CompletedFileUpload> future =
new CompletableFuture<>();
TransferProgress transferProgress = Mockito.mock(TransferProgress.class);
when(transferProgress.snapshot()).thenReturn(DefaultTransferProgressSnapshot.builder()
.sdkResponse(putObjectResponse)
.transferredBytes(0L)
.build());
S3MetaRequestPauseObservable observable = new S3MetaRequestPauseObservable();
when(metaRequest.pause()).thenThrow(new CrtRuntimeException(6));
UploadFileRequest request = uploadFileRequest();
CrtFileUpload fileUpload =
new CrtFileUpload(future, transferProgress, observable, request);
observable.subscribe(metaRequest);
ResumableFileUpload resumableFileUpload = fileUpload.pause();
Mockito.verify(metaRequest).pause();
assertThat(resumableFileUpload.totalParts()).isEmpty();
assertThat(resumableFileUpload.partSizeInBytes()).isEmpty();
assertThat(resumableFileUpload.multipartUploadId()).isEmpty();
assertThat(resumableFileUpload.fileLength()).isEqualTo(file.length());
assertThat(resumableFileUpload.uploadFileRequest()).isEqualTo(request);
assertThat(resumableFileUpload.fileLastModified()).isEqualTo(Instant.ofEpochMilli(file.lastModified()));
}
private UploadFileRequest uploadFileRequest() {
return UploadFileRequest.builder()
.source(file)
.putObjectRequest(p -> p.key("test").bucket("bucket"))
.build();
}
} | 3,705 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal/ListObjectsHelperTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import software.amazon.awssdk.services.s3.model.CommonPrefix;
import software.amazon.awssdk.services.s3.model.ListObjectsV2Request;
import software.amazon.awssdk.services.s3.model.ListObjectsV2Response;
import software.amazon.awssdk.services.s3.model.S3Object;
class ListObjectsHelperTest {
private Function<ListObjectsV2Request,
CompletableFuture<ListObjectsV2Response>> listObjectsFunction;
private ListObjectsHelper listObjectsHelper;
@BeforeEach
public void setup() {
listObjectsFunction = Mockito.mock(Function.class);
listObjectsHelper = new ListObjectsHelper(listObjectsFunction);
}
@Test
void listS3Objects_noNextPageOrCommonPrefixes_shouldNotFetchAgain() {
ListObjectsV2Response response = listObjectsV2Response("key1", "key2");
CompletableFuture<ListObjectsV2Response> future = CompletableFuture.completedFuture(response);
when(listObjectsFunction.apply(any(ListObjectsV2Request.class)))
.thenReturn(future);
List<S3Object> actualObjects = new ArrayList<>();
listObjectsHelper.listS3ObjectsRecursively(ListObjectsV2Request.builder()
.bucket("bucket")
.build())
.subscribe(actualObjects::add).join();
future.complete(response);
assertThat(actualObjects).hasSameElementsAs(response.contents());
verify(listObjectsFunction, times(1)).apply(any(ListObjectsV2Request.class));
}
/**
* source
* / / | | \ \
* 1 2 3 4 jan feb
* / / | \ / \
* 1 2 3 4 1 2
* The order of S3Objects should be "1, 2, 3, 4, jan/1, jan/2, jan/3, jan/4, feb/1, feb/2"
*/
@Test
void listS3Objects_hasNextPageAndCommonPrefixes_shouldReturnAll() {
List<CommonPrefix> commonPrefixes = Arrays.asList(CommonPrefix.builder().prefix("jan/").build(),
CommonPrefix.builder().prefix("feb/").build());
ListObjectsV2Response responsePage1 = listObjectsV2Response("nextPage", commonPrefixes, "1", "2");
ListObjectsV2Response responsePage2 = listObjectsV2Response(null, Collections.emptyList(), "3", "4");
ListObjectsV2Response responsePage3 = listObjectsV2Response("nextPage", Collections.emptyList(), "jan/1", "jan/2");
ListObjectsV2Response responsePage4 = listObjectsV2Response(null, Collections.emptyList(), "jan/3", "jan/4");
ListObjectsV2Response responsePage5 = listObjectsV2Response(null, Collections.emptyList(), "feb/1", "feb/2");
CompletableFuture<ListObjectsV2Response> futurePage1 = CompletableFuture.completedFuture(responsePage1);
CompletableFuture<ListObjectsV2Response> futurePage2 = CompletableFuture.completedFuture(responsePage2);
CompletableFuture<ListObjectsV2Response> futurePage3 = CompletableFuture.completedFuture(responsePage3);
CompletableFuture<ListObjectsV2Response> futurePage4 = CompletableFuture.completedFuture(responsePage4);
CompletableFuture<ListObjectsV2Response> futurePage5 = CompletableFuture.completedFuture(responsePage5);
when(listObjectsFunction.apply(any(ListObjectsV2Request.class))).thenReturn(futurePage1)
.thenReturn(futurePage2)
.thenReturn(futurePage3)
.thenReturn(futurePage4)
.thenReturn(futurePage5);
List<S3Object> actualObjects = new ArrayList<>();
ListObjectsV2Request firstRequest = ListObjectsV2Request.builder()
.bucket("bucket")
.build();
listObjectsHelper.listS3ObjectsRecursively(firstRequest)
.subscribe(actualObjects::add).join();
futurePage1.complete(responsePage1);
ArgumentCaptor<ListObjectsV2Request> argumentCaptor = ArgumentCaptor.forClass(ListObjectsV2Request.class);
verify(listObjectsFunction, times(5)).apply(argumentCaptor.capture());
List<ListObjectsV2Request> actualListObjectsV2Request = argumentCaptor.getAllValues();
assertThat(actualListObjectsV2Request).hasSize(5)
.satisfies(list -> {
assertThat(list.get(0)).isEqualTo(firstRequest);
assertThat(list.get(1)).isEqualTo(firstRequest.toBuilder().continuationToken(
"nextPage").build());
assertThat(list.get(2)).isEqualTo(firstRequest.toBuilder().prefix("jan/").build());
assertThat(list.get(3)).isEqualTo(firstRequest.toBuilder().prefix("jan/")
.continuationToken("nextPage").build());
assertThat(list.get(4)).isEqualTo(firstRequest.toBuilder().prefix("feb/").build());
});
assertThat(actualObjects).hasSize(10);
}
private ListObjectsV2Response listObjectsV2Response(String... keys) {
return listObjectsV2Response(null, null, keys);
}
private ListObjectsV2Response listObjectsV2Response(String continuationToken,
List<CommonPrefix> commonPrefixes,
String... keys) {
List<S3Object> s3Objects = Arrays.stream(keys).map(k -> S3Object.builder().key(k).build()).collect(Collectors.toList());
return ListObjectsV2Response.builder()
.nextContinuationToken(continuationToken)
.commonPrefixes(commonPrefixes)
.contents(s3Objects)
.build();
}
}
| 3,706 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal/UploadDirectoryHelperTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.google.common.jimfs.Configuration;
import com.google.common.jimfs.Jimfs;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.ArgumentCaptor;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.services.s3.internal.crt.S3MetaRequestPauseObservable;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.PutObjectResponse;
import software.amazon.awssdk.testutils.FileUtils;
import software.amazon.awssdk.transfer.s3.config.TransferRequestOverrideConfiguration;
import software.amazon.awssdk.transfer.s3.internal.model.DefaultFileUpload;
import software.amazon.awssdk.transfer.s3.internal.progress.DefaultTransferProgress;
import software.amazon.awssdk.transfer.s3.internal.progress.DefaultTransferProgressSnapshot;
import software.amazon.awssdk.transfer.s3.model.CompletedDirectoryUpload;
import software.amazon.awssdk.transfer.s3.model.CompletedFileUpload;
import software.amazon.awssdk.transfer.s3.model.DirectoryUpload;
import software.amazon.awssdk.transfer.s3.model.FileUpload;
import software.amazon.awssdk.transfer.s3.model.UploadDirectoryRequest;
import software.amazon.awssdk.transfer.s3.model.UploadFileRequest;
import software.amazon.awssdk.transfer.s3.progress.LoggingTransferListener;
import software.amazon.awssdk.transfer.s3.progress.TransferListener;
public class UploadDirectoryHelperTest {
private FileSystem jimfs;
private Path directory;
/**
* Local directory is needed to test symlinks because jimfs doesn't work well with symlinks
*/
private static Path localDirectory;
private Function<UploadFileRequest, FileUpload> singleUploadFunction;
private UploadDirectoryHelper uploadDirectoryHelper;
public static Collection<FileSystem> fileSystems() {
return Arrays.asList(Jimfs.newFileSystem(Configuration.unix()),
Jimfs.newFileSystem(Configuration.osX()),
Jimfs.newFileSystem(Configuration.windows()));
}
@BeforeAll
public static void setUp() throws IOException {
localDirectory = createLocalTestDirectory();
}
@AfterAll
public static void tearDown() throws IOException {
FileUtils.cleanUpTestDirectory(localDirectory);
}
@BeforeEach
public void methodSetup() throws IOException {
jimfs = Jimfs.newFileSystem();
directory = jimfs.getPath("test");
Files.createDirectory(directory);
Files.createFile(jimfs.getPath("test/1"));
Files.createFile(jimfs.getPath("test/2"));
singleUploadFunction = mock(Function.class);
uploadDirectoryHelper = new UploadDirectoryHelper(TransferManagerConfiguration.builder().build(), singleUploadFunction);
}
@AfterEach
public void methodCleanup() throws IOException {
jimfs.close();
}
@Test
void uploadDirectory_cancel_shouldCancelAllFutures() {
CompletableFuture<CompletedFileUpload> future = new CompletableFuture<>();
FileUpload fileUpload = newUpload(future);
CompletableFuture<CompletedFileUpload> future2 = new CompletableFuture<>();
FileUpload fileUpload2 = newUpload(future2);
when(singleUploadFunction.apply(any(UploadFileRequest.class))).thenReturn(fileUpload, fileUpload2);
DirectoryUpload uploadDirectory =
uploadDirectoryHelper.uploadDirectory(UploadDirectoryRequest.builder()
.source(directory)
.bucket("bucket")
.build());
uploadDirectory.completionFuture().cancel(true);
assertThatThrownBy(() -> future.get(1, TimeUnit.SECONDS))
.isInstanceOf(CancellationException.class);
assertThatThrownBy(() -> future2.get(1, TimeUnit.SECONDS))
.isInstanceOf(CancellationException.class);
}
@Test
void uploadDirectory_allUploadsSucceed_failedUploadsShouldBeEmpty() throws Exception {
PutObjectResponse putObjectResponse = PutObjectResponse.builder().eTag("1234").build();
CompletedFileUpload completedFileUpload = CompletedFileUpload.builder().response(putObjectResponse).build();
CompletableFuture<CompletedFileUpload> successfulFuture = new CompletableFuture<>();
FileUpload fileUpload = newUpload(successfulFuture);
successfulFuture.complete(completedFileUpload);
PutObjectResponse putObjectResponse2 = PutObjectResponse.builder().eTag("5678").build();
CompletedFileUpload completedFileUpload2 = CompletedFileUpload.builder().response(putObjectResponse2).build();
CompletableFuture<CompletedFileUpload> successfulFuture2 = new CompletableFuture<>();
FileUpload fileUpload2 = newUpload(successfulFuture2);
successfulFuture2.complete(completedFileUpload2);
when(singleUploadFunction.apply(any(UploadFileRequest.class))).thenReturn(fileUpload, fileUpload2);
DirectoryUpload uploadDirectory =
uploadDirectoryHelper.uploadDirectory(UploadDirectoryRequest.builder()
.source(directory)
.bucket("bucket")
.build());
CompletedDirectoryUpload completedDirectoryUpload = uploadDirectory.completionFuture().get(5, TimeUnit.SECONDS);
assertThat(completedDirectoryUpload.failedTransfers()).isEmpty();
}
@Test
void uploadDirectory_partialSuccess_shouldProvideFailedUploads() throws Exception {
PutObjectResponse putObjectResponse = PutObjectResponse.builder().eTag("1234").build();
CompletedFileUpload completedFileUpload = CompletedFileUpload.builder().response(putObjectResponse).build();
CompletableFuture<CompletedFileUpload> successfulFuture = new CompletableFuture<>();
FileUpload fileUpload = newUpload(successfulFuture);
successfulFuture.complete(completedFileUpload);
SdkClientException exception = SdkClientException.create("failed");
CompletableFuture<CompletedFileUpload> failedFuture = new CompletableFuture<>();
FileUpload fileUpload2 = newUpload(failedFuture);
failedFuture.completeExceptionally(exception);
when(singleUploadFunction.apply(any(UploadFileRequest.class))).thenReturn(fileUpload, fileUpload2);
DirectoryUpload uploadDirectory =
uploadDirectoryHelper.uploadDirectory(UploadDirectoryRequest.builder()
.source(directory)
.bucket("bucket")
.build());
CompletedDirectoryUpload completedDirectoryUpload = uploadDirectory.completionFuture().get(5, TimeUnit.SECONDS);
assertThat(completedDirectoryUpload.failedTransfers()).hasSize(1);
assertThat(completedDirectoryUpload.failedTransfers().iterator().next().exception()).isEqualTo(exception);
assertThat(completedDirectoryUpload.failedTransfers().iterator().next().request().source().toString())
.isEqualTo("test" + directory.getFileSystem().getSeparator() + "2");
}
@Test
void uploadDirectory_withRequestTransformer_usesRequestTransformer() throws Exception {
PutObjectResponse putObjectResponse = PutObjectResponse.builder().eTag("1234").build();
CompletedFileUpload completedFileUpload = CompletedFileUpload.builder().response(putObjectResponse).build();
CompletableFuture<CompletedFileUpload> successfulFuture = new CompletableFuture<>();
FileUpload upload = newUpload(successfulFuture);
successfulFuture.complete(completedFileUpload);
PutObjectResponse putObjectResponse2 = PutObjectResponse.builder().eTag("5678").build();
CompletedFileUpload completedFileUpload2 = CompletedFileUpload.builder().response(putObjectResponse2).build();
CompletableFuture<CompletedFileUpload> successfulFuture2 = new CompletableFuture<>();
FileUpload upload2 = newUpload(successfulFuture2);
successfulFuture2.complete(completedFileUpload2);
ArgumentCaptor<UploadFileRequest> uploadRequestCaptor = ArgumentCaptor.forClass(UploadFileRequest.class);
when(singleUploadFunction.apply(uploadRequestCaptor.capture())).thenReturn(upload, upload2);
Path newSource = Paths.get("/new/path");
PutObjectRequest newPutObjectRequest = PutObjectRequest.builder().build();
TransferRequestOverrideConfiguration newOverrideConfig = TransferRequestOverrideConfiguration.builder()
.build();
List<TransferListener> listeners = Arrays.asList(LoggingTransferListener.create());
Consumer<UploadFileRequest.Builder> uploadFileRequestTransformer = r -> r.source(newSource)
.putObjectRequest(newPutObjectRequest)
.transferListeners(listeners);
uploadDirectoryHelper.uploadDirectory(UploadDirectoryRequest.builder()
.source(directory)
.bucket("bucket")
.uploadFileRequestTransformer(uploadFileRequestTransformer)
.build())
.completionFuture()
.get(5, TimeUnit.SECONDS);
List<UploadFileRequest> uploadRequests = uploadRequestCaptor.getAllValues();
assertThat(uploadRequests).hasSize(2);
assertThat(uploadRequests).element(0).satisfies(r -> {
assertThat(r.source()).isEqualTo(newSource);
assertThat(r.putObjectRequest()).isEqualTo(newPutObjectRequest);
assertThat(r.transferListeners()).isEqualTo(listeners);
});
assertThat(uploadRequests).element(1).satisfies(r -> {
assertThat(r.source()).isEqualTo(newSource);
assertThat(r.putObjectRequest()).isEqualTo(newPutObjectRequest);
assertThat(r.transferListeners()).isEqualTo(listeners);
});
}
@ParameterizedTest
@MethodSource("fileSystems")
void uploadDirectory_defaultSetting_shouldRecursivelyUpload(FileSystem fileSystem) {
directory = createJimFsTestDirectory(fileSystem);
ArgumentCaptor<UploadFileRequest> requestArgumentCaptor = ArgumentCaptor.forClass(UploadFileRequest.class);
when(singleUploadFunction.apply(requestArgumentCaptor.capture()))
.thenReturn(completedUpload());
DirectoryUpload uploadDirectory =
uploadDirectoryHelper.uploadDirectory(UploadDirectoryRequest.builder()
.source(directory)
.bucket("bucket")
.followSymbolicLinks(false)
.build());
uploadDirectory.completionFuture().join();
List<UploadFileRequest> actualRequests = requestArgumentCaptor.getAllValues();
actualRequests.forEach(r -> assertThat(r.putObjectRequest().bucket()).isEqualTo("bucket"));
assertThat(actualRequests.size()).isEqualTo(3);
List<String> keys =
actualRequests.stream().map(u -> u.putObjectRequest().key())
.collect(Collectors.toList());
assertThat(keys).containsOnly("bar.txt", "foo/1.txt", "foo/2.txt");
}
@Test
void uploadDirectory_depth1FollowSymlinkTrue_shouldOnlyUploadTopLevel() {
ArgumentCaptor<UploadFileRequest> requestArgumentCaptor = ArgumentCaptor.forClass(UploadFileRequest.class);
when(singleUploadFunction.apply(requestArgumentCaptor.capture())).thenReturn(completedUpload());
DirectoryUpload uploadDirectory =
uploadDirectoryHelper.uploadDirectory(UploadDirectoryRequest.builder()
.source(localDirectory)
.bucket("bucket")
.maxDepth(1)
.followSymbolicLinks(true)
.build());
uploadDirectory.completionFuture().join();
List<UploadFileRequest> actualRequests = requestArgumentCaptor.getAllValues();
List<String> keys =
actualRequests.stream().map(u -> u.putObjectRequest().key())
.collect(Collectors.toList());
assertThat(keys.size()).isEqualTo(2);
assertThat(keys).containsOnly("bar.txt", "symlink2");
}
@Test
void uploadDirectory_FollowSymlinkTrue_shouldIncludeLinkedFiles() {
ArgumentCaptor<UploadFileRequest> requestArgumentCaptor = ArgumentCaptor.forClass(UploadFileRequest.class);
when(singleUploadFunction.apply(requestArgumentCaptor.capture())).thenReturn(completedUpload());
DirectoryUpload uploadDirectory =
uploadDirectoryHelper.uploadDirectory(UploadDirectoryRequest.builder()
.source(localDirectory)
.bucket("bucket")
.followSymbolicLinks(true)
.build());
uploadDirectory.completionFuture().join();
List<UploadFileRequest> actualRequests = requestArgumentCaptor.getAllValues();
actualRequests.forEach(r -> assertThat(r.putObjectRequest().bucket()).isEqualTo("bucket"));
List<String> keys =
actualRequests.stream().map(u -> u.putObjectRequest().key())
.collect(Collectors.toList());
assertThat(keys.size()).isEqualTo(5);
assertThat(keys).containsOnly("bar.txt", "foo/1.txt", "foo/2.txt", "symlink/2.txt", "symlink2");
}
@ParameterizedTest
@MethodSource("fileSystems")
void uploadDirectory_withPrefix_keysShouldHavePrefix(FileSystem fileSystem) {
directory = createJimFsTestDirectory(fileSystem);
ArgumentCaptor<UploadFileRequest> requestArgumentCaptor = ArgumentCaptor.forClass(UploadFileRequest.class);
when(singleUploadFunction.apply(requestArgumentCaptor.capture())).thenReturn(completedUpload());
DirectoryUpload uploadDirectory =
uploadDirectoryHelper.uploadDirectory(UploadDirectoryRequest.builder()
.source(directory)
.bucket("bucket")
.s3Prefix("yolo")
.build());
uploadDirectory.completionFuture().join();
List<String> keys =
requestArgumentCaptor.getAllValues().stream().map(u -> u.putObjectRequest().key())
.collect(Collectors.toList());
assertThat(keys.size()).isEqualTo(3);
keys.forEach(r -> assertThat(r).startsWith("yolo/"));
}
@ParameterizedTest
@MethodSource("fileSystems")
void uploadDirectory_withDelimiter_shouldHonor(FileSystem fileSystem) {
directory = createJimFsTestDirectory(fileSystem);
ArgumentCaptor<UploadFileRequest> requestArgumentCaptor = ArgumentCaptor.forClass(UploadFileRequest.class);
when(singleUploadFunction.apply(requestArgumentCaptor.capture())).thenReturn(completedUpload());
DirectoryUpload uploadDirectory =
uploadDirectoryHelper.uploadDirectory(UploadDirectoryRequest.builder()
.source(directory)
.bucket("bucket")
.s3Delimiter(",")
.s3Prefix("yolo")
.build());
uploadDirectory.completionFuture().join();
List<String> keys =
requestArgumentCaptor.getAllValues().stream().map(u -> u.putObjectRequest().key())
.collect(Collectors.toList());
assertThat(keys.size()).isEqualTo(3);
assertThat(keys).containsOnly("yolo,foo,2.txt", "yolo,foo,1.txt", "yolo,bar.txt");
}
@ParameterizedTest
@MethodSource("fileSystems")
void uploadDirectory_maxLengthOne_shouldOnlyUploadTopLevel(FileSystem fileSystem) {
directory = createJimFsTestDirectory(fileSystem);
ArgumentCaptor<UploadFileRequest> requestArgumentCaptor = ArgumentCaptor.forClass(UploadFileRequest.class);
when(singleUploadFunction.apply(requestArgumentCaptor.capture()))
.thenReturn(completedUpload());
DirectoryUpload uploadDirectory =
uploadDirectoryHelper.uploadDirectory(UploadDirectoryRequest.builder()
.source(directory)
.bucket("bucket")
.maxDepth(1)
.build());
uploadDirectory.completionFuture().join();
List<UploadFileRequest> actualRequests = requestArgumentCaptor.getAllValues();
actualRequests.forEach(r -> assertThat(r.putObjectRequest().bucket()).isEqualTo("bucket"));
assertThat(actualRequests.size()).isEqualTo(1);
List<String> keys =
actualRequests.stream().map(u -> u.putObjectRequest().key())
.collect(Collectors.toList());
assertThat(keys).containsOnly("bar.txt");
}
@ParameterizedTest
@MethodSource("fileSystems")
void uploadDirectory_directoryNotExist_shouldCompleteFutureExceptionally(FileSystem fileSystem) {
directory = createJimFsTestDirectory(fileSystem);
assertThatThrownBy(() -> uploadDirectoryHelper.uploadDirectory(UploadDirectoryRequest.builder().source(Paths.get(
"randomstringneverexistas234ersaf1231"))
.bucket("bucketName").build()).completionFuture().join())
.hasMessageContaining("does not exist").hasCauseInstanceOf(IllegalArgumentException.class);
}
@Test
void uploadDirectory_notDirectory_shouldCompleteFutureExceptionally() {
assertThatThrownBy(() -> uploadDirectoryHelper.uploadDirectory(UploadDirectoryRequest.builder()
.source(Paths.get(localDirectory.toString(), "symlink"))
.bucket("bucketName").build()).completionFuture().join())
.hasMessageContaining("is not a directory").hasCauseInstanceOf(IllegalArgumentException.class);
}
@Test
void uploadDirectory_notDirectoryFollowSymlinkTrue_shouldCompleteSuccessfully() {
ArgumentCaptor<UploadFileRequest> requestArgumentCaptor = ArgumentCaptor.forClass(UploadFileRequest.class);
when(singleUploadFunction.apply(requestArgumentCaptor.capture())).thenReturn(completedUpload());
DirectoryUpload uploadDirectory = uploadDirectoryHelper.uploadDirectory(UploadDirectoryRequest.builder()
.followSymbolicLinks(true)
.source(Paths.get(localDirectory.toString(), "symlink"))
.bucket("bucket").build());
uploadDirectory.completionFuture().join();
List<UploadFileRequest> actualRequests = requestArgumentCaptor.getAllValues();
actualRequests.forEach(r -> assertThat(r.putObjectRequest().bucket()).isEqualTo("bucket"));
assertThat(actualRequests.size()).isEqualTo(1);
List<String> keys =
actualRequests.stream().map(u -> u.putObjectRequest().key())
.collect(Collectors.toList());
assertThat(keys).containsOnly("2.txt");
}
private DefaultFileUpload completedUpload() {
return new DefaultFileUpload(CompletableFuture.completedFuture(CompletedFileUpload.builder()
.response(PutObjectResponse.builder().build())
.build()),
new DefaultTransferProgress(DefaultTransferProgressSnapshot.builder()
.transferredBytes(0L)
.build()),
UploadFileRequest.builder()
.source(Paths.get(".")).putObjectRequest(b -> b.bucket("bucket").key("key"))
.build());
}
private FileUpload newUpload(CompletableFuture<CompletedFileUpload> future) {
return new DefaultFileUpload(future,
new DefaultTransferProgress(DefaultTransferProgressSnapshot.builder()
.transferredBytes(0L)
.build()),
UploadFileRequest.builder()
.putObjectRequest(p -> p.key("key").bucket("bucket")).source(Paths.get(
"test.txt"))
.build());
}
private Path createJimFsTestDirectory(FileSystem fileSystem) {
try {
return createJmfsTestDirectory(fileSystem);
} catch (IOException exception) {
throw new UncheckedIOException(exception);
}
}
private static Path createLocalTestDirectory() {
try {
return createLocalTestDirectoryWithSymLink();
} catch (IOException exception) {
throw new UncheckedIOException(exception);
}
}
/**
* Create a test directory with the following structure - test1 - foo - 1.txt - 2.txt - bar.txt - symlink -> test2 - symlink2
* -> test3/4.txt - test2 - 2.txt - test3 - 4.txt
*/
private static Path createLocalTestDirectoryWithSymLink() throws IOException {
Path directory = Files.createTempDirectory("test1");
Path anotherDirectory = Files.createTempDirectory("test2");
Path thirdDirectory = Files.createTempDirectory("test3");
String directoryName = directory.toString();
String anotherDirectoryName = anotherDirectory.toString();
Files.createDirectory(Paths.get(directory + "/foo"));
Files.write(Paths.get(directoryName, "bar.txt"), "bar".getBytes(StandardCharsets.UTF_8));
Files.write(Paths.get(directoryName, "foo/1.txt"), "1".getBytes(StandardCharsets.UTF_8));
Files.write(Paths.get(directoryName, "foo/2.txt"), "2".getBytes(StandardCharsets.UTF_8));
Files.write(Paths.get(anotherDirectoryName, "2.txt"), "2".getBytes(StandardCharsets.UTF_8));
Files.write(Paths.get(thirdDirectory.toString(), "3.txt"), "3".getBytes(StandardCharsets.UTF_8));
Files.createSymbolicLink(Paths.get(directoryName, "symlink"), anotherDirectory);
Files.createSymbolicLink(Paths.get(directoryName, "symlink2"), Paths.get(thirdDirectory.toString(), "3.txt"));
return directory;
}
/**
* Create a test directory with the following structure - test1 - foo - 1.txt - 2.txt - bar.txt
*/
private Path createJmfsTestDirectory(FileSystem jimfs) throws IOException {
String directoryName = "test";
Path directory = jimfs.getPath(directoryName);
Files.createDirectory(directory);
Files.createDirectory(jimfs.getPath(directoryName + "/foo"));
Files.write(jimfs.getPath(directoryName, "bar.txt"), "bar".getBytes(StandardCharsets.UTF_8));
Files.write(jimfs.getPath(directoryName, "foo", "1.txt"), "1".getBytes(StandardCharsets.UTF_8));
Files.write(jimfs.getPath(directoryName, "foo", "2.txt"), "2".getBytes(StandardCharsets.UTF_8));
return directory;
}
}
| 3,707 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal/DefaultDirectoryUploadTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal;
import nl.jqno.equalsverifier.EqualsVerifier;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.transfer.s3.internal.model.DefaultDirectoryUpload;
class DefaultDirectoryUploadTest {
@Test
void equals_hashcode() {
EqualsVerifier.forClass(DefaultDirectoryUpload.class)
.withNonnullFields("completionFuture")
.verify();
}
} | 3,708 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal/DefaultCopyTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal;
import nl.jqno.equalsverifier.EqualsVerifier;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.transfer.s3.internal.model.DefaultCopy;
class DefaultCopyTest {
@Test
void equals_hashcode() {
EqualsVerifier.forClass(DefaultCopy.class)
.withNonnullFields("completionFuture", "progress")
.verify();
}
} | 3,709 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal/S3TransferManagerUploadPauseAndResumeTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute.SDK_HTTP_EXECUTION_ATTRIBUTES;
import static software.amazon.awssdk.services.s3.internal.crt.S3InternalSdkHttpExecutionAttribute.CRT_PAUSE_RESUME_TOKEN;
import static software.amazon.awssdk.transfer.s3.SizeConstant.MB;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Instant;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.http.SdkHttpExecutionAttributes;
import software.amazon.awssdk.services.s3.internal.crt.S3CrtAsyncClient;
import software.amazon.awssdk.services.s3.model.AbortMultipartUploadRequest;
import software.amazon.awssdk.services.s3.model.AbortMultipartUploadResponse;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.PutObjectResponse;
import software.amazon.awssdk.testutils.RandomTempFile;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.transfer.s3.model.CompletedFileUpload;
import software.amazon.awssdk.transfer.s3.model.UploadFileRequest;
class S3TransferManagerUploadPauseAndResumeTest {
private S3CrtAsyncClient mockS3Crt;
private S3TransferManager tm;
private UploadDirectoryHelper uploadDirectoryHelper;
private DownloadDirectoryHelper downloadDirectoryHelper;
private TransferManagerConfiguration configuration;
private File file;
@BeforeEach
public void methodSetup() throws IOException {
file = RandomTempFile.createTempFile("test", UUID.randomUUID().toString());
Files.write(file.toPath(), RandomStringUtils.randomAlphanumeric(1000).getBytes(StandardCharsets.UTF_8));
mockS3Crt = mock(S3CrtAsyncClient.class);
uploadDirectoryHelper = mock(UploadDirectoryHelper.class);
configuration = mock(TransferManagerConfiguration.class);
downloadDirectoryHelper = mock(DownloadDirectoryHelper.class);
tm = new CrtS3TransferManager(configuration, mockS3Crt, false);
}
@AfterEach
public void methodTeardown() {
file.delete();
tm.close();
}
@Test
void resumeUploadFile_noResumeToken_shouldUploadFromBeginning() {
PutObjectRequest putObjectRequest = putObjectRequest();
PutObjectResponse response = PutObjectResponse.builder().build();
Instant fileLastModified = Instant.ofEpochMilli(file.lastModified());
long fileLength = file.length();
UploadFileRequest uploadFileRequest = UploadFileRequest.builder()
.putObjectRequest(putObjectRequest)
.source(file)
.build();
when(mockS3Crt.putObject(any(PutObjectRequest.class), any(Path.class)))
.thenReturn(CompletableFuture.completedFuture(response));
CompletedFileUpload completedFileUpload = tm.resumeUploadFile(r -> r.fileLength(fileLength)
.uploadFileRequest(uploadFileRequest)
.fileLastModified(fileLastModified))
.completionFuture()
.join();
assertThat(completedFileUpload.response()).isEqualTo(response);
verifyActualPutObjectRequestNotResumed();
}
@Test
void resumeUploadFile_fileModified_shouldAbortExistingAndUploadFromBeginning() {
PutObjectRequest putObjectRequest = putObjectRequest();
PutObjectResponse response = PutObjectResponse.builder().build();
Instant fileLastModified = Instant.ofEpochMilli(file.lastModified());
long fileLength = file.length();
UploadFileRequest uploadFileRequest = UploadFileRequest.builder()
.putObjectRequest(putObjectRequest)
.source(file)
.build();
when(mockS3Crt.putObject(any(PutObjectRequest.class), any(Path.class)))
.thenReturn(CompletableFuture.completedFuture(response));
when(mockS3Crt.abortMultipartUpload(any(AbortMultipartUploadRequest.class)))
.thenReturn(CompletableFuture.completedFuture(AbortMultipartUploadResponse.builder().build()));
String multipartId = "someId";
CompletedFileUpload completedFileUpload = tm.resumeUploadFile(r -> r.fileLength(fileLength + 10L)
.partSizeInBytes(8 * MB)
.totalParts(10L)
.multipartUploadId(multipartId)
.uploadFileRequest(uploadFileRequest)
.fileLastModified(fileLastModified))
.completionFuture()
.join();
assertThat(completedFileUpload.response()).isEqualTo(response);
verifyActualPutObjectRequestNotResumed();
ArgumentCaptor<AbortMultipartUploadRequest> abortMultipartUploadRequestArgumentCaptor =
ArgumentCaptor.forClass(AbortMultipartUploadRequest.class);
verify(mockS3Crt).abortMultipartUpload(abortMultipartUploadRequestArgumentCaptor.capture());
AbortMultipartUploadRequest actualRequest = abortMultipartUploadRequestArgumentCaptor.getValue();
assertThat(actualRequest.uploadId()).isEqualTo(multipartId);
}
@Test
void resumeUploadFile_hasValidResumeToken_shouldResumeUpload() {
PutObjectRequest putObjectRequest = putObjectRequest();
PutObjectResponse response = PutObjectResponse.builder().build();
Instant fileLastModified = Instant.ofEpochMilli(file.lastModified());
long fileLength = file.length();
UploadFileRequest uploadFileRequest = UploadFileRequest.builder()
.putObjectRequest(putObjectRequest)
.source(file)
.build();
when(mockS3Crt.putObject(any(PutObjectRequest.class), any(Path.class)))
.thenReturn(CompletableFuture.completedFuture(response));
String multipartId = "someId";
long totalParts = 10L;
long partSizeInBytes = 8 * MB;
CompletedFileUpload completedFileUpload = tm.resumeUploadFile(r -> r.fileLength(fileLength)
.partSizeInBytes(partSizeInBytes)
.totalParts(totalParts)
.multipartUploadId(multipartId)
.uploadFileRequest(uploadFileRequest)
.fileLastModified(fileLastModified))
.completionFuture()
.join();
assertThat(completedFileUpload.response()).isEqualTo(response);
ArgumentCaptor<PutObjectRequest> putObjectRequestArgumentCaptor =
ArgumentCaptor.forClass(PutObjectRequest.class);
verify(mockS3Crt).putObject(putObjectRequestArgumentCaptor.capture(), any(Path.class));
PutObjectRequest actualRequest = putObjectRequestArgumentCaptor.getValue();
AwsRequestOverrideConfiguration awsRequestOverrideConfiguration = actualRequest.overrideConfiguration().get();
SdkHttpExecutionAttributes attribute =
awsRequestOverrideConfiguration.executionAttributes().getAttribute(SDK_HTTP_EXECUTION_ATTRIBUTES);
assertThat(attribute.getAttribute(CRT_PAUSE_RESUME_TOKEN)).satisfies(token -> {
assertThat(token.getUploadId()).isEqualTo(multipartId);
assertThat(token.getPartSize()).isEqualTo(partSizeInBytes);
assertThat(token.getTotalNumParts()).isEqualTo(totalParts);
});
}
private void verifyActualPutObjectRequestNotResumed() {
ArgumentCaptor<PutObjectRequest> putObjectRequestArgumentCaptor =
ArgumentCaptor.forClass(PutObjectRequest.class);
verify(mockS3Crt).putObject(putObjectRequestArgumentCaptor.capture(), any(Path.class));
PutObjectRequest actualRequest = putObjectRequestArgumentCaptor.getValue();
AwsRequestOverrideConfiguration awsRequestOverrideConfiguration = actualRequest.overrideConfiguration().get();
SdkHttpExecutionAttributes attribute =
awsRequestOverrideConfiguration.executionAttributes().getAttribute(SDK_HTTP_EXECUTION_ATTRIBUTES);
assertThat(attribute.getAttribute(CRT_PAUSE_RESUME_TOKEN)).isNull();
}
private static PutObjectRequest putObjectRequest() {
return PutObjectRequest.builder()
.key("key")
.bucket("bucket")
.build();
}
}
| 3,710 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal/DefaultUploadTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal;
import nl.jqno.equalsverifier.EqualsVerifier;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.transfer.s3.internal.model.DefaultUpload;
public class DefaultUploadTest {
@Test
public void equals_hashcode() {
EqualsVerifier.forClass(DefaultUpload.class)
.withNonnullFields("completionFuture", "progress")
.verify();
}
} | 3,711 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal/TransferManagerConfigurationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static software.amazon.awssdk.transfer.s3.internal.TransferConfigurationOption.EXECUTOR;
import static software.amazon.awssdk.transfer.s3.internal.TransferConfigurationOption.UPLOAD_DIRECTORY_FOLLOW_SYMBOLIC_LINKS;
import static software.amazon.awssdk.transfer.s3.internal.TransferConfigurationOption.UPLOAD_DIRECTORY_MAX_DEPTH;
import java.nio.file.Paths;
import java.util.concurrent.ExecutorService;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import software.amazon.awssdk.transfer.s3.model.UploadDirectoryRequest;
public class TransferManagerConfigurationTest {
private TransferManagerConfiguration transferManagerConfiguration;
@Test
public void resolveMaxDepth_requestOverride_requestOverrideShouldTakePrecedence() {
transferManagerConfiguration = TransferManagerConfiguration.builder()
.uploadDirectoryMaxDepth(1)
.build();
UploadDirectoryRequest uploadDirectoryRequest = UploadDirectoryRequest.builder()
.bucket("bucket")
.source(Paths.get("."))
.maxDepth(2)
.build();
assertThat(transferManagerConfiguration.resolveUploadDirectoryMaxDepth(uploadDirectoryRequest)).isEqualTo(2);
}
@Test
public void resolveFollowSymlinks_requestOverride_requestOverrideShouldTakePrecedence() {
transferManagerConfiguration = TransferManagerConfiguration.builder()
.uploadDirectoryFollowSymbolicLinks(false)
.build();
UploadDirectoryRequest uploadDirectoryRequest = UploadDirectoryRequest.builder()
.bucket("bucket")
.source(Paths.get("."))
.followSymbolicLinks(true)
.build();
assertThat(transferManagerConfiguration.resolveUploadDirectoryFollowSymbolicLinks(uploadDirectoryRequest)).isTrue();
}
@Test
public void noOverride_shouldUseDefaults() {
transferManagerConfiguration = TransferManagerConfiguration.builder().build();
assertThat(transferManagerConfiguration.option(UPLOAD_DIRECTORY_FOLLOW_SYMBOLIC_LINKS)).isFalse();
assertThat(transferManagerConfiguration.option(UPLOAD_DIRECTORY_MAX_DEPTH)).isEqualTo(Integer.MAX_VALUE);
assertThat(transferManagerConfiguration.option(EXECUTOR)).isNotNull();
}
@Test
public void close_noCustomExecutor_shouldCloseDefaultOne() {
transferManagerConfiguration = TransferManagerConfiguration.builder().build();
transferManagerConfiguration.close();
ExecutorService executor = (ExecutorService) transferManagerConfiguration.option(EXECUTOR);
assertThat(executor.isShutdown()).isTrue();
}
@Test
public void close_customExecutor_shouldNotCloseCustomExecutor() {
ExecutorService executorService = Mockito.mock(ExecutorService.class);
transferManagerConfiguration = TransferManagerConfiguration.builder().executor(executorService).build();
transferManagerConfiguration.close();
verify(executorService, never()).shutdown();
}
}
| 3,712 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal/DefaultDirectoryDownloadTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal;
import nl.jqno.equalsverifier.EqualsVerifier;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.transfer.s3.internal.model.DefaultDirectoryDownload;
class DefaultDirectoryDownloadTest {
@Test
void equals_hashcode() {
EqualsVerifier.forClass(DefaultDirectoryDownload.class)
.withNonnullFields("completionFuture")
.verify();
}
} | 3,713 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal/DefaultTransferProgressSnapshotTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.transfer.s3.internal.progress.DefaultTransferProgressSnapshot;
import software.amazon.awssdk.transfer.s3.progress.TransferProgressSnapshot;
public class DefaultTransferProgressSnapshotTest {
@Test
public void bytesTransferred_greaterThan_transferSize_shouldThrow() {
DefaultTransferProgressSnapshot.Builder builder = DefaultTransferProgressSnapshot.builder()
.transferredBytes(2L)
.totalBytes(1L);
assertThatThrownBy(builder::build)
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("transferredBytes (2) must not be greater than totalBytes (1)");
}
@Test
public void ratioTransferred_withoutTransferSize_isEmpty() {
TransferProgressSnapshot snapshot = DefaultTransferProgressSnapshot.builder()
.transferredBytes(1L)
.build();
assertThat(snapshot.ratioTransferred()).isNotPresent();
}
@Test
public void ratioTransferred_withTransferSize_isCorrect() {
TransferProgressSnapshot snapshot = DefaultTransferProgressSnapshot.builder()
.transferredBytes(1L)
.totalBytes(2L)
.build();
assertThat(snapshot.ratioTransferred()).hasValue(0.5);
}
@Test
public void bytesRemainingTransferred_withoutTransferSize_isEmpty() {
TransferProgressSnapshot snapshot = DefaultTransferProgressSnapshot.builder()
.transferredBytes(1L)
.build();
assertThat(snapshot.remainingBytes()).isNotPresent();
}
@Test
public void bytesRemainingTransferred_withTransferSize_isCorrect() {
TransferProgressSnapshot snapshot = DefaultTransferProgressSnapshot.builder()
.transferredBytes(1L)
.totalBytes(3L)
.build();
assertThat(snapshot.remainingBytes()).hasValue(2L);
}
} | 3,714 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal/S3TransferManagerListenerTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import com.google.common.jimfs.Configuration;
import com.google.common.jimfs.Jimfs;
import java.nio.ByteBuffer;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ThreadLocalRandom;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.stubbing.Answer;
import software.amazon.awssdk.core.ResponseBytes;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.core.async.AsyncResponseTransformer;
import software.amazon.awssdk.core.async.DrainingSubscriber;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.services.s3.internal.crt.S3CrtAsyncClient;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.PutObjectResponse;
import software.amazon.awssdk.transfer.s3.model.CompletedFileUpload;
import software.amazon.awssdk.transfer.s3.model.Download;
import software.amazon.awssdk.transfer.s3.model.DownloadFileRequest;
import software.amazon.awssdk.transfer.s3.model.DownloadRequest;
import software.amazon.awssdk.transfer.s3.model.FileDownload;
import software.amazon.awssdk.transfer.s3.model.FileUpload;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.transfer.s3.model.Upload;
import software.amazon.awssdk.transfer.s3.model.UploadFileRequest;
import software.amazon.awssdk.transfer.s3.model.UploadRequest;
import software.amazon.awssdk.transfer.s3.progress.TransferListener;
public class S3TransferManagerListenerTest {
private final FileSystem fs = Jimfs.newFileSystem(Configuration.unix());
private S3CrtAsyncClient s3Crt;
private S3TransferManager tm;
private long contentLength;
@BeforeEach
public void methodSetup() {
s3Crt = mock(S3CrtAsyncClient.class);
tm = new GenericS3TransferManager(s3Crt, mock(UploadDirectoryHelper.class), mock(TransferManagerConfiguration.class),
mock(DownloadDirectoryHelper.class));
contentLength = 1024L;
when(s3Crt.putObject(any(PutObjectRequest.class), any(AsyncRequestBody.class)))
.thenAnswer(drainPutRequestBody());
when(s3Crt.getObject(any(GetObjectRequest.class), any(AsyncResponseTransformer.class)))
.thenAnswer(randomGetResponseBody(contentLength));
}
@AfterEach
public void methodTeardown() {
tm.close();
}
@Test
public void uploadFile_success_shouldInvokeListener() throws Exception {
TransferListener listener = mock(TransferListener.class);
Path path = newTempFile();
Files.write(path, randomBytes(contentLength));
UploadFileRequest uploadFileRequest = UploadFileRequest.builder()
.putObjectRequest(r -> r.bucket("bucket")
.key("key"))
.source(path)
.addTransferListener(listener)
.build();
FileUpload fileUpload = tm.uploadFile(uploadFileRequest);
ArgumentCaptor<TransferListener.Context.TransferInitiated> captor1 =
ArgumentCaptor.forClass(TransferListener.Context.TransferInitiated.class);
verify(listener, timeout(1000).times(1)).transferInitiated(captor1.capture());
TransferListener.Context.TransferInitiated ctx1 = captor1.getValue();
assertThat(ctx1.request()).isSameAs(uploadFileRequest);
assertThat(ctx1.progressSnapshot().totalBytes()).hasValue(contentLength);
assertThat(ctx1.progressSnapshot().transferredBytes()).isZero();
ArgumentCaptor<TransferListener.Context.BytesTransferred> captor2 =
ArgumentCaptor.forClass(TransferListener.Context.BytesTransferred.class);
verify(listener, timeout(1000).times(1)).bytesTransferred(captor2.capture());
TransferListener.Context.BytesTransferred ctx2 = captor2.getValue();
assertThat(ctx2.request()).isSameAs(uploadFileRequest);
assertThat(ctx2.progressSnapshot().totalBytes()).hasValue(contentLength);
assertThat(ctx2.progressSnapshot().transferredBytes()).isPositive();
ArgumentCaptor<TransferListener.Context.TransferComplete> captor3 =
ArgumentCaptor.forClass(TransferListener.Context.TransferComplete.class);
verify(listener, timeout(1000).times(1)).transferComplete(captor3.capture());
TransferListener.Context.TransferComplete ctx3 = captor3.getValue();
assertThat(ctx3.request()).isSameAs(uploadFileRequest);
assertThat(ctx3.progressSnapshot().totalBytes()).hasValue(contentLength);
assertThat(ctx3.progressSnapshot().transferredBytes()).isEqualTo(contentLength);
assertThat(ctx3.completedTransfer()).isSameAs(fileUpload.completionFuture().get());
fileUpload.completionFuture().join();
verifyNoMoreInteractions(listener);
}
@Test
public void upload_success_shouldInvokeListener() throws Exception {
TransferListener listener = mock(TransferListener.class);
UploadRequest uploadRequest = UploadRequest.builder()
.putObjectRequest(r -> r.bucket("bucket")
.key("key"))
.requestBody(AsyncRequestBody.fromString("foo"))
.addTransferListener(listener)
.build();
Upload upload = tm.upload(uploadRequest);
ArgumentCaptor<TransferListener.Context.TransferInitiated> captor1 =
ArgumentCaptor.forClass(TransferListener.Context.TransferInitiated.class);
verify(listener, timeout(1000).times(1)).transferInitiated(captor1.capture());
TransferListener.Context.TransferInitiated ctx1 = captor1.getValue();
assertThat(ctx1.request()).isSameAs(uploadRequest);
assertThat(ctx1.progressSnapshot().totalBytes()).hasValue(3L);
assertThat(ctx1.progressSnapshot().transferredBytes()).isZero();
ArgumentCaptor<TransferListener.Context.BytesTransferred> captor2 =
ArgumentCaptor.forClass(TransferListener.Context.BytesTransferred.class);
verify(listener, timeout(1000).times(1)).bytesTransferred(captor2.capture());
TransferListener.Context.BytesTransferred ctx2 = captor2.getValue();
assertThat(ctx2.request()).isSameAs(uploadRequest);
assertThat(ctx2.progressSnapshot().totalBytes()).hasValue(3L);
assertThat(ctx2.progressSnapshot().transferredBytes()).isPositive();
ArgumentCaptor<TransferListener.Context.TransferComplete> captor3 =
ArgumentCaptor.forClass(TransferListener.Context.TransferComplete.class);
verify(listener, timeout(1000).times(1)).transferComplete(captor3.capture());
TransferListener.Context.TransferComplete ctx3 = captor3.getValue();
assertThat(ctx3.request()).isSameAs(uploadRequest);
assertThat(ctx3.progressSnapshot().totalBytes()).hasValue(3L);
assertThat(ctx3.progressSnapshot().transferredBytes()).isEqualTo(3L);
assertThat(ctx3.completedTransfer()).isSameAs(upload.completionFuture().get());
upload.completionFuture().join();
verifyNoMoreInteractions(listener);
}
@Test
public void downloadFile_success_shouldInvokeListener() throws Exception {
TransferListener listener = mock(TransferListener.class);
DownloadFileRequest downloadRequest = DownloadFileRequest.builder()
.getObjectRequest(r -> r.bucket("bucket")
.key("key"))
.destination(newTempFile())
.addTransferListener(listener)
.build();
FileDownload download = tm.downloadFile(downloadRequest);
ArgumentCaptor<TransferListener.Context.TransferInitiated> captor1 =
ArgumentCaptor.forClass(TransferListener.Context.TransferInitiated.class);
verify(listener, timeout(1000).times(1)).transferInitiated(captor1.capture());
TransferListener.Context.TransferInitiated ctx1 = captor1.getValue();
assertThat(ctx1.request()).isSameAs(downloadRequest);
// transferSize is not known until we receive GetObjectResponse header
assertThat(ctx1.progressSnapshot().totalBytes()).isNotPresent();
assertThat(ctx1.progressSnapshot().transferredBytes()).isZero();
ArgumentCaptor<TransferListener.Context.BytesTransferred> captor2 =
ArgumentCaptor.forClass(TransferListener.Context.BytesTransferred.class);
verify(listener, timeout(1000).times(1)).bytesTransferred(captor2.capture());
TransferListener.Context.BytesTransferred ctx2 = captor2.getValue();
assertThat(ctx2.request()).isSameAs(downloadRequest);
// transferSize should now be known
assertThat(ctx2.progressSnapshot().totalBytes()).hasValue(contentLength);
assertThat(ctx2.progressSnapshot().transferredBytes()).isPositive();
ArgumentCaptor<TransferListener.Context.TransferComplete> captor3 =
ArgumentCaptor.forClass(TransferListener.Context.TransferComplete.class);
verify(listener, timeout(1000).times(1)).transferComplete(captor3.capture());
TransferListener.Context.TransferComplete ctx3 = captor3.getValue();
assertThat(ctx3.request()).isSameAs(downloadRequest);
assertThat(ctx3.progressSnapshot().totalBytes()).hasValue(contentLength);
assertThat(ctx3.progressSnapshot().transferredBytes()).isEqualTo(contentLength);
assertThat(ctx3.completedTransfer()).isSameAs(download.completionFuture().get());
download.completionFuture().join();
verifyNoMoreInteractions(listener);
}
@Test
public void download_success_shouldInvokeListener() throws Exception {
TransferListener listener = mock(TransferListener.class);
DownloadRequest<ResponseBytes<GetObjectResponse>> downloadRequest =
DownloadRequest.builder()
.getObjectRequest(r -> r.bucket(
"bucket")
.key("key"))
.responseTransformer(AsyncResponseTransformer.toBytes())
.addTransferListener(listener)
.build();
Download<ResponseBytes<GetObjectResponse>> download = tm.download(downloadRequest);
ArgumentCaptor<TransferListener.Context.TransferInitiated> captor1 =
ArgumentCaptor.forClass(TransferListener.Context.TransferInitiated.class);
verify(listener, timeout(1000).times(1)).transferInitiated(captor1.capture());
TransferListener.Context.TransferInitiated ctx1 = captor1.getValue();
assertThat(ctx1.request()).isSameAs(downloadRequest);
// transferSize is not known until we receive GetObjectResponse header
assertThat(ctx1.progressSnapshot().totalBytes()).isNotPresent();
assertThat(ctx1.progressSnapshot().transferredBytes()).isZero();
ArgumentCaptor<TransferListener.Context.BytesTransferred> captor2 =
ArgumentCaptor.forClass(TransferListener.Context.BytesTransferred.class);
verify(listener, timeout(1000).times(1)).bytesTransferred(captor2.capture());
TransferListener.Context.BytesTransferred ctx2 = captor2.getValue();
assertThat(ctx2.request()).isSameAs(downloadRequest);
// transferSize should now be known
assertThat(ctx2.progressSnapshot().totalBytes()).hasValue(contentLength);
assertThat(ctx2.progressSnapshot().transferredBytes()).isPositive();
ArgumentCaptor<TransferListener.Context.TransferComplete> captor3 =
ArgumentCaptor.forClass(TransferListener.Context.TransferComplete.class);
verify(listener, timeout(1000).times(1)).transferComplete(captor3.capture());
TransferListener.Context.TransferComplete ctx3 = captor3.getValue();
assertThat(ctx3.request()).isSameAs(downloadRequest);
assertThat(ctx3.progressSnapshot().totalBytes()).hasValue(contentLength);
assertThat(ctx3.progressSnapshot().transferredBytes()).isEqualTo(contentLength);
assertThat(ctx3.completedTransfer()).isSameAs(download.completionFuture().get());
download.completionFuture().join();
verifyNoMoreInteractions(listener);
}
@Test
public void uploadFile_failure_shouldInvokeListener() throws Exception {
TransferListener listener = mock(TransferListener.class);
Path path = newTempFile();
Files.write(path, randomBytes(contentLength));
UploadFileRequest uploadFileRequest = UploadFileRequest.builder()
.putObjectRequest(r -> r.bucket("bucket")
.key("key"))
.source(path)
.addTransferListener(listener)
.build();
SdkClientException sdkClientException = SdkClientException.create("");
when(s3Crt.putObject(any(PutObjectRequest.class), any(AsyncRequestBody.class)))
.thenThrow(sdkClientException);
FileUpload fileUpload = tm.uploadFile(uploadFileRequest);
CompletableFuture<CompletedFileUpload> future = fileUpload.completionFuture();
assertThatThrownBy(future::join)
.isInstanceOf(CompletionException.class)
.hasCause(sdkClientException);
ArgumentCaptor<TransferListener.Context.TransferInitiated> captor1 =
ArgumentCaptor.forClass(TransferListener.Context.TransferInitiated.class);
verify(listener, timeout(1000).times(1)).transferInitiated(captor1.capture());
TransferListener.Context.TransferInitiated ctx1 = captor1.getValue();
assertThat(ctx1.request()).isSameAs(uploadFileRequest);
assertThat(ctx1.progressSnapshot().transferredBytes()).isZero();
ArgumentCaptor<TransferListener.Context.TransferFailed> captor2 =
ArgumentCaptor.forClass(TransferListener.Context.TransferFailed.class);
verify(listener, timeout(1000).times(1)).transferFailed(captor2.capture());
TransferListener.Context.TransferFailed ctx2 = captor2.getValue();
assertThat(ctx2.request()).isSameAs(uploadFileRequest);
assertThat(ctx2.progressSnapshot().transferredBytes()).isZero();
assertThat(ctx2.exception()).isEqualTo(sdkClientException);
verifyNoMoreInteractions(listener);
}
@Test
public void listener_exception_shouldBeSuppressed() throws Exception {
TransferListener listener = throwingListener();
Path path = newTempFile();
Files.write(path, randomBytes(contentLength));
UploadFileRequest uploadFileRequest = UploadFileRequest.builder()
.putObjectRequest(r -> r.bucket("bucket")
.key("key"))
.source(path)
.addTransferListener(listener)
.build();
FileUpload fileUpload = tm.uploadFile(uploadFileRequest);
verify(listener, timeout(1000).times(1)).transferInitiated(any());
verify(listener, timeout(1000).times(1)).bytesTransferred(any());
verify(listener, timeout(1000).times(1)).transferComplete(any());
fileUpload.completionFuture().join();
verifyNoMoreInteractions(listener);
}
private static TransferListener throwingListener() {
TransferListener listener = mock(TransferListener.class);
RuntimeException e = new RuntimeException("Intentional exception for testing purposes");
doThrow(e).when(listener).transferInitiated(any());
doThrow(e).when(listener).bytesTransferred(any());
doThrow(e).when(listener).transferComplete(any());
doThrow(e).when(listener).transferFailed(any());
return listener;
}
private static Answer<CompletableFuture<PutObjectResponse>> drainPutRequestBody() {
return invocationOnMock -> {
AsyncRequestBody requestBody = invocationOnMock.getArgument(1, AsyncRequestBody.class);
CompletableFuture<PutObjectResponse> cf = new CompletableFuture<>();
requestBody.subscribe(new DrainingSubscriber<ByteBuffer>() {
@Override
public void onError(Throwable t) {
cf.completeExceptionally(t);
}
@Override
public void onComplete() {
cf.complete(PutObjectResponse.builder().build());
}
});
return cf;
};
}
private static Answer<CompletableFuture<GetObjectResponse>> randomGetResponseBody(long contentLength) {
return invocationOnMock -> {
AsyncResponseTransformer<GetObjectResponse, GetObjectResponse> responseTransformer =
invocationOnMock.getArgument(1, AsyncResponseTransformer.class);
CompletableFuture<GetObjectResponse> cf = responseTransformer.prepare();
responseTransformer.onResponse(GetObjectResponse.builder()
.contentLength(contentLength)
.build());
responseTransformer.onStream(AsyncRequestBody.fromBytes(randomBytes(contentLength)));
return cf;
};
}
private Path newTempFile() {
return fs.getPath("/", UUID.randomUUID().toString());
}
private static byte[] randomBytes(long size) {
byte[] bytes = new byte[Math.toIntExact(size)];
ThreadLocalRandom.current().nextBytes(bytes);
return bytes;
}
}
| 3,715 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal/CrtTransferManagerPauseAndResumeTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.time.Instant;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import software.amazon.awssdk.core.async.AsyncResponseTransformer;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.exception.SdkException;
import software.amazon.awssdk.services.s3.internal.crt.S3CrtAsyncClient;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.services.s3.model.HeadObjectResponse;
import software.amazon.awssdk.testutils.RandomTempFile;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.transfer.s3.model.CompletedFileDownload;
import software.amazon.awssdk.transfer.s3.model.DownloadFileRequest;
import software.amazon.awssdk.transfer.s3.model.FileDownload;
import software.amazon.awssdk.transfer.s3.model.ResumableFileDownload;
import software.amazon.awssdk.utils.CompletableFutureUtils;
class CrtTransferManagerPauseAndResumeTest {
private S3CrtAsyncClient mockS3Crt;
private S3TransferManager tm;
private UploadDirectoryHelper uploadDirectoryHelper;
private DownloadDirectoryHelper downloadDirectoryHelper;
private TransferManagerConfiguration configuration;
private File file;
@BeforeEach
public void methodSetup() throws IOException {
file = RandomTempFile.createTempFile("test", UUID.randomUUID().toString());
Files.write(file.toPath(), RandomStringUtils.randomAlphanumeric(1000).getBytes(StandardCharsets.UTF_8));
mockS3Crt = mock(S3CrtAsyncClient.class);
uploadDirectoryHelper = mock(UploadDirectoryHelper.class);
configuration = mock(TransferManagerConfiguration.class);
downloadDirectoryHelper = mock(DownloadDirectoryHelper.class);
tm = new CrtS3TransferManager(configuration, mockS3Crt, false);
}
@AfterEach
public void methodTeardown() {
file.delete();
tm.close();
}
@Test
void resumeDownloadFile_shouldSetRangeAccordingly() {
GetObjectRequest getObjectRequest = getObjectRequest();
GetObjectResponse response = GetObjectResponse.builder().build();
Instant s3ObjectLastModified = Instant.now();
Instant fileLastModified = Instant.ofEpochMilli(file.lastModified());
HeadObjectResponse headObjectResponse = headObjectResponse(s3ObjectLastModified);
DownloadFileRequest downloadFileRequest = DownloadFileRequest.builder()
.getObjectRequest(getObjectRequest)
.destination(file)
.build();
when(mockS3Crt.getObject(any(GetObjectRequest.class), any(AsyncResponseTransformer.class)))
.thenReturn(CompletableFuture.completedFuture(response));
when(mockS3Crt.headObject(any(Consumer.class)))
.thenReturn(CompletableFuture.completedFuture(headObjectResponse));
CompletedFileDownload completedFileDownload = tm.resumeDownloadFile(r -> r.bytesTransferred(file.length())
.downloadFileRequest(downloadFileRequest)
.fileLastModified(fileLastModified)
.s3ObjectLastModified(s3ObjectLastModified))
.completionFuture()
.join();
assertThat(completedFileDownload.response()).isEqualTo(response);
verifyActualGetObjectRequest(getObjectRequest, "bytes=1000-2000");
}
@Test
void resumeDownloadFile_headObjectFailed_shouldFail() {
GetObjectRequest getObjectRequest = getObjectRequest();
Instant fileLastModified = Instant.ofEpochMilli(file.lastModified());
DownloadFileRequest downloadFileRequest = DownloadFileRequest.builder()
.getObjectRequest(getObjectRequest)
.destination(file)
.build();
SdkClientException sdkClientException = SdkClientException.create("failed");
when(mockS3Crt.headObject(any(Consumer.class)))
.thenReturn(CompletableFutureUtils.failedFuture(sdkClientException));
assertThatThrownBy(() -> tm.resumeDownloadFile(r -> r.bytesTransferred(1000l)
.downloadFileRequest(downloadFileRequest)
.fileLastModified(fileLastModified)
.s3ObjectLastModified(Instant.now()))
.completionFuture()
.join()).hasRootCause(sdkClientException);
}
@Test
void resumeDownloadFile_errorShouldNotBeWrapped() {
GetObjectRequest getObjectRequest = getObjectRequest();
Instant fileLastModified = Instant.ofEpochMilli(file.lastModified());
DownloadFileRequest downloadFileRequest = DownloadFileRequest.builder()
.getObjectRequest(getObjectRequest)
.destination(file)
.build();
Error error = new OutOfMemoryError();
when(mockS3Crt.headObject(any(Consumer.class)))
.thenReturn(CompletableFutureUtils.failedFuture(error));
assertThatThrownBy(() -> tm.resumeDownloadFile(r -> r.bytesTransferred(1000l)
.downloadFileRequest(downloadFileRequest)
.fileLastModified(fileLastModified)
.s3ObjectLastModified(Instant.now()))
.completionFuture()
.join()).hasCauseInstanceOf(Error.class);
}
@Test
void resumeDownloadFile_SdkExceptionShouldNotBeWrapped() {
GetObjectRequest getObjectRequest = getObjectRequest();
Instant fileLastModified = Instant.ofEpochMilli(file.lastModified());
DownloadFileRequest downloadFileRequest = DownloadFileRequest.builder()
.getObjectRequest(getObjectRequest)
.destination(file)
.build();
SdkException sdkException = SdkException.create("Failed to resume the request", new Throwable());
when(mockS3Crt.headObject(any(Consumer.class)))
.thenReturn(CompletableFutureUtils.failedFuture(sdkException));
assertThatThrownBy(() -> tm.resumeDownloadFile(r -> r.bytesTransferred(1000l)
.downloadFileRequest(downloadFileRequest)
.fileLastModified(fileLastModified)
.s3ObjectLastModified(Instant.now()))
.completionFuture()
.join()).hasCause(sdkException);
}
@Test
public void pauseAfterResumeBeforeHeadSucceeds() throws InterruptedException {
DownloadFileRequest downloadFileRequest = DownloadFileRequest.builder()
.getObjectRequest(getObjectRequest())
.destination(file)
.build();
CompletableFuture<?> headFuture = new CompletableFuture<>();
when(mockS3Crt.headObject(any(Consumer.class))).thenReturn(headFuture);
ResumableFileDownload originalResumable =
ResumableFileDownload.builder()
.bytesTransferred(file.length())
.downloadFileRequest(downloadFileRequest)
.fileLastModified(Instant.ofEpochMilli(file.lastModified()))
.s3ObjectLastModified(Instant.now())
.totalSizeInBytes(2000L)
.build();
FileDownload fileDownload = tm.resumeDownloadFile(originalResumable);
ResumableFileDownload newResumable = fileDownload.pause();
assertThat(newResumable).isEqualTo(originalResumable);
assertThat(fileDownload.completionFuture()).isCancelled();
assertThat(headFuture).isCancelled();
}
@Test
public void pauseAfterResumeAfterHeadBeforeGetSucceeds() throws InterruptedException {
DownloadFileRequest downloadFileRequest = DownloadFileRequest.builder()
.getObjectRequest(getObjectRequest())
.destination(file)
.build();
CompletableFuture<?> getFuture = new CompletableFuture<>();
when(mockS3Crt.getObject(any(GetObjectRequest.class), any(AsyncResponseTransformer.class))).thenReturn(getFuture);
Instant s3LastModified = Instant.now();
when(mockS3Crt.headObject(any(Consumer.class)))
.thenReturn(CompletableFuture.completedFuture(headObjectResponse(s3LastModified)));
ResumableFileDownload originalResumable =
ResumableFileDownload.builder()
.bytesTransferred(file.length())
.downloadFileRequest(downloadFileRequest)
.fileLastModified(Instant.ofEpochMilli(file.lastModified()))
.s3ObjectLastModified(s3LastModified)
.totalSizeInBytes(2000L)
.build();
FileDownload fileDownload = tm.resumeDownloadFile(originalResumable);
ResumableFileDownload newResumable = fileDownload.pause();
assertThat(newResumable.s3ObjectLastModified()).isEqualTo(originalResumable.s3ObjectLastModified());
assertThat(newResumable.bytesTransferred()).isEqualTo(originalResumable.bytesTransferred());
assertThat(newResumable.totalSizeInBytes()).isEqualTo(originalResumable.totalSizeInBytes());
assertThat(newResumable.fileLastModified()).isEqualTo(originalResumable.fileLastModified());
// Download will be modified now that we finished the head request
assertThat(newResumable.downloadFileRequest()).isNotEqualTo(originalResumable.downloadFileRequest());
assertThat(fileDownload.completionFuture()).isCancelled();
assertThat(getFuture).isCancelled();
}
private void verifyActualGetObjectRequest(GetObjectRequest getObjectRequest, String range) {
ArgumentCaptor<GetObjectRequest> getObjectRequestArgumentCaptor =
ArgumentCaptor.forClass(GetObjectRequest.class);
verify(mockS3Crt).getObject(getObjectRequestArgumentCaptor.capture(), any(AsyncResponseTransformer.class));
GetObjectRequest actualRequest = getObjectRequestArgumentCaptor.getValue();
assertThat(actualRequest.bucket()).isEqualTo(getObjectRequest.bucket());
assertThat(actualRequest.key()).isEqualTo(getObjectRequest.key());
assertThat(actualRequest.range()).isEqualTo(range);
}
private static GetObjectRequest getObjectRequest() {
return GetObjectRequest.builder()
.key("key")
.bucket("bucket")
.build();
}
private static HeadObjectResponse headObjectResponse(Instant s3ObjectLastModified) {
return HeadObjectResponse
.builder()
.contentLength(2000L)
.lastModified(s3ObjectLastModified)
.build();
}
}
| 3,716 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal/AsyncBufferingSubscriberTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal;
import static org.assertj.core.api.Assertions.assertThat;
import io.reactivex.Flowable;
import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.IntStream;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.reactivestreams.Subscription;
class AsyncBufferingSubscriberTest {
private static final int MAX_CONCURRENT_EXECUTIONS = 5;
private AsyncBufferingSubscriber<String> subscriber;
private Function<String, CompletableFuture<?>> consumer;
private CompletableFuture<Void> returnFuture;
private final List<CompletableFuture<Void>> futures = new ArrayList<>();
private static ScheduledExecutorService scheduledExecutorService;
@BeforeAll
public static void setUp() {
scheduledExecutorService = Executors.newScheduledThreadPool(5);
}
@BeforeEach
public void setUpPerTest() {
returnFuture = new CompletableFuture<>();
for (int i = 0; i < 101; i++) {
futures.add(new CompletableFuture<>());
}
Iterator<CompletableFuture<Void>> iterator = futures.iterator();
consumer = s -> {
CompletableFuture<Void> future = iterator.next();
scheduledExecutorService.schedule(() -> {
future.complete(null);
}, 200, TimeUnit.MILLISECONDS);
return future;
};
subscriber = new AsyncBufferingSubscriber<>(consumer, returnFuture,
MAX_CONCURRENT_EXECUTIONS);
}
@AfterAll
public static void cleanUp() {
scheduledExecutorService.shutdown();
}
@ParameterizedTest
@ValueSource(ints = {1, 4, 11, 20, 100})
void differentNumberOfStrings_shouldCompleteSuccessfully(int numberOfStrings) throws Exception {
Flowable.fromArray(IntStream.range(0, numberOfStrings).mapToObj(String::valueOf).toArray(String[]::new)).subscribe(subscriber);
List<Integer> numRequestsInFlightSampling = new ArrayList<>();
Disposable disposable = Observable.interval(100, TimeUnit.MILLISECONDS, Schedulers.newThread())
.map(time -> subscriber.numRequestsInFlight())
.subscribe(numRequestsInFlightSampling::add, t -> {});
returnFuture.get(1000, TimeUnit.SECONDS);
assertThat(returnFuture).isCompleted().isNotCompletedExceptionally();
if (numberOfStrings >= MAX_CONCURRENT_EXECUTIONS) {
assertThat(numRequestsInFlightSampling).contains(MAX_CONCURRENT_EXECUTIONS);
}
disposable.dispose();
}
@Test
void onErrorInvoked_shouldCompleteFutureExceptionally() {
subscriber.onSubscribe(new Subscription() {
@Override
public void request(long n) {
}
@Override
public void cancel() {
}
});
RuntimeException exception = new RuntimeException("test");
subscriber.onError(exception);
assertThat(returnFuture).isCompletedExceptionally();
}
}
| 3,717 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal/DownloadDirectoryHelperTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static software.amazon.awssdk.transfer.s3.util.S3ApiCallMockUtils.stubSuccessfulListObjects;
import com.google.common.jimfs.Configuration;
import com.google.common.jimfs.Jimfs;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.assertj.core.util.Sets;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.services.s3.model.EncodingType;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.services.s3.model.ListObjectsV2Request;
import software.amazon.awssdk.transfer.s3.internal.model.DefaultFileDownload;
import software.amazon.awssdk.transfer.s3.internal.progress.DefaultTransferProgress;
import software.amazon.awssdk.transfer.s3.internal.progress.DefaultTransferProgressSnapshot;
import software.amazon.awssdk.transfer.s3.model.CompletedDirectoryDownload;
import software.amazon.awssdk.transfer.s3.model.CompletedFileDownload;
import software.amazon.awssdk.transfer.s3.model.DirectoryDownload;
import software.amazon.awssdk.transfer.s3.model.DownloadDirectoryRequest;
import software.amazon.awssdk.transfer.s3.model.DownloadFileRequest;
import software.amazon.awssdk.transfer.s3.model.FileDownload;
import software.amazon.awssdk.transfer.s3.progress.LoggingTransferListener;
import software.amazon.awssdk.transfer.s3.progress.TransferListener;
public class DownloadDirectoryHelperTest {
private static final String DIRECTORY_NAME = "test";
private FileSystem fs;
private Path directory;
private Function<DownloadFileRequest, FileDownload> singleDownloadFunction;
private DownloadDirectoryHelper downloadDirectoryHelper;
private ListObjectsHelper listObjectsHelper;
@BeforeEach
public void methodSetup() {
fs = Jimfs.newFileSystem();
directory = fs.getPath("test");
listObjectsHelper = mock(ListObjectsHelper.class);
singleDownloadFunction = mock(Function.class);
downloadDirectoryHelper = new DownloadDirectoryHelper(TransferManagerConfiguration.builder().build(),
listObjectsHelper,
singleDownloadFunction);
}
@AfterEach
public void methodCleanup() throws IOException {
fs.close();
}
public static Collection<FileSystem> fileSystems() {
return Sets.newHashSet(Arrays.asList(Jimfs.newFileSystem(Configuration.unix()),
Jimfs.newFileSystem(Configuration.osX()),
Jimfs.newFileSystem(Configuration.windows())));
}
@Test
void downloadDirectory_allDownloadsSucceed_failedDownloadsShouldBeEmpty() throws Exception {
stubSuccessfulListObjects(listObjectsHelper, "key1", "key2");
FileDownload fileDownload = newSuccessfulDownload();
FileDownload fileDownload2 = newSuccessfulDownload();
when(singleDownloadFunction.apply(any(DownloadFileRequest.class))).thenReturn(fileDownload, fileDownload2);
DirectoryDownload downloadDirectory =
downloadDirectoryHelper.downloadDirectory(DownloadDirectoryRequest.builder()
.destination(directory)
.bucket("bucket")
.build());
CompletedDirectoryDownload completedDirectoryDownload = downloadDirectory.completionFuture().get(5, TimeUnit.SECONDS);
ArgumentCaptor<DownloadFileRequest> argumentCaptor = ArgumentCaptor.forClass(DownloadFileRequest.class);
verify(singleDownloadFunction, times(2)).apply(argumentCaptor.capture());
assertThat(completedDirectoryDownload.failedTransfers()).isEmpty();
assertThat(argumentCaptor.getAllValues()).element(0).satisfies(d -> assertThat(d.getObjectRequest().key()).isEqualTo(
"key1"));
assertThat(argumentCaptor.getAllValues()).element(1).satisfies(d -> assertThat(d.getObjectRequest().key()).isEqualTo(
"key2"));
}
@ParameterizedTest
@ValueSource(strings = {"/blah",
"../blah/object.dat",
"blah/../../object.dat",
"blah/../object/../../blah/another/object.dat",
"../{directory-name}-2/object.dat"})
void invalidKey_shouldThrowException(String testingString) throws Exception {
assertExceptionThrownForInvalidKeys(testingString);
}
private void assertExceptionThrownForInvalidKeys(String key) throws IOException {
Path destinationDirectory = Files.createTempDirectory("test");
String lastElement = destinationDirectory.getName(destinationDirectory.getNameCount() - 1).toString();
key = key.replace("{directory-name}", lastElement);
stubSuccessfulListObjects(listObjectsHelper, key);
DirectoryDownload downloadDirectory =
downloadDirectoryHelper.downloadDirectory(DownloadDirectoryRequest.builder()
.destination(destinationDirectory)
.bucket("bucket")
.build());
assertThatThrownBy(() -> downloadDirectory.completionFuture().get(5, TimeUnit.SECONDS))
.hasCauseInstanceOf(SdkClientException.class).getRootCause().hasMessageContaining("Cannot download key");
}
@Test
void downloadDirectory_cancel_shouldCancelAllFutures() throws Exception {
stubSuccessfulListObjects(listObjectsHelper, "key1", "key2");
CompletableFuture<CompletedFileDownload> future = new CompletableFuture<>();
FileDownload fileDownload = newDownload(future);
CompletableFuture<CompletedFileDownload> future2 = new CompletableFuture<>();
FileDownload fileDownload2 = newDownload(future2);
when(singleDownloadFunction.apply(any(DownloadFileRequest.class))).thenReturn(fileDownload, fileDownload2);
DirectoryDownload downloadDirectory =
downloadDirectoryHelper.downloadDirectory(DownloadDirectoryRequest.builder()
.destination(directory)
.bucket("bucket")
.build());
downloadDirectory.completionFuture().cancel(true);
assertThatThrownBy(() -> future.get(1, TimeUnit.SECONDS))
.isInstanceOf(CancellationException.class);
assertThatThrownBy(() -> future2.get(1, TimeUnit.SECONDS))
.isInstanceOf(CancellationException.class);
}
@Test
void downloadDirectory_partialSuccess_shouldProvideFailedDownload() throws Exception {
stubSuccessfulListObjects(listObjectsHelper, "key1", "key2");
FileDownload fileDownload = newSuccessfulDownload();
SdkClientException exception = SdkClientException.create("failed");
FileDownload fileDownload2 = newFailedDownload(exception);
when(singleDownloadFunction.apply(any(DownloadFileRequest.class))).thenReturn(fileDownload, fileDownload2);
DirectoryDownload downloadDirectory =
downloadDirectoryHelper.downloadDirectory(DownloadDirectoryRequest.builder()
.destination(directory)
.bucket("bucket")
.build());
CompletedDirectoryDownload completedDirectoryDownload = downloadDirectory.completionFuture().get(5, TimeUnit.SECONDS);
assertThat(completedDirectoryDownload.failedTransfers()).hasSize(1)
.element(0).satisfies(failedFileDownload -> assertThat(failedFileDownload.exception()).isEqualTo(exception));
}
@Test
void downloadDirectory_withFilter_shouldHonorFilter() throws Exception {
stubSuccessfulListObjects(listObjectsHelper, "key1", "key2");
FileDownload fileDownload = newSuccessfulDownload();
FileDownload fileDownload2 = newSuccessfulDownload();
when(singleDownloadFunction.apply(any(DownloadFileRequest.class))).thenReturn(fileDownload, fileDownload2);
DirectoryDownload downloadDirectory =
downloadDirectoryHelper.downloadDirectory(DownloadDirectoryRequest.builder()
.destination(directory)
.bucket("bucket")
.filter(s3Object -> "key2".equals(s3Object.key()))
.build());
CompletedDirectoryDownload completedDirectoryDownload = downloadDirectory.completionFuture().get(5, TimeUnit.SECONDS);
ArgumentCaptor<DownloadFileRequest> argumentCaptor = ArgumentCaptor.forClass(DownloadFileRequest.class);
verify(singleDownloadFunction, times(1)).apply(argumentCaptor.capture());
assertThat(completedDirectoryDownload.failedTransfers()).isEmpty();
assertThat(argumentCaptor.getAllValues()).element(0).satisfies(d -> assertThat(d.getObjectRequest().key()).isEqualTo(
"key2"));
}
@Test
void downloadDirectory_withDownloadRequestTransformer_shouldTransform() throws Exception {
stubSuccessfulListObjects(listObjectsHelper, "key1", "key2");
FileDownload fileDownload = newSuccessfulDownload();
FileDownload fileDownload2 = newSuccessfulDownload();
when(singleDownloadFunction.apply(any(DownloadFileRequest.class))).thenReturn(fileDownload, fileDownload2);
Path newDestination = Paths.get("/new/path");
GetObjectRequest newGetObjectRequest = GetObjectRequest.builder().build();
List<TransferListener> newTransferListener = Arrays.asList(LoggingTransferListener.create());
DirectoryDownload downloadDirectory =
downloadDirectoryHelper.downloadDirectory(DownloadDirectoryRequest.builder()
.destination(directory)
.bucket("bucket")
.downloadFileRequestTransformer(d -> d.destination(newDestination)
.getObjectRequest(newGetObjectRequest)
.transferListeners(newTransferListener))
.build());
CompletedDirectoryDownload completedDirectoryDownload = downloadDirectory.completionFuture().get(5, TimeUnit.SECONDS);
ArgumentCaptor<DownloadFileRequest> argumentCaptor = ArgumentCaptor.forClass(DownloadFileRequest.class);
verify(singleDownloadFunction, times(2)).apply(argumentCaptor.capture());
assertThat(completedDirectoryDownload.failedTransfers()).isEmpty();
assertThat(argumentCaptor.getAllValues()).allSatisfy(d -> {
assertThat(d.getObjectRequest()).isEqualTo(newGetObjectRequest);
assertThat(d.transferListeners()).isEqualTo(newTransferListener);
assertThat(d.destination()).isEqualTo(newDestination);
});
}
@Test
void downloadDirectory_withListObjectsRequestTransformer_shouldTransform() throws Exception {
stubSuccessfulListObjects(listObjectsHelper, "key1", "key2");
FileDownload fileDownload = newSuccessfulDownload();
FileDownload fileDownload2 = newSuccessfulDownload();
EncodingType newEncodingType = EncodingType.URL;
int newMaxKeys = 10;
when(singleDownloadFunction.apply(any(DownloadFileRequest.class))).thenReturn(fileDownload, fileDownload2);
DirectoryDownload downloadDirectory =
downloadDirectoryHelper.downloadDirectory(DownloadDirectoryRequest.builder()
.destination(directory)
.bucket("bucket")
.listObjectsV2RequestTransformer(l -> l.encodingType(newEncodingType)
.maxKeys(newMaxKeys))
.build());
CompletedDirectoryDownload completedDirectoryDownload = downloadDirectory.completionFuture().get(5, TimeUnit.SECONDS);
ArgumentCaptor<ListObjectsV2Request> argumentCaptor = ArgumentCaptor.forClass(ListObjectsV2Request.class);
verify(listObjectsHelper, times(1)).listS3ObjectsRecursively(argumentCaptor.capture());
assertThat(completedDirectoryDownload.failedTransfers()).isEmpty();
assertThat(argumentCaptor.getValue()).satisfies(l -> {
assertThat(l.encodingType()).isEqualTo(newEncodingType);
assertThat(l.maxKeys()).isEqualTo(newMaxKeys);
});
}
@ParameterizedTest
@MethodSource("fileSystems")
void downloadDirectory_shouldRecursivelyDownload(FileSystem jimfs) {
directory = jimfs.getPath("test");
String[] keys = {"1.png", "2020/1.png", "2021/1.png", "2022/1.png", "2023/1/1.png"};
stubSuccessfulListObjects(listObjectsHelper, keys);
ArgumentCaptor<DownloadFileRequest> requestArgumentCaptor = ArgumentCaptor.forClass(DownloadFileRequest.class);
when(singleDownloadFunction.apply(requestArgumentCaptor.capture()))
.thenReturn(completedDownload());
DirectoryDownload downloadDirectory =
downloadDirectoryHelper.downloadDirectory(DownloadDirectoryRequest.builder()
.destination(directory)
.bucket("bucket")
.build());
CompletedDirectoryDownload completedDirectoryDownload = downloadDirectory.completionFuture().join();
assertThat(completedDirectoryDownload.failedTransfers()).isEmpty();
List<DownloadFileRequest> actualRequests = requestArgumentCaptor.getAllValues();
actualRequests.forEach(r -> assertThat(r.getObjectRequest().bucket()).isEqualTo("bucket"));
assertThat(actualRequests.size()).isEqualTo(keys.length);
verifyDestinationPathForSingleDownload(jimfs, "/", keys, actualRequests);
}
/**
* The S3 bucket has the following keys:
* abc/def/image.jpg
* abc/def/title.jpg
* abc/def/ghi/xyz.txt
*
* if the prefix is "abc/def/", the structure should like this:
* image.jpg
* title.jpg
* ghi
* - xyz.txt
*/
@ParameterizedTest
@MethodSource("fileSystems")
void downloadDirectory_withPrefix_shouldStripPrefixInDestinationPath(FileSystem jimfs) {
directory = jimfs.getPath("test");
String[] keys = {"abc/def/image.jpg", "abc/def/title.jpg", "abc/def/ghi/xyz.txt"};
stubSuccessfulListObjects(listObjectsHelper, keys);
ArgumentCaptor<DownloadFileRequest> requestArgumentCaptor = ArgumentCaptor.forClass(DownloadFileRequest.class);
when(singleDownloadFunction.apply(requestArgumentCaptor.capture()))
.thenReturn(completedDownload());
DirectoryDownload downloadDirectory =
downloadDirectoryHelper.downloadDirectory(DownloadDirectoryRequest.builder()
.destination(directory)
.bucket("bucket")
.listObjectsV2RequestTransformer(l -> l.prefix(
"abc/def/"))
.build());
CompletedDirectoryDownload completedDirectoryDownload = downloadDirectory.completionFuture().join();
assertThat(completedDirectoryDownload.failedTransfers()).isEmpty();
List<DownloadFileRequest> actualRequests = requestArgumentCaptor.getAllValues();
assertThat(actualRequests.size()).isEqualTo(keys.length);
List<String> destinations =
actualRequests.stream().map(u -> u.destination().toString())
.collect(Collectors.toList());
String jimfsSeparator = jimfs.getSeparator();
List<String> expectedPaths =
Arrays.asList("image.jpg", "title.jpg", "ghi/xyz.txt").stream()
.map(k -> DIRECTORY_NAME + jimfsSeparator + k.replace("/",jimfsSeparator)).collect(Collectors.toList());
assertThat(destinations).isEqualTo(expectedPaths);
}
@ParameterizedTest
@MethodSource("fileSystems")
void downloadDirectory_containsObjectWithPrefixInIt_shouldInclude(FileSystem jimfs) {
String prefix = "abc";
directory = jimfs.getPath("test");
String[] keys = {"abc/def/image.jpg", "abc/def/title.jpg", "abcd"};
stubSuccessfulListObjects(listObjectsHelper, keys);
ArgumentCaptor<DownloadFileRequest> requestArgumentCaptor = ArgumentCaptor.forClass(DownloadFileRequest.class);
when(singleDownloadFunction.apply(requestArgumentCaptor.capture()))
.thenReturn(completedDownload());
DirectoryDownload downloadDirectory =
downloadDirectoryHelper.downloadDirectory(DownloadDirectoryRequest.builder()
.destination(directory)
.bucket("bucket")
.listObjectsV2RequestTransformer(l -> l.prefix(prefix))
.build());
CompletedDirectoryDownload completedDirectoryDownload = downloadDirectory.completionFuture().join();
assertThat(completedDirectoryDownload.failedTransfers()).isEmpty();
List<DownloadFileRequest> actualRequests = requestArgumentCaptor.getAllValues();
assertThat(actualRequests.size()).isEqualTo(keys.length);
List<String> destinations =
actualRequests.stream().map(u -> u.destination().toString())
.collect(Collectors.toList());
String jimfsSeparator = jimfs.getSeparator();
List<String> expectedPaths =
Arrays.asList("def/image.jpg", "def/title.jpg", "abcd").stream()
.map(k -> DIRECTORY_NAME + jimfsSeparator + k.replace("/",jimfsSeparator)).collect(Collectors.toList());
assertThat(destinations).isEqualTo(expectedPaths);
}
@ParameterizedTest
@MethodSource("fileSystems")
void downloadDirectory_withDelimiter_shouldHonor(FileSystem jimfs) {
directory = jimfs.getPath("test");
String delimiter = "|";
String[] keys = {"1.png", "2020|1.png", "2021|1.png", "2022|1.png", "2023|1|1.png"};
stubSuccessfulListObjects(listObjectsHelper, keys);
ArgumentCaptor<DownloadFileRequest> requestArgumentCaptor = ArgumentCaptor.forClass(DownloadFileRequest.class);
when(singleDownloadFunction.apply(requestArgumentCaptor.capture())).thenReturn(completedDownload());
DirectoryDownload downloadDirectory =
downloadDirectoryHelper.downloadDirectory(DownloadDirectoryRequest.builder()
.destination(directory)
.bucket("bucket")
.listObjectsV2RequestTransformer(r -> r.delimiter(delimiter))
.build());
CompletedDirectoryDownload completedDirectoryDownload = downloadDirectory.completionFuture().join();
assertThat(completedDirectoryDownload.failedTransfers()).isEmpty();
List<DownloadFileRequest> actualRequests = requestArgumentCaptor.getAllValues();
actualRequests.forEach(r -> assertThat(r.getObjectRequest().bucket()).isEqualTo("bucket"));
assertThat(actualRequests.size()).isEqualTo(keys.length);
verifyDestinationPathForSingleDownload(jimfs, delimiter, keys, actualRequests);
}
@ParameterizedTest
@MethodSource("fileSystems")
void downloadDirectory_notDirectory_shouldCompleteFutureExceptionally(FileSystem jimfs) throws IOException {
directory = jimfs.getPath("test");
Path file = jimfs.getPath("afile" + UUID.randomUUID());
Files.write(file, "hellowrold".getBytes(StandardCharsets.UTF_8));
assertThatThrownBy(() -> downloadDirectoryHelper.downloadDirectory(DownloadDirectoryRequest.builder().destination(file)
.bucket("bucketName").build()).completionFuture().join())
.hasMessageContaining("is not a directory").hasCauseInstanceOf(IllegalArgumentException.class);
}
private static DefaultFileDownload completedDownload() {
return new DefaultFileDownload(CompletableFuture.completedFuture(CompletedFileDownload.builder()
.response(GetObjectResponse.builder().build())
.build()),
new DefaultTransferProgress(DefaultTransferProgressSnapshot.builder()
.transferredBytes(0L)
.build()),
() -> DownloadFileRequest.builder().getObjectRequest(GetObjectRequest.builder().build())
.destination(Paths.get("."))
.build(),
null);
}
private static void verifyDestinationPathForSingleDownload(FileSystem jimfs, String delimiter, String[] keys,
List<DownloadFileRequest> actualRequests) {
String jimfsSeparator = jimfs.getSeparator();
List<String> destinations =
actualRequests.stream().map(u -> u.destination().toString())
.collect(Collectors.toList());
List<String> expectedPaths =
Arrays.stream(keys).map(k -> DIRECTORY_NAME + jimfsSeparator + k.replace(delimiter, jimfsSeparator)).collect(Collectors.toList());
assertThat(destinations).isEqualTo(expectedPaths);
}
private FileDownload newSuccessfulDownload() {
GetObjectResponse getObjectResponse = GetObjectResponse.builder().eTag(UUID.randomUUID().toString()).build();
CompletedFileDownload completedFileDownload = CompletedFileDownload.builder().response(getObjectResponse).build();
CompletableFuture<CompletedFileDownload> successfulFuture = new CompletableFuture<>();
FileDownload fileDownload = newDownload(successfulFuture);
successfulFuture.complete(completedFileDownload);
return fileDownload;
}
private FileDownload newFailedDownload(SdkClientException exception) {
CompletableFuture<CompletedFileDownload> failedFuture = new CompletableFuture<>();
FileDownload fileDownload2 = newDownload(failedFuture);
failedFuture.completeExceptionally(exception);
return fileDownload2;
}
private FileDownload newDownload(CompletableFuture<CompletedFileDownload> future) {
return new DefaultFileDownload(future,
new DefaultTransferProgress(DefaultTransferProgressSnapshot.builder()
.transferredBytes(0L)
.build()),
() -> DownloadFileRequest.builder().destination(Paths.get(
".")).getObjectRequest(GetObjectRequest.builder().build()).build(),
null);
}
}
| 3,718 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal/serialization/ResumableFileDownloadSerializerTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.serialization;
import static org.assertj.core.api.Assertions.assertThat;
import static software.amazon.awssdk.utils.DateUtils.parseIso8601Date;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.time.Instant;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration;
import software.amazon.awssdk.services.s3.model.ChecksumMode;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.RequestPayer;
import software.amazon.awssdk.testutils.RandomTempFile;
import software.amazon.awssdk.transfer.s3.model.DownloadFileRequest;
import software.amazon.awssdk.transfer.s3.model.ResumableFileDownload;
import software.amazon.awssdk.transfer.s3.progress.LoggingTransferListener;
class ResumableFileDownloadSerializerTest {
private static final Path PATH = RandomTempFile.randomUncreatedFile().toPath();
private static final Instant DATE1 = parseIso8601Date("2022-05-13T21:55:52.529Z");
private static final Instant DATE2 = parseIso8601Date("2022-05-15T21:50:11.308Z");
private static final Map<String, GetObjectRequest> GET_OBJECT_REQUESTS;
static {
Map<String, GetObjectRequest> requests = new HashMap<>();
requests.put("EMPTY", GetObjectRequest.builder().build());
requests.put("STANDARD", GetObjectRequest.builder().bucket("BUCKET").key("KEY").build());
requests.put("ALL_TYPES", GetObjectRequest.builder()
.bucket("BUCKET")
.key("KEY")
.partNumber(1)
.ifModifiedSince(parseIso8601Date("2020-01-01T12:10:30Z"))
.checksumMode(ChecksumMode.ENABLED)
.requestPayer(RequestPayer.REQUESTER)
.build());
GET_OBJECT_REQUESTS = Collections.unmodifiableMap(requests);
}
@ParameterizedTest
@MethodSource("downloadObjects")
void serializeDeserialize_ShouldWorkForAllDownloads(ResumableFileDownload download) {
byte[] serializedDownload = ResumableFileDownloadSerializer.toJson(download);
ResumableFileDownload deserializedDownload = ResumableFileDownloadSerializer.fromJson(serializedDownload);
assertThat(deserializedDownload).isEqualTo(download);
}
@Test
void serializeDeserialize_fromStoredString_ShouldWork() {
ResumableFileDownload download =
ResumableFileDownload.builder()
.downloadFileRequest(d -> d.destination(Paths.get("test/request"))
.getObjectRequest(GET_OBJECT_REQUESTS.get("ALL_TYPES")))
.bytesTransferred(1000L)
.fileLastModified(parseIso8601Date("2022-03-08T10:15:30Z"))
.totalSizeInBytes(5000L)
.s3ObjectLastModified(parseIso8601Date("2022-03-10T08:21:00Z"))
.build();
byte[] serializedDownload = ResumableFileDownloadSerializer.toJson(download);
assertThat(new String(serializedDownload, StandardCharsets.UTF_8)).isEqualTo(SERIALIZED_DOWNLOAD_OBJECT);
ResumableFileDownload deserializedDownload =
ResumableFileDownloadSerializer.fromJson(SERIALIZED_DOWNLOAD_OBJECT.getBytes(StandardCharsets.UTF_8));
assertThat(deserializedDownload).isEqualTo(download);
}
@Test
void serializeDeserialize_DoesNotPersistConfiguration() {
ResumableFileDownload download =
ResumableFileDownload.builder()
.downloadFileRequest(d -> d.destination(PATH)
.getObjectRequest(GET_OBJECT_REQUESTS.get("STANDARD"))
.addTransferListener(LoggingTransferListener.create()))
.bytesTransferred(1000L)
.build();
byte[] serializedDownload = ResumableFileDownloadSerializer.toJson(download);
ResumableFileDownload deserializedDownload = ResumableFileDownloadSerializer.fromJson(serializedDownload);
DownloadFileRequest fileRequestWithoutConfig =
download.downloadFileRequest().copy(r -> r.transferListeners((List) null));
assertThat(deserializedDownload).isEqualTo(download.copy(d -> d.downloadFileRequest(fileRequestWithoutConfig)));
}
@Test
void serializeDeserialize_DoesNotPersistRequestOverrideConfiguration() {
GetObjectRequest requestWithOverride =
GetObjectRequest.builder()
.bucket("BUCKET")
.key("KEY")
.overrideConfiguration(c -> c.apiCallAttemptTimeout(Duration.ofMillis(20)).build())
.build();
DownloadFileRequest downloadFileRequest = DownloadFileRequest.builder()
.destination(PATH)
.getObjectRequest(requestWithOverride)
.build();
ResumableFileDownload download = ResumableFileDownload.builder()
.downloadFileRequest(downloadFileRequest)
.build();
byte[] serializedDownload = ResumableFileDownloadSerializer.toJson(download);
ResumableFileDownload deserializedDownload = ResumableFileDownloadSerializer.fromJson(serializedDownload);
GetObjectRequest requestWithoutOverride =
requestWithOverride.copy(r -> r.overrideConfiguration((AwsRequestOverrideConfiguration) null));
DownloadFileRequest fileRequestCopy = downloadFileRequest.copy(r -> r.getObjectRequest(requestWithoutOverride));
assertThat(deserializedDownload).isEqualTo(download.copy(d -> d.downloadFileRequest(fileRequestCopy)));
}
public static Collection<ResumableFileDownload> downloadObjects() {
return Stream.of(differentDownloadSettings(),
differentGetObjects())
.flatMap(Collection::stream).collect(Collectors.toList());
}
private static List<ResumableFileDownload> differentGetObjects() {
return GET_OBJECT_REQUESTS.values()
.stream()
.map(request -> resumableFileDownload(1000L, null, DATE1, null, downloadRequest(PATH, request)))
.collect(Collectors.toList());
}
private static List<ResumableFileDownload> differentDownloadSettings() {
DownloadFileRequest request = downloadRequest(PATH, GET_OBJECT_REQUESTS.get("STANDARD"));
return Arrays.asList(
resumableFileDownload(null, null, null, null, request),
resumableFileDownload(1000L, null, null, null, request),
resumableFileDownload(1000L, null, DATE1, null, request),
resumableFileDownload(1000L, 2000L, DATE1, DATE2, request),
resumableFileDownload(Long.MAX_VALUE, Long.MAX_VALUE, DATE1, DATE2, request)
);
}
private static ResumableFileDownload resumableFileDownload(Long bytesTransferred,
Long totalSizeInBytes,
Instant fileLastModified,
Instant s3ObjectLastModified,
DownloadFileRequest request) {
ResumableFileDownload.Builder builder = ResumableFileDownload.builder()
.downloadFileRequest(request)
.bytesTransferred(bytesTransferred);
if (totalSizeInBytes != null) {
builder.totalSizeInBytes(totalSizeInBytes);
}
if (fileLastModified != null) {
builder.fileLastModified(fileLastModified);
}
if (s3ObjectLastModified != null) {
builder.s3ObjectLastModified(s3ObjectLastModified);
}
return builder.build();
}
private static DownloadFileRequest downloadRequest(Path path, GetObjectRequest request) {
return DownloadFileRequest.builder()
.getObjectRequest(request)
.destination(path)
.build();
}
private static final String SERIALIZED_DOWNLOAD_OBJECT = "{\"bytesTransferred\":1000,\"fileLastModified\":1646734530.000,"
+ "\"totalSizeInBytes\":5000,\"s3ObjectLastModified\":1646900460"
+ ".000,\"downloadFileRequest\":{\"destination\":\"test/request\","
+ "\"getObjectRequest\":{\"Bucket\":\"BUCKET\","
+ "\"If-Modified-Since\":1577880630.000,\"Key\":\"KEY\","
+ "\"x-amz-request-payer\":\"requester\",\"partNumber\":1,"
+ "\"x-amz-checksum-mode\":\"ENABLED\"}}}";
}
| 3,719 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal/serialization/TransferManagerMarshallerUtilsTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.serialization;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Arrays;
import java.util.Collections;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.core.document.Document;
import software.amazon.awssdk.core.protocol.MarshallingType;
class TransferManagerMarshallerUtilsTest {
@ParameterizedTest
@MethodSource("marshallingValues")
void getMarshallerByType(Object o, MarshallingType<Object> type, TransferManagerJsonMarshaller<?> expectedMarshaller) {
TransferManagerJsonMarshaller<Object> marshaller = TransferManagerMarshallingUtils.getMarshaller(type, o);
assertThat(marshaller).isNotNull()
.isEqualTo(expectedMarshaller);
}
@ParameterizedTest
@MethodSource("marshallingValues")
void findMarshallerByValue(Object o, MarshallingType<Object> type, TransferManagerJsonMarshaller<?> expectedMarshaller) {
TransferManagerJsonMarshaller<Object> marshaller = TransferManagerMarshallingUtils.getMarshaller(o);
assertThat(marshaller).isEqualTo(expectedMarshaller);
}
@ParameterizedTest
@MethodSource("unmarshallingValues")
void getUnmarshaller(MarshallingType<Object> type, TransferManagerJsonUnmarshaller<?> expectedUnmarshaller) {
TransferManagerJsonUnmarshaller<Object> marshaller = (TransferManagerJsonUnmarshaller<Object>) TransferManagerMarshallingUtils.getUnmarshaller(type);
assertThat(marshaller).isEqualTo(expectedUnmarshaller);
}
@Test
void whenNoMarshaller_shouldThrowException() {
assertThatThrownBy(() -> TransferManagerMarshallingUtils.getMarshaller(MarshallingType.DOCUMENT, Document.fromNull()))
.isInstanceOf(IllegalStateException.class).hasMessageContaining("Cannot find a marshaller");
}
@Test
void whenNoUnmarshaller_shouldThrowException() {
assertThatThrownBy(() -> TransferManagerMarshallingUtils.getUnmarshaller(MarshallingType.DOCUMENT))
.isInstanceOf(IllegalStateException.class).hasMessageContaining("Cannot find an unmarshaller");
}
private static Stream<Arguments> marshallingValues() {
return Stream.of(Arguments.of("String", MarshallingType.STRING, TransferManagerJsonMarshaller.STRING),
Arguments.of((short) 10, MarshallingType.SHORT, TransferManagerJsonMarshaller.SHORT),
Arguments.of(100, MarshallingType.INTEGER, TransferManagerJsonMarshaller.INTEGER),
Arguments.of(100L, MarshallingType.LONG, TransferManagerJsonMarshaller.LONG),
Arguments.of(Instant.now(), MarshallingType.INSTANT, TransferManagerJsonMarshaller.INSTANT),
Arguments.of(null, MarshallingType.NULL, TransferManagerJsonMarshaller.NULL),
Arguments.of(12.34f, MarshallingType.FLOAT, TransferManagerJsonMarshaller.FLOAT),
Arguments.of(12.34d, MarshallingType.DOUBLE, TransferManagerJsonMarshaller.DOUBLE),
Arguments.of(new BigDecimal(34), MarshallingType.BIG_DECIMAL, TransferManagerJsonMarshaller.BIG_DECIMAL),
Arguments.of(true, MarshallingType.BOOLEAN, TransferManagerJsonMarshaller.BOOLEAN),
Arguments.of(SdkBytes.fromString("String", StandardCharsets.UTF_8),
MarshallingType.SDK_BYTES, TransferManagerJsonMarshaller.SDK_BYTES),
Arguments.of(Arrays.asList(100, 45), MarshallingType.LIST, TransferManagerJsonMarshaller.LIST),
Arguments.of(Collections.singletonMap("key", "value"), MarshallingType.MAP,
TransferManagerJsonMarshaller.MAP)
);
}
private static Stream<Arguments> unmarshallingValues() {
return Stream.of(Arguments.of(MarshallingType.STRING, TransferManagerJsonUnmarshaller.STRING),
Arguments.of(MarshallingType.SHORT, TransferManagerJsonUnmarshaller.SHORT),
Arguments.of(MarshallingType.INTEGER, TransferManagerJsonUnmarshaller.INTEGER),
Arguments.of(MarshallingType.LONG, TransferManagerJsonUnmarshaller.LONG),
Arguments.of(MarshallingType.INSTANT, TransferManagerJsonUnmarshaller.INSTANT),
Arguments.of(MarshallingType.NULL, TransferManagerJsonUnmarshaller.NULL),
Arguments.of(MarshallingType.FLOAT, TransferManagerJsonUnmarshaller.FLOAT),
Arguments.of(MarshallingType.DOUBLE, TransferManagerJsonUnmarshaller.DOUBLE),
Arguments.of(MarshallingType.BIG_DECIMAL, TransferManagerJsonUnmarshaller.BIG_DECIMAL),
Arguments.of(MarshallingType.BOOLEAN, TransferManagerJsonUnmarshaller.BOOLEAN),
Arguments.of(MarshallingType.SDK_BYTES, TransferManagerJsonUnmarshaller.SDK_BYTES)
);
}
}
| 3,720 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal/serialization/ResumableFileUploadSerializerTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.serialization;
import static org.assertj.core.api.Assertions.assertThat;
import static software.amazon.awssdk.utils.DateUtils.parseIso8601Date;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.time.Instant;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration;
import software.amazon.awssdk.services.s3.model.ChecksumAlgorithm;
import software.amazon.awssdk.services.s3.model.ObjectCannedACL;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.RequestPayer;
import software.amazon.awssdk.testutils.RandomTempFile;
import software.amazon.awssdk.transfer.s3.model.UploadFileRequest;
import software.amazon.awssdk.transfer.s3.model.ResumableFileUpload;
import software.amazon.awssdk.transfer.s3.progress.LoggingTransferListener;
class ResumableFileUploadSerializerTest {
private static final Instant DATE = parseIso8601Date("2022-05-15T21:50:11.308Z");
private static final Path PATH = RandomTempFile.randomUncreatedFile().toPath();
private static final Map<String, PutObjectRequest> PUT_OBJECT_REQUESTS;
static {
Map<String, PutObjectRequest> requests = new HashMap<>();
requests.put("EMPTY", PutObjectRequest.builder().build());
requests.put("STANDARD", PutObjectRequest.builder().bucket("BUCKET").key("KEY").build());
Map<String, String> metadata = new HashMap<>();
metadata.put("foo", "bar");
requests.put("ALL_TYPES", PutObjectRequest.builder()
.bucket("BUCKET")
.key("KEY")
.acl(ObjectCannedACL.PRIVATE)
.checksumAlgorithm(ChecksumAlgorithm.CRC32)
.requestPayer(RequestPayer.REQUESTER)
.metadata(metadata)
.build());
PUT_OBJECT_REQUESTS = Collections.unmodifiableMap(requests);
}
@ParameterizedTest
@MethodSource("uploadObjects")
void serializeDeserialize_ShouldWorkForAllUploads(ResumableFileUpload upload) {
byte[] serializedUpload = ResumableFileUploadSerializer.toJson(upload);
ResumableFileUpload deserializedUpload = ResumableFileUploadSerializer.fromJson(serializedUpload);
assertThat(deserializedUpload).isEqualTo(upload);
}
@Test
void serializeDeserialize_fromStoredString_ShouldWork() {
ResumableFileUpload upload =
ResumableFileUpload.builder()
.uploadFileRequest(d -> d.source(Paths.get("test/request"))
.putObjectRequest(PUT_OBJECT_REQUESTS.get("ALL_TYPES")))
.fileLength(5000L)
.fileLastModified(parseIso8601Date("2022-03-08T10:15:30Z"))
.multipartUploadId("id")
.totalParts(40L)
.partSizeInBytes(1024L)
.build();
byte[] serializedUpload = ResumableFileUploadSerializer.toJson(upload);
assertThat(new String(serializedUpload, StandardCharsets.UTF_8)).isEqualTo(SERIALIZED_UPLOAD_OBJECT);
ResumableFileUpload deserializedUpload =
ResumableFileUploadSerializer.fromJson(SERIALIZED_UPLOAD_OBJECT.getBytes(StandardCharsets.UTF_8));
assertThat(deserializedUpload).isEqualTo(upload);
}
@Test
void serializeDeserialize_DoesNotPersistConfiguration() {
ResumableFileUpload upload =
ResumableFileUpload.builder()
.uploadFileRequest(d -> d.source(PATH)
.putObjectRequest(PUT_OBJECT_REQUESTS.get("STANDARD"))
.addTransferListener(LoggingTransferListener.create()))
.fileLength(5000L)
.fileLastModified(parseIso8601Date("2022-03-08T10:15:30Z"))
.build();
byte[] serializedUpload = ResumableFileUploadSerializer.toJson(upload);
ResumableFileUpload deserializedUpload = ResumableFileUploadSerializer.fromJson(serializedUpload);
UploadFileRequest fileRequestWithoutConfig =
upload.uploadFileRequest().copy(r -> r.transferListeners((List) null));
assertThat(deserializedUpload).isEqualTo(upload.copy(d -> d.uploadFileRequest(fileRequestWithoutConfig)));
}
@Test
void serializeDeserialize_DoesNotPersistRequestOverrideConfiguration() {
PutObjectRequest requestWithOverride =
PutObjectRequest.builder()
.bucket("BUCKET")
.key("KEY")
.overrideConfiguration(c -> c.apiCallAttemptTimeout(Duration.ofMillis(20)).build())
.build();
UploadFileRequest uploadFileRequest = UploadFileRequest.builder()
.source(PATH)
.putObjectRequest(requestWithOverride)
.build();
ResumableFileUpload upload = ResumableFileUpload.builder()
.uploadFileRequest(uploadFileRequest)
.fileLastModified(DATE)
.fileLength(1000L)
.build();
byte[] serializedUpload = ResumableFileUploadSerializer.toJson(upload);
ResumableFileUpload deserializedUpload = ResumableFileUploadSerializer.fromJson(serializedUpload);
PutObjectRequest requestWithoutOverride =
requestWithOverride.copy(r -> r.overrideConfiguration((AwsRequestOverrideConfiguration) null));
UploadFileRequest fileRequestCopy = uploadFileRequest.copy(r -> r.putObjectRequest(requestWithoutOverride));
assertThat(deserializedUpload).isEqualTo(upload.copy(d -> d.uploadFileRequest(fileRequestCopy)));
}
public static Collection<ResumableFileUpload> uploadObjects() {
return Stream.of(differentUploadSettings(),
differentPutObjects())
.flatMap(Collection::stream).collect(Collectors.toList());
}
private static List<ResumableFileUpload> differentPutObjects() {
return PUT_OBJECT_REQUESTS.values()
.stream()
.map(request -> resumableFileUpload(1000L, null, null, null))
.collect(Collectors.toList());
}
private static List<ResumableFileUpload> differentUploadSettings() {
return Arrays.asList(
resumableFileUpload(null, null, null, null),
resumableFileUpload(1000L, null, null, null),
resumableFileUpload(1000L, 5L, 1L, null),
resumableFileUpload(1000L, 5L, 2L, "1234")
);
}
private static ResumableFileUpload resumableFileUpload(Long partSizeInBytes,
Long totalNumberOfParts,
Long transferredParts,
String multipartUploadId) {
UploadFileRequest request = downloadRequest(PATH, PUT_OBJECT_REQUESTS.get("STANDARD"));
return ResumableFileUpload.builder()
.uploadFileRequest(request)
.fileLength(1000L)
.multipartUploadId(multipartUploadId)
.fileLastModified(DATE)
.partSizeInBytes(partSizeInBytes)
.totalParts(totalNumberOfParts)
.transferredParts(transferredParts)
.build();
}
private static UploadFileRequest downloadRequest(Path path, PutObjectRequest request) {
return UploadFileRequest.builder()
.putObjectRequest(request)
.source(path)
.build();
}
private static final String SERIALIZED_UPLOAD_OBJECT = "{\"fileLength\":5000,\"fileLastModified\":1646734530.000,"
+ "\"multipartUploadId\":\"id\",\"partSizeInBytes\":1024,"
+ "\"totalParts\":40,\"uploadFileRequest\":{\"source\":\"test"
+ "/request\",\"putObjectRequest\":{\"x-amz-acl\":\"private\","
+ "\"Bucket\":\"BUCKET\",\"x-amz-sdk-checksum-algorithm\":\"CRC32\","
+ "\"Key\":\"KEY\",\"x-amz-meta-\":{\"foo\":\"bar\"},"
+ "\"x-amz-request-payer\":\"requester\"}}}";
}
| 3,721 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal/serialization/TransferManagerJsonUnmarshallerTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.serialization;
import static org.assertj.core.api.Assertions.assertThat;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.protocols.jsoncore.JsonNode;
import software.amazon.awssdk.protocols.jsoncore.internal.NullJsonNode;
import software.amazon.awssdk.protocols.jsoncore.internal.NumberJsonNode;
import software.amazon.awssdk.protocols.jsoncore.internal.StringJsonNode;
import software.amazon.awssdk.utils.BinaryUtils;
import software.amazon.awssdk.utils.DateUtils;
class TransferManagerJsonUnmarshallerTest {
@ParameterizedTest
@MethodSource("unmarshallingValues")
void deserialize_ShouldWorkForAllSupportedTypes(JsonNode node, Object o, TransferManagerJsonUnmarshaller<?> unmarshaller) {
Object param = unmarshaller.unmarshall(node);
assertThat(param).isEqualTo(o);
}
private static Stream<Arguments> unmarshallingValues() {
return Stream.of(Arguments.of(new StringJsonNode("String"), "String", TransferManagerJsonUnmarshaller.STRING),
Arguments.of(new NumberJsonNode("100"), (short) 100, TransferManagerJsonUnmarshaller.SHORT),
Arguments.of(new NumberJsonNode("100"), 100, TransferManagerJsonUnmarshaller.INTEGER),
Arguments.of(new NumberJsonNode("100"), 100L, TransferManagerJsonUnmarshaller.LONG),
Arguments.of(new NumberJsonNode("12.34"), 12.34f, TransferManagerJsonUnmarshaller.FLOAT),
Arguments.of(new NumberJsonNode("12.34"), 12.34d, TransferManagerJsonUnmarshaller.DOUBLE),
Arguments.of(new NumberJsonNode("2.3"),
new BigDecimal("2.3"),
TransferManagerJsonUnmarshaller.BIG_DECIMAL),
Arguments.of(new NumberJsonNode("1646734530.000"),
DateUtils.parseIso8601Date("2022-03-08T10:15:30Z"),
TransferManagerJsonUnmarshaller.INSTANT),
Arguments.of(NullJsonNode.instance(), null, TransferManagerJsonUnmarshaller.NULL),
Arguments.of(new StringJsonNode(BinaryUtils.toBase64(SdkBytes.fromString("100", StandardCharsets.UTF_8)
.asByteArray())),
SdkBytes.fromString("100", StandardCharsets.UTF_8),
TransferManagerJsonUnmarshaller.SDK_BYTES)
);
}
}
| 3,722 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/internal/serialization/TransferManagerJsonMarshallerTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.serialization;
import static org.assertj.core.api.Assertions.assertThat;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.protocols.jsoncore.JsonWriter;
import software.amazon.awssdk.utils.DateUtils;
class TransferManagerJsonMarshallerTest {
@ParameterizedTest
@MethodSource("marshallingValues")
void serialize_ShouldWorkForAllSupportedTypes(Object o, TransferManagerJsonMarshaller<Object> marshaller, String expected) {
JsonWriter writer = JsonWriter.create();
writer.writeStartObject();
marshaller.marshall(o, writer, "param");
writer.writeEndObject();
String serializedResult = new String(writer.getBytes(), StandardCharsets.UTF_8);
assertThat(serializedResult).contains(expected);
}
private static Stream<Arguments> marshallingValues() {
return Stream.of(Arguments.of("String", TransferManagerJsonMarshaller.STRING, "String"),
Arguments.of((short) 10, TransferManagerJsonMarshaller.SHORT, Short.toString((short) 10)),
Arguments.of(100, TransferManagerJsonMarshaller.INTEGER, Integer.toString(100)),
Arguments.of(100L, TransferManagerJsonMarshaller.LONG, Long.toString(100L)),
Arguments.of(DateUtils.parseIso8601Date("2022-03-08T10:15:30Z"), TransferManagerJsonMarshaller.INSTANT,
"1646734530.000"),
Arguments.of(null, TransferManagerJsonMarshaller.NULL, "{}"),
Arguments.of(12.34f, TransferManagerJsonMarshaller.FLOAT, Float.toString(12.34f)),
Arguments.of(12.34d, TransferManagerJsonMarshaller.DOUBLE, Double.toString(12.34d)),
Arguments.of(new BigDecimal(34), TransferManagerJsonMarshaller.BIG_DECIMAL, (new BigDecimal(34)).toString()),
Arguments.of(true, TransferManagerJsonMarshaller.BOOLEAN, "true"),
Arguments.of(SdkBytes.fromString("String", StandardCharsets.UTF_8),
TransferManagerJsonMarshaller.SDK_BYTES, "U3RyaW5n"),
Arguments.of(Arrays.asList(100, 45), TransferManagerJsonMarshaller.LIST, "[100,45]"),
Arguments.of(Arrays.asList("100", "45"), TransferManagerJsonMarshaller.LIST, "[\"100\",\"45\"]"),
Arguments.of(Collections.singletonMap("key", "value"), TransferManagerJsonMarshaller.MAP,
"{\"key\":\"value\"}"),
Arguments.of(new HashMap<String, Long>() {{
put("key1", 100L);
put("key2", 200L);
}}, TransferManagerJsonMarshaller.MAP, "{\"key1\":100,\"key2\":200}")
);
}
private static String serializedValue(String paramValue) {
return String.format("{\"param\":%s}", paramValue);
}
}
| 3,723 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/samples/S3TransferManagerSamples.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.samples;
import static software.amazon.awssdk.transfer.s3.SizeConstant.MB;
import java.nio.file.Path;
import java.nio.file.Paths;
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.core.ResponseBytes;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.core.async.AsyncResponseTransformer;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.model.CopyObjectRequest;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.transfer.s3.model.CompletedCopy;
import software.amazon.awssdk.transfer.s3.model.CompletedDirectoryDownload;
import software.amazon.awssdk.transfer.s3.model.CompletedDirectoryUpload;
import software.amazon.awssdk.transfer.s3.model.Copy;
import software.amazon.awssdk.transfer.s3.model.CopyRequest;
import software.amazon.awssdk.transfer.s3.model.DirectoryDownload;
import software.amazon.awssdk.transfer.s3.model.DirectoryUpload;
import software.amazon.awssdk.transfer.s3.model.Download;
import software.amazon.awssdk.transfer.s3.model.DownloadDirectoryRequest;
import software.amazon.awssdk.transfer.s3.model.DownloadFileRequest;
import software.amazon.awssdk.transfer.s3.model.DownloadRequest;
import software.amazon.awssdk.transfer.s3.model.FileDownload;
import software.amazon.awssdk.transfer.s3.model.FileUpload;
import software.amazon.awssdk.transfer.s3.model.ResumableFileDownload;
import software.amazon.awssdk.transfer.s3.model.ResumableFileUpload;
import software.amazon.awssdk.transfer.s3.model.Upload;
import software.amazon.awssdk.transfer.s3.model.UploadDirectoryRequest;
import software.amazon.awssdk.transfer.s3.model.UploadFileRequest;
import software.amazon.awssdk.transfer.s3.model.UploadRequest;
import software.amazon.awssdk.transfer.s3.progress.LoggingTransferListener;
/**
* Contains code snippets that will be used in the Javadocs of {@link S3TransferManager}
*/
public class S3TransferManagerSamples {
public void defaultClient() {
// @start region=defaultTM
S3TransferManager transferManager = S3TransferManager.create();
// @end region=defaultTM
}
public void customClient() {
// @start region=customTM
S3AsyncClient s3AsyncClient = S3AsyncClient.crtBuilder()
.credentialsProvider(DefaultCredentialsProvider.create())
.region(Region.US_WEST_2)
.targetThroughputInGbps(20.0)
.minimumPartSizeInBytes(8 * MB)
.build();
S3TransferManager transferManager =
S3TransferManager.builder()
.s3Client(s3AsyncClient)
.build();
// @end region=customTM
}
public void downloadFile() {
// @start region=downloadFile
S3TransferManager transferManager = S3TransferManager.create();
DownloadFileRequest downloadFileRequest = DownloadFileRequest.builder()
.getObjectRequest(req -> req.bucket("bucket").key("key"))
.destination(Paths.get("myFile.txt"))
.addTransferListener(LoggingTransferListener.create())
.build();
FileDownload download = transferManager.downloadFile(downloadFileRequest);
// Wait for the transfer to complete
download.completionFuture().join();
// @end region=downloadFile
}
public void download() {
// @start region=download
S3TransferManager transferManager = S3TransferManager.create();
DownloadRequest<ResponseBytes<GetObjectResponse>> downloadRequest =
DownloadRequest.builder()
.getObjectRequest(req -> req.bucket("bucket").key("key"))
.responseTransformer(AsyncResponseTransformer.toBytes())
.build();
// Initiate the transfer
Download<ResponseBytes<GetObjectResponse>> download =
transferManager.download(downloadRequest);
// Wait for the transfer to complete
download.completionFuture().join();
// @end region=download
}
public void resumeDownloadFile() {
// @start region=resumeDownloadFile
S3TransferManager transferManager = S3TransferManager.create();
DownloadFileRequest downloadFileRequest = DownloadFileRequest.builder()
.getObjectRequest(req -> req.bucket("bucket").key("key"))
.destination(Paths.get("myFile.txt"))
.build();
// Initiate the transfer
FileDownload download =
transferManager.downloadFile(downloadFileRequest);
// Pause the download
ResumableFileDownload resumableFileDownload = download.pause(); // @link substring="pause" target="software.amazon.awssdk.transfer.s3.model.FileDownload#pause()"
// Optionally, persist the download object
Path path = Paths.get("resumableFileDownload.json");
resumableFileDownload.serializeToFile(path);
// Retrieve the resumableFileDownload from the file
resumableFileDownload = ResumableFileDownload.fromFile(path);
// Resume the download
FileDownload resumedDownload = transferManager.resumeDownloadFile(resumableFileDownload);
// Wait for the transfer to complete
resumedDownload.completionFuture().join();
// @end region=resumeDownloadFile
}
public void resumeUploadFile() {
// @start region=resumeUploadFile
S3TransferManager transferManager = S3TransferManager.create();
UploadFileRequest uploadFileRequest = UploadFileRequest.builder()
.putObjectRequest(req -> req.bucket("bucket").key("key"))
.source(Paths.get("myFile.txt"))
.build();
// Initiate the transfer
FileUpload upload =
transferManager.uploadFile(uploadFileRequest);
// Pause the upload
ResumableFileUpload resumableFileUpload = upload.pause();
// Optionally, persist the resumableFileUpload
Path path = Paths.get("resumableFileUpload.json");
resumableFileUpload.serializeToFile(path);
// Retrieve the resumableFileUpload from the file
ResumableFileUpload persistedResumableFileUpload = ResumableFileUpload.fromFile(path);
// Resume the upload
FileUpload resumedUpload = transferManager.resumeUploadFile(persistedResumableFileUpload);
// Wait for the transfer to complete
resumedUpload.completionFuture().join();
// @end region=resumeUploadFile
}
public void uploadFile() {
// @start region=uploadFile
S3TransferManager transferManager = S3TransferManager.create();
UploadFileRequest uploadFileRequest = UploadFileRequest.builder()
.putObjectRequest(req -> req.bucket("bucket").key("key"))
.addTransferListener(LoggingTransferListener.create())
.source(Paths.get("myFile.txt"))
.build();
FileUpload upload = transferManager.uploadFile(uploadFileRequest);
upload.completionFuture().join();
// @end region=uploadFile
}
public void upload() {
// @start region=upload
S3TransferManager transferManager = S3TransferManager.create();
UploadRequest uploadRequest = UploadRequest.builder()
.requestBody(AsyncRequestBody.fromString("Hello world"))
.putObjectRequest(req -> req.bucket("bucket").key("key"))
.build();
Upload upload = transferManager.upload(uploadRequest);
// Wait for the transfer to complete
upload.completionFuture().join();
// @end region=upload
}
public void uploadDirectory() {
// @start region=uploadDirectory
S3TransferManager transferManager = S3TransferManager.create();
DirectoryUpload directoryUpload =
transferManager.uploadDirectory(UploadDirectoryRequest.builder()
.source(Paths.get("source/directory"))
.bucket("bucket")
.s3Prefix("prefix")
.build());
// Wait for the transfer to complete
CompletedDirectoryUpload completedDirectoryUpload = directoryUpload.completionFuture().join();
// Print out the failed uploads
completedDirectoryUpload.failedTransfers().forEach(System.out::println);
// @end region=uploadDirectory
}
public void downloadDirectory() {
// @start region=downloadDirectory
S3TransferManager transferManager = S3TransferManager.create();
DirectoryDownload directoryDownload =
transferManager.downloadDirectory(DownloadDirectoryRequest.builder()
.destination(Paths.get("destination/directory"))
.bucket("bucket")
.listObjectsV2RequestTransformer(l -> l.prefix("prefix"))
.build());
// Wait for the transfer to complete
CompletedDirectoryDownload completedDirectoryDownload = directoryDownload.completionFuture().join();
// Print out the failed downloads
completedDirectoryDownload.failedTransfers().forEach(System.out::println);
// @end region=downloadDirectory
}
public void copy() {
// @start region=copy
S3TransferManager transferManager = S3TransferManager.create();
CopyObjectRequest copyObjectRequest = CopyObjectRequest.builder()
.sourceBucket("source_bucket")
.sourceKey("source_key")
.destinationBucket("dest_bucket")
.destinationKey("dest_key")
.build();
CopyRequest copyRequest = CopyRequest.builder()
.copyObjectRequest(copyObjectRequest)
.build();
Copy copy = transferManager.copy(copyRequest);
// Wait for the transfer to complete
CompletedCopy completedCopy = copy.completionFuture().join();
// @end region=copy
}
} | 3,724 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/model/CompletedFileDownloadTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.assertj.core.api.Assertions.assertThatThrownBy;
import nl.jqno.equalsverifier.EqualsVerifier;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.transfer.s3.model.CompletedFileDownload;
public class CompletedFileDownloadTest {
@Test
public void responseNull_shouldThrowException() {
assertThatThrownBy(() -> CompletedFileDownload.builder().build()).isInstanceOf(NullPointerException.class)
.hasMessageContaining("must not be null");
}
@Test
public void equalsHashcode() {
EqualsVerifier.forClass(CompletedFileDownload.class)
.withNonnullFields("response")
.verify();
}
}
| 3,725 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/model/CompletedFileUploadTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.assertj.core.api.Assertions.assertThatThrownBy;
import nl.jqno.equalsverifier.EqualsVerifier;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.transfer.s3.model.CompletedFileUpload;
public class CompletedFileUploadTest {
@Test
public void responseNull_shouldThrowException() {
assertThatThrownBy(() -> CompletedFileUpload.builder().build()).isInstanceOf(NullPointerException.class)
.hasMessageContaining("must not be null");
}
@Test
public void equalsHashcode() {
EqualsVerifier.forClass(CompletedFileUpload.class)
.withNonnullFields("response")
.verify();
}
}
| 3,726 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/model/DownloadRequestTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import nl.jqno.equalsverifier.EqualsVerifier;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.ResponseBytes;
import software.amazon.awssdk.core.async.AsyncResponseTransformer;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
class DownloadRequestTest {
@Test
void noGetObjectRequest_throws() {
assertThatThrownBy(() -> DownloadRequest.builder()
.responseTransformer(AsyncResponseTransformer.toBytes())
.build()).isInstanceOf(NullPointerException.class).hasMessageContaining(
"getObjectRequest");
}
@Test
public void usingFile() {
AsyncResponseTransformer<GetObjectResponse, ResponseBytes<GetObjectResponse>> responseTransformer =
AsyncResponseTransformer.toBytes();
DownloadRequest requestUsingFile = DownloadRequest.builder()
.getObjectRequest(b -> b.bucket("bucket").key("key"))
.responseTransformer(responseTransformer)
.build();
assertThat(requestUsingFile.responseTransformer()).isEqualTo(responseTransformer);
}
@Test
public void null_responseTransformer_shouldThrowException() {
assertThatThrownBy(() -> DownloadRequest.builder()
.getObjectRequest(b -> b.bucket("bucket").key("key"))
.responseTransformer(null)
.build()).isInstanceOf(NullPointerException.class).hasMessageContaining(
"responseTransformer");
}
@Test
public void equals_hashcode() {
EqualsVerifier.forClass(DownloadRequest.class)
.withNonnullFields("responseTransformer", "getObjectRequest")
.verify();
}
}
| 3,727 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/model/CompletedDirectoryDownloadTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.assertj.core.api.Assertions.assertThat;
import nl.jqno.equalsverifier.EqualsVerifier;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.transfer.s3.model.CompletedDirectoryDownload;
class CompletedDirectoryDownloadTest {
@Test
void equalsHashcode() {
EqualsVerifier.forClass(CompletedDirectoryDownload.class)
.withNonnullFields("failedTransfers")
.verify();
}
@Test
void defaultBuilder() {
assertThat(CompletedDirectoryDownload.builder().build().failedTransfers())
.isEmpty();
}
}
| 3,728 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/model/DownloadFileRequestTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import nl.jqno.equalsverifier.EqualsVerifier;
import org.junit.jupiter.api.Test;
class DownloadFileRequestTest {
@Test
void noGetObjectRequest_throws() {
assertThatThrownBy(() -> DownloadFileRequest.builder()
.destination(Paths.get("."))
.build()).isInstanceOf(NullPointerException.class).hasMessageContaining(
"getObjectRequest");
}
@Test
public void pathMissing_throws() {
assertThatThrownBy(() -> DownloadFileRequest.builder()
.getObjectRequest(b -> b.bucket("bucket").key("key"))
.build()).isInstanceOf(NullPointerException.class).hasMessageContaining(
"destination");
}
@Test
public void usingFile() {
Path path = Paths.get(".");
DownloadFileRequest requestUsingFile = DownloadFileRequest.builder()
.getObjectRequest(b -> b.bucket("bucket").key("key"))
.destination(path.toFile())
.build();
assertThat(requestUsingFile.destination()).isEqualTo(path);
}
@Test
void usingFile_null_shouldThrowException() {
File file = null;
assertThatThrownBy(() -> DownloadFileRequest.builder()
.getObjectRequest(b -> b.bucket("bucket").key("key"))
.destination(file)
.build()).isInstanceOf(NullPointerException.class).hasMessageContaining(
"destination");
}
@Test
void equals_hashcode() {
EqualsVerifier.forClass(DownloadFileRequest.class)
.withNonnullFields("destination", "getObjectRequest")
.verify();
}
}
| 3,729 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/model/FailedFileDownloadTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.assertj.core.api.Assertions.assertThatThrownBy;
import java.nio.file.Paths;
import nl.jqno.equalsverifier.EqualsVerifier;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.transfer.s3.model.DownloadFileRequest;
import software.amazon.awssdk.transfer.s3.model.FailedFileDownload;
class FailedFileDownloadTest {
@Test
void requestNull_mustThrowException() {
assertThatThrownBy(() -> FailedFileDownload.builder()
.exception(SdkClientException.create("xxx")).build())
.isInstanceOf(NullPointerException.class)
.hasMessageContaining("request must not be null");
}
@Test
void exceptionNull_mustThrowException() {
DownloadFileRequest downloadFileRequest =
DownloadFileRequest.builder().destination(Paths.get(".")).getObjectRequest(p -> p.bucket("bucket").key("key")).build();
assertThatThrownBy(() -> FailedFileDownload.builder()
.request(downloadFileRequest).build())
.isInstanceOf(NullPointerException.class)
.hasMessageContaining("exception must not be null");
}
@Test
void equalsHashcode() {
EqualsVerifier.forClass(FailedFileDownload.class)
.withNonnullFields("exception", "request")
.verify();
}
}
| 3,730 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/model/CompletedUploadTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.assertj.core.api.Assertions.assertThatThrownBy;
import nl.jqno.equalsverifier.EqualsVerifier;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.transfer.s3.model.CompletedUpload;
public class CompletedUploadTest {
@Test
public void responseNull_shouldThrowException() {
assertThatThrownBy(() -> CompletedUpload.builder().build()).isInstanceOf(NullPointerException.class)
.hasMessageContaining("must not be null");
}
@Test
public void equalsHashcode() {
EqualsVerifier.forClass(CompletedUpload.class)
.withNonnullFields("response")
.verify();
}
}
| 3,731 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/model/ResumableFileUploadTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.assertj.core.api.Assertions.assertThat;
import static software.amazon.awssdk.transfer.s3.SizeConstant.MB;
import static software.amazon.awssdk.utils.DateUtils.parseIso8601Date;
import com.google.common.jimfs.Jimfs;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
import nl.jqno.equalsverifier.EqualsVerifier;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.services.s3.model.ChecksumAlgorithm;
import software.amazon.awssdk.testutils.RandomTempFile;
class ResumableFileUploadTest {
private static final Instant DATE = parseIso8601Date("2022-05-15T21:50:11.308Z");
private static FileSystem jimfs;
private static ResumableFileUpload resumeableFileUpload;
@BeforeAll
public static void setup() {
jimfs = Jimfs.newFileSystem();
resumeableFileUpload = ResumableFileUpload();
}
@Test
void equalsHashcode() {
EqualsVerifier.forClass(ResumableFileUpload.class)
.withNonnullFields("fileLength", "uploadFileRequest", "fileLastModified")
.verify();
}
@Test
void toBuilder() {
ResumableFileUpload fileUpload =
ResumableFileUpload.builder()
.multipartUploadId("1234")
.uploadFileRequest(UploadFileRequest.builder().putObjectRequest(p -> p.bucket("bucket").key("key"
)).source(Paths.get("test")).build())
.fileLastModified(Instant.now())
.fileLength(10L)
.partSizeInBytes(10 * MB)
.build();
assertThat(fileUpload.toBuilder().build()).isEqualTo(fileUpload);
assertThat(fileUpload.toBuilder().multipartUploadId("5678").build()).isNotEqualTo(fileUpload);
}
@Test
void fileSerDeser() throws IOException {
String directoryName = "test";
Path directory = jimfs.getPath(directoryName);
Files.createDirectory(directory);
Path file = jimfs.getPath(directoryName, "serializedDownload");
resumeableFileUpload.serializeToFile(file);
ResumableFileUpload deserializedDownload = ResumableFileUpload.fromFile(file);
assertThat(deserializedDownload).isEqualTo(resumeableFileUpload);
}
@Test
void stringSerDeser() {
String serializedDownload = resumeableFileUpload.serializeToString();
ResumableFileUpload deserializedDownload = ResumableFileUpload.fromString(serializedDownload);
assertThat(deserializedDownload).isEqualTo(resumeableFileUpload);
}
@Test
void bytesSerDeser() {
SdkBytes serializedDownload = resumeableFileUpload.serializeToBytes();
ResumableFileUpload deserializedDownload =
ResumableFileUpload.fromBytes(SdkBytes.fromByteArrayUnsafe(serializedDownload.asByteArray()));
assertThat(deserializedDownload).isEqualTo(resumeableFileUpload);
}
@Test
void inputStreamSerDeser() {
InputStream serializedDownload = resumeableFileUpload.serializeToInputStream();
ResumableFileUpload deserializedDownload =
ResumableFileUpload.fromBytes(SdkBytes.fromInputStream(serializedDownload));
assertThat(deserializedDownload).isEqualTo(resumeableFileUpload);
}
@Test
void outputStreamSer() {
ByteArrayOutputStream serializedDownload = new ByteArrayOutputStream();
resumeableFileUpload.serializeToOutputStream(serializedDownload);
ResumableFileUpload deserializedDownload =
ResumableFileUpload.fromBytes(SdkBytes.fromByteArrayUnsafe(serializedDownload.toByteArray()));
assertThat(deserializedDownload).isEqualTo(resumeableFileUpload);
}
@Test
void byteBufferDeser() {
SdkBytes serializedDownload = resumeableFileUpload.serializeToBytes();
ResumableFileUpload deserializedDownload =
ResumableFileUpload.fromBytes(SdkBytes.fromByteBuffer(serializedDownload.asByteBuffer()));
assertThat(deserializedDownload).isEqualTo(resumeableFileUpload);
}
private static ResumableFileUpload ResumableFileUpload() {
Path path = RandomTempFile.randomUncreatedFile().toPath();
Map<String, String> metadata = new HashMap<>();
return ResumableFileUpload.builder()
.uploadFileRequest(r -> r.putObjectRequest(b -> b.bucket("BUCKET")
.key("KEY")
.checksumAlgorithm(ChecksumAlgorithm.CRC32)
.bucketKeyEnabled(Boolean.FALSE)
.metadata(metadata))
.source(path))
.fileLength(5000L)
.fileLastModified(DATE)
.partSizeInBytes(1024L)
.totalParts(5L)
.build();
}
}
| 3,732 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/model/UploadFileRequestTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import nl.jqno.equalsverifier.EqualsVerifier;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
public class UploadFileRequestTest {
@Test
public void upload_noRequestParamsProvided_throws() {
assertThatThrownBy(() -> UploadFileRequest.builder()
.source(Paths.get("."))
.build()).isInstanceOf(NullPointerException.class).hasMessageContaining(
"putObjectRequest");
}
@Test
public void pathMissing_shouldThrow() {
assertThatThrownBy(() -> UploadFileRequest.builder()
.putObjectRequest(PutObjectRequest.builder().build())
.build()).isInstanceOf(NullPointerException.class).hasMessageContaining(
"source");
}
@Test
public void sourceUsingFile() {
Path path = Paths.get(".");
UploadFileRequest request = UploadFileRequest.builder()
.putObjectRequest(b -> b.bucket("bucket").key("key"))
.source(path.toFile())
.build();
assertThat(request.source()).isEqualTo(path);
}
@Test
public void sourceUsingFile_null_shouldThrowException() {
File file = null;
assertThatThrownBy(() -> UploadFileRequest.builder()
.putObjectRequest(b -> b.bucket("bucket").key("key"))
.source(file)
.build()).isInstanceOf(NullPointerException.class).hasMessageContaining(
"source");
}
@Test
public void equals_hashcode() {
EqualsVerifier.forClass(UploadFileRequest.class)
.withNonnullFields("source", "putObjectRequest")
.verify();
}
}
| 3,733 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/model/CopyRequestTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.assertj.core.api.Assertions.assertThatThrownBy;
import nl.jqno.equalsverifier.EqualsVerifier;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.transfer.s3.model.CopyRequest;
class CopyRequestTest {
@Test
void nocopyObjectRequest_throws() {
CopyRequest.Builder builder = CopyRequest.builder();
assertThatThrownBy(builder::build)
.isInstanceOf(NullPointerException.class)
.hasMessageContaining("copyObjectRequest");
}
@Test
void equals_hashcode() {
EqualsVerifier.forClass(CopyRequest.class)
.withNonnullFields("copyObjectRequest")
.verify();
}
}
| 3,734 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/model/CompletedCopyTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.assertj.core.api.Assertions.assertThatThrownBy;
import nl.jqno.equalsverifier.EqualsVerifier;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.transfer.s3.model.CompletedCopy;
class CompletedCopyTest {
@Test
void responseNull_shouldThrowException() {
CompletedCopy.Builder builder = CompletedCopy.builder();
assertThatThrownBy(builder::build)
.isInstanceOf(NullPointerException.class)
.hasMessageContaining("response");
}
@Test
void equalsHashcode() {
EqualsVerifier.forClass(CompletedCopy.class)
.withNonnullFields("response")
.verify();
}
}
| 3,735 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/model/UploadRequestTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.nio.file.Paths;
import nl.jqno.equalsverifier.EqualsVerifier;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
public class UploadRequestTest {
@Test
public void upload_noRequestParamsProvided_throws() {
assertThatThrownBy(() -> UploadRequest.builder()
.requestBody(AsyncRequestBody.fromString("foo"))
.build()).isInstanceOf(NullPointerException.class).hasMessageContaining(
"putObjectRequest");
}
@Test
public void bodyMissing_shouldThrow() {
assertThatThrownBy(() -> UploadRequest.builder()
.putObjectRequest(PutObjectRequest.builder().build())
.build()).isInstanceOf(NullPointerException.class).hasMessageContaining(
"requestBody");
}
@Test
public void bodyEqualsGivenBody() {
AsyncRequestBody requestBody = AsyncRequestBody.fromString("foo");
UploadRequest request = UploadRequest.builder()
.putObjectRequest(b -> b.bucket("bucket").key("key"))
.requestBody(requestBody)
.build();
assertThat(request.requestBody()).isSameAs(requestBody);
}
@Test
public void null_requestBody_shouldThrowException() {
assertThatThrownBy(() -> UploadRequest.builder()
.requestBody(null)
.putObjectRequest(b -> b.bucket("bucket").key("key"))
.build()).isInstanceOf(NullPointerException.class).hasMessageContaining(
"requestBody");
}
@Test
public void equals_hashcode() {
EqualsVerifier.forClass(UploadRequest.class)
.withNonnullFields("requestBody", "putObjectRequest")
.verify();
}
}
| 3,736 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/model/CompletedDownloadTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.assertj.core.api.Assertions.assertThatThrownBy;
import nl.jqno.equalsverifier.EqualsVerifier;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.transfer.s3.model.CompletedDownload;
public class CompletedDownloadTest {
@Test
public void responseNull_shouldThrowException() {
assertThatThrownBy(() -> CompletedDownload.builder().result(null).build()).isInstanceOf(NullPointerException.class)
.hasMessageContaining("must not be null");
}
@Test
public void equalsHashcode() {
EqualsVerifier.forClass(CompletedDownload.class)
.withNonnullFields("result")
.verify();
}
}
| 3,737 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/model/DownloadDirectoryRequestTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.assertj.core.api.Assertions.assertThatThrownBy;
import java.nio.file.Paths;
import nl.jqno.equalsverifier.EqualsVerifier;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.transfer.s3.model.DownloadDirectoryRequest;
class DownloadDirectoryRequestTest {
@Test
void nodirectory_throws() {
assertThatThrownBy(() ->
DownloadDirectoryRequest.builder().bucket("bucket").build()
).isInstanceOf(NullPointerException.class).hasMessageContaining("destination");
}
@Test
void noBucket_throws() {
assertThatThrownBy(() ->
DownloadDirectoryRequest.builder().destination(Paths.get(".")).build()
).isInstanceOf(NullPointerException.class).hasMessageContaining("bucket");
}
@Test
void equals_hashcode() {
EqualsVerifier.forClass(DownloadDirectoryRequest.class)
.withNonnullFields("destination", "bucket")
.verify();
}
}
| 3,738 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/model/CompletedDirectoryUploadTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.assertj.core.api.Assertions.assertThat;
import nl.jqno.equalsverifier.EqualsVerifier;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.transfer.s3.model.CompletedDirectoryUpload;
class CompletedDirectoryUploadTest {
@Test
void equalsHashcode() {
EqualsVerifier.forClass(CompletedDirectoryUpload.class)
.withNonnullFields("failedTransfers")
.verify();
}
@Test
void defaultBuilder() {
assertThat(CompletedDirectoryUpload.builder().build().failedTransfers())
.isEmpty();
}
}
| 3,739 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/model/ResumableFileDownloadTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.assertj.core.api.Assertions.assertThat;
import static software.amazon.awssdk.utils.DateUtils.parseIso8601Date;
import com.google.common.jimfs.Jimfs;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Instant;
import nl.jqno.equalsverifier.EqualsVerifier;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.testutils.RandomTempFile;
import software.amazon.awssdk.transfer.s3.model.ResumableFileDownload;
class ResumableFileDownloadTest {
private static final Instant DATE1 = parseIso8601Date("2022-05-13T21:55:52.529Z");
private static final Instant DATE2 = parseIso8601Date("2022-05-15T21:50:11.308Z");
private static FileSystem jimfs;
private static ResumableFileDownload standardDownloadObject;
@BeforeAll
public static void setup() {
jimfs = Jimfs.newFileSystem();
standardDownloadObject = resumableFileDownload();
}
@AfterAll
public static void tearDown() {
try {
jimfs.close();
} catch (IOException e) {
// no-op
}
}
@Test
void equalsHashcode() {
EqualsVerifier.forClass(ResumableFileDownload.class)
.withNonnullFields("downloadFileRequest")
.verify();
}
@Test
void fileSerDeser() throws IOException {
String directoryName = "test";
Path directory = jimfs.getPath(directoryName);
Files.createDirectory(directory);
Path file = jimfs.getPath(directoryName, "serializedDownload");
standardDownloadObject.serializeToFile(file);
ResumableFileDownload deserializedDownload = ResumableFileDownload.fromFile(file);
assertThat(deserializedDownload).isEqualTo(standardDownloadObject);
}
@Test
void stringSerDeser() {
String serializedDownload = standardDownloadObject.serializeToString();
ResumableFileDownload deserializedDownload = ResumableFileDownload.fromString(serializedDownload);
assertThat(deserializedDownload).isEqualTo(standardDownloadObject);
}
@Test
void bytesSerDeser() {
SdkBytes serializedDownload = standardDownloadObject.serializeToBytes();
ResumableFileDownload deserializedDownload =
ResumableFileDownload.fromBytes(SdkBytes.fromByteArrayUnsafe(serializedDownload.asByteArray()));
assertThat(deserializedDownload).isEqualTo(standardDownloadObject);
}
@Test
void inputStreamSerDeser() throws IOException {
InputStream serializedDownload = standardDownloadObject.serializeToInputStream();
ResumableFileDownload deserializedDownload =
ResumableFileDownload.fromBytes(SdkBytes.fromInputStream(serializedDownload));
assertThat(deserializedDownload).isEqualTo(standardDownloadObject);
}
@Test
void outputStreamSer() throws IOException {
ByteArrayOutputStream serializedDownload = new ByteArrayOutputStream();
standardDownloadObject.serializeToOutputStream(serializedDownload);
ResumableFileDownload deserializedDownload =
ResumableFileDownload.fromBytes(SdkBytes.fromByteArrayUnsafe(serializedDownload.toByteArray()));
assertThat(deserializedDownload).isEqualTo(standardDownloadObject);
}
@Test
void byteBufferDeser() {
SdkBytes serializedDownload = standardDownloadObject.serializeToBytes();
ResumableFileDownload deserializedDownload =
ResumableFileDownload.fromBytes(SdkBytes.fromByteBuffer(serializedDownload.asByteBuffer()));
assertThat(deserializedDownload).isEqualTo(standardDownloadObject);
}
private static ResumableFileDownload resumableFileDownload() {
Path path = RandomTempFile.randomUncreatedFile().toPath();
return ResumableFileDownload.builder()
.downloadFileRequest(r -> r.getObjectRequest(b -> b.bucket("BUCKET")
.key("KEY")
.partNumber(1)
.ifModifiedSince(DATE1))
.destination(path))
.bytesTransferred(1000L)
.fileLastModified(DATE1)
.s3ObjectLastModified(DATE2)
.totalSizeInBytes(2000L)
.build();
}
}
| 3,740 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/model/UploadDirectoryRequestTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.assertj.core.api.Assertions.assertThatThrownBy;
import java.nio.file.Paths;
import nl.jqno.equalsverifier.EqualsVerifier;
import org.junit.jupiter.api.Test;
public class UploadDirectoryRequestTest {
@Test
public void noSourceDirectory_throws() {
assertThatThrownBy(() ->
UploadDirectoryRequest.builder().bucket("bucket").build()
).isInstanceOf(NullPointerException.class).hasMessageContaining("source");
}
@Test
public void noBucket_throws() {
assertThatThrownBy(() ->
UploadDirectoryRequest.builder().source(Paths.get(".")).build()
).isInstanceOf(NullPointerException.class).hasMessageContaining("bucket");
}
@Test
public void equals_hashcode() {
EqualsVerifier.forClass(UploadDirectoryRequest.class)
.withNonnullFields("source", "bucket")
.verify();
}
}
| 3,741 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/test/java/software/amazon/awssdk/transfer/s3/model/FailedFileUploadTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.assertj.core.api.Assertions.assertThatThrownBy;
import java.nio.file.Paths;
import nl.jqno.equalsverifier.EqualsVerifier;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.transfer.s3.model.FailedFileUpload;
import software.amazon.awssdk.transfer.s3.model.UploadFileRequest;
public class FailedFileUploadTest {
@Test
public void requestNull_mustThrowException() {
assertThatThrownBy(() -> FailedFileUpload.builder()
.exception(SdkClientException.create("xxx")).build())
.isInstanceOf(NullPointerException.class)
.hasMessageContaining("request must not be null");
}
@Test
public void exceptionNull_mustThrowException() {
UploadFileRequest uploadFileRequest =
UploadFileRequest.builder().source(Paths.get(".")).putObjectRequest(p -> p.bucket("bucket").key("key")).build();
assertThatThrownBy(() -> FailedFileUpload.builder()
.request(uploadFileRequest).build())
.isInstanceOf(NullPointerException.class)
.hasMessageContaining("exception must not be null");
}
@Test
public void equalsHashcode() {
EqualsVerifier.forClass(FailedFileUpload.class)
.withNonnullFields("exception", "request")
.verify();
}
}
| 3,742 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/it/java/software/amazon/awssdk/transfer | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/it/java/software/amazon/awssdk/transfer/s3/CaptureTransferListener.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.transfer.s3.progress.TransferListener;
public class CaptureTransferListener implements TransferListener {
public Boolean isTransferInitiated() {
return transferInitiated;
}
public Boolean isTransferComplete() {
return transferComplete;
}
public List<Double> getRatioTransferredList() {
return ratioTransferredList;
}
public CompletableFuture<Void> getCompletionFuture() {
return completionFuture;
}
public Throwable getExceptionCaught() {
return exceptionCaught;
}
private Boolean transferInitiated = false;
private Boolean transferComplete = false;
CompletableFuture<Void> completionFuture = new CompletableFuture<>();
private List<Double> ratioTransferredList = new ArrayList<>();
private Throwable exceptionCaught;
@Override
public void transferInitiated(Context.TransferInitiated context) {
transferInitiated = true;
context.progressSnapshot().ratioTransferred().ifPresent(ratioTransferredList::add);
}
@Override
public void bytesTransferred(Context.BytesTransferred context) {
context.progressSnapshot().ratioTransferred().ifPresent(ratioTransferredList::add);
}
@Override
public void transferComplete(Context.TransferComplete context) {
context.progressSnapshot().ratioTransferred().ifPresent(ratioTransferredList::add);
transferComplete = true;
completionFuture.complete(null);
}
@Override
public void transferFailed(Context.TransferFailed context) {
exceptionCaught = context.exception();
completionFuture.completeExceptionally(exceptionCaught);
}
}
| 3,743 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/it/java/software/amazon/awssdk/transfer | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/it/java/software/amazon/awssdk/transfer/s3/S3TransferManagerDownloadPauseResumeIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static software.amazon.awssdk.testutils.service.S3BucketUtils.temporaryBucketName;
import static software.amazon.awssdk.transfer.s3.SizeConstant.MB;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.Optional;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.SdkResponse;
import software.amazon.awssdk.core.retry.backoff.FixedDelayBackoffStrategy;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.core.waiters.Waiter;
import software.amazon.awssdk.core.waiters.WaiterAcceptor;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.testutils.RandomTempFile;
import software.amazon.awssdk.transfer.s3.model.DownloadFileRequest;
import software.amazon.awssdk.transfer.s3.model.FileDownload;
import software.amazon.awssdk.transfer.s3.model.ResumableFileDownload;
import software.amazon.awssdk.transfer.s3.progress.TransferListener;
import software.amazon.awssdk.transfer.s3.progress.TransferProgressSnapshot;
import software.amazon.awssdk.utils.Logger;
public class S3TransferManagerDownloadPauseResumeIntegrationTest extends S3IntegrationTestBase {
private static final Logger log = Logger.loggerFor(S3TransferManagerDownloadPauseResumeIntegrationTest.class);
private static final String BUCKET = temporaryBucketName(S3TransferManagerDownloadPauseResumeIntegrationTest.class);
private static final String KEY = "key";
// 24 * MB is chosen to make sure we have data written in the file already upon pausing.
private static final long OBJ_SIZE = 24 * MB;
private static File sourceFile;
@BeforeAll
public static void setup() throws Exception {
createBucket(BUCKET);
sourceFile = new RandomTempFile(OBJ_SIZE);
s3.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(KEY)
.build(), sourceFile.toPath());
}
@AfterAll
public static void cleanup() {
deleteBucketAndAllContents(BUCKET);
sourceFile.delete();
}
@Test
void pauseAndResume_ObjectNotChanged_shouldResumeDownload() {
Path path = RandomTempFile.randomUncreatedFile().toPath();
TestDownloadListener testDownloadListener = new TestDownloadListener();
DownloadFileRequest request = DownloadFileRequest.builder()
.getObjectRequest(b -> b.bucket(BUCKET).key(KEY))
.destination(path)
.addTransferListener(testDownloadListener)
.build();
FileDownload download = tmCrt.downloadFile(request);
waitUntilFirstByteBufferDelivered(download);
ResumableFileDownload resumableFileDownload = download.pause();
long bytesTransferred = resumableFileDownload.bytesTransferred();
log.debug(() -> "Paused: " + resumableFileDownload);
assertThat(resumableFileDownload.downloadFileRequest()).isEqualTo(request);
assertThat(testDownloadListener.getObjectResponse).isNotNull();
assertThat(resumableFileDownload.s3ObjectLastModified()).hasValue(testDownloadListener.getObjectResponse.lastModified());
assertThat(bytesTransferred).isEqualTo(path.toFile().length());
assertThat(resumableFileDownload.totalSizeInBytes()).hasValue(sourceFile.length());
assertThat(bytesTransferred).isLessThan(sourceFile.length());
assertThat(download.completionFuture()).isCancelled();
log.debug(() -> "Resuming download ");
verifyFileDownload(path, resumableFileDownload, OBJ_SIZE - bytesTransferred);
}
@Test
void pauseAndResume_objectChanged_shouldStartFromBeginning() {
try {
Path path = RandomTempFile.randomUncreatedFile().toPath();
DownloadFileRequest request = DownloadFileRequest.builder()
.getObjectRequest(b -> b.bucket(BUCKET).key(KEY))
.destination(path)
.build();
FileDownload download = tmCrt.downloadFile(request);
waitUntilFirstByteBufferDelivered(download);
ResumableFileDownload resumableFileDownload = download.pause();
log.debug(() -> "Paused: " + resumableFileDownload);
String newObject = RandomStringUtils.randomAlphanumeric(1000);
// Re-upload the S3 object
s3.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(KEY)
.build(), RequestBody.fromString(newObject));
log.debug(() -> "Resuming download ");
FileDownload resumedFileDownload = tmCrt.resumeDownloadFile(resumableFileDownload);
resumedFileDownload.progress().snapshot();
resumedFileDownload.completionFuture().join();
assertThat(path.toFile()).hasContent(newObject);
assertThat(resumedFileDownload.progress().snapshot().totalBytes()).hasValue((long) newObject.getBytes(StandardCharsets.UTF_8).length);
} finally {
s3.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(KEY)
.build(), sourceFile.toPath());
}
}
@Test
void pauseAndResume_fileChanged_shouldStartFromBeginning() throws Exception {
Path path = RandomTempFile.randomUncreatedFile().toPath();
DownloadFileRequest request = DownloadFileRequest.builder()
.getObjectRequest(b -> b.bucket(BUCKET).key(KEY))
.destination(path)
.build();
FileDownload download = tmCrt.downloadFile(request);
waitUntilFirstByteBufferDelivered(download);
ResumableFileDownload resumableFileDownload = download.pause();
Files.write(path, "helloworld".getBytes(StandardCharsets.UTF_8));
verifyFileDownload(path, resumableFileDownload, OBJ_SIZE);
}
private static void verifyFileDownload(Path path, ResumableFileDownload resumableFileDownload, long expectedBytesTransferred) {
FileDownload resumedFileDownload = tmCrt.resumeDownloadFile(resumableFileDownload);
resumedFileDownload.completionFuture().join();
assertThat(resumedFileDownload.progress().snapshot().totalBytes()).hasValue(expectedBytesTransferred);
assertThat(path.toFile()).hasSameBinaryContentAs(sourceFile);
}
private static void waitUntilFirstByteBufferDelivered(FileDownload download) {
Waiter<TransferProgressSnapshot> waiter = Waiter.builder(TransferProgressSnapshot.class)
.addAcceptor(WaiterAcceptor.successOnResponseAcceptor(r -> r.transferredBytes() > 0))
.addAcceptor(WaiterAcceptor.retryOnResponseAcceptor(r -> true))
.overrideConfiguration(o -> o.waitTimeout(Duration.ofMinutes(1))
.maxAttempts(Integer.MAX_VALUE)
.backoffStrategy(FixedDelayBackoffStrategy.create(Duration.ofMillis(100))))
.build();
waiter.run(() -> download.progress().snapshot());
}
private static final class TestDownloadListener implements TransferListener {
private GetObjectResponse getObjectResponse;
@Override
public void bytesTransferred(Context.BytesTransferred context) {
Optional<SdkResponse> sdkResponse = context.progressSnapshot().sdkResponse();
if (sdkResponse.isPresent() && sdkResponse.get() instanceof GetObjectResponse) {
getObjectResponse = (GetObjectResponse) sdkResponse.get();
}
}
}
}
| 3,744 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/it/java/software/amazon/awssdk/transfer | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/it/java/software/amazon/awssdk/transfer/s3/S3TransferManagerDownloadDirectoryIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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;
import static org.assertj.core.api.Assertions.assertThat;
import static software.amazon.awssdk.testutils.FileUtils.toFileTreeString;
import static software.amazon.awssdk.testutils.service.S3BucketUtils.temporaryBucketName;
import static software.amazon.awssdk.utils.IoUtils.closeQuietly;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.opentest4j.AssertionFailedError;
import software.amazon.awssdk.testutils.FileUtils;
import software.amazon.awssdk.transfer.s3.model.CompletedDirectoryDownload;
import software.amazon.awssdk.transfer.s3.model.DirectoryDownload;
import software.amazon.awssdk.utils.Logger;
public class S3TransferManagerDownloadDirectoryIntegrationTest extends S3IntegrationTestBase {
private static final Logger log = Logger.loggerFor(S3TransferManagerDownloadDirectoryIntegrationTest.class);
private static final String TEST_BUCKET = temporaryBucketName(S3TransferManagerDownloadDirectoryIntegrationTest.class);
private static final String TEST_BUCKET_CUSTOM_DELIMITER = temporaryBucketName("S3TransferManagerUploadIntegrationTest"
+ "-delimiter");
private static final String CUSTOM_DELIMITER = "-";
private static Path sourceDirectory;
private Path directory;
@BeforeAll
public static void setUp() throws Exception {
createBucket(TEST_BUCKET);
createBucket(TEST_BUCKET_CUSTOM_DELIMITER);
sourceDirectory = createLocalTestDirectory();
tmCrt.uploadDirectory(u -> u.source(sourceDirectory).bucket(TEST_BUCKET)).completionFuture().join();
tmCrt.uploadDirectory(u -> u.source(sourceDirectory)
.s3Delimiter(CUSTOM_DELIMITER)
.bucket(TEST_BUCKET_CUSTOM_DELIMITER))
.completionFuture().join();
}
@BeforeEach
public void setUpPerTest() throws IOException {
directory = Files.createTempDirectory("destination");
}
@AfterEach
public void cleanup() {
FileUtils.cleanUpTestDirectory(directory);
}
@AfterAll
public static void teardown() {
try {
FileUtils.cleanUpTestDirectory(sourceDirectory);
} catch (Exception exception) {
log.warn(() -> "Failed to clean up test directory " + sourceDirectory, exception);
}
try {
deleteBucketAndAllContents(TEST_BUCKET);
} catch (Exception exception) {
log.warn(() -> "Failed to delete s3 bucket " + TEST_BUCKET, exception);
}
try {
deleteBucketAndAllContents(TEST_BUCKET_CUSTOM_DELIMITER);
} catch (Exception exception) {
log.warn(() -> "Failed to delete s3 bucket " + TEST_BUCKET_CUSTOM_DELIMITER, exception);
}
closeQuietly(tmCrt, log.logger());
}
/**
* The destination directory structure should match with the directory uploaded
* <pre>
* {@code
* - destination
* - README.md
* - CHANGELOG.md
* - notes
* - 2021
* - 1.txt
* - 2.txt
* - 2022
* - 1.txt
* - important.txt
* }
* </pre>
*/
@Test
public void downloadDirectory() throws Exception {
DirectoryDownload downloadDirectory = tmCrt.downloadDirectory(u -> u.destination(directory)
.bucket(TEST_BUCKET));
CompletedDirectoryDownload completedDirectoryDownload = downloadDirectory.completionFuture().get(5, TimeUnit.SECONDS);
assertThat(completedDirectoryDownload.failedTransfers()).isEmpty();
assertTwoDirectoriesHaveSameStructure(sourceDirectory, directory);
}
@ParameterizedTest
@ValueSource(strings = {"notes/2021", "notes/2021/"})
void downloadDirectory_withPrefix(String prefix) throws Exception {
DirectoryDownload downloadDirectory = tmCrt.downloadDirectory(u -> u.destination(directory)
.listObjectsV2RequestTransformer(r -> r.prefix(prefix))
.bucket(TEST_BUCKET));
CompletedDirectoryDownload completedDirectoryDownload = downloadDirectory.completionFuture().get(5, TimeUnit.SECONDS);
assertThat(completedDirectoryDownload.failedTransfers()).isEmpty();
assertTwoDirectoriesHaveSameStructure(sourceDirectory.resolve(prefix), directory);
}
/**
* With prefix = "notes", the destination directory structure should be the following:
* <pre>
* {@code
* - destination
* - notesMemo.txt
* - 2021
* - 1.txt
* - 2.txt
* - 2022
* - 1.txt
* - important.txt
* }
* </pre>
*/
@Test
void downloadDirectory_containsObjectWithPrefixInTheKey_shouldResolveCorrectly() throws Exception {
String prefix = "notes";
DirectoryDownload downloadDirectory = tmCrt.downloadDirectory(u -> u.destination(directory)
.listObjectsV2RequestTransformer(r -> r.prefix(prefix))
.bucket(TEST_BUCKET));
CompletedDirectoryDownload completedDirectoryDownload = downloadDirectory.completionFuture().get(5, TimeUnit.SECONDS);
assertThat(completedDirectoryDownload.failedTransfers()).isEmpty();
Path expectedDirectory = Files.createTempDirectory("expectedDirectory");
try {
FileUtils.copyDirectory(sourceDirectory.resolve(prefix), expectedDirectory);
Files.copy(sourceDirectory.resolve("notesMemo.txt"), expectedDirectory.resolve("notesMemo.txt"));
assertTwoDirectoriesHaveSameStructure(expectedDirectory, directory);
} finally {
FileUtils.cleanUpTestDirectory(expectedDirectory);
}
}
/**
* The destination directory structure should be the following with prefix "notes"
* <pre>
* {@code
* - destination
* - 1.txt
* - 2.txt
* }
* </pre>
*/
@Test
public void downloadDirectory_withPrefixAndDelimiter() throws Exception {
String prefix = "notes-2021";
DirectoryDownload downloadDirectory =
tmCrt.downloadDirectory(u -> u.destination(directory)
.listObjectsV2RequestTransformer(r -> r.delimiter(CUSTOM_DELIMITER)
.prefix(prefix))
.bucket(TEST_BUCKET_CUSTOM_DELIMITER));
CompletedDirectoryDownload completedDirectoryDownload = downloadDirectory.completionFuture().get(5, TimeUnit.SECONDS);
assertThat(completedDirectoryDownload.failedTransfers()).isEmpty();
assertTwoDirectoriesHaveSameStructure(sourceDirectory.resolve("notes").resolve("2021"), directory);
}
/**
* The destination directory structure should only contain file names starting with "2":
* <pre>
* {@code
* - destination
* - notes
* - 2021
* - 2.txt
* }
* </pre>
*/
@Test
public void downloadDirectory_withFilter() throws Exception {
DirectoryDownload downloadDirectory = tmCrt.downloadDirectory(u -> u
.destination(directory)
.bucket(TEST_BUCKET)
.filter(s3Object -> s3Object.key().startsWith("notes/2021/2")));
CompletedDirectoryDownload completedDirectoryDownload = downloadDirectory.completionFuture().get(5, TimeUnit.SECONDS);
assertThat(completedDirectoryDownload.failedTransfers()).isEmpty();
Path expectedDirectory = Files.createTempDirectory("expectedDirectory");
try {
FileUtils.copyDirectory(sourceDirectory, expectedDirectory);
Files.delete(expectedDirectory.resolve("README.md"));
Files.delete(expectedDirectory.resolve("CHANGELOG.md"));
Files.delete(expectedDirectory.resolve("notes/2022/1.txt"));
Files.delete(expectedDirectory.resolve("notes/2022"));
Files.delete(expectedDirectory.resolve("notes/important.txt"));
Files.delete(expectedDirectory.resolve("notes/2021/1.txt"));
Files.delete(expectedDirectory.resolve("notesMemo.txt"));
assertTwoDirectoriesHaveSameStructure(expectedDirectory, directory);
} finally {
FileUtils.cleanUpTestDirectory(expectedDirectory);
}
}
private static void assertTwoDirectoriesHaveSameStructure(Path a, Path b) {
assertLeftHasRight(a, b);
assertLeftHasRight(b, a);
}
private static void assertLeftHasRight(Path left, Path right) {
try (Stream<Path> paths = Files.walk(left)) {
paths.forEach(leftPath -> {
Path leftRelative = left.relativize(leftPath);
Path rightPath = right.resolve(leftRelative);
log.debug(() -> String.format("Comparing %s with %s", leftPath, rightPath));
try {
assertThat(rightPath).exists();
} catch (AssertionError e) {
throw new AssertionFailedError(e.getMessage(), toFileTreeString(left), toFileTreeString(right));
}
if (Files.isRegularFile(leftPath)) {
assertThat(leftPath).hasSameBinaryContentAs(rightPath);
}
});
} catch (IOException e) {
throw new UncheckedIOException(String.format("Failed to compare %s with %s", left, right), e);
}
}
/**
* Create a test directory with the following structure
* <pre>
* {@code
* - source
* - README.md
* - CHANGELOG.md
* - notesMemo.txt
* - notes
* - 2021
* - 1.txt
* - 2.txt
* - 2022
* - 1.txt
* - important.txt
* }
* </pre>
*/
private static Path createLocalTestDirectory() throws IOException {
Path directory = Files.createTempDirectory("source");
String directoryName = directory.toString();
Files.createDirectory(Paths.get(directoryName, "notes"));
Files.createDirectory(Paths.get(directoryName, "notes", "2021"));
Files.createDirectory(Paths.get(directoryName, "notes", "2022"));
Files.write(Paths.get(directoryName, "README.md"), RandomStringUtils.random(100).getBytes(StandardCharsets.UTF_8));
Files.write(Paths.get(directoryName, "CHANGELOG.md"), RandomStringUtils.random(100).getBytes(StandardCharsets.UTF_8));
Files.write(Paths.get(directoryName, "notesMemo.txt"), RandomStringUtils.random(100).getBytes(StandardCharsets.UTF_8));
Files.write(Paths.get(directoryName, "notes", "2021", "1.txt"),
RandomStringUtils.random(100).getBytes(StandardCharsets.UTF_8));
Files.write(Paths.get(directoryName, "notes", "2021", "2.txt"),
RandomStringUtils.random(100).getBytes(StandardCharsets.UTF_8));
Files.write(Paths.get(directoryName, "notes", "2022", "1.txt"),
RandomStringUtils.random(100).getBytes(StandardCharsets.UTF_8));
Files.write(Paths.get(directoryName, "notes", "important.txt"),
RandomStringUtils.random(100).getBytes(StandardCharsets.UTF_8));
return directory;
}
}
| 3,745 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/it/java/software/amazon/awssdk/transfer | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/it/java/software/amazon/awssdk/transfer/s3/S3TransferManagerUploadIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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;
import static org.assertj.core.api.Assertions.assertThat;
import static software.amazon.awssdk.testutils.service.S3BucketUtils.temporaryBucketName;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CancellationException;
import java.util.stream.Stream;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import software.amazon.awssdk.core.ResponseInputStream;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.core.internal.async.FileAsyncRequestBody;
import software.amazon.awssdk.core.sync.ResponseTransformer;
import software.amazon.awssdk.services.s3.model.ChecksumAlgorithm;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.testutils.RandomTempFile;
import software.amazon.awssdk.transfer.s3.model.CompletedFileUpload;
import software.amazon.awssdk.transfer.s3.model.CompletedUpload;
import software.amazon.awssdk.transfer.s3.model.FileUpload;
import software.amazon.awssdk.transfer.s3.model.Upload;
import software.amazon.awssdk.transfer.s3.model.UploadRequest;
import software.amazon.awssdk.transfer.s3.progress.LoggingTransferListener;
import software.amazon.awssdk.transfer.s3.util.ChecksumUtils;
public class S3TransferManagerUploadIntegrationTest extends S3IntegrationTestBase {
private static final String TEST_BUCKET = temporaryBucketName(S3TransferManagerUploadIntegrationTest.class);
private static final String TEST_KEY = "16mib_file.dat";
private static final int OBJ_SIZE = 16 * 1024 * 1024;
private static RandomTempFile testFile;
@BeforeAll
public static void setUp() throws Exception {
createBucket(TEST_BUCKET);
testFile = new RandomTempFile(TEST_KEY, OBJ_SIZE);
}
@AfterAll
public static void teardown() throws IOException {
Files.delete(testFile.toPath());
deleteBucketAndAllContents(TEST_BUCKET);
}
private static Stream<Arguments> transferManagers() {
return Stream.of(
Arguments.of(tmCrt),
Arguments.of(tmJava));
}
@ParameterizedTest
@MethodSource("transferManagers")
void upload_file_SentCorrectly(S3TransferManager transferManager) throws IOException {
Map<String, String> metadata = new HashMap<>();
CaptureTransferListener transferListener = new CaptureTransferListener();
metadata.put("x-amz-meta-foobar", "FOO BAR");
FileUpload fileUpload =
transferManager.uploadFile(u -> u.putObjectRequest(p -> p.bucket(TEST_BUCKET).key(TEST_KEY).metadata(metadata).checksumAlgorithm(ChecksumAlgorithm.CRC32))
.source(testFile.toPath())
.addTransferListener(LoggingTransferListener.create())
.addTransferListener(transferListener)
.build());
CompletedFileUpload completedFileUpload = fileUpload.completionFuture().join();
assertThat(completedFileUpload.response().responseMetadata().requestId()).isNotNull();
assertThat(completedFileUpload.response().sdkHttpResponse()).isNotNull();
ResponseInputStream<GetObjectResponse> obj = s3.getObject(r -> r.bucket(TEST_BUCKET).key(TEST_KEY),
ResponseTransformer.toInputStream());
assertThat(ChecksumUtils.computeCheckSum(Files.newInputStream(testFile.toPath())))
.isEqualTo(ChecksumUtils.computeCheckSum(obj));
assertThat(obj.response().responseMetadata().requestId()).isNotNull();
assertThat(obj.response().metadata()).containsEntry("foobar", "FOO BAR");
assertThat(fileUpload.progress().snapshot().sdkResponse()).isPresent();
assertListenerForSuccessfulTransferComplete(transferListener);
}
private static void assertListenerForSuccessfulTransferComplete(CaptureTransferListener transferListener) {
assertThat(transferListener.isTransferInitiated()).isTrue();
assertThat(transferListener.isTransferComplete()).isTrue();
assertThat(transferListener.getRatioTransferredList()).isNotEmpty();
assertThat(transferListener.getRatioTransferredList().contains(0.0));
assertThat(transferListener.getRatioTransferredList().contains(100.0));
assertThat(transferListener.getExceptionCaught()).isNull();
}
@ParameterizedTest
@MethodSource("transferManagers")
void upload_asyncRequestBodyFromString_SentCorrectly(S3TransferManager transferManager) throws IOException {
String content = UUID.randomUUID().toString();
CaptureTransferListener transferListener = new CaptureTransferListener();
Upload upload =
transferManager.upload(UploadRequest.builder()
.putObjectRequest(b -> b.bucket(TEST_BUCKET).key(TEST_KEY))
.requestBody(AsyncRequestBody.fromString(content))
.addTransferListener(LoggingTransferListener.create())
.addTransferListener(transferListener)
.build());
CompletedUpload completedUpload = upload.completionFuture().join();
assertThat(completedUpload.response().responseMetadata().requestId()).isNotNull();
assertThat(completedUpload.response().sdkHttpResponse()).isNotNull();
ResponseInputStream<GetObjectResponse> obj = s3.getObject(r -> r.bucket(TEST_BUCKET).key(TEST_KEY),
ResponseTransformer.toInputStream());
assertThat(ChecksumUtils.computeCheckSum(content.getBytes(StandardCharsets.UTF_8)))
.isEqualTo(ChecksumUtils.computeCheckSum(obj));
assertThat(obj.response().responseMetadata().requestId()).isNotNull();
assertThat(upload.progress().snapshot().sdkResponse()).isPresent();
assertListenerForSuccessfulTransferComplete(transferListener);
}
@ParameterizedTest
@MethodSource("transferManagers")
void upload_asyncRequestBodyFromFile_SentCorrectly(S3TransferManager transferManager) throws IOException {
CaptureTransferListener transferListener = new CaptureTransferListener();
Upload upload =
transferManager.upload(UploadRequest.builder()
.putObjectRequest(b -> b.bucket(TEST_BUCKET).key(TEST_KEY))
.requestBody(FileAsyncRequestBody.builder().chunkSizeInBytes(1024).path(testFile.toPath()).build())
.addTransferListener(LoggingTransferListener.create())
.addTransferListener(transferListener)
.build());
CompletedUpload completedUpload = upload.completionFuture().join();
assertThat(completedUpload.response().responseMetadata().requestId()).isNotNull();
assertThat(completedUpload.response().sdkHttpResponse()).isNotNull();
ResponseInputStream<GetObjectResponse> obj = s3.getObject(r -> r.bucket(TEST_BUCKET).key(TEST_KEY),
ResponseTransformer.toInputStream());
assertThat(ChecksumUtils.computeCheckSum(Files.newInputStream(testFile.toPath())))
.isEqualTo(ChecksumUtils.computeCheckSum(obj));
assertThat(obj.response().responseMetadata().requestId()).isNotNull();
assertThat(upload.progress().snapshot().sdkResponse()).isPresent();
assertListenerForSuccessfulTransferComplete(transferListener);
}
@ParameterizedTest
@MethodSource("transferManagers")
void upload_file_Interupted_CancelsTheListener(S3TransferManager transferManager) throws IOException, InterruptedException {
Map<String, String> metadata = new HashMap<>();
CaptureTransferListener transferListener = new CaptureTransferListener();
metadata.put("x-amz-meta-foobar", "FOO BAR");
FileUpload fileUpload =
transferManager.uploadFile(u -> u.putObjectRequest(p -> p.bucket(TEST_BUCKET).key(TEST_KEY).metadata(metadata).checksumAlgorithm(ChecksumAlgorithm.CRC32))
.source(testFile.toPath())
.addTransferListener(LoggingTransferListener.create())
.addTransferListener(transferListener)
.build());
fileUpload.completionFuture().cancel(true);
assertThat(transferListener.isTransferInitiated()).isTrue();
assertThat(transferListener.isTransferComplete()).isFalse();
assertThat(transferListener.getExceptionCaught()).isInstanceOf(CancellationException.class);
assertThat(transferListener.getRatioTransferredList().get(transferListener.getRatioTransferredList().size() - 1))
.isNotEqualTo(100.0);
}
}
| 3,746 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/it/java/software/amazon/awssdk/transfer | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/it/java/software/amazon/awssdk/transfer/s3/S3TransferManagerUploadDirectoryIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import static software.amazon.awssdk.testutils.service.S3BucketUtils.temporaryBucketName;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import software.amazon.awssdk.core.sync.ResponseTransformer;
import software.amazon.awssdk.services.s3.model.NoSuchBucketException;
import software.amazon.awssdk.services.s3.model.S3Object;
import software.amazon.awssdk.testutils.FileUtils;
import software.amazon.awssdk.transfer.s3.model.CompletedDirectoryUpload;
import software.amazon.awssdk.transfer.s3.model.DirectoryUpload;
import software.amazon.awssdk.utils.Logger;
public class S3TransferManagerUploadDirectoryIntegrationTest extends S3IntegrationTestBase {
private static final Logger log = Logger.loggerFor(S3TransferManagerUploadDirectoryIntegrationTest.class);
private static final String TEST_BUCKET = temporaryBucketName(S3TransferManagerUploadDirectoryIntegrationTest.class);
private static Path directory;
private static String randomString;
@BeforeAll
public static void setUp() throws Exception {
createBucket(TEST_BUCKET);
randomString = RandomStringUtils.random(100);
directory = createLocalTestDirectory();
}
@AfterAll
public static void teardown() {
try {
FileUtils.cleanUpTestDirectory(directory);
} catch (Exception exception) {
log.warn(() -> "Failed to clean up test directory " + directory, exception);
}
try {
deleteBucketAndAllContents(TEST_BUCKET);
} catch (Exception exception) {
log.warn(() -> "Failed to delete s3 bucket " + TEST_BUCKET, exception);
}
}
@Test
void uploadDirectory_filesSentCorrectly() {
String prefix = "yolo";
DirectoryUpload uploadDirectory = tmCrt.uploadDirectory(u -> u.source(directory)
.bucket(TEST_BUCKET)
.s3Prefix(prefix));
CompletedDirectoryUpload completedDirectoryUpload = uploadDirectory.completionFuture().join();
assertThat(completedDirectoryUpload.failedTransfers()).isEmpty();
List<String> keys =
s3.listObjectsV2Paginator(b -> b.bucket(TEST_BUCKET).prefix(prefix)).contents().stream().map(S3Object::key)
.collect(Collectors.toList());
assertThat(keys).containsOnly(prefix + "/bar.txt", prefix + "/foo/1.txt", prefix + "/foo/2.txt");
keys.forEach(k -> verifyContent(k, k.substring(prefix.length() + 1) + randomString));
}
@Test
void uploadDirectory_nonExistsBucket_shouldAddFailedRequest() {
String prefix = "yolo";
DirectoryUpload uploadDirectory = tmCrt.uploadDirectory(u -> u.source(directory)
.bucket("nonExistingTestBucket" + UUID.randomUUID())
.s3Prefix(prefix));
CompletedDirectoryUpload completedDirectoryUpload = uploadDirectory.completionFuture().join();
assertThat(completedDirectoryUpload.failedTransfers()).hasSize(3).allSatisfy(f ->
assertThat(f.exception()).isInstanceOf(NoSuchBucketException.class));
}
@Test
void uploadDirectory_withDelimiter_filesSentCorrectly() {
String prefix = "hello";
String delimiter = "0";
DirectoryUpload uploadDirectory = tmCrt.uploadDirectory(u -> u.source(directory)
.bucket(TEST_BUCKET)
.s3Delimiter(delimiter)
.s3Prefix(prefix));
CompletedDirectoryUpload completedDirectoryUpload = uploadDirectory.completionFuture().join();
assertThat(completedDirectoryUpload.failedTransfers()).isEmpty();
List<String> keys =
s3.listObjectsV2Paginator(b -> b.bucket(TEST_BUCKET).prefix(prefix)).contents().stream().map(S3Object::key)
.collect(Collectors.toList());
assertThat(keys).containsOnly(prefix + "0bar.txt", prefix + "0foo01.txt", prefix + "0foo02.txt");
keys.forEach(k -> {
String path = k.replace(delimiter, "/");
verifyContent(k, path.substring(prefix.length() + 1) + randomString);
});
}
@Test
void uploadDirectory_withRequestTransformer_usesRequestTransformer() throws Exception {
String prefix = "requestTransformerTest";
Path newSourceForEachUpload = Paths.get(directory.toString(), "bar.txt");
CompletedDirectoryUpload result =
tmCrt.uploadDirectory(r -> r.source(directory)
.bucket(TEST_BUCKET)
.s3Prefix(prefix)
.uploadFileRequestTransformer(f -> f.source(newSourceForEachUpload)))
.completionFuture()
.get(10, TimeUnit.SECONDS);
assertThat(result.failedTransfers()).isEmpty();
s3.listObjectsV2Paginator(b -> b.bucket(TEST_BUCKET).prefix(prefix)).contents().forEach(object -> {
verifyContent(object.key(), "bar.txt" + randomString);
});
}
public static Collection<String> prefix() {
return Arrays.asList(
/* ASCII, 1-byte UTF-8 */
"E",
/* ASCII, 2-byte UTF-8 */
"É",
/* Non-ASCII, 2-byte UTF-8 */
"Ũ",
/* Non-ASCII, 3-byte UTF-8 */
"स",
/* Non-ASCII, 4-byte UTF-8 */
"\uD808\uDC8C"
);
}
/**
* Tests the behavior of traversing local directories with special Unicode characters in their path name. These characters have
* known to be problematic when using Java's old File API or with Windows (which uses UTF-16 for file-name encoding).
*/
@ParameterizedTest
@MethodSource("prefix")
void uploadDirectory_fileNameWithUnicode_traversedCorrectly(String directoryPrefix) throws IOException {
assumeTrue(Charset.defaultCharset().equals(StandardCharsets.UTF_8), "Ignoring the test if the test directory can't be "
+ "created");
Path testDirectory = null;
try {
log.info(() -> "Testing directory prefix: " + directoryPrefix);
log.info(() -> "UTF-8 bytes: " + Hex.encodeHexString(directoryPrefix.getBytes(StandardCharsets.UTF_8)));
log.info(() -> "UTF-16 bytes: " + Hex.encodeHexString(directoryPrefix.getBytes(StandardCharsets.UTF_16)));
testDirectory = createLocalTestDirectory(directoryPrefix);
Path finalTestDirectory = testDirectory;
DirectoryUpload uploadDirectory = tmCrt.uploadDirectory(u -> u.source(finalTestDirectory)
.bucket(TEST_BUCKET));
CompletedDirectoryUpload completedDirectoryUpload = uploadDirectory.completionFuture().join();
assertThat(completedDirectoryUpload.failedTransfers()).isEmpty();
List<String> keys = s3.listObjectsV2Paginator(b -> b.bucket(TEST_BUCKET))
.contents()
.stream()
.map(S3Object::key)
.collect(Collectors.toList());
assertThat(keys).containsOnly("bar.txt", "foo/1.txt", "foo/2.txt");
keys.forEach(k -> verifyContent(finalTestDirectory, k));
} finally {
FileUtils.cleanUpTestDirectory(testDirectory);
}
}
private static Path createLocalTestDirectory() throws IOException {
Path directory = Files.createTempDirectory("test");
String directoryName = directory.toString();
Files.createDirectory(Paths.get(directory + "/foo"));
Files.write(Paths.get(directoryName, "bar.txt"), ("bar.txt" + randomString).getBytes(StandardCharsets.UTF_8));
Files.write(Paths.get(directoryName, "foo/1.txt"), ("foo/1.txt" + randomString).getBytes(StandardCharsets.UTF_8));
Files.write(Paths.get(directoryName, "foo/2.txt"), ("foo/2.txt" + randomString).getBytes(StandardCharsets.UTF_8));
return directory;
}
private Path createLocalTestDirectory(String directoryPrefix) throws IOException {
Path dir = Files.createTempDirectory(directoryPrefix);
Files.createDirectory(Paths.get(dir + "/foo"));
Files.write(dir.resolve("bar.txt"), randomBytes(1024));
Files.write(dir.resolve("foo/1.txt"), randomBytes(1024));
Files.write(dir.resolve("foo/2.txt"), randomBytes(1024));
return dir;
}
private static void verifyContent(String key, String expectedContent) {
String actualContent = s3.getObject(r -> r.bucket(TEST_BUCKET).key(key),
ResponseTransformer.toBytes()).asUtf8String();
assertThat(actualContent).isEqualTo(expectedContent);
}
private void verifyContent(Path testDirectory, String key) {
try {
byte[] expectedContent = Files.readAllBytes(testDirectory.resolve(key));
byte[] actualContent = s3.getObject(r -> r.bucket(TEST_BUCKET).key(key), ResponseTransformer.toBytes()).asByteArray();
assertThat(actualContent).isEqualTo(expectedContent);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private static byte[] randomBytes(long size) {
byte[] bytes = new byte[Math.toIntExact(size)];
ThreadLocalRandom.current().nextBytes(bytes);
return bytes;
}
}
| 3,747 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/it/java/software/amazon/awssdk/transfer | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/it/java/software/amazon/awssdk/transfer/s3/S3TransferManagerCopyIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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;
import static org.assertj.core.api.Assertions.assertThat;
import static software.amazon.awssdk.testutils.service.S3BucketUtils.temporaryBucketName;
import static software.amazon.awssdk.transfer.s3.SizeConstant.MB;
import static software.amazon.awssdk.transfer.s3.util.ChecksumUtils.computeCheckSum;
import java.util.concurrent.ThreadLocalRandom;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.ResponseBytes;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.core.sync.ResponseTransformer;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.transfer.s3.model.CompletedCopy;
import software.amazon.awssdk.transfer.s3.model.Copy;
import software.amazon.awssdk.transfer.s3.progress.LoggingTransferListener;
public class S3TransferManagerCopyIntegrationTest extends S3IntegrationTestBase {
private static final String BUCKET = temporaryBucketName(S3TransferManagerCopyIntegrationTest.class);
private static final String ORIGINAL_OBJ = "test_file.dat";
private static final String COPIED_OBJ = "test_file_copy.dat";
private static final String ORIGINAL_OBJ_SPECIAL_CHARACTER = "original-special-chars-@$%";
private static final String COPIED_OBJ_SPECIAL_CHARACTER = "special-special-chars-@$%";
private static final long OBJ_SIZE = ThreadLocalRandom.current().nextLong(8 * MB, 16 * MB + 1);
@BeforeAll
public static void setUp() throws Exception {
createBucket(BUCKET);
}
@AfterAll
public static void teardown() throws Exception {
deleteBucketAndAllContents(BUCKET);
}
@Test
void copy_copiedObject_hasSameContent() {
byte[] originalContent = randomBytes(OBJ_SIZE);
createOriginalObject(originalContent, ORIGINAL_OBJ);
copyObject(ORIGINAL_OBJ, COPIED_OBJ);
validateCopiedObject(originalContent, ORIGINAL_OBJ);
}
@Test
void copy_specialCharacters_hasSameContent() {
byte[] originalContent = randomBytes(OBJ_SIZE);
createOriginalObject(originalContent, ORIGINAL_OBJ_SPECIAL_CHARACTER);
copyObject(ORIGINAL_OBJ_SPECIAL_CHARACTER, COPIED_OBJ_SPECIAL_CHARACTER);
validateCopiedObject(originalContent, COPIED_OBJ_SPECIAL_CHARACTER);
}
private void createOriginalObject(byte[] originalContent, String originalKey) {
s3.putObject(r -> r.bucket(BUCKET)
.key(originalKey),
RequestBody.fromBytes(originalContent));
}
private void copyObject(String original, String destination) {
Copy copy = tmCrt.copy(c -> c
.copyObjectRequest(r -> r
.sourceBucket(BUCKET)
.sourceKey(original)
.destinationBucket(BUCKET)
.destinationKey(destination))
.addTransferListener(LoggingTransferListener.create()));
CompletedCopy completedCopy = copy.completionFuture().join();
assertThat(completedCopy.response().responseMetadata().requestId()).isNotNull();
assertThat(completedCopy.response().sdkHttpResponse()).isNotNull();
}
private void validateCopiedObject(byte[] originalContent, String originalKey) {
ResponseBytes<GetObjectResponse> copiedObject = s3.getObject(r -> r.bucket(BUCKET)
.key(originalKey),
ResponseTransformer.toBytes());
assertThat(computeCheckSum(copiedObject.asByteArrayUnsafe())).isEqualTo(computeCheckSum(originalContent));
}
private static byte[] randomBytes(long size) {
byte[] bytes = new byte[Math.toIntExact(size)];
ThreadLocalRandom.current().nextBytes(bytes);
return bytes;
}
}
| 3,748 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/it/java/software/amazon/awssdk/transfer | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/it/java/software/amazon/awssdk/transfer/s3/S3TransferManagerDownloadIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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;
import static org.assertj.core.api.Assertions.assertThat;
import static software.amazon.awssdk.testutils.service.S3BucketUtils.temporaryBucketName;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.ResponseBytes;
import software.amazon.awssdk.core.async.AsyncResponseTransformer;
import software.amazon.awssdk.core.async.ResponsePublisher;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.testutils.RandomTempFile;
import software.amazon.awssdk.transfer.s3.model.CompletedDownload;
import software.amazon.awssdk.transfer.s3.model.CompletedFileDownload;
import software.amazon.awssdk.transfer.s3.model.Download;
import software.amazon.awssdk.transfer.s3.model.DownloadFileRequest;
import software.amazon.awssdk.transfer.s3.model.DownloadRequest;
import software.amazon.awssdk.transfer.s3.model.FileDownload;
import software.amazon.awssdk.transfer.s3.progress.LoggingTransferListener;
import software.amazon.awssdk.utils.Md5Utils;
public class S3TransferManagerDownloadIntegrationTest extends S3IntegrationTestBase {
private static final String BUCKET = temporaryBucketName(S3TransferManagerDownloadIntegrationTest.class);
private static final String KEY = "key";
private static final int OBJ_SIZE = 18 * 1024 * 1024;
private static File file;
@BeforeAll
public static void setup() throws IOException {
createBucket(BUCKET);
file = new RandomTempFile(OBJ_SIZE);
s3.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(KEY)
.build(), file.toPath());
}
@AfterAll
public static void cleanup() {
deleteBucketAndAllContents(BUCKET);
}
@Test
void download_toFile() throws Exception {
Path path = RandomTempFile.randomUncreatedFile().toPath();
FileDownload download =
tmCrt.downloadFile(DownloadFileRequest.builder()
.getObjectRequest(b -> b.bucket(BUCKET).key(KEY))
.destination(path)
.addTransferListener(LoggingTransferListener.create())
.build());
CompletedFileDownload completedFileDownload = download.completionFuture().get(1, TimeUnit.MINUTES);
assertThat(Md5Utils.md5AsBase64(path.toFile())).isEqualTo(Md5Utils.md5AsBase64(file));
assertThat(completedFileDownload.response().responseMetadata().requestId()).isNotNull();
}
@Test
void download_toFile_shouldReplaceExisting() throws IOException {
Path path = RandomTempFile.randomUncreatedFile().toPath();
Files.write(path, RandomStringUtils.random(1024).getBytes(StandardCharsets.UTF_8));
assertThat(path).exists();
FileDownload download =
tmCrt.downloadFile(DownloadFileRequest.builder()
.getObjectRequest(b -> b.bucket(BUCKET).key(KEY))
.destination(path)
.addTransferListener(LoggingTransferListener.create())
.build());
CompletedFileDownload completedFileDownload = download.completionFuture().join();
assertThat(Md5Utils.md5AsBase64(path.toFile())).isEqualTo(Md5Utils.md5AsBase64(file));
assertThat(completedFileDownload.response().responseMetadata().requestId()).isNotNull();
}
@Test
void download_toBytes() throws Exception {
Download<ResponseBytes<GetObjectResponse>> download =
tmCrt.download(DownloadRequest.builder()
.getObjectRequest(b -> b.bucket(BUCKET).key(KEY))
.responseTransformer(AsyncResponseTransformer.toBytes())
.addTransferListener(LoggingTransferListener.create())
.build());
CompletedDownload<ResponseBytes<GetObjectResponse>> completedDownload = download.completionFuture().join();
ResponseBytes<GetObjectResponse> result = completedDownload.result();
assertThat(Md5Utils.md5AsBase64(result.asByteArray())).isEqualTo(Md5Utils.md5AsBase64(file));
assertThat(result.response().responseMetadata().requestId()).isNotNull();
}
@Test
void download_toPublisher() throws Exception {
Download<ResponsePublisher<GetObjectResponse>> download =
tmCrt.download(DownloadRequest.builder()
.getObjectRequest(b -> b.bucket(BUCKET).key(KEY))
.responseTransformer(AsyncResponseTransformer.toPublisher())
.addTransferListener(LoggingTransferListener.create())
.build());
CompletedDownload<ResponsePublisher<GetObjectResponse>> completedDownload = download.completionFuture().join();
ResponsePublisher<GetObjectResponse> responsePublisher = completedDownload.result();
ByteBuffer buf = ByteBuffer.allocate(Math.toIntExact(responsePublisher.response().contentLength()));
CompletableFuture<Void> drainPublisherFuture = responsePublisher.subscribe(buf::put);
drainPublisherFuture.join();
assertThat(Md5Utils.md5AsBase64(buf.array())).isEqualTo(Md5Utils.md5AsBase64(file));
}
}
| 3,749 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/it/java/software/amazon/awssdk/transfer | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/it/java/software/amazon/awssdk/transfer/s3/S3IntegrationTestBase.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import software.amazon.awssdk.crt.CrtResource;
import software.amazon.awssdk.crt.Log;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.S3AsyncClientBuilder;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.S3ClientBuilder;
import software.amazon.awssdk.services.s3.internal.crt.S3CrtAsyncClient;
import software.amazon.awssdk.services.s3.model.BucketLocationConstraint;
import software.amazon.awssdk.services.s3.model.CreateBucketConfiguration;
import software.amazon.awssdk.services.s3.model.CreateBucketRequest;
import software.amazon.awssdk.services.s3.model.DeleteBucketRequest;
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
import software.amazon.awssdk.services.s3.model.HeadObjectRequest;
import software.amazon.awssdk.services.s3.model.ListObjectVersionsRequest;
import software.amazon.awssdk.services.s3.model.ListObjectVersionsResponse;
import software.amazon.awssdk.services.s3.model.ListObjectsRequest;
import software.amazon.awssdk.services.s3.model.ListObjectsResponse;
import software.amazon.awssdk.services.s3.model.ObjectVersion;
import software.amazon.awssdk.services.s3.model.S3Exception;
import software.amazon.awssdk.services.s3.model.S3Object;
import software.amazon.awssdk.testutils.service.AwsTestBase;
/**
* Base class for S3 integration tests. Loads AWS credentials from a properties
* file and creates an S3 client for callers to use.
*/
public class S3IntegrationTestBase extends AwsTestBase {
protected static final Region DEFAULT_REGION = Region.US_WEST_1;
/**
* The S3 client for all tests to use.
*/
protected static S3Client s3;
protected static S3AsyncClient s3Async;
protected static S3AsyncClient s3CrtAsync;
protected static S3TransferManager tmCrt;
protected static S3TransferManager tmJava;
/**
* Loads the AWS account info for the integration tests and creates an S3
* client for tests to use.
*/
@BeforeAll
public static void setUpForAllIntegTests() throws Exception {
Log.initLoggingToStdout(Log.LogLevel.Warn);
System.setProperty("aws.crt.debugnative", "true");
s3 = s3ClientBuilder().build();
s3Async = s3AsyncClientBuilder().build();
s3CrtAsync = S3CrtAsyncClient.builder()
.credentialsProvider(CREDENTIALS_PROVIDER_CHAIN)
.region(DEFAULT_REGION)
.build();
tmCrt = S3TransferManager.builder()
.s3Client(s3CrtAsync)
.build();
tmJava = S3TransferManager.builder()
.s3Client(s3Async)
.build();
}
@AfterAll
public static void cleanUpForAllIntegTests() {
s3.close();
s3Async.close();
s3CrtAsync.close();
tmCrt.close();
CrtResource.waitForNoResources();
}
protected static S3ClientBuilder s3ClientBuilder() {
return S3Client.builder()
.region(DEFAULT_REGION)
.credentialsProvider(CREDENTIALS_PROVIDER_CHAIN);
}
protected static S3AsyncClientBuilder s3AsyncClientBuilder() {
return S3AsyncClient.builder()
.region(DEFAULT_REGION)
.credentialsProvider(CREDENTIALS_PROVIDER_CHAIN);
}
protected static void createBucket(String bucketName) {
createBucket(bucketName, 0);
s3.waiter().waitUntilBucketExists(b -> b.bucket(bucketName));
}
private static void createBucket(String bucketName, int retryCount) {
try {
s3.createBucket(
CreateBucketRequest.builder()
.bucket(bucketName)
.createBucketConfiguration(
CreateBucketConfiguration.builder()
.locationConstraint(BucketLocationConstraint.US_WEST_1)
.build())
.build());
} catch (S3Exception e) {
System.err.println("Error attempting to create bucket: " + bucketName);
if (e.awsErrorDetails().errorCode().equals("BucketAlreadyOwnedByYou")) {
System.err.printf("%s bucket already exists, likely leaked by a previous run\n", bucketName);
} else if (e.awsErrorDetails().errorCode().equals("TooManyBuckets")) {
System.err.println("Error: TooManyBuckets. Printing all buckets for debug:");
s3.listBuckets().buckets().forEach(System.err::println);
if (retryCount < 2) {
System.err.println("Retrying...");
createBucket(bucketName, retryCount + 1);
} else {
throw e;
}
} else {
throw e;
}
}
}
protected static void deleteBucketAndAllContents(String bucketName) {
System.out.println("Deleting S3 bucket: " + bucketName);
ListObjectsResponse response = s3.listObjects(ListObjectsRequest.builder().bucket(bucketName).build());
while (true) {
if (response.contents() == null) {
break;
}
for (S3Object objectSummary : response.contents()) {
s3.deleteObject(DeleteObjectRequest.builder().bucket(bucketName).key(objectSummary.key()).build());
s3.waiter().waitUntilObjectNotExists(HeadObjectRequest.builder().bucket(bucketName).key(objectSummary.key()).build());
}
if (response.isTruncated()) {
response = s3.listObjects(ListObjectsRequest.builder().marker(response.nextMarker()).build());
} else {
break;
}
}
ListObjectVersionsResponse versionsResponse = s3
.listObjectVersions(ListObjectVersionsRequest.builder().bucket(bucketName).build());
if (versionsResponse.versions() != null) {
for (ObjectVersion s : versionsResponse.versions()) {
s3.deleteObject(DeleteObjectRequest.builder()
.bucket(bucketName)
.key(s.key())
.versionId(s.versionId())
.build());
}
}
s3.deleteBucket(DeleteBucketRequest.builder().bucket(bucketName).build());
}
}
| 3,750 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/it/java/software/amazon/awssdk/transfer | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/it/java/software/amazon/awssdk/transfer/s3/S3TransferManagerUploadPauseResumeIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy;
import static software.amazon.awssdk.testutils.service.S3BucketUtils.temporaryBucketName;
import static software.amazon.awssdk.transfer.s3.SizeConstant.MB;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.time.Duration;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.retry.backoff.FixedDelayBackoffStrategy;
import software.amazon.awssdk.core.waiters.AsyncWaiter;
import software.amazon.awssdk.core.waiters.Waiter;
import software.amazon.awssdk.core.waiters.WaiterAcceptor;
import software.amazon.awssdk.services.s3.model.ListMultipartUploadsResponse;
import software.amazon.awssdk.services.s3.model.ListPartsResponse;
import software.amazon.awssdk.services.s3.model.NoSuchUploadException;
import software.amazon.awssdk.testutils.RandomTempFile;
import software.amazon.awssdk.transfer.s3.model.FileUpload;
import software.amazon.awssdk.transfer.s3.model.ResumableFileUpload;
import software.amazon.awssdk.transfer.s3.model.UploadFileRequest;
import software.amazon.awssdk.transfer.s3.progress.LoggingTransferListener;
import software.amazon.awssdk.utils.Logger;
public class S3TransferManagerUploadPauseResumeIntegrationTest extends S3IntegrationTestBase {
private static final Logger log = Logger.loggerFor(S3TransferManagerUploadPauseResumeIntegrationTest.class);
private static final String BUCKET = temporaryBucketName(S3TransferManagerUploadPauseResumeIntegrationTest.class);
private static final String KEY = "key";
// 24 * MB is chosen to make sure we have data written in the file already upon pausing.
private static final long OBJ_SIZE = 24 * MB;
private static File largeFile;
private static File smallFile;
private static ScheduledExecutorService executorService;
@BeforeAll
public static void setup() throws Exception {
createBucket(BUCKET);
largeFile = new RandomTempFile(OBJ_SIZE);
smallFile = new RandomTempFile(2 * MB);
executorService = Executors.newScheduledThreadPool(3);
}
@AfterAll
public static void cleanup() {
deleteBucketAndAllContents(BUCKET);
largeFile.delete();
smallFile.delete();
executorService.shutdown();
}
@Test
void pause_singlePart_shouldResume() {
UploadFileRequest request = UploadFileRequest.builder()
.putObjectRequest(b -> b.bucket(BUCKET).key(KEY))
.source(smallFile)
.build();
FileUpload fileUpload = tmCrt.uploadFile(request);
ResumableFileUpload resumableFileUpload = fileUpload.pause();
log.debug(() -> "Paused: " + resumableFileUpload);
validateEmptyResumeToken(resumableFileUpload);
FileUpload resumedUpload = tmCrt.resumeUploadFile(resumableFileUpload);
resumedUpload.completionFuture().join();
}
@Test
void pause_fileNotChanged_shouldResume() {
UploadFileRequest request = UploadFileRequest.builder()
.putObjectRequest(b -> b.bucket(BUCKET).key(KEY))
.addTransferListener(LoggingTransferListener.create())
.source(largeFile)
.build();
FileUpload fileUpload = tmCrt.uploadFile(request);
waitUntilMultipartUploadExists();
ResumableFileUpload resumableFileUpload = fileUpload.pause();
log.debug(() -> "Paused: " + resumableFileUpload);
assertThat(resumableFileUpload.multipartUploadId()).isNotEmpty();
assertThat(resumableFileUpload.partSizeInBytes()).isNotEmpty();
assertThat(resumableFileUpload.totalParts()).isNotEmpty();
verifyMultipartUploadIdExists(resumableFileUpload);
FileUpload resumedUpload = tmCrt.resumeUploadFile(resumableFileUpload);
resumedUpload.completionFuture().join();
}
@Test
void pauseImmediately_resume_shouldStartFromBeginning() {
UploadFileRequest request = UploadFileRequest.builder()
.putObjectRequest(b -> b.bucket(BUCKET).key(KEY))
.source(largeFile)
.build();
FileUpload fileUpload = tmCrt.uploadFile(request);
ResumableFileUpload resumableFileUpload = fileUpload.pause();
log.debug(() -> "Paused: " + resumableFileUpload);
validateEmptyResumeToken(resumableFileUpload);
FileUpload resumedUpload = tmCrt.resumeUploadFile(resumableFileUpload);
resumedUpload.completionFuture().join();
}
@Test
void pause_fileChanged_resumeShouldStartFromBeginning() throws Exception {
UploadFileRequest request = UploadFileRequest.builder()
.putObjectRequest(b -> b.bucket(BUCKET).key(KEY))
.source(largeFile)
.build();
FileUpload fileUpload = tmCrt.uploadFile(request);
waitUntilMultipartUploadExists();
ResumableFileUpload resumableFileUpload = fileUpload.pause();
log.debug(() -> "Paused: " + resumableFileUpload);
assertThat(resumableFileUpload.multipartUploadId()).isNotEmpty();
assertThat(resumableFileUpload.partSizeInBytes()).isNotEmpty();
assertThat(resumableFileUpload.totalParts()).isNotEmpty();
verifyMultipartUploadIdExists(resumableFileUpload);
byte[] bytes = "helloworld".getBytes(StandardCharsets.UTF_8);
Files.write(largeFile.toPath(), bytes);
FileUpload resumedUpload = tmCrt.resumeUploadFile(resumableFileUpload);
resumedUpload.completionFuture().join();
verifyMultipartUploadIdNotExist(resumableFileUpload);
assertThat(resumedUpload.progress().snapshot().totalBytes()).hasValue(bytes.length);
}
private void verifyMultipartUploadIdExists(ResumableFileUpload resumableFileUpload) {
String multipartUploadId = resumableFileUpload.multipartUploadId().get();
ListPartsResponse listMultipartUploadsResponse =
s3Async.listParts(r -> r.uploadId(multipartUploadId).bucket(BUCKET).key(KEY)).join();
assertThat(listMultipartUploadsResponse).isNotNull();
}
private void verifyMultipartUploadIdNotExist(ResumableFileUpload resumableFileUpload) {
String multipartUploadId = resumableFileUpload.multipartUploadId().get();
AsyncWaiter<ListPartsResponse> waiter = AsyncWaiter.builder(ListPartsResponse.class)
.addAcceptor(WaiterAcceptor.successOnExceptionAcceptor(e -> e instanceof NoSuchUploadException))
.addAcceptor(WaiterAcceptor.retryOnResponseAcceptor(r -> true))
.overrideConfiguration(o -> o.waitTimeout(Duration.ofMinutes(1)))
.scheduledExecutorService(executorService)
.build();
waiter.runAsync(() -> s3Async.listParts(r -> r.uploadId(multipartUploadId).bucket(BUCKET).key(KEY)));
}
private static void waitUntilMultipartUploadExists() {
Waiter<ListMultipartUploadsResponse> waiter = Waiter.builder(ListMultipartUploadsResponse.class)
.addAcceptor(WaiterAcceptor.successOnResponseAcceptor(ListMultipartUploadsResponse::hasUploads))
.addAcceptor(WaiterAcceptor.retryOnResponseAcceptor(r -> true))
.overrideConfiguration(o -> o.waitTimeout(Duration.ofMinutes(1))
.maxAttempts(10)
.backoffStrategy(FixedDelayBackoffStrategy.create(Duration.ofMillis(100))))
.build();
waiter.run(() -> s3.listMultipartUploads(l -> l.bucket(BUCKET)));
}
private static void validateEmptyResumeToken(ResumableFileUpload resumableFileUpload) {
assertThat(resumableFileUpload.multipartUploadId()).isEmpty();
assertThat(resumableFileUpload.partSizeInBytes()).isEmpty();
assertThat(resumableFileUpload.totalParts()).isEmpty();
assertThat(resumableFileUpload.transferredParts()).isEmpty();
}
}
| 3,751 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/SizeConstant.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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;
import software.amazon.awssdk.annotations.SdkPublicApi;
/**
* Helpful constants for common size units.
*/
@SdkPublicApi
public final class SizeConstant {
/**
* 1 Kibibyte
* */
public static final long KB = 1024;
/**
* 1 Mebibyte.
*/
public static final long MB = 1024 * KB;
/**
* 1 Gibibyte.
*/
public static final long GB = 1024 * MB;
private SizeConstant() {
}
}
| 3,752 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/S3TransferManager.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.function.Consumer;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.core.async.AsyncResponseTransformer;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.S3CrtAsyncClientBuilder;
import software.amazon.awssdk.services.s3.model.CopyObjectRequest;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.UploadPartCopyRequest;
import software.amazon.awssdk.transfer.s3.internal.TransferManagerFactory;
import software.amazon.awssdk.transfer.s3.model.CompletedDirectoryDownload;
import software.amazon.awssdk.transfer.s3.model.CompletedDirectoryUpload;
import software.amazon.awssdk.transfer.s3.model.Copy;
import software.amazon.awssdk.transfer.s3.model.CopyRequest;
import software.amazon.awssdk.transfer.s3.model.DirectoryDownload;
import software.amazon.awssdk.transfer.s3.model.DirectoryUpload;
import software.amazon.awssdk.transfer.s3.model.Download;
import software.amazon.awssdk.transfer.s3.model.DownloadDirectoryRequest;
import software.amazon.awssdk.transfer.s3.model.DownloadFileRequest;
import software.amazon.awssdk.transfer.s3.model.DownloadRequest;
import software.amazon.awssdk.transfer.s3.model.FileDownload;
import software.amazon.awssdk.transfer.s3.model.FileUpload;
import software.amazon.awssdk.transfer.s3.model.ResumableFileDownload;
import software.amazon.awssdk.transfer.s3.model.ResumableFileUpload;
import software.amazon.awssdk.transfer.s3.model.Upload;
import software.amazon.awssdk.transfer.s3.model.UploadDirectoryRequest;
import software.amazon.awssdk.transfer.s3.model.UploadFileRequest;
import software.amazon.awssdk.transfer.s3.model.UploadRequest;
import software.amazon.awssdk.transfer.s3.progress.LoggingTransferListener;
import software.amazon.awssdk.transfer.s3.progress.TransferListener;
import software.amazon.awssdk.utils.SdkAutoCloseable;
import software.amazon.awssdk.utils.Validate;
/**
* The S3 Transfer Manager offers a simple API that allows you to transfer a single object or a set of objects to and
* from Amazon S3 with enhanced throughput and reliability. It leverages Amazon S3 multipart upload and
* byte-range fetches to perform transfers in parallel. In addition, the S3 Transfer Manager also enables you to
* monitor a transfer's progress in real-time, as well as pause the transfer for execution at a later time.
*
* <h2>Instantiate the S3 Transfer Manager</h2>
* <b>Create a transfer manager instance with SDK default settings. Note that it's recommended
* to add {@code software.amazon.awssdk.crt:aws-crt} dependency so that automatic multipart feature can be enabled</b>
* {@snippet :
* S3TransferManager transferManager = S3TransferManager.create();
* }
* <b>Create an S3 Transfer Manager instance with custom settings</b>
* {@snippet :
* S3AsyncClient s3AsyncClient = S3AsyncClient.crtBuilder()
* .credentialsProvider(DefaultCredentialsProvider.create())
* .region(Region.US_WEST_2)
* .targetThroughputInGbps(20.0)
* .minimumPartSizeInBytes(8 * MB)
* .build();
*
* S3TransferManager transferManager =
* S3TransferManager.builder()
* .s3AsyncClient(s3AsyncClient)
* .build();
* }
* <h2>Common Usage Patterns</h2>
* <b>Upload a file to S3</b>
* {@snippet :
* S3TransferManager transferManager = S3TransferManager.create();
*
* UploadFileRequest uploadFileRequest = UploadFileRequest.builder()
* .putObjectRequest(req -> req.bucket("bucket").key("key"))
* .addTransferListener(LoggingTransferListener.create())
* .source(Paths.get("myFile.txt"))
* .build();
*
* FileUpload upload = transferManager.uploadFile(uploadFileRequest);
* upload.completionFuture().join();
* }
* <b>Download an S3 object to a local file</b>
* {@snippet :
* S3TransferManager transferManager = S3TransferManager.create();
*
* DownloadFileRequest downloadFileRequest =
* DownloadFileRequest.builder()
* .getObjectRequest(req -> req.bucket("bucket").key("key"))
* .destination(Paths.get("myFile.txt"))
* .addTransferListener(LoggingTransferListener.create())
* .build();
*
* FileDownload download = transferManager.downloadFile(downloadFileRequest);
*
* // Wait for the transfer to complete
* download.completionFuture().join();
* }
* <b>Upload a local directory to an S3 bucket</b>
* {@snippet :
* S3TransferManager transferManager = S3TransferManager.create();
* DirectoryUpload directoryUpload =
* transferManager.uploadDirectory(UploadDirectoryRequest.builder()
* .source(Paths.get("source/directory"))
* .bucket("bucket")
* .s3Prefix("prefix")
* .build());
*
* // Wait for the transfer to complete
* CompletedDirectoryUpload completedDirectoryUpload = directoryUpload.completionFuture().join();
*
* // Print out any failed uploads
* completedDirectoryUpload.failedTransfers().forEach(System.out::println);
* }
* <b>Download S3 objects to a local directory</b>
* {@snippet :
* S3TransferManager transferManager = S3TransferManager.create();
* DirectoryDownload directoryDownload =
* transferManager.downloadDirectory(
* DownloadDirectoryRequest.builder()
* .destination(Paths.get("destination/directory"))
* .bucket("bucket")
* .listObjectsV2RequestTransformer(l -> l.prefix("prefix"))
* .build());
* // Wait for the transfer to complete
* CompletedDirectoryDownload completedDirectoryDownload = directoryDownload.completionFuture().join();
*
* // Print out any failed downloads
* completedDirectoryDownload.failedTransfers().forEach(System.out::println);
* }
* <b>Copy an S3 object to a different location in S3</b>
* {@snippet :
* S3TransferManager transferManager = S3TransferManager.create();
* CopyObjectRequest copyObjectRequest = CopyObjectRequest.builder()
* .sourceBucket("source_bucket")
* .sourceKey("source_key")
* .destinationBucket("dest_bucket")
* .destinationKey("dest_key")
* .build();
* CopyRequest copyRequest = CopyRequest.builder()
* .copyObjectRequest(copyObjectRequest)
* .build();
*
* Copy copy = transferManager.copy(copyRequest);
* // Wait for the transfer to complete
* CompletedCopy completedCopy = copy.completionFuture().join();
* }
*/
@SdkPublicApi
@ThreadSafe
public interface S3TransferManager extends SdkAutoCloseable {
/**
* Downloads an object identified by the bucket and key from S3 to a local file. For non-file-based downloads, you may use
* {@link #download(DownloadRequest)} instead.
* <p>
* The SDK will create a new file if the provided one doesn't exist. The default permission for the new file depends on
* the file system and platform. Users can configure the permission on the file using Java API by themselves.
* If the file already exists, the SDK will replace it. In the event of an error, the SDK will <b>NOT</b> attempt to delete
* the file, leaving it as-is.
* <p>
* Users can monitor the progress of the transfer by attaching a {@link TransferListener}. The provided
* {@link LoggingTransferListener} logs a basic progress bar; users can also implement their own listeners.
* <p>
*
* <b>Usage Example:</b>
* {@snippet :
* S3TransferManager transferManager = S3TransferManager.create();
*
* DownloadFileRequest downloadFileRequest =
* DownloadFileRequest.builder()
* .getObjectRequest(req -> req.bucket("bucket").key("key"))
* .destination(Paths.get("myFile.txt"))
* .addTransferListener(LoggingTransferListener.create())
* .build();
*
* FileDownload download = transferManager.downloadFile(downloadFileRequest);
*
* // Wait for the transfer to complete
* download.completionFuture().join();
* }
*
* @see #downloadFile(Consumer)
* @see #download(DownloadRequest)
*/
default FileDownload downloadFile(DownloadFileRequest downloadRequest) {
throw new UnsupportedOperationException();
}
/**
* 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()}.
*
* @see #downloadFile(DownloadFileRequest)
*/
default FileDownload downloadFile(Consumer<DownloadFileRequest.Builder> request) {
return downloadFile(DownloadFileRequest.builder().applyMutation(request).build());
}
/**
* Resumes a downloadFile operation. This download operation uses the same configuration as the original download. Any content
* that has already been fetched since the last pause will be skipped and only the remaining data will be downloaded from
* Amazon S3.
*
* <p>
* If it is determined that the source S3 object or the destination file has be modified since the last pause, the SDK
* will download the object from the beginning as if it is a new {@link DownloadFileRequest}.
*
* <p>
* <b>Usage Example:</b>
* {@snippet :
* S3TransferManager transferManager = S3TransferManager.create();
*
* DownloadFileRequest downloadFileRequest = DownloadFileRequest.builder()
* .getObjectRequest(req -> req.bucket("bucket").key
* ("key"))
* .destination(Paths.get("myFile.txt"))
* .build();
*
* // Initiate the transfer
* FileDownload download =
* transferManager.downloadFile(downloadFileRequest);
*
* // Pause the download
* ResumableFileDownload resumableFileDownload = download.pause();
*
* // Optionally, persist the download object
* Path path = Paths.get("resumableFileDownload.json");
* resumableFileDownload.serializeToFile(path);
*
* // Retrieve the resumableFileDownload from the file
* resumableFileDownload = ResumableFileDownload.fromFile(path);
*
* // Resume the download
* FileDownload resumedDownload = transferManager.resumeDownloadFile(resumableFileDownload);
*
* // Wait for the transfer to complete
* resumedDownload.completionFuture().join();
* }
*
* @param resumableFileDownload the download to resume.
* @return A new {@code FileDownload} object to use to check the state of the download.
* @see #downloadFile(DownloadFileRequest)
* @see FileDownload#pause()
*/
default FileDownload resumeDownloadFile(ResumableFileDownload resumableFileDownload) {
throw new UnsupportedOperationException();
}
/**
* This is a convenience method that creates an instance of the {@link ResumableFileDownload} builder, avoiding the need to
* create one manually via {@link ResumableFileDownload#builder()}.
*
* @see #resumeDownloadFile(ResumableFileDownload)
*/
default FileDownload resumeDownloadFile(Consumer<ResumableFileDownload.Builder> resumableFileDownload) {
return resumeDownloadFile(ResumableFileDownload.builder().applyMutation(resumableFileDownload).build());
}
/**
* Downloads an object identified by the bucket and key from S3 through the given {@link AsyncResponseTransformer}. For
* downloading to a file, you may use {@link #downloadFile(DownloadFileRequest)} instead.
* <p>
* Users can monitor the progress of the transfer by attaching a {@link TransferListener}. The provided
* {@link LoggingTransferListener} logs a basic progress bar; users can also implement their own listeners.
*
* <p>
* <b>Usage Example (this example buffers the entire object in memory and is not suitable for large objects):</b>
*
* {@snippet :
* S3TransferManager transferManager = S3TransferManager.create();
*
* DownloadRequest<ResponseBytes<GetObjectResponse>> downloadRequest =
* DownloadRequest.builder()
* .getObjectRequest(req -> req.bucket("bucket").key("key"))
* .responseTransformer(AsyncResponseTransformer.toBytes())
* .build();
*
* // Initiate the transfer
* Download<ResponseBytes<GetObjectResponse>> download =
* transferManager.download(downloadRequest);
* // Wait for the transfer to complete
* download.completionFuture().join();
* }
*
* <p>
* See the static factory methods available in {@link AsyncResponseTransformer} for other use cases.
*
* @param downloadRequest the download request, containing a {@link GetObjectRequest} and {@link AsyncResponseTransformer}
* @param <ResultT> The type of data the {@link AsyncResponseTransformer} produces
* @return A {@link Download} that can be used to track the ongoing transfer
* @see #downloadFile(DownloadFileRequest)
*/
default <ResultT> Download<ResultT> download(DownloadRequest<ResultT> downloadRequest) {
throw new UnsupportedOperationException();
}
/**
* Uploads a local file to an object in S3. For non-file-based uploads, you may use {@link #upload(UploadRequest)} instead.
* <p>
* Users can monitor the progress of the transfer by attaching a {@link TransferListener}. The provided
* {@link LoggingTransferListener} logs a basic progress bar; users can also implement their own listeners.
*
* Upload a local file to an object in S3. For non-file-based uploads, you may use {@link #upload(UploadRequest)} instead.
* <p>
* <b>Usage Example:</b>
* {@snippet :
* S3TransferManager transferManager = S3TransferManager.create();
*
* UploadFileRequest uploadFileRequest = UploadFileRequest.builder()
* .putObjectRequest(req -> req.bucket("bucket").key("key"))
* .addTransferListener(LoggingTransferListener.create())
* .source(Paths.get("myFile.txt"))
* .build();
*
* FileUpload upload = transferManager.uploadFile(uploadFileRequest);
* upload.completionFuture().join();
* }
*
* @see #uploadFile(Consumer)
* @see #upload(UploadRequest)
*/
default FileUpload uploadFile(UploadFileRequest uploadFileRequest) {
throw new UnsupportedOperationException();
}
/**
* 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()}.
*
* @see #uploadFile(UploadFileRequest)
*/
default FileUpload uploadFile(Consumer<UploadFileRequest.Builder> request) {
return uploadFile(UploadFileRequest.builder().applyMutation(request).build());
}
/**
* Resumes uploadFile operation. This upload operation will use the same configuration provided in
* {@link ResumableFileUpload}. The SDK will skip the data that has already been upload since the last pause
* and only upload the remaining data from the source file.
* <p>
* If it is determined that the source file has be modified since the last pause, the SDK will upload the object from the
* beginning as if it is a new {@link UploadFileRequest}.
*
* <p>
* <b>Usage Example:</b>
* {@snippet :
* S3TransferManager transferManager = S3TransferManager.create();
*
* UploadFileRequest uploadFileRequest = UploadFileRequest.builder()
* .putObjectRequest(req -> req.bucket("bucket").key("key"))
* .source(Paths.get("myFile.txt"))
* .build();
*
* // Initiate the transfer
* FileUpload upload =
* transferManager.uploadFile(uploadFileRequest);
* // Pause the upload
* ResumableFileUpload resumableFileUpload = upload.pause();
*
* // Optionally, persist the resumableFileUpload
* Path path = Paths.get("resumableFileUpload.json");
* resumableFileUpload.serializeToFile(path);
*
* // Retrieve the resumableFileUpload from the file
* ResumableFileUpload persistedResumableFileUpload = ResumableFileUpload.fromFile(path);
*
* // Resume the upload
* FileUpload resumedUpload = transferManager.resumeUploadFile(persistedResumableFileUpload);
*
* // Wait for the transfer to complete
* resumedUpload.completionFuture().join();
* }
*
* @param resumableFileUpload the upload to resume.
* @return A new {@code FileUpload} object to use to check the state of the download.
* @see #uploadFile(UploadFileRequest)
* @see FileUpload#pause()
*/
default FileUpload resumeUploadFile(ResumableFileUpload resumableFileUpload) {
throw new UnsupportedOperationException();
}
/**
* This is a convenience method that creates an instance of the {@link ResumableFileUpload} builder, avoiding the need to
* create one manually via {@link ResumableFileUpload#builder()}.
*
* @see #resumeUploadFile(ResumableFileUpload)
*/
default FileUpload resumeUploadFile(Consumer<ResumableFileUpload.Builder> resumableFileUpload) {
return resumeUploadFile(ResumableFileUpload.builder().applyMutation(resumableFileUpload).build());
}
/**
* Uploads the given {@link AsyncRequestBody} to an object in S3. For file-based uploads, you may use
* {@link #uploadFile(UploadFileRequest)} instead.
*
* <p>
* Users can monitor the progress of the transfer by attaching a {@link TransferListener}. The provided
* {@link LoggingTransferListener} logs a basic progress bar; users can also implement their own listeners.
*
* <p>
* <b>Usage Example:</b>
* {@snippet :
* S3TransferManager transferManager = S3TransferManager.create();
*
* UploadRequest uploadRequest = UploadRequest.builder()
* .requestBody(AsyncRequestBody.fromString("Hello world"))
* .putObjectRequest(req -> req.bucket("bucket").key("key"))
* .build();
*
* Upload upload = transferManager.upload(uploadRequest);
* // Wait for the transfer to complete
* upload.completionFuture().join();
* }
*
* See the static factory methods available in {@link AsyncRequestBody} for other use cases.
*
* @param uploadRequest the upload request, containing a {@link PutObjectRequest} and {@link AsyncRequestBody}
* @return An {@link Upload} that can be used to track the ongoing transfer
* @see #upload(Consumer)
* @see #uploadFile(UploadFileRequest)
*/
default Upload upload(UploadRequest uploadRequest) {
throw new UnsupportedOperationException();
}
/**
* This is a convenience method that creates an instance of the {@link UploadRequest} builder, avoiding the need to create one
* manually via {@link UploadRequest#builder()}.
*
* @see #upload(UploadRequest)
*/
default Upload upload(Consumer<UploadRequest.Builder> request) {
return upload(UploadRequest.builder().applyMutation(request).build());
}
/**
* Uploads all files under the given directory to the provided S3 bucket. The key name transformation depends on the optional
* prefix and delimiter provided in the {@link UploadDirectoryRequest}. By default, all subdirectories will be uploaded
* recursively, and symbolic links are not followed automatically.
* This behavior can be configured in at request level via
* {@link UploadDirectoryRequest.Builder#followSymbolicLinks(Boolean)} or
* client level via {@link S3TransferManager.Builder#uploadDirectoryFollowSymbolicLinks(Boolean)}
* Note that request-level configuration takes precedence over client-level configuration.
* <p>
* By default, the prefix is an empty string and the delimiter is {@code "/"}. Assume you have a local
* directory "/test" with the following structure:
* <pre>
* {@code
* |- test
* |- sample.jpg
* |- photos
* |- 2022
* |- January
* |- sample.jpg
* |- February
* |- sample1.jpg
* |- sample2.jpg
* |- sample3.jpg
* }
* </pre>
* Give a request to upload directory "/test" to an S3 bucket, the target bucket will have the following
* S3 objects:
* <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>
* <p>
* The returned {@link CompletableFuture} only completes exceptionally if the request cannot be attempted as a whole (the
* source directory provided does not exist for example). The future completes successfully for partial successful
* requests, i.e., there might be failed uploads in the successfully completed response. As a result,
* you should check for errors in the response via {@link CompletedDirectoryUpload#failedTransfers()}
* even when the future completes successfully.
*
* <p>
* The current user must have read access to all directories and files.
*
* <p>
* <b>Usage Example:</b>
* {@snippet :
* S3TransferManager transferManager = S3TransferManager.create();
* DirectoryUpload directoryUpload =
* transferManager.uploadDirectory(UploadDirectoryRequest.builder()
* .source(Paths.get("source/directory"))
* .bucket("bucket")
* .s3Prefix("prefix")
* .build());
*
* // Wait for the transfer to complete
* CompletedDirectoryUpload completedDirectoryUpload = directoryUpload.completionFuture().join();
*
* // Print out any failed uploads
* completedDirectoryUpload.failedTransfers().forEach(System.out::println);
* }
*
* @param uploadDirectoryRequest the upload directory request
* @see #uploadDirectory(Consumer)
*/
default DirectoryUpload uploadDirectory(UploadDirectoryRequest uploadDirectoryRequest) {
throw new UnsupportedOperationException();
}
/**
* This is a convenience method that creates an instance of the {@link UploadDirectoryRequest} builder, avoiding the need to
* create one manually via {@link UploadDirectoryRequest#builder()}.
*
* @see #uploadDirectory(UploadDirectoryRequest)
*/
default DirectoryUpload uploadDirectory(Consumer<UploadDirectoryRequest.Builder> requestBuilder) {
Validate.paramNotNull(requestBuilder, "requestBuilder");
return uploadDirectory(UploadDirectoryRequest.builder().applyMutation(requestBuilder).build());
}
/**
* Downloads all objects under a bucket to the provided directory. By default, all objects in the entire
* bucket will be downloaded. You can modify this behavior by providing a
* {@link DownloadDirectoryRequest#listObjectsRequestTransformer()} and/or
* a {@link DownloadDirectoryRequest#filter()} in {@link DownloadDirectoryRequest} to
* limit the S3 objects to download.
*
* <p>
* The downloaded directory structure will match with the provided S3 virtual bucket.
* 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>
* Give a request to download the bucket to a destination with path of "/test", 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>
* <p>
* The returned {@link CompletableFuture} only completes exceptionally if the request cannot be attempted as a whole (the
* downloadDirectoryRequest is invalid for example). The future completes successfully for partial successful
* requests, i.e., there might be failed downloads in a successfully completed response. As a result, you should check for
* errors in the response via {@link CompletedDirectoryDownload#failedTransfers()} even when the future completes
* successfully.
*
* <p>
* The SDK will create the destination directory if it does not already exist. If a specific file
* already exists, the existing content will be replaced with the corresponding S3 object content.
*
* <p>
* The current user must have write access to all directories and files
*
* <p>
* <b>Usage Example:</b>
* {@snippet :
* S3TransferManager transferManager = S3TransferManager.create();
* DirectoryDownload directoryDownload =
* transferManager.downloadDirectory(
* DownloadDirectoryRequest.builder()
* .destination(Paths.get("destination/directory"))
* .bucket("bucket")
* // only download objects with prefix "photos"
* .listObjectsV2RequestTransformer(l -> l.prefix("photos"))
* .build());
* // Wait for the transfer to complete
* CompletedDirectoryDownload completedDirectoryDownload = directoryDownload.completionFuture().join();
*
* // Print out any failed downloads
* completedDirectoryDownload.failedTransfers().forEach(System.out::println);
* }
*
* @param downloadDirectoryRequest the download directory request
* @see #downloadDirectory(Consumer)
*/
default DirectoryDownload downloadDirectory(DownloadDirectoryRequest downloadDirectoryRequest) {
throw new UnsupportedOperationException();
}
/**
* This is a convenience method that creates an instance of the {@link DownloadDirectoryRequest} builder, avoiding the need to
* create one manually via {@link DownloadDirectoryRequest#builder()}.
*
* @see #downloadDirectory(DownloadDirectoryRequest)
*/
default DirectoryDownload downloadDirectory(Consumer<DownloadDirectoryRequest.Builder> requestBuilder) {
Validate.paramNotNull(requestBuilder, "requestBuilder");
return downloadDirectory(DownloadDirectoryRequest.builder().applyMutation(requestBuilder).build());
}
/**
* Creates a copy of an object that is already stored in S3.
* <p>
* Depending on the underlying S3Client, {@link S3TransferManager} may intelligently use plain {@link CopyObjectRequest}s
* for smaller objects, and multiple parallel {@link UploadPartCopyRequest}s for larger objects. If multipart copy is
* supported by the underlying S3Client, this behavior can be configured via
* {@link S3CrtAsyncClientBuilder#minimumPartSizeInBytes(Long)}. Note that for multipart copy request, existing metadata
* stored in the source object is NOT copied to the destination object; if required, you can retrieve the metadata from the
* source object and set it explicitly in the @link CopyObjectRequest.Builder#metadata(Map)}.
*
* <p>
* While this API supports {@link TransferListener}s, they will not receive {@code bytesTransferred} callback-updates due to
* the way the {@link CopyObjectRequest} API behaves. When copying an object, S3 performs the byte copying on your behalf
* while keeping the connection alive. The progress of the copy is not known until it fully completes and S3 sends a response
* describing the outcome.
*
* <p>
* If you are copying an object to a bucket in a different region, you need to enable cross region access
* on the {@link S3AsyncClient}.
*
* <p>
* <b>Usage Example:</b>
* {@snippet :
* S3AsyncClient s3AsyncClient =
* S3AsyncClient.crtBuilder()
* // enable cross-region access, only required if you are making cross-region copy
* .crossRegionAccessEnabled(true)
* .build();
* S3TransferManager transferManager = S3TransferManager.builder()
* .s3Client(s3AsyncClient)
* .build();
* CopyObjectRequest copyObjectRequest = CopyObjectRequest.builder()
* .sourceBucket("source_bucket")
* .sourceKey("source_key")
* .destinationBucket("dest_bucket")
* .destinationKey("dest_key")
* .build();
* CopyRequest copyRequest = CopyRequest.builder()
* .copyObjectRequest(copyObjectRequest)
* .build();
*
* Copy copy = transferManager.copy(copyRequest);
* // Wait for the transfer to complete
* CompletedCopy completedCopy = copy.completionFuture().join();
* }
*
* @param copyRequest the copy request, containing a {@link CopyObjectRequest}
* @return A {@link Copy} that can be used to track the ongoing transfer
* @see #copy(Consumer)
* @see S3AsyncClient#copyObject(CopyObjectRequest)
*/
default Copy copy(CopyRequest copyRequest) {
throw new UnsupportedOperationException();
}
/**
* 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()}.
*
* @see #copy(CopyRequest)
*/
default Copy copy(Consumer<CopyRequest.Builder> copyRequestBuilder) {
return copy(CopyRequest.builder().applyMutation(copyRequestBuilder).build());
}
/**
* Create an {@code S3TransferManager} using the default values.
* <p>
* The type of {@link S3AsyncClient} used depends on if AWS Common Runtime (CRT) library
* {@code software.amazon.awssdk.crt:aws-crt} is in the classpath. If AWS CRT is available, an AWS CRT-based S3 client will
* be created via ({@link S3AsyncClient#crtCreate()}). Otherwise, a standard S3 client({@link S3AsyncClient#create()}) will
* be created. Note that only AWS CRT-based S3 client supports parallel transfer, i.e, leveraging multipart upload/download
* for now, so it's recommended to add AWS CRT as a dependency.
*/
static S3TransferManager create() {
return builder().build();
}
/**
* Creates a default builder for {@link S3TransferManager}.
*/
static S3TransferManager.Builder builder() {
return new TransferManagerFactory.DefaultBuilder();
}
/**
* The builder definition for a {@link S3TransferManager}.
*/
interface Builder {
/**
* Specifies the low level {@link S3AsyncClient} that will be used to send requests to S3. The SDK will create a default
* {@link S3AsyncClient} if not provided.
*
* <p>
* It's highly recommended to use {@link S3AsyncClient#crtBuilder()} to create an {@link S3AsyncClient} instance to
* benefit from multipart upload/download feature and maximum throughput.
*
* <p>
* Note: the provided {@link S3AsyncClient} will not be closed when the transfer manager is closed; it must be closed by
* the caller when it is ready to be disposed.
*
* @param s3AsyncClient the S3 async client
* @return Returns a reference to this object so that method calls can be chained together.
* @see S3AsyncClient#crtBuilder()
*/
Builder s3Client(S3AsyncClient s3AsyncClient);
/**
* Specifies the executor that {@link S3TransferManager} will use to execute background tasks before handing them off to
* the underlying S3 async client, such as visiting file tree in a
* {@link S3TransferManager#uploadDirectory(UploadDirectoryRequest)} operation.
*
* <p>
* The SDK will create an executor if not provided.
*
* <p>
* <b>This executor must be shut down by the user when it is ready to be disposed. The SDK will not close the executor
* when the s3 transfer manager is closed.</b>
*
* @param executor the executor to use
* @return this builder for method chaining.
*/
Builder executor(Executor executor);
/**
* Specifies whether to follow symbolic links when traversing the file tree in
* {@link S3TransferManager#uploadDirectory} operation
* <p>
* Default to false
*
* @param uploadDirectoryFollowSymbolicLinks whether to follow symbolic links
* @return This builder for method chaining.
*/
Builder uploadDirectoryFollowSymbolicLinks(Boolean uploadDirectoryFollowSymbolicLinks);
/**
* Specifies the maximum number of levels of directories to visit in {@link S3TransferManager#uploadDirectory} operation.
* Must be positive. 1 means only the files directly within
* the provided source directory are visited.
*
* <p>
* Default to {@code Integer.MAX_VALUE}
*
* @param uploadDirectoryMaxDepth the maximum number of directory levels to visit
* @return This builder for method chaining.
*/
Builder uploadDirectoryMaxDepth(Integer uploadDirectoryMaxDepth);
/**
* Builds an instance of {@link S3TransferManager} based on the settings supplied to this builder
*
* @return an instance of {@link S3TransferManager}
*/
S3TransferManager build();
}
}
| 3,753 |
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/progress/TransferListener.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.progress;
import java.util.concurrent.CompletionException;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkPreviewApi;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.services.s3.model.CompleteMultipartUploadRequest;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.transfer.s3.model.CompletedFileDownload;
import software.amazon.awssdk.transfer.s3.model.CompletedFileUpload;
import software.amazon.awssdk.transfer.s3.model.CompletedObjectTransfer;
import software.amazon.awssdk.transfer.s3.model.DownloadFileRequest;
import software.amazon.awssdk.transfer.s3.model.TransferObjectRequest;
import software.amazon.awssdk.transfer.s3.model.TransferRequest;
import software.amazon.awssdk.transfer.s3.model.UploadFileRequest;
/**
* The {@link TransferListener} interface may be implemented by your application in order to receive event-driven updates on the
* progress of a transfer initiated by {@link S3TransferManager}. When you construct an {@link UploadFileRequest} or {@link
* DownloadFileRequest} request to submit to {@link S3TransferManager}, you may provide a variable number of {@link
* TransferListener}s to be associated with that request. Then, throughout the lifecycle of the request, {@link S3TransferManager}
* will invoke the provided {@link TransferListener}s when important events occur, like additional bytes being transferred,
* allowing you to monitor the ongoing progress of the transfer.
* <p>
* Each {@link TransferListener} callback is invoked with an immutable {@link Context} object. Depending on the current lifecycle
* of the request, different {@link Context} objects have different attributes available (indicated by the provided context
* interface). Most notably, every callback is given access to the current {@link TransferProgressSnapshot}, which contains
* helpful progress-related methods like {@link TransferProgressSnapshot#transferredBytes()} and {@link
* TransferProgressSnapshot#ratioTransferred()}.
* <p>
* A successful transfer callback lifecycle is sequenced as follows:
* <ol>
* <li>{@link #transferInitiated(Context.TransferInitiated)} - A new transfer has been initiated. This method is called
* exactly once per transfer.</li>
* <ul>Available context attributes:
* <li>{@link Context.TransferInitiated#request()}</li>
* <li>{@link Context.TransferInitiated#progressSnapshot()}</li>
* </ul>
* <li>{@link #bytesTransferred(Context.BytesTransferred)} - Additional bytes have been submitted or received. This method
* may be called many times per transfer, depending on the transfer size and I/O buffer sizes.
* <li>{@link #transferComplete(Context.TransferComplete)} - The transfer has completed successfully. This method is called
* exactly once for a successful transfer.</li>
* <ul>Additional available context attributes:
* <li>{@link Context.TransferComplete#completedTransfer()}</li>
* </ul>
* </ol>
* In the case of a failed transfer, both {@link #transferInitiated(Context.TransferInitiated)} and
* {@link #transferFailed(Context.TransferFailed)} will be called exactly once. There are no guarantees on whether any other
* callbacks are invoked.
* <p>
* There are a few important rules and best practices that govern the usage of {@link TransferListener}s:
* <ol>
* <li>{@link TransferListener} implementations should not block, sleep, or otherwise delay the calling thread. If you need
* to perform blocking operations, you should schedule them in a separate thread or executor that you control.</li>
* <li>Be mindful that {@link #bytesTransferred(Context.BytesTransferred)} may be called extremely often (subject to I/O
* buffer sizes). Be careful in implementing expensive operations as a side effect. Consider rate-limiting your side
* effect operations, if needed.</li>
* <li>In the case of uploads, there may be some delay between the bytes being fully transferred and the transfer
* successfully completing. Internally, {@link S3TransferManager} uses the Amazon S3
* <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/mpuoverview.html">multipart upload API</a>
* and must finalize uploads with a {@link CompleteMultipartUploadRequest}.</li>
* <li>{@link TransferListener}s may be invoked by different threads. If your {@link TransferListener} is stateful,
* ensure that it is also thread-safe.</li>
* <li>{@link TransferListener}s are not intended to be used for control flow, and therefore your implementation
* should not <i>throw</i>. Any thrown exceptions will be suppressed and logged as an error.</li>
* </ol>
* <p>
* A classical use case of {@link TransferListener} is to create a progress bar to monitor an ongoing transfer's progress.
* Refer to the implementation of {@link LoggingTransferListener} for a basic example, or test it in your application by providing
* the listener as part of your {@link TransferRequest}. E.g.,
* <pre>{@code
* Upload upload = tm.upload(UploadRequest.builder()
* .putObjectRequest(b -> b.bucket("bucket").key("key"))
* .source(Paths.get(...))
* .addTransferListener(LoggingTransferListener.create())
* .build());
* }</pre>
* And then a successful transfer may output something similar to:
* <pre>
* Transfer initiated...
* | | 0.0%
* |== | 12.5%
* |===== | 25.0%
* |======= | 37.5%
* |========== | 50.0%
* |============ | 62.5%
* |=============== | 75.0%
* |================= | 87.5%
* |====================| 100.0%
* Transfer complete!
* </pre>
*/
@SdkPublicApi
public interface TransferListener {
/**
* A new transfer has been initiated. This method is called exactly once per transfer.
* <p>
* Available context attributes:
* <ol>
* <li>{@link Context.TransferInitiated#request()}</li>
* <li>{@link Context.TransferInitiated#progressSnapshot()}</li>
* </ol>
*/
default void transferInitiated(Context.TransferInitiated context) {
}
/**
* Additional bytes have been submitted or received. This method may be called many times per transfer, depending on the
* transfer size and I/O buffer sizes.
* <p>
* Available context attributes:
* <ol>
* <li>{@link Context.BytesTransferred#request()}</li>
* <li>{@link Context.BytesTransferred#progressSnapshot()}</li>
* </ol>
*/
default void bytesTransferred(Context.BytesTransferred context) {
}
/**
* The transfer has completed successfully. This method is called exactly once for a successful transfer.
* <p>
* Available context attributes:
* <ol>
* <li>{@link Context.TransferComplete#request()}</li>
* <li>{@link Context.TransferComplete#progressSnapshot()}</li>
* <li>{@link Context.TransferComplete#completedTransfer()}</li>
* </ol>
*/
default void transferComplete(Context.TransferComplete context) {
}
/**
* The transfer failed. This method is called exactly once for a failed transfer.
* <p>
* Available context attributes:
* <ol>
* <li>{@link Context.TransferFailed#request()}</li>
* <li>{@link Context.TransferFailed#progressSnapshot()}</li>
* <li>{@link Context.TransferFailed#exception()}</li>
* </ol>
*/
default void transferFailed(Context.TransferFailed context) {
}
/**
* A wrapper class that groups together the different context interfaces that are exposed to {@link TransferListener}s.
* <p>
* Successful transfer interface hierarchy:
* <ol>
* <li>{@link TransferInitiated}</li>
* <li>{@link BytesTransferred}</li>
* <li>{@link TransferComplete}</li>
* </ol>
* Failed transfer interface hierarchy:
* <ol>
* <li>{@link TransferInitiated}</li>
* <li>{@link TransferFailed}</li>
* </ol>
*
* @see TransferListener
*/
@SdkProtectedApi
final class Context {
private Context() {
}
/**
* A new transfer has been initiated.
* <p>
* Available context attributes:
* <ol>
* <li>{@link TransferInitiated#request()}</li>
* <li>{@link TransferInitiated#progressSnapshot()}</li>
* </ol>
*/
@Immutable
@ThreadSafe
@SdkPublicApi
@SdkPreviewApi
public interface TransferInitiated {
/**
* The {@link TransferRequest} that was submitted to {@link S3TransferManager}, i.e., the {@link UploadFileRequest} or
* {@link DownloadFileRequest}.
*/
TransferObjectRequest request();
/**
* The immutable {@link TransferProgressSnapshot} for this specific update.
*/
TransferProgressSnapshot progressSnapshot();
}
/**
* Additional bytes have been submitted or received.
* <p>
* Available context attributes:
* <ol>
* <li>{@link BytesTransferred#request()}</li>
* <li>{@link BytesTransferred#progressSnapshot()}</li>
* </ol>
*/
@Immutable
@ThreadSafe
@SdkPublicApi
@SdkPreviewApi
public interface BytesTransferred extends TransferInitiated {
}
/**
* The transfer has completed successfully.
* <p>
* Available context attributes:
* <ol>
* <li>{@link TransferComplete#request()}</li>
* <li>{@link TransferComplete#progressSnapshot()}</li>
* <li>{@link TransferComplete#completedTransfer()}</li>
* </ol>
*/
@Immutable
@ThreadSafe
@SdkPublicApi
@SdkPreviewApi
public interface TransferComplete extends BytesTransferred {
/**
* The completed transfer, i.e., the {@link CompletedFileUpload} or {@link CompletedFileDownload}.
*/
CompletedObjectTransfer completedTransfer();
}
/**
* The transfer failed.
* <p>
* Available context attributes:
* <ol>
* <li>{@link TransferFailed#request()}</li>
* <li>{@link TransferFailed#progressSnapshot()}</li>
* <li>{@link TransferFailed#exception()}</li>
* </ol>
*/
@Immutable
@ThreadSafe
@SdkPublicApi
@SdkPreviewApi
public interface TransferFailed extends TransferInitiated {
/**
* The exception associated with the failed transfer.
* <p>
* Note that this would be the <i>cause</i> of a {@link CompletionException}, and not a {@link CompletionException}
* itself.
*/
Throwable exception();
}
}
}
| 3,754 |
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/progress/TransferProgress.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.progress;
import software.amazon.awssdk.annotations.Mutable;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.transfer.s3.model.Copy;
import software.amazon.awssdk.transfer.s3.model.Download;
import software.amazon.awssdk.transfer.s3.model.ObjectTransfer;
import software.amazon.awssdk.transfer.s3.model.Upload;
/**
* {@link TransferProgress} is a <b>stateful</b> representation of the progress of a transfer initiated by {@link
* S3TransferManager}. {@link TransferProgress} offers the ability to take a {@link #snapshot()} of the current progress,
* represented by an immutable {@link TransferProgressSnapshot}, which contains helpful progress-related methods like {@link
* TransferProgressSnapshot#transferredBytes()} and {@link TransferProgressSnapshot#ratioTransferred()}. {@link TransferProgress}
* is attached to {@link ObjectTransfer} objects, namely {@link Upload}, {@link Download}, and {@link Copy}.
* <p>
* Where possible, it is typically recommended to <b>avoid</b> directly querying {@link TransferProgress} and to instead leverage
* the {@link TransferListener} interface to receive event-driven updates of the latest {@link TransferProgressSnapshot}. See the
* {@link TransferListener} documentation for usage instructions. However, if desired, {@link TransferProgress} can be used for
* poll-like checking of the current progress. E.g.,
* <pre>{@code
* Upload upload = tm.upload(...);
* while (!upload.completionFuture().isDone()) {
* upload.progress().snapshot().ratioTransferred().ifPresent(System.out::println);
* Thread.sleep(1000);
* }
* }</pre>
*
* @see TransferProgressSnapshot
* @see TransferListener
* @see S3TransferManager
*/
@Mutable
@ThreadSafe
@SdkPublicApi
public interface TransferProgress {
/**
* Takes a snapshot of the current progress, represented by an immutable {@link TransferProgressSnapshot}.
*/
TransferProgressSnapshot snapshot();
}
| 3,755 |
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/progress/LoggingTransferListener.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.progress;
import static software.amazon.awssdk.utils.StringUtils.repeat;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.concurrent.atomic.AtomicInteger;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.utils.Logger;
/**
* An example implementation of {@link TransferListener} that logs a progress bar at the {@code INFO} level. This implementation
* effectively rate-limits how frequently updates are logged by only logging when a new "tick" advances in the progress bar. By
* default, the progress bar has {@value #DEFAULT_MAX_TICKS} ticks, meaning an update is only logged, at most, once every 5%.
*/
@SdkPublicApi
public final class LoggingTransferListener implements TransferListener {
private static final Logger log = Logger.loggerFor(LoggingTransferListener.class);
private static final int DEFAULT_MAX_TICKS = 20;
private final ProgressBar progressBar;
private LoggingTransferListener(int maxTicks) {
progressBar = new ProgressBar(maxTicks);
}
/**
* Create an instance of {@link LoggingTransferListener} with a custom {@code maxTicks} value.
*
* @param maxTicks the number of ticks in the logged progress bar
*/
public static LoggingTransferListener create(int maxTicks) {
return new LoggingTransferListener(maxTicks);
}
/**
* Create an instance of {@link LoggingTransferListener} with the default configuration.
*/
public static LoggingTransferListener create() {
return new LoggingTransferListener(DEFAULT_MAX_TICKS);
}
@Override
public void transferInitiated(Context.TransferInitiated context) {
log.info(() -> "Transfer initiated...");
context.progressSnapshot().ratioTransferred().ifPresent(progressBar::update);
}
@Override
public void bytesTransferred(Context.BytesTransferred context) {
context.progressSnapshot().ratioTransferred().ifPresent(progressBar::update);
}
@Override
public void transferComplete(Context.TransferComplete context) {
context.progressSnapshot().ratioTransferred().ifPresent(progressBar::update);
log.info(() -> "Transfer complete!");
}
@Override
public void transferFailed(Context.TransferFailed context) {
log.warn(() -> "Transfer failed.", context.exception());
}
private static class ProgressBar {
private final int maxTicks;
private final AtomicInteger prevTicks = new AtomicInteger(-1);
ProgressBar(int maxTicks) {
this.maxTicks = maxTicks;
}
void update(double ratio) {
int ticks = (int) Math.floor(ratio * maxTicks);
if (prevTicks.getAndSet(ticks) != ticks) {
log.info(() -> String.format("|%s%s| %s",
repeat("=", ticks),
repeat(" ", maxTicks - ticks),
round(ratio * 100, 1) + "%"));
}
}
private static double round(double value, int places) {
BigDecimal bd = BigDecimal.valueOf(value);
bd = bd.setScale(places, RoundingMode.FLOOR);
return bd.doubleValue();
}
}
}
| 3,756 |
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/progress/TransferProgressSnapshot.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.progress;
import java.util.Optional;
import java.util.OptionalDouble;
import java.util.OptionalLong;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.core.SdkResponse;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.services.s3.model.PutObjectResponse;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.transfer.s3.model.Download;
import software.amazon.awssdk.transfer.s3.model.FileUpload;
import software.amazon.awssdk.transfer.s3.model.TransferRequest;
import software.amazon.awssdk.transfer.s3.model.Upload;
/**
* {@link TransferProgressSnapshot} is an <b>immutable</b>, point-in-time representation of the progress of a given transfer
* initiated by {@link S3TransferManager}. {@link TransferProgressSnapshot} offers several helpful methods for checking the
* progress of a transfer, like {@link #transferredBytes()} and {@link #ratioTransferred()}.
* <p>
* {@link TransferProgressSnapshot}'s methods that return {@link Optional} are dependent upon the size of a transfer (i.e., the
* {@code Content-Length}) being known. In the case of file-based {@link FileUpload}s, transfer sizes are known up front and
* immediately available. In the case of {@link Download}s, the transfer size is not known until {@link S3TransferManager}
* receives a {@link GetObjectResponse} from Amazon S3.
* <p>
* The recommended way to receive updates of the latest {@link TransferProgressSnapshot} is to implement the {@link
* TransferListener} interface. See the {@link TransferListener} documentation for usage instructions. A {@link
* TransferProgressSnapshot} can also be obtained from a {@link TransferProgress} returned as part of the result from a {@link
* TransferRequest}.
*
* @see TransferProgress
* @see TransferListener
* @see S3TransferManager
*/
@Immutable
@ThreadSafe
@SdkPublicApi
public interface TransferProgressSnapshot {
/**
* The total number of bytes that have been transferred so far.
*/
long transferredBytes();
/**
* The total size of the transfer, in bytes, or {@link Optional#empty()} if unknown.
* <p>
* In the case of file-based {@link FileUpload}s, transfer sizes are known up front and immediately available. In the case of
* {@link Download}s, the transfer size is not known until {@link S3TransferManager} receives a {@link GetObjectResponse} from
* Amazon S3.
*/
OptionalLong totalBytes();
/**
* The SDK response, or {@link Optional#empty()} if unknown.
*
* <p>
* In the case of {@link Download}, the response is {@link GetObjectResponse}, and the response is known before
* it starts streaming. In the case of {@link Upload}, the response is {@link PutObjectResponse}, and the response is not
* known until streaming finishes.
*/
Optional<SdkResponse> sdkResponse();
/**
* The ratio of the {@link #totalBytes()} that has been transferred so far, or {@link Optional#empty()} if unknown.
* This method depends on the {@link #totalBytes()} being known in order to return non-empty.
* <p>
* Ratio is computed as {@link #transferredBytes()} {@code /} {@link #totalBytes()}, where a transfer that is
* half-complete would return {@code 0.5}.
*
* @see #totalBytes()
*/
OptionalDouble ratioTransferred();
/**
* The total number of bytes that are remaining to be transferred, or {@link Optional#empty()} if unknown. This method depends
* on the {@link #totalBytes()} being known in order to return non-empty.
*
* @see #totalBytes()
*/
OptionalLong remainingBytes();
}
| 3,757 |
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/config/DownloadFilter.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.config;
import java.util.function.Predicate;
import software.amazon.awssdk.annotations.SdkPreviewApi;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.services.s3.model.S3Object;
import software.amazon.awssdk.transfer.s3.model.DownloadDirectoryRequest;
/**
* {@link DownloadFilter} allows you to filter out which objects should be downloaded as part of a {@link
* DownloadDirectoryRequest}. You could use it, for example, to only download objects of a given size, of a given file extension,
* of a given last-modified date, etc. Multiple {@link DownloadFilter}s can be composed together via {@link #and(Predicate)} and
* {@link #or(Predicate)} methods.
*/
@SdkPublicApi
@SdkPreviewApi
public interface DownloadFilter extends Predicate<S3Object> {
/**
* Evaluate condition the remote {@link S3Object} should be downloaded.
*
* @param s3Object Remote {@link S3Object}
* @return true if the object should be downloaded, false if the object should not be downloaded
*/
@Override
boolean test(S3Object s3Object);
/**
* A {@link DownloadFilter} that downloads all objects. This is the default behavior if no filter is provided.
*/
@SdkPreviewApi
static DownloadFilter allObjects() {
return ctx -> true;
}
}
| 3,758 |
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/config/TransferRequestOverrideConfiguration.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.config;
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.SdkPreviewApi;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.transfer.s3.model.DownloadFileRequest;
import software.amazon.awssdk.transfer.s3.model.UploadFileRequest;
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;
/**
* Configuration options for {@link UploadFileRequest} and {@link DownloadFileRequest}. All values are optional, and not
* specifying them will use the SDK default values.
*
* <p>Use {@link #builder()} to create a set of options.
*/
@SdkPublicApi
@SdkPreviewApi
public final class TransferRequestOverrideConfiguration
implements ToCopyableBuilder<TransferRequestOverrideConfiguration.Builder, TransferRequestOverrideConfiguration> {
private final List<TransferListener> listeners;
public TransferRequestOverrideConfiguration(DefaultBuilder builder) {
this.listeners = builder.listeners != null ? Collections.unmodifiableList(builder.listeners) : Collections.emptyList();
}
/**
* @return The {@link TransferListener}s that will be notified as part of this request.
*/
public List<TransferListener> listeners() {
return listeners;
}
@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;
}
TransferRequestOverrideConfiguration that = (TransferRequestOverrideConfiguration) o;
return Objects.equals(listeners, that.listeners);
}
@Override
public int hashCode() {
return listeners != null ? listeners.hashCode() : 0;
}
@Override
public String toString() {
return ToString.builder("TransferRequestOverrideConfiguration")
.add("listeners", listeners)
.build();
}
public static Builder builder() {
return new DefaultBuilder();
}
public static Class<? extends Builder> serializableBuilderClass() {
return DefaultBuilder.class;
}
public interface Builder extends CopyableBuilder<Builder, TransferRequestOverrideConfiguration> {
/**
* 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.
* @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);
@Override
TransferRequestOverrideConfiguration build();
}
private static final class DefaultBuilder implements Builder {
private List<TransferListener> listeners;
private DefaultBuilder(TransferRequestOverrideConfiguration configuration) {
this.listeners = configuration.listeners;
}
private DefaultBuilder() {
}
@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 TransferRequestOverrideConfiguration build() {
return new TransferRequestOverrideConfiguration(this);
}
}
}
| 3,759 |
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/internal/CrtS3TransferManager.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal;
import static software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute.SDK_HTTP_EXECUTION_ATTRIBUTES;
import static software.amazon.awssdk.services.s3.crt.S3CrtSdkHttpExecutionAttribute.CRT_PROGRESS_LISTENER;
import static software.amazon.awssdk.services.s3.crt.S3CrtSdkHttpExecutionAttribute.METAREQUEST_PAUSE_OBSERVABLE;
import static software.amazon.awssdk.services.s3.internal.crt.S3InternalSdkHttpExecutionAttribute.CRT_PAUSE_RESUME_TOKEN;
import static software.amazon.awssdk.transfer.s3.internal.GenericS3TransferManager.assertNotUnsupportedArn;
import static software.amazon.awssdk.transfer.s3.internal.utils.FileUtils.fileNotModified;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.crt.s3.ResumeToken;
import software.amazon.awssdk.http.SdkHttpExecutionAttributes;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.internal.crt.S3MetaRequestPauseObservable;
import software.amazon.awssdk.services.s3.model.AbortMultipartUploadRequest;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.PutObjectResponse;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.transfer.s3.internal.model.CrtFileUpload;
import software.amazon.awssdk.transfer.s3.internal.progress.TransferProgressUpdater;
import software.amazon.awssdk.transfer.s3.model.CompletedFileUpload;
import software.amazon.awssdk.transfer.s3.model.FileUpload;
import software.amazon.awssdk.transfer.s3.model.ResumableFileUpload;
import software.amazon.awssdk.transfer.s3.model.UploadFileRequest;
import software.amazon.awssdk.utils.CompletableFutureUtils;
import software.amazon.awssdk.utils.Logger;
import software.amazon.awssdk.utils.Validate;
/**
* An implementation of {@link S3TransferManager} that uses CRT-based S3 client under the hood.
*/
@SdkInternalApi
class CrtS3TransferManager extends DelegatingS3TransferManager {
private static final Logger log = Logger.loggerFor(S3TransferManager.class);
private final S3AsyncClient s3AsyncClient;
CrtS3TransferManager(TransferManagerConfiguration transferConfiguration, S3AsyncClient s3AsyncClient,
boolean isDefaultS3AsyncClient) {
super(new GenericS3TransferManager(transferConfiguration, s3AsyncClient, isDefaultS3AsyncClient));
this.s3AsyncClient = s3AsyncClient;
}
@Override
public FileUpload uploadFile(UploadFileRequest uploadFileRequest) {
Validate.paramNotNull(uploadFileRequest, "uploadFileRequest");
S3MetaRequestPauseObservable observable = new S3MetaRequestPauseObservable();
Long fileContentLength = AsyncRequestBody.fromFile(uploadFileRequest.source()).contentLength().orElse(null);
TransferProgressUpdater progressUpdater = new TransferProgressUpdater(uploadFileRequest, fileContentLength);
Consumer<SdkHttpExecutionAttributes.Builder> attachObservable =
b -> b.put(METAREQUEST_PAUSE_OBSERVABLE, observable)
.put(CRT_PROGRESS_LISTENER, progressUpdater.crtProgressListener());
PutObjectRequest putObjectRequest = attachSdkAttribute(uploadFileRequest.putObjectRequest(), attachObservable);
CompletableFuture<CompletedFileUpload> returnFuture = new CompletableFuture<>();
progressUpdater.transferInitiated();
progressUpdater.registerCompletion(returnFuture);
try {
assertNotUnsupportedArn(putObjectRequest.bucket(), "upload");
CompletableFuture<PutObjectResponse> crtFuture =
s3AsyncClient.putObject(putObjectRequest, uploadFileRequest.source());
// Forward upload cancellation to CRT future
CompletableFutureUtils.forwardExceptionTo(returnFuture, crtFuture);
CompletableFutureUtils.forwardTransformedResultTo(crtFuture, returnFuture,
r -> CompletedFileUpload.builder()
.response(r)
.build());
} catch (Throwable throwable) {
returnFuture.completeExceptionally(throwable);
}
return new CrtFileUpload(returnFuture, progressUpdater.progress(), observable, uploadFileRequest);
}
private FileUpload uploadFromBeginning(ResumableFileUpload resumableFileUpload, boolean fileModified,
boolean noResumeToken) {
UploadFileRequest uploadFileRequest = resumableFileUpload.uploadFileRequest();
PutObjectRequest putObjectRequest = uploadFileRequest.putObjectRequest();
if (fileModified) {
log.debug(() -> String.format("The file (%s) has been modified since "
+ "the last pause. " +
"The SDK will upload the requested object in bucket"
+ " (%s) with key (%s) from "
+ "the "
+ "beginning.",
uploadFileRequest.source(),
putObjectRequest.bucket(),
putObjectRequest.key()));
resumableFileUpload.multipartUploadId()
.ifPresent(id -> {
log.debug(() -> "Aborting previous upload with multipartUploadId: " + id);
s3AsyncClient.abortMultipartUpload(
AbortMultipartUploadRequest.builder()
.bucket(putObjectRequest.bucket())
.key(putObjectRequest.key())
.uploadId(id)
.build())
.exceptionally(t -> {
log.warn(() -> String.format("Failed to abort previous multipart upload "
+ "(id: %s)"
+ ". You may need to call "
+ "S3AsyncClient#abortMultiPartUpload to "
+ "free all storage consumed by"
+ " all parts. ",
id), t);
return null;
});
});
}
if (noResumeToken) {
log.debug(() -> String.format("No resume token is found. " +
"The SDK will upload the requested object in bucket"
+ " (%s) with key (%s) from "
+ "the beginning.",
putObjectRequest.bucket(),
putObjectRequest.key()));
}
return uploadFile(uploadFileRequest);
}
@Override
public FileUpload resumeUploadFile(ResumableFileUpload resumableFileUpload) {
Validate.paramNotNull(resumableFileUpload, "resumableFileUpload");
boolean fileModified = !fileNotModified(resumableFileUpload.fileLength(),
resumableFileUpload.fileLastModified(),
resumableFileUpload.uploadFileRequest().source());
boolean noResumeToken = !hasResumeToken(resumableFileUpload);
if (fileModified || noResumeToken) {
return uploadFromBeginning(resumableFileUpload, fileModified, noResumeToken);
}
return doResumeUpload(resumableFileUpload);
}
private FileUpload doResumeUpload(ResumableFileUpload resumableFileUpload) {
UploadFileRequest uploadFileRequest = resumableFileUpload.uploadFileRequest();
PutObjectRequest putObjectRequest = uploadFileRequest.putObjectRequest();
ResumeToken resumeToken = crtResumeToken(resumableFileUpload);
Consumer<SdkHttpExecutionAttributes.Builder> attachResumeToken =
b -> b.put(CRT_PAUSE_RESUME_TOKEN, resumeToken);
PutObjectRequest modifiedPutObjectRequest = attachSdkAttribute(putObjectRequest, attachResumeToken);
return uploadFile(uploadFileRequest.toBuilder()
.putObjectRequest(modifiedPutObjectRequest)
.build());
}
private static ResumeToken crtResumeToken(ResumableFileUpload resumableFileUpload) {
return new ResumeToken(new ResumeToken.PutResumeTokenBuilder()
.withNumPartsCompleted(resumableFileUpload.transferredParts().orElse(0L))
.withTotalNumParts(resumableFileUpload.totalParts().orElse(0L))
.withPartSize(resumableFileUpload.partSizeInBytes().getAsLong())
.withUploadId(resumableFileUpload.multipartUploadId().orElse(null)));
}
private boolean hasResumeToken(ResumableFileUpload resumableFileUpload) {
return resumableFileUpload.totalParts().isPresent() && resumableFileUpload.partSizeInBytes().isPresent();
}
private PutObjectRequest attachSdkAttribute(PutObjectRequest putObjectRequest,
Consumer<SdkHttpExecutionAttributes.Builder> builderMutation) {
SdkHttpExecutionAttributes modifiedAttributes =
putObjectRequest.overrideConfiguration().map(o -> o.executionAttributes().getAttribute(SDK_HTTP_EXECUTION_ATTRIBUTES))
.map(b -> b.toBuilder().applyMutation(builderMutation).build())
.orElseGet(() -> SdkHttpExecutionAttributes.builder().applyMutation(builderMutation).build());
Consumer<AwsRequestOverrideConfiguration.Builder> attachSdkHttpAttributes =
b -> b.putExecutionAttribute(SDK_HTTP_EXECUTION_ATTRIBUTES, modifiedAttributes);
AwsRequestOverrideConfiguration modifiedRequestOverrideConfig =
putObjectRequest.overrideConfiguration()
.map(o -> o.toBuilder().applyMutation(attachSdkHttpAttributes).build())
.orElseGet(() -> AwsRequestOverrideConfiguration.builder()
.applyMutation(attachSdkHttpAttributes)
.build());
return putObjectRequest.toBuilder()
.overrideConfiguration(modifiedRequestOverrideConfig)
.build();
}
}
| 3,760 |
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/internal/GenericS3TransferManager.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal;
import static software.amazon.awssdk.transfer.s3.SizeConstant.MB;
import static software.amazon.awssdk.transfer.s3.internal.utils.ResumableRequestConverter.toDownloadFileRequestAndTransformer;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.SdkTestInternalApi;
import software.amazon.awssdk.arns.Arn;
import software.amazon.awssdk.core.FileTransformerConfiguration;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.core.async.AsyncResponseTransformer;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.exception.SdkException;
import software.amazon.awssdk.core.internal.async.FileAsyncRequestBody;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.internal.resource.S3AccessPointResource;
import software.amazon.awssdk.services.s3.internal.resource.S3ArnConverter;
import software.amazon.awssdk.services.s3.internal.resource.S3Resource;
import software.amazon.awssdk.services.s3.model.CopyObjectResponse;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.services.s3.model.HeadObjectResponse;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.PutObjectResponse;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.transfer.s3.internal.model.DefaultCopy;
import software.amazon.awssdk.transfer.s3.internal.model.DefaultDirectoryDownload;
import software.amazon.awssdk.transfer.s3.internal.model.DefaultDirectoryUpload;
import software.amazon.awssdk.transfer.s3.internal.model.DefaultDownload;
import software.amazon.awssdk.transfer.s3.internal.model.DefaultFileDownload;
import software.amazon.awssdk.transfer.s3.internal.model.DefaultFileUpload;
import software.amazon.awssdk.transfer.s3.internal.model.DefaultUpload;
import software.amazon.awssdk.transfer.s3.internal.progress.ResumeTransferProgress;
import software.amazon.awssdk.transfer.s3.internal.progress.TransferProgressUpdater;
import software.amazon.awssdk.transfer.s3.model.CompletedCopy;
import software.amazon.awssdk.transfer.s3.model.CompletedDownload;
import software.amazon.awssdk.transfer.s3.model.CompletedFileDownload;
import software.amazon.awssdk.transfer.s3.model.CompletedFileUpload;
import software.amazon.awssdk.transfer.s3.model.CompletedUpload;
import software.amazon.awssdk.transfer.s3.model.Copy;
import software.amazon.awssdk.transfer.s3.model.CopyRequest;
import software.amazon.awssdk.transfer.s3.model.DirectoryDownload;
import software.amazon.awssdk.transfer.s3.model.DirectoryUpload;
import software.amazon.awssdk.transfer.s3.model.Download;
import software.amazon.awssdk.transfer.s3.model.DownloadDirectoryRequest;
import software.amazon.awssdk.transfer.s3.model.DownloadFileRequest;
import software.amazon.awssdk.transfer.s3.model.DownloadRequest;
import software.amazon.awssdk.transfer.s3.model.FileDownload;
import software.amazon.awssdk.transfer.s3.model.FileUpload;
import software.amazon.awssdk.transfer.s3.model.ResumableFileDownload;
import software.amazon.awssdk.transfer.s3.model.Upload;
import software.amazon.awssdk.transfer.s3.model.UploadDirectoryRequest;
import software.amazon.awssdk.transfer.s3.model.UploadFileRequest;
import software.amazon.awssdk.transfer.s3.model.UploadRequest;
import software.amazon.awssdk.transfer.s3.progress.TransferProgress;
import software.amazon.awssdk.utils.CompletableFutureUtils;
import software.amazon.awssdk.utils.IoUtils;
import software.amazon.awssdk.utils.Logger;
import software.amazon.awssdk.utils.Pair;
import software.amazon.awssdk.utils.Validate;
@SdkInternalApi
class GenericS3TransferManager implements S3TransferManager {
protected static final int DEFAULT_FILE_UPLOAD_CHUNK_SIZE = (int) (16 * MB);
private static final Logger log = Logger.loggerFor(S3TransferManager.class);
private final S3AsyncClient s3AsyncClient;
private final UploadDirectoryHelper uploadDirectoryHelper;
private final DownloadDirectoryHelper downloadDirectoryHelper;
private final boolean isDefaultS3AsyncClient;
private final TransferManagerConfiguration transferConfiguration;
GenericS3TransferManager(TransferManagerConfiguration transferConfiguration,
S3AsyncClient s3AsyncClient,
boolean isDefaultS3AsyncClient) {
this.s3AsyncClient = s3AsyncClient;
this.transferConfiguration = transferConfiguration;
uploadDirectoryHelper = new UploadDirectoryHelper(transferConfiguration, this::uploadFile);
ListObjectsHelper listObjectsHelper = new ListObjectsHelper(s3AsyncClient::listObjectsV2);
downloadDirectoryHelper = new DownloadDirectoryHelper(transferConfiguration,
listObjectsHelper,
this::downloadFile);
this.isDefaultS3AsyncClient = isDefaultS3AsyncClient;
}
@SdkTestInternalApi
GenericS3TransferManager(S3AsyncClient s3CrtAsyncClient,
UploadDirectoryHelper uploadDirectoryHelper,
TransferManagerConfiguration configuration,
DownloadDirectoryHelper downloadDirectoryHelper) {
this.s3AsyncClient = s3CrtAsyncClient;
this.isDefaultS3AsyncClient = false;
this.transferConfiguration = configuration;
this.uploadDirectoryHelper = uploadDirectoryHelper;
this.downloadDirectoryHelper = downloadDirectoryHelper;
}
@Override
public Upload upload(UploadRequest uploadRequest) {
Validate.paramNotNull(uploadRequest, "uploadRequest");
AsyncRequestBody requestBody = uploadRequest.requestBody();
CompletableFuture<CompletedUpload> returnFuture = new CompletableFuture<>();
TransferProgressUpdater progressUpdater = new TransferProgressUpdater(uploadRequest,
requestBody.contentLength().orElse(null));
progressUpdater.transferInitiated();
requestBody = progressUpdater.wrapRequestBody(requestBody);
progressUpdater.registerCompletion(returnFuture);
try {
assertNotUnsupportedArn(uploadRequest.putObjectRequest().bucket(), "upload");
CompletableFuture<PutObjectResponse> crtFuture =
s3AsyncClient.putObject(uploadRequest.putObjectRequest(), requestBody);
// Forward upload cancellation to CRT future
CompletableFutureUtils.forwardExceptionTo(returnFuture, crtFuture);
CompletableFutureUtils.forwardTransformedResultTo(crtFuture, returnFuture,
r -> CompletedUpload.builder()
.response(r)
.build());
} catch (Throwable throwable) {
returnFuture.completeExceptionally(throwable);
}
return new DefaultUpload(returnFuture, progressUpdater.progress());
}
@Override
public FileUpload uploadFile(UploadFileRequest uploadFileRequest) {
Validate.paramNotNull(uploadFileRequest, "uploadFileRequest");
AsyncRequestBody requestBody =
FileAsyncRequestBody.builder()
.path(uploadFileRequest.source())
.chunkSizeInBytes(DEFAULT_FILE_UPLOAD_CHUNK_SIZE)
.build();
PutObjectRequest putObjectRequest = uploadFileRequest.putObjectRequest();
CompletableFuture<CompletedFileUpload> returnFuture = new CompletableFuture<>();
TransferProgressUpdater progressUpdater = new TransferProgressUpdater(uploadFileRequest,
requestBody.contentLength().orElse(null));
progressUpdater.transferInitiated();
requestBody = progressUpdater.wrapRequestBody(requestBody);
progressUpdater.registerCompletion(returnFuture);
try {
assertNotUnsupportedArn(putObjectRequest.bucket(), "upload");
CompletableFuture<PutObjectResponse> putObjectFuture =
s3AsyncClient.putObject(putObjectRequest, requestBody);
// Forward upload cancellation to putObjectFuture
CompletableFutureUtils.forwardExceptionTo(returnFuture, putObjectFuture);
CompletableFutureUtils.forwardTransformedResultTo(putObjectFuture, returnFuture,
r -> CompletedFileUpload.builder()
.response(r)
.build());
} catch (Throwable throwable) {
returnFuture.completeExceptionally(throwable);
}
return new DefaultFileUpload(returnFuture, progressUpdater.progress(), uploadFileRequest);
}
@Override
public DirectoryUpload uploadDirectory(UploadDirectoryRequest uploadDirectoryRequest) {
Validate.paramNotNull(uploadDirectoryRequest, "uploadDirectoryRequest");
try {
assertNotUnsupportedArn(uploadDirectoryRequest.bucket(), "uploadDirectory");
return uploadDirectoryHelper.uploadDirectory(uploadDirectoryRequest);
} catch (Throwable throwable) {
return new DefaultDirectoryUpload(CompletableFutureUtils.failedFuture(throwable));
}
}
@Override
public <ResultT> Download<ResultT> download(DownloadRequest<ResultT> downloadRequest) {
Validate.paramNotNull(downloadRequest, "downloadRequest");
AsyncResponseTransformer<GetObjectResponse, ResultT> responseTransformer =
downloadRequest.responseTransformer();
CompletableFuture<CompletedDownload<ResultT>> returnFuture = new CompletableFuture<>();
TransferProgressUpdater progressUpdater = new TransferProgressUpdater(downloadRequest, null);
progressUpdater.transferInitiated();
responseTransformer = progressUpdater.wrapResponseTransformer(responseTransformer);
progressUpdater.registerCompletion(returnFuture);
try {
assertNotUnsupportedArn(downloadRequest.getObjectRequest().bucket(), "download");
CompletableFuture<ResultT> crtFuture =
s3AsyncClient.getObject(downloadRequest.getObjectRequest(), responseTransformer);
// Forward download cancellation to CRT future
CompletableFutureUtils.forwardExceptionTo(returnFuture, crtFuture);
CompletableFutureUtils.forwardTransformedResultTo(crtFuture, returnFuture,
r -> CompletedDownload.builder()
.result(r)
.build());
} catch (Throwable throwable) {
returnFuture.completeExceptionally(throwable);
}
return new DefaultDownload<>(returnFuture, progressUpdater.progress());
}
@Override
public FileDownload downloadFile(DownloadFileRequest downloadRequest) {
Validate.paramNotNull(downloadRequest, "downloadFileRequest");
AsyncResponseTransformer<GetObjectResponse, GetObjectResponse> responseTransformer =
AsyncResponseTransformer.toFile(downloadRequest.destination(),
FileTransformerConfiguration.defaultCreateOrReplaceExisting());
CompletableFuture<CompletedFileDownload> returnFuture = new CompletableFuture<>();
TransferProgressUpdater progressUpdater = doDownloadFile(downloadRequest, responseTransformer, returnFuture);
return new DefaultFileDownload(returnFuture, progressUpdater.progress(), () -> downloadRequest, null);
}
private TransferProgressUpdater doDownloadFile(
DownloadFileRequest downloadRequest,
AsyncResponseTransformer<GetObjectResponse, GetObjectResponse> responseTransformer,
CompletableFuture<CompletedFileDownload> returnFuture) {
TransferProgressUpdater progressUpdater = new TransferProgressUpdater(downloadRequest, null);
try {
progressUpdater.transferInitiated();
responseTransformer = progressUpdater.wrapResponseTransformer(responseTransformer);
progressUpdater.registerCompletion(returnFuture);
assertNotUnsupportedArn(downloadRequest.getObjectRequest().bucket(), "download");
CompletableFuture<GetObjectResponse> crtFuture =
s3AsyncClient.getObject(downloadRequest.getObjectRequest(),
responseTransformer);
// Forward download cancellation to CRT future
CompletableFutureUtils.forwardExceptionTo(returnFuture, crtFuture);
CompletableFutureUtils.forwardTransformedResultTo(crtFuture, returnFuture,
res -> CompletedFileDownload.builder()
.response(res)
.build());
} catch (Throwable throwable) {
returnFuture.completeExceptionally(throwable);
}
return progressUpdater;
}
@Override
public FileDownload resumeDownloadFile(ResumableFileDownload resumableFileDownload) {
Validate.paramNotNull(resumableFileDownload, "resumableFileDownload");
CompletableFuture<CompletedFileDownload> returnFuture = new CompletableFuture<>();
DownloadFileRequest originalDownloadRequest = resumableFileDownload.downloadFileRequest();
GetObjectRequest getObjectRequest = originalDownloadRequest.getObjectRequest();
CompletableFuture<TransferProgress> progressFuture = new CompletableFuture<>();
CompletableFuture<DownloadFileRequest> newDownloadFileRequestFuture = new CompletableFuture<>();
CompletableFuture<HeadObjectResponse> headFuture =
s3AsyncClient.headObject(b -> b.bucket(getObjectRequest.bucket()).key(getObjectRequest.key()));
// Ensure cancellations are forwarded to the head future
CompletableFutureUtils.forwardExceptionTo(returnFuture, headFuture);
headFuture.thenAccept(headObjectResponse -> {
Pair<DownloadFileRequest, AsyncResponseTransformer<GetObjectResponse, GetObjectResponse>>
requestPair = toDownloadFileRequestAndTransformer(resumableFileDownload, headObjectResponse,
originalDownloadRequest);
DownloadFileRequest newDownloadFileRequest = requestPair.left();
newDownloadFileRequestFuture.complete(newDownloadFileRequest);
log.debug(() -> "Sending downloadFileRequest " + newDownloadFileRequest);
TransferProgressUpdater progressUpdater = doDownloadFile(newDownloadFileRequest,
requestPair.right(),
returnFuture);
progressFuture.complete(progressUpdater.progress());
}).exceptionally(throwable -> {
handleException(returnFuture, progressFuture, newDownloadFileRequestFuture, throwable);
return null;
});
return new DefaultFileDownload(returnFuture,
new ResumeTransferProgress(progressFuture),
() -> newOrOriginalRequestForPause(newDownloadFileRequestFuture, originalDownloadRequest),
resumableFileDownload);
}
private DownloadFileRequest newOrOriginalRequestForPause(CompletableFuture<DownloadFileRequest> newDownloadFuture,
DownloadFileRequest originalDownloadRequest) {
try {
return newDownloadFuture.getNow(originalDownloadRequest);
} catch (CompletionException e) {
return originalDownloadRequest;
}
}
private static void handleException(CompletableFuture<CompletedFileDownload> returnFuture,
CompletableFuture<TransferProgress> progressFuture,
CompletableFuture<DownloadFileRequest> newDownloadFileRequestFuture,
Throwable throwable) {
Throwable exceptionCause = throwable instanceof CompletionException ? throwable.getCause() : throwable;
Throwable propagatedException = exceptionCause instanceof SdkException || exceptionCause instanceof Error
? exceptionCause
: SdkClientException.create("Failed to resume the request", exceptionCause);
returnFuture.completeExceptionally(propagatedException);
progressFuture.completeExceptionally(propagatedException);
newDownloadFileRequestFuture.completeExceptionally(propagatedException);
}
@Override
public DirectoryDownload downloadDirectory(DownloadDirectoryRequest downloadDirectoryRequest) {
Validate.paramNotNull(downloadDirectoryRequest, "downloadDirectoryRequest");
try {
assertNotUnsupportedArn(downloadDirectoryRequest.bucket(), "downloadDirectoryRequest");
return downloadDirectoryHelper.downloadDirectory(downloadDirectoryRequest);
} catch (Throwable throwable) {
return new DefaultDirectoryDownload(CompletableFutureUtils.failedFuture(throwable));
}
}
@Override
public Copy copy(CopyRequest copyRequest) {
Validate.paramNotNull(copyRequest, "copyRequest");
CompletableFuture<CompletedCopy> returnFuture = new CompletableFuture<>();
TransferProgressUpdater progressUpdater = new TransferProgressUpdater(copyRequest, null);
progressUpdater.transferInitiated();
progressUpdater.registerCompletion(returnFuture);
try {
assertNotUnsupportedArn(copyRequest.copyObjectRequest().sourceBucket(), "copy sourceBucket");
assertNotUnsupportedArn(copyRequest.copyObjectRequest().destinationBucket(), "copy destinationBucket");
CompletableFuture<CopyObjectResponse> crtFuture =
s3AsyncClient.copyObject(copyRequest.copyObjectRequest());
// Forward transfer cancellation to CRT future
CompletableFutureUtils.forwardExceptionTo(returnFuture, crtFuture);
CompletableFutureUtils.forwardTransformedResultTo(crtFuture, returnFuture,
r -> CompletedCopy.builder()
.response(r)
.build());
} catch (Throwable throwable) {
returnFuture.completeExceptionally(throwable);
}
return new DefaultCopy(returnFuture, progressUpdater.progress());
}
@Override
public void close() {
if (isDefaultS3AsyncClient) {
IoUtils.closeQuietly(s3AsyncClient, log.logger());
}
IoUtils.closeQuietly(transferConfiguration, log.logger());
}
protected static void assertNotUnsupportedArn(String bucket, String operation) {
if (bucket == null) {
return;
}
if (!bucket.startsWith("arn:")) {
return;
}
if (isObjectLambdaArn(bucket)) {
String error = String.format("%s does not support S3 Object Lambda resources", operation);
throw new IllegalArgumentException(error);
}
Arn arn = Arn.fromString(bucket);
if (isMrapArn(arn)) {
String error = String.format("%s does not support S3 multi-region access point ARN", operation);
throw new IllegalArgumentException(error);
}
}
private static boolean isObjectLambdaArn(String arn) {
return arn.contains(":s3-object-lambda");
}
private static boolean isMrapArn(Arn arn) {
S3Resource s3Resource = S3ArnConverter.create().convertArn(arn);
S3AccessPointResource s3EndpointResource =
Validate.isInstanceOf(S3AccessPointResource.class, s3Resource,
"An ARN was passed as a bucket parameter to an S3 operation, however it does not "
+ "appear to be a valid S3 access point ARN.");
return !s3EndpointResource.region().isPresent();
}
}
| 3,761 |
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/internal/DownloadDirectoryHelper.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal;
import static software.amazon.awssdk.transfer.s3.internal.TransferConfigurationOption.DEFAULT_DELIMITER;
import static software.amazon.awssdk.transfer.s3.internal.TransferConfigurationOption.DEFAULT_DOWNLOAD_DIRECTORY_MAX_CONCURRENCY;
import static software.amazon.awssdk.transfer.s3.internal.TransferConfigurationOption.DEFAULT_PREFIX;
import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collection;
import java.util.Queue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.function.Function;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.ListObjectsV2Request;
import software.amazon.awssdk.services.s3.model.S3Object;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.transfer.s3.internal.model.DefaultDirectoryDownload;
import software.amazon.awssdk.transfer.s3.model.CompletedDirectoryDownload;
import software.amazon.awssdk.transfer.s3.model.CompletedFileDownload;
import software.amazon.awssdk.transfer.s3.model.DirectoryDownload;
import software.amazon.awssdk.transfer.s3.model.DownloadDirectoryRequest;
import software.amazon.awssdk.transfer.s3.model.DownloadFileRequest;
import software.amazon.awssdk.transfer.s3.model.FailedFileDownload;
import software.amazon.awssdk.transfer.s3.model.FileDownload;
import software.amazon.awssdk.utils.CompletableFutureUtils;
import software.amazon.awssdk.utils.Logger;
import software.amazon.awssdk.utils.StringUtils;
import software.amazon.awssdk.utils.Validate;
/**
* An internal helper class that sends {@link DownloadFileRequest}s while it retrieves the objects to download from S3
* recursively
*/
@SdkInternalApi
public class DownloadDirectoryHelper {
private static final Logger log = Logger.loggerFor(S3TransferManager.class);
private final TransferManagerConfiguration transferConfiguration;
private final Function<DownloadFileRequest, FileDownload> downloadFileFunction;
private final ListObjectsHelper listObjectsHelper;
public DownloadDirectoryHelper(TransferManagerConfiguration transferConfiguration,
ListObjectsHelper listObjectsHelper,
Function<DownloadFileRequest, FileDownload> downloadFileFunction) {
this.transferConfiguration = transferConfiguration;
this.downloadFileFunction = downloadFileFunction;
this.listObjectsHelper = listObjectsHelper;
}
public DirectoryDownload downloadDirectory(DownloadDirectoryRequest downloadDirectoryRequest) {
CompletableFuture<CompletedDirectoryDownload> returnFuture = new CompletableFuture<>();
CompletableFuture.runAsync(() -> doDownloadDirectory(returnFuture, downloadDirectoryRequest),
transferConfiguration.option(TransferConfigurationOption.EXECUTOR))
.whenComplete((r, t) -> {
if (t != null) {
returnFuture.completeExceptionally(t);
}
});
return new DefaultDirectoryDownload(returnFuture);
}
private static void validateDirectoryIfExists(Path directory) {
if (Files.exists(directory)) {
Validate.isTrue(Files.isDirectory(directory), "The destination directory provided (%s) is not a "
+ "directory", directory);
}
}
private void doDownloadDirectory(CompletableFuture<CompletedDirectoryDownload> returnFuture,
DownloadDirectoryRequest downloadDirectoryRequest) {
validateDirectoryIfExists(downloadDirectoryRequest.destination());
String bucket = downloadDirectoryRequest.bucket();
// Delimiter is null by default. See https://github.com/aws/aws-sdk-java/issues/1215
ListObjectsV2Request request =
ListObjectsV2Request.builder()
.bucket(bucket)
.prefix(DEFAULT_PREFIX)
.applyMutation(downloadDirectoryRequest.listObjectsRequestTransformer())
.build();
Queue<FailedFileDownload> failedFileDownloads = new ConcurrentLinkedQueue<>();
CompletableFuture<Void> allOfFutures = new CompletableFuture<>();
AsyncBufferingSubscriber<S3Object> asyncBufferingSubscriber =
new AsyncBufferingSubscriber<>(downloadSingleFile(returnFuture, downloadDirectoryRequest, request,
failedFileDownloads),
allOfFutures,
DEFAULT_DOWNLOAD_DIRECTORY_MAX_CONCURRENCY);
listObjectsHelper.listS3ObjectsRecursively(request)
.filter(downloadDirectoryRequest.filter())
.subscribe(asyncBufferingSubscriber);
allOfFutures.whenComplete((r, t) -> {
if (t != null) {
returnFuture.completeExceptionally(SdkClientException.create("Failed to send request", t));
} else {
returnFuture.complete(CompletedDirectoryDownload.builder()
.failedTransfers(failedFileDownloads)
.build());
}
});
}
private Function<S3Object, CompletableFuture<?>> downloadSingleFile(
CompletableFuture<CompletedDirectoryDownload> returnFuture,
DownloadDirectoryRequest downloadDirectoryRequest,
ListObjectsV2Request listRequest,
Queue<FailedFileDownload> failedFileDownloads) {
return s3Object -> {
CompletableFuture<CompletedFileDownload> future = doDownloadSingleFile(downloadDirectoryRequest,
failedFileDownloads,
listRequest,
s3Object);
CompletableFutureUtils.forwardExceptionTo(returnFuture, future);
return future;
};
}
private Path determineDestinationPath(DownloadDirectoryRequest downloadDirectoryRequest,
ListObjectsV2Request listRequest,
S3Object s3Object) {
FileSystem fileSystem = downloadDirectoryRequest.destination().getFileSystem();
String delimiter = listRequest.delimiter() == null ? DEFAULT_DELIMITER : listRequest.delimiter();
String key = normalizeKey(listRequest, s3Object.key(), delimiter);
String relativePath = getRelativePath(fileSystem, delimiter, key);
Path destinationPath = downloadDirectoryRequest.destination().resolve(relativePath);
validatePath(downloadDirectoryRequest.destination(), destinationPath, s3Object.key());
return destinationPath;
}
private void validatePath(Path destinationDirectory, Path targetPath, String key) {
if (!targetPath.toAbsolutePath().normalize().startsWith(destinationDirectory.toAbsolutePath().normalize())) {
throw SdkClientException.create("Cannot download key " + key +
", its relative path resolves outside the parent directory.");
}
}
private CompletableFuture<CompletedFileDownload> doDownloadSingleFile(DownloadDirectoryRequest downloadDirectoryRequest,
Collection<FailedFileDownload> failedFileDownloads,
ListObjectsV2Request listRequest,
S3Object s3Object) {
Path destinationPath = determineDestinationPath(downloadDirectoryRequest, listRequest, s3Object);
DownloadFileRequest downloadFileRequest = downloadFileRequest(downloadDirectoryRequest, s3Object, destinationPath);
try {
log.debug(() -> "Sending download request " + downloadFileRequest);
createParentDirectoriesIfNeeded(destinationPath);
CompletableFuture<CompletedFileDownload> executionFuture =
downloadFileFunction.apply(downloadFileRequest).completionFuture();
CompletableFuture<CompletedFileDownload> future = executionFuture.whenComplete((r, t) -> {
if (t != null) {
failedFileDownloads.add(FailedFileDownload.builder()
.exception(t instanceof CompletionException ? t.getCause() : t)
.request(downloadFileRequest)
.build());
}
});
CompletableFutureUtils.forwardExceptionTo(future, executionFuture);
return future;
} catch (Throwable throwable) {
failedFileDownloads.add(FailedFileDownload.builder()
.exception(throwable)
.request(downloadFileRequest)
.build());
return CompletableFutureUtils.failedFuture(throwable);
}
}
/**
* If the prefix is not empty AND the key contains the delimiter, normalize the key by stripping the prefix from the key.
*
* If a delimiter is null (not provided by user), use "/" by default.
*
* For example: given a request with prefix = "notes/2021" or "notes/2021/", delimiter = "/" and key = "notes/2021/1.txt",
* the normalized key should be "1.txt".
*/
private static String normalizeKey(ListObjectsV2Request listObjectsRequest,
String key,
String delimiter) {
if (StringUtils.isEmpty(listObjectsRequest.prefix())) {
return key;
}
String prefix = listObjectsRequest.prefix();
if (!key.contains(delimiter)) {
return key;
}
String normalizedKey;
if (prefix.endsWith(delimiter)) {
normalizedKey = key.substring(prefix.length());
} else {
normalizedKey = key.substring(prefix.length() + delimiter.length());
}
return normalizedKey;
}
private static String getRelativePath(FileSystem fileSystem, String delimiter, String key) {
if (delimiter == null) {
return key;
}
if (fileSystem.getSeparator().equals(delimiter)) {
return key;
}
return StringUtils.replace(key, delimiter, fileSystem.getSeparator());
}
private static DownloadFileRequest downloadFileRequest(DownloadDirectoryRequest downloadDirectoryRequest,
S3Object s3Object, Path destinationPath) {
GetObjectRequest getObjectRequest = GetObjectRequest.builder()
.bucket(downloadDirectoryRequest.bucket())
.key(s3Object.key())
.build();
return DownloadFileRequest.builder()
.destination(destinationPath)
.getObjectRequest(getObjectRequest)
.applyMutation(downloadDirectoryRequest.downloadFileRequestTransformer())
.build();
}
private static void createParentDirectoriesIfNeeded(Path destinationPath) {
Path parentDirectory = destinationPath.getParent();
try {
if (parentDirectory != null) {
Files.createDirectories(parentDirectory);
}
} catch (IOException e) {
throw SdkClientException.create("Failed to create parent directories for " + destinationPath, e);
}
}
}
| 3,762 |
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/internal/TransferConfigurationOption.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal;
import java.util.concurrent.Executor;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.utils.AttributeMap;
/**
* A set of internal options required by the {@link TransferManagerFactory} via {@link TransferManagerConfiguration}.
* It contains the default settings
*
*/
@SdkInternalApi
public final class TransferConfigurationOption<T> extends AttributeMap.Key<T> {
public static final TransferConfigurationOption<Integer> UPLOAD_DIRECTORY_MAX_DEPTH =
new TransferConfigurationOption<>("UploadDirectoryMaxDepth", Integer.class);
public static final TransferConfigurationOption<Boolean> UPLOAD_DIRECTORY_FOLLOW_SYMBOLIC_LINKS =
new TransferConfigurationOption<>("UploadDirectoryFileVisitOption", Boolean.class);
public static final TransferConfigurationOption<Executor> EXECUTOR =
new TransferConfigurationOption<>("Executor", Executor.class);
public static final String DEFAULT_DELIMITER = "/";
public static final String DEFAULT_PREFIX = "";
public static final int DEFAULT_DOWNLOAD_DIRECTORY_MAX_CONCURRENCY = 100;
private static final int DEFAULT_UPLOAD_DIRECTORY_MAX_DEPTH = Integer.MAX_VALUE;
public static final AttributeMap TRANSFER_MANAGER_DEFAULTS = AttributeMap
.builder()
.put(UPLOAD_DIRECTORY_MAX_DEPTH, DEFAULT_UPLOAD_DIRECTORY_MAX_DEPTH)
.put(UPLOAD_DIRECTORY_FOLLOW_SYMBOLIC_LINKS, false)
.build();
private final String name;
private TransferConfigurationOption(String name, Class<T> clzz) {
super(clzz);
this.name = name;
}
/**
* Note that the name is mainly used for debugging purposes. Two option key objects with the same name do not represent
* the same option. Option keys are compared by reference when obtaining a value from an {@link AttributeMap}.
*
* @return Name of this option key.
*/
public String name() {
return name;
}
@Override
public String toString() {
return name;
}
}
| 3,763 |
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/internal/S3ClientType.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.services.s3.S3AsyncClient;
/**
* Enum type to indicate the implementation of {@link S3AsyncClient}
*/
@SdkInternalApi
public enum S3ClientType {
CRT_BASED,
JAVA_BASED,
OTHER
}
| 3,764 |
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/internal/ApplyUserAgentInterceptor.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.transfer.s3.internal;
import java.util.function.Consumer;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration;
import software.amazon.awssdk.core.ApiName;
import software.amazon.awssdk.core.SdkRequest;
import software.amazon.awssdk.core.interceptor.Context;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.interceptor.ExecutionInterceptor;
import software.amazon.awssdk.services.s3.model.S3Request;
/**
* Apply TM specific user agent to the request
*/
@SdkInternalApi
public final class ApplyUserAgentInterceptor implements ExecutionInterceptor {
private static final ApiName API_NAME =
ApiName.builder().name("ft").version("s3-transfer").build();
private static final Consumer<AwsRequestOverrideConfiguration.Builder> USER_AGENT_APPLIER =
b -> b.addApiName(API_NAME);
@Override
public SdkRequest modifyRequest(Context.ModifyRequest context, ExecutionAttributes executionAttributes) {
assert context.request() instanceof S3Request;
S3Request request = (S3Request) context.request();
AwsRequestOverrideConfiguration overrideConfiguration =
request.overrideConfiguration()
.map(c -> c.toBuilder()
.applyMutation(USER_AGENT_APPLIER)
.build())
.orElseGet(() -> AwsRequestOverrideConfiguration.builder()
.applyMutation(USER_AGENT_APPLIER)
.build());
return request.toBuilder().overrideConfiguration(overrideConfiguration).build();
}
}
| 3,765 |
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/internal/UploadDirectoryHelper.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal;
import static software.amazon.awssdk.transfer.s3.internal.TransferConfigurationOption.DEFAULT_DELIMITER;
import static software.amazon.awssdk.transfer.s3.internal.TransferConfigurationOption.DEFAULT_PREFIX;
import java.io.IOException;
import java.nio.file.FileVisitOption;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.transfer.s3.internal.model.DefaultDirectoryUpload;
import software.amazon.awssdk.transfer.s3.model.CompletedDirectoryUpload;
import software.amazon.awssdk.transfer.s3.model.CompletedFileUpload;
import software.amazon.awssdk.transfer.s3.model.DirectoryUpload;
import software.amazon.awssdk.transfer.s3.model.FailedFileUpload;
import software.amazon.awssdk.transfer.s3.model.FileUpload;
import software.amazon.awssdk.transfer.s3.model.UploadDirectoryRequest;
import software.amazon.awssdk.transfer.s3.model.UploadFileRequest;
import software.amazon.awssdk.utils.CompletableFutureUtils;
import software.amazon.awssdk.utils.Logger;
import software.amazon.awssdk.utils.StringUtils;
import software.amazon.awssdk.utils.Validate;
/**
* An internal helper class that traverses the file tree and send the upload request
* for each file.
*/
@SdkInternalApi
public class UploadDirectoryHelper {
private static final Logger log = Logger.loggerFor(S3TransferManager.class);
private final TransferManagerConfiguration transferConfiguration;
private final Function<UploadFileRequest, FileUpload> uploadFunction;
public UploadDirectoryHelper(TransferManagerConfiguration transferConfiguration,
Function<UploadFileRequest, FileUpload> uploadFunction) {
this.transferConfiguration = transferConfiguration;
this.uploadFunction = uploadFunction;
}
public DirectoryUpload uploadDirectory(UploadDirectoryRequest uploadDirectoryRequest) {
CompletableFuture<CompletedDirectoryUpload> returnFuture = new CompletableFuture<>();
// offload the execution to the transfer manager executor
CompletableFuture.runAsync(() -> doUploadDirectory(returnFuture, uploadDirectoryRequest),
transferConfiguration.option(TransferConfigurationOption.EXECUTOR))
.whenComplete((r, t) -> {
if (t != null) {
returnFuture.completeExceptionally(t);
}
});
return new DefaultDirectoryUpload(returnFuture);
}
private void doUploadDirectory(CompletableFuture<CompletedDirectoryUpload> returnFuture,
UploadDirectoryRequest uploadDirectoryRequest) {
Path directory = uploadDirectoryRequest.source();
validateDirectory(uploadDirectoryRequest);
Collection<FailedFileUpload> failedFileUploads = new ConcurrentLinkedQueue<>();
List<CompletableFuture<CompletedFileUpload>> futures;
try (Stream<Path> entries = listFiles(directory, uploadDirectoryRequest)) {
futures = entries.map(path -> {
CompletableFuture<CompletedFileUpload> future = uploadSingleFile(uploadDirectoryRequest,
failedFileUploads, path);
// Forward cancellation of the return future to all individual futures.
CompletableFutureUtils.forwardExceptionTo(returnFuture, future);
return future;
}).collect(Collectors.toList());
}
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
.whenComplete((r, t) -> returnFuture.complete(CompletedDirectoryUpload.builder()
.failedTransfers(failedFileUploads)
.build()));
}
private void validateDirectory(UploadDirectoryRequest uploadDirectoryRequest) {
Path directory = uploadDirectoryRequest.source();
Validate.isTrue(Files.exists(directory), "The source directory provided (%s) does not exist", directory);
boolean followSymbolicLinks = transferConfiguration.resolveUploadDirectoryFollowSymbolicLinks(uploadDirectoryRequest);
if (followSymbolicLinks) {
Validate.isTrue(Files.isDirectory(directory), "The source directory provided (%s) is not a "
+ "directory", directory);
} else {
Validate.isTrue(Files.isDirectory(directory, LinkOption.NOFOLLOW_LINKS), "The source directory provided (%s)"
+ " is not a "
+ "directory", directory);
}
}
private CompletableFuture<CompletedFileUpload> uploadSingleFile(UploadDirectoryRequest uploadDirectoryRequest,
Collection<FailedFileUpload> failedFileUploads,
Path path) {
int nameCount = uploadDirectoryRequest.source().getNameCount();
UploadFileRequest uploadFileRequest = constructUploadRequest(uploadDirectoryRequest, nameCount, path);
log.debug(() -> String.format("Sending upload request (%s) for path (%s)", uploadFileRequest, path));
CompletableFuture<CompletedFileUpload> executionFuture = uploadFunction.apply(uploadFileRequest).completionFuture();
CompletableFuture<CompletedFileUpload> future = executionFuture.whenComplete((r, t) -> {
if (t != null) {
failedFileUploads.add(FailedFileUpload.builder()
.exception(t instanceof CompletionException ? t.getCause() : t)
.request(uploadFileRequest)
.build());
}
});
CompletableFutureUtils.forwardExceptionTo(future, executionFuture);
return future;
}
private Stream<Path> listFiles(Path directory, UploadDirectoryRequest request) {
try {
boolean followSymbolicLinks = transferConfiguration.resolveUploadDirectoryFollowSymbolicLinks(request);
int maxDepth = transferConfiguration.resolveUploadDirectoryMaxDepth(request);
if (followSymbolicLinks) {
return Files.walk(directory, maxDepth, FileVisitOption.FOLLOW_LINKS)
.filter(path -> isRegularFile(path, true));
}
return Files.walk(directory, maxDepth)
.filter(path -> isRegularFile(path, false));
} catch (IOException e) {
throw SdkClientException.create("Failed to list files within the provided directory: " + directory, e);
}
}
private boolean isRegularFile(Path path, boolean followSymlinks) {
if (followSymlinks) {
return Files.isRegularFile(path);
}
return Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS);
}
/**
* If the prefix already ends with the same string as delimiter, there is no need to add delimiter.
*/
private static String normalizePrefix(String prefix, String delimiter) {
if (StringUtils.isEmpty(prefix)) {
return "";
}
return prefix.endsWith(delimiter) ? prefix : prefix + delimiter;
}
private String getRelativePathName(Path source, int directoryNameCount, Path path, String delimiter) {
String relativePathName = path.subpath(directoryNameCount,
path.getNameCount()).toString();
String separator = source.getFileSystem().getSeparator();
// Optimization for the case where separator equals to the delimiter: there is no need to call String#replace which
// invokes Pattern#compile in Java 8
if (delimiter.equals(separator)) {
return relativePathName;
}
return StringUtils.replace(relativePathName, separator, delimiter);
}
private UploadFileRequest constructUploadRequest(UploadDirectoryRequest uploadDirectoryRequest,
int directoryNameCount,
Path path) {
String delimiter =
uploadDirectoryRequest.s3Delimiter()
.filter(s -> !s.isEmpty())
.orElse(DEFAULT_DELIMITER);
String prefix = uploadDirectoryRequest.s3Prefix()
.map(s -> normalizePrefix(s, delimiter))
.orElse(DEFAULT_PREFIX);
String relativePathName = getRelativePathName(uploadDirectoryRequest.source(),
directoryNameCount,
path,
delimiter);
String key = prefix + relativePathName;
PutObjectRequest putObjectRequest = PutObjectRequest.builder()
.bucket(uploadDirectoryRequest.bucket())
.key(key)
.build();
UploadFileRequest.Builder requestBuilder = UploadFileRequest.builder()
.source(path)
.putObjectRequest(putObjectRequest);
uploadDirectoryRequest.uploadFileRequestTransformer().accept(requestBuilder);
return requestBuilder.build();
}
}
| 3,766 |
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/internal/TransferManagerFactory.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal;
import java.util.concurrent.Executor;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.internal.util.ClassLoaderHelper;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.internal.crt.S3CrtAsyncClient;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.utils.Logger;
/**
* An {@link S3TransferManager} factory that instantiate an {@link S3TransferManager} implementation based on the underlying
* {@link S3AsyncClient}.
*/
@SdkInternalApi
public final class TransferManagerFactory {
private static final Logger log = Logger.loggerFor(S3TransferManager.class);
private TransferManagerFactory() {
}
public static S3TransferManager createTransferManager(DefaultBuilder tmBuilder) {
TransferManagerConfiguration transferConfiguration = resolveTransferManagerConfiguration(tmBuilder);
S3AsyncClient s3AsyncClient;
boolean isDefaultS3AsyncClient;
if (tmBuilder.s3AsyncClient == null) {
isDefaultS3AsyncClient = true;
s3AsyncClient = defaultS3AsyncClient().get();
} else {
isDefaultS3AsyncClient = false;
s3AsyncClient = tmBuilder.s3AsyncClient;
}
if (s3AsyncClient instanceof S3CrtAsyncClient) {
return new CrtS3TransferManager(transferConfiguration, s3AsyncClient, isDefaultS3AsyncClient);
}
if (s3AsyncClient.getClass().getName().equals("software.amazon.awssdk.services.s3.DefaultS3AsyncClient")) {
log.warn(() -> "The provided DefaultS3AsyncClient is not an instance of S3CrtAsyncClient, and thus multipart"
+ " upload/download feature is not enabled and resumable file upload is not supported. To benefit "
+ "from maximum throughput, consider using S3AsyncClient.crtBuilder().build() instead.");
} else {
log.debug(() -> "The provided S3AsyncClient is not an instance of S3CrtAsyncClient, and thus multipart"
+ " upload/download feature may not be enabled and resumable file upload may not be supported.");
}
return new GenericS3TransferManager(transferConfiguration, s3AsyncClient, isDefaultS3AsyncClient);
}
private static Supplier<S3AsyncClient> defaultS3AsyncClient() {
if (crtInClasspath()) {
return S3AsyncClient::crtCreate;
}
return S3AsyncClient::create;
}
private static boolean crtInClasspath() {
try {
ClassLoaderHelper.loadClass("software.amazon.awssdk.crt.s3.S3Client", false);
} catch (ClassNotFoundException e) {
return false;
}
return true;
}
private static TransferManagerConfiguration resolveTransferManagerConfiguration(DefaultBuilder tmBuilder) {
TransferManagerConfiguration.Builder transferConfigBuilder = TransferManagerConfiguration.builder();
transferConfigBuilder.uploadDirectoryFollowSymbolicLinks(tmBuilder.uploadDirectoryFollowSymbolicLinks);
transferConfigBuilder.uploadDirectoryMaxDepth(tmBuilder.uploadDirectoryMaxDepth);
transferConfigBuilder.executor(tmBuilder.executor);
return transferConfigBuilder.build();
}
public static final class DefaultBuilder implements S3TransferManager.Builder {
private S3AsyncClient s3AsyncClient;
private Executor executor;
private Boolean uploadDirectoryFollowSymbolicLinks;
private Integer uploadDirectoryMaxDepth;
@Override
public DefaultBuilder s3Client(S3AsyncClient s3AsyncClient) {
this.s3AsyncClient = s3AsyncClient;
return this;
}
@Override
public DefaultBuilder executor(Executor executor) {
this.executor = executor;
return this;
}
@Override
public DefaultBuilder uploadDirectoryFollowSymbolicLinks(Boolean uploadDirectoryFollowSymbolicLinks) {
this.uploadDirectoryFollowSymbolicLinks = uploadDirectoryFollowSymbolicLinks;
return this;
}
public void setUploadDirectoryFollowSymbolicLinks(Boolean followSymbolicLinks) {
uploadDirectoryFollowSymbolicLinks(followSymbolicLinks);
}
public Boolean getUploadDirectoryFollowSymbolicLinks() {
return uploadDirectoryFollowSymbolicLinks;
}
@Override
public DefaultBuilder uploadDirectoryMaxDepth(Integer uploadDirectoryMaxDepth) {
this.uploadDirectoryMaxDepth = uploadDirectoryMaxDepth;
return this;
}
public void setUploadDirectoryMaxDepth(Integer uploadDirectoryMaxDepth) {
uploadDirectoryMaxDepth(uploadDirectoryMaxDepth);
}
public Integer getUploadDirectoryMaxDepth() {
return uploadDirectoryMaxDepth;
}
@Override
public S3TransferManager build() {
return createTransferManager(this);
}
}
}
| 3,767 |
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/internal/ListObjectsHelper.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal;
import java.util.Collections;
import java.util.Deque;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.function.Function;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.async.SdkPublisher;
import software.amazon.awssdk.core.pagination.async.AsyncPageFetcher;
import software.amazon.awssdk.core.pagination.async.PaginatedItemsPublisher;
import software.amazon.awssdk.core.util.PaginatorUtils;
import software.amazon.awssdk.services.s3.model.CommonPrefix;
import software.amazon.awssdk.services.s3.model.ListObjectsV2Request;
import software.amazon.awssdk.services.s3.model.ListObjectsV2Response;
import software.amazon.awssdk.services.s3.model.S3Object;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.utils.CollectionUtils;
import software.amazon.awssdk.utils.Logger;
/**
* A helper class that returns all objects within a bucket given a {@link ListObjectsV2Request} recursively.
*/
@SdkInternalApi
public class ListObjectsHelper {
private static final Logger logger = Logger.loggerFor(S3TransferManager.class);
private final Function<ListObjectsV2Request, CompletableFuture<ListObjectsV2Response>> listObjectsFunction;
private final S3ObjectsIteratorFunction objectsIteratorFunction;
public ListObjectsHelper(Function<ListObjectsV2Request,
CompletableFuture<ListObjectsV2Response>> listObjectsFunction) {
this .objectsIteratorFunction = new S3ObjectsIteratorFunction();
this.listObjectsFunction = listObjectsFunction;
}
public SdkPublisher<S3Object> listS3ObjectsRecursively(ListObjectsV2Request firstRequest) {
return PaginatedItemsPublisher.builder().nextPageFetcher(new ListObjectsV2ResponseFetcher(firstRequest))
.iteratorFunction(objectsIteratorFunction).isLastPage(false).build();
}
private static final class S3ObjectsIteratorFunction implements Function<ListObjectsV2Response, Iterator<S3Object>> {
@Override
public Iterator<S3Object> apply(ListObjectsV2Response response) {
if (response != null && !CollectionUtils.isNullOrEmpty(response.contents())) {
return response.contents().stream().filter(r -> {
if (response.prefix() != null && response.prefix().equals(r.key())) {
logger.debug(() -> "Skipping download for object (" + r.key() + ") since it is a virtual directory");
return false;
}
return true;
}).iterator();
}
return Collections.emptyIterator();
}
}
private final class ListObjectsV2ResponseFetcher implements AsyncPageFetcher<ListObjectsV2Response> {
private final Deque<String> commonPrefixes = new ConcurrentLinkedDeque<>();
private volatile ListObjectsV2Request firstRequest;
private ListObjectsV2ResponseFetcher(ListObjectsV2Request firstRequest) {
this.firstRequest = firstRequest;
}
@Override
public boolean hasNextPage(ListObjectsV2Response previousPage) {
return PaginatorUtils.isOutputTokenAvailable(previousPage.nextContinuationToken()) ||
!commonPrefixes.isEmpty();
}
@Override
public CompletableFuture<ListObjectsV2Response> nextPage(ListObjectsV2Response previousPage) {
CompletableFuture<ListObjectsV2Response> future;
if (previousPage == null) {
// If this is the first request
future = listObjectsFunction.apply(firstRequest);
} else if (PaginatorUtils.isOutputTokenAvailable(previousPage.nextContinuationToken())) {
// If there is a next page with the same prefix
future =
listObjectsFunction.apply(firstRequest.toBuilder()
.continuationToken(previousPage.nextContinuationToken())
.build());
} else {
// If there is no next page, we should start with the next common prefix
String nextPrefix = commonPrefixes.pop();
firstRequest = firstRequest.toBuilder().prefix(nextPrefix).build();
future = listObjectsFunction.apply(firstRequest);
}
return future.thenApply(t -> {
List<CommonPrefix> newCommonPrefixes = t.commonPrefixes();
for (int i = newCommonPrefixes.size() - 1; i >= 0; i--) {
commonPrefixes.push(newCommonPrefixes.get(i).prefix());
}
return t;
});
}
}
}
| 3,768 |
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/internal/DelegatingS3TransferManager.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.transfer.s3.model.Copy;
import software.amazon.awssdk.transfer.s3.model.CopyRequest;
import software.amazon.awssdk.transfer.s3.model.DirectoryDownload;
import software.amazon.awssdk.transfer.s3.model.DirectoryUpload;
import software.amazon.awssdk.transfer.s3.model.Download;
import software.amazon.awssdk.transfer.s3.model.DownloadDirectoryRequest;
import software.amazon.awssdk.transfer.s3.model.DownloadFileRequest;
import software.amazon.awssdk.transfer.s3.model.DownloadRequest;
import software.amazon.awssdk.transfer.s3.model.FileDownload;
import software.amazon.awssdk.transfer.s3.model.FileUpload;
import software.amazon.awssdk.transfer.s3.model.ResumableFileDownload;
import software.amazon.awssdk.transfer.s3.model.Upload;
import software.amazon.awssdk.transfer.s3.model.UploadDirectoryRequest;
import software.amazon.awssdk.transfer.s3.model.UploadFileRequest;
import software.amazon.awssdk.transfer.s3.model.UploadRequest;
/**
* An {@link S3TransferManager} that just delegates to another {@link S3TransferManager}.
*/
@SdkInternalApi
abstract class DelegatingS3TransferManager implements S3TransferManager {
private final S3TransferManager delegate;
protected DelegatingS3TransferManager(S3TransferManager delegate) {
this.delegate = delegate;
}
@Override
public Upload upload(UploadRequest uploadRequest) {
return delegate.upload(uploadRequest);
}
@Override
public FileUpload uploadFile(UploadFileRequest uploadFileRequest) {
return delegate.uploadFile(uploadFileRequest);
}
@Override
public DirectoryUpload uploadDirectory(UploadDirectoryRequest uploadDirectoryRequest) {
return delegate.uploadDirectory(uploadDirectoryRequest);
}
@Override
public <ResultT> Download<ResultT> download(DownloadRequest<ResultT> downloadRequest) {
return delegate.download(downloadRequest);
}
@Override
public FileDownload downloadFile(DownloadFileRequest downloadRequest) {
return delegate.downloadFile(downloadRequest);
}
@Override
public FileDownload resumeDownloadFile(ResumableFileDownload resumableFileDownload) {
return delegate.resumeDownloadFile(resumableFileDownload);
}
@Override
public DirectoryDownload downloadDirectory(DownloadDirectoryRequest downloadDirectoryRequest) {
return delegate.downloadDirectory(downloadDirectoryRequest);
}
@Override
public Copy copy(CopyRequest copyRequest) {
return delegate.copy(copyRequest);
}
@Override
public void close() {
delegate.close();
}
}
| 3,769 |
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/internal/TransferManagerConfiguration.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal;
import static software.amazon.awssdk.transfer.s3.internal.TransferConfigurationOption.TRANSFER_MANAGER_DEFAULTS;
import static software.amazon.awssdk.transfer.s3.internal.TransferConfigurationOption.UPLOAD_DIRECTORY_FOLLOW_SYMBOLIC_LINKS;
import static software.amazon.awssdk.transfer.s3.internal.TransferConfigurationOption.UPLOAD_DIRECTORY_MAX_DEPTH;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.transfer.s3.model.UploadDirectoryRequest;
import software.amazon.awssdk.utils.AttributeMap;
import software.amazon.awssdk.utils.ExecutorUtils;
import software.amazon.awssdk.utils.SdkAutoCloseable;
import software.amazon.awssdk.utils.ThreadFactoryBuilder;
/**
* Contains resolved configuration settings for {@link GenericS3TransferManager}.
* This configuration object can be {@link #close()}d to release all closeable resources configured within it.
*/
@SdkInternalApi
public class TransferManagerConfiguration implements SdkAutoCloseable {
private final AttributeMap options;
private TransferManagerConfiguration(Builder builder) {
AttributeMap.Builder standardOptions = AttributeMap.builder();
standardOptions.put(UPLOAD_DIRECTORY_FOLLOW_SYMBOLIC_LINKS, builder.uploadDirectoryFollowSymbolicLinks);
standardOptions.put(UPLOAD_DIRECTORY_MAX_DEPTH, builder.uploadDirectoryMaxDepth);
finalizeExecutor(builder, standardOptions);
options = standardOptions.build().merge(TRANSFER_MANAGER_DEFAULTS);
}
private void finalizeExecutor(Builder builder, AttributeMap.Builder standardOptions) {
if (builder.executor != null) {
standardOptions.put(TransferConfigurationOption.EXECUTOR, ExecutorUtils.unmanagedExecutor(builder.executor));
} else {
standardOptions.put(TransferConfigurationOption.EXECUTOR, defaultExecutor());
}
}
/**
* Retrieve the value of a specific option.
*/
public <T> T option(TransferConfigurationOption<T> option) {
return options.get(option);
}
public boolean resolveUploadDirectoryFollowSymbolicLinks(UploadDirectoryRequest request) {
return request.followSymbolicLinks()
.orElseGet(() -> options.get(UPLOAD_DIRECTORY_FOLLOW_SYMBOLIC_LINKS));
}
public int resolveUploadDirectoryMaxDepth(UploadDirectoryRequest request) {
return request.maxDepth()
.orElseGet(() -> options.get(UPLOAD_DIRECTORY_MAX_DEPTH));
}
@Override
public void close() {
options.close();
}
private Executor defaultExecutor() {
int maxPoolSize = 100;
ThreadPoolExecutor executor = new ThreadPoolExecutor(0, maxPoolSize,
60, TimeUnit.SECONDS,
new LinkedBlockingQueue<>(1_000),
new ThreadFactoryBuilder()
.threadNamePrefix("s3-transfer-manager").build());
// Allow idle core threads to time out
executor.allowCoreThreadTimeOut(true);
return executor;
}
public static Builder builder() {
return new Builder();
}
public static final class Builder {
private Boolean uploadDirectoryFollowSymbolicLinks;
private Integer uploadDirectoryMaxDepth;
private Executor executor;
public Builder uploadDirectoryFollowSymbolicLinks(Boolean uploadDirectoryFollowSymbolicLinks) {
this.uploadDirectoryFollowSymbolicLinks = uploadDirectoryFollowSymbolicLinks;
return this;
}
public Builder uploadDirectoryMaxDepth(Integer uploadDirectoryMaxDepth) {
this.uploadDirectoryMaxDepth = uploadDirectoryMaxDepth;
return this;
}
public Builder executor(Executor executor) {
this.executor = executor;
return this;
}
public TransferManagerConfiguration build() {
return new TransferManagerConfiguration(this);
}
}
}
| 3,770 |
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/internal/AsyncBufferingSubscriber.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.utils.Logger;
import software.amazon.awssdk.utils.Validate;
/**
* An implementation of {@link Subscriber} that execute the provided function for every event and limits the number of concurrent
* function execution to the given {@code maxConcurrentRequests}
*
* @param <T> Type of data requested
*/
@SdkInternalApi
public class AsyncBufferingSubscriber<T> implements Subscriber<T> {
private static final Logger log = Logger.loggerFor(AsyncBufferingSubscriber.class);
private final CompletableFuture<?> returnFuture;
private final Function<T, CompletableFuture<?>> consumer;
private final int maxConcurrentExecutions;
private final AtomicInteger numRequestsInFlight;
private volatile boolean upstreamDone;
private Subscription subscription;
public AsyncBufferingSubscriber(Function<T, CompletableFuture<?>> consumer,
CompletableFuture<Void> returnFuture,
int maxConcurrentExecutions) {
this.returnFuture = returnFuture;
this.consumer = consumer;
this.maxConcurrentExecutions = maxConcurrentExecutions;
this.numRequestsInFlight = new AtomicInteger(0);
}
@Override
public void onSubscribe(Subscription subscription) {
Validate.paramNotNull(subscription, "subscription");
if (this.subscription != null) {
log.warn(() -> "The subscriber has already been subscribed. Cancelling the incoming subscription");
subscription.cancel();
return;
}
this.subscription = subscription;
subscription.request(maxConcurrentExecutions);
}
@Override
public void onNext(T item) {
numRequestsInFlight.incrementAndGet();
consumer.apply(item).whenComplete((r, t) -> {
checkForCompletion(numRequestsInFlight.decrementAndGet());
synchronized (this) {
subscription.request(1);
}
});
}
@Override
public void onError(Throwable t) {
// Need to complete future exceptionally first to prevent
// accidental successful completion by a concurrent checkForCompletion.
returnFuture.completeExceptionally(t);
upstreamDone = true;
}
@Override
public void onComplete() {
upstreamDone = true;
checkForCompletion(numRequestsInFlight.get());
}
private void checkForCompletion(int requestsInFlight) {
if (upstreamDone && requestsInFlight == 0) {
// This could get invoked multiple times, but it doesn't matter
// because future.complete is idempotent.
returnFuture.complete(null);
}
}
/**
* @return the number of requests that are currently in flight
*/
public int numRequestsInFlight() {
return numRequestsInFlight.get();
}
}
| 3,771 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/internal | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/internal/progress/TransferListenerFailedContext.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.progress;
import java.util.concurrent.CompletionException;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.transfer.s3.model.TransferObjectRequest;
import software.amazon.awssdk.transfer.s3.progress.TransferListener;
import software.amazon.awssdk.transfer.s3.progress.TransferProgressSnapshot;
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 SDK-internal implementation of {@link TransferListener.Context.TransferFailed}.
*
* @see TransferListenerContext
*/
@SdkInternalApi
@Immutable
public class TransferListenerFailedContext
implements TransferListener.Context.TransferFailed,
ToCopyableBuilder<TransferListenerFailedContext.Builder, TransferListenerFailedContext> {
private final TransferListenerContext transferContext;
private final Throwable exception;
private TransferListenerFailedContext(Builder builder) {
this.exception = unwrap(Validate.paramNotNull(builder.exception, "exception"));
this.transferContext = Validate.paramNotNull(builder.transferContext, "transferContext");
}
private Throwable unwrap(Throwable exception) {
while (exception instanceof CompletionException) {
exception = exception.getCause();
}
return exception;
}
public static Builder builder() {
return new Builder();
}
@Override
public Builder toBuilder() {
return new Builder(this);
}
@Override
public TransferObjectRequest request() {
return transferContext.request();
}
@Override
public TransferProgressSnapshot progressSnapshot() {
return transferContext.progressSnapshot();
}
@Override
public Throwable exception() {
return exception;
}
@Override
public String toString() {
return ToString.builder("TransferListenerFailedContext")
.add("transferContext", transferContext)
.add("exception", exception)
.build();
}
public static final class Builder implements CopyableBuilder<Builder, TransferListenerFailedContext> {
private TransferListenerContext transferContext;
private Throwable exception;
private Builder() {
}
private Builder(TransferListenerFailedContext failedContext) {
this.exception = failedContext.exception;
this.transferContext = failedContext.transferContext;
}
public Builder exception(Throwable exception) {
this.exception = exception;
return this;
}
public Builder transferContext(TransferListenerContext transferContext) {
this.transferContext = transferContext;
return this;
}
@Override
public TransferListenerFailedContext build() {
return new TransferListenerFailedContext(this);
}
}
}
| 3,772 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/internal | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/internal/progress/TransferListenerInvoker.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.progress;
import static software.amazon.awssdk.utils.FunctionalUtils.runAndLogError;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.transfer.s3.progress.TransferListener;
import software.amazon.awssdk.utils.Logger;
import software.amazon.awssdk.utils.Validate;
/**
* An SDK-internal helper class that composes multiple provided {@link TransferListener}s together into a single logical chain.
* Invocations on {@link TransferListenerInvoker} will be delegated to the underlying chain, while suppressing (and logging) any
* exceptions that are thrown.
*/
@SdkInternalApi
public class TransferListenerInvoker implements TransferListener {
private static final Logger log = Logger.loggerFor(TransferListener.class);
private final List<TransferListener> listeners;
private final AtomicBoolean initiated = new AtomicBoolean();
private final AtomicBoolean complete = new AtomicBoolean();
public TransferListenerInvoker(List<TransferListener> listeners) {
this.listeners = Validate.paramNotNull(listeners, "listeners");
}
@Override
public void transferInitiated(Context.TransferInitiated context) {
if (!initiated.getAndSet(true)) {
forEach(listener -> listener.transferInitiated(context));
}
}
@Override
public void bytesTransferred(Context.BytesTransferred context) {
forEach(listener -> listener.bytesTransferred(context));
}
@Override
public void transferComplete(Context.TransferComplete context) {
if (!complete.getAndSet(true)) {
forEach(listener -> listener.transferComplete(context));
}
}
@Override
public void transferFailed(Context.TransferFailed context) {
if (!complete.getAndSet(true)) {
forEach(listener -> listener.transferFailed(context));
}
}
private void forEach(Consumer<TransferListener> action) {
for (TransferListener listener : listeners) {
runAndLogError(log.logger(), "Exception thrown in TransferListener, ignoring",
() -> action.accept(listener));
}
}
}
| 3,773 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/internal | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/internal/progress/DefaultTransferProgress.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.progress;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import software.amazon.awssdk.annotations.Mutable;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.transfer.s3.internal.progress.DefaultTransferProgressSnapshot.Builder;
import software.amazon.awssdk.transfer.s3.progress.TransferProgress;
import software.amazon.awssdk.transfer.s3.progress.TransferProgressSnapshot;
import software.amazon.awssdk.utils.ToString;
/**
* An SDK-internal implementation of {@link TransferProgress}. This implementation acts as a thin wrapper around {@link
* AtomicReference}, where calls to get the latest {@link #snapshot()} simply return the latest reference, while {@link
* TransferProgressUpdater} is responsible for continuously updating the latest reference.
*
* @see TransferProgress
*/
@Mutable
@ThreadSafe
@SdkInternalApi
public final class DefaultTransferProgress implements TransferProgress {
private final AtomicReference<TransferProgressSnapshot> snapshot;
public DefaultTransferProgress(TransferProgressSnapshot snapshot) {
this.snapshot = new AtomicReference<>(snapshot);
}
/**
* Atomically convert the current snapshot reference to its {@link Builder}, perform updates using the provided {@link
* Consumer}, and save the result as the latest snapshot.
*/
public TransferProgressSnapshot updateAndGet(Consumer<DefaultTransferProgressSnapshot.Builder> updater) {
return this.snapshot.updateAndGet(s -> ((DefaultTransferProgressSnapshot) s).copy(updater));
}
@Override
public TransferProgressSnapshot snapshot() {
return snapshot.get();
}
@Override
public String toString() {
return ToString.builder("TransferProgress")
.add("snapshot", snapshot)
.build();
}
}
| 3,774 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/internal | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/internal/progress/DefaultTransferProgressSnapshot.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.progress;
import java.util.Objects;
import java.util.Optional;
import java.util.OptionalDouble;
import java.util.OptionalLong;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.SdkResponse;
import software.amazon.awssdk.transfer.s3.progress.TransferProgressSnapshot;
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 SDK-internal implementation of {@link TransferProgressSnapshot}.
*/
@SdkInternalApi
public final class DefaultTransferProgressSnapshot
implements ToCopyableBuilder<DefaultTransferProgressSnapshot.Builder, DefaultTransferProgressSnapshot>,
TransferProgressSnapshot {
private final long transferredBytes;
private final Long totalBytes;
private final SdkResponse sdkResponse;
private DefaultTransferProgressSnapshot(Builder builder) {
if (builder.totalBytes != null) {
Validate.isNotNegative(builder.totalBytes, "totalBytes");
Validate.isTrue(builder.transferredBytes <= builder.totalBytes,
"transferredBytes (%s) must not be greater than totalBytes (%s)",
builder.transferredBytes, builder.totalBytes);
}
Validate.paramNotNull(builder.transferredBytes, "byteTransferred");
this.transferredBytes = Validate.isNotNegative(builder.transferredBytes, "transferredBytes");
this.totalBytes = builder.totalBytes;
this.sdkResponse = builder.sdkResponse;
}
public static Builder builder() {
return new Builder();
}
@Override
public Builder toBuilder() {
return new Builder(this);
}
@Override
public long transferredBytes() {
return transferredBytes;
}
@Override
public OptionalLong totalBytes() {
return totalBytes == null ? OptionalLong.empty() : OptionalLong.of(totalBytes);
}
@Override
public Optional<SdkResponse> sdkResponse() {
return Optional.ofNullable(sdkResponse);
}
@Override
public OptionalDouble ratioTransferred() {
if (totalBytes == null) {
return OptionalDouble.empty();
}
return totalBytes == 0 ? OptionalDouble.of(1.0) : OptionalDouble.of(transferredBytes / totalBytes.doubleValue());
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DefaultTransferProgressSnapshot that = (DefaultTransferProgressSnapshot) o;
if (transferredBytes != that.transferredBytes) {
return false;
}
if (!Objects.equals(totalBytes, that.totalBytes)) {
return false;
}
return Objects.equals(sdkResponse, that.sdkResponse);
}
@Override
public int hashCode() {
int result = (int) (transferredBytes ^ (transferredBytes >>> 32));
result = 31 * result + (totalBytes != null ? totalBytes.hashCode() : 0);
result = 31 * result + (sdkResponse != null ? sdkResponse.hashCode() : 0);
return result;
}
@Override
public OptionalLong remainingBytes() {
if (totalBytes == null) {
return OptionalLong.empty();
}
return OptionalLong.of(totalBytes - transferredBytes);
}
@Override
public String toString() {
return ToString.builder("TransferProgressSnapshot")
.add("transferredBytes", transferredBytes)
.add("totalBytes", totalBytes)
.add("sdkResponse", sdkResponse)
.build();
}
public static final class Builder implements CopyableBuilder<Builder, DefaultTransferProgressSnapshot> {
private Long transferredBytes;
private Long totalBytes;
private SdkResponse sdkResponse;
private Builder() {
}
private Builder(DefaultTransferProgressSnapshot snapshot) {
this.transferredBytes = snapshot.transferredBytes;
this.totalBytes = snapshot.totalBytes;
this.sdkResponse = snapshot.sdkResponse;
}
public Builder transferredBytes(Long transferredBytes) {
this.transferredBytes = transferredBytes;
return this;
}
public long getTransferredBytes() {
return transferredBytes;
}
public Builder totalBytes(Long totalBytes) {
this.totalBytes = totalBytes;
return this;
}
public Long getTotalBytes() {
return totalBytes;
}
public Builder sdkResponse(SdkResponse sdkResponse) {
this.sdkResponse = sdkResponse;
return this;
}
@Override
public DefaultTransferProgressSnapshot build() {
return new DefaultTransferProgressSnapshot(this);
}
}
}
| 3,775 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/internal | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/internal/progress/TransferProgressUpdater.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.progress;
import java.nio.ByteBuffer;
import java.util.Collections;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicBoolean;
import org.reactivestreams.Subscriber;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.core.async.AsyncResponseTransformer;
import software.amazon.awssdk.core.async.listener.AsyncRequestBodyListener;
import software.amazon.awssdk.core.async.listener.AsyncResponseTransformerListener;
import software.amazon.awssdk.core.async.listener.PublisherListener;
import software.amazon.awssdk.crt.s3.S3MetaRequestProgress;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.transfer.s3.model.CompletedObjectTransfer;
import software.amazon.awssdk.transfer.s3.model.TransferObjectRequest;
import software.amazon.awssdk.transfer.s3.progress.TransferListener;
import software.amazon.awssdk.transfer.s3.progress.TransferProgress;
import software.amazon.awssdk.transfer.s3.progress.TransferProgressSnapshot;
/**
* An SDK-internal helper class that facilitates updating a {@link TransferProgress} and invoking {@link TransferListener}s.
*/
@SdkInternalApi
public class TransferProgressUpdater {
private final DefaultTransferProgress progress;
private final TransferListenerContext context;
private final TransferListenerInvoker listenerInvoker;
private final CompletableFuture<Void> endOfStreamFuture;
public TransferProgressUpdater(TransferObjectRequest request,
Long contentLength) {
DefaultTransferProgressSnapshot.Builder snapshotBuilder = DefaultTransferProgressSnapshot.builder();
snapshotBuilder.transferredBytes(0L);
Optional.ofNullable(contentLength).ifPresent(snapshotBuilder::totalBytes);
TransferProgressSnapshot snapshot = snapshotBuilder.build();
progress = new DefaultTransferProgress(snapshot);
context = TransferListenerContext.builder()
.request(request)
.progressSnapshot(snapshot)
.build();
listenerInvoker = request.transferListeners() == null
? new TransferListenerInvoker(Collections.emptyList())
: new TransferListenerInvoker(request.transferListeners());
endOfStreamFuture = new CompletableFuture<>();
}
public TransferProgress progress() {
return progress;
}
public void transferInitiated() {
listenerInvoker.transferInitiated(context);
}
public AsyncRequestBody wrapRequestBody(AsyncRequestBody requestBody) {
return AsyncRequestBodyListener.wrap(
requestBody,
new AsyncRequestBodyListener() {
final AtomicBoolean done = new AtomicBoolean(false);
@Override
public void publisherSubscribe(Subscriber<? super ByteBuffer> subscriber) {
resetBytesTransferred();
}
@Override
public void subscriberOnNext(ByteBuffer byteBuffer) {
incrementBytesTransferred(byteBuffer.limit());
progress.snapshot().ratioTransferred().ifPresent(ratioTransferred -> {
if (Double.compare(ratioTransferred, 1.0) == 0) {
endOfStreamFutureCompleted();
}
});
}
@Override
public void subscriberOnError(Throwable t) {
transferFailed(t);
}
@Override
public void subscriberOnComplete() {
endOfStreamFutureCompleted();
}
private void endOfStreamFutureCompleted() {
if (done.compareAndSet(false, true)) {
endOfStreamFuture.complete(null);
}
}
});
}
public PublisherListener<S3MetaRequestProgress> crtProgressListener() {
return new PublisherListener<S3MetaRequestProgress>() {
@Override
public void publisherSubscribe(Subscriber<? super S3MetaRequestProgress> subscriber) {
resetBytesTransferred();
}
@Override
public void subscriberOnNext(S3MetaRequestProgress s3MetaRequestProgress) {
incrementBytesTransferred(s3MetaRequestProgress.getBytesTransferred());
}
@Override
public void subscriberOnError(Throwable t) {
transferFailed(t);
}
@Override
public void subscriberOnComplete() {
endOfStreamFuture.complete(null);
}
};
}
public <ResultT> AsyncResponseTransformer<GetObjectResponse, ResultT> wrapResponseTransformer(
AsyncResponseTransformer<GetObjectResponse, ResultT> responseTransformer) {
return AsyncResponseTransformerListener.wrap(
responseTransformer,
new AsyncResponseTransformerListener<GetObjectResponse>() {
@Override
public void transformerOnResponse(GetObjectResponse response) {
if (response.contentLength() != null) {
progress.updateAndGet(b -> b.totalBytes(response.contentLength()).sdkResponse(response));
}
}
@Override
public void transformerExceptionOccurred(Throwable t) {
transferFailed(t);
}
@Override
public void publisherSubscribe(Subscriber<? super ByteBuffer> subscriber) {
resetBytesTransferred();
}
@Override
public void subscriberOnNext(ByteBuffer byteBuffer) {
incrementBytesTransferred(byteBuffer.limit());
}
@Override
public void subscriberOnError(Throwable t) {
transferFailed(t);
}
@Override
public void subscriberOnComplete() {
endOfStreamFuture.complete(null);
}
});
}
private void resetBytesTransferred() {
progress.updateAndGet(b -> b.transferredBytes(0L));
}
private void incrementBytesTransferred(long numBytes) {
TransferProgressSnapshot snapshot = progress.updateAndGet(b -> {
b.transferredBytes(b.getTransferredBytes() + numBytes);
});
listenerInvoker.bytesTransferred(context.copy(b -> b.progressSnapshot(snapshot)));
}
public void registerCompletion(CompletableFuture<? extends CompletedObjectTransfer> future) {
future.whenComplete((r, t) -> {
if (t == null) {
endOfStreamFuture.whenComplete((r2, t2) -> {
if (t2 == null) {
transferComplete(r);
} else {
transferFailed(t2);
}
});
} else {
transferFailed(t);
}
});
}
private void transferComplete(CompletedObjectTransfer r) {
listenerInvoker.transferComplete(context.copy(b -> {
TransferProgressSnapshot snapshot = progress.snapshot();
if (!snapshot.sdkResponse().isPresent()) {
snapshot = progress.updateAndGet(p -> p.sdkResponse(r.response()));
}
b.progressSnapshot(snapshot);
b.completedTransfer(r);
}));
}
private void transferFailed(Throwable t) {
listenerInvoker.transferFailed(TransferListenerFailedContext.builder()
.transferContext(
context.copy(
b -> b.progressSnapshot(progress.snapshot())))
.exception(t)
.build());
}
}
| 3,776 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/internal | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/internal/progress/TransferListenerContext.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.progress;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.transfer.s3.model.CompletedObjectTransfer;
import software.amazon.awssdk.transfer.s3.model.TransferObjectRequest;
import software.amazon.awssdk.transfer.s3.progress.TransferListener;
import software.amazon.awssdk.transfer.s3.progress.TransferProgressSnapshot;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* An SDK-internal implementation of {@link TransferListener.Context.TransferComplete} and its parent interfaces.
*
* @see TransferListenerFailedContext
*/
@SdkProtectedApi
@Immutable
public final class TransferListenerContext
implements TransferListener.Context.TransferComplete,
ToCopyableBuilder<TransferListenerContext.Builder, TransferListenerContext> {
private final TransferObjectRequest request;
private final TransferProgressSnapshot progressSnapshot;
private final CompletedObjectTransfer completedTransfer;
private TransferListenerContext(Builder builder) {
this.request = builder.request;
this.progressSnapshot = builder.progressSnapshot;
this.completedTransfer = builder.completedTransfer;
}
public static Builder builder() {
return new Builder();
}
@Override
public Builder toBuilder() {
return new Builder(this);
}
@Override
public TransferObjectRequest request() {
return request;
}
@Override
public TransferProgressSnapshot progressSnapshot() {
return progressSnapshot;
}
@Override
public CompletedObjectTransfer completedTransfer() {
return completedTransfer;
}
@Override
public String toString() {
return ToString.builder("TransferListenerContext")
.add("request", request)
.add("progressSnapshot", progressSnapshot)
.add("completedTransfer", completedTransfer)
.build();
}
public static final class Builder implements CopyableBuilder<Builder, TransferListenerContext> {
private TransferObjectRequest request;
private TransferProgressSnapshot progressSnapshot;
private CompletedObjectTransfer completedTransfer;
private Builder() {
}
private Builder(TransferListenerContext context) {
this.request = context.request;
this.progressSnapshot = context.progressSnapshot;
this.completedTransfer = context.completedTransfer;
}
public Builder request(TransferObjectRequest request) {
this.request = request;
return this;
}
public Builder progressSnapshot(TransferProgressSnapshot progressSnapshot) {
this.progressSnapshot = progressSnapshot;
return this;
}
public Builder completedTransfer(CompletedObjectTransfer completedTransfer) {
this.completedTransfer = completedTransfer;
return this;
}
@Override
public TransferListenerContext build() {
return new TransferListenerContext(this);
}
}
}
| 3,777 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/internal | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/internal/progress/ResumeTransferProgress.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.progress;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.transfer.s3.progress.TransferProgress;
import software.amazon.awssdk.transfer.s3.progress.TransferProgressSnapshot;
import software.amazon.awssdk.utils.Validate;
/**
* An implementation of {@link TransferProgress} used when resuming a transfer. This uses a bytes-transferred of 0 until the real
* progress is available (when the transfer starts).
*/
@SdkInternalApi
public class ResumeTransferProgress implements TransferProgress {
private CompletableFuture<TransferProgress> progressFuture;
public ResumeTransferProgress(CompletableFuture<TransferProgress> progressFuture) {
this.progressFuture = Validate.paramNotNull(progressFuture, "progressFuture");
}
@Override
public TransferProgressSnapshot snapshot() {
if (progressFuture.isDone() && !progressFuture.isCompletedExceptionally()) {
return progressFuture.join().snapshot();
}
return DefaultTransferProgressSnapshot.builder().transferredBytes(0L).build();
}
}
| 3,778 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/internal | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/internal/serialization/ResumableFileUploadSerializer.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.serialization;
import static software.amazon.awssdk.transfer.s3.internal.serialization.TransferManagerMarshallingUtils.getMarshaller;
import static software.amazon.awssdk.transfer.s3.internal.serialization.TransferManagerMarshallingUtils.getUnmarshaller;
import static software.amazon.awssdk.transfer.s3.internal.serialization.TransferManagerMarshallingUtils.putObjectSdkField;
import java.io.InputStream;
import java.nio.file.Paths;
import java.time.Instant;
import java.util.Map;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.SdkField;
import software.amazon.awssdk.core.protocol.MarshallingType;
import software.amazon.awssdk.protocols.jsoncore.JsonNode;
import software.amazon.awssdk.protocols.jsoncore.JsonNodeParser;
import software.amazon.awssdk.protocols.jsoncore.JsonWriter;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.transfer.s3.model.ResumableFileUpload;
import software.amazon.awssdk.transfer.s3.model.UploadFileRequest;
import software.amazon.awssdk.utils.Logger;
import software.amazon.awssdk.utils.Validate;
@SdkInternalApi
public final class ResumableFileUploadSerializer {
private static final Logger log = Logger.loggerFor(S3TransferManager.class);
private static final String MULTIPART_UPLOAD_ID = "multipartUploadId";
private static final String FILE_LENGTH = "fileLength";
private static final String FILE_LAST_MODIFIED = "fileLastModified";
private static final String PART_SIZE_IN_BYTES = "partSizeInBytes";
private static final String TOTAL_PARTS = "totalParts";
private static final String TRANSFERRED_PARTS = "transferredParts";
private static final String UPLOAD_FILE_REQUEST = "uploadFileRequest";
private static final String SOURCE = "source";
private static final String PUT_OBJECT_REQUEST = "putObjectRequest";
private ResumableFileUploadSerializer() {
}
/**
* Serializes an instance of {@link ResumableFileUpload} into valid JSON. This object contains a nested PutObjectRequest and
* therefore makes use of the standard JSON marshalling classes.
*/
public static byte[] toJson(ResumableFileUpload upload) {
JsonWriter jsonGenerator = JsonWriter.create();
jsonGenerator.writeStartObject();
TransferManagerJsonMarshaller.LONG.marshall(upload.fileLength(), jsonGenerator, FILE_LENGTH);
TransferManagerJsonMarshaller.INSTANT.marshall(upload.fileLastModified(), jsonGenerator, FILE_LAST_MODIFIED);
if (upload.multipartUploadId().isPresent()) {
TransferManagerJsonMarshaller.STRING.marshall(upload.multipartUploadId().get(), jsonGenerator,
MULTIPART_UPLOAD_ID);
}
if (upload.partSizeInBytes().isPresent()) {
TransferManagerJsonMarshaller.LONG.marshall(upload.partSizeInBytes().getAsLong(),
jsonGenerator,
PART_SIZE_IN_BYTES);
}
if (upload.totalParts().isPresent()) {
TransferManagerJsonMarshaller.LONG.marshall(upload.totalParts().getAsLong(),
jsonGenerator,
TOTAL_PARTS);
}
if (upload.transferredParts().isPresent()) {
TransferManagerJsonMarshaller.LONG.marshall(upload.transferredParts().getAsLong(),
jsonGenerator,
TRANSFERRED_PARTS);
}
marshallUploadFileRequest(upload.uploadFileRequest(), jsonGenerator);
jsonGenerator.writeEndObject();
return jsonGenerator.getBytes();
}
/**
* At this point we do not need to persist the TransferRequestOverrideConfiguration, because it only contains listeners and
* they are not used in the resume operation.
*/
private static void marshallUploadFileRequest(UploadFileRequest fileRequest, JsonWriter jsonGenerator) {
jsonGenerator.writeFieldName(UPLOAD_FILE_REQUEST);
jsonGenerator.writeStartObject();
jsonGenerator.writeFieldName(SOURCE);
jsonGenerator.writeValue(fileRequest.source().toString());
marshallPutObjectRequest(fileRequest.putObjectRequest(), jsonGenerator);
jsonGenerator.writeEndObject();
}
private static void marshallPutObjectRequest(PutObjectRequest putObjectRequest, JsonWriter jsonGenerator) {
jsonGenerator.writeFieldName(PUT_OBJECT_REQUEST);
jsonGenerator.writeStartObject();
validateNoRequestOverrideConfiguration(putObjectRequest);
putObjectRequest.sdkFields().forEach(field -> marshallPojoField(field, putObjectRequest, jsonGenerator));
jsonGenerator.writeEndObject();
}
private static void validateNoRequestOverrideConfiguration(PutObjectRequest putObjectRequest) {
if (putObjectRequest.overrideConfiguration().isPresent()) {
log.debug(() -> "ResumableFileUpload PutObjectRequest contains an override configuration that will not be "
+ "serialized");
}
}
private static void marshallPojoField(SdkField<?> field, PutObjectRequest request, JsonWriter jsonGenerator) {
Object val = field.getValueOrDefault(request);
TransferManagerJsonMarshaller<Object> marshaller = getMarshaller(field.marshallingType(), val);
marshaller.marshall(val, jsonGenerator, field.locationName());
}
public static ResumableFileUpload fromJson(String bytes) {
JsonNodeParser jsonNodeParser = JsonNodeParser.builder().build();
Map<String, JsonNode> uploadNodes = jsonNodeParser.parse(bytes).asObject();
return fromNodes(uploadNodes);
}
public static ResumableFileUpload fromJson(byte[] string) {
JsonNodeParser jsonNodeParser = JsonNodeParser.builder().build();
Map<String, JsonNode> uploadNodes = jsonNodeParser.parse(string).asObject();
return fromNodes(uploadNodes);
}
public static ResumableFileUpload fromJson(InputStream inputStream) {
JsonNodeParser jsonNodeParser = JsonNodeParser.builder().build();
Map<String, JsonNode> uploadNodes = jsonNodeParser.parse(inputStream).asObject();
return fromNodes(uploadNodes);
}
@SuppressWarnings("unchecked")
private static ResumableFileUpload fromNodes(Map<String, JsonNode> uploadNodes) {
TransferManagerJsonUnmarshaller<Long> longUnmarshaller =
(TransferManagerJsonUnmarshaller<Long>) getUnmarshaller(MarshallingType.LONG);
TransferManagerJsonUnmarshaller<Instant> instantUnmarshaller =
(TransferManagerJsonUnmarshaller<Instant>) getUnmarshaller(MarshallingType.INSTANT);
TransferManagerJsonUnmarshaller<String> stringUnmarshaller =
(TransferManagerJsonUnmarshaller<String>) getUnmarshaller(MarshallingType.STRING);
ResumableFileUpload.Builder builder = ResumableFileUpload.builder();
JsonNode fileLength = Validate.paramNotNull(uploadNodes.get(FILE_LENGTH), FILE_LENGTH);
builder.fileLength(longUnmarshaller.unmarshall(fileLength));
JsonNode fileLastModified = Validate.paramNotNull(uploadNodes.get(FILE_LAST_MODIFIED), FILE_LAST_MODIFIED);
builder.fileLastModified(instantUnmarshaller.unmarshall(fileLastModified));
if (uploadNodes.get(MULTIPART_UPLOAD_ID) != null) {
builder.multipartUploadId(stringUnmarshaller.unmarshall(uploadNodes.get(MULTIPART_UPLOAD_ID)));
}
if (uploadNodes.get(PART_SIZE_IN_BYTES) != null) {
builder.partSizeInBytes(longUnmarshaller.unmarshall(uploadNodes.get(PART_SIZE_IN_BYTES)));
}
if (uploadNodes.get(TOTAL_PARTS) != null) {
builder.totalParts(longUnmarshaller.unmarshall(uploadNodes.get(TOTAL_PARTS)));
}
if (uploadNodes.get(TRANSFERRED_PARTS) != null) {
builder.transferredParts(longUnmarshaller.unmarshall(uploadNodes.get(TRANSFERRED_PARTS)));
}
JsonNode jsonNode = Validate.paramNotNull(uploadNodes.get(UPLOAD_FILE_REQUEST), UPLOAD_FILE_REQUEST);
builder.uploadFileRequest(parseUploadFileRequest(jsonNode));
return builder.build();
}
private static UploadFileRequest parseUploadFileRequest(JsonNode fileRequest) {
UploadFileRequest.Builder fileRequestBuilder = UploadFileRequest.builder();
Map<String, JsonNode> fileRequestNodes = fileRequest.asObject();
fileRequestBuilder.source(Paths.get(fileRequestNodes.get(SOURCE).asString()));
PutObjectRequest.Builder putObjectBuilder = PutObjectRequest.builder();
Map<String, JsonNode> putObjectRequestNodes = fileRequestNodes.get(PUT_OBJECT_REQUEST).asObject();
putObjectRequestNodes.forEach((key, value) -> setPutObjectParameters(putObjectBuilder, key, value));
fileRequestBuilder.putObjectRequest(putObjectBuilder.build());
return fileRequestBuilder.build();
}
private static void setPutObjectParameters(PutObjectRequest.Builder putObjectBuilder, String key, JsonNode value) {
SdkField<?> f = putObjectSdkField(key);
MarshallingType<?> marshallingType = f.marshallingType();
TransferManagerJsonUnmarshaller<?> unmarshaller = getUnmarshaller(marshallingType);
f.set(putObjectBuilder, unmarshaller.unmarshall(value, f));
}
}
| 3,779 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/internal | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/internal/serialization/TransferManagerJsonMarshaller.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.serialization;
import static software.amazon.awssdk.transfer.s3.internal.serialization.TransferManagerMarshallingUtils.getMarshaller;
import java.math.BigDecimal;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.core.util.SdkAutoConstructList;
import software.amazon.awssdk.core.util.SdkAutoConstructMap;
import software.amazon.awssdk.protocols.core.Marshaller;
import software.amazon.awssdk.protocols.jsoncore.JsonWriter;
/**
* Interface to marshall data according to the JSON protocol specification.
*
* @param <T> Type to marshall.
*/
@FunctionalInterface
@SdkInternalApi
public interface TransferManagerJsonMarshaller<T> extends Marshaller<T> {
TransferManagerJsonMarshaller<String> STRING = (val, jsonGenerator) -> jsonGenerator.writeValue(val);
TransferManagerJsonMarshaller<Short> SHORT = (val, jsonGenerator) -> jsonGenerator.writeValue(val);
TransferManagerJsonMarshaller<Integer> INTEGER = (val, jsonGenerator) -> jsonGenerator.writeValue(val);
TransferManagerJsonMarshaller<Long> LONG = (val, jsonGenerator) -> jsonGenerator.writeValue(val);
TransferManagerJsonMarshaller<Float> FLOAT = (val, jsonGenerator) -> jsonGenerator.writeValue(val);
TransferManagerJsonMarshaller<Double> DOUBLE = (val, jsonGenerator) -> jsonGenerator.writeValue(val);
TransferManagerJsonMarshaller<BigDecimal> BIG_DECIMAL = (val, jsonGenerator) -> jsonGenerator.writeValue(val);
TransferManagerJsonMarshaller<Boolean> BOOLEAN = (val, jsonGenerator) -> jsonGenerator.writeValue(val);
TransferManagerJsonMarshaller<Instant> INSTANT = (val, jsonGenerator) -> jsonGenerator.writeValue(val);
TransferManagerJsonMarshaller<SdkBytes> SDK_BYTES = (val, jsonGenerator) -> jsonGenerator.writeValue(val.asByteBuffer());
TransferManagerJsonMarshaller<Void> NULL = new TransferManagerJsonMarshaller<Void>() {
@Override
public void marshall(Void val, JsonWriter generator, String paramName) {
if (paramName == null) {
generator.writeNull();
}
}
@Override
public void marshall(Void val, JsonWriter jsonGenerator) {
}
};
TransferManagerJsonMarshaller<List<?>> LIST = new TransferManagerJsonMarshaller<List<?>>() {
@Override
public void marshall(List<?> list, JsonWriter jsonGenerator) {
jsonGenerator.writeStartArray();
list.forEach(val -> getMarshaller(val).marshall(val, jsonGenerator, null));
jsonGenerator.writeEndArray();
}
@Override
public boolean shouldEmit(List<?> list) {
return !list.isEmpty() || !(list instanceof SdkAutoConstructList);
}
};
TransferManagerJsonMarshaller<Map<String, ?>> MAP = new TransferManagerJsonMarshaller<Map<String, ?>>() {
@Override
public void marshall(Map<String, ?> map, JsonWriter jsonGenerator) {
jsonGenerator.writeStartObject();
map.forEach((key, value) -> {
if (value != null) {
jsonGenerator.writeFieldName(key);
getMarshaller(value).marshall(value, jsonGenerator, null);
}
});
jsonGenerator.writeEndObject();
}
@Override
public boolean shouldEmit(Map<String, ?> map) {
return !map.isEmpty() || !(map instanceof SdkAutoConstructMap);
}
};
default void marshall(T val, JsonWriter generator, String paramName) {
if (!shouldEmit(val)) {
return;
}
if (paramName != null) {
generator.writeFieldName(paramName);
}
marshall(val, generator);
}
void marshall(T val, JsonWriter jsonGenerator);
default boolean shouldEmit(T val) {
return true;
}
}
| 3,780 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/internal | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/internal/serialization/ResumableFileDownloadSerializer.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.serialization;
import static software.amazon.awssdk.transfer.s3.internal.serialization.TransferManagerMarshallingUtils.getMarshaller;
import static software.amazon.awssdk.transfer.s3.internal.serialization.TransferManagerMarshallingUtils.getObjectSdkField;
import static software.amazon.awssdk.transfer.s3.internal.serialization.TransferManagerMarshallingUtils.getUnmarshaller;
import java.io.InputStream;
import java.nio.file.Paths;
import java.time.Instant;
import java.util.Map;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.SdkField;
import software.amazon.awssdk.core.protocol.MarshallingType;
import software.amazon.awssdk.protocols.jsoncore.JsonNode;
import software.amazon.awssdk.protocols.jsoncore.JsonNodeParser;
import software.amazon.awssdk.protocols.jsoncore.JsonWriter;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.transfer.s3.model.DownloadFileRequest;
import software.amazon.awssdk.transfer.s3.model.ResumableFileDownload;
import software.amazon.awssdk.utils.Logger;
@SdkInternalApi
public final class ResumableFileDownloadSerializer {
private static final Logger log = Logger.loggerFor(S3TransferManager.class);
private ResumableFileDownloadSerializer() {
}
/**
* Serializes an instance of {@link ResumableFileDownload} into valid JSON. This object contains a nested GetObjectRequest and
* therefore makes use of the standard JSON marshalling classes.
*/
public static byte[] toJson(ResumableFileDownload download) {
JsonWriter jsonGenerator = JsonWriter.create();
jsonGenerator.writeStartObject();
TransferManagerJsonMarshaller.LONG.marshall(download.bytesTransferred(), jsonGenerator, "bytesTransferred");
TransferManagerJsonMarshaller.INSTANT.marshall(download.fileLastModified(), jsonGenerator, "fileLastModified");
if (download.totalSizeInBytes().isPresent()) {
TransferManagerJsonMarshaller.LONG.marshall(download.totalSizeInBytes().getAsLong(), jsonGenerator,
"totalSizeInBytes");
}
if (download.s3ObjectLastModified().isPresent()) {
TransferManagerJsonMarshaller.INSTANT.marshall(download.s3ObjectLastModified().get(),
jsonGenerator,
"s3ObjectLastModified");
}
marshallDownloadFileRequest(download.downloadFileRequest(), jsonGenerator);
jsonGenerator.writeEndObject();
return jsonGenerator.getBytes();
}
/**
* At this point we do not need to persist the TransferRequestOverrideConfiguration, because it only contains listeners and
* they are not used in the resume operation.
*/
private static void marshallDownloadFileRequest(DownloadFileRequest fileRequest, JsonWriter jsonGenerator) {
jsonGenerator.writeFieldName("downloadFileRequest");
jsonGenerator.writeStartObject();
jsonGenerator.writeFieldName("destination");
jsonGenerator.writeValue(fileRequest.destination().toString());
marshallGetObjectRequest(fileRequest.getObjectRequest(), jsonGenerator);
jsonGenerator.writeEndObject();
}
private static void marshallGetObjectRequest(GetObjectRequest getObjectRequest, JsonWriter jsonGenerator) {
jsonGenerator.writeFieldName("getObjectRequest");
jsonGenerator.writeStartObject();
validateNoRequestOverrideConfiguration(getObjectRequest);
getObjectRequest.sdkFields().forEach(field -> marshallPojoField(field, getObjectRequest, jsonGenerator));
jsonGenerator.writeEndObject();
}
private static void validateNoRequestOverrideConfiguration(GetObjectRequest getObjectRequest) {
if (getObjectRequest.overrideConfiguration().isPresent()) {
log.debug(() -> "ResumableFileDownload GetObjectRequest contains an override configuration that will not be "
+ "serialized");
}
}
private static void marshallPojoField(SdkField<?> field, GetObjectRequest request, JsonWriter jsonGenerator) {
Object val = field.getValueOrDefault(request);
TransferManagerJsonMarshaller<Object> marshaller = getMarshaller(field.marshallingType(), val);
marshaller.marshall(val, jsonGenerator, field.locationName());
}
public static ResumableFileDownload fromJson(String bytes) {
JsonNodeParser jsonNodeParser = JsonNodeParser.builder().build();
Map<String, JsonNode> downloadNodes = jsonNodeParser.parse(bytes).asObject();
return fromNodes(downloadNodes);
}
public static ResumableFileDownload fromJson(byte[] bytes) {
JsonNodeParser jsonNodeParser = JsonNodeParser.builder().build();
Map<String, JsonNode> downloadNodes = jsonNodeParser.parse(bytes).asObject();
return fromNodes(downloadNodes);
}
public static ResumableFileDownload fromJson(InputStream bytes) {
JsonNodeParser jsonNodeParser = JsonNodeParser.builder().build();
Map<String, JsonNode> downloadNodes = jsonNodeParser.parse(bytes).asObject();
return fromNodes(downloadNodes);
}
@SuppressWarnings("unchecked")
private static ResumableFileDownload fromNodes(Map<String, JsonNode> downloadNodes) {
TransferManagerJsonUnmarshaller<Long> longUnmarshaller =
(TransferManagerJsonUnmarshaller<Long>) getUnmarshaller(MarshallingType.LONG);
TransferManagerJsonUnmarshaller<Instant> instantUnmarshaller =
(TransferManagerJsonUnmarshaller<Instant>) getUnmarshaller(MarshallingType.INSTANT);
ResumableFileDownload.Builder builder = ResumableFileDownload.builder();
builder.bytesTransferred(longUnmarshaller.unmarshall(downloadNodes.get("bytesTransferred")));
builder.fileLastModified(instantUnmarshaller.unmarshall(downloadNodes.get("fileLastModified")));
if (downloadNodes.get("totalSizeInBytes") != null) {
builder.totalSizeInBytes(longUnmarshaller.unmarshall(downloadNodes.get("totalSizeInBytes")));
}
if (downloadNodes.get("s3ObjectLastModified") != null) {
builder.s3ObjectLastModified(instantUnmarshaller.unmarshall(downloadNodes.get("s3ObjectLastModified")));
}
builder.downloadFileRequest(parseDownloadFileRequest(downloadNodes.get("downloadFileRequest")));
return builder.build();
}
private static DownloadFileRequest parseDownloadFileRequest(JsonNode fileRequest) {
DownloadFileRequest.Builder fileRequestBuilder = DownloadFileRequest.builder();
Map<String, JsonNode> fileRequestNodes = fileRequest.asObject();
fileRequestBuilder.destination(Paths.get(fileRequestNodes.get("destination").asString()));
GetObjectRequest.Builder getObjectBuilder = GetObjectRequest.builder();
Map<String, JsonNode> getObjectRequestNodes = fileRequestNodes.get("getObjectRequest").asObject();
getObjectRequestNodes.forEach((key, value) -> setGetObjectParameters(getObjectBuilder, key, value));
fileRequestBuilder.getObjectRequest(getObjectBuilder.build());
return fileRequestBuilder.build();
}
private static void setGetObjectParameters(GetObjectRequest.Builder getObjectBuilder, String key, JsonNode value) {
SdkField<?> f = getObjectSdkField(key);
MarshallingType<?> marshallingType = f.marshallingType();
TransferManagerJsonUnmarshaller<?> unmarshaller = getUnmarshaller(marshallingType);
f.set(getObjectBuilder, unmarshaller.unmarshall(value));
}
}
| 3,781 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/internal | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/internal/serialization/TransferManagerJsonUnmarshaller.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.serialization;
import static software.amazon.awssdk.transfer.s3.internal.serialization.TransferManagerMarshallingUtils.getUnmarshaller;
import java.math.BigDecimal;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.core.SdkField;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.traits.MapTrait;
import software.amazon.awssdk.protocols.jsoncore.JsonNode;
import software.amazon.awssdk.utils.BinaryUtils;
import software.amazon.awssdk.utils.DateUtils;
/**
* Interface for unmarshalling a field from JSON.
*
* @param <T> Type to unmarshall into.
*/
@FunctionalInterface
@SdkInternalApi
public interface TransferManagerJsonUnmarshaller<T> {
TransferManagerJsonUnmarshaller<String> STRING = (val, sdkField) -> val;
TransferManagerJsonUnmarshaller<Short> SHORT = (val, sdkField) -> Short.parseShort(val);
TransferManagerJsonUnmarshaller<Integer> INTEGER = (val, sdkField) -> Integer.parseInt(val);
TransferManagerJsonUnmarshaller<Long> LONG = (val, sdkField) -> Long.parseLong(val);
TransferManagerJsonUnmarshaller<Void> NULL = (val, sdkField) -> null;
TransferManagerJsonUnmarshaller<Float> FLOAT = (val, sdkField) -> Float.parseFloat(val);
TransferManagerJsonUnmarshaller<Double> DOUBLE = (val, sdkField) -> Double.parseDouble(val);
TransferManagerJsonUnmarshaller<BigDecimal> BIG_DECIMAL = (val, sdkField) -> new BigDecimal(val);
TransferManagerJsonUnmarshaller<Boolean> BOOLEAN = (val, sdkField) -> Boolean.parseBoolean(val);
TransferManagerJsonUnmarshaller<SdkBytes> SDK_BYTES =
(content, sdkField) -> SdkBytes.fromByteArray(BinaryUtils.fromBase64(content));
TransferManagerJsonUnmarshaller<Instant> INSTANT = new TransferManagerJsonUnmarshaller<Instant>() {
@Override
public Instant unmarshall(String value, SdkField<?> field) {
if (value == null) {
return null;
}
return safeParseDate(DateUtils::parseUnixTimestampInstant).apply(value);
}
private Function<String, Instant> safeParseDate(Function<String, Instant> dateUnmarshaller) {
return value -> {
try {
return dateUnmarshaller.apply(value);
} catch (NumberFormatException e) {
throw SdkClientException.builder()
.message("Unable to parse date : " + value)
.cause(e)
.build();
}
};
}
};
TransferManagerJsonUnmarshaller<Map<String, Object>> MAP = new TransferManagerJsonUnmarshaller<Map<String, Object>>() {
@Override
public Map<String, Object> unmarshall(JsonNode jsonContent, SdkField<?> field) {
if (jsonContent == null) {
return null;
}
SdkField<Object> valueInfo = field.getTrait(MapTrait.class).valueFieldInfo();
Map<String, Object> map = new HashMap<>();
jsonContent.asObject().forEach((fieldName, value) -> {
TransferManagerJsonUnmarshaller<?> unmarshaller = getUnmarshaller(valueInfo.marshallingType());
map.put(fieldName, unmarshaller.unmarshall(value));
});
return map;
}
@Override
public Map<String, Object> unmarshall(String content, SdkField<?> field) {
return unmarshall(JsonNode.parser().parse(content), field);
}
};
default T unmarshall(JsonNode jsonContent, SdkField<?> field) {
return jsonContent != null && !jsonContent.isNull() ? unmarshall(jsonContent.text(), field) : null;
}
default T unmarshall(JsonNode jsonContent) {
return unmarshall(jsonContent, null);
}
T unmarshall(String content, SdkField<?> field);
}
| 3,782 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/internal | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/internal/serialization/TransferManagerMarshallingUtils.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.serialization;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.SdkField;
import software.amazon.awssdk.core.protocol.MarshallingType;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
/**
* Marshallers and unmarshallers for serializing objects in TM, using the SDK request {@link MarshallingType}.
* <p>
* Excluded marshalling types that should not appear inside a POJO like GetObjectRequest:
* <ul>
* <li>MarshallingType.SDK_POJO</li>
* <li>MarshallingType.DOCUMENT</li>
* <li>MarshallingType.MAP</li>
* <li>MarshallingType.LIST</li>
* </ul>
* <p>
* Note: unmarshalling generic List structures is not supported at this time
*/
@SdkInternalApi
public final class TransferManagerMarshallingUtils {
private static final Map<MarshallingType<?>, TransferManagerJsonMarshaller<?>> MARSHALLERS;
private static final Map<MarshallingType<?>, TransferManagerJsonUnmarshaller<?>> UNMARSHALLERS;
private static final Map<String, SdkField<?>> GET_OBJECT_SDK_FIELDS;
private static final Map<String, SdkField<?>> PUT_OBJECT_SDK_FIELDS;
static {
Map<MarshallingType<?>, TransferManagerJsonMarshaller<?>> marshallers = new HashMap<>();
marshallers.put(MarshallingType.STRING, TransferManagerJsonMarshaller.STRING);
marshallers.put(MarshallingType.SHORT, TransferManagerJsonMarshaller.SHORT);
marshallers.put(MarshallingType.INTEGER, TransferManagerJsonMarshaller.INTEGER);
marshallers.put(MarshallingType.LONG, TransferManagerJsonMarshaller.LONG);
marshallers.put(MarshallingType.INSTANT, TransferManagerJsonMarshaller.INSTANT);
marshallers.put(MarshallingType.NULL, TransferManagerJsonMarshaller.NULL);
marshallers.put(MarshallingType.FLOAT, TransferManagerJsonMarshaller.FLOAT);
marshallers.put(MarshallingType.DOUBLE, TransferManagerJsonMarshaller.DOUBLE);
marshallers.put(MarshallingType.BIG_DECIMAL, TransferManagerJsonMarshaller.BIG_DECIMAL);
marshallers.put(MarshallingType.BOOLEAN, TransferManagerJsonMarshaller.BOOLEAN);
marshallers.put(MarshallingType.SDK_BYTES, TransferManagerJsonMarshaller.SDK_BYTES);
marshallers.put(MarshallingType.LIST, TransferManagerJsonMarshaller.LIST);
marshallers.put(MarshallingType.MAP, TransferManagerJsonMarshaller.MAP);
MARSHALLERS = Collections.unmodifiableMap(marshallers);
Map<MarshallingType<?>, TransferManagerJsonUnmarshaller<?>> unmarshallers = new HashMap<>();
unmarshallers.put(MarshallingType.STRING, TransferManagerJsonUnmarshaller.STRING);
unmarshallers.put(MarshallingType.SHORT, TransferManagerJsonUnmarshaller.SHORT);
unmarshallers.put(MarshallingType.INTEGER, TransferManagerJsonUnmarshaller.INTEGER);
unmarshallers.put(MarshallingType.LONG, TransferManagerJsonUnmarshaller.LONG);
unmarshallers.put(MarshallingType.INSTANT, TransferManagerJsonUnmarshaller.INSTANT);
unmarshallers.put(MarshallingType.NULL, TransferManagerJsonUnmarshaller.NULL);
unmarshallers.put(MarshallingType.FLOAT, TransferManagerJsonUnmarshaller.FLOAT);
unmarshallers.put(MarshallingType.DOUBLE, TransferManagerJsonUnmarshaller.DOUBLE);
unmarshallers.put(MarshallingType.BIG_DECIMAL, TransferManagerJsonUnmarshaller.BIG_DECIMAL);
unmarshallers.put(MarshallingType.BOOLEAN, TransferManagerJsonUnmarshaller.BOOLEAN);
unmarshallers.put(MarshallingType.SDK_BYTES, TransferManagerJsonUnmarshaller.SDK_BYTES);
unmarshallers.put(MarshallingType.MAP, TransferManagerJsonUnmarshaller.MAP);
UNMARSHALLERS = Collections.unmodifiableMap(unmarshallers);
GET_OBJECT_SDK_FIELDS = Collections.unmodifiableMap(
GetObjectRequest.builder().build()
.sdkFields().stream()
.collect(Collectors.toMap(SdkField::locationName, Function.identity())));
PUT_OBJECT_SDK_FIELDS = Collections.unmodifiableMap(
PutObjectRequest.builder().build()
.sdkFields().stream()
.collect(Collectors.toMap(SdkField::locationName, Function.identity())));
}
private TransferManagerMarshallingUtils() {
}
@SuppressWarnings("unchecked")
public static <T> TransferManagerJsonMarshaller<T> getMarshaller(T val) {
MarshallingType<T> tMarshallingType = toMarshallingType(val);
return getMarshaller(tMarshallingType, val);
}
@SuppressWarnings("unchecked")
private static <T> MarshallingType<T> toMarshallingType(T val) {
MarshallingType<?> marshallingType = MarshallingType.NULL;
if (val != null) {
marshallingType =
MARSHALLERS.keySet()
.stream()
.filter(type -> type.getTargetClass()
.isAssignableFrom(val.getClass()))
.findFirst()
.orElse(MarshallingType.NULL);
}
return (MarshallingType<T>) marshallingType;
}
@SuppressWarnings("unchecked")
public static <T> TransferManagerJsonMarshaller<T> getMarshaller(MarshallingType<?> marshallingType, T val) {
TransferManagerJsonMarshaller<?> marshaller = MARSHALLERS.get(val == null ? MarshallingType.NULL : marshallingType);
if (marshaller == null) {
throw new IllegalStateException(String.format("Cannot find a marshaller for marshalling type %s", marshallingType));
}
return (TransferManagerJsonMarshaller<T>) marshaller;
}
public static TransferManagerJsonUnmarshaller<?> getUnmarshaller(MarshallingType<?> marshallingType) {
TransferManagerJsonUnmarshaller<?> unmarshaller = UNMARSHALLERS.get(marshallingType);
if (unmarshaller == null) {
throw new IllegalStateException(String.format("Cannot find an unmarshaller for marshalling type %s",
marshallingType));
}
return unmarshaller;
}
public static SdkField<?> getObjectSdkField(String key) {
SdkField<?> sdkField = GET_OBJECT_SDK_FIELDS.get(key);
if (sdkField != null) {
return sdkField;
}
throw new IllegalStateException("Could not match a field in GetObjectRequest");
}
public static SdkField<?> putObjectSdkField(String key) {
SdkField<?> sdkField = PUT_OBJECT_SDK_FIELDS.get(key);
if (sdkField != null) {
return sdkField;
}
throw new IllegalStateException("Could not match a field in PutObjectRequest");
}
}
| 3,783 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/internal | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/internal/utils/FileUtils.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.utils;
import java.io.File;
import java.nio.file.Path;
import java.time.Instant;
import software.amazon.awssdk.annotations.SdkInternalApi;
@SdkInternalApi
public final class FileUtils {
private FileUtils() {
}
// On certain platforms, File.lastModified() does not contain milliseconds precision, so we need to check the
// file length as well https://bugs.java.com/bugdatabase/view_bug.do?bug_id=8177809
public static boolean fileNotModified(long recordedFileContentLength,
Instant recordedFileLastModified,
Path path) {
File file = path.toFile();
Instant fileLastModified = Instant.ofEpochMilli(file.lastModified());
return fileLastModified.equals(recordedFileLastModified)
&& recordedFileContentLength == file.length();
}
}
| 3,784 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/internal | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/internal/utils/ResumableRequestConverter.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.utils;
import static software.amazon.awssdk.transfer.s3.internal.utils.FileUtils.fileNotModified;
import java.time.Instant;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.FileTransformerConfiguration;
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.services.s3.model.HeadObjectResponse;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.transfer.s3.model.DownloadFileRequest;
import software.amazon.awssdk.transfer.s3.model.ResumableFileDownload;
import software.amazon.awssdk.utils.Logger;
import software.amazon.awssdk.utils.Pair;
@SdkInternalApi
public final class ResumableRequestConverter {
private static final Logger log = Logger.loggerFor(S3TransferManager.class);
private ResumableRequestConverter() {
}
/**
* Converts a {@link ResumableFileDownload} to {@link DownloadFileRequest} and {@link AsyncResponseTransformer} pair.
*/
public static Pair<DownloadFileRequest, AsyncResponseTransformer<GetObjectResponse, GetObjectResponse>>
toDownloadFileRequestAndTransformer(ResumableFileDownload resumableFileDownload,
HeadObjectResponse headObjectResponse,
DownloadFileRequest originalDownloadRequest) {
GetObjectRequest getObjectRequest = originalDownloadRequest.getObjectRequest();
DownloadFileRequest newDownloadFileRequest;
boolean shouldAppend;
Instant lastModified = resumableFileDownload.s3ObjectLastModified().orElse(null);
boolean s3ObjectNotModified = headObjectResponse.lastModified().equals(lastModified);
boolean fileNotModified = fileNotModified(resumableFileDownload.bytesTransferred(),
resumableFileDownload.fileLastModified(), resumableFileDownload.downloadFileRequest().destination());
if (fileNotModified && s3ObjectNotModified) {
newDownloadFileRequest = resumedDownloadFileRequest(resumableFileDownload,
originalDownloadRequest,
getObjectRequest,
headObjectResponse);
shouldAppend = true;
} else {
logIfNeeded(originalDownloadRequest, getObjectRequest, fileNotModified, s3ObjectNotModified);
shouldAppend = false;
newDownloadFileRequest = newDownloadFileRequest(originalDownloadRequest, getObjectRequest,
headObjectResponse);
}
AsyncResponseTransformer<GetObjectResponse, GetObjectResponse> responseTransformer =
fileAsyncResponseTransformer(newDownloadFileRequest, shouldAppend);
return Pair.of(newDownloadFileRequest, responseTransformer);
}
private static AsyncResponseTransformer<GetObjectResponse, GetObjectResponse> fileAsyncResponseTransformer(
DownloadFileRequest newDownloadFileRequest,
boolean shouldAppend) {
FileTransformerConfiguration fileTransformerConfiguration =
shouldAppend ? FileTransformerConfiguration.defaultCreateOrAppend() :
FileTransformerConfiguration.defaultCreateOrReplaceExisting();
return AsyncResponseTransformer.toFile(newDownloadFileRequest.destination(),
fileTransformerConfiguration);
}
private static void logIfNeeded(DownloadFileRequest downloadRequest,
GetObjectRequest getObjectRequest,
boolean fileNotModified,
boolean s3ObjectNotModified) {
if (log.logger().isDebugEnabled()) {
if (!s3ObjectNotModified) {
log.debug(() -> String.format("The requested object in bucket (%s) with key (%s) "
+ "has been modified on Amazon S3 since the last "
+ "pause. The SDK will download the S3 object from "
+ "the beginning",
getObjectRequest.bucket(), getObjectRequest.key()));
}
if (!fileNotModified) {
log.debug(() -> String.format("The file (%s) has been modified since "
+ "the last pause. " +
"The SDK will download the requested object in bucket"
+ " (%s) with key (%s) from "
+ "the "
+ "beginning.",
downloadRequest.destination(),
getObjectRequest.bucket(),
getObjectRequest.key()));
}
}
}
private static DownloadFileRequest resumedDownloadFileRequest(ResumableFileDownload resumableFileDownload,
DownloadFileRequest downloadRequest,
GetObjectRequest getObjectRequest,
HeadObjectResponse headObjectResponse) {
DownloadFileRequest newDownloadFileRequest;
long bytesTransferred = resumableFileDownload.bytesTransferred();
GetObjectRequest newGetObjectRequest =
getObjectRequest.toBuilder()
.ifUnmodifiedSince(headObjectResponse.lastModified())
.range("bytes=" + bytesTransferred + "-" + headObjectResponse.contentLength())
.build();
newDownloadFileRequest = downloadRequest.toBuilder()
.getObjectRequest(newGetObjectRequest)
.build();
return newDownloadFileRequest;
}
private static DownloadFileRequest newDownloadFileRequest(DownloadFileRequest originalDownloadRequest,
GetObjectRequest getObjectRequest,
HeadObjectResponse headObjectResponse) {
return originalDownloadRequest.toBuilder()
.getObjectRequest(
getObjectRequest.toBuilder()
.ifUnmodifiedSince(headObjectResponse.lastModified()).build())
.build();
}
}
| 3,785 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/internal | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/internal/model/DefaultDownload.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.model;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.transfer.s3.model.CompletedDownload;
import software.amazon.awssdk.transfer.s3.model.Download;
import software.amazon.awssdk.transfer.s3.progress.TransferProgress;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
@SdkInternalApi
public final class DefaultDownload<ReturnT> implements Download<ReturnT> {
private final CompletableFuture<CompletedDownload<ReturnT>> completionFuture;
private final TransferProgress progress;
public DefaultDownload(CompletableFuture<CompletedDownload<ReturnT>> completionFuture, TransferProgress progress) {
this.completionFuture = Validate.paramNotNull(completionFuture, "completionFuture");
this.progress = Validate.paramNotNull(progress, "progress");
}
@Override
public CompletableFuture<CompletedDownload<ReturnT>> completionFuture() {
return completionFuture;
}
@Override
public TransferProgress progress() {
return progress;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DefaultDownload<?> that = (DefaultDownload<?>) o;
if (!Objects.equals(completionFuture, that.completionFuture)) {
return false;
}
return Objects.equals(progress, that.progress);
}
@Override
public int hashCode() {
int result = completionFuture != null ? completionFuture.hashCode() : 0;
result = 31 * result + (progress != null ? progress.hashCode() : 0);
return result;
}
@Override
public String toString() {
return ToString.builder("DefaultDownload")
.add("completionFuture", completionFuture)
.add("progress", progress)
.build();
}
}
| 3,786 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/internal | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/internal/model/DefaultFileDownload.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.model;
import java.io.File;
import java.time.Instant;
import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.transfer.s3.model.CompletedFileDownload;
import software.amazon.awssdk.transfer.s3.model.DownloadFileRequest;
import software.amazon.awssdk.transfer.s3.model.FileDownload;
import software.amazon.awssdk.transfer.s3.model.ResumableFileDownload;
import software.amazon.awssdk.transfer.s3.progress.TransferProgress;
import software.amazon.awssdk.transfer.s3.progress.TransferProgressSnapshot;
import software.amazon.awssdk.utils.Lazy;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
@SdkInternalApi
public final class DefaultFileDownload implements FileDownload {
private final CompletableFuture<CompletedFileDownload> completionFuture;
private final Lazy<ResumableFileDownload> resumableFileDownload;
private final TransferProgress progress;
private final Supplier<DownloadFileRequest> requestSupplier;
private final ResumableFileDownload resumedDownload;
public DefaultFileDownload(CompletableFuture<CompletedFileDownload> completedFileDownloadFuture,
TransferProgress progress,
Supplier<DownloadFileRequest> requestSupplier,
ResumableFileDownload resumedDownload) {
this.completionFuture = Validate.paramNotNull(completedFileDownloadFuture, "completedFileDownloadFuture");
this.progress = Validate.paramNotNull(progress, "progress");
this.requestSupplier = Validate.paramNotNull(requestSupplier, "requestSupplier");
this.resumableFileDownload = new Lazy<>(this::doPause);
this.resumedDownload = resumedDownload;
}
@Override
public TransferProgress progress() {
return progress;
}
@Override
public ResumableFileDownload pause() {
return resumableFileDownload.getValue();
}
private ResumableFileDownload doPause() {
completionFuture.cancel(true);
Instant s3objectLastModified = null;
Long totalSizeInBytes = null;
TransferProgressSnapshot snapshot = progress.snapshot();
if (snapshot.sdkResponse().isPresent() && snapshot.sdkResponse().get() instanceof GetObjectResponse) {
GetObjectResponse getObjectResponse = (GetObjectResponse) snapshot.sdkResponse().get();
s3objectLastModified = getObjectResponse.lastModified();
totalSizeInBytes = getObjectResponse.contentLength();
} else if (resumedDownload != null) {
s3objectLastModified = resumedDownload.s3ObjectLastModified().orElse(null);
totalSizeInBytes = resumedDownload.totalSizeInBytes().isPresent() ? resumedDownload.totalSizeInBytes().getAsLong()
: null;
}
DownloadFileRequest request = requestSupplier.get();
File destination = request.destination().toFile();
long length = destination.length();
Instant fileLastModified = Instant.ofEpochMilli(destination.lastModified());
return ResumableFileDownload.builder()
.downloadFileRequest(request)
.s3ObjectLastModified(s3objectLastModified)
.fileLastModified(fileLastModified)
.bytesTransferred(length)
.totalSizeInBytes(totalSizeInBytes)
.build();
}
@Override
public CompletableFuture<CompletedFileDownload> completionFuture() {
return completionFuture;
}
@Override
public String toString() {
return ToString.builder("DefaultFileDownload")
.add("completionFuture", completionFuture)
.add("progress", progress)
.add("request", requestSupplier.get())
.build();
}
}
| 3,787 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/internal | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/internal/model/CrtFileUpload.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.model;
import java.io.File;
import java.time.Instant;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.crt.CrtRuntimeException;
import software.amazon.awssdk.crt.s3.ResumeToken;
import software.amazon.awssdk.services.s3.internal.crt.S3MetaRequestPauseObservable;
import software.amazon.awssdk.transfer.s3.model.CompletedFileUpload;
import software.amazon.awssdk.transfer.s3.model.FileUpload;
import software.amazon.awssdk.transfer.s3.model.ResumableFileUpload;
import software.amazon.awssdk.transfer.s3.model.UploadFileRequest;
import software.amazon.awssdk.transfer.s3.progress.TransferProgress;
import software.amazon.awssdk.utils.Lazy;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
@SdkInternalApi
public final class CrtFileUpload implements FileUpload {
private final Lazy<ResumableFileUpload> resumableFileUpload;
private final CompletableFuture<CompletedFileUpload> completionFuture;
private final TransferProgress progress;
private final UploadFileRequest request;
private final S3MetaRequestPauseObservable observable;
public CrtFileUpload(CompletableFuture<CompletedFileUpload> completionFuture,
TransferProgress progress,
S3MetaRequestPauseObservable observable,
UploadFileRequest request) {
this.completionFuture = Validate.paramNotNull(completionFuture, "completionFuture");
this.progress = Validate.paramNotNull(progress, "progress");
this.observable = Validate.paramNotNull(observable, "observable");
this.request = Validate.paramNotNull(request, "request");
this.resumableFileUpload = new Lazy<>(this::doPause);
}
@Override
public ResumableFileUpload pause() {
return resumableFileUpload.getValue();
}
private ResumableFileUpload doPause() {
File sourceFile = request.source().toFile();
if (completionFuture.isDone()) {
Instant fileLastModified = Instant.ofEpochMilli(sourceFile.lastModified());
return ResumableFileUpload.builder()
.fileLastModified(fileLastModified)
.fileLength(sourceFile.length())
.uploadFileRequest(request)
.build();
}
Instant fileLastModified = Instant.ofEpochMilli(sourceFile
.lastModified());
ResumeToken token = null;
try {
token = observable.pause();
} catch (CrtRuntimeException exception) {
// CRT throws exception if it is a single part
if (!exception.errorName.equals("AWS_ERROR_UNSUPPORTED_OPERATION")) {
throw exception;
}
}
completionFuture.cancel(true);
// Upload hasn't started yet, or it's a single object upload
if (token == null) {
return ResumableFileUpload.builder()
.fileLastModified(fileLastModified)
.fileLength(sourceFile.length())
.uploadFileRequest(request)
.build();
}
return ResumableFileUpload.builder()
.multipartUploadId(token.getUploadId())
.totalParts(token.getTotalNumParts())
.transferredParts(token.getNumPartsCompleted())
.partSizeInBytes(token.getPartSize())
.fileLastModified(fileLastModified)
.fileLength(sourceFile.length())
.uploadFileRequest(request)
.build();
}
@Override
public CompletableFuture<CompletedFileUpload> completionFuture() {
return completionFuture;
}
@Override
public TransferProgress progress() {
return progress;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CrtFileUpload that = (CrtFileUpload) o;
if (!resumableFileUpload.equals(that.resumableFileUpload)) {
return false;
}
if (!completionFuture.equals(that.completionFuture)) {
return false;
}
if (!progress.equals(that.progress)) {
return false;
}
if (!request.equals(that.request)) {
return false;
}
return observable == that.observable;
}
@Override
public int hashCode() {
int result = resumableFileUpload.hashCode();
result = 31 * result + completionFuture.hashCode();
result = 31 * result + progress.hashCode();
result = 31 * result + request.hashCode();
result = 31 * result + observable.hashCode();
return result;
}
@Override
public String toString() {
return ToString.builder("DefaultFileUpload")
.add("completionFuture", completionFuture)
.add("progress", progress)
.add("request", request)
.build();
}
}
| 3,788 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/internal | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/internal/model/DefaultCopy.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.model;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.transfer.s3.model.CompletedCopy;
import software.amazon.awssdk.transfer.s3.model.Copy;
import software.amazon.awssdk.transfer.s3.progress.TransferProgress;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
@SdkInternalApi
public final class DefaultCopy implements Copy {
private final CompletableFuture<CompletedCopy> completionFuture;
private final TransferProgress progress;
public DefaultCopy(CompletableFuture<CompletedCopy> completionFuture, TransferProgress progress) {
this.completionFuture = Validate.paramNotNull(completionFuture, "completionFuture");
this.progress = Validate.paramNotNull(progress, "progress");
}
@Override
public CompletableFuture<CompletedCopy> completionFuture() {
return completionFuture;
}
@Override
public TransferProgress progress() {
return progress;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DefaultCopy that = (DefaultCopy) o;
if (!Objects.equals(completionFuture, that.completionFuture)) {
return false;
}
return Objects.equals(progress, that.progress);
}
@Override
public int hashCode() {
int result = completionFuture != null ? completionFuture.hashCode() : 0;
result = 31 * result + (progress != null ? progress.hashCode() : 0);
return result;
}
@Override
public String toString() {
return ToString.builder("DefaultCopy")
.add("completionFuture", completionFuture)
.add("progress", progress)
.build();
}
}
| 3,789 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/internal | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/internal/model/DefaultUpload.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.model;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.transfer.s3.model.CompletedUpload;
import software.amazon.awssdk.transfer.s3.model.Upload;
import software.amazon.awssdk.transfer.s3.progress.TransferProgress;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
@SdkInternalApi
public final class DefaultUpload implements Upload {
private final CompletableFuture<CompletedUpload> completionFuture;
private final TransferProgress progress;
public DefaultUpload(CompletableFuture<CompletedUpload> completionFuture, TransferProgress progress) {
this.completionFuture = Validate.paramNotNull(completionFuture, "completionFuture");
this.progress = Validate.paramNotNull(progress, "progress");
}
@Override
public CompletableFuture<CompletedUpload> completionFuture() {
return completionFuture;
}
@Override
public TransferProgress progress() {
return progress;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DefaultUpload that = (DefaultUpload) o;
if (!Objects.equals(completionFuture, that.completionFuture)) {
return false;
}
return Objects.equals(progress, that.progress);
}
@Override
public int hashCode() {
int result = completionFuture != null ? completionFuture.hashCode() : 0;
result = 31 * result + (progress != null ? progress.hashCode() : 0);
return result;
}
@Override
public String toString() {
return ToString.builder("DefaultUpload")
.add("completionFuture", completionFuture)
.add("progress", progress)
.build();
}
}
| 3,790 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/internal | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/internal/model/DefaultDirectoryUpload.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.model;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.transfer.s3.model.CompletedDirectoryUpload;
import software.amazon.awssdk.transfer.s3.model.DirectoryUpload;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
@SdkInternalApi
public final class DefaultDirectoryUpload implements DirectoryUpload {
private final CompletableFuture<CompletedDirectoryUpload> completionFuture;
public DefaultDirectoryUpload(CompletableFuture<CompletedDirectoryUpload> completionFuture) {
this.completionFuture = Validate.paramNotNull(completionFuture, "completionFuture");
}
@Override
public CompletableFuture<CompletedDirectoryUpload> completionFuture() {
return completionFuture;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DefaultDirectoryUpload that = (DefaultDirectoryUpload) o;
return Objects.equals(completionFuture, that.completionFuture);
}
@Override
public int hashCode() {
return completionFuture != null ? completionFuture.hashCode() : 0;
}
@Override
public String toString() {
return ToString.builder("DefaultDirectoryUpload")
.add("completionFuture", completionFuture)
.build();
}
}
| 3,791 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/internal | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/internal/model/DefaultFileUpload.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.model;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.transfer.s3.model.CompletedFileUpload;
import software.amazon.awssdk.transfer.s3.model.FileUpload;
import software.amazon.awssdk.transfer.s3.model.ResumableFileUpload;
import software.amazon.awssdk.transfer.s3.model.UploadFileRequest;
import software.amazon.awssdk.transfer.s3.progress.TransferProgress;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
@SdkInternalApi
public final class DefaultFileUpload implements FileUpload {
private final CompletableFuture<CompletedFileUpload> completionFuture;
private final TransferProgress progress;
private final UploadFileRequest request;
public DefaultFileUpload(CompletableFuture<CompletedFileUpload> completionFuture,
TransferProgress progress,
UploadFileRequest request) {
this.completionFuture = Validate.paramNotNull(completionFuture, "completionFuture");
this.progress = Validate.paramNotNull(progress, "progress");
this.request = Validate.paramNotNull(request, "request");
}
@Override
public ResumableFileUpload pause() {
throw new UnsupportedOperationException("Pausing an upload is not supported in a non CRT-based S3 Client. For "
+ "upload pause support, pass an AWS CRT-based S3 client to S3TransferManager"
+ "instead: S3AsyncClient.crtBuilder().build();");
}
@Override
public CompletableFuture<CompletedFileUpload> completionFuture() {
return completionFuture;
}
@Override
public TransferProgress progress() {
return progress;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DefaultFileUpload that = (DefaultFileUpload) o;
if (!completionFuture.equals(that.completionFuture)) {
return false;
}
if (!progress.equals(that.progress)) {
return false;
}
return request.equals(that.request);
}
@Override
public int hashCode() {
int result = completionFuture.hashCode();
result = 31 * result + progress.hashCode();
result = 31 * result + request.hashCode();
return result;
}
@Override
public String toString() {
return ToString.builder("DefaultFileUpload")
.add("completionFuture", completionFuture)
.add("progress", progress)
.add("request", request)
.build();
}
}
| 3,792 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/internal | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/internal/model/DefaultDirectoryDownload.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.internal.model;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.transfer.s3.model.CompletedDirectoryDownload;
import software.amazon.awssdk.transfer.s3.model.DirectoryDownload;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
@SdkInternalApi
public final class DefaultDirectoryDownload implements DirectoryDownload {
private final CompletableFuture<CompletedDirectoryDownload> completionFuture;
public DefaultDirectoryDownload(CompletableFuture<CompletedDirectoryDownload> completionFuture) {
this.completionFuture = Validate.paramNotNull(completionFuture, "completionFuture");
}
@Override
public CompletableFuture<CompletedDirectoryDownload> completionFuture() {
return completionFuture;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DefaultDirectoryDownload that = (DefaultDirectoryDownload) o;
return Objects.equals(completionFuture, that.completionFuture);
}
@Override
public int hashCode() {
return completionFuture != null ? completionFuture.hashCode() : 0;
}
@Override
public String toString() {
return ToString.builder("DefaultDirectoryDownload")
.add("completionFuture", completionFuture)
.build();
}
}
| 3,793 |
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/DirectoryDownload.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 directory of objects from S3
*/
@SdkPublicApi
public interface DirectoryDownload extends DirectoryTransfer {
@Override
CompletableFuture<CompletedDirectoryDownload> completionFuture();
}
| 3,794 |
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/CompletedTransfer.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 completed transfers.
*
* @see CompletedObjectTransfer
* @see CompletedDirectoryTransfer
*/
@SdkPublicApi
public interface CompletedTransfer {
}
| 3,795 |
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/CompletedDownload.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.core.async.AsyncResponseTransformer;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.transfer.s3.model.CompletedDownload.TypedBuilder;
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 transfer from Amazon S3. It can be used to track the underlying result
* that was transformed via an {@link AsyncResponseTransformer}.
*
* @see S3TransferManager#download(DownloadRequest)
*/
@SdkPublicApi
public final class CompletedDownload<ResultT>
implements CompletedObjectTransfer,
ToCopyableBuilder<TypedBuilder<ResultT>, CompletedDownload<ResultT>> {
private final ResultT result;
private CompletedDownload(DefaultTypedBuilder<ResultT> builder) {
this.result = Validate.paramNotNull(builder.result, "result");
}
/**
* Creates a builder that can be used to create a {@link CompletedDownload}.
*
* @see UntypedBuilder
*/
public static UntypedBuilder builder() {
return new DefaultUntypedBuilder();
}
@Override
public TypedBuilder<ResultT> toBuilder() {
return new DefaultTypedBuilder<>(this);
}
/**
* Returns the result.
*/
public ResultT result() {
return result;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CompletedDownload<?> that = (CompletedDownload<?>) o;
return Objects.equals(result, that.result);
}
@Override
public int hashCode() {
return result != null ? result.hashCode() : 0;
}
@Override
public String toString() {
return ToString.builder("CompletedDownload")
.add("result", result)
.build();
}
/**
* Initial calls to {@link CompletedDownload#builder()} return an {@link UntypedBuilder}, where the builder is not yet
* parameterized with the generic type associated with {@link CompletedDownload}. This prevents the otherwise awkward syntax
* of having to explicitly cast the builder type, e.g.,
* {@snippet :
* CompletedDownload.<ResponseBytes<GetObjectResponse>>builder()
* }
* Instead, the type may be inferred as part of specifying the {@link #result(Object)} parameter, at which point the builder
* chain will return a new {@link TypedBuilder}.
*/
public interface UntypedBuilder {
/**
* Specifies the result of the completed download. This method also infers the generic type of {@link CompletedDownload}
* to create.
*
* @param result the result of the completed download, as transformed by an {@link AsyncResponseTransformer}
* @param <T> the type of {@link CompletedDownload} to create
* @return a reference to this object so that method calls can be chained together.
*/
<T> TypedBuilder<T> result(T result);
}
private static class DefaultUntypedBuilder implements UntypedBuilder {
private DefaultUntypedBuilder() {
}
@Override
public <T> TypedBuilder<T> result(T result) {
return new DefaultTypedBuilder<T>()
.result(result);
}
}
/**
* The type-parameterized version of {@link UntypedBuilder}. This builder's type is inferred as part of specifying {@link
* #result(Object)}, after which this builder can be used to construct a {@link CompletedDownload} with the same generic
* type.
*/
public interface TypedBuilder<T> extends CopyableBuilder<TypedBuilder<T>, CompletedDownload<T>> {
/**
* Specifies the result of the completed download. The generic type used is constrained by the {@link
* UntypedBuilder#result(Object)} that was previously used to create this {@link TypedBuilder}.
*
* @param result the result of the completed download, as transformed by an {@link AsyncResponseTransformer}
* @return a reference to this object so that method calls can be chained together.
*/
TypedBuilder<T> result(T result);
}
private static class DefaultTypedBuilder<T> implements TypedBuilder<T> {
private T result;
private DefaultTypedBuilder() {
}
private DefaultTypedBuilder(CompletedDownload<T> request) {
this.result = request.result;
}
@Override
public TypedBuilder<T> result(T result) {
this.result = result;
return this;
}
@Override
public CompletedDownload<T> build() {
return new CompletedDownload<>(this);
}
}
}
| 3,796 |
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/DirectoryTransfer.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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;
/**
* Represents the upload or download of a directory of files to or from S3.
*
* @see DirectoryUpload
*/
@SdkPublicApi
public interface DirectoryTransfer extends Transfer {
}
| 3,797 |
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/CompletedFileUpload.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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#uploadFile(UploadFileRequest)
*/
@SdkPublicApi
public final class CompletedFileUpload implements CompletedObjectTransfer {
private final PutObjectResponse response;
private CompletedFileUpload(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;
}
CompletedFileUpload that = (CompletedFileUpload) o;
return Objects.equals(response, that.response);
}
@Override
public int hashCode() {
return response.hashCode();
}
@Override
public String toString() {
return ToString.builder("CompletedFileUpload")
.add("response", response)
.build();
}
public static Class<? extends Builder> serializableBuilderClass() {
return DefaultBuilder.class;
}
/**
* Creates a default builder for {@link CompletedFileUpload}.
*/
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 CompletedFileUpload} based on the properties supplied to this builder
* @return An initialized {@link CompletedFileUpload}
*/
CompletedFileUpload 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 CompletedFileUpload build() {
return new CompletedFileUpload(this);
}
}
}
| 3,798 |
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/ObjectTransfer.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.progress.TransferProgress;
/**
* Represents the upload or download of a single object to or from S3.
*
* @see FileUpload
* @see FileDownload
* @see Upload
* @see Download
*/
@SdkPublicApi
public interface ObjectTransfer extends Transfer {
/**
* The stateful {@link TransferProgress} associated with this transfer.
*/
TransferProgress progress();
}
| 3,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.