index int64 0 0 | repo_id stringlengths 9 205 | file_path stringlengths 31 246 | content stringlengths 1 12.2M | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/aws-sdk-java-v2/services-custom/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();
}
}
| 4,000 |
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();
}
}
| 4,001 |
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();
}
}
| 4,002 |
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();
}
}
| 4,003 |
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();
}
}
| 4,004 |
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();
}
}
| 4,005 |
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();
}
}
| 4,006 |
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();
}
}
| 4,007 |
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();
}
}
| 4,008 |
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();
}
}
| 4,009 |
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();
}
}
| 4,010 |
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();
}
}
| 4,011 |
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();
}
}
| 4,012 |
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();
}
}
| 4,013 |
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();
}
}
| 4,014 |
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();
}
}
| 4,015 |
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);
}
}
| 4,016 |
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();
}
}
}
}
| 4,017 |
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;
}
}
| 4,018 |
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);
}
}
| 4,019 |
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;
}
}
| 4,020 |
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;
}
}
| 4,021 |
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));
}
}
| 4,022 |
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());
}
}
| 4,023 |
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();
}
}
| 4,024 |
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() {
}
}
| 4,025 |
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();
}
}
| 4,026 |
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();
}
}
}
| 4,027 |
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();
}
| 4,028 |
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();
}
}
}
| 4,029 |
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();
}
| 4,030 |
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;
}
}
| 4,031 |
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);
}
}
}
| 4,032 |
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();
}
}
| 4,033 |
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();
}
}
| 4,034 |
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);
}
}
}
| 4,035 |
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;
}
}
| 4,036 |
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
}
| 4,037 |
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();
}
}
| 4,038 |
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();
}
}
| 4,039 |
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);
}
}
}
| 4,040 |
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;
});
}
}
}
| 4,041 |
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();
}
}
| 4,042 |
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);
}
}
}
| 4,043 |
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();
}
}
| 4,044 |
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);
}
}
}
| 4,045 |
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));
}
}
}
| 4,046 |
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();
}
}
| 4,047 |
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);
}
}
}
| 4,048 |
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());
}
}
| 4,049 |
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);
}
}
}
| 4,050 |
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();
}
}
| 4,051 |
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));
}
}
| 4,052 |
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;
}
}
| 4,053 |
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));
}
}
| 4,054 |
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);
}
| 4,055 |
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");
}
}
| 4,056 |
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();
}
}
| 4,057 |
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();
}
}
| 4,058 |
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();
}
}
| 4,059 |
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();
}
}
| 4,060 |
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();
}
}
| 4,061 |
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();
}
}
| 4,062 |
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();
}
}
| 4,063 |
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();
}
}
| 4,064 |
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();
}
}
| 4,065 |
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();
}
}
| 4,066 |
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();
}
| 4,067 |
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 {
}
| 4,068 |
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);
}
}
}
| 4,069 |
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 {
}
| 4,070 |
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);
}
}
}
| 4,071 |
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();
}
| 4,072 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/CopyRequest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.transfer.s3.model;
import static software.amazon.awssdk.utils.Validate.paramNotNull;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;
import software.amazon.awssdk.annotations.NotThreadSafe;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.services.s3.model.CopyObjectRequest;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.transfer.s3.progress.TransferListener;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* Creates a copy of an object that is already stored in S3.
*
* @see S3TransferManager#copy(CopyRequest)
*/
@SdkPublicApi
public final class CopyRequest
implements TransferObjectRequest,
ToCopyableBuilder<CopyRequest.Builder, CopyRequest> {
private final CopyObjectRequest copyObjectRequest;
private final List<TransferListener> transferListeners;
private CopyRequest(DefaultBuilder builder) {
this.copyObjectRequest = paramNotNull(builder.copyObjectRequest, "copyObjectRequest");
this.transferListeners = builder.transferListeners;
}
/**
* @return The {@link CopyObjectRequest} request that should be used for the copy
*/
public CopyObjectRequest copyObjectRequest() {
return copyObjectRequest;
}
/**
* @return the List of transferListener.
* @see Builder#transferListeners(Collection)
*/
@Override
public List<TransferListener> transferListeners() {
return transferListeners;
}
/**
* Creates a builder that can be used to create a {@link CopyRequest}.
*
* @see S3TransferManager#copy(CopyRequest)
*/
public static Builder builder() {
return new DefaultBuilder();
}
public static Class<? extends Builder> serializableBuilderClass() {
return DefaultBuilder.class;
}
@Override
public Builder toBuilder() {
return new DefaultBuilder(this);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CopyRequest that = (CopyRequest) o;
if (!Objects.equals(copyObjectRequest, that.copyObjectRequest)) {
return false;
}
return Objects.equals(transferListeners, that.transferListeners);
}
@Override
public int hashCode() {
int result = copyObjectRequest != null ? copyObjectRequest.hashCode() : 0;
result = 31 * result + (transferListeners != null ? transferListeners.hashCode() : 0);
return result;
}
@Override
public String toString() {
return ToString.builder("CopyRequest")
.add("copyRequest", copyObjectRequest)
.add("transferListeners", transferListeners)
.build();
}
/**
* A builder for a {@link CopyRequest}, created with {@link #builder()}
*/
@SdkPublicApi
@NotThreadSafe
public interface Builder extends CopyableBuilder<Builder, CopyRequest> {
/**
* Configures the {@link CopyRequest} that should be used for the copy
*
* @param copyRequest the copyRequest
* @return Returns a reference to this object so that method calls can be chained together.
* @see #copyObjectRequest(Consumer)
*/
Builder copyObjectRequest(CopyObjectRequest copyRequest);
/**
* Configures the {@link CopyRequest} that should be used for the copy
*
* <p>
* This is a convenience method that creates an instance of the {@link CopyRequest} builder avoiding the need to create
* one manually via {@link CopyRequest#builder()}.
*
* @param copyRequestBuilder the copyRequest consumer builder
* @return Returns a reference to this object so that method calls can be chained together.
* @see #copyObjectRequest(CopyObjectRequest)
*/
default Builder copyObjectRequest(Consumer<CopyObjectRequest.Builder> copyRequestBuilder) {
return copyObjectRequest(CopyObjectRequest.builder()
.applyMutation(copyRequestBuilder)
.build());
}
/**
* The {@link TransferListener}s that will be notified as part of this request. This method overrides and replaces any
* transferListeners that have already been set. Add an optional request override configuration.
*
* @param transferListeners the collection of transferListeners
* @return Returns a reference to this object so that method calls can be chained together.
* @return This builder for method chaining.
* @see TransferListener
*/
Builder transferListeners(Collection<TransferListener> transferListeners);
/**
* Adds a {@link TransferListener} that will be notified as part of this request.
*
* @param transferListener the transferListener to add
* @return Returns a reference to this object so that method calls can be chained together.
* @see TransferListener
*/
Builder addTransferListener(TransferListener transferListener);
/**
* @return The built request.
*/
@Override
CopyRequest build();
}
private static class DefaultBuilder implements Builder {
private CopyObjectRequest copyObjectRequest;
private List<TransferListener> transferListeners;
private DefaultBuilder() {
}
private DefaultBuilder(CopyRequest copyRequest) {
this.copyObjectRequest = copyRequest.copyObjectRequest;
this.transferListeners = copyRequest.transferListeners;
}
@Override
public Builder copyObjectRequest(CopyObjectRequest copyRequest) {
this.copyObjectRequest = copyRequest;
return this;
}
public CopyObjectRequest getCopyObjectRequest() {
return copyObjectRequest;
}
public void setCopyObjectRequest(CopyObjectRequest copyObjectRequest) {
copyObjectRequest(copyObjectRequest);
}
@Override
public DefaultBuilder transferListeners(Collection<TransferListener> transferListeners) {
this.transferListeners = transferListeners != null ? new ArrayList<>(transferListeners) : null;
return this;
}
@Override
public DefaultBuilder addTransferListener(TransferListener transferListener) {
if (transferListeners == null) {
transferListeners = new ArrayList<>();
}
transferListeners.add(transferListener);
return this;
}
public List<TransferListener> getTransferListeners() {
return transferListeners;
}
public void setTransferListeners(Collection<TransferListener> transferListeners) {
transferListeners(transferListeners);
}
@Override
public CopyRequest build() {
return new CopyRequest(this);
}
}
}
| 4,073 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/DownloadRequest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.transfer.s3.model;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.async.AsyncResponseTransformer;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.transfer.s3.model.DownloadRequest.TypedBuilder;
import software.amazon.awssdk.transfer.s3.progress.TransferListener;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* Represents the request to download an object identified by the bucket and key from S3 through the given
* {@link AsyncResponseTransformer}. For
* downloading to a file, you may use {@link DownloadFileRequest} instead.
*
* @see S3TransferManager#download(DownloadRequest)
*/
@SdkPublicApi
public final class DownloadRequest<ReturnT>
implements TransferObjectRequest,
ToCopyableBuilder<TypedBuilder<ReturnT>, DownloadRequest<ReturnT>> {
private final AsyncResponseTransformer<GetObjectResponse, ReturnT> responseTransformer;
private final GetObjectRequest getObjectRequest;
private final List<TransferListener> transferListeners;
private DownloadRequest(DefaultTypedBuilder<ReturnT> builder) {
this.responseTransformer = Validate.paramNotNull(builder.responseTransformer, "responseTransformer");
this.getObjectRequest = Validate.paramNotNull(builder.getObjectRequest, "getObjectRequest");
this.transferListeners = builder.transferListeners;
}
/**
* Creates a builder that can be used to create a {@link DownloadRequest}.
*
* @see UntypedBuilder
*/
public static UntypedBuilder builder() {
return new DefaultUntypedBuilder();
}
@Override
public TypedBuilder<ReturnT> toBuilder() {
return new DefaultTypedBuilder<>(this);
}
/**
* The {@link Path} to file that response contents will be written to. The file must not exist or this method will throw an
* exception. If the file is not writable by the current user then an exception will be thrown.
*
* @return the destination path
*/
public AsyncResponseTransformer<GetObjectResponse, ReturnT> responseTransformer() {
return responseTransformer;
}
/**
* @return The {@link GetObjectRequest} request that should be used for the download
*/
public GetObjectRequest getObjectRequest() {
return getObjectRequest;
}
/**
* @return the List of transferListeners.
* @see TypedBuilder#transferListeners(Collection)
*/
@Override
public List<TransferListener> transferListeners() {
return transferListeners;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DownloadRequest<?> that = (DownloadRequest<?>) o;
if (!Objects.equals(responseTransformer, that.responseTransformer)) {
return false;
}
if (!Objects.equals(getObjectRequest, that.getObjectRequest)) {
return false;
}
return Objects.equals(transferListeners, that.transferListeners);
}
@Override
public int hashCode() {
int result = responseTransformer != null ? responseTransformer.hashCode() : 0;
result = 31 * result + (getObjectRequest != null ? getObjectRequest.hashCode() : 0);
result = 31 * result + (transferListeners != null ? transferListeners.hashCode() : 0);
return result;
}
@Override
public String toString() {
return ToString.builder("DownloadRequest")
.add("responseTransformer", responseTransformer)
.add("getObjectRequest", getObjectRequest)
.add("transferListeners", transferListeners)
.build();
}
/**
* Initial calls to {@link DownloadRequest#builder()} return an {@link UntypedBuilder}, where the builder is not yet
* parameterized with the generic type associated with {@link DownloadRequest}. This prevents the otherwise awkward syntax of
* having to explicitly cast the builder type, e.g.,
* <pre>
* {@code DownloadRequest.<ResponseBytes<GetObjectResponse>>builder()}
* </pre>
* Instead, the type may be inferred as part of specifying the {@link #responseTransformer(AsyncResponseTransformer)}
* parameter, at which point the builder chain will return a new {@link TypedBuilder}.
*/
public interface UntypedBuilder {
/**
* The {@link GetObjectRequest} request that should be used for the download
*
* @param getObjectRequest the getObject request
* @return a reference to this object so that method calls can be chained together.
* @see #getObjectRequest(Consumer)
*/
UntypedBuilder getObjectRequest(GetObjectRequest getObjectRequest);
/**
* The {@link GetObjectRequest} request that should be used for the download
* <p>
* This is a convenience method that creates an instance of the {@link GetObjectRequest} builder, avoiding the need to
* create one manually via {@link GetObjectRequest#builder()}.
*
* @param getObjectRequestBuilder the getObject request
* @return a reference to this object so that method calls can be chained together.
* @see #getObjectRequest(GetObjectRequest)
*/
default UntypedBuilder getObjectRequest(Consumer<GetObjectRequest.Builder> getObjectRequestBuilder) {
GetObjectRequest request = GetObjectRequest.builder()
.applyMutation(getObjectRequestBuilder)
.build();
getObjectRequest(request);
return this;
}
/**
* The {@link TransferListener}s that will be notified as part of this request. This method overrides and replaces any
* transferListeners that have already been set. Add an optional request override configuration.
*
* @param transferListeners the collection of transferListeners
* @return Returns a reference to this object so that method calls can be chained together.
* @return This builder for method chaining.
* @see TransferListener
*/
UntypedBuilder transferListeners(Collection<TransferListener> transferListeners);
/**
* Adds a {@link TransferListener} that will be notified as part of this request.
*
* @param transferListener the transferListener to add
* @return Returns a reference to this object so that method calls can be chained together.
* @see TransferListener
*/
UntypedBuilder addTransferListener(TransferListener transferListener);
/**
* Specifies the {@link AsyncResponseTransformer} that should be used for the download. This method also infers the
* generic type of {@link DownloadRequest} to create, inferred from the second type parameter of the provided {@link
* AsyncResponseTransformer}. E.g, specifying {@link AsyncResponseTransformer#toBytes()} would result in inferring the
* type of the {@link DownloadRequest} to be of {@code ResponseBytes<GetObjectResponse>}. See the static factory methods
* available in {@link AsyncResponseTransformer}.
*
* @param responseTransformer the AsyncResponseTransformer
* @param <T> the type of {@link DownloadRequest} to create
* @return a reference to this object so that method calls can be chained together.
* @see AsyncResponseTransformer
*/
<T> TypedBuilder<T> responseTransformer(AsyncResponseTransformer<GetObjectResponse, T> responseTransformer);
}
private static final class DefaultUntypedBuilder implements UntypedBuilder {
private GetObjectRequest getObjectRequest;
private List<TransferListener> transferListeners;
private DefaultUntypedBuilder() {
}
@Override
public UntypedBuilder getObjectRequest(GetObjectRequest getObjectRequest) {
this.getObjectRequest = getObjectRequest;
return this;
}
@Override
public UntypedBuilder transferListeners(Collection<TransferListener> transferListeners) {
this.transferListeners = transferListeners != null ? new ArrayList<>(transferListeners) : null;
return this;
}
@Override
public UntypedBuilder addTransferListener(TransferListener transferListener) {
if (transferListeners == null) {
transferListeners = new ArrayList<>();
}
transferListeners.add(transferListener);
return this;
}
public List<TransferListener> getTransferListeners() {
return transferListeners;
}
public void setTransferListeners(Collection<TransferListener> transferListeners) {
transferListeners(transferListeners);
}
@Override
public <T> TypedBuilder<T> responseTransformer(AsyncResponseTransformer<GetObjectResponse, T> responseTransformer) {
return new DefaultTypedBuilder<T>()
.getObjectRequest(getObjectRequest)
.transferListeners(transferListeners)
.responseTransformer(responseTransformer);
}
}
/**
* The type-parameterized version of {@link UntypedBuilder}. This builder's type is inferred as part of specifying {@link
* UntypedBuilder#responseTransformer(AsyncResponseTransformer)}, after which this builder can be used to construct a {@link
* DownloadRequest} with the same generic type.
*/
public interface TypedBuilder<T> extends CopyableBuilder<TypedBuilder<T>, DownloadRequest<T>> {
/**
* The {@link GetObjectRequest} request that should be used for the download
*
* @param getObjectRequest the getObject request
* @return a reference to this object so that method calls can be chained together.
* @see #getObjectRequest(Consumer)
*/
TypedBuilder<T> getObjectRequest(GetObjectRequest getObjectRequest);
/**
* The {@link GetObjectRequest} request that should be used for the download
* <p>
* This is a convenience method that creates an instance of the {@link GetObjectRequest} builder, avoiding the need to
* create one manually via {@link GetObjectRequest#builder()}.
*
* @param getObjectRequestBuilder the getObject request
* @return a reference to this object so that method calls can be chained together.
* @see #getObjectRequest(GetObjectRequest)
*/
default TypedBuilder<T> getObjectRequest(Consumer<GetObjectRequest.Builder> getObjectRequestBuilder) {
GetObjectRequest request = GetObjectRequest.builder()
.applyMutation(getObjectRequestBuilder)
.build();
getObjectRequest(request);
return this;
}
/**
* The {@link TransferListener}s that will be notified as part of this request. This method overrides and replaces any
* transferListeners that have already been set. Add an optional request override configuration.
*
* @param transferListeners the collection of transferListeners
* @return Returns a reference to this object so that method calls can be chained together.
* @return This builder for method chaining.
* @see TransferListener
*/
TypedBuilder<T> transferListeners(Collection<TransferListener> transferListeners);
/**
* Add a {@link TransferListener} that will be notified as part of this request.
*
* @param transferListener the transferListener to add
* @return Returns a reference to this object so that method calls can be chained together.
* @see TransferListener
*/
TypedBuilder<T> addTransferListener(TransferListener transferListener);
/**
* Specifies the {@link AsyncResponseTransformer} that should be used for the download. The generic type used is
* constrained by the {@link UntypedBuilder#responseTransformer(AsyncResponseTransformer)} that was previously used to
* create this {@link TypedBuilder}.
*
* @param responseTransformer the AsyncResponseTransformer
* @return a reference to this object so that method calls can be chained together.
* @see AsyncResponseTransformer
*/
TypedBuilder<T> responseTransformer(AsyncResponseTransformer<GetObjectResponse, T> responseTransformer);
}
private static class DefaultTypedBuilder<T> implements TypedBuilder<T> {
private GetObjectRequest getObjectRequest;
private List<TransferListener> transferListeners;
private AsyncResponseTransformer<GetObjectResponse, T> responseTransformer;
private DefaultTypedBuilder() {
}
private DefaultTypedBuilder(DownloadRequest<T> request) {
this.getObjectRequest = request.getObjectRequest;
this.responseTransformer = request.responseTransformer;
this.transferListeners = request.transferListeners;
}
@Override
public TypedBuilder<T> getObjectRequest(GetObjectRequest getObjectRequest) {
this.getObjectRequest = getObjectRequest;
return this;
}
@Override
public TypedBuilder<T> responseTransformer(AsyncResponseTransformer<GetObjectResponse, T> responseTransformer) {
this.responseTransformer = responseTransformer;
return this;
}
@Override
public TypedBuilder<T> transferListeners(Collection<TransferListener> transferListeners) {
this.transferListeners = transferListeners != null ? new ArrayList<>(transferListeners) : null;
return this;
}
@Override
public TypedBuilder<T> addTransferListener(TransferListener transferListener) {
if (transferListeners == null) {
transferListeners = new ArrayList<>();
}
transferListeners.add(transferListener);
return this;
}
public List<TransferListener> getTransferListeners() {
return transferListeners;
}
public void setTransferListeners(Collection<TransferListener> transferListeners) {
transferListeners(transferListeners);
}
@Override
public DownloadRequest<T> build() {
return new DownloadRequest<>(this);
}
}
}
| 4,074 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/FailedFileDownload.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.transfer.s3.model;
import java.util.Objects;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* Represents a failed single file download from {@link S3TransferManager#downloadDirectory(DownloadDirectoryRequest)}. It
* has a detailed description of the result.
*/
@SdkPublicApi
public final class FailedFileDownload
implements FailedObjectTransfer,
ToCopyableBuilder<FailedFileDownload.Builder, FailedFileDownload> {
private final DownloadFileRequest request;
private final Throwable exception;
private FailedFileDownload(DefaultBuilder builder) {
this.exception = Validate.paramNotNull(builder.exception, "exception");
this.request = Validate.paramNotNull(builder.request, "request");
}
@Override
public Throwable exception() {
return exception;
}
@Override
public DownloadFileRequest request() {
return request;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
FailedFileDownload that = (FailedFileDownload) o;
if (!Objects.equals(request, that.request)) {
return false;
}
return Objects.equals(exception, that.exception);
}
@Override
public int hashCode() {
int result = request != null ? request.hashCode() : 0;
result = 31 * result + (exception != null ? exception.hashCode() : 0);
return result;
}
@Override
public String toString() {
return ToString.builder("FailedFileDownload")
.add("request", request)
.add("exception", exception)
.build();
}
public static Builder builder() {
return new DefaultBuilder();
}
public static Class<? extends Builder> serializableBuilderClass() {
return DefaultBuilder.class;
}
@Override
public Builder toBuilder() {
return new DefaultBuilder(this);
}
public interface Builder extends CopyableBuilder<Builder, FailedFileDownload> {
Builder exception(Throwable exception);
Builder request(DownloadFileRequest request);
}
private static final class DefaultBuilder implements Builder {
private DownloadFileRequest request;
private Throwable exception;
private DefaultBuilder(FailedFileDownload failedFileDownload) {
this.request = failedFileDownload.request;
this.exception = failedFileDownload.exception;
}
private DefaultBuilder() {
}
@Override
public Builder exception(Throwable exception) {
this.exception = exception;
return this;
}
public void setException(Throwable exception) {
exception(exception);
}
public Throwable getException() {
return exception;
}
@Override
public Builder request(DownloadFileRequest request) {
this.request = request;
return this;
}
public void setRequest(DownloadFileRequest request) {
request(request);
}
public DownloadFileRequest getRequest() {
return request;
}
@Override
public FailedFileDownload build() {
return new FailedFileDownload(this);
}
}
}
| 4,075 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/CompletedCopy.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.transfer.s3.model;
import java.util.Objects;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.model.CopyObjectResponse;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
/**
* Represents a completed copy transfer to Amazon S3. It can be used to track the underlying {@link CopyObjectResponse}
*
* @see S3TransferManager#copy(CopyRequest)
*/
@SdkPublicApi
public final class CompletedCopy implements CompletedObjectTransfer {
private final CopyObjectResponse response;
private CompletedCopy(DefaultBuilder builder) {
this.response = Validate.paramNotNull(builder.response, "response");
}
/**
* Returns the {@link CopyObjectResponse}.
*/
@Override
public CopyObjectResponse response() {
return response;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CompletedCopy that = (CompletedCopy) o;
return Objects.equals(response, that.response);
}
@Override
public int hashCode() {
return response.hashCode();
}
@Override
public String toString() {
return ToString.builder("CompletedCopy")
.add("response", response)
.build();
}
public static Class<? extends Builder> serializableBuilderClass() {
return DefaultBuilder.class;
}
/**
* Creates a default builder for {@link CompletedCopy}.
*/
public static Builder builder() {
return new DefaultBuilder();
}
public interface Builder {
/**
* Specifies the {@link CopyObjectResponse} from {@link S3AsyncClient#putObject}
*
* @param response the response
* @return This builder for method chaining.
*/
Builder response(CopyObjectResponse response);
/**
* Builds a {@link CompletedCopy} based on the properties supplied to this builder
*
* @return An initialized {@link CompletedCopy}
*/
CompletedCopy build();
}
private static class DefaultBuilder implements Builder {
private CopyObjectResponse response;
private DefaultBuilder() {
}
@Override
public Builder response(CopyObjectResponse response) {
this.response = response;
return this;
}
@Override
public CompletedCopy build() {
return new CompletedCopy(this);
}
}
}
| 4,076 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/CompletedDirectoryDownload.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.transfer.s3.model;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* Represents a completed download directory transfer to Amazon S3. It can be used to track
* failed single file downloads.
*
* @see S3TransferManager#downloadDirectory(DownloadDirectoryRequest)
*/
@SdkPublicApi
public final class CompletedDirectoryDownload implements CompletedDirectoryTransfer,
ToCopyableBuilder<CompletedDirectoryDownload.Builder,
CompletedDirectoryDownload> {
private final List<FailedFileDownload> failedTransfers;
private CompletedDirectoryDownload(DefaultBuilder builder) {
this.failedTransfers = Collections.unmodifiableList(
new ArrayList<>(Validate.paramNotNull(builder.failedTransfers, "failedTransfers")));
}
@Override
public List<FailedFileDownload> failedTransfers() {
return failedTransfers;
}
/**
* Creates a default builder for {@link CompletedDirectoryDownload}.
*/
public static Builder builder() {
return new DefaultBuilder();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CompletedDirectoryDownload that = (CompletedDirectoryDownload) o;
return Objects.equals(failedTransfers, that.failedTransfers);
}
@Override
public int hashCode() {
return failedTransfers != null ? failedTransfers.hashCode() : 0;
}
@Override
public String toString() {
return ToString.builder("CompletedDirectoryDownload")
.add("failedTransfers", failedTransfers)
.build();
}
public static Class<? extends Builder> serializableBuilderClass() {
return DefaultBuilder.class;
}
@Override
public Builder toBuilder() {
return new DefaultBuilder(this);
}
public interface Builder extends CopyableBuilder<CompletedDirectoryDownload.Builder,
CompletedDirectoryDownload> {
/**
* Sets a collection of {@link FailedFileDownload}s
*
* @param failedTransfers failed download
* @return This builder for method chaining.
*/
Builder failedTransfers(Collection<FailedFileDownload> failedTransfers);
/**
* Adds a {@link FailedFileDownload}
*
* @param failedTransfer failed download
* @return This builder for method chaining.
*/
Builder addFailedTransfer(FailedFileDownload failedTransfer);
/**
* Builds a {@link CompletedDirectoryDownload} based on the properties supplied to this builder
* @return An initialized {@link CompletedDirectoryDownload}
*/
CompletedDirectoryDownload build();
}
private static final class DefaultBuilder implements Builder {
private Collection<FailedFileDownload> failedTransfers = new ArrayList<>();
private DefaultBuilder() {
}
private DefaultBuilder(CompletedDirectoryDownload completedDirectoryDownload) {
this.failedTransfers = new ArrayList<>(completedDirectoryDownload.failedTransfers);
}
@Override
public Builder failedTransfers(Collection<FailedFileDownload> failedTransfers) {
this.failedTransfers = new ArrayList<>(failedTransfers);
return this;
}
@Override
public Builder addFailedTransfer(FailedFileDownload failedTransfer) {
failedTransfers.add(failedTransfer);
return this;
}
public Collection<FailedFileDownload> getFailedTransfers() {
return Collections.unmodifiableCollection(failedTransfers);
}
public void setFailedTransfers(Collection<FailedFileDownload> failedTransfers) {
failedTransfers(failedTransfers);
}
@Override
public CompletedDirectoryDownload build() {
return new CompletedDirectoryDownload(this);
}
}
}
| 4,077 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/CompletedDirectoryTransfer.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.transfer.s3.model;
import java.util.List;
import software.amazon.awssdk.annotations.SdkPublicApi;
/**
* A completed directory-based transfer.
*
* @see CompletedDirectoryUpload
*/
@SdkPublicApi
public interface CompletedDirectoryTransfer extends CompletedTransfer {
/**
* A list of failed transfer details, including the {@link FailedObjectTransfer#exception()} responsible for the failure and
* the {@link FailedObjectTransfer#request()} that initiated the transfer.
*
* @return an immutable list of failed transfers
*/
List<? extends FailedObjectTransfer> failedTransfers();
}
| 4,078 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/DownloadFileRequest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.transfer.s3.model;
import java.io.File;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;
import software.amazon.awssdk.annotations.NotThreadSafe;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.transfer.s3.progress.TransferListener;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* Download an object identified by the bucket and key from S3 to a local file. For non-file-based downloads, you may use {@link
* DownloadRequest} instead.
*
* @see S3TransferManager#downloadFile(DownloadFileRequest)
*/
@SdkPublicApi
public final class DownloadFileRequest
implements TransferObjectRequest, ToCopyableBuilder<DownloadFileRequest.Builder, DownloadFileRequest> {
private final Path destination;
private final GetObjectRequest getObjectRequest;
private final List<TransferListener> transferListeners;
private DownloadFileRequest(DefaultBuilder builder) {
this.destination = Validate.paramNotNull(builder.destination, "destination");
this.getObjectRequest = Validate.paramNotNull(builder.getObjectRequest, "getObjectRequest");
this.transferListeners = builder.transferListeners;
}
/**
* Creates a builder that can be used to create a {@link DownloadFileRequest}.
*
* @see S3TransferManager#downloadFile(DownloadFileRequest)
*/
public static Builder builder() {
return new DefaultBuilder();
}
@Override
public Builder toBuilder() {
return new DefaultBuilder(this);
}
/**
* The {@link Path} to file that response contents will be written to. The file must not exist or this method
* will throw an exception. If the file is not writable by the current user then an exception will be thrown.
*
* @return the destination path
*/
public Path destination() {
return destination;
}
/**
* @return The {@link GetObjectRequest} request that should be used for the download
*/
public GetObjectRequest getObjectRequest() {
return getObjectRequest;
}
/**
*
* @return List of {@link TransferListener}s that will be notified as part of this request.
*/
@Override
public List<TransferListener> transferListeners() {
return transferListeners;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DownloadFileRequest that = (DownloadFileRequest) o;
if (!Objects.equals(destination, that.destination)) {
return false;
}
if (!Objects.equals(getObjectRequest, that.getObjectRequest)) {
return false;
}
return Objects.equals(transferListeners, that.transferListeners);
}
@Override
public int hashCode() {
int result = destination != null ? destination.hashCode() : 0;
result = 31 * result + (getObjectRequest != null ? getObjectRequest.hashCode() : 0);
result = 31 * result + (transferListeners != null ? transferListeners.hashCode() : 0);
return result;
}
@Override
public String toString() {
return ToString.builder("DownloadFileRequest")
.add("destination", destination)
.add("getObjectRequest", getObjectRequest)
.add("transferListeners", transferListeners)
.build();
}
public static Class<? extends Builder> serializableBuilderClass() {
return DefaultBuilder.class;
}
/**
* A builder for a {@link DownloadFileRequest}, created with {@link #builder()}
*/
@SdkPublicApi
@NotThreadSafe
public interface Builder extends CopyableBuilder<Builder, DownloadFileRequest> {
/**
* The {@link Path} to file that response contents will be written to. The file must not exist or this method
* will throw an exception. If the file is not writable by the current user then an exception will be thrown.
*
* @param destination the destination path
* @return Returns a reference to this object so that method calls can be chained together.
*/
Builder destination(Path destination);
/**
* The file that response contents will be written to. The file must not exist or this method
* will throw an exception. If the file is not writable by the current user then an exception will be thrown.
*
* @param destination the destination path
* @return Returns a reference to this object so that method calls can be chained together.
*/
default Builder destination(File destination) {
Validate.paramNotNull(destination, "destination");
return destination(destination.toPath());
}
/**
* The {@link GetObjectRequest} request that should be used for the download
*
* @param getObjectRequest the getObject request
* @return a reference to this object so that method calls can be chained together.
* @see #getObjectRequest(Consumer)
*/
Builder getObjectRequest(GetObjectRequest getObjectRequest);
/**
* The {@link GetObjectRequest} request that should be used for the download
*
* <p>
* This is a convenience method that creates an instance of the {@link GetObjectRequest} builder avoiding the
* need to create one manually via {@link GetObjectRequest#builder()}.
*
* @param getObjectRequestBuilder the getObject request
* @return a reference to this object so that method calls can be chained together.
* @see #getObjectRequest(GetObjectRequest)
*/
default Builder getObjectRequest(Consumer<GetObjectRequest.Builder> getObjectRequestBuilder) {
GetObjectRequest request = GetObjectRequest.builder()
.applyMutation(getObjectRequestBuilder)
.build();
getObjectRequest(request);
return this;
}
/**
* The {@link TransferListener}s that will be notified as part of this request. This method overrides and replaces any
* transferListeners that have already been set. Add an optional request override configuration.
*
* @param transferListeners the collection of transferListeners
* @return Returns a reference to this object so that method calls can be chained together.
* @return This builder for method chaining.
* @see TransferListener
*/
Builder transferListeners(Collection<TransferListener> transferListeners);
/**
* Add a {@link TransferListener} that will be notified as part of this request.
*
* @param transferListener the transferListener to add
* @return Returns a reference to this object so that method calls can be chained together.
* @see TransferListener
*/
Builder addTransferListener(TransferListener transferListener);
}
private static final class DefaultBuilder implements Builder {
private Path destination;
private GetObjectRequest getObjectRequest;
private List<TransferListener> transferListeners;
private DefaultBuilder() {
}
private DefaultBuilder(DownloadFileRequest downloadFileRequest) {
this.destination = downloadFileRequest.destination;
this.getObjectRequest = downloadFileRequest.getObjectRequest;
this.transferListeners = downloadFileRequest.transferListeners;
}
@Override
public Builder destination(Path destination) {
this.destination = Validate.paramNotNull(destination, "destination");
return this;
}
public Path getDestination() {
return destination;
}
public void setDestination(Path destination) {
destination(destination);
}
@Override
public DefaultBuilder getObjectRequest(GetObjectRequest getObjectRequest) {
this.getObjectRequest = getObjectRequest;
return this;
}
public GetObjectRequest getGetObjectRequest() {
return getObjectRequest;
}
public void setGetObjectRequest(GetObjectRequest getObjectRequest) {
getObjectRequest(getObjectRequest);
}
@Override
public DefaultBuilder transferListeners(Collection<TransferListener> transferListeners) {
this.transferListeners = transferListeners != null ? new ArrayList<>(transferListeners) : null;
return this;
}
@Override
public Builder addTransferListener(TransferListener transferListener) {
if (transferListeners == null) {
transferListeners = new ArrayList<>();
}
transferListeners.add(transferListener);
return this;
}
public List<TransferListener> getTransferListeners() {
return transferListeners;
}
public void setTransferListeners(Collection<TransferListener> transferListeners) {
transferListeners(transferListeners);
}
@Override
public DownloadFileRequest build() {
return new DownloadFileRequest(this);
}
}
}
| 4,079 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/TransferDirectoryRequest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.transfer.s3.model;
import software.amazon.awssdk.annotations.SdkPublicApi;
/**
* Interface for all transfer directory requests.
*
* @see UploadDirectoryRequest
*/
@SdkPublicApi
public interface TransferDirectoryRequest extends TransferRequest {
}
| 4,080 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/ResumableFileDownload.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.transfer.s3.model;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Instant;
import java.util.Objects;
import java.util.Optional;
import java.util.OptionalLong;
import java.util.function.Consumer;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.transfer.s3.config.TransferRequestOverrideConfiguration;
import software.amazon.awssdk.transfer.s3.internal.serialization.ResumableFileDownloadSerializer;
import software.amazon.awssdk.utils.IoUtils;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* An opaque token that holds the state and can be used to resume a paused download operation.
* <p>
* <b>Serialization: </b>When serializing this token, the following structures will not be preserved/persisted:
* <ul>
* <li>{@link TransferRequestOverrideConfiguration}</li>
* <li>{@link AwsRequestOverrideConfiguration} (from {@link GetObjectRequest})</li>
* </ul>
*
* @see S3TransferManager#downloadFile(DownloadFileRequest)
*/
@SdkPublicApi
public final class ResumableFileDownload implements ResumableTransfer,
ToCopyableBuilder<ResumableFileDownload.Builder, ResumableFileDownload> {
private final DownloadFileRequest downloadFileRequest;
private final long bytesTransferred;
private final Instant s3ObjectLastModified;
private final Long totalSizeInBytes;
private final Instant fileLastModified;
private ResumableFileDownload(DefaultBuilder builder) {
this.downloadFileRequest = Validate.paramNotNull(builder.downloadFileRequest, "downloadFileRequest");
this.bytesTransferred = builder.bytesTransferred == null ? 0 : Validate.isNotNegative(builder.bytesTransferred,
"bytesTransferred");
this.s3ObjectLastModified = builder.s3ObjectLastModified;
this.totalSizeInBytes = Validate.isPositiveOrNull(builder.totalSizeInBytes, "totalSizeInBytes");
this.fileLastModified = builder.fileLastModified;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ResumableFileDownload that = (ResumableFileDownload) o;
if (bytesTransferred != that.bytesTransferred) {
return false;
}
if (!downloadFileRequest.equals(that.downloadFileRequest)) {
return false;
}
if (!Objects.equals(s3ObjectLastModified, that.s3ObjectLastModified)) {
return false;
}
if (!Objects.equals(fileLastModified, that.fileLastModified)) {
return false;
}
return Objects.equals(totalSizeInBytes, that.totalSizeInBytes);
}
@Override
public int hashCode() {
int result = downloadFileRequest.hashCode();
result = 31 * result + (int) (bytesTransferred ^ (bytesTransferred >>> 32));
result = 31 * result + (s3ObjectLastModified != null ? s3ObjectLastModified.hashCode() : 0);
result = 31 * result + (fileLastModified != null ? fileLastModified.hashCode() : 0);
result = 31 * result + (totalSizeInBytes != null ? totalSizeInBytes.hashCode() : 0);
return result;
}
public static Builder builder() {
return new DefaultBuilder();
}
/**
* @return the {@link DownloadFileRequest} to resume
*/
public DownloadFileRequest downloadFileRequest() {
return downloadFileRequest;
}
/**
* Retrieve the number of bytes that have been transferred.
* @return the number of bytes
*/
public long bytesTransferred() {
return bytesTransferred;
}
/**
* Last modified time of the S3 object since last pause, or {@link Optional#empty()} if unknown
*/
public Optional<Instant> s3ObjectLastModified() {
return Optional.ofNullable(s3ObjectLastModified);
}
/**
* Last modified time of the file since last pause
*/
public Instant fileLastModified() {
return fileLastModified;
}
/**
* The total size of the transfer in bytes or {@link OptionalLong#empty()} if unknown
*
* @return the optional total size of the transfer.
*/
public OptionalLong totalSizeInBytes() {
return totalSizeInBytes == null ? OptionalLong.empty() : OptionalLong.of(totalSizeInBytes);
}
@Override
public String toString() {
return ToString.builder("ResumableFileDownload")
.add("bytesTransferred", bytesTransferred)
.add("fileLastModified", fileLastModified)
.add("s3ObjectLastModified", s3ObjectLastModified)
.add("totalSizeInBytes", totalSizeInBytes)
.add("downloadFileRequest", downloadFileRequest)
.build();
}
/**
* Persists this download object to a file in Base64-encoded JSON format.
*
* @param path The path to the file to which you want to write the serialized download object.
*/
@Override
public void serializeToFile(Path path) {
try {
Files.write(path, ResumableFileDownloadSerializer.toJson(this));
} catch (IOException e) {
throw SdkClientException.create("Failed to write to " + path, e);
}
}
/**
* Writes the serialized JSON data representing this object to an output stream.
* Note that the {@link OutputStream} is not closed or flushed after writing.
*
* @param outputStream The output stream to write the serialized object to.
*/
@Override
public void serializeToOutputStream(OutputStream outputStream) {
byte[] bytes = ResumableFileDownloadSerializer.toJson(this);
try {
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
IoUtils.copy(byteArrayInputStream, outputStream);
} catch (IOException e) {
throw SdkClientException.create("Failed to write this download object to the given OutputStream", e);
}
}
/**
* Returns the serialized JSON data representing this object as a string.
*/
@Override
public String serializeToString() {
return new String(ResumableFileDownloadSerializer.toJson(this), StandardCharsets.UTF_8);
}
/**
* Returns the serialized JSON data representing this object as an {@link SdkBytes} object.
*
* @return the serialized JSON as {@link SdkBytes}
*/
@Override
public SdkBytes serializeToBytes() {
return SdkBytes.fromByteArrayUnsafe(ResumableFileDownloadSerializer.toJson(this));
}
/**
* Returns the serialized JSON data representing this object as an {@link InputStream}.
*
* @return the serialized JSON input stream
*/
@Override
public InputStream serializeToInputStream() {
return new ByteArrayInputStream(ResumableFileDownloadSerializer.toJson(this));
}
/**
* Deserialize data at the given path into a {@link ResumableFileDownload}.
*
* @param path The {@link Path} to the file with serialized data
* @return the deserialized {@link ResumableFileDownload}
*/
public static ResumableFileDownload fromFile(Path path) {
try (InputStream stream = Files.newInputStream(path)) {
return ResumableFileDownloadSerializer.fromJson(stream);
} catch (IOException e) {
throw SdkClientException.create("Failed to create a ResumableFileDownload from " + path, e);
}
}
/**
* Deserialize bytes with JSON data into a {@link ResumableFileDownload}.
*
* @param bytes the serialized data
* @return the deserialized {@link ResumableFileDownload}
*/
public static ResumableFileDownload fromBytes(SdkBytes bytes) {
return ResumableFileDownloadSerializer.fromJson(bytes.asByteArrayUnsafe());
}
/**
* Deserialize a string with JSON data into a {@link ResumableFileDownload}.
*
* @param contents the serialized data
* @return the deserialized {@link ResumableFileDownload}
*/
public static ResumableFileDownload fromString(String contents) {
return ResumableFileDownloadSerializer.fromJson(contents);
}
@Override
public Builder toBuilder() {
return new DefaultBuilder(this);
}
public interface Builder extends CopyableBuilder<Builder, ResumableFileDownload> {
/**
* Sets the download file request
*
* @param downloadFileRequest the download file request
* @return a reference to this object so that method calls can be chained together.
*/
Builder downloadFileRequest(DownloadFileRequest downloadFileRequest);
/**
* The {@link DownloadFileRequest} request
*
* <p>
* This is a convenience method that creates an instance of the {@link DownloadFileRequest} builder avoiding the
* need to create one manually via {@link DownloadFileRequest#builder()}.
*
* @param downloadFileRequestBuilder the download file request builder
* @return a reference to this object so that method calls can be chained together.
* @see #downloadFileRequest(DownloadFileRequest)
*/
default ResumableFileDownload.Builder downloadFileRequest(Consumer<DownloadFileRequest.Builder>
downloadFileRequestBuilder) {
DownloadFileRequest request = DownloadFileRequest.builder()
.applyMutation(downloadFileRequestBuilder)
.build();
downloadFileRequest(request);
return this;
}
/**
* Sets the number of bytes transferred
*
* @param bytesTransferred the number of bytes transferred
* @return a reference to this object so that method calls can be chained together.
*/
Builder bytesTransferred(Long bytesTransferred);
/**
* Sets the total transfer size in bytes
* @param totalSizeInBytes the transfer size in bytes
* @return a reference to this object so that method calls can be chained together.
*/
Builder totalSizeInBytes(Long totalSizeInBytes);
/**
* Sets the last modified time of the object
*
* @param s3ObjectLastModified the last modified time of the object
* @return a reference to this object so that method calls can be chained together.
*/
Builder s3ObjectLastModified(Instant s3ObjectLastModified);
/**
* Sets the last modified time of the object
*
* @param lastModified the last modified time of the object
* @return a reference to this object so that method calls can be chained together.
*/
Builder fileLastModified(Instant lastModified);
}
private static final class DefaultBuilder implements Builder {
private DownloadFileRequest downloadFileRequest;
private Long bytesTransferred;
private Instant s3ObjectLastModified;
private Long totalSizeInBytes;
private Instant fileLastModified;
private DefaultBuilder() {
}
private DefaultBuilder(ResumableFileDownload persistableFileDownload) {
this.downloadFileRequest = persistableFileDownload.downloadFileRequest;
this.bytesTransferred = persistableFileDownload.bytesTransferred;
this.totalSizeInBytes = persistableFileDownload.totalSizeInBytes;
this.fileLastModified = persistableFileDownload.fileLastModified;
this.s3ObjectLastModified = persistableFileDownload.s3ObjectLastModified;
}
@Override
public Builder downloadFileRequest(DownloadFileRequest downloadFileRequest) {
this.downloadFileRequest = downloadFileRequest;
return this;
}
@Override
public Builder bytesTransferred(Long bytesTransferred) {
this.bytesTransferred = bytesTransferred;
return this;
}
@Override
public Builder totalSizeInBytes(Long totalSizeInBytes) {
this.totalSizeInBytes = totalSizeInBytes;
return this;
}
@Override
public Builder s3ObjectLastModified(Instant s3ObjectLastModified) {
this.s3ObjectLastModified = s3ObjectLastModified;
return this;
}
@Override
public Builder fileLastModified(Instant fileLastModified) {
this.fileLastModified = fileLastModified;
return this;
}
@Override
public ResumableFileDownload build() {
return new ResumableFileDownload(this);
}
}
}
| 4,081 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/UploadRequest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.transfer.s3.model;
import static software.amazon.awssdk.utils.Validate.paramNotNull;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;
import software.amazon.awssdk.annotations.NotThreadSafe;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.transfer.s3.progress.TransferListener;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* Upload the given {@link AsyncRequestBody} to an object in S3. For file-based uploads, you may use {@link UploadFileRequest}
* instead.
*
* @see S3TransferManager#upload(UploadRequest)
*/
@SdkPublicApi
public final class UploadRequest
implements TransferObjectRequest,
ToCopyableBuilder<UploadRequest.Builder, UploadRequest> {
private final PutObjectRequest putObjectRequest;
private final AsyncRequestBody requestBody;
private final List<TransferListener> listeners;
private UploadRequest(DefaultBuilder builder) {
this.putObjectRequest = paramNotNull(builder.putObjectRequest, "putObjectRequest");
this.requestBody = paramNotNull(builder.requestBody, "requestBody");
this.listeners = builder.listeners;
}
/**
* @return The {@link PutObjectRequest} request that should be used for the upload
*/
public PutObjectRequest putObjectRequest() {
return putObjectRequest;
}
/**
* The {@link AsyncRequestBody} containing data to send to the service.
*
* @return the request body
*/
public AsyncRequestBody requestBody() {
return requestBody;
}
/**
* @return the List of {@link TransferListener}s that will be notified as part of this request.
*/
@Override
public List<TransferListener> transferListeners() {
return listeners;
}
/**
* Creates a builder that can be used to create a {@link UploadRequest}.
*
* @see S3TransferManager#upload(UploadRequest)
*/
public static Builder builder() {
return new DefaultBuilder();
}
public static Class<? extends Builder> serializableBuilderClass() {
return DefaultBuilder.class;
}
@Override
public Builder toBuilder() {
return new DefaultBuilder(this);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
UploadRequest that = (UploadRequest) o;
if (!Objects.equals(putObjectRequest, that.putObjectRequest)) {
return false;
}
if (!Objects.equals(requestBody, that.requestBody)) {
return false;
}
return Objects.equals(listeners, that.listeners);
}
@Override
public int hashCode() {
int result = putObjectRequest != null ? putObjectRequest.hashCode() : 0;
result = 31 * result + (requestBody != null ? requestBody.hashCode() : 0);
result = 31 * result + (listeners != null ? listeners.hashCode() : 0);
return result;
}
@Override
public String toString() {
return ToString.builder("UploadRequest")
.add("putObjectRequest", putObjectRequest)
.add("requestBody", requestBody)
.add("configuration", listeners)
.build();
}
/**
* A builder for a {@link UploadRequest}, created with {@link #builder()}
*/
@SdkPublicApi
@NotThreadSafe
public interface Builder extends CopyableBuilder<Builder, UploadRequest> {
/**
* The {@link AsyncRequestBody} containing the data to send to the service. Request bodies may be declared using one of
* the static factory methods in the {@link AsyncRequestBody} class.
*
* @param requestBody the request body
* @return Returns a reference to this object so that method calls can be chained together.
* @see AsyncRequestBody
*/
Builder requestBody(AsyncRequestBody requestBody);
/**
* Configure the {@link PutObjectRequest} that should be used for the upload
*
* @param putObjectRequest the putObjectRequest
* @return Returns a reference to this object so that method calls can be chained together.
* @see #putObjectRequest(Consumer)
*/
Builder putObjectRequest(PutObjectRequest putObjectRequest);
/**
* Configure the {@link PutObjectRequest} that should be used for the upload
*
* <p>
* This is a convenience method that creates an instance of the {@link PutObjectRequest} builder avoiding the
* need to create one manually via {@link PutObjectRequest#builder()}.
*
* @param putObjectRequestBuilder the putObjectRequest consumer builder
* @return Returns a reference to this object so that method calls can be chained together.
* @see #putObjectRequest(PutObjectRequest)
*/
default Builder putObjectRequest(Consumer<PutObjectRequest.Builder> putObjectRequestBuilder) {
return putObjectRequest(PutObjectRequest.builder()
.applyMutation(putObjectRequestBuilder)
.build());
}
/**
* The {@link TransferListener}s that will be notified as part of this request. This method overrides and replaces any
* transferListeners that have already been set. Add an optional request override configuration.
*
* @param transferListeners the collection of transferListeners
* @return Returns a reference to this object so that method calls can be chained together.
* @return This builder for method chaining.
* @see TransferListener
*/
Builder transferListeners(Collection<TransferListener> transferListeners);
/**
* Add a {@link TransferListener} that will be notified as part of this request.
*
* @param transferListener the transferListener to add
* @return Returns a reference to this object so that method calls can be chained together.
* @see TransferListener
*/
Builder addTransferListener(TransferListener transferListener);
/**
* @return The built request.
*/
@Override
UploadRequest build();
}
private static class DefaultBuilder implements Builder {
private PutObjectRequest putObjectRequest;
private AsyncRequestBody requestBody;
private List<TransferListener> listeners;
private DefaultBuilder() {
}
private DefaultBuilder(UploadRequest uploadRequest) {
this.putObjectRequest = uploadRequest.putObjectRequest;
this.requestBody = uploadRequest.requestBody;
this.listeners = uploadRequest.listeners;
}
@Override
public Builder requestBody(AsyncRequestBody requestBody) {
this.requestBody = Validate.paramNotNull(requestBody, "requestBody");
return this;
}
public AsyncRequestBody getRequestBody() {
return requestBody;
}
public void setRequestBody(AsyncRequestBody requestBody) {
requestBody(requestBody);
}
@Override
public Builder putObjectRequest(PutObjectRequest putObjectRequest) {
this.putObjectRequest = putObjectRequest;
return this;
}
public PutObjectRequest getPutObjectRequest() {
return putObjectRequest;
}
public void setPutObjectRequest(PutObjectRequest putObjectRequest) {
putObjectRequest(putObjectRequest);
}
@Override
public Builder transferListeners(Collection<TransferListener> transferListeners) {
this.listeners = transferListeners != null ? new ArrayList<>(transferListeners) : null;
return this;
}
@Override
public Builder addTransferListener(TransferListener transferListener) {
if (listeners == null) {
listeners = new ArrayList<>();
}
listeners.add(transferListener);
return this;
}
public List<TransferListener> getListeners() {
return listeners;
}
public void setListeners(Collection<TransferListener> listeners) {
transferListeners(listeners);
}
@Override
public UploadRequest build() {
return new UploadRequest(this);
}
}
}
| 4,082 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/TransferRequest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.transfer.s3.model;
import software.amazon.awssdk.annotations.SdkPublicApi;
/**
* The parent interface for all transfer requests.
*
* @see TransferObjectRequest
* @see TransferDirectoryRequest
*/
@SdkPublicApi
public interface TransferRequest {
}
| 4,083 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/FailedObjectTransfer.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.transfer.s3.model;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
/**
* Represents a failed single file transfer in a multi-file transfer operation such as
* {@link S3TransferManager#uploadDirectory}
*/
@SdkPublicApi
public interface FailedObjectTransfer {
/**
* The exception thrown from a specific single file transfer
*
* @return the exception thrown
*/
Throwable exception();
/**
* The failed {@link TransferObjectRequest}.
*
* @return the failed request
*/
TransferObjectRequest request();
}
| 4,084 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/DownloadDirectoryRequest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.transfer.s3.model;
import java.nio.file.Path;
import java.util.Objects;
import java.util.function.Consumer;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.ListObjectsV2Request;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.transfer.s3.config.DownloadFilter;
import software.amazon.awssdk.transfer.s3.config.TransferRequestOverrideConfiguration;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* Request object to download the objects in the provided S3 bucket to a local directory using the Transfer Manager.
*
* @see S3TransferManager#downloadDirectory(DownloadDirectoryRequest)
*/
@SdkPublicApi
public final class DownloadDirectoryRequest
implements TransferDirectoryRequest, ToCopyableBuilder<DownloadDirectoryRequest.Builder, DownloadDirectoryRequest> {
private final Path destination;
private final String bucket;
private final DownloadFilter filter;
private final Consumer<DownloadFileRequest.Builder> downloadFileRequestTransformer;
private final Consumer<ListObjectsV2Request.Builder> listObjectsRequestTransformer;
public DownloadDirectoryRequest(DefaultBuilder builder) {
this.destination = Validate.paramNotNull(builder.destination, "destination");
this.bucket = Validate.paramNotNull(builder.bucket, "bucket");
this.filter = builder.filter;
this.downloadFileRequestTransformer = builder.downloadFileRequestTransformer;
this.listObjectsRequestTransformer = builder.listObjectsRequestTransformer;
}
/**
* The destination directory to which files should be downloaded.
*
* @return the destination directory
* @see Builder#destination(Path)
*/
public Path destination() {
return destination;
}
/**
* The name of the bucket
*
* @return bucket name
* @see Builder#bucket(String)
*/
public String bucket() {
return bucket;
}
/**
* @return the optional filter, or {@link DownloadFilter#allObjects()} if no filter was provided
* @see Builder#filter(DownloadFilter)
*/
public DownloadFilter filter() {
return filter == null ? DownloadFilter.allObjects() : filter;
}
/**
* @return the {@link ListObjectsV2Request} transformer if not null, otherwise no-op
* @see Builder#listObjectsV2RequestTransformer(Consumer)
*/
public Consumer<ListObjectsV2Request.Builder> listObjectsRequestTransformer() {
return listObjectsRequestTransformer == null ? ignore -> { } : listObjectsRequestTransformer;
}
/**
* @return the upload request transformer if not null, otherwise no-op
* @see Builder#listObjectsV2RequestTransformer(Consumer)
*/
public Consumer<DownloadFileRequest.Builder> downloadFileRequestTransformer() {
return downloadFileRequestTransformer == null ? ignore -> { } : downloadFileRequestTransformer;
}
public static Builder builder() {
return new DefaultBuilder();
}
public static Class<? extends Builder> serializableBuilderClass() {
return DefaultBuilder.class;
}
@Override
public Builder toBuilder() {
return new DefaultBuilder(this);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DownloadDirectoryRequest that = (DownloadDirectoryRequest) o;
if (!Objects.equals(destination, that.destination)) {
return false;
}
if (!Objects.equals(bucket, that.bucket)) {
return false;
}
if (!Objects.equals(downloadFileRequestTransformer, that.downloadFileRequestTransformer)) {
return false;
}
if (!Objects.equals(listObjectsRequestTransformer, that.listObjectsRequestTransformer)) {
return false;
}
return Objects.equals(filter, that.filter);
}
@Override
public int hashCode() {
int result = destination != null ? destination.hashCode() : 0;
result = 31 * result + (bucket != null ? bucket.hashCode() : 0);
result = 31 * result + (filter != null ? filter.hashCode() : 0);
result = 31 * result + (downloadFileRequestTransformer != null ? downloadFileRequestTransformer.hashCode() : 0);
result = 31 * result + (listObjectsRequestTransformer != null ? listObjectsRequestTransformer.hashCode() : 0);
return result;
}
@Override
public String toString() {
return ToString.builder("DownloadDirectoryRequest")
.add("destination", destination)
.add("bucket", bucket)
.add("filter", filter)
.add("downloadFileRequestTransformer", downloadFileRequestTransformer)
.add("listObjectsRequestTransformer", listObjectsRequestTransformer)
.build();
}
public interface Builder extends CopyableBuilder<Builder, DownloadDirectoryRequest> {
/**
* Specifies the destination directory to which files should be downloaded.
*
* @param destination the destination directorÏy
* @return This builder for method chaining.
*/
Builder destination(Path destination);
/**
* The name of the bucket to download objects from.
*
* @param bucket the bucket name
* @return This builder for method chaining.
*/
Builder bucket(String bucket);
/**
* Specifies a filter that will be used to evaluate which objects should be downloaded from the target directory.
* <p>
* You can use a filter, for example, to only download objects of a given size, of a given file extension, of a given
* last-modified date, etc. See {@link DownloadFilter} for some ready-made implementations. Multiple {@link
* DownloadFilter}s can be composed together via the {@code and} and {@code or} methods.
* <p>
* By default, if no filter is specified, all objects will be downloaded.
*
* @param filter the filter
* @return This builder for method chaining.
* @see DownloadFilter
*/
Builder filter(DownloadFilter filter);
/**
* Specifies a function used to transform the {@link DownloadFileRequest}s generated by this
* {@link DownloadDirectoryRequest}. The provided function is called once for each file that is downloaded, allowing
* you to modify the paths resolved by TransferManager on a per-file basis, modify the created {@link GetObjectRequest}
* before it is passed to S3, or configure a {@link TransferRequestOverrideConfiguration}.
*
* <p>The factory receives the {@link DownloadFileRequest}s created by Transfer Manager for each S3 Object in the
* S3 bucket being downloaded and returns a (potentially modified) {@code DownloadFileRequest}.
*
* <p>
* <b>Usage Example:</b>
* {@snippet :
* // Add a LoggingTransferListener to every transfer within the download directory request
*
* DownloadDirectoryRequest request =
* DownloadDirectoryRequest.builder()
* .destination(Paths.get("."))
* .bucket("bucket")
* .downloadFileRequestTransformer(request -> request.addTransferListener(LoggingTransferListener.create()))
* .build();
*
* DownloadDirectoryTransfer downloadDirectory = transferManager.downloadDirectory(request);
*
* // Wait for the transfer to complete
* CompletedDownloadDirectory completedDownloadDirectory = downloadDirectory.completionFuture().join();
*
* // Print out the failed downloads
* completedDownloadDirectory.failedDownloads().forEach(System.out::println);
* }
*
* @param downloadFileRequestTransformer A transformer to use for modifying the file-level download requests
* before execution
* @return This builder for method chaining
*/
Builder downloadFileRequestTransformer(Consumer<DownloadFileRequest.Builder> downloadFileRequestTransformer);
/**
* Specifies a function used to transform the {@link ListObjectsV2Request}s generated by this
* {@link DownloadDirectoryRequest}. The provided function is called once, allowing you to modify
* {@link ListObjectsV2Request} before it is passed to S3.
*
* <p>The factory receives the {@link ListObjectsV2Request}s created by Transfer Manager and
* returns a (potentially modified) {@code ListObjectsV2Request}.
*
* <p>
* <b>Usage Example:</b>
* {@snippet :
*
* DownloadDirectoryRequest request =
* DownloadDirectoryRequest.builder()
* .destination(Paths.get("."))
* .bucket("bucket")
* .listObjectsV2RequestTransformer(request -> request.encodingType(newEncodingType))
* .build();
*
* DownloadDirectoryTransfer downloadDirectory = transferManager.downloadDirectory(request);
*
* // Wait for the transfer to complete
* CompletedDownloadDirectory completedDownloadDirectory = downloadDirectory.completionFuture().join();
*
* // Print out the failed downloads
* completedDownloadDirectory.failedDownloads().forEach(System.out::println);
* }
*
* <p>
* <b>Prefix:</b>
* {@code ListObjectsV2Request}'s {@code prefix} specifies the key prefix for the virtual directory. If not provided,
* all subdirectories will be downloaded recursively
* <p>
* See <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-prefixes.html">Organizing objects using
* prefixes</a>
*
* <p>
* When a non-empty prefix is provided, the prefix is stripped from the directory structure of the files.
* <p>
* For example, assume that you have the following keys in your bucket:
* <ul>
* <li>sample.jpg</li>
* <li>photos/2022/January/sample.jpg</li>
* <li>photos/2022/February/sample1.jpg</li>
* <li>photos/2022/February/sample2.jpg</li>
* <li>photos/2022/February/sample3.jpg</li>
* </ul>
*
* Given a request to download the bucket to a destination with a prefix of "/photos" and destination path of "test", the
* downloaded directory would like this
*
* <pre>
* {@code
* |- test
* |- 2022
* |- January
* |- sample.jpg
* |- February
* |- sample1.jpg
* |- sample2.jpg
* |- sample3.jpg
* }
* </pre>
*
* <p>
* <b>Delimiter:</b>
* {@code ListObjectsV2Request}'s {@code delimiter} specifies the delimiter that will be used to retrieve the objects
* within the provided bucket. A delimiter causes a list operation to roll up all the keys that share a common prefix
* into a single summary list result. It's null by default.
*
* For example, assume that you have the following keys in your bucket:
*
* <ul>
* <li>sample.jpg</li>
* <li>photos-2022-January-sample.jpg</li>
* <li>photos-2022-February-sample1.jpg</li>
* <li>photos-2022-February-sample2.jpg</li>
* <li>photos-2022-February-sample3.jpg</li>
* </ul>
*
* Given a request to download the bucket to a destination with delimiter of "-", the downloaded directory would look
* like this
*
* <pre>
* {@code
* |- test
* |- sample.jpg
* |- photos
* |- 2022
* |- January
* |- sample.jpg
* |- February
* |- sample1.jpg
* |- sample2.jpg
* |- sample3.jpg
* }
* </pre>
*
* @param listObjectsV2RequestTransformer A transformer to use for modifying ListObjectsV2Request before execution
* @return This builder for method chaining
*/
Builder listObjectsV2RequestTransformer(Consumer<ListObjectsV2Request.Builder> listObjectsV2RequestTransformer);
}
private static final class DefaultBuilder implements Builder {
private Path destination;
private String bucket;
private DownloadFilter filter;
private Consumer<DownloadFileRequest.Builder> downloadFileRequestTransformer;
private Consumer<ListObjectsV2Request.Builder> listObjectsRequestTransformer;
private DefaultBuilder() {
}
private DefaultBuilder(DownloadDirectoryRequest request) {
this.destination = request.destination;
this.bucket = request.bucket;
this.filter = request.filter;
this.downloadFileRequestTransformer = request.downloadFileRequestTransformer;
this.listObjectsRequestTransformer = request.listObjectsRequestTransformer;
}
@Override
public Builder destination(Path destination) {
this.destination = destination;
return this;
}
public void setDestination(Path destination) {
destination(destination);
}
public Path getDestination() {
return destination;
}
@Override
public Builder bucket(String bucket) {
this.bucket = bucket;
return this;
}
public void setBucket(String bucket) {
bucket(bucket);
}
public String getBucket() {
return bucket;
}
@Override
public Builder filter(DownloadFilter filter) {
this.filter = filter;
return this;
}
@Override
public Builder downloadFileRequestTransformer(Consumer<DownloadFileRequest.Builder> downloadFileRequestTransformer) {
this.downloadFileRequestTransformer = downloadFileRequestTransformer;
return this;
}
@Override
public Builder listObjectsV2RequestTransformer(Consumer<ListObjectsV2Request.Builder> listObjectsRequestTransformer) {
this.listObjectsRequestTransformer = listObjectsRequestTransformer;
return this;
}
public void setFilter(DownloadFilter filter) {
filter(filter);
}
public DownloadFilter getFilter() {
return filter;
}
@Override
public DownloadDirectoryRequest build() {
return new DownloadDirectoryRequest(this);
}
}
}
| 4,085 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/CompletedObjectTransfer.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.transfer.s3.model;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.SdkResponse;
/**
* A completed single object transfer.
*
* @see CompletedFileUpload
* @see CompletedFileDownload
* @see CompletedUpload
* @see CompletedDownload
*/
@SdkPublicApi
public interface CompletedObjectTransfer extends CompletedTransfer {
/**
* Return the {@link SdkResponse} associated with this transfer
*/
default SdkResponse response() {
throw new UnsupportedOperationException();
}
}
| 4,086 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/TransferObjectRequest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.transfer.s3.model;
import java.util.List;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.transfer.s3.progress.TransferListener;
/**
* Interface for all single object transfer requests.
*
* @see UploadFileRequest
* @see DownloadFileRequest
* @see UploadRequest
* @see DownloadRequest
*/
@SdkPublicApi
public interface TransferObjectRequest extends TransferRequest {
List<TransferListener> transferListeners();
}
| 4,087 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/UploadDirectoryRequest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.transfer.s3.model;
import java.nio.file.Path;
import java.util.Objects;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.function.Consumer;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.transfer.s3.config.TransferRequestOverrideConfiguration;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* Request object to upload a local directory to S3 using the Transfer Manager.
*
* @see S3TransferManager#uploadDirectory(UploadDirectoryRequest)
*/
@SdkPublicApi
public final class UploadDirectoryRequest
implements TransferDirectoryRequest, ToCopyableBuilder<UploadDirectoryRequest.Builder, UploadDirectoryRequest> {
private final Path source;
private final String bucket;
private final String s3Prefix;
private final String s3Delimiter;
private final Boolean followSymbolicLinks;
private final Integer maxDepth;
private final Consumer<UploadFileRequest.Builder> uploadFileRequestTransformer;
public UploadDirectoryRequest(DefaultBuilder builder) {
this.source = Validate.paramNotNull(builder.source, "source");
this.bucket = Validate.paramNotNull(builder.bucket, "bucket");
this.s3Prefix = builder.s3Prefix;
this.s3Delimiter = builder.s3Delimiter;
this.followSymbolicLinks = builder.followSymbolicLinks;
this.maxDepth = builder.maxDepth;
this.uploadFileRequestTransformer = builder.uploadFileRequestTransformer;
}
/**
* The source directory to upload
*
* @return the source directory
* @see Builder#source(Path)
*/
public Path source() {
return source;
}
/**
* The name of the bucket to upload objects to.
*
* @return bucket name
* @see Builder#bucket(String)
*/
public String bucket() {
return bucket;
}
/**
* @return the optional key prefix
* @see Builder#s3Prefix(String)
*/
public Optional<String> s3Prefix() {
return Optional.ofNullable(s3Prefix);
}
/**
* @return the optional delimiter
* @see Builder#s3Delimiter(String)
*/
public Optional<String> s3Delimiter() {
return Optional.ofNullable(s3Delimiter);
}
/**
* @return whether to follow symbolic links
* @see Builder#followSymbolicLinks(Boolean)
*/
public Optional<Boolean> followSymbolicLinks() {
return Optional.ofNullable(followSymbolicLinks);
}
/**
* @return the maximum number of directory levels to traverse
* @see Builder#maxDepth(Integer)
*/
public OptionalInt maxDepth() {
return maxDepth == null ? OptionalInt.empty() : OptionalInt.of(maxDepth);
}
/**
* @return the upload request transformer if not null, otherwise no-op
* @see Builder#uploadFileRequestTransformer(Consumer)
*/
public Consumer<UploadFileRequest.Builder> uploadFileRequestTransformer() {
return uploadFileRequestTransformer == null ? ignore -> { } : uploadFileRequestTransformer;
}
public static Builder builder() {
return new DefaultBuilder();
}
public static Class<? extends Builder> serializableBuilderClass() {
return DefaultBuilder.class;
}
@Override
public Builder toBuilder() {
return new DefaultBuilder(this);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
UploadDirectoryRequest that = (UploadDirectoryRequest) o;
if (!Objects.equals(source, that.source)) {
return false;
}
if (!Objects.equals(bucket, that.bucket)) {
return false;
}
if (!Objects.equals(s3Prefix, that.s3Prefix)) {
return false;
}
if (!Objects.equals(followSymbolicLinks, that.followSymbolicLinks)) {
return false;
}
if (!Objects.equals(maxDepth, that.maxDepth)) {
return false;
}
if (!Objects.equals(uploadFileRequestTransformer, that.uploadFileRequestTransformer)) {
return false;
}
return Objects.equals(s3Delimiter, that.s3Delimiter);
}
@Override
public int hashCode() {
int result = source != null ? source.hashCode() : 0;
result = 31 * result + (bucket != null ? bucket.hashCode() : 0);
result = 31 * result + (s3Prefix != null ? s3Prefix.hashCode() : 0);
result = 31 * result + (s3Delimiter != null ? s3Delimiter.hashCode() : 0);
result = 31 * result + (followSymbolicLinks != null ? followSymbolicLinks.hashCode() : 0);
result = 31 * result + (maxDepth != null ? maxDepth.hashCode() : 0);
result = 31 * result + (uploadFileRequestTransformer != null ? uploadFileRequestTransformer.hashCode() : 0);
return result;
}
@Override
public String toString() {
return ToString.builder("UploadDirectoryRequest")
.add("source", source)
.add("bucket", bucket)
.add("s3Prefix", s3Prefix)
.add("s3Delimiter", s3Delimiter)
.add("followSymbolicLinks", followSymbolicLinks)
.add("maxDepth", maxDepth)
.add("uploadFileRequestTransformer", uploadFileRequestTransformer)
.build();
}
public interface Builder extends CopyableBuilder<Builder, UploadDirectoryRequest> {
/**
* Specifies the source directory to upload. The source directory must exist.
* Fle wildcards are not supported and treated literally. Hidden files/directories are visited.
*
* <p>
* Note that the current user must have read access to all directories and files,
* otherwise {@link SecurityException} will be thrown.
*
* @param source the source directory
* @return This builder for method chaining.
*/
Builder source(Path source);
/**
* The name of the bucket to upload objects to.
*
* @param bucket the bucket name
* @return This builder for method chaining.
*/
Builder bucket(String bucket);
/**
* Specifies the key prefix to use for the objects. If not provided, files will be uploaded to the root of the bucket
* <p>
* See <a
* href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-prefixes.html">Organizing objects using
* prefixes</a>
*
* <p>
* Note: if the provided prefix ends with the same string as delimiter, it will get "normalized" when generating the key
* name. For example, assuming the prefix provided is "foo/" and the delimiter is "/" and the source directory has the
* following structure:
*
* <pre>
* |- test
* |- obj1.txt
* |- obj2.txt
* </pre>
*
* the object keys will be "foo/obj1.txt" and "foo/obj2.txt" as apposed to "foo//obj1.txt" and "foo//obj2.txt"
*
* @param s3Prefix the key prefix
* @return This builder for method chaining.
* @see #s3Delimiter(String)
*/
Builder s3Prefix(String s3Prefix);
/**
* Specifies the delimiter. A delimiter causes a list operation to roll up all the keys that share a common prefix into a
* single summary list result. If not provided, {@code "/"} will be used.
*
* See <a
* href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-prefixes.html">Organizing objects using
* prefixes</a>
*
* <p>
* Note: if the provided prefix ends with the same string as delimiter, it will get "normalized" when generating the key
* name. For example, assuming the prefix provided is "foo/" and the delimiter is "/" and the source directory has the
* following structure:
*
* <pre>
* |- test
* |- obj1.txt
* |- obj2.txt
* </pre>
*
* the object keys will be "foo/obj1.txt" and "foo/obj2.txt" as apposed to "foo//obj1.txt" and "foo//obj2.txt"
*
* @param s3Delimiter the delimiter
* @return This builder for method chaining.
* @see #s3Prefix(String)
*/
Builder s3Delimiter(String s3Delimiter);
/**
* Specifies whether to follow symbolic links when traversing the file tree in
* {@link S3TransferManager#downloadDirectory} operation
* <p>
* Default to false
*
* @param followSymbolicLinks whether to follow symbolic links
* @return This builder for method chaining.
*/
Builder followSymbolicLinks(Boolean followSymbolicLinks);
/**
* Specifies the maximum number of levels of directories to visit. Must be positive.
* 1 means only the files directly within the provided source directory are visited.
*
* <p>
* Default to {@code Integer.MAX_VALUE}
*
* @param maxDepth the maximum number of directory levels to visit
* @return This builder for method chaining.
*/
Builder maxDepth(Integer maxDepth);
/**
* Specifies a function used to transform the {@link UploadFileRequest}s generated by this {@link UploadDirectoryRequest}.
* The provided function is called once for each file that is uploaded, allowing you to modify the paths resolved by
* TransferManager on a per-file basis, modify the created {@link PutObjectRequest} before it is passed to S3, or
* configure a {@link TransferRequestOverrideConfiguration}.
*
* <p>The factory receives the {@link UploadFileRequest}s created by Transfer Manager for each file in the directory
* being uploaded, and returns a (potentially modified) {@code UploadFileRequest}.
*
* <p>
* <b>Usage Example:</b>
* <pre>
* {@code
* // Add a LoggingTransferListener to every transfer within the upload directory request
*
* UploadDirectoryOverrideConfiguration directoryUploadConfiguration =
* UploadDirectoryOverrideConfiguration.builder()
* .uploadFileRequestTransformer(request -> request.addTransferListenerf(LoggingTransferListener.create())
* .build();
*
* UploadDirectoryRequest request =
* UploadDirectoryRequest.builder()
* .source(Paths.get("."))
* .bucket("bucket")
* .prefix("prefix")
* .overrideConfiguration(directoryUploadConfiguration)
* .build()
*
* UploadDirectoryTransfer uploadDirectory = transferManager.uploadDirectory(request);
*
* // Wait for the transfer to complete
* CompletedUploadDirectory completedUploadDirectory = uploadDirectory.completionFuture().join();
*
* // Print out the failed uploads
* completedUploadDirectory.failedUploads().forEach(System.out::println);
* }
* </pre>
*
* @param uploadFileRequestTransformer A transformer to use for modifying the file-level upload requests before execution
* @return This builder for method chaining
*/
Builder uploadFileRequestTransformer(Consumer<UploadFileRequest.Builder> uploadFileRequestTransformer);
@Override
UploadDirectoryRequest build();
}
private static final class DefaultBuilder implements Builder {
private Path source;
private String bucket;
private String s3Prefix;
private String s3Delimiter;
private Boolean followSymbolicLinks;
private Integer maxDepth;
private Consumer<UploadFileRequest.Builder> uploadFileRequestTransformer;
private DefaultBuilder() {
}
private DefaultBuilder(UploadDirectoryRequest request) {
this.source = request.source;
this.bucket = request.bucket;
this.s3Prefix = request.s3Prefix;
this.s3Delimiter = request.s3Delimiter;
this.followSymbolicLinks = request.followSymbolicLinks;
this.maxDepth = request.maxDepth;
this.uploadFileRequestTransformer = request.uploadFileRequestTransformer;
}
@Override
public Builder source(Path source) {
this.source = source;
return this;
}
public void setSource(Path source) {
source(source);
}
public Path getSource() {
return source;
}
@Override
public Builder bucket(String bucket) {
this.bucket = bucket;
return this;
}
public void setBucket(String bucket) {
bucket(bucket);
}
public String getBucket() {
return bucket;
}
@Override
public Builder s3Prefix(String s3Prefix) {
this.s3Prefix = s3Prefix;
return this;
}
public void setS3Prefix(String s3Prefix) {
s3Prefix(s3Prefix);
}
public String getS3Prefix() {
return s3Prefix;
}
@Override
public Builder s3Delimiter(String s3Delimiter) {
this.s3Delimiter = s3Delimiter;
return this;
}
public void setS3Delimiter(String s3Delimiter) {
s3Delimiter(s3Delimiter);
}
public String getS3Delimiter() {
return s3Delimiter;
}
@Override
public Builder followSymbolicLinks(Boolean followSymbolicLinks) {
this.followSymbolicLinks = followSymbolicLinks;
return this;
}
public void setFollowSymbolicLinks(Boolean followSymbolicLinks) {
followSymbolicLinks(followSymbolicLinks);
}
public Boolean getFollowSymbolicLinks() {
return followSymbolicLinks;
}
@Override
public Builder maxDepth(Integer maxDepth) {
this.maxDepth = maxDepth;
return this;
}
public void setMaxDepth(Integer maxDepth) {
maxDepth(maxDepth);
}
public Integer getMaxDepth() {
return maxDepth;
}
@Override
public Builder uploadFileRequestTransformer(Consumer<UploadFileRequest.Builder> uploadFileRequestTransformer) {
this.uploadFileRequestTransformer = uploadFileRequestTransformer;
return this;
}
public Consumer<UploadFileRequest.Builder> getUploadFileRequestTransformer() {
return uploadFileRequestTransformer;
}
public void setUploadFileRequestTransformer(Consumer<UploadFileRequest.Builder> uploadFileRequestTransformer) {
this.uploadFileRequestTransformer = uploadFileRequestTransformer;
}
@Override
public UploadDirectoryRequest build() {
return new UploadDirectoryRequest(this);
}
}
}
| 4,088 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/UploadFileRequest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.transfer.s3.model;
import static software.amazon.awssdk.utils.Validate.paramNotNull;
import java.io.File;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;
import software.amazon.awssdk.annotations.NotThreadSafe;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.transfer.s3.progress.TransferListener;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* Represents the request to upload a local file to an object in S3. For non-file-based uploads, you may use {@link UploadRequest}
* instead.
*
* @see S3TransferManager#uploadFile(UploadFileRequest)
*/
@SdkPublicApi
public final class UploadFileRequest
implements TransferObjectRequest,
ToCopyableBuilder<UploadFileRequest.Builder, UploadFileRequest> {
private final PutObjectRequest putObjectRequest;
private final Path source;
private final List<TransferListener> listeners;
private UploadFileRequest(DefaultBuilder builder) {
this.putObjectRequest = paramNotNull(builder.putObjectRequest, "putObjectRequest");
this.source = paramNotNull(builder.source, "source");
this.listeners = builder.listeners;
}
/**
* @return The {@link PutObjectRequest} request that should be used for the upload
*/
public PutObjectRequest putObjectRequest() {
return putObjectRequest;
}
/**
* The {@link Path} containing data to send to the service.
*
* @return the request body
*/
public Path source() {
return source;
}
/**
* @return the List of transferListeners.
*/
@Override
public List<TransferListener> transferListeners() {
return listeners;
}
/**
* Creates a builder that can be used to create a {@link UploadFileRequest}.
*
* @see S3TransferManager#uploadFile(UploadFileRequest)
*/
public static Builder builder() {
return new DefaultBuilder();
}
public static Class<? extends Builder> serializableBuilderClass() {
return DefaultBuilder.class;
}
@Override
public Builder toBuilder() {
return new DefaultBuilder(this);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
UploadFileRequest that = (UploadFileRequest) o;
if (!Objects.equals(putObjectRequest, that.putObjectRequest)) {
return false;
}
if (!Objects.equals(source, that.source)) {
return false;
}
return Objects.equals(listeners, that.listeners);
}
@Override
public int hashCode() {
int result = putObjectRequest != null ? putObjectRequest.hashCode() : 0;
result = 31 * result + (source != null ? source.hashCode() : 0);
result = 31 * result + (listeners != null ? listeners.hashCode() : 0);
return result;
}
@Override
public String toString() {
return ToString.builder("UploadFileRequest")
.add("putObjectRequest", putObjectRequest)
.add("source", source)
.add("configuration", listeners)
.build();
}
/**
* A builder for a {@link UploadFileRequest}, created with {@link #builder()}
*/
@SdkPublicApi
@NotThreadSafe
public interface Builder extends CopyableBuilder<Builder, UploadFileRequest> {
/**
* The {@link Path} to file containing data to send to the service. File will be read entirely and may be read
* multiple times in the event of a retry. If the file does not exist or the current user does not have
* access to read it then an exception will be thrown.
*
* @param source the source path
* @return Returns a reference to this object so that method calls can be chained together.
*/
Builder source(Path source);
/**
* The file containing data to send to the service. File will be read entirely and may be read
* multiple times in the event of a retry. If the file does not exist or the current user does not have
* access to read it then an exception will be thrown.
*
* @param source the source path
* @return Returns a reference to this object so that method calls can be chained together.
*/
default Builder source(File source) {
Validate.paramNotNull(source, "source");
return this.source(source.toPath());
}
/**
* Configure the {@link PutObjectRequest} that should be used for the upload
*
* @param putObjectRequest the putObjectRequest
* @return Returns a reference to this object so that method calls can be chained together.
* @see #putObjectRequest(Consumer)
*/
Builder putObjectRequest(PutObjectRequest putObjectRequest);
/**
* Configure the {@link PutObjectRequest} that should be used for the upload
*
* <p>
* This is a convenience method that creates an instance of the {@link PutObjectRequest} builder avoiding the
* need to create one manually via {@link PutObjectRequest#builder()}.
*
* @param putObjectRequestBuilder the putObjectRequest consumer builder
* @return Returns a reference to this object so that method calls can be chained together.
* @see #putObjectRequest(PutObjectRequest)
*/
default Builder putObjectRequest(Consumer<PutObjectRequest.Builder> putObjectRequestBuilder) {
return putObjectRequest(PutObjectRequest.builder()
.applyMutation(putObjectRequestBuilder)
.build());
}
/**
* The {@link TransferListener}s that will be notified as part of this request. This method overrides and replaces any
* transferListeners that have already been set. Add an optional request override configuration.
*
* @param transferListeners the collection of transferListeners
* @return Returns a reference to this object so that method calls can be chained together.
* @return This builder for method chaining.
* @see TransferListener
*/
Builder transferListeners(Collection<TransferListener> transferListeners);
/**
* Add a {@link TransferListener} that will be notified as part of this request.
*
* @param transferListener the transferListener to add
* @return Returns a reference to this object so that method calls can be chained together.
* @see TransferListener
*/
Builder addTransferListener(TransferListener transferListener);
}
private static class DefaultBuilder implements Builder {
private PutObjectRequest putObjectRequest;
private Path source;
private List<TransferListener> listeners;
private DefaultBuilder() {
}
private DefaultBuilder(UploadFileRequest uploadFileRequest) {
this.source = uploadFileRequest.source;
this.putObjectRequest = uploadFileRequest.putObjectRequest;
this.listeners = uploadFileRequest.listeners;
}
@Override
public Builder source(Path source) {
this.source = Validate.paramNotNull(source, "source");
return this;
}
public Path getSource() {
return source;
}
public void setSource(Path source) {
source(source);
}
@Override
public Builder putObjectRequest(PutObjectRequest putObjectRequest) {
this.putObjectRequest = putObjectRequest;
return this;
}
public PutObjectRequest getPutObjectRequest() {
return putObjectRequest;
}
public void setPutObjectRequest(PutObjectRequest putObjectRequest) {
putObjectRequest(putObjectRequest);
}
@Override
public Builder transferListeners(Collection<TransferListener> transferListeners) {
this.listeners = transferListeners != null ? new ArrayList<>(transferListeners) : null;
return this;
}
@Override
public Builder addTransferListener(TransferListener transferListener) {
if (listeners == null) {
listeners = new ArrayList<>();
}
listeners.add(transferListener);
return this;
}
public List<TransferListener> getListeners() {
return listeners;
}
public void setListeners(Collection<TransferListener> listeners) {
transferListeners(listeners);
}
@Override
public UploadFileRequest build() {
return new UploadFileRequest(this);
}
}
}
| 4,089 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/Download.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.transfer.s3.model;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.annotations.SdkPublicApi;
/**
* A download transfer of a single object from S3.
*/
@SdkPublicApi
public interface Download<ResultT> extends ObjectTransfer {
@Override
CompletableFuture<CompletedDownload<ResultT>> completionFuture();
}
| 4,090 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/Transfer.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.transfer.s3.model;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.annotations.SdkPublicApi;
/**
* Represents the upload or download of one or more objects to or from S3.
*
* @see ObjectTransfer
* @see DirectoryTransfer
*/
@SdkPublicApi
public interface Transfer {
/**
* @return The future that will be completed when this transfer is complete.
*/
CompletableFuture<? extends CompletedTransfer> completionFuture();
}
| 4,091 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/CompletedUpload.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.transfer.s3.model;
import java.util.Objects;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.model.PutObjectResponse;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
/**
* Represents a completed upload transfer to Amazon S3. It can be used to track
* the underlying {@link PutObjectResponse}
*
* @see S3TransferManager#upload(UploadRequest)
*/
@SdkPublicApi
public final class CompletedUpload implements CompletedObjectTransfer {
private final PutObjectResponse response;
private CompletedUpload(DefaultBuilder builder) {
this.response = Validate.paramNotNull(builder.response, "response");
}
@Override
public PutObjectResponse response() {
return response;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CompletedUpload that = (CompletedUpload) o;
return Objects.equals(response, that.response);
}
@Override
public int hashCode() {
return response.hashCode();
}
@Override
public String toString() {
return ToString.builder("CompletedUpload")
.add("response", response)
.build();
}
public static Class<? extends Builder> serializableBuilderClass() {
return DefaultBuilder.class;
}
/**
* Creates a default builder for {@link CompletedUpload}.
*/
public static Builder builder() {
return new DefaultBuilder();
}
public interface Builder {
/**
* Specifies the {@link PutObjectResponse} from {@link S3AsyncClient#putObject}
*
* @param response the response
* @return This builder for method chaining.
*/
Builder response(PutObjectResponse response);
/**
* Builds a {@link CompletedUpload} based on the properties supplied to this builder
* @return An initialized {@link CompletedUpload}
*/
CompletedUpload build();
}
private static class DefaultBuilder implements Builder {
private PutObjectResponse response;
private DefaultBuilder() {
}
@Override
public Builder response(PutObjectResponse response) {
this.response = response;
return this;
}
@Override
public CompletedUpload build() {
return new CompletedUpload(this);
}
}
}
| 4,092 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/Copy.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.transfer.s3.model;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.annotations.SdkPublicApi;
/**
* A copy transfer of an object that is already stored in S3.
*/
@SdkPublicApi
public interface Copy extends ObjectTransfer {
@Override
CompletableFuture<CompletedCopy> completionFuture();
}
| 4,093 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/CompletedFileDownload.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.transfer.s3.model;
import java.util.Objects;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
/**
* Represents a completed download transfer from Amazon S3. It can be used to track
* the underlying {@link GetObjectResponse}
*
* @see S3TransferManager#downloadFile(DownloadFileRequest)
*/
@SdkPublicApi
public final class CompletedFileDownload implements CompletedObjectTransfer {
private final GetObjectResponse response;
private CompletedFileDownload(DefaultBuilder builder) {
this.response = Validate.paramNotNull(builder.response, "response");
}
@Override
public GetObjectResponse response() {
return response;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CompletedFileDownload that = (CompletedFileDownload) o;
return Objects.equals(response, that.response);
}
@Override
public int hashCode() {
return response != null ? response.hashCode() : 0;
}
@Override
public String toString() {
return ToString.builder("CompletedFileDownload")
.add("response", response)
.build();
}
public static Builder builder() {
return new DefaultBuilder();
}
public interface Builder {
/**
* Specifies the {@link GetObjectResponse} from {@link S3AsyncClient#getObject}
*
* @param response the response
* @return This builder for method chaining.
*/
Builder response(GetObjectResponse response);
/**
* Builds a {@link CompletedFileUpload} based on the properties supplied to this builder
* @return An initialized {@link CompletedFileDownload}
*/
CompletedFileDownload build();
}
private static final class DefaultBuilder implements Builder {
private GetObjectResponse response;
private DefaultBuilder() {
}
@Override
public Builder response(GetObjectResponse response) {
this.response = response;
return this;
}
public void setResponse(GetObjectResponse response) {
response(response);
}
public GetObjectResponse getResponse() {
return response;
}
@Override
public CompletedFileDownload build() {
return new CompletedFileDownload(this);
}
}
}
| 4,094 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/DirectoryUpload.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.transfer.s3.model;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.annotations.SdkPublicApi;
/**
* An upload transfer of a single object to S3.
*/
@SdkPublicApi
public interface DirectoryUpload extends DirectoryTransfer {
@Override
CompletableFuture<CompletedDirectoryUpload> completionFuture();
}
| 4,095 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/FailedFileUpload.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.transfer.s3.model;
import java.util.Objects;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* Represents a failed single file upload from {@link S3TransferManager#uploadDirectory}. It
* has a detailed description of the result.
*/
@SdkPublicApi
public final class FailedFileUpload
implements FailedObjectTransfer,
ToCopyableBuilder<FailedFileUpload.Builder, FailedFileUpload> {
private final UploadFileRequest request;
private final Throwable exception;
private FailedFileUpload(DefaultBuilder builder) {
this.exception = Validate.paramNotNull(builder.exception, "exception");
this.request = Validate.paramNotNull(builder.request, "request");
}
@Override
public Throwable exception() {
return exception;
}
@Override
public UploadFileRequest request() {
return request;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
FailedFileUpload that = (FailedFileUpload) o;
if (!Objects.equals(request, that.request)) {
return false;
}
return Objects.equals(exception, that.exception);
}
@Override
public int hashCode() {
int result = request != null ? request.hashCode() : 0;
result = 31 * result + (exception != null ? exception.hashCode() : 0);
return result;
}
@Override
public String toString() {
return ToString.builder("FailedFileUpload")
.add("request", request)
.add("exception", exception)
.build();
}
public static Builder builder() {
return new DefaultBuilder();
}
public static Class<? extends Builder> serializableBuilderClass() {
return DefaultBuilder.class;
}
@Override
public Builder toBuilder() {
return new DefaultBuilder(this);
}
public interface Builder extends CopyableBuilder<Builder, FailedFileUpload> {
Builder exception(Throwable exception);
Builder request(UploadFileRequest request);
}
private static final class DefaultBuilder implements Builder {
private UploadFileRequest request;
private Throwable exception;
private DefaultBuilder(FailedFileUpload failedFileUpload) {
this.request = failedFileUpload.request;
this.exception = failedFileUpload.exception;
}
private DefaultBuilder() {
}
@Override
public Builder exception(Throwable exception) {
this.exception = exception;
return this;
}
public void setException(Throwable exception) {
exception(exception);
}
public Throwable getException() {
return exception;
}
@Override
public Builder request(UploadFileRequest request) {
this.request = request;
return this;
}
public void setRequest(UploadFileRequest request) {
request(request);
}
public UploadFileRequest getRequest() {
return request;
}
@Override
public FailedFileUpload build() {
return new FailedFileUpload(this);
}
}
}
| 4,096 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/ResumableFileUpload.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.transfer.s3.model;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Instant;
import java.util.Objects;
import java.util.Optional;
import java.util.OptionalLong;
import java.util.function.Consumer;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.transfer.s3.config.TransferRequestOverrideConfiguration;
import software.amazon.awssdk.transfer.s3.internal.serialization.ResumableFileUploadSerializer;
import software.amazon.awssdk.utils.IoUtils;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* POJO class that holds the state and can be used to resume a paused upload file operation.
* <p>
* <b>Serialization: </b>When serializing this token, the following structures will not be preserved/persisted:
* <ul>
* <li>{@link TransferRequestOverrideConfiguration}</li>
* <li>{@link AwsRequestOverrideConfiguration} (from {@link PutObjectRequest})</li>
* </ul>
*
* @see S3TransferManager#uploadFile(UploadFileRequest)
* @see S3TransferManager#resumeUploadFile(ResumableFileUpload)
*/
@SdkPublicApi
public final class ResumableFileUpload implements ResumableTransfer,
ToCopyableBuilder<ResumableFileUpload.Builder, ResumableFileUpload> {
private final UploadFileRequest uploadFileRequest;
private final Instant fileLastModified;
private final String multipartUploadId;
private final Long partSizeInBytes;
private final Long totalParts;
private final long fileLength;
private final Long transferredParts;
private ResumableFileUpload(DefaultBuilder builder) {
this.uploadFileRequest = Validate.paramNotNull(builder.uploadFileRequest, "uploadFileRequest");
this.fileLastModified = Validate.paramNotNull(builder.fileLastModified, "fileLastModified");
this.fileLength = Validate.paramNotNull(builder.fileLength, "fileLength");
this.multipartUploadId = builder.multipartUploadId;
this.totalParts = builder.totalParts;
this.partSizeInBytes = builder.partSizeInBytes;
this.transferredParts = builder.transferredParts;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ResumableFileUpload that = (ResumableFileUpload) o;
if (fileLength != that.fileLength) {
return false;
}
if (!uploadFileRequest.equals(that.uploadFileRequest)) {
return false;
}
if (!fileLastModified.equals(that.fileLastModified)) {
return false;
}
if (!Objects.equals(multipartUploadId, that.multipartUploadId)) {
return false;
}
if (!Objects.equals(partSizeInBytes, that.partSizeInBytes)) {
return false;
}
if (!Objects.equals(transferredParts, that.transferredParts)) {
return false;
}
return Objects.equals(totalParts, that.totalParts);
}
@Override
public int hashCode() {
int result = uploadFileRequest.hashCode();
result = 31 * result + fileLastModified.hashCode();
result = 31 * result + (multipartUploadId != null ? multipartUploadId.hashCode() : 0);
result = 31 * result + (partSizeInBytes != null ? partSizeInBytes.hashCode() : 0);
result = 31 * result + (totalParts != null ? totalParts.hashCode() : 0);
result = 31 * result + (transferredParts != null ? transferredParts.hashCode() : 0);
result = 31 * result + (int) (fileLength ^ (fileLength >>> 32));
return result;
}
public static Builder builder() {
return new DefaultBuilder();
}
/**
* @return the {@link UploadFileRequest} to resume
*/
public UploadFileRequest uploadFileRequest() {
return uploadFileRequest;
}
/**
* Last modified time of the file since last pause
*/
public Instant fileLastModified() {
return fileLastModified;
}
/**
* File length since last pause
*/
public long fileLength() {
return fileLength;
}
/**
* Return the part size in bytes or {@link OptionalLong#empty()} if unknown
*/
public OptionalLong partSizeInBytes() {
return partSizeInBytes == null ? OptionalLong.empty() : OptionalLong.of(partSizeInBytes);
}
/**
* Return the total number of parts associated with this transfer or {@link OptionalLong#empty()} if unknown
*/
public OptionalLong totalParts() {
return totalParts == null ? OptionalLong.empty() : OptionalLong.of(totalParts);
}
/**
* The multipart upload ID, or {@link Optional#empty()} if unknown
*
* @return the optional total size of the transfer.
*/
public Optional<String> multipartUploadId() {
return Optional.ofNullable(multipartUploadId);
}
/**
* Return the total number of parts completed with this transfer or {@link OptionalLong#empty()} if unknown
*/
public OptionalLong transferredParts() {
return transferredParts == null ? OptionalLong.empty() : OptionalLong.of(transferredParts);
}
@Override
public void serializeToFile(Path path) {
try {
Files.write(path, ResumableFileUploadSerializer.toJson(this));
} catch (IOException e) {
throw SdkClientException.create("Failed to write to " + path, e);
}
}
@Override
public void serializeToOutputStream(OutputStream outputStream) {
byte[] bytes = ResumableFileUploadSerializer.toJson(this);
try {
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
IoUtils.copy(byteArrayInputStream, outputStream);
} catch (IOException e) {
throw SdkClientException.create("Failed to write this download object to the given OutputStream", e);
}
}
@Override
public String serializeToString() {
return new String(ResumableFileUploadSerializer.toJson(this), StandardCharsets.UTF_8);
}
@Override
public SdkBytes serializeToBytes() {
return SdkBytes.fromByteArrayUnsafe(ResumableFileUploadSerializer.toJson(this));
}
@Override
public InputStream serializeToInputStream() {
return new ByteArrayInputStream(ResumableFileUploadSerializer.toJson(this));
}
/**
* Deserializes data at the given path into a {@link ResumableFileUpload}.
*
* @param path The {@link Path} to the file with serialized data
* @return the deserialized {@link ResumableFileUpload}
*/
public static ResumableFileUpload fromFile(Path path) {
try (InputStream stream = Files.newInputStream(path)) {
return ResumableFileUploadSerializer.fromJson(stream);
} catch (IOException e) {
throw SdkClientException.create("Failed to create a ResumableFileUpload from " + path, e);
}
}
/**
* Deserializes bytes with JSON data into a {@link ResumableFileUpload}.
*
* @param bytes the serialized data
* @return the deserialized {@link ResumableFileUpload}
*/
public static ResumableFileUpload fromBytes(SdkBytes bytes) {
return ResumableFileUploadSerializer.fromJson(bytes.asByteArrayUnsafe());
}
/**
* Deserializes a string with JSON data into a {@link ResumableFileUpload}.
*
* @param contents the serialized data
* @return the deserialized {@link ResumableFileUpload}
*/
public static ResumableFileUpload fromString(String contents) {
return ResumableFileUploadSerializer.fromJson(contents);
}
@Override
public String toString() {
return ToString.builder("ResumableFileUpload")
.add("fileLastModified", fileLastModified)
.add("multipartUploadId", multipartUploadId)
.add("uploadFileRequest", uploadFileRequest)
.add("fileLength", fileLength)
.add("totalParts", totalParts)
.add("partSizeInBytes", partSizeInBytes)
.add("transferredParts", transferredParts)
.build();
}
@Override
public Builder toBuilder() {
return new DefaultBuilder(this);
}
public interface Builder extends CopyableBuilder<Builder, ResumableFileUpload> {
/**
* Sets the upload file request
*
* @param uploadFileRequest the upload file request
* @return a reference to this object so that method calls can be chained together.
*/
Builder uploadFileRequest(UploadFileRequest uploadFileRequest);
/**
* The {@link UploadFileRequest} request
*
* <p>
* This is a convenience method that creates an instance of the {@link UploadFileRequest} builder avoiding the
* need to create one manually via {@link UploadFileRequest#builder()}.
*
* @param uploadFileRequestBuilder the upload file request builder
* @return a reference to this object so that method calls can be chained together.
* @see #uploadFileRequest(UploadFileRequest)
*/
default ResumableFileUpload.Builder uploadFileRequest(Consumer<UploadFileRequest.Builder>
uploadFileRequestBuilder) {
UploadFileRequest request = UploadFileRequest.builder()
.applyMutation(uploadFileRequestBuilder)
.build();
uploadFileRequest(request);
return this;
}
/**
* Sets multipart ID associated with this transfer
*
* @param multipartUploadId the multipart ID
* @return a reference to this object so that method calls can be chained together.
*/
Builder multipartUploadId(String multipartUploadId);
/**
* Sets the last modified time of the object
*
* @param fileLastModified the last modified time of the file
* @return a reference to this object so that method calls can be chained together.
*/
Builder fileLastModified(Instant fileLastModified);
/**
* Sets the file length
*
* @param fileLength the last modified time of the object
* @return a reference to this object so that method calls can be chained together.
*/
Builder fileLength(Long fileLength);
/**
* Sets the total number of parts
*
* @param totalParts the total number of parts
* @return a reference to this object so that method calls can be chained together.
*/
Builder totalParts(Long totalParts);
/**
* Set the total number of parts transferred
*
* @param transferredParts the number of parts completed
* @return a reference to this object so that method calls can be chained together.
*/
Builder transferredParts(Long transferredParts);
/**
* The part size associated with this transfer
* @param partSizeInBytes the part size in bytes
* @return a reference to this object so that method calls can be chained together.
*/
Builder partSizeInBytes(Long partSizeInBytes);
}
private static final class DefaultBuilder implements Builder {
private String multipartUploadId;
private UploadFileRequest uploadFileRequest;
private Long partSizeInBytes;
private Long totalParts;
private Instant fileLastModified;
private Long fileLength;
private Long transferredParts;
private DefaultBuilder() {
}
private DefaultBuilder(ResumableFileUpload persistableFileUpload) {
this.multipartUploadId = persistableFileUpload.multipartUploadId;
this.uploadFileRequest = persistableFileUpload.uploadFileRequest;
this.partSizeInBytes = persistableFileUpload.partSizeInBytes;
this.fileLastModified = persistableFileUpload.fileLastModified;
this.totalParts = persistableFileUpload.totalParts;
this.fileLength = persistableFileUpload.fileLength;
this.transferredParts = persistableFileUpload.transferredParts;
}
@Override
public Builder uploadFileRequest(UploadFileRequest uploadFileRequest) {
this.uploadFileRequest = uploadFileRequest;
return this;
}
@Override
public Builder multipartUploadId(String mutipartUploadId) {
this.multipartUploadId = mutipartUploadId;
return this;
}
@Override
public Builder fileLastModified(Instant fileLastModified) {
this.fileLastModified = fileLastModified;
return this;
}
@Override
public Builder fileLength(Long fileLength) {
this.fileLength = fileLength;
return this;
}
@Override
public Builder totalParts(Long totalParts) {
this.totalParts = totalParts;
return this;
}
@Override
public Builder transferredParts(Long transferredParts) {
this.transferredParts = transferredParts;
return this;
}
@Override
public Builder partSizeInBytes(Long partSizeInBytes) {
this.partSizeInBytes = partSizeInBytes;
return this;
}
@Override
public ResumableFileUpload build() {
return new ResumableFileUpload(this);
}
}
}
| 4,097 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/ResumableTransfer.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.transfer.s3.model;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Path;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.SdkBytes;
/**
* Contains the information of a pausible upload or download; such
* information can be used to resume the upload or download later on
*
* @see FileDownload#pause()
*/
@SdkPublicApi
public interface ResumableTransfer {
/**
* Persists this download object to a file in Base64-encoded JSON format.
*
* @param path The path to the file to which you want to write the serialized download object.
*/
default void serializeToFile(Path path) {
throw new UnsupportedOperationException();
}
/**
* Writes the serialized JSON data representing this object to an output stream.
* Note that the {@link OutputStream} is not closed or flushed after writing.
*
* @param outputStream The output stream to write the serialized object to.
*/
default void serializeToOutputStream(OutputStream outputStream) {
throw new UnsupportedOperationException();
}
/**
* Returns the serialized JSON data representing this object as a string.
*/
default String serializeToString() {
throw new UnsupportedOperationException();
}
/**
* Returns the serialized JSON data representing this object as an {@link SdkBytes} object.
*
* @return the serialized JSON as {@link SdkBytes}
*/
default SdkBytes serializeToBytes() {
throw new UnsupportedOperationException();
}
/**
* Returns the serialized JSON data representing this object as an {@link InputStream}.
*
* @return the serialized JSON input stream
*/
default InputStream serializeToInputStream() {
throw new UnsupportedOperationException();
}
}
| 4,098 |
0 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3 | Create_ds/aws-sdk-java-v2/services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/model/Upload.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.transfer.s3.model;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.annotations.SdkPublicApi;
/**
* An upload transfer of a single object to S3.
*/
@SdkPublicApi
public interface Upload extends ObjectTransfer {
@Override
CompletableFuture<CompletedUpload> completionFuture();
}
| 4,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.