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/s3/src/it/java/software/amazon/awssdk/services/s3
Create_ds/aws-sdk-java-v2/services/s3/src/it/java/software/amazon/awssdk/services/s3/crossregion/S3CrossRegionCrtIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.crossregion; import static software.amazon.awssdk.testutils.service.S3BucketUtils.temporaryBucketName; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.http.apache.ApacheHttpClient; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3AsyncClient; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.ListObjectsRequest; import software.amazon.awssdk.services.s3.model.ListObjectsResponse; public class S3CrossRegionCrtIntegrationTest extends S3CrossRegionAsyncIntegrationTestBase { private static final String BUCKET = temporaryBucketName(S3CrossRegionCrtIntegrationTest.class); @BeforeAll static void setUpClass() { s3 = s3ClientBuilder().build(); createBucket(BUCKET); } @AfterAll static void clearClass() { deleteBucketAndAllContents(BUCKET); } @BeforeEach public void initialize() { crossRegionS3Client = S3AsyncClient.crtBuilder() .region(CROSS_REGION) .crossRegionAccessEnabled(true) .build(); } @Override protected String bucketName() { return BUCKET; } }
4,800
0
Create_ds/aws-sdk-java-v2/services/s3/src/it/java/software/amazon/awssdk/services/s3
Create_ds/aws-sdk-java-v2/services/s3/src/it/java/software/amazon/awssdk/services/s3/crossregion/S3CrossRegionIntegrationTestBase.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.crossregion; import static org.assertj.core.api.Assertions.assertThat; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.ResponseBytes; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3IntegrationTestBase; import software.amazon.awssdk.services.s3.model.ChecksumAlgorithm; import software.amazon.awssdk.services.s3.model.ChecksumMode; import software.amazon.awssdk.services.s3.model.DeleteObjectRequest; import software.amazon.awssdk.services.s3.model.DeleteObjectResponse; import software.amazon.awssdk.services.s3.model.DeleteObjectsRequest; import software.amazon.awssdk.services.s3.model.DeleteObjectsResponse; import software.amazon.awssdk.services.s3.model.GetObjectRequest; import software.amazon.awssdk.services.s3.model.GetObjectResponse; import software.amazon.awssdk.services.s3.model.HeadBucketRequest; import software.amazon.awssdk.services.s3.model.HeadBucketResponse; import software.amazon.awssdk.services.s3.model.ListObjectsV2Request; import software.amazon.awssdk.services.s3.model.PutObjectRequest; import software.amazon.awssdk.services.s3.model.PutObjectResponse; import software.amazon.awssdk.services.s3.model.S3Object; public abstract class S3CrossRegionIntegrationTestBase extends S3IntegrationTestBase { public static final String X_AMZ_BUCKET_REGION = "x-amz-bucket-region"; protected static final Region CROSS_REGION = Region.of("eu-central-1"); private static final String KEY = "key"; @Test void getApi_CrossRegionCall() { s3.putObject(p -> p.bucket(bucketName()).checksumAlgorithm(ChecksumAlgorithm.CRC32).key(KEY), RequestBody.fromString( "TEST_STRING")); GetObjectRequest getObjectRequest = GetObjectRequest.builder().bucket(bucketName()).checksumMode(ChecksumMode.ENABLED).key(KEY).build(); ResponseBytes<GetObjectResponse> response = getAPICall(getObjectRequest); assertThat(new String(response.asByteArray())).isEqualTo("TEST_STRING"); } @Test void putApi_CrossRegionCall() { s3.putObject(p -> p.bucket(bucketName()).checksumAlgorithm(ChecksumAlgorithm.CRC32).key(KEY), RequestBody.fromString( "TEST_STRING")); PutObjectRequest putObjectRequest = PutObjectRequest.builder().bucket(bucketName()).checksumAlgorithm(ChecksumAlgorithm.CRC32).key(KEY).build(); PutObjectResponse response = putAPICall(putObjectRequest, "TEST_STRING"); assertThat(response.checksumCRC32()).isEqualTo("S9ke8w=="); } @Test void deleteApi_CrossRegionCall() { s3.putObject(p -> p.bucket(bucketName()).checksumAlgorithm(ChecksumAlgorithm.CRC32).key(KEY), RequestBody.fromString( "TEST_STRING")); DeleteObjectRequest deleteObjectRequest = DeleteObjectRequest.builder().bucket(bucketName()).key(KEY).build(); DeleteObjectResponse response = deleteObjectAPICall(deleteObjectRequest); assertThat(response).isNotNull(); } @Test void postApi_CrossRegionCall() { s3.putObject(p -> p.bucket(bucketName()).checksumAlgorithm(ChecksumAlgorithm.CRC32).key(KEY), RequestBody.fromString( "TEST_STRING")); s3.putObject(p -> p.bucket(bucketName()).checksumAlgorithm(ChecksumAlgorithm.CRC32).key(KEY + "_1"), RequestBody.fromString("TEST_STRING")); DeleteObjectsRequest deleteObjectsRequest = DeleteObjectsRequest.builder().bucket(bucketName()).delete(d -> d.objects(o -> o.key(KEY), o -> o.key(KEY + "_1"))).build(); DeleteObjectsResponse response = postObjectAPICall(deleteObjectsRequest); assertThat(response).isNotNull(); } @Test void cachedRegionGetsUsed_when_CrossRegionCall() { putAPICall(PutObjectRequest.builder().bucket(bucketName()).checksumAlgorithm(ChecksumAlgorithm.CRC32).key(KEY).build(), "TEST_STRING"); GetObjectRequest getObjectRequest = GetObjectRequest.builder().bucket(bucketName()).checksumMode(ChecksumMode.ENABLED).key(KEY).build(); ResponseBytes<GetObjectResponse> response = getAPICall(getObjectRequest); assertThat(new String(response.asByteArray())).isEqualTo("TEST_STRING"); } @Test void paginatedApi_CrossRegionCall() { s3.deleteObject(p -> p.bucket(bucketName()).key(KEY)); int maxKeys = 3; int totalKeys = maxKeys * 2 ; IntStream.range(0, totalKeys ) .forEach( i -> s3.putObject(p -> p.bucket(bucketName()).checksumAlgorithm(ChecksumAlgorithm.CRC32).key(KEY + "_" + i), RequestBody.fromString("TEST_STRING")) ); ListObjectsV2Request listObjectsV2Request = ListObjectsV2Request.builder().bucket(bucketName()).maxKeys(maxKeys).build(); List<S3Object> s3ObjectList = paginatedAPICall(listObjectsV2Request); assertThat(s3ObjectList.stream().filter( g -> g.key().contains(KEY+ "_")).collect(Collectors.toList())).hasSize(totalKeys); IntStream.range(0, totalKeys ).forEach(i -> s3.deleteObject(p -> p.bucket(bucketName()).key(KEY + "_" + i))); } @Test void headApi_CrossRegionCall() { s3.putObject(p -> p.bucket(bucketName()).checksumAlgorithm(ChecksumAlgorithm.CRC32).key(KEY), RequestBody.fromString( "TEST_STRING")); HeadBucketRequest headBucketRequest = HeadBucketRequest.builder().bucket(bucketName()).build(); HeadBucketResponse response = headAPICall(headBucketRequest); assertThat(response).isNotNull(); } protected abstract List<S3Object> paginatedAPICall(ListObjectsV2Request listObjectsV2Request); protected abstract DeleteObjectsResponse postObjectAPICall(DeleteObjectsRequest deleteObjectsRequest); protected abstract HeadBucketResponse headAPICall(HeadBucketRequest headBucketRequest); protected abstract DeleteObjectResponse deleteObjectAPICall(DeleteObjectRequest deleteObjectRequest); protected abstract PutObjectResponse putAPICall(PutObjectRequest putObjectRequest, String testString); protected abstract ResponseBytes<GetObjectResponse> getAPICall(GetObjectRequest getObjectRequest); protected abstract String bucketName(); }
4,801
0
Create_ds/aws-sdk-java-v2/services/s3/src/it/java/software/amazon/awssdk/services/s3
Create_ds/aws-sdk-java-v2/services/s3/src/it/java/software/amazon/awssdk/services/s3/crossregion/S3CrossRegionAsyncIntegrationTestBase.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.crossregion; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import software.amazon.awssdk.core.ResponseBytes; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.core.async.AsyncResponseTransformer; import software.amazon.awssdk.services.s3.S3AsyncClient; import software.amazon.awssdk.services.s3.model.DeleteObjectRequest; import software.amazon.awssdk.services.s3.model.DeleteObjectResponse; import software.amazon.awssdk.services.s3.model.DeleteObjectsRequest; import software.amazon.awssdk.services.s3.model.DeleteObjectsResponse; import software.amazon.awssdk.services.s3.model.GetObjectRequest; import software.amazon.awssdk.services.s3.model.GetObjectResponse; import software.amazon.awssdk.services.s3.model.HeadBucketRequest; import software.amazon.awssdk.services.s3.model.HeadBucketResponse; import software.amazon.awssdk.services.s3.model.ListObjectsV2Request; import software.amazon.awssdk.services.s3.model.PutObjectRequest; import software.amazon.awssdk.services.s3.model.PutObjectResponse; import software.amazon.awssdk.services.s3.model.S3Object; import software.amazon.awssdk.services.s3.paginators.ListObjectsV2Publisher; public abstract class S3CrossRegionAsyncIntegrationTestBase extends S3CrossRegionIntegrationTestBase{ protected S3AsyncClient crossRegionS3Client; @Override protected List<S3Object> paginatedAPICall(ListObjectsV2Request listObjectsV2Request) { List<S3Object> resultObjects = new ArrayList<>(); ListObjectsV2Publisher publisher = crossRegionS3Client.listObjectsV2Paginator(listObjectsV2Request); CompletableFuture<Void> subscribe = publisher.subscribe(response -> { response.contents().forEach(a -> resultObjects.add(a)); }); subscribe.join(); return resultObjects; } @Override protected DeleteObjectsResponse postObjectAPICall(DeleteObjectsRequest deleteObjectsRequest) { return crossRegionS3Client.deleteObjects(deleteObjectsRequest).join(); } @Override protected HeadBucketResponse headAPICall(HeadBucketRequest headBucketRequest) { return crossRegionS3Client.headBucket(headBucketRequest).join(); } @Override protected DeleteObjectResponse deleteObjectAPICall(DeleteObjectRequest deleteObjectRequest) { return crossRegionS3Client.deleteObject(deleteObjectRequest).join(); } @Override protected PutObjectResponse putAPICall(PutObjectRequest putObjectRequest, String testString) { return crossRegionS3Client.putObject(putObjectRequest, AsyncRequestBody.fromString(testString)).join(); } @Override protected ResponseBytes<GetObjectResponse> getAPICall(GetObjectRequest getObjectRequest) { return crossRegionS3Client.getObject(getObjectRequest, AsyncResponseTransformer.toBytes()).join(); } }
4,802
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/S3Configuration.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3; import java.util.Optional; import java.util.function.Supplier; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.core.ServiceConfiguration; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.profiles.ProfileFileSupplier; import software.amazon.awssdk.profiles.ProfileFileSystemSetting; import software.amazon.awssdk.services.s3.internal.FieldWithDefault; import software.amazon.awssdk.services.s3.internal.settingproviders.DisableMultiRegionProviderChain; import software.amazon.awssdk.services.s3.internal.settingproviders.UseArnRegionProviderChain; import software.amazon.awssdk.services.s3.model.PutBucketAccelerateConfigurationRequest; import software.amazon.awssdk.services.s3.presigner.S3Presigner; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; @SdkPublicApi @Immutable @ThreadSafe public final class S3Configuration implements ServiceConfiguration, ToCopyableBuilder<S3Configuration.Builder, S3Configuration> { /** * The default setting for use of path style addressing. */ private static final boolean DEFAULT_PATH_STYLE_ACCESS_ENABLED = false; /** * S3 accelerate is by default not enabled */ private static final boolean DEFAULT_ACCELERATE_MODE_ENABLED = false; /** * S3 dualstack endpoint is by default not enabled */ private static final boolean DEFAULT_DUALSTACK_ENABLED = false; /** * S3 payload checksum validation is by default enabled; */ private static final boolean DEFAULT_CHECKSUM_VALIDATION_ENABLED = true; /** * S3 The default value for enabling chunked encoding for {@link * software.amazon.awssdk.services.s3.model.PutObjectRequest} and {@link * software.amazon.awssdk.services.s3.model.UploadPartRequest}. */ private static final boolean DEFAULT_CHUNKED_ENCODING_ENABLED = true; private final FieldWithDefault<Boolean> pathStyleAccessEnabled; private final FieldWithDefault<Boolean> accelerateModeEnabled; private final FieldWithDefault<Boolean> dualstackEnabled; private final FieldWithDefault<Boolean> checksumValidationEnabled; private final FieldWithDefault<Boolean> chunkedEncodingEnabled; private final Boolean useArnRegionEnabled; private final Boolean multiRegionEnabled; private final FieldWithDefault<Supplier<ProfileFile>> profileFile; private final FieldWithDefault<String> profileName; private S3Configuration(DefaultS3ServiceConfigurationBuilder builder) { this.dualstackEnabled = FieldWithDefault.create(builder.dualstackEnabled, DEFAULT_DUALSTACK_ENABLED); this.accelerateModeEnabled = FieldWithDefault.create(builder.accelerateModeEnabled, DEFAULT_ACCELERATE_MODE_ENABLED); this.pathStyleAccessEnabled = FieldWithDefault.create(builder.pathStyleAccessEnabled, DEFAULT_PATH_STYLE_ACCESS_ENABLED); this.checksumValidationEnabled = FieldWithDefault.create(builder.checksumValidationEnabled, DEFAULT_CHECKSUM_VALIDATION_ENABLED); this.chunkedEncodingEnabled = FieldWithDefault.create(builder.chunkedEncodingEnabled, DEFAULT_CHUNKED_ENCODING_ENABLED); this.profileFile = FieldWithDefault.create(builder.profileFile, ProfileFile::defaultProfileFile); this.profileName = FieldWithDefault.create(builder.profileName, ProfileFileSystemSetting.AWS_PROFILE.getStringValueOrThrow()); this.useArnRegionEnabled = builder.useArnRegionEnabled; this.multiRegionEnabled = builder.multiRegionEnabled; if (accelerateModeEnabled() && pathStyleAccessEnabled()) { throw new IllegalArgumentException("Accelerate mode cannot be used with path style addressing"); } } private boolean resolveUseArnRegionEnabled() { return UseArnRegionProviderChain.create(this.profileFile.value(), this.profileName.value()) .resolveUseArnRegion() .orElse(false); } private boolean resolveMultiRegionEnabled() { return !DisableMultiRegionProviderChain.create(this.profileFile.value(), this.profileName.value()) .resolve() .orElse(false); } /** * Create a {@link Builder}, used to create a {@link S3Configuration}. */ public static Builder builder() { return new DefaultS3ServiceConfigurationBuilder(); } /** * <p> * Returns whether the client uses path-style access for all requests. * </p> * <p> * Amazon S3 supports virtual-hosted-style and path-style access in all * Regions. The path-style syntax, however, requires that you use the * region-specific endpoint when attempting to access a bucket. * </p> * <p> * The default behaviour is to detect which access style to use based on * the configured endpoint (an IP will result in path-style access) and * the bucket being accessed (some buckets are not valid DNS names). * Setting this flag will result in path-style access being used for all * requests. * </p> * * @return True is the client should always use path-style access */ public boolean pathStyleAccessEnabled() { return pathStyleAccessEnabled.value(); } /** * <p> * Returns whether the client has enabled accelerate mode for getting and putting objects. * </p> * <p> * The default behavior is to disable accelerate mode for any operations (GET, PUT, DELETE). You need to call * {@link DefaultS3Client#putBucketAccelerateConfiguration(PutBucketAccelerateConfigurationRequest)} * first to use this feature. * </p> * * @return True if accelerate mode is enabled. */ public boolean accelerateModeEnabled() { return accelerateModeEnabled.value(); } /** * <p> * Returns whether the client is configured to use dualstack mode for * accessing S3. If you want to use IPv6 when accessing S3, dualstack * must be enabled. * </p> * * <p> * Dualstack endpoints are disabled by default. * </p> * * @return True if the client will use the dualstack endpoints */ public boolean dualstackEnabled() { return dualstackEnabled.value(); } public boolean checksumValidationEnabled() { return checksumValidationEnabled.value(); } /** * Returns whether the client should use chunked encoding when signing the * payload body. * <p> * This option only currently applies to {@link * software.amazon.awssdk.services.s3.model.PutObjectRequest} and {@link * software.amazon.awssdk.services.s3.model.UploadPartRequest}. * * @return True if chunked encoding should be used. */ public boolean chunkedEncodingEnabled() { return chunkedEncodingEnabled.value(); } /** * Returns whether the client is allowed to make cross-region calls when an S3 Access Point ARN has a different * region to the one configured on the client. * <p> * @return True if a different region in the ARN can be used. */ public boolean useArnRegionEnabled() { return Optional.ofNullable(useArnRegionEnabled) .orElseGet(this::resolveUseArnRegionEnabled); } /** * Returns whether the client is allowed to make cross-region calls when using an S3 Multi-Region Access Point ARN. * <p> * @return True if multi-region ARNs is enabled. */ public boolean multiRegionEnabled() { return Optional.ofNullable(multiRegionEnabled) .orElseGet(this::resolveMultiRegionEnabled); } @Override public Builder toBuilder() { return builder() .dualstackEnabled(dualstackEnabled.valueOrNullIfDefault()) .multiRegionEnabled(multiRegionEnabled) .accelerateModeEnabled(accelerateModeEnabled.valueOrNullIfDefault()) .pathStyleAccessEnabled(pathStyleAccessEnabled.valueOrNullIfDefault()) .checksumValidationEnabled(checksumValidationEnabled.valueOrNullIfDefault()) .chunkedEncodingEnabled(chunkedEncodingEnabled.valueOrNullIfDefault()) .useArnRegionEnabled(useArnRegionEnabled) .profileFile(profileFile.valueOrNullIfDefault()) .profileName(profileName.valueOrNullIfDefault()); } @NotThreadSafe public interface Builder extends CopyableBuilder<Builder, S3Configuration> { Boolean dualstackEnabled(); /** * Option to enable using the dualstack endpoints when accessing S3. Dualstack * should be enabled if you want to use IPv6. * * <p> * Dualstack endpoints are disabled by default. * </p> * * @deprecated This option has been replaced with {@link S3ClientBuilder#dualstackEnabled(Boolean)} and * {@link S3Presigner.Builder#dualstackEnabled(Boolean)}. If both this and one of those options are set, an exception * will be thrown. */ @Deprecated Builder dualstackEnabled(Boolean dualstackEnabled); Boolean accelerateModeEnabled(); /** * Option to enable using the accelerate endpoint when accessing S3. Accelerate * endpoints allow faster transfer of objects by using Amazon CloudFront's * globally distributed edge locations. * * <p> * Accelerate mode is disabled by default. * </p> * * @see S3Configuration#accelerateModeEnabled(). */ Builder accelerateModeEnabled(Boolean accelerateModeEnabled); Boolean pathStyleAccessEnabled(); /** * Option to enable using path style access for accessing S3 objects * instead of DNS style access. DNS style access is preferred as it * will result in better load balancing when accessing S3. * * <p> * Path style access is disabled by default. Path style may still be used for legacy * buckets that are not DNS compatible. * </p> * * @see S3Configuration#pathStyleAccessEnabled(). */ Builder pathStyleAccessEnabled(Boolean pathStyleAccessEnabled); Boolean checksumValidationEnabled(); /** * Option to disable doing a validation of the checksum of an object stored in S3. * * <p> * Checksum validation is enabled by default. * </p> * * @see S3Configuration#checksumValidationEnabled(). */ Builder checksumValidationEnabled(Boolean checksumValidationEnabled); Boolean chunkedEncodingEnabled(); /** * Option to enable using chunked encoding when signing the request * payload for {@link * software.amazon.awssdk.services.s3.model.PutObjectRequest} and {@link * software.amazon.awssdk.services.s3.model.UploadPartRequest}. * * @see S3Configuration#chunkedEncodingEnabled() */ Builder chunkedEncodingEnabled(Boolean chunkedEncodingEnabled); Boolean useArnRegionEnabled(); /** * If an S3 resource ARN is passed in as the target of an S3 operation that has a different region to the one * the client was configured with, this flag must be set to 'true' to permit the client to make a * cross-region call to the region specified in the ARN otherwise an exception will be thrown. * * @see S3Configuration#useArnRegionEnabled() */ Builder useArnRegionEnabled(Boolean useArnRegionEnabled); Boolean multiRegionEnabled(); /** * Option to enable or disable the usage of multi-region access point ARNs. Multi-region access point ARNs * can result in cross-region calls, and can be prevented by setting this flag to false. This option is * enabled by default. * * @see S3Configuration#multiRegionEnabled() */ Builder multiRegionEnabled(Boolean multiRegionEnabled); ProfileFile profileFile(); /** * The profile file that should be consulted to determine the default value of {@link #useArnRegionEnabled(Boolean)} * or {@link #multiRegionEnabled(Boolean)}. * This is not used, if those parameters are configured. * * <p> * By default, the {@link ProfileFile#defaultProfileFile()} is used. * </p> */ Builder profileFile(ProfileFile profileFile); Supplier<ProfileFile> profileFileSupplier(); /** * The supplier of profile file instances that should be consulted to determine the default value of * {@link #useArnRegionEnabled(Boolean)} or {@link #multiRegionEnabled(Boolean)}. * This is not used, if those parameters are configured on the builder. * * <p> * By default, the {@link ProfileFile#defaultProfileFile()} is used. * </p> */ Builder profileFile(Supplier<ProfileFile> profileFile); String profileName(); /** * The profile name that should be consulted to determine the default value of {@link #useArnRegionEnabled(Boolean)} * or {@link #multiRegionEnabled(Boolean)}. * This is not used, if those parameters are configured. * * <p> * By default, the {@link ProfileFileSystemSetting#AWS_PROFILE} is used. * </p> */ Builder profileName(String profileName); } static final class DefaultS3ServiceConfigurationBuilder implements Builder { private Boolean dualstackEnabled; private Boolean accelerateModeEnabled; private Boolean pathStyleAccessEnabled; private Boolean checksumValidationEnabled; private Boolean chunkedEncodingEnabled; private Boolean useArnRegionEnabled; private Boolean multiRegionEnabled; private Supplier<ProfileFile> profileFile; private String profileName; @Override public Boolean dualstackEnabled() { return dualstackEnabled; } @Override public Builder dualstackEnabled(Boolean dualstackEnabled) { this.dualstackEnabled = dualstackEnabled; return this; } @Override public Boolean accelerateModeEnabled() { return accelerateModeEnabled; } public void setDualstackEnabled(Boolean dualstackEnabled) { dualstackEnabled(dualstackEnabled); } @Override public Builder accelerateModeEnabled(Boolean accelerateModeEnabled) { this.accelerateModeEnabled = accelerateModeEnabled; return this; } @Override public Boolean pathStyleAccessEnabled() { return pathStyleAccessEnabled; } public void setAccelerateModeEnabled(Boolean accelerateModeEnabled) { accelerateModeEnabled(accelerateModeEnabled); } @Override public Builder pathStyleAccessEnabled(Boolean pathStyleAccessEnabled) { this.pathStyleAccessEnabled = pathStyleAccessEnabled; return this; } @Override public Boolean checksumValidationEnabled() { return checksumValidationEnabled; } public void setPathStyleAccessEnabled(Boolean pathStyleAccessEnabled) { pathStyleAccessEnabled(pathStyleAccessEnabled); } @Override public Builder checksumValidationEnabled(Boolean checksumValidationEnabled) { this.checksumValidationEnabled = checksumValidationEnabled; return this; } @Override public Boolean chunkedEncodingEnabled() { return chunkedEncodingEnabled; } public void setChecksumValidationEnabled(Boolean checksumValidationEnabled) { checksumValidationEnabled(checksumValidationEnabled); } @Override public Builder chunkedEncodingEnabled(Boolean chunkedEncodingEnabled) { this.chunkedEncodingEnabled = chunkedEncodingEnabled; return this; } @Override public Boolean useArnRegionEnabled() { return useArnRegionEnabled; } public void setChunkedEncodingEnabled(Boolean chunkedEncodingEnabled) { chunkedEncodingEnabled(chunkedEncodingEnabled); } @Override public Builder useArnRegionEnabled(Boolean useArnRegionEnabled) { this.useArnRegionEnabled = useArnRegionEnabled; return this; } @Override public Boolean multiRegionEnabled() { return multiRegionEnabled; } @Override public Builder multiRegionEnabled(Boolean multiRegionEnabled) { this.multiRegionEnabled = multiRegionEnabled; return this; } @Override public ProfileFile profileFile() { return Optional.ofNullable(profileFile) .map(Supplier::get) .orElse(null); } @Override public Builder profileFile(ProfileFile profileFile) { return profileFile(Optional.ofNullable(profileFile) .map(ProfileFileSupplier::fixedProfileFile) .orElse(null)); } @Override public Supplier<ProfileFile> profileFileSupplier() { return profileFile; } @Override public Builder profileFile(Supplier<ProfileFile> profileFile) { this.profileFile = profileFile; return this; } @Override public String profileName() { return profileName; } @Override public Builder profileName(String profileName) { this.profileName = profileName; return this; } public void setUseArnRegionEnabled(Boolean useArnRegionEnabled) { useArnRegionEnabled(useArnRegionEnabled); } @Override public S3Configuration build() { return new S3Configuration(this); } } }
4,803
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/S3CrtAsyncClientBuilder.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3; import java.net.URI; import java.nio.file.Path; import java.util.function.Consumer; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.crt.S3CrtHttpConfiguration; import software.amazon.awssdk.services.s3.crt.S3CrtRetryConfiguration; import software.amazon.awssdk.services.s3.model.GetObjectRequest; import software.amazon.awssdk.services.s3.model.PutObjectRequest; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.builder.SdkBuilder; /** * Builder API to build instance of Common Run Time based S3AsyncClient. */ @SdkPublicApi public interface S3CrtAsyncClientBuilder extends SdkBuilder<S3CrtAsyncClientBuilder, S3AsyncClient> { /** * Configure the credentials that should be used to authenticate with S3. * * <p>The default provider will attempt to identify the credentials automatically using the following checks: * <ol> * <li>Java System Properties - <code>aws.accessKeyId</code> and <code>aws.secretKey</code></li> * <li>Environment Variables - <code>AWS_ACCESS_KEY_ID</code> and <code>AWS_SECRET_ACCESS_KEY</code></li> * <li>Credential profiles file at the default location (~/.aws/credentials) shared by all AWS SDKs and the AWS CLI</li> * <li>Credentials delivered through the Amazon EC2 container service if AWS_CONTAINER_CREDENTIALS_RELATIVE_URI * environment variable is set and security manager has permission to access the variable.</li> * <li>Instance profile credentials delivered through the Amazon EC2 metadata service</li> * </ol> * * <p>If the credentials are not found in any of the locations above, an exception will be thrown at {@link #build()} * time. * </p> * * @param credentialsProvider the credentials to use * @return This builder for method chaining. */ default S3CrtAsyncClientBuilder credentialsProvider(AwsCredentialsProvider credentialsProvider) { return credentialsProvider((IdentityProvider<? extends AwsCredentialsIdentity>) credentialsProvider); } /** * Configure the credentials that should be used to authenticate with S3. * * <p>The default provider will attempt to identify the credentials automatically using the following checks: * <ol> * <li>Java System Properties - {@code aws.accessKeyId} and {@code aws.secretKey}</li> * <li>Environment Variables - {@code AWS_ACCESS_KEY_ID} and {@code AWS_SECRET_ACCESS_KEY}</li> * <li>Credential profiles file at the default location (~/.aws/credentials) shared by all AWS SDKs and the AWS CLI</li> * <li>Credentials delivered through the Amazon EC2 container service if AWS_CONTAINER_CREDENTIALS_RELATIVE_URI * environment variable is set and security manager has permission to access the variable.</li> * <li>Instance profile credentials delivered through the Amazon EC2 metadata service</li> * </ol> * * <p>If the credentials are not found in any of the locations above, an exception will be thrown at {@link #build()} * time. * </p> * * @param credentialsProvider the credentials to use * @return This builder for method chaining. */ default S3CrtAsyncClientBuilder credentialsProvider(IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider) { throw new UnsupportedOperationException(); } /** * Configure the region with which the SDK should communicate. * * <p>If this is not specified, the SDK will attempt to identify the endpoint automatically using the following logic: * <ol> * <li>Check the 'aws.region' system property for the region.</li> * <li>Check the 'AWS_REGION' environment variable for the region.</li> * <li>Check the {user.home}/.aws/credentials and {user.home}/.aws/config files for the region.</li> * <li>If running in EC2, check the EC2 metadata service for the region.</li> * </ol> * * @param region the region to be used * @return this builder for method chaining. */ S3CrtAsyncClientBuilder region(Region region); /** * Sets the minimum part size for transfer parts. Decreasing the minimum part size causes multipart transfer to be split into * a larger number of smaller parts. Setting this value too low has a negative effect on transfer speeds, causing extra * latency and network communication for each part. * * <p> * By default, it is 8MB. See <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/qfacts.html">Amazon S3 multipart * upload limits</a> for guidance. * * @param uploadPartSize The minimum part size for transfer parts. * @return this builder for method chaining. */ S3CrtAsyncClientBuilder minimumPartSizeInBytes(Long uploadPartSize); /** * The target throughput for transfer requests. Higher value means more connections will be established with S3. * * <p> * Whether the transfer manager can achieve the configured target throughput depends on various factors such as the network * bandwidth of the environment and whether {@link #maxConcurrency} is configured. * * <p> * By default, it is 10 gigabits per second. If users want to transfer as fast as possible, it's recommended to set it to the * maximum network bandwidth on the host that the application is running on. For EC2 instances, you can find network * bandwidth for a specific * instance type in <a href="https://aws.amazon.com/ec2/instance-types/">Amazon EC2 instance type page</a>. * If you are running into out of file descriptors error, consider using {@link #maxConcurrency(Integer)} to limit the * number of connections. * * @param targetThroughputInGbps the target throughput in Gbps * @return this builder for method chaining. * @see #maxConcurrency(Integer) */ S3CrtAsyncClientBuilder targetThroughputInGbps(Double targetThroughputInGbps); /** * Specifies the maximum number of S3 connections that should be established during * a transfer. * * <p> * If not provided, the TransferManager will calculate the optional number of connections * based on {@link #targetThroughputInGbps}. If the value is too low, the S3TransferManager * might not achieve the specified target throughput. * * @param maxConcurrency the max number of concurrent requests * @return this builder for method chaining. * @see #targetThroughputInGbps(Double) */ S3CrtAsyncClientBuilder maxConcurrency(Integer maxConcurrency); /** * Configure the endpoint override with which the SDK should communicate. * * @param endpointOverride the endpoint override to be used * @return this builder for method chaining. */ S3CrtAsyncClientBuilder endpointOverride(URI endpointOverride); /** * Option to disable checksum validation for {@link S3AsyncClient#getObject(GetObjectRequest, Path)} and * {@link S3AsyncClient#putObject(PutObjectRequest, Path)}. * * <p> * Checksum validation using CRC32 is enabled by default. */ S3CrtAsyncClientBuilder checksumValidationEnabled(Boolean checksumValidationEnabled); /** * Configure the starting buffer size the client will use to buffer the parts downloaded from S3. Maintain a larger window to * keep up a high download throughput; parts cannot download in parallel unless the window is large enough to hold multiple * parts. Maintain a smaller window to limit the amount of data buffered in memory. * * <p> * By default, it is equal to the resolved part size * 10 * * @param initialReadBufferSizeInBytes the initial read buffer size * @return this builder for method chaining. */ S3CrtAsyncClientBuilder initialReadBufferSizeInBytes(Long initialReadBufferSizeInBytes); /** * Sets the HTTP configuration to use for this client. * * @param configuration The http proxy configuration to use * @return The builder of the method chaining. */ S3CrtAsyncClientBuilder httpConfiguration(S3CrtHttpConfiguration configuration); /** * Sets the Retry configuration to use for this client. * * @param retryConfiguration The retry configurations to be used. * @return The builder of the method chaining. */ S3CrtAsyncClientBuilder retryConfiguration(S3CrtRetryConfiguration retryConfiguration); /** * A convenience method that creates an instance of the {@link S3CrtHttpConfiguration} builder, avoiding the * need to create one manually via {@link S3CrtHttpConfiguration#builder()}. * * @param configurationBuilder The health checks config builder to use * @return The builder of the method chaining. * @see #httpConfiguration(S3CrtHttpConfiguration) */ default S3CrtAsyncClientBuilder httpConfiguration(Consumer<S3CrtHttpConfiguration.Builder> configurationBuilder) { Validate.paramNotNull(configurationBuilder, "configurationBuilder"); return httpConfiguration(S3CrtHttpConfiguration.builder() .applyMutation(configurationBuilder) .build()); } // S3 client context params, copied from S3BaseClientBuilder. Note we only have accelerate and path style because they're // the only ones we can support in the CRT client (does not affect signing). /** * Enables this client to use S3 Transfer Acceleration endpoints. */ S3CrtAsyncClientBuilder accelerate(Boolean accelerate); /** * Forces this client to use path-style addressing for buckets. */ S3CrtAsyncClientBuilder forcePathStyle(Boolean forcePathStyle); /** * A convenience method that creates an instance of the {@link S3CrtRetryConfiguration} builder, avoiding the * need to create one manually via {@link S3CrtRetryConfiguration#builder()}. * * @param retryConfigurationBuilder The retry config builder to use * @return The builder of the method chaining. * @see #retryConfiguration(S3CrtRetryConfiguration) */ default S3CrtAsyncClientBuilder retryConfiguration(Consumer<S3CrtRetryConfiguration.Builder> retryConfigurationBuilder) { Validate.paramNotNull(retryConfigurationBuilder, "retryConfigurationBuilder"); return retryConfiguration(S3CrtRetryConfiguration.builder() .applyMutation(retryConfigurationBuilder) .build()); } /** * <p> Configures whether cross-region bucket access is enabled for clients using the configuration. * <p>The following behavior is used when this mode is enabled: * <ol> * <li>This method allows enabling or disabling cross-region bucket access for clients. When cross-region bucket * access is enabled, requests that do not act on an existing bucket (e.g., createBucket API) will be routed to the * region configured on the client</li> * <li>The first time a request is made that references an existing bucket (e.g., putObject API), a request will be * made to the client-configured region. If the bucket does not exist in this region, the service will include the * actual region in the error responses. Subsequently, the API will be called using the correct region obtained * from the error response. </li> * <li>This location may be cached in the client for subsequent requests to the same bucket.</li> * </ol> * <p>Enabling this mode has several drawbacks, as it can increase latency if the bucket's location is physically far * from the location of the request.Therefore, it is strongly advised, whenever possible, to know the location of your * buckets and create a region-specific client to access them * * @param crossRegionAccessEnabled Whether cross region bucket access should be enabled. * @return The builder object for method chaining. */ S3CrtAsyncClientBuilder crossRegionAccessEnabled(Boolean crossRegionAccessEnabled); /** * Configure the size threshold, in bytes, for when to use multipart upload. Uploads/copies over this size will automatically * use a multipart upload strategy, while uploads/copies smaller than this threshold will use a single connection to * upload/copy the whole object. * * <p> * Multipart uploads are easier to recover from and also potentially faster than single part uploads, especially when the * upload parts can be uploaded in parallel. Because there are additional network API calls, small objects are still * recommended to use a single connection for the upload. See * <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/mpuoverview.html">Uploading and copying objects using * multipart upload</a>. * * <p> * By default, it is the same as {@link #minimumPartSizeInBytes(Long)}. * * @param thresholdInBytes the value of the threshold to set. * @return an instance of this builder. */ S3CrtAsyncClientBuilder thresholdInBytes(Long thresholdInBytes); @Override S3AsyncClient build(); }
4,804
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/S3Uri.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3; import java.net.URI; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.utils.CollectionUtils; 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; /** * Object that represents a parsed S3 URI. Can be used to easily retrieve the bucket, key, region, style, and query parameters * of the URI. Only path-style and virtual-hosted-style URI parsing is supported, including CLI-style URIs, e.g., * "s3://bucket/key". AccessPoints and Outposts URI parsing is not supported. If you work with object keys and/or query * parameters with special characters, they must be URL-encoded, e.g., replace " " with "%20". If you work with * virtual-hosted-style URIs with bucket names that contain a dot, i.e., ".", the dot must not be URL-encoded. Encoded buckets, * keys, and query parameters will be returned decoded. */ @Immutable @SdkPublicApi public final class S3Uri implements ToCopyableBuilder<S3Uri.Builder, S3Uri> { private final URI uri; private final String bucket; private final String key; private final Region region; private final boolean isPathStyle; private final Map<String, List<String>> queryParams; private S3Uri(Builder builder) { this.uri = Validate.notNull(builder.uri, "URI must not be null"); this.bucket = builder.bucket; this.key = builder.key; this.region = builder.region; this.isPathStyle = Validate.notNull(builder.isPathStyle, "Path style flag must not be null"); this.queryParams = builder.queryParams == null ? new HashMap<>() : CollectionUtils.deepCopyMap(builder.queryParams); } public static Builder builder() { return new Builder(); } @Override public Builder toBuilder() { return new Builder(this); } /** * Returns the original URI that was used to instantiate the {@link S3Uri} */ public URI uri() { return uri; } /** * Returns the bucket specified in the URI. Returns an empty optional if no bucket is specified. */ public Optional<String> bucket() { return Optional.ofNullable(bucket); } /** * Returns the key specified in the URI. Returns an empty optional if no key is specified. */ public Optional<String> key() { return Optional.ofNullable(key); } /** * Returns the region specified in the URI. Returns an empty optional if no region is specified, i.e., global endpoint. */ public Optional<Region> region() { return Optional.ofNullable(region); } /** * Returns true if the URI is path-style, false if the URI is virtual-hosted style. */ public boolean isPathStyle() { return isPathStyle; } /** * Returns a map of the query parameters specified in the URI. Returns an empty map if no queries are specified. */ public Map<String, List<String>> rawQueryParameters() { return queryParams; } /** * Returns the list of values for a specified query parameter. A empty list is returned if the URI does not contain the * specified query parameter. */ public List<String> firstMatchingRawQueryParameters(String key) { List<String> queryValues = queryParams.get(key); if (queryValues == null) { return new ArrayList<>(); } List<String> queryValuesCopy = Arrays.asList(new String[queryValues.size()]); Collections.copy(queryValuesCopy, queryValues); return queryValuesCopy; } /** * Returns the value for the specified query parameter. If there are multiple values for the query parameter, the first * value is returned. An empty optional is returned if the URI does not contain the specified query parameter. */ public Optional<String> firstMatchingRawQueryParameter(String key) { return Optional.ofNullable(queryParams.get(key)).map(q -> q.get(0)); } @Override public String toString() { return ToString.builder("S3Uri") .add("uri", uri) .add("bucket", bucket) .add("key", key) .add("region", region) .add("isPathStyle", isPathStyle) .add("queryParams", queryParams) .build(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } S3Uri s3Uri = (S3Uri) o; return Objects.equals(uri, s3Uri.uri) && Objects.equals(bucket, s3Uri.bucket) && Objects.equals(key, s3Uri.key) && Objects.equals(region, s3Uri.region) && Objects.equals(isPathStyle, s3Uri.isPathStyle) && Objects.equals(queryParams, s3Uri.queryParams); } @Override public int hashCode() { int result = uri != null ? uri.hashCode() : 0; result = 31 * result + (bucket != null ? bucket.hashCode() : 0); result = 31 * result + (key != null ? key.hashCode() : 0); result = 31 * result + (region != null ? region.hashCode() : 0); result = 31 * result + Boolean.hashCode(isPathStyle); result = 31 * result + (queryParams != null ? queryParams.hashCode() : 0); return result; } /** * A builder for creating a {@link S3Uri} */ public static final class Builder implements CopyableBuilder<Builder, S3Uri> { private URI uri; private String bucket; private String key; private Region region; private boolean isPathStyle; private Map<String, List<String>> queryParams; private Builder() { } private Builder(S3Uri s3Uri) { this.uri = s3Uri.uri; this.bucket = s3Uri.bucket; this.key = s3Uri.key; this.region = s3Uri.region; this.isPathStyle = s3Uri.isPathStyle; this.queryParams = s3Uri.queryParams; } /** * Configure the URI */ public Builder uri(URI uri) { this.uri = uri; return this; } /** * Configure the bucket */ public Builder bucket(String bucket) { this.bucket = bucket; return this; } /** * Configure the key */ public Builder key(String key) { this.key = key; return this; } /** * Configure the region */ public Builder region(Region region) { this.region = region; return this; } /** * Configure the path style flag */ public Builder isPathStyle(boolean isPathStyle) { this.isPathStyle = isPathStyle; return this; } /** * Configure the map of query parameters */ public Builder queryParams(Map<String, List<String>> queryParams) { this.queryParams = queryParams; return this; } @Override public S3Uri build() { return new S3Uri(this); } } }
4,805
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/S3SystemSetting.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.utils.SystemSetting; /** * S3 specific system setting */ @SdkProtectedApi public enum S3SystemSetting implements SystemSetting { AWS_S3_USE_ARN_REGION("aws.s3UseArnRegion", null), AWS_S3_DISABLE_MULTIREGION_ACCESS_POINTS("aws.s3DisableMultiRegionAccessPoints", null); private final String systemProperty; private final String defaultValue; S3SystemSetting(String systemProperty, String defaultValue) { this.systemProperty = systemProperty; this.defaultValue = defaultValue; } @Override public String property() { return systemProperty; } @Override public String environmentVariable() { return name(); } @Override public String defaultValue() { return defaultValue; } }
4,806
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/S3Utilities.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.Consumer; import java.util.function.Supplier; import java.util.regex.Matcher; import java.util.regex.Pattern; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.awscore.AwsExecutionAttribute; import software.amazon.awssdk.awscore.client.config.AwsClientOption; import software.amazon.awssdk.awscore.defaultsmode.DefaultsMode; import software.amazon.awssdk.awscore.endpoint.DefaultServiceEndpointBuilder; import software.amazon.awssdk.awscore.endpoint.DualstackEnabledProvider; import software.amazon.awssdk.awscore.endpoint.FipsEnabledProvider; import software.amazon.awssdk.awscore.internal.defaultsmode.DefaultsModeConfiguration; import software.amazon.awssdk.core.ClientType; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.client.config.SdkClientOption; import software.amazon.awssdk.core.exception.SdkException; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.core.interceptor.ExecutionInterceptorChain; import software.amazon.awssdk.core.interceptor.InterceptorContext; import software.amazon.awssdk.core.interceptor.SdkExecutionAttribute; import software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.profiles.ProfileFileSupplier; import software.amazon.awssdk.protocols.core.OperationInfo; import software.amazon.awssdk.protocols.core.PathMarshaller; import software.amazon.awssdk.protocols.core.ProtocolUtils; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.regions.ServiceMetadataAdvancedOption; import software.amazon.awssdk.services.s3.endpoints.S3ClientContextParams; import software.amazon.awssdk.services.s3.endpoints.S3EndpointProvider; import software.amazon.awssdk.services.s3.endpoints.internal.S3RequestSetEndpointInterceptor; import software.amazon.awssdk.services.s3.endpoints.internal.S3ResolveEndpointInterceptor; import software.amazon.awssdk.services.s3.internal.endpoints.UseGlobalEndpointResolver; import software.amazon.awssdk.services.s3.model.GetObjectRequest; import software.amazon.awssdk.services.s3.model.GetUrlRequest; import software.amazon.awssdk.utils.AttributeMap; import software.amazon.awssdk.utils.StringUtils; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.http.SdkHttpUtils; /** * Utilities for working with Amazon S3 objects. An instance of this class can be created by: * <p> * 1) Directly using the {@link #builder()} method. You have to manually specify the configuration params like region, * s3Configuration on the builder. * * <pre> * S3Utilities utilities = S3Utilities.builder().region(Region.US_WEST_2).build() * GetUrlRequest request = GetUrlRequest.builder().bucket("foo-bucket").key("key-without-spaces").build(); * URL url = utilities.getUrl(request); * </pre> * * <p> * 2) Using the low-level client {@link S3Client#utilities()} method. This is recommended as SDK will use the same * configuration from the {@link S3Client} object to create the {@link S3Utilities} object. * * <pre> * S3Client s3client = S3Client.create(); * S3Utilities utilities = s3client.utilities(); * GetUrlRequest request = GetUrlRequest.builder().bucket("foo-bucket").key("key-without-spaces").build(); * URL url = utilities.getUrl(request); * </pre> * * Note: This class does not make network calls. */ @Immutable @SdkPublicApi public final class S3Utilities { private static final String SERVICE_NAME = "s3"; private static final Pattern ENDPOINT_PATTERN = Pattern.compile("^(.+\\.)?s3[.-]([a-z0-9-]+)\\."); private final Region region; private final URI endpoint; private final S3Configuration s3Configuration; private final Supplier<ProfileFile> profileFile; private final String profileName; private final boolean fipsEnabled; private final ExecutionInterceptorChain interceptorChain; private final UseGlobalEndpointResolver useGlobalEndpointResolver; /** * SDK currently validates that region is present while constructing {@link S3Utilities} object. * This can be relaxed in the future when more methods are added that don't use region. */ private S3Utilities(Builder builder) { this.region = Validate.paramNotNull(builder.region, "Region"); this.endpoint = builder.endpoint; this.profileFile = Optional.ofNullable(builder.profileFile) .orElseGet(() -> ProfileFileSupplier.fixedProfileFile(ProfileFile.defaultProfileFile())); this.profileName = builder.profileName; if (builder.s3Configuration == null) { this.s3Configuration = S3Configuration.builder().dualstackEnabled(builder.dualstackEnabled).build(); } else { this.s3Configuration = builder.s3Configuration.toBuilder() .applyMutation(b -> resolveDualstackSetting(b, builder)) .build(); } this.fipsEnabled = builder.fipsEnabled != null ? builder.fipsEnabled : FipsEnabledProvider.builder() .profileFile(profileFile) .profileName(profileName) .build() .isFipsEnabled() .orElse(false); this.interceptorChain = createEndpointInterceptorChain(); this.useGlobalEndpointResolver = createUseGlobalEndpointResolver(); } private void resolveDualstackSetting(S3Configuration.Builder s3ConfigBuilder, Builder s3UtiltiesBuilder) { Validate.validState(s3ConfigBuilder.dualstackEnabled() == null || s3UtiltiesBuilder.dualstackEnabled == null, "Only one of S3Configuration.Builder's dualstackEnabled or S3Utilities.Builder's dualstackEnabled " + "should be set."); if (s3ConfigBuilder.dualstackEnabled() != null) { return; } if (s3UtiltiesBuilder.dualstackEnabled != null) { s3ConfigBuilder.dualstackEnabled(s3UtiltiesBuilder.dualstackEnabled); return; } s3ConfigBuilder.dualstackEnabled(DualstackEnabledProvider.builder() .profileFile(profileFile) .profileName(profileName) .build() .isDualstackEnabled() .orElse(false)); } /** * Creates a builder for {@link S3Utilities}. */ public static Builder builder() { return new Builder(); } // Used by low-level client @SdkInternalApi static S3Utilities create(SdkClientConfiguration clientConfiguration) { S3Utilities.Builder builder = builder() .region(clientConfiguration.option(AwsClientOption.AWS_REGION)) .s3Configuration((S3Configuration) clientConfiguration.option(SdkClientOption.SERVICE_CONFIGURATION)) .profileFile(clientConfiguration.option(SdkClientOption.PROFILE_FILE_SUPPLIER)) .profileName(clientConfiguration.option(SdkClientOption.PROFILE_NAME)); if (Boolean.TRUE.equals(clientConfiguration.option(SdkClientOption.ENDPOINT_OVERRIDDEN))) { builder.endpoint(clientConfiguration.option(SdkClientOption.ENDPOINT)); } return builder.build(); } /** * Returns the URL for an object stored in Amazon S3. * * If the object identified by the given bucket and key has public read permissions, * then this URL can be directly accessed to retrieve the object's data. * * <p> * If same configuration options are set on both #GetUrlRequest and #S3Utilities objects (for example: region), * the configuration set on the #GetUrlRequest takes precedence. * </p> * * <p> * This is a convenience which creates an instance of the {@link GetUrlRequest.Builder} avoiding the need to * create one manually via {@link GetUrlRequest#builder()} * </p> * * @param getUrlRequest A {@link Consumer} that will call methods on {@link GetUrlRequest.Builder} to create a request. * @return A URL for an object stored in Amazon S3. * @throws SdkException Generated Url is malformed */ public URL getUrl(Consumer<GetUrlRequest.Builder> getUrlRequest) { return getUrl(GetUrlRequest.builder().applyMutation(getUrlRequest).build()); } /** * Returns the URL for an object stored in Amazon S3. * * If the object identified by the given bucket and key has public read permissions, * then this URL can be directly accessed to retrieve the object's data. * * <p> * If same configuration options are set on both #GetUrlRequest and #S3Utilities objects (for example: region), * the configuration set on the #GetUrlRequest takes precedence. * </p> * * @param getUrlRequest request to construct url * @return A URL for an object stored in Amazon S3. * @throws SdkException Generated Url is malformed */ public URL getUrl(GetUrlRequest getUrlRequest) { Region resolvedRegion = resolveRegionForGetUrl(getUrlRequest); URI endpointOverride = getEndpointOverride(getUrlRequest); URI resolvedEndpoint = resolveEndpoint(endpointOverride, resolvedRegion); SdkHttpFullRequest marshalledRequest = createMarshalledRequest(getUrlRequest, resolvedEndpoint); GetObjectRequest getObjectRequest = GetObjectRequest.builder() .bucket(getUrlRequest.bucket()) .key(getUrlRequest.key()) .versionId(getUrlRequest.versionId()) .build(); InterceptorContext interceptorContext = InterceptorContext.builder() .httpRequest(marshalledRequest) .request(getObjectRequest) .build(); ExecutionAttributes executionAttributes = createExecutionAttributes(resolvedEndpoint, resolvedRegion, endpointOverride != null); SdkHttpRequest modifiedRequest = runInterceptors(interceptorContext, executionAttributes).httpRequest(); try { return modifiedRequest.getUri().toURL(); } catch (MalformedURLException exception) { throw SdkException.create("Generated URI is malformed: " + modifiedRequest.getUri(), exception); } } /** * Returns a parsed {@link S3Uri} with which a user can easily retrieve the bucket, key, region, style, and query * parameters of the URI. Only path-style and virtual-hosted-style URI parsing is supported, including CLI-style * URIs, e.g., "s3://bucket/key". AccessPoints and Outposts URI parsing is not supported. If you work with object keys * and/or query parameters with special characters, they must be URL-encoded, e.g., replace " " with "%20". If you work with * virtual-hosted-style URIs with bucket names that contain a dot, i.e., ".", the dot must not be URL-encoded. Encoded * buckets, keys, and query parameters will be returned decoded. * * <p> * For more information on path-style and virtual-hosted-style URIs, see <a href= * "https://docs.aws.amazon.com/AmazonS3/latest/userguide/access-bucket-intro.html" * >Methods for accessing a bucket</a>. * * @param uri The URI to be parsed * @return Parsed {@link S3Uri} * * <p><b>Example Usage</b> * <p> * {@snippet : * S3Client s3Client = S3Client.create(); * S3Utilities s3Utilities = s3Client.utilities(); * String uriString = "https://myBucket.s3.us-west-1.amazonaws.com/doc.txt?versionId=abc123"; * URI uri = URI.create(uriString); * S3Uri s3Uri = s3Utilities.parseUri(uri); * * String bucket = s3Uri.bucket().orElse(null); // "myBucket" * String key = s3Uri.key().orElse(null); // "doc.txt" * Region region = s3Uri.region().orElse(null); // Region.US_WEST_1 * boolean isPathStyle = s3Uri.isPathStyle(); // false * String versionId = s3Uri.firstMatchingRawQueryParameter("versionId").orElse(null); // "abc123" *} */ public S3Uri parseUri(URI uri) { validateUri(uri); if ("s3".equalsIgnoreCase(uri.getScheme())) { return parseAwsCliStyleUri(uri); } return parseStandardUri(uri); } private S3Uri parseStandardUri(URI uri) { if (uri.getHost() == null) { throw new IllegalArgumentException("Invalid S3 URI: no hostname: " + uri); } Matcher matcher = ENDPOINT_PATTERN.matcher(uri.getHost()); if (!matcher.find()) { throw new IllegalArgumentException("Invalid S3 URI: hostname does not appear to be a valid S3 endpoint: " + uri); } S3Uri.Builder builder = S3Uri.builder().uri(uri); addRegionIfNeeded(builder, matcher.group(2)); addQueryParamsIfNeeded(builder, uri); String prefix = matcher.group(1); if (StringUtils.isEmpty(prefix)) { return parsePathStyleUri(builder, uri); } return parseVirtualHostedStyleUri(builder, uri, matcher); } private S3Uri.Builder addRegionIfNeeded(S3Uri.Builder builder, String region) { if (!"amazonaws".equals(region)) { return builder.region(Region.of(region)); } return builder; } private S3Uri.Builder addQueryParamsIfNeeded(S3Uri.Builder builder, URI uri) { if (uri.getQuery() != null) { return builder.queryParams(SdkHttpUtils.uriParams(uri)); } return builder; } private S3Uri parsePathStyleUri(S3Uri.Builder builder, URI uri) { String bucket = null; String key = null; String path = uri.getPath(); if (!StringUtils.isEmpty(path) && !"/".equals(path)) { int index = path.indexOf('/', 1); if (index == -1) { // No trailing slash, e.g., "https://s3.amazonaws.com/bucket" bucket = path.substring(1); } else { bucket = path.substring(1, index); if (index != path.length() - 1) { key = path.substring(index + 1); } } } return builder.key(key) .bucket(bucket) .isPathStyle(true) .build(); } private S3Uri parseVirtualHostedStyleUri(S3Uri.Builder builder, URI uri, Matcher matcher) { String bucket; String key = null; String path = uri.getPath(); String prefix = matcher.group(1); bucket = prefix.substring(0, prefix.length() - 1); if (!StringUtils.isEmpty(path) && !"/".equals(path)) { key = path.substring(1); } return builder.key(key) .bucket(bucket) .build(); } private S3Uri parseAwsCliStyleUri(URI uri) { String key = null; String bucket = uri.getAuthority(); Region region = null; boolean isPathStyle = false; Map<String, List<String>> queryParams = new HashMap<>(); String path = uri.getPath(); if (bucket == null) { throw new IllegalArgumentException("Invalid S3 URI: bucket not included: " + uri); } if (path.length() > 1) { key = path.substring(1); } return S3Uri.builder() .uri(uri) .bucket(bucket) .key(key) .region(region) .isPathStyle(isPathStyle) .queryParams(queryParams) .build(); } private void validateUri(URI uri) { Validate.paramNotNull(uri, "uri"); if (uri.toString().contains(".s3-accesspoint")) { throw new IllegalArgumentException("AccessPoints URI parsing is not supported: " + uri); } if (uri.toString().contains(".s3-outposts")) { throw new IllegalArgumentException("Outposts URI parsing is not supported: " + uri); } } private Region resolveRegionForGetUrl(GetUrlRequest getUrlRequest) { if (getUrlRequest.region() == null && this.region == null) { throw new IllegalArgumentException("Region should be provided either in GetUrlRequest object or S3Utilities object"); } return getUrlRequest.region() != null ? getUrlRequest.region() : this.region; } /** * If endpoint is not present, construct a default endpoint using the region information. */ private URI resolveEndpoint(URI overrideEndpoint, Region region) { return overrideEndpoint != null ? overrideEndpoint : new DefaultServiceEndpointBuilder("s3", "https").withRegion(region) .withProfileFile(profileFile) .withProfileName(profileName) .withDualstackEnabled(s3Configuration.dualstackEnabled()) .withFipsEnabled(fipsEnabled) .getServiceEndpoint(); } private URI getEndpointOverride(GetUrlRequest request) { URI requestOverrideEndpoint = request.endpoint(); return requestOverrideEndpoint != null ? requestOverrideEndpoint : endpoint; } /** * Create a {@link SdkHttpFullRequest} object with the bucket and key values marshalled into the path params. */ private SdkHttpFullRequest createMarshalledRequest(GetUrlRequest getUrlRequest, URI endpoint) { OperationInfo operationInfo = OperationInfo.builder() .requestUri("/{Key+}") .httpMethod(SdkHttpMethod.HEAD) .build(); SdkHttpFullRequest.Builder builder = ProtocolUtils.createSdkHttpRequest(operationInfo, endpoint); // encode bucket builder.encodedPath(PathMarshaller.NON_GREEDY.marshall(builder.encodedPath(), "Bucket", getUrlRequest.bucket())); // encode key builder.encodedPath(PathMarshaller.GREEDY.marshall(builder.encodedPath(), "Key", getUrlRequest.key())); if (getUrlRequest.versionId() != null) { builder.appendRawQueryParameter("versionId", getUrlRequest.versionId()); } return builder.build(); } /** * Create the execution attributes to provide to the endpoint interceptors. * @return */ private ExecutionAttributes createExecutionAttributes(URI clientEndpoint, Region region, boolean isEndpointOverridden) { ExecutionAttributes executionAttributes = new ExecutionAttributes() .putAttribute(AwsExecutionAttribute.AWS_REGION, region) .putAttribute(SdkExecutionAttribute.CLIENT_TYPE, ClientType.SYNC) .putAttribute(SdkExecutionAttribute.SERVICE_NAME, SERVICE_NAME) .putAttribute(SdkExecutionAttribute.OPERATION_NAME, "GetObject") .putAttribute(SdkExecutionAttribute.SERVICE_CONFIG, s3Configuration) .putAttribute(AwsExecutionAttribute.FIPS_ENDPOINT_ENABLED, fipsEnabled) .putAttribute(AwsExecutionAttribute.DUALSTACK_ENDPOINT_ENABLED, s3Configuration.dualstackEnabled()) .putAttribute(SdkInternalExecutionAttribute.ENDPOINT_PROVIDER, S3EndpointProvider.defaultProvider()) .putAttribute(SdkInternalExecutionAttribute.CLIENT_CONTEXT_PARAMS, createClientContextParams()) .putAttribute(SdkExecutionAttribute.CLIENT_ENDPOINT, clientEndpoint) .putAttribute(AwsExecutionAttribute.USE_GLOBAL_ENDPOINT, useGlobalEndpointResolver.resolve(region)); if (isEndpointOverridden) { executionAttributes.putAttribute(SdkExecutionAttribute.ENDPOINT_OVERRIDDEN, true); } return executionAttributes; } private AttributeMap createClientContextParams() { AttributeMap.Builder params = AttributeMap.builder(); params.put(S3ClientContextParams.USE_ARN_REGION, s3Configuration.useArnRegionEnabled()); params.put(S3ClientContextParams.DISABLE_MULTI_REGION_ACCESS_POINTS, !s3Configuration.multiRegionEnabled()); params.put(S3ClientContextParams.FORCE_PATH_STYLE, s3Configuration.pathStyleAccessEnabled()); params.put(S3ClientContextParams.ACCELERATE, s3Configuration.accelerateModeEnabled()); return params.build(); } private InterceptorContext runInterceptors(InterceptorContext context, ExecutionAttributes executionAttributes) { context = interceptorChain.modifyRequest(context, executionAttributes); return interceptorChain.modifyHttpRequestAndHttpContent(context, executionAttributes); } private ExecutionInterceptorChain createEndpointInterceptorChain() { List<ExecutionInterceptor> interceptors = new ArrayList<>(); interceptors.add(new S3ResolveEndpointInterceptor()); interceptors.add(new S3RequestSetEndpointInterceptor()); return new ExecutionInterceptorChain(interceptors); } private UseGlobalEndpointResolver createUseGlobalEndpointResolver() { String standardOption = DefaultsModeConfiguration.defaultConfig(DefaultsMode.LEGACY) .get(ServiceMetadataAdvancedOption.DEFAULT_S3_US_EAST_1_REGIONAL_ENDPOINT); SdkClientConfiguration config = SdkClientConfiguration.builder() .option(ServiceMetadataAdvancedOption.DEFAULT_S3_US_EAST_1_REGIONAL_ENDPOINT, standardOption) .option(SdkClientOption.PROFILE_FILE_SUPPLIER, profileFile) .option(SdkClientOption.PROFILE_NAME, profileName) .build(); return new UseGlobalEndpointResolver(config); } /** * Builder class to construct {@link S3Utilities} object */ public static final class Builder { private Region region; private URI endpoint; private S3Configuration s3Configuration; private Supplier<ProfileFile> profileFile; private String profileName; private Boolean dualstackEnabled; private Boolean fipsEnabled; private Builder() { } /** * The default region to use when working with the methods in {@link S3Utilities} class. * * There can be methods in {@link S3Utilities} that don't need the region info. * In that case, this option will be ignored when using those methods. * * @return This object for method chaining */ public Builder region(Region region) { this.region = region; return this; } /** * The default endpoint to use when working with the methods in {@link S3Utilities} class. * * There can be methods in {@link S3Utilities} that don't need the endpoint info. * In that case, this option will be ignored when using those methods. * * @return This object for method chaining */ public Builder endpoint(URI endpoint) { this.endpoint = endpoint; return this; } /** * Configure whether the SDK should use the AWS dualstack endpoint. * * <p>If this is not specified, the SDK will attempt to determine whether the dualstack endpoint should be used * automatically using the following logic: * <ol> * <li>Check the 'aws.useDualstackEndpoint' system property for 'true' or 'false'.</li> * <li>Check the 'AWS_USE_DUALSTACK_ENDPOINT' environment variable for 'true' or 'false'.</li> * <li>Check the {user.home}/.aws/credentials and {user.home}/.aws/config files for the 'use_dualstack_endpoint' * property set to 'true' or 'false'.</li> * </ol> * * <p>If the setting is not found in any of the locations above, 'false' will be used. */ public Builder dualstackEnabled(Boolean dualstackEnabled) { this.dualstackEnabled = dualstackEnabled; return this; } /** * Configure whether the SDK should use the AWS fips endpoint. * * <p>If this is not specified, the SDK will attempt to determine whether the fips endpoint should be used * automatically using the following logic: * <ol> * <li>Check the 'aws.useFipsEndpoint' system property for 'true' or 'false'.</li> * <li>Check the 'AWS_USE_FIPS_ENDPOINT' environment variable for 'true' or 'false'.</li> * <li>Check the {user.home}/.aws/credentials and {user.home}/.aws/config files for the 'use_fips_endpoint' * property set to 'true' or 'false'.</li> * </ol> * * <p>If the setting is not found in any of the locations above, 'false' will be used. */ public Builder fipsEnabled(Boolean fipsEnabled) { this.fipsEnabled = fipsEnabled; return this; } /** * Sets the S3 configuration to enable options like path style access, dual stack, accelerate mode etc. * * There can be methods in {@link S3Utilities} that don't need the region info. * In that case, this option will be ignored when using those methods. * * @return This object for method chaining */ public Builder s3Configuration(S3Configuration s3Configuration) { this.s3Configuration = s3Configuration; return this; } /** * The profile file from the {@link ClientOverrideConfiguration#defaultProfileFile()}. This is private and only used * when the utilities is created via {@link S3Client#utilities()}. This is not currently public because it may be less * confusing to support the full {@link ClientOverrideConfiguration} object in the future. */ private Builder profileFile(Supplier<ProfileFile> profileFileSupplier) { this.profileFile = profileFileSupplier; return this; } /** * The profile name from the {@link ClientOverrideConfiguration#defaultProfileFile()}. This is private and only used * when the utilities is created via {@link S3Client#utilities()}. This is not currently public because it may be less * confusing to support the full {@link ClientOverrideConfiguration} object in the future. */ private Builder profileName(String profileName) { this.profileName = profileName; return this; } /** * Construct a {@link S3Utilities} object. */ public S3Utilities build() { return new S3Utilities(this); } } }
4,807
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/FieldWithDefault.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.utils.Lazy; /** * A helper class for setting a field's value to a default if it isn't specified, while still keeping track of whether the value * was from the default or from the field. * * For example, a "profile name" field-with-default might be set to "null" with a default of "foo". {@link #value()} returns * "foo", while {@link #isDefault()} can be used to keep track of the fact that the value was from the default. */ @SdkInternalApi public abstract class FieldWithDefault<T> { private FieldWithDefault() { } /** * Create a {@link FieldWithDefault} using the provided field and its default value. If the field is null, the default value * will be returned by {@link #value()} and {@link #isDefault()} will return true. If the field is not null, the field value * will be returned by {@link #value()} and {@link #isDefault()} will return false. * * @see #createLazy(Object, Supplier) */ public static <T> FieldWithDefault<T> create(T field, T defaultValue) { return new Impl<>(field, defaultValue); } /** * Create a {@link FieldWithDefault} using the provided field and its default value. If the field is null, the default value * will be returned by {@link #value()} and {@link #isDefault()} will return true. If the field is not null, the field value * will be returned by {@link #value()} and {@link #isDefault()} will return false. * * <p>This differs from {@link #create(Object, Object)} in that the default value won't be resolved if the provided field is * not null. The default value also won't be resolved until the first {@link #value()} call. This is useful for delaying * expensive calculations until right before they're needed. */ public static <T> FieldWithDefault<T> createLazy(T field, Supplier<T> defaultValue) { return new LazyImpl<>(field, defaultValue); } /** * Retrieve the value of this field. */ public abstract T value(); /** * True, if the value returned by {@link #value()} is the default value (i.e. the field is null). False otherwise. */ public abstract boolean isDefault(); /** * Return the field exactly as it was specified when the field-with-default was created. If the field was null, this will * return null. This will not resolve the default if this is a field from {@link #createLazy(Object, Supplier)}. */ public abstract T valueOrNullIfDefault(); private static class Impl<T> extends FieldWithDefault<T> { private final T value; private final boolean isDefault; private Impl(T field, T defaultValue) { this.value = field != null ? field : defaultValue; this.isDefault = field == null; } @Override public T value() { return value; } @Override public boolean isDefault() { return isDefault; } @Override public T valueOrNullIfDefault() { return isDefault ? null : value; } } private static class LazyImpl<T> extends FieldWithDefault<T> { private final Lazy<T> value; private final boolean isDefault; private LazyImpl(T field, Supplier<T> defaultValue) { this.value = field != null ? new Lazy<>(() -> field) : new Lazy<>(defaultValue); this.isDefault = field == null; } @Override public T value() { return value.getValue(); } @Override public boolean isDefault() { return isDefault; } @Override public T valueOrNullIfDefault() { return isDefault ? null : value.getValue(); } } }
4,808
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/ConfiguredS3SdkHttpRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal; import java.util.Optional; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; @SdkInternalApi public class ConfiguredS3SdkHttpRequest implements ToCopyableBuilder<ConfiguredS3SdkHttpRequest.Builder, ConfiguredS3SdkHttpRequest> { private final SdkHttpRequest sdkHttpRequest; private final Region signingRegionModification; private final String signingServiceModification; private ConfiguredS3SdkHttpRequest(Builder builder) { this.sdkHttpRequest = Validate.notNull(builder.sdkHttpRequest, "sdkHttpRequest"); this.signingRegionModification = builder.signingRegionModification; this.signingServiceModification = builder.signingServiceModification; } public static Builder builder() { return new Builder(); } public SdkHttpRequest sdkHttpRequest() { return sdkHttpRequest; } public Optional<Region> signingRegionModification() { return Optional.ofNullable(signingRegionModification); } public Optional<String> signingServiceModification() { return Optional.ofNullable(signingServiceModification); } @Override public Builder toBuilder() { return builder().sdkHttpRequest(sdkHttpRequest) .signingRegionModification(signingRegionModification) .signingServiceModification(signingServiceModification); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ConfiguredS3SdkHttpRequest that = (ConfiguredS3SdkHttpRequest) o; if (!sdkHttpRequest.equals(that.sdkHttpRequest)) { return false; } if (signingRegionModification != null ? !signingRegionModification.equals(that.signingRegionModification) : that.signingRegionModification != null) { return false; } return signingServiceModification != null ? signingServiceModification.equals(that.signingServiceModification) : that.signingServiceModification == null; } @Override public int hashCode() { int result = sdkHttpRequest.hashCode(); result = 31 * result + (signingRegionModification != null ? signingRegionModification.hashCode() : 0); result = 31 * result + (signingServiceModification != null ? signingServiceModification.hashCode() : 0); return result; } public static class Builder implements CopyableBuilder<Builder, ConfiguredS3SdkHttpRequest> { private String signingServiceModification; private SdkHttpRequest sdkHttpRequest; private Region signingRegionModification; private Builder() { } public Builder sdkHttpRequest(SdkHttpRequest sdkHttpRequest) { this.sdkHttpRequest = sdkHttpRequest; return this; } public Builder signingRegionModification(Region signingRegionModification) { this.signingRegionModification = signingRegionModification; return this; } public Builder signingServiceModification(String signingServiceModification) { this.signingServiceModification = signingServiceModification; return this; } @Override public ConfiguredS3SdkHttpRequest build() { return new ConfiguredS3SdkHttpRequest(this); } } }
4,809
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/BucketUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal; import java.util.regex.Pattern; import software.amazon.awssdk.annotations.SdkInternalApi; /** * Utilities for working with Amazon S3 bucket names, such as validation and * checked to see if they are compatible with DNS addressing. */ @SdkInternalApi public final class BucketUtils { private static final int MIN_BUCKET_NAME_LENGTH = 3; private static final int MAX_BUCKET_NAME_LENGTH = 63; private static final Pattern IP_ADDRESS_PATTERN = Pattern.compile("(\\d+\\.){3}\\d+"); private BucketUtils() { } /** * Validates that the specified bucket name is valid for Amazon S3 V2 naming * (i.e. DNS addressable in virtual host style). Throws an * IllegalArgumentException if the bucket name is not valid. * <p> * S3 bucket naming guidelines are specified in * <a href="http://docs.amazonwebservices.com/AmazonS3/latest/dev/index.html?BucketRestrictions.html" * > http://docs.amazonwebservices.com/AmazonS3/latest/dev/index.html? * BucketRestrictions.html</a> * * @param bucketName The bucket name to validate. * @throws IllegalArgumentException If the specified bucket name doesn't follow Amazon S3's * guidelines. */ public static boolean isValidDnsBucketName(final String bucketName, final boolean throwOnError) { if (bucketName == null) { return exception(throwOnError, "Bucket name cannot be null"); } if (bucketName.length() < MIN_BUCKET_NAME_LENGTH || bucketName.length() > MAX_BUCKET_NAME_LENGTH) { return exception( throwOnError, "Bucket name should be between " + MIN_BUCKET_NAME_LENGTH + " and " + MAX_BUCKET_NAME_LENGTH + " characters long" ); } if (IP_ADDRESS_PATTERN.matcher(bucketName).matches()) { return exception( throwOnError, "Bucket name must not be formatted as an IP Address" ); } char previous = '\0'; for (int i = 0; i < bucketName.length(); ++i) { char next = bucketName.charAt(i); if (next >= 'A' && next <= 'Z') { return exception( throwOnError, "Bucket name should not contain uppercase characters" ); } if (next == ' ' || next == '\t' || next == '\r' || next == '\n') { return exception( throwOnError, "Bucket name should not contain white space" ); } if (next == '.') { if (previous == '\0') { return exception( throwOnError, "Bucket name should not begin with a period" ); } if (previous == '.') { return exception( throwOnError, "Bucket name should not contain two adjacent periods" ); } if (previous == '-') { return exception( throwOnError, "Bucket name should not contain dashes next to periods" ); } } else if (next == '-') { if (previous == '.') { return exception( throwOnError, "Bucket name should not contain dashes next to periods" ); } if (previous == '\0') { return exception( throwOnError, "Bucket name should not begin with a '-'" ); } } else if ((next < '0') || (next > '9' && next < 'a') || (next > 'z')) { return exception( throwOnError, "Bucket name should not contain '" + next + "'" ); } previous = next; } if (previous == '.' || previous == '-') { return exception( throwOnError, "Bucket name should not end with '-' or '.'" ); } return true; } /** * Validates if the given bucket name follows naming guidelines that are acceptable for using * virtual host style addressing. * * @param bucketName The bucket name to validate. * @param throwOnError boolean to decide if an error should be thrown if the bucket name doesn't follow the naming convention */ public static boolean isVirtualAddressingCompatibleBucketName(final String bucketName, final boolean throwOnError) { return isValidDnsBucketName(bucketName, throwOnError) && !bucketName.contains("."); } /** * If 'exception' is true, throw an IllegalArgumentException with the given * message. Otherwise, silently return false. * * @param exception true to throw an exception * @param message the message for the exception * @return false if 'exception' is false */ private static boolean exception(final boolean exception, final String message) { if (exception) { throw new IllegalArgumentException(message); } return false; } }
4,810
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/TaggingAdapter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.adapter.TypeAdapter; import software.amazon.awssdk.services.s3.model.Tag; import software.amazon.awssdk.services.s3.model.Tagging; import software.amazon.awssdk.utils.http.SdkHttpUtils; /** * {@link TypeAdapter} that converts the {@link Tagging} modeled object into a * URL encoded map of key to values. Used for Put and Copy object operations * which models the Tagging as a string. */ @SdkInternalApi public final class TaggingAdapter implements TypeAdapter<Tagging, String> { private static final TaggingAdapter INSTANCE = new TaggingAdapter(); private TaggingAdapter() { } @Override public String adapt(Tagging tagging) { StringBuilder tagBuilder = new StringBuilder(); if (tagging != null && !tagging.tagSet().isEmpty()) { Tagging taggingClone = tagging.toBuilder().build(); Tag firstTag = taggingClone.tagSet().get(0); tagBuilder.append(SdkHttpUtils.urlEncode(firstTag.key())); tagBuilder.append("="); tagBuilder.append(SdkHttpUtils.urlEncode(firstTag.value())); for (int i = 1; i < taggingClone.tagSet().size(); i++) { Tag t = taggingClone.tagSet().get(i); tagBuilder.append("&"); tagBuilder.append(SdkHttpUtils.urlEncode(t.key())); tagBuilder.append("="); tagBuilder.append(SdkHttpUtils.urlEncode(t.value())); } } return tagBuilder.toString(); } /** * @return Singleton instance of {@link TaggingAdapter}. */ public static TaggingAdapter instance() { return INSTANCE; } }
4,811
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/signing/DefaultS3Presigner.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.signing; import static java.util.stream.Collectors.toMap; import static software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute.PRESIGNER_EXPIRATION; import static software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME; import static software.amazon.awssdk.utils.CollectionUtils.mergeLists; import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely; import java.net.URI; import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.time.ZoneOffset; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.function.Function; import java.util.stream.Stream; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute; import software.amazon.awssdk.awscore.AwsExecutionAttribute; import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration; import software.amazon.awssdk.awscore.client.builder.AwsDefaultClientBuilder; import software.amazon.awssdk.awscore.defaultsmode.DefaultsMode; import software.amazon.awssdk.awscore.endpoint.DefaultServiceEndpointBuilder; import software.amazon.awssdk.awscore.internal.AwsExecutionContextBuilder; import software.amazon.awssdk.awscore.internal.defaultsmode.DefaultsModeConfiguration; import software.amazon.awssdk.awscore.presigner.PresignRequest; import software.amazon.awssdk.awscore.presigner.PresignedRequest; import software.amazon.awssdk.core.ClientType; import software.amazon.awssdk.core.RequestOverrideConfiguration; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.SelectedAuthScheme; import software.amazon.awssdk.core.client.builder.SdkDefaultClientBuilder; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.client.config.SdkClientOption; import software.amazon.awssdk.core.http.ExecutionContext; import software.amazon.awssdk.core.interceptor.ClasspathInterceptorChainFactory; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.core.interceptor.ExecutionInterceptorChain; import software.amazon.awssdk.core.interceptor.InterceptorContext; import software.amazon.awssdk.core.interceptor.SdkExecutionAttribute; import software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute; import software.amazon.awssdk.core.signer.Presigner; import software.amazon.awssdk.core.signer.Signer; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.http.ContentStreamProvider; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.http.auth.aws.scheme.AwsV4AuthScheme; import software.amazon.awssdk.http.auth.aws.scheme.AwsV4aAuthScheme; import software.amazon.awssdk.http.auth.aws.signer.AwsV4FamilyHttpSigner; import software.amazon.awssdk.http.auth.spi.scheme.AuthScheme; import software.amazon.awssdk.http.auth.spi.scheme.AuthSchemeOption; import software.amazon.awssdk.http.auth.spi.signer.HttpSigner; import software.amazon.awssdk.http.auth.spi.signer.SignRequest; import software.amazon.awssdk.http.auth.spi.signer.SignedRequest; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.identity.spi.Identity; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.identity.spi.IdentityProviders; import software.amazon.awssdk.protocols.xml.AwsS3ProtocolFactory; import software.amazon.awssdk.regions.ServiceMetadataAdvancedOption; import software.amazon.awssdk.services.s3.S3Configuration; import software.amazon.awssdk.services.s3.auth.scheme.S3AuthSchemeProvider; import software.amazon.awssdk.services.s3.auth.scheme.internal.S3AuthSchemeInterceptor; import software.amazon.awssdk.services.s3.endpoints.S3ClientContextParams; import software.amazon.awssdk.services.s3.endpoints.S3EndpointProvider; import software.amazon.awssdk.services.s3.endpoints.internal.S3RequestSetEndpointInterceptor; import software.amazon.awssdk.services.s3.endpoints.internal.S3ResolveEndpointInterceptor; import software.amazon.awssdk.services.s3.internal.endpoints.UseGlobalEndpointResolver; import software.amazon.awssdk.services.s3.model.AbortMultipartUploadRequest; import software.amazon.awssdk.services.s3.model.CompleteMultipartUploadRequest; import software.amazon.awssdk.services.s3.model.CreateMultipartUploadRequest; import software.amazon.awssdk.services.s3.model.DeleteObjectRequest; import software.amazon.awssdk.services.s3.model.GetObjectRequest; import software.amazon.awssdk.services.s3.model.PutObjectRequest; import software.amazon.awssdk.services.s3.model.UploadPartRequest; import software.amazon.awssdk.services.s3.presigner.S3Presigner; import software.amazon.awssdk.services.s3.presigner.model.AbortMultipartUploadPresignRequest; import software.amazon.awssdk.services.s3.presigner.model.CompleteMultipartUploadPresignRequest; import software.amazon.awssdk.services.s3.presigner.model.CreateMultipartUploadPresignRequest; import software.amazon.awssdk.services.s3.presigner.model.DeleteObjectPresignRequest; import software.amazon.awssdk.services.s3.presigner.model.GetObjectPresignRequest; import software.amazon.awssdk.services.s3.presigner.model.PresignedAbortMultipartUploadRequest; import software.amazon.awssdk.services.s3.presigner.model.PresignedCompleteMultipartUploadRequest; import software.amazon.awssdk.services.s3.presigner.model.PresignedCreateMultipartUploadRequest; import software.amazon.awssdk.services.s3.presigner.model.PresignedDeleteObjectRequest; import software.amazon.awssdk.services.s3.presigner.model.PresignedGetObjectRequest; import software.amazon.awssdk.services.s3.presigner.model.PresignedPutObjectRequest; import software.amazon.awssdk.services.s3.presigner.model.PresignedUploadPartRequest; import software.amazon.awssdk.services.s3.presigner.model.PutObjectPresignRequest; import software.amazon.awssdk.services.s3.presigner.model.UploadPartPresignRequest; import software.amazon.awssdk.services.s3.transform.AbortMultipartUploadRequestMarshaller; import software.amazon.awssdk.services.s3.transform.CompleteMultipartUploadRequestMarshaller; import software.amazon.awssdk.services.s3.transform.CreateMultipartUploadRequestMarshaller; import software.amazon.awssdk.services.s3.transform.DeleteObjectRequestMarshaller; import software.amazon.awssdk.services.s3.transform.GetObjectRequestMarshaller; import software.amazon.awssdk.services.s3.transform.PutObjectRequestMarshaller; import software.amazon.awssdk.services.s3.transform.UploadPartRequestMarshaller; import software.amazon.awssdk.utils.AttributeMap; import software.amazon.awssdk.utils.CompletableFutureUtils; import software.amazon.awssdk.utils.IoUtils; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Validate; /** * The default implementation of the {@link S3Presigner} interface. */ @SdkInternalApi public final class DefaultS3Presigner extends DefaultSdkPresigner implements S3Presigner { private static final Logger log = Logger.loggerFor(DefaultS3Presigner.class); private static final String SERVICE_NAME = "s3"; private static final String SIGNING_NAME = "s3"; private final S3Configuration serviceConfiguration; private final List<ExecutionInterceptor> clientInterceptors; private final GetObjectRequestMarshaller getObjectRequestMarshaller; private final PutObjectRequestMarshaller putObjectRequestMarshaller; private final CreateMultipartUploadRequestMarshaller createMultipartUploadRequestMarshaller; private final UploadPartRequestMarshaller uploadPartRequestMarshaller; private final DeleteObjectRequestMarshaller deleteObjectRequestMarshaller; private final CompleteMultipartUploadRequestMarshaller completeMultipartUploadRequestMarshaller; private final AbortMultipartUploadRequestMarshaller abortMultipartUploadRequestMarshaller; private final SdkClientConfiguration clientConfiguration; private final AttributeMap clientContextParams; private final UseGlobalEndpointResolver useGlobalEndpointResolver; private DefaultS3Presigner(Builder b) { super(b); S3Configuration serviceConfiguration = b.serviceConfiguration != null ? b.serviceConfiguration : S3Configuration.builder() .profileFile(profileFileSupplier()) .profileName(profileName()) .checksumValidationEnabled(false) .build(); S3Configuration.Builder serviceConfigBuilder = serviceConfiguration.toBuilder(); if (serviceConfiguration.checksumValidationEnabled()) { log.debug(() -> "The provided S3Configuration has ChecksumValidationEnabled set to true. Please note that " + "the pre-signed request can't be executed using a web browser if checksum validation is enabled."); } if (dualstackEnabled() != null && serviceConfigBuilder.dualstackEnabled() != null) { throw new IllegalStateException("Dualstack has been configured in both S3Configuration and at the " + "presigner/global level. Please limit dualstack configuration to one location."); } if (dualstackEnabled() != null) { serviceConfigBuilder.dualstackEnabled(dualstackEnabled()); } this.serviceConfiguration = serviceConfigBuilder.build(); this.clientInterceptors = initializeInterceptors(); this.clientConfiguration = createClientConfiguration(); // Copied from DefaultS3Client#init AwsS3ProtocolFactory protocolFactory = AwsS3ProtocolFactory.builder() .clientConfiguration(clientConfiguration) .build(); // Copied from DefaultS3Client#getObject this.getObjectRequestMarshaller = new GetObjectRequestMarshaller(protocolFactory); // Copied from DefaultS3Client#putObject this.putObjectRequestMarshaller = new PutObjectRequestMarshaller(protocolFactory); // Copied from DefaultS3Client#createMultipartUpload this.createMultipartUploadRequestMarshaller = new CreateMultipartUploadRequestMarshaller(protocolFactory); // Copied from DefaultS3Client#uploadPart this.uploadPartRequestMarshaller = new UploadPartRequestMarshaller(protocolFactory); // Copied from DefaultS3Client#deleteObject this.deleteObjectRequestMarshaller = new DeleteObjectRequestMarshaller(protocolFactory); // Copied from DefaultS3Client#completeMultipartUpload this.completeMultipartUploadRequestMarshaller = new CompleteMultipartUploadRequestMarshaller(protocolFactory); // Copied from DefaultS3Client#abortMultipartUpload this.abortMultipartUploadRequestMarshaller = new AbortMultipartUploadRequestMarshaller(protocolFactory); this.clientContextParams = createClientContextParams(); this.useGlobalEndpointResolver = createUseGlobalEndpointResolver(); } public static S3Presigner.Builder builder() { return new Builder(); } /** * Copied from {@code DefaultS3BaseClientBuilder} and {@link SdkDefaultClientBuilder}. */ private List<ExecutionInterceptor> initializeInterceptors() { ClasspathInterceptorChainFactory interceptorFactory = new ClasspathInterceptorChainFactory(); List<ExecutionInterceptor> s3Interceptors = interceptorFactory.getInterceptors("software/amazon/awssdk/services/s3/execution.interceptors"); List<ExecutionInterceptor> additionalInterceptors = new ArrayList<>(); additionalInterceptors.add(new S3AuthSchemeInterceptor()); additionalInterceptors.add(new S3ResolveEndpointInterceptor()); additionalInterceptors.add(new S3RequestSetEndpointInterceptor()); s3Interceptors = mergeLists(s3Interceptors, additionalInterceptors); return mergeLists(interceptorFactory.getGlobalInterceptors(), s3Interceptors); } /** * Copied from {@link AwsDefaultClientBuilder}. */ private SdkClientConfiguration createClientConfiguration() { if (endpointOverride() != null) { return SdkClientConfiguration.builder() .option(SdkClientOption.ENDPOINT, endpointOverride()) .option(SdkClientOption.ENDPOINT_OVERRIDDEN, true) .build(); } else { URI defaultEndpoint = new DefaultServiceEndpointBuilder(SERVICE_NAME, "https") .withRegion(region()) .withProfileFile(profileFileSupplier()) .withProfileName(profileName()) .withDualstackEnabled(serviceConfiguration.dualstackEnabled()) .withFipsEnabled(fipsEnabled()) .getServiceEndpoint(); return SdkClientConfiguration.builder() .option(SdkClientOption.ENDPOINT, defaultEndpoint) .build(); } } @Override public PresignedGetObjectRequest presignGetObject(GetObjectPresignRequest request) { return presign(PresignedGetObjectRequest.builder(), request, request.getObjectRequest(), GetObjectRequest.class, getObjectRequestMarshaller::marshall, "GetObject") .build(); } @Override public PresignedPutObjectRequest presignPutObject(PutObjectPresignRequest request) { return presign(PresignedPutObjectRequest.builder(), request, request.putObjectRequest(), PutObjectRequest.class, putObjectRequestMarshaller::marshall, "PutObject") .build(); } @Override public PresignedDeleteObjectRequest presignDeleteObject(DeleteObjectPresignRequest request) { return presign(PresignedDeleteObjectRequest.builder(), request, request.deleteObjectRequest(), DeleteObjectRequest.class, deleteObjectRequestMarshaller::marshall, "DeleteObject") .build(); } @Override public PresignedCreateMultipartUploadRequest presignCreateMultipartUpload(CreateMultipartUploadPresignRequest request) { return presign(PresignedCreateMultipartUploadRequest.builder(), request, request.createMultipartUploadRequest(), CreateMultipartUploadRequest.class, createMultipartUploadRequestMarshaller::marshall, "CreateMultipartUpload") .build(); } @Override public PresignedUploadPartRequest presignUploadPart(UploadPartPresignRequest request) { return presign(PresignedUploadPartRequest.builder(), request, request.uploadPartRequest(), UploadPartRequest.class, uploadPartRequestMarshaller::marshall, "UploadPart") .build(); } @Override public PresignedCompleteMultipartUploadRequest presignCompleteMultipartUpload(CompleteMultipartUploadPresignRequest request) { return presign(PresignedCompleteMultipartUploadRequest.builder(), request, request.completeMultipartUploadRequest(), CompleteMultipartUploadRequest.class, completeMultipartUploadRequestMarshaller::marshall, "CompleteMultipartUpload") .build(); } @Override public PresignedAbortMultipartUploadRequest presignAbortMultipartUpload(AbortMultipartUploadPresignRequest request) { return presign(PresignedAbortMultipartUploadRequest.builder(), request, request.abortMultipartUploadRequest(), AbortMultipartUploadRequest.class, abortMultipartUploadRequestMarshaller::marshall, "AbortMultipartUpload") .build(); } protected S3Configuration serviceConfiguration() { return serviceConfiguration; } /** * Generate a {@link PresignedRequest} from a {@link PresignedRequest} and {@link SdkRequest}. */ private <T extends PresignedRequest.Builder, U> T presign(T presignedRequest, PresignRequest presignRequest, SdkRequest requestToPresign, Class<U> requestToPresignType, Function<U, SdkHttpFullRequest> requestMarshaller, String operationName) { // A fixed signingClock is used, so that the current time used by the signing logic, as well as to determine expiration // are the same. Instant signingInstant = Instant.now(); Clock signingClock = Clock.fixed(signingInstant, ZoneOffset.UTC); Duration expirationDuration = presignRequest.signatureDuration(); Instant expiration = signingInstant.plus(expirationDuration); ExecutionContext execCtx = invokeInterceptorsAndCreateExecutionContext(presignRequest, requestToPresign, operationName, expiration); callBeforeMarshallingHooks(execCtx); marshalRequestAndUpdateContext(execCtx, requestToPresignType, requestMarshaller); callAfterMarshallingHooks(execCtx); addRequestLevelHeadersAndQueryParameters(execCtx); callModifyHttpRequestHooksAndUpdateContext(execCtx); SdkHttpFullRequest httpRequest = getHttpFullRequest(execCtx); SdkHttpFullRequest signedHttpRequest = execCtx.signer() != null ? presignRequest(execCtx, httpRequest) : sraPresignRequest(execCtx, httpRequest, signingClock, expirationDuration); initializePresignedRequest(presignedRequest, execCtx, signedHttpRequest, expiration); return presignedRequest; } /** * Creates an execution context from the provided request information. */ private ExecutionContext invokeInterceptorsAndCreateExecutionContext(PresignRequest presignRequest, SdkRequest sdkRequest, String operationName, Instant expiration) { ExecutionAttributes executionAttributes = new ExecutionAttributes() .putAttribute(AwsSignerExecutionAttribute.SERVICE_SIGNING_NAME, SIGNING_NAME) .putAttribute(AwsExecutionAttribute.AWS_REGION, region()) .putAttribute(AwsSignerExecutionAttribute.SIGNING_REGION, region()) .putAttribute(SdkInternalExecutionAttribute.IS_FULL_DUPLEX, false) .putAttribute(SdkExecutionAttribute.CLIENT_TYPE, ClientType.SYNC) .putAttribute(SdkExecutionAttribute.SERVICE_NAME, SERVICE_NAME) .putAttribute(SdkExecutionAttribute.OPERATION_NAME, operationName) .putAttribute(SdkExecutionAttribute.SERVICE_CONFIG, serviceConfiguration()) .putAttribute(PRESIGNER_EXPIRATION, expiration) .putAttribute(SdkExecutionAttribute.CLIENT_ENDPOINT, clientConfiguration.option(SdkClientOption.ENDPOINT)) .putAttribute(SdkExecutionAttribute.ENDPOINT_OVERRIDDEN, clientConfiguration.option(SdkClientOption.ENDPOINT_OVERRIDDEN)) .putAttribute(AwsExecutionAttribute.FIPS_ENDPOINT_ENABLED, fipsEnabled()) .putAttribute(AwsExecutionAttribute.DUALSTACK_ENDPOINT_ENABLED, serviceConfiguration.dualstackEnabled()) .putAttribute(SdkInternalExecutionAttribute.ENDPOINT_PROVIDER, S3EndpointProvider.defaultProvider()) .putAttribute(AwsExecutionAttribute.USE_GLOBAL_ENDPOINT, useGlobalEndpointResolver.resolve(region())) .putAttribute(SdkInternalExecutionAttribute.CLIENT_CONTEXT_PARAMS, clientContextParams) .putAttribute(SdkInternalExecutionAttribute.AUTH_SCHEME_RESOLVER, S3AuthSchemeProvider.defaultProvider()) .putAttribute(SdkInternalExecutionAttribute.AUTH_SCHEMES, authSchemes()) .putAttribute(SdkInternalExecutionAttribute.IDENTITY_PROVIDERS, resolveIdentityProviders(sdkRequest)); ExecutionInterceptorChain executionInterceptorChain = new ExecutionInterceptorChain(clientInterceptors); InterceptorContext interceptorContext = InterceptorContext.builder() .request(sdkRequest) .build(); interceptorContext = AwsExecutionContextBuilder.runInitialInterceptors(interceptorContext, executionAttributes, executionInterceptorChain); Signer signer = sdkRequest.overrideConfiguration().flatMap(RequestOverrideConfiguration::signer).orElse(null); return ExecutionContext.builder() .interceptorChain(executionInterceptorChain) .interceptorContext(interceptorContext) .executionAttributes(executionAttributes) .signer(signer) .build(); } private IdentityProviders resolveIdentityProviders(SdkRequest originalRequest) { IdentityProvider<? extends AwsCredentialsIdentity> identityProvider = originalRequest.overrideConfiguration() .filter(c -> c instanceof AwsRequestOverrideConfiguration) .map(c -> (AwsRequestOverrideConfiguration) c) .flatMap(AwsRequestOverrideConfiguration::credentialsIdentityProvider) .orElse(credentialsProvider()); return IdentityProviders.builder() .putIdentityProvider(identityProvider) .build(); } private Map<String, AuthScheme<?>> authSchemes() { Map<String, AuthScheme<?>> schemes = new HashMap<>(2); AwsV4AuthScheme awsV4AuthScheme = AwsV4AuthScheme.create(); schemes.put(awsV4AuthScheme.schemeId(), awsV4AuthScheme); AwsV4aAuthScheme awsV4aAuthScheme = AwsV4aAuthScheme.create(); schemes.put(awsV4aAuthScheme.schemeId(), awsV4aAuthScheme); return Collections.unmodifiableMap(schemes); } /** * Call the before-marshalling interceptor hooks. */ private void callBeforeMarshallingHooks(ExecutionContext execCtx) { execCtx.interceptorChain().beforeMarshalling(execCtx.interceptorContext(), execCtx.executionAttributes()); } /** * Marshal the request and update the execution context with the result. */ private <T> void marshalRequestAndUpdateContext(ExecutionContext execCtx, Class<T> requestType, Function<T, SdkHttpFullRequest> requestMarshaller) { T sdkRequest = Validate.isInstanceOf(requestType, execCtx.interceptorContext().request(), "Interceptor generated unsupported type (%s) when %s was expected.", execCtx.interceptorContext().request().getClass(), requestType); SdkHttpFullRequest marshalledRequest = requestMarshaller.apply(sdkRequest); // TODO: The core SDK doesn't put the request body into the interceptor context. That should be fixed. Optional<RequestBody> requestBody = marshalledRequest.contentStreamProvider() .map(ContentStreamProvider::newStream) .map(is -> invokeSafely(() -> IoUtils.toByteArray(is))) .map(RequestBody::fromBytes); execCtx.interceptorContext(execCtx.interceptorContext().copy(r -> r.httpRequest(marshalledRequest) .requestBody(requestBody.orElse(null)))); } /** * Call the after-marshalling interceptor hooks. */ private void callAfterMarshallingHooks(ExecutionContext execCtx) { execCtx.interceptorChain().afterMarshalling(execCtx.interceptorContext(), execCtx.executionAttributes()); } /** * Update the provided HTTP request by adding any HTTP headers or query parameters specified as part of the * {@link SdkRequest}. */ private void addRequestLevelHeadersAndQueryParameters(ExecutionContext execCtx) { SdkHttpRequest httpRequest = execCtx.interceptorContext().httpRequest(); SdkRequest sdkRequest = execCtx.interceptorContext().request(); SdkHttpRequest updatedHttpRequest = httpRequest.toBuilder() .applyMutation(b -> addRequestLevelHeaders(b, sdkRequest)) .applyMutation(b -> addRequestLeveQueryParameters(b, sdkRequest)) .build(); execCtx.interceptorContext(execCtx.interceptorContext().copy(c -> c.httpRequest(updatedHttpRequest))); } private void addRequestLevelHeaders(SdkHttpRequest.Builder builder, SdkRequest request) { request.overrideConfiguration().ifPresent(overrideConfig -> { if (!overrideConfig.headers().isEmpty()) { overrideConfig.headers().forEach(builder::putHeader); } }); } private void addRequestLeveQueryParameters(SdkHttpRequest.Builder builder, SdkRequest request) { request.overrideConfiguration().ifPresent(overrideConfig -> { if (!overrideConfig.rawQueryParameters().isEmpty()) { overrideConfig.rawQueryParameters().forEach(builder::putRawQueryParameter); } }); } /** * Call the after-marshalling interceptor hooks and return the HTTP request that should be pre-signed. */ private void callModifyHttpRequestHooksAndUpdateContext(ExecutionContext execCtx) { execCtx.interceptorContext(execCtx.interceptorChain().modifyHttpRequestAndHttpContent(execCtx.interceptorContext(), execCtx.executionAttributes())); } /** * Get the HTTP full request from the execution context. */ private SdkHttpFullRequest getHttpFullRequest(ExecutionContext execCtx) { SdkHttpRequest requestFromInterceptor = execCtx.interceptorContext().httpRequest(); Optional<RequestBody> bodyFromInterceptor = execCtx.interceptorContext().requestBody(); return SdkHttpFullRequest.builder() .method(requestFromInterceptor.method()) .protocol(requestFromInterceptor.protocol()) .host(requestFromInterceptor.host()) .port(requestFromInterceptor.port()) .encodedPath(requestFromInterceptor.encodedPath()) .applyMutation(r -> { requestFromInterceptor.forEachHeader(r::putHeader); requestFromInterceptor.forEachRawQueryParameter(r::putRawQueryParameter); }) .contentStreamProvider(bodyFromInterceptor.map(RequestBody::contentStreamProvider).orElse(null)) .build(); } /** * Presign the provided HTTP request using old Signer */ private SdkHttpFullRequest presignRequest(ExecutionContext execCtx, SdkHttpFullRequest request) { Presigner presigner = Validate.isInstanceOf(Presigner.class, execCtx.signer(), "Configured signer (%s) does not support presigning (must implement %s).", execCtx.signer().getClass(), Presigner.class); return presigner.presign(request, execCtx.executionAttributes()); } /** * Presign the provided HTTP request using SRA HttpSigner */ private SdkHttpFullRequest sraPresignRequest(ExecutionContext execCtx, SdkHttpFullRequest request, Clock signingClock, Duration expirationDuration) { SelectedAuthScheme selectedAuthScheme = execCtx.executionAttributes().getAttribute(SELECTED_AUTH_SCHEME); return doSraPresign(request, selectedAuthScheme, signingClock, expirationDuration); } private <T extends Identity> SdkHttpFullRequest doSraPresign(SdkHttpFullRequest request, SelectedAuthScheme<T> selectedAuthScheme, Clock signingClock, Duration expirationDuration) { CompletableFuture<? extends T> identityFuture = selectedAuthScheme.identity(); T identity = CompletableFutureUtils.joinLikeSync(identityFuture); // presigned url puts auth info in query string, does not sign the payload, and has an expiry. SignRequest.Builder<T> signRequestBuilder = SignRequest .builder(identity) .putProperty(AwsV4FamilyHttpSigner.AUTH_LOCATION, AwsV4FamilyHttpSigner.AuthLocation.QUERY_STRING) .putProperty(AwsV4FamilyHttpSigner.PAYLOAD_SIGNING_ENABLED, false) .putProperty(AwsV4FamilyHttpSigner.EXPIRATION_DURATION, expirationDuration) .putProperty(HttpSigner.SIGNING_CLOCK, signingClock) .request(request) .payload(request.contentStreamProvider().orElse(null)); AuthSchemeOption authSchemeOption = selectedAuthScheme.authSchemeOption(); authSchemeOption.forEachSignerProperty(signRequestBuilder::putProperty); HttpSigner<T> signer = selectedAuthScheme.signer(); SignedRequest signedRequest = signer.sign(signRequestBuilder.build()); return toSdkHttpFullRequest(signedRequest); } private SdkHttpFullRequest toSdkHttpFullRequest(SignedRequest signedRequest) { SdkHttpRequest request = signedRequest.request(); return SdkHttpFullRequest.builder() .contentStreamProvider(signedRequest.payload().orElse(null)) .protocol(request.protocol()) .method(request.method()) .host(request.host()) .port(request.port()) .encodedPath(request.encodedPath()) .applyMutation(r -> request.forEachHeader(r::putHeader)) .applyMutation(r -> request.forEachRawQueryParameter(r::putRawQueryParameter)) .build(); } /** * Initialize the provided presigned request. */ private void initializePresignedRequest(PresignedRequest.Builder presignedRequest, ExecutionContext execCtx, SdkHttpFullRequest signedHttpRequest, Instant expiration) { SdkBytes signedPayload = signedHttpRequest.contentStreamProvider() .map(p -> SdkBytes.fromInputStream(p.newStream())) .orElse(null); List<String> signedHeadersQueryParam = signedHttpRequest.firstMatchingRawQueryParameters("X-Amz-SignedHeaders"); Validate.validState(!signedHeadersQueryParam.isEmpty(), "Only SigV4 signers are supported at this time, but the configured " + "signer did not seem to generate a SigV4 signature."); Map<String, List<String>> signedHeaders = signedHeadersQueryParam.stream() .flatMap(h -> Stream.of(h.split(";"))) .collect(toMap(h -> h, h -> signedHttpRequest.firstMatchingHeader(h) .map(Collections::singletonList) .orElseGet(ArrayList::new))); boolean isBrowserExecutable = signedHttpRequest.method() == SdkHttpMethod.GET && signedPayload == null && (signedHeaders.isEmpty() || (signedHeaders.size() == 1 && signedHeaders.containsKey("host"))); presignedRequest.expiration(expiration) .isBrowserExecutable(isBrowserExecutable) .httpRequest(signedHttpRequest) .signedHeaders(signedHeaders) .signedPayload(signedPayload); } private AttributeMap createClientContextParams() { AttributeMap.Builder params = AttributeMap.builder(); params.put(S3ClientContextParams.USE_ARN_REGION, serviceConfiguration.useArnRegionEnabled()); params.put(S3ClientContextParams.DISABLE_MULTI_REGION_ACCESS_POINTS, !serviceConfiguration.multiRegionEnabled()); params.put(S3ClientContextParams.FORCE_PATH_STYLE, serviceConfiguration.pathStyleAccessEnabled()); params.put(S3ClientContextParams.ACCELERATE, serviceConfiguration.accelerateModeEnabled()); return params.build(); } private UseGlobalEndpointResolver createUseGlobalEndpointResolver() { String legacyOption = DefaultsModeConfiguration.defaultConfig(DefaultsMode.LEGACY) .get(ServiceMetadataAdvancedOption.DEFAULT_S3_US_EAST_1_REGIONAL_ENDPOINT); SdkClientConfiguration config = clientConfiguration.toBuilder() .option(ServiceMetadataAdvancedOption.DEFAULT_S3_US_EAST_1_REGIONAL_ENDPOINT, legacyOption) .option(SdkClientOption.PROFILE_FILE_SUPPLIER, profileFileSupplier()) .option(SdkClientOption.PROFILE_NAME, profileName()) .build(); return new UseGlobalEndpointResolver(config); } @SdkInternalApi public static final class Builder extends DefaultSdkPresigner.Builder<Builder> implements S3Presigner.Builder { private S3Configuration serviceConfiguration; private Builder() { } /** * Allows providing a custom S3 serviceConfiguration by providing a {@link S3Configuration} object; * * Note: chunkedEncodingEnabled and checksumValidationEnabled do not apply to presigned requests. * * @param serviceConfiguration {@link S3Configuration} * @return this Builder */ @Override public Builder serviceConfiguration(S3Configuration serviceConfiguration) { this.serviceConfiguration = serviceConfiguration; return this; } @Override public S3Presigner build() { return new DefaultS3Presigner(this); } } }
4,812
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/signing/S3SigningUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.signing; import java.util.Optional; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.arns.Arn; import software.amazon.awssdk.core.signer.Signer; import software.amazon.awssdk.services.s3.internal.endpoints.S3EndpointUtils; 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.S3Request; /** * Utilities for working with S3 specific signing */ @SdkInternalApi public final class S3SigningUtils { private S3SigningUtils() { } public static Optional<Signer> internalSignerOverride(S3Request originalRequest) { return originalRequest.getValueForField("Bucket", String.class) .filter(S3EndpointUtils::isArn) .flatMap(S3SigningUtils::getS3ResourceSigner); } private static Optional<Signer> getS3ResourceSigner(String name) { S3Resource resolvedS3Resource = S3ArnConverter.create().convertArn(Arn.fromString(name)); return resolvedS3Resource.overrideSigner(); } }
4,813
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/signing/DefaultSdkPresigner.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.signing; import java.net.URI; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.awscore.endpoint.DualstackEnabledProvider; import software.amazon.awssdk.awscore.endpoint.FipsEnabledProvider; import software.amazon.awssdk.awscore.presigner.SdkPresigner; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.profiles.ProfileFileSystemSetting; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.regions.providers.DefaultAwsRegionProviderChain; import software.amazon.awssdk.utils.IoUtils; /** * The base class implementing the {@link SdkPresigner} interface. * <p> * TODO: This should get moved to aws-core (or split and moved to sdk-core and aws-core) when we support presigning from * multiple services. * TODO: After moving, this should get marked as an @SdkProtectedApi. */ @SdkInternalApi public abstract class DefaultSdkPresigner implements SdkPresigner { private final Supplier<ProfileFile> profileFile; private final String profileName; private final Region region; private final URI endpointOverride; private final IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider; private final Boolean dualstackEnabled; private final boolean fipsEnabled; protected DefaultSdkPresigner(Builder<?> b) { this.profileFile = ProfileFile::defaultProfileFile; this.profileName = ProfileFileSystemSetting.AWS_PROFILE.getStringValueOrThrow(); this.region = b.region != null ? b.region : DefaultAwsRegionProviderChain.builder() .profileFile(profileFile) .profileName(profileName) .build() .getRegion(); this.credentialsProvider = b.credentialsProvider != null ? b.credentialsProvider : DefaultCredentialsProvider.builder() .profileFile(profileFile) .profileName(profileName) .build(); this.endpointOverride = b.endpointOverride; this.dualstackEnabled = b.dualstackEnabled != null ? b.dualstackEnabled : DualstackEnabledProvider.builder() .profileFile(profileFile) .profileName(profileName) .build() .isDualstackEnabled() .orElse(null); this.fipsEnabled = b.fipsEnabled != null ? b.fipsEnabled : FipsEnabledProvider.builder() .profileFile(profileFile) .profileName(profileName) .build() .isFipsEnabled() .orElse(false); } protected Supplier<ProfileFile> profileFileSupplier() { return profileFile; } protected String profileName() { return profileName; } protected Region region() { return region; } protected IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider() { return credentialsProvider; } protected Boolean dualstackEnabled() { return dualstackEnabled; } protected boolean fipsEnabled() { return fipsEnabled; } protected URI endpointOverride() { return endpointOverride; } @Override public void close() { IoUtils.closeIfCloseable(credentialsProvider, null); } /** * The base class implementing the {@link SdkPresigner.Builder} interface. */ @SdkInternalApi public abstract static class Builder<B extends Builder<B>> implements SdkPresigner.Builder { private Region region; private IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider; private Boolean dualstackEnabled; private Boolean fipsEnabled; private URI endpointOverride; protected Builder() { } @Override public B region(Region region) { this.region = region; return thisBuilder(); } @Override public B credentialsProvider(AwsCredentialsProvider credentialsProvider) { return credentialsProvider((IdentityProvider<? extends AwsCredentialsIdentity>) credentialsProvider); } @Override public B credentialsProvider(IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider) { this.credentialsProvider = credentialsProvider; return thisBuilder(); } @Override public B dualstackEnabled(Boolean dualstackEnabled) { this.dualstackEnabled = dualstackEnabled; return thisBuilder(); } @Override public B fipsEnabled(Boolean fipsEnabled) { this.fipsEnabled = fipsEnabled; return thisBuilder(); } @Override public B endpointOverride(URI endpointOverride) { this.endpointOverride = endpointOverride; return thisBuilder(); } @SuppressWarnings("unchecked") private B thisBuilder() { return (B) this; } } }
4,814
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/endpoints/S3EndpointResolverContext.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.endpoints; import java.net.URI; import java.util.Objects; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3Configuration; /** * Contains the information needed to resolve S3 endpoints. */ @SdkInternalApi public final class S3EndpointResolverContext { private final SdkHttpRequest request; private final SdkRequest originalRequest; private final Region region; private final S3Configuration serviceConfiguration; private final URI endpointOverride; private final boolean disableHostPrefixInjection; private final boolean fipsEnabled; private S3EndpointResolverContext(Builder builder) { this.request = builder.request; this.originalRequest = builder.originalRequest; this.region = builder.region; this.serviceConfiguration = builder.serviceConfiguration; this.endpointOverride = builder.endpointOverride; this.disableHostPrefixInjection = builder.disableHostPrefixInjection; this.fipsEnabled = builder.fipsEnabled != null ? builder.fipsEnabled : false; } public static Builder builder() { return new Builder(); } public SdkHttpRequest request() { return request; } public SdkRequest originalRequest() { return originalRequest; } public Region region() { return region; } public S3Configuration serviceConfiguration() { return serviceConfiguration; } public boolean fipsEnabled() { return fipsEnabled; } public URI endpointOverride() { return endpointOverride; } public boolean isDisableHostPrefixInjection() { return disableHostPrefixInjection; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } S3EndpointResolverContext that = (S3EndpointResolverContext) o; return Objects.equals(endpointOverride, that.endpointOverride) && Objects.equals(request, that.request) && Objects.equals(originalRequest, that.originalRequest) && Objects.equals(region, that.region) && Objects.equals(serviceConfiguration, that.serviceConfiguration) && (disableHostPrefixInjection == that.disableHostPrefixInjection); } @Override public int hashCode() { int hashCode = 1; hashCode = 31 * hashCode + Objects.hashCode(request()); hashCode = 31 * hashCode + Objects.hashCode(originalRequest()); hashCode = 31 * hashCode + Objects.hashCode(region()); hashCode = 31 * hashCode + Objects.hashCode(serviceConfiguration()); hashCode = 31 * hashCode + Objects.hashCode(endpointOverride()); hashCode = 31 * hashCode + Objects.hashCode(isDisableHostPrefixInjection()); hashCode = 31 * hashCode + Boolean.hashCode(fipsEnabled()); return hashCode; } public Builder toBuilder() { return builder().endpointOverride(endpointOverride) .request(request) .originalRequest(originalRequest) .region(region) .serviceConfiguration(serviceConfiguration) .fipsEnabled(fipsEnabled); } public static final class Builder { private SdkHttpRequest request; private SdkRequest originalRequest; private Region region; private S3Configuration serviceConfiguration; private URI endpointOverride; private boolean disableHostPrefixInjection; private Boolean fipsEnabled; private Supplier<ProfileFile> profileFile; private String profileName; private Builder() { } public Builder request(SdkHttpRequest request) { this.request = request; return this; } public Builder originalRequest(SdkRequest originalRequest) { this.originalRequest = originalRequest; return this; } public Builder region(Region region) { this.region = region; return this; } public Builder serviceConfiguration(S3Configuration serviceConfiguration) { this.serviceConfiguration = serviceConfiguration; return this; } public Builder endpointOverride(URI endpointOverride) { this.endpointOverride = endpointOverride; return this; } public Builder disableHostPrefixInjection(boolean disableHostPrefixInjection) { this.disableHostPrefixInjection = disableHostPrefixInjection; return this; } public Builder fipsEnabled(Boolean fipsEnabled) { this.fipsEnabled = fipsEnabled; return this; } public S3EndpointResolverContext build() { return new S3EndpointResolverContext(this); } } }
4,815
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/endpoints/S3EndpointUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.endpoints; import java.net.URI; import java.net.URISyntaxException; import java.util.Arrays; import java.util.List; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.services.s3.S3Configuration; import software.amazon.awssdk.services.s3.model.CreateBucketRequest; import software.amazon.awssdk.services.s3.model.DeleteBucketRequest; import software.amazon.awssdk.services.s3.model.ListBucketsRequest; import software.amazon.awssdk.utils.StringUtils; /** * Utilities for working with Amazon S3 bucket names and endpoints. */ @SdkInternalApi public final class S3EndpointUtils { private static final List<Class<?>> ACCELERATE_DISABLED_OPERATIONS = Arrays.asList( ListBucketsRequest.class, CreateBucketRequest.class, DeleteBucketRequest.class); private S3EndpointUtils() { } public static String removeFipsIfNeeded(String region) { if (region.startsWith("fips-")) { return StringUtils.replace(region, "fips-", ""); } if (region.endsWith("-fips")) { return StringUtils.replace(region, "-fips", ""); } return region; } public static boolean isFipsRegion(String region) { return !StringUtils.isEmpty(region) && (region.startsWith("fips-") || region.endsWith("-fips")); } /** * @return True if accelerate mode is enabled per {@link S3Configuration}, false if not. */ public static boolean isAccelerateEnabled(S3Configuration serviceConfiguration) { return serviceConfiguration != null && serviceConfiguration.accelerateModeEnabled(); } /** * @param originalRequest Request object to identify the operation. * @return True if accelerate is supported for the given operation, false if not. */ public static boolean isAccelerateSupported(SdkRequest originalRequest) { return !ACCELERATE_DISABLED_OPERATIONS.contains(originalRequest.getClass()); } /** * @return The endpoint for an S3 accelerate enabled operation. S3 accelerate has a single global endpoint. */ public static URI accelerateEndpoint(String domain, String protocol) { return toUri(protocol, "s3-accelerate." + domain); } /** * @return The endpoint for an S3 accelerate enabled operation. S3 accelerate has a single global endpoint. */ public static URI accelerateDualstackEndpoint(String domain, String protocol) { return toUri(protocol, "s3-accelerate.dualstack." + domain); } /** * @return True if dualstack is enabled per {@link S3Configuration}, false if not. */ public static boolean isDualstackEnabled(S3Configuration serviceConfiguration) { return serviceConfiguration != null && serviceConfiguration.dualstackEnabled(); } /** * @return dual stack endpoint from given protocol and region metadata */ public static URI dualstackEndpoint(String id, String domain, String protocol) { String serviceEndpoint = String.format("%s.%s.%s.%s", "s3", "dualstack", id, domain); return toUri(protocol, serviceEndpoint); } /** * @return fips endpoint from given protocol and region metadata */ public static URI fipsEndpoint(String id, String domain, String protocol) { String serviceEndpoint = String.format("%s.%s.%s", "s3-fips", id, domain); return toUri(protocol, serviceEndpoint); } /** * @return dual stack + fips endpoint from given protocol and region metadata */ public static URI fipsDualstackEndpoint(String id, String domain, String protocol) { String serviceEndpoint = String.format("%s.%s.%s.%s", "s3-fips", "dualstack", id, domain); return toUri(protocol, serviceEndpoint); } /** * @return True if path style access is enabled per {@link S3Configuration}, false if not. */ public static boolean isPathStyleAccessEnabled(S3Configuration serviceConfiguration) { return serviceConfiguration != null && serviceConfiguration.pathStyleAccessEnabled(); } public static boolean isArnRegionEnabled(S3Configuration serviceConfiguration) { return serviceConfiguration != null && serviceConfiguration.useArnRegionEnabled(); } /** * Changes from path style addressing (which the marshallers produce by default, to DNS style or virtual style addressing * where the bucket name is prepended to the host. DNS style addressing is preferred due to the better load balancing * qualities it provides, path style is an option mainly for proxy based situations and alternative S3 implementations. * * @param mutableRequest Marshalled HTTP request we are modifying. * @param bucketName Bucket name for this particular operation. */ public static void changeToDnsEndpoint(SdkHttpRequest.Builder mutableRequest, String bucketName) { if (mutableRequest.host().startsWith("s3")) { String newHost = mutableRequest.host().replaceFirst("s3", bucketName + "." + "s3"); String newPath = mutableRequest.encodedPath().replaceFirst("/" + bucketName, ""); mutableRequest.host(newHost).encodedPath(newPath); } } public static boolean isArn(String s) { return s.startsWith("arn:"); } private static URI toUri(String protocol, String endpoint) { try { return new URI(String.format("%s://%s", protocol, endpoint)); } catch (URISyntaxException e) { throw new IllegalArgumentException(e); } } }
4,816
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/endpoints/S3EndpointResolver.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.endpoints; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.services.s3.internal.ConfiguredS3SdkHttpRequest; /** * An S3 endpoint resolver returns a {@link ConfiguredS3SdkHttpRequest} based on the HTTP context and previously * set execution attributes. * <p/> * @see software.amazon.awssdk.services.s3.internal.handlers.EndpointAddressInterceptor */ @SdkInternalApi public interface S3EndpointResolver { ConfiguredS3SdkHttpRequest applyEndpointConfiguration(S3EndpointResolverContext context); }
4,817
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/endpoints/UseGlobalEndpointResolver.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.endpoints; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkSystemSetting; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.client.config.SdkClientOption; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.profiles.ProfileProperty; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.regions.ServiceMetadataAdvancedOption; import software.amazon.awssdk.regions.servicemetadata.EnhancedS3ServiceMetadata; import software.amazon.awssdk.utils.Lazy; import software.amazon.awssdk.utils.Logger; /** * Resolve the use global endpoint setting for S3. * <p> * This logic is identical to that in {@link EnhancedS3ServiceMetadata}, there's no good way to share it aside from creating a * protected API that both the s3 and regions module consume. */ @SdkInternalApi public class UseGlobalEndpointResolver { private static final Logger LOG = Logger.loggerFor(UseGlobalEndpointResolver.class); private static final String REGIONAL_SETTING = "regional"; private final Lazy<Boolean> useUsEast1RegionalEndpoint; public UseGlobalEndpointResolver(SdkClientConfiguration config) { String defaultS3UsEast1RegionalEndpointFromSmartDefaults = config.option(ServiceMetadataAdvancedOption.DEFAULT_S3_US_EAST_1_REGIONAL_ENDPOINT); this.useUsEast1RegionalEndpoint = new Lazy<>(() -> useUsEast1RegionalEndpoint(config.option(SdkClientOption.PROFILE_FILE_SUPPLIER), () -> config.option(SdkClientOption.PROFILE_NAME), defaultS3UsEast1RegionalEndpointFromSmartDefaults)); } public boolean resolve(Region region) { if (!Region.US_EAST_1.equals(region)) { return false; } return !useUsEast1RegionalEndpoint.getValue(); } private boolean useUsEast1RegionalEndpoint(Supplier<ProfileFile> profileFile, Supplier<String> profileName, String defaultS3UsEast1RegionalEndpoint) { String env = envVarSetting(); if (env != null) { return REGIONAL_SETTING.equalsIgnoreCase(env); } String profile = profileFileSetting(profileFile, profileName); if (profile != null) { return REGIONAL_SETTING.equalsIgnoreCase(profile); } return REGIONAL_SETTING.equalsIgnoreCase(defaultS3UsEast1RegionalEndpoint); } private static String envVarSetting() { return SdkSystemSetting.AWS_S3_US_EAST_1_REGIONAL_ENDPOINT.getStringValue().orElse(null); } private String profileFileSetting(Supplier<ProfileFile> profileFileSupplier, Supplier<String> profileNameSupplier) { try { ProfileFile profileFile = profileFileSupplier.get(); String profileName = profileNameSupplier.get(); if (profileFile == null || profileName == null) { return null; } return profileFile.profile(profileName) .flatMap(p -> p.property(ProfileProperty.S3_US_EAST_1_REGIONAL_ENDPOINT)) .orElse(null); } catch (Exception t) { LOG.warn(() -> "Unable to load config file", t); return null; } } }
4,818
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/endpoints/S3EndpointResolverFactoryContext.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.endpoints; import java.util.Optional; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.services.s3.model.S3Request; @SdkInternalApi public final class S3EndpointResolverFactoryContext { private final String bucketName; private final S3Request originalRequest; private S3EndpointResolverFactoryContext(DefaultBuilder builder) { this.bucketName = builder.bucketName; this.originalRequest = builder.originalRequest; } public Optional<String> bucketName() { return Optional.ofNullable(bucketName); } public S3Request originalRequest() { return originalRequest; } public static Builder builder() { return new DefaultBuilder(); } public interface Builder { Builder bucketName(String bucketName); Builder originalRequest(S3Request originalRequest); S3EndpointResolverFactoryContext build(); } private static final class DefaultBuilder implements Builder { private String bucketName; private S3Request originalRequest; @Override public Builder bucketName(String bucketName) { this.bucketName = bucketName; return this; } @Override public Builder originalRequest(S3Request originalRequest) { this.originalRequest = originalRequest; return this; } @Override public S3EndpointResolverFactoryContext build() { return new S3EndpointResolverFactoryContext(this); } } }
4,819
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/endpoints/S3ObjectLambdaOperationEndpointBuilder.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.endpoints; import java.net.URI; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.utils.Validate; /** * Endpoint builder for operations specific to S3 Object Lambda. */ @SdkInternalApi public class S3ObjectLambdaOperationEndpointBuilder { private String region; private String protocol; private String domain; private S3ObjectLambdaOperationEndpointBuilder() { } /** * Create a new instance of this builder class. */ public static S3ObjectLambdaOperationEndpointBuilder create() { return new S3ObjectLambdaOperationEndpointBuilder(); } public S3ObjectLambdaOperationEndpointBuilder region(String region) { this.region = region; return this; } public S3ObjectLambdaOperationEndpointBuilder protocol(String protocol) { this.protocol = protocol; return this; } public S3ObjectLambdaOperationEndpointBuilder domain(String domain) { this.domain = domain; return this; } /** * Generate an endpoint URI with no path that maps to the Object Lambdas Access Point information stored in this builder. */ public URI toUri() { Validate.paramNotBlank(protocol, "protocol"); Validate.paramNotBlank(domain, "domain"); Validate.paramNotBlank(region, "region"); String servicePrefix = "s3-object-lambda"; String uriString = String.format("%s://%s.%s.%s", protocol, servicePrefix, region, domain); return URI.create(uriString); } }
4,820
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/multipart/CopyObjectHelper.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.multipart; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicReferenceArray; import java.util.stream.IntStream; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.services.s3.S3AsyncClient; import software.amazon.awssdk.services.s3.internal.crt.UploadPartCopyRequestIterable; import software.amazon.awssdk.services.s3.model.CompleteMultipartUploadRequest; import software.amazon.awssdk.services.s3.model.CompleteMultipartUploadResponse; import software.amazon.awssdk.services.s3.model.CompletedMultipartUpload; import software.amazon.awssdk.services.s3.model.CompletedPart; import software.amazon.awssdk.services.s3.model.CopyObjectRequest; import software.amazon.awssdk.services.s3.model.CopyObjectResponse; import software.amazon.awssdk.services.s3.model.CopyPartResult; import software.amazon.awssdk.services.s3.model.CreateMultipartUploadRequest; import software.amazon.awssdk.services.s3.model.CreateMultipartUploadResponse; import software.amazon.awssdk.services.s3.model.HeadObjectResponse; import software.amazon.awssdk.services.s3.model.UploadPartCopyRequest; import software.amazon.awssdk.services.s3.model.UploadPartCopyResponse; import software.amazon.awssdk.utils.CompletableFutureUtils; import software.amazon.awssdk.utils.Logger; /** * An internal helper class that automatically uses multipart copy based on the size of the source object */ @SdkInternalApi public final class CopyObjectHelper { private static final Logger log = Logger.loggerFor(S3AsyncClient.class); private final S3AsyncClient s3AsyncClient; private final long partSizeInBytes; private final GenericMultipartHelper<CopyObjectRequest, CopyObjectResponse> genericMultipartHelper; private final long uploadThreshold; public CopyObjectHelper(S3AsyncClient s3AsyncClient, long partSizeInBytes, long uploadThreshold) { this.s3AsyncClient = s3AsyncClient; this.partSizeInBytes = partSizeInBytes; this.genericMultipartHelper = new GenericMultipartHelper<>(s3AsyncClient, SdkPojoConversionUtils::toAbortMultipartUploadRequest, SdkPojoConversionUtils::toCopyObjectResponse); this.uploadThreshold = uploadThreshold; } public CompletableFuture<CopyObjectResponse> copyObject(CopyObjectRequest copyObjectRequest) { CompletableFuture<CopyObjectResponse> returnFuture = new CompletableFuture<>(); try { CompletableFuture<HeadObjectResponse> headFuture = s3AsyncClient.headObject(SdkPojoConversionUtils.toHeadObjectRequest(copyObjectRequest)); // Ensure cancellations are forwarded to the head future CompletableFutureUtils.forwardExceptionTo(returnFuture, headFuture); headFuture.whenComplete((headObjectResponse, throwable) -> { if (throwable != null) { genericMultipartHelper.handleException(returnFuture, () -> "Failed to retrieve metadata from the source " + "object", throwable); } else { doCopyObject(copyObjectRequest, returnFuture, headObjectResponse); } }); } catch (Throwable throwable) { returnFuture.completeExceptionally(throwable); } return returnFuture; } private void doCopyObject(CopyObjectRequest copyObjectRequest, CompletableFuture<CopyObjectResponse> returnFuture, HeadObjectResponse headObjectResponse) { Long contentLength = headObjectResponse.contentLength(); if (contentLength <= partSizeInBytes || contentLength <= uploadThreshold) { log.debug(() -> "Starting the copy as a single copy part request"); copyInOneChunk(copyObjectRequest, returnFuture); } else { log.debug(() -> "Starting the copy as multipart copy request"); copyInParts(copyObjectRequest, contentLength, returnFuture); } } private void copyInParts(CopyObjectRequest copyObjectRequest, Long contentLength, CompletableFuture<CopyObjectResponse> returnFuture) { CreateMultipartUploadRequest request = SdkPojoConversionUtils.toCreateMultipartUploadRequest(copyObjectRequest); CompletableFuture<CreateMultipartUploadResponse> createMultipartUploadFuture = s3AsyncClient.createMultipartUpload(request); // Ensure cancellations are forwarded to the createMultipartUploadFuture future CompletableFutureUtils.forwardExceptionTo(returnFuture, createMultipartUploadFuture); createMultipartUploadFuture.whenComplete((createMultipartUploadResponse, throwable) -> { if (throwable != null) { genericMultipartHelper.handleException(returnFuture, () -> "Failed to initiate multipart upload", throwable); } else { log.debug(() -> "Initiated new multipart upload, uploadId: " + createMultipartUploadResponse.uploadId()); doCopyInParts(copyObjectRequest, contentLength, returnFuture, createMultipartUploadResponse.uploadId()); } }); } private void doCopyInParts(CopyObjectRequest copyObjectRequest, Long contentLength, CompletableFuture<CopyObjectResponse> returnFuture, String uploadId) { long optimalPartSize = genericMultipartHelper.calculateOptimalPartSizeFor(contentLength, partSizeInBytes); int partCount = genericMultipartHelper.determinePartCount(contentLength, optimalPartSize); if (optimalPartSize > partSizeInBytes) { log.debug(() -> String.format("Configured partSize is %d, but using %d to prevent reaching maximum number of parts " + "allowed", partSizeInBytes, optimalPartSize)); } log.debug(() -> String.format("Starting multipart copy with partCount: %s, optimalPartSize: %s", partCount, optimalPartSize)); // The list of completed parts must be sorted AtomicReferenceArray<CompletedPart> completedParts = new AtomicReferenceArray<>(partCount); List<CompletableFuture<CompletedPart>> futures = sendUploadPartCopyRequests(copyObjectRequest, contentLength, uploadId, completedParts, optimalPartSize); CompletableFutureUtils.allOfExceptionForwarded(futures.toArray(new CompletableFuture[0])) .thenCompose(ignore -> completeMultipartUpload(copyObjectRequest, uploadId, completedParts)) .handle(genericMultipartHelper.handleExceptionOrResponse(copyObjectRequest, returnFuture, uploadId)) .exceptionally(throwable -> { genericMultipartHelper.handleException(returnFuture, () -> "Unexpected exception occurred", throwable); return null; }); } private CompletableFuture<CompleteMultipartUploadResponse> completeMultipartUpload( CopyObjectRequest copyObjectRequest, String uploadId, AtomicReferenceArray<CompletedPart> completedParts) { log.debug(() -> String.format("Sending completeMultipartUploadRequest, uploadId: %s", uploadId)); CompletedPart[] parts = IntStream.range(0, completedParts.length()) .mapToObj(completedParts::get) .toArray(CompletedPart[]::new); CompleteMultipartUploadRequest completeMultipartUploadRequest = CompleteMultipartUploadRequest.builder() .bucket(copyObjectRequest.destinationBucket()) .key(copyObjectRequest.destinationKey()) .uploadId(uploadId) .multipartUpload(CompletedMultipartUpload.builder() .parts(parts) .build()) .sseCustomerAlgorithm(copyObjectRequest.sseCustomerAlgorithm()) .sseCustomerKey(copyObjectRequest.sseCustomerKey()) .sseCustomerKeyMD5(copyObjectRequest.sseCustomerKeyMD5()) .build(); return s3AsyncClient.completeMultipartUpload(completeMultipartUploadRequest); } private List<CompletableFuture<CompletedPart>> sendUploadPartCopyRequests(CopyObjectRequest copyObjectRequest, long contentLength, String uploadId, AtomicReferenceArray<CompletedPart> completedParts, long optimalPartSize) { List<CompletableFuture<CompletedPart>> futures = new ArrayList<>(); UploadPartCopyRequestIterable uploadPartCopyRequests = new UploadPartCopyRequestIterable(uploadId, optimalPartSize, copyObjectRequest, contentLength); uploadPartCopyRequests.forEach(uploadPartCopyRequest -> sendIndividualUploadPartCopy(uploadId, completedParts, futures, uploadPartCopyRequest)); return futures; } private void sendIndividualUploadPartCopy(String uploadId, AtomicReferenceArray<CompletedPart> completedParts, List<CompletableFuture<CompletedPart>> futures, UploadPartCopyRequest uploadPartCopyRequest) { Integer partNumber = uploadPartCopyRequest.partNumber(); log.debug(() -> "Sending uploadPartCopyRequest with range: " + uploadPartCopyRequest.copySourceRange() + " uploadId: " + uploadId); CompletableFuture<UploadPartCopyResponse> uploadPartCopyFuture = s3AsyncClient.uploadPartCopy(uploadPartCopyRequest); CompletableFuture<CompletedPart> convertFuture = uploadPartCopyFuture.thenApply(uploadPartCopyResponse -> convertUploadPartCopyResponse(completedParts, partNumber, uploadPartCopyResponse)); futures.add(convertFuture); CompletableFutureUtils.forwardExceptionTo(convertFuture, uploadPartCopyFuture); } private static CompletedPart convertUploadPartCopyResponse(AtomicReferenceArray<CompletedPart> completedParts, Integer partNumber, UploadPartCopyResponse uploadPartCopyResponse) { CopyPartResult copyPartResult = uploadPartCopyResponse.copyPartResult(); CompletedPart completedPart = SdkPojoConversionUtils.toCompletedPart(copyPartResult, partNumber); completedParts.set(partNumber - 1, completedPart); return completedPart; } private void copyInOneChunk(CopyObjectRequest copyObjectRequest, CompletableFuture<CopyObjectResponse> returnFuture) { CompletableFuture<CopyObjectResponse> copyObjectFuture = s3AsyncClient.copyObject(copyObjectRequest); CompletableFutureUtils.forwardExceptionTo(returnFuture, copyObjectFuture); CompletableFutureUtils.forwardResultTo(copyObjectFuture, returnFuture); } }
4,821
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/multipart/MultipartUploadHelper.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.multipart; import static software.amazon.awssdk.services.s3.internal.multipart.SdkPojoConversionUtils.toAbortMultipartUploadRequest; import java.util.Collection; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.services.s3.S3AsyncClient; import software.amazon.awssdk.services.s3.model.CompletedPart; import software.amazon.awssdk.services.s3.model.CreateMultipartUploadRequest; import software.amazon.awssdk.services.s3.model.CreateMultipartUploadResponse; import software.amazon.awssdk.services.s3.model.PutObjectRequest; import software.amazon.awssdk.services.s3.model.PutObjectResponse; import software.amazon.awssdk.services.s3.model.UploadPartRequest; import software.amazon.awssdk.services.s3.model.UploadPartResponse; import software.amazon.awssdk.utils.CompletableFutureUtils; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Pair; /** * A base class contains common logic used by {@link UploadWithUnknownContentLengthHelper} and * {@link UploadWithKnownContentLengthHelper}. */ @SdkInternalApi public final class MultipartUploadHelper { private static final Logger log = Logger.loggerFor(MultipartUploadHelper.class); private final S3AsyncClient s3AsyncClient; private final long partSizeInBytes; private final GenericMultipartHelper<PutObjectRequest, PutObjectResponse> genericMultipartHelper; private final long maxMemoryUsageInBytes; private final long multipartUploadThresholdInBytes; public MultipartUploadHelper(S3AsyncClient s3AsyncClient, long partSizeInBytes, long multipartUploadThresholdInBytes, long maxMemoryUsageInBytes) { this.s3AsyncClient = s3AsyncClient; this.partSizeInBytes = partSizeInBytes; this.genericMultipartHelper = new GenericMultipartHelper<>(s3AsyncClient, SdkPojoConversionUtils::toAbortMultipartUploadRequest, SdkPojoConversionUtils::toPutObjectResponse); this.maxMemoryUsageInBytes = maxMemoryUsageInBytes; this.multipartUploadThresholdInBytes = multipartUploadThresholdInBytes; } CompletableFuture<CreateMultipartUploadResponse> createMultipartUpload(PutObjectRequest putObjectRequest, CompletableFuture<PutObjectResponse> returnFuture) { CreateMultipartUploadRequest request = SdkPojoConversionUtils.toCreateMultipartUploadRequest(putObjectRequest); CompletableFuture<CreateMultipartUploadResponse> createMultipartUploadFuture = s3AsyncClient.createMultipartUpload(request); // Ensure cancellations are forwarded to the createMultipartUploadFuture future CompletableFutureUtils.forwardExceptionTo(returnFuture, createMultipartUploadFuture); return createMultipartUploadFuture; } void completeMultipartUpload(CompletableFuture<PutObjectResponse> returnFuture, String uploadId, CompletedPart[] completedParts, PutObjectRequest putObjectRequest) { genericMultipartHelper.completeMultipartUpload(putObjectRequest, uploadId, completedParts) .handle(genericMultipartHelper.handleExceptionOrResponse(putObjectRequest, returnFuture, uploadId)) .exceptionally(throwable -> { genericMultipartHelper.handleException(returnFuture, () -> "Unexpected exception occurred", throwable); return null; }); } CompletableFuture<CompletedPart> sendIndividualUploadPartRequest(String uploadId, Consumer<CompletedPart> completedPartsConsumer, Collection<CompletableFuture<CompletedPart>> futures, Pair<UploadPartRequest, AsyncRequestBody> requestPair) { UploadPartRequest uploadPartRequest = requestPair.left(); Integer partNumber = uploadPartRequest.partNumber(); log.debug(() -> "Sending uploadPartRequest: " + uploadPartRequest.partNumber() + " uploadId: " + uploadId + " " + "contentLength " + requestPair.right().contentLength()); CompletableFuture<UploadPartResponse> uploadPartFuture = s3AsyncClient.uploadPart(uploadPartRequest, requestPair.right()); CompletableFuture<CompletedPart> convertFuture = uploadPartFuture.thenApply(uploadPartResponse -> convertUploadPartResponse(completedPartsConsumer, partNumber, uploadPartResponse)); futures.add(convertFuture); CompletableFutureUtils.forwardExceptionTo(convertFuture, uploadPartFuture); return convertFuture; } void failRequestsElegantly(Collection<CompletableFuture<CompletedPart>> futures, Throwable t, String uploadId, CompletableFuture<PutObjectResponse> returnFuture, PutObjectRequest putObjectRequest) { genericMultipartHelper.handleException(returnFuture, () -> "Failed to send multipart upload requests", t); if (uploadId != null) { genericMultipartHelper.cleanUpParts(uploadId, toAbortMultipartUploadRequest(putObjectRequest)); } cancelingOtherOngoingRequests(futures, t); } static void cancelingOtherOngoingRequests(Collection<CompletableFuture<CompletedPart>> futures, Throwable t) { log.trace(() -> "cancelling other ongoing requests " + futures.size()); futures.forEach(f -> f.completeExceptionally(t)); } static CompletedPart convertUploadPartResponse(Consumer<CompletedPart> consumer, Integer partNumber, UploadPartResponse uploadPartResponse) { CompletedPart completedPart = SdkPojoConversionUtils.toCompletedPart(uploadPartResponse, partNumber); consumer.accept(completedPart); return completedPart; } void uploadInOneChunk(PutObjectRequest putObjectRequest, AsyncRequestBody asyncRequestBody, CompletableFuture<PutObjectResponse> returnFuture) { CompletableFuture<PutObjectResponse> putObjectResponseCompletableFuture = s3AsyncClient.putObject(putObjectRequest, asyncRequestBody); CompletableFutureUtils.forwardExceptionTo(returnFuture, putObjectResponseCompletableFuture); CompletableFutureUtils.forwardResultTo(putObjectResponseCompletableFuture, returnFuture); } }
4,822
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/multipart/SdkPojoConversionUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.multipart; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.core.SdkPojo; import software.amazon.awssdk.services.s3.model.AbortMultipartUploadRequest; import software.amazon.awssdk.services.s3.model.CompleteMultipartUploadResponse; import software.amazon.awssdk.services.s3.model.CompletedPart; import software.amazon.awssdk.services.s3.model.CopyObjectRequest; import software.amazon.awssdk.services.s3.model.CopyObjectResponse; import software.amazon.awssdk.services.s3.model.CopyObjectResult; import software.amazon.awssdk.services.s3.model.CopyPartResult; import software.amazon.awssdk.services.s3.model.CreateMultipartUploadRequest; import software.amazon.awssdk.services.s3.model.HeadObjectRequest; import software.amazon.awssdk.services.s3.model.PutObjectRequest; import software.amazon.awssdk.services.s3.model.PutObjectResponse; import software.amazon.awssdk.services.s3.model.UploadPartCopyRequest; import software.amazon.awssdk.services.s3.model.UploadPartRequest; import software.amazon.awssdk.services.s3.model.UploadPartResponse; import software.amazon.awssdk.utils.Logger; /** * Request conversion utility method for POJO classes associated with multipart feature. */ @SdkInternalApi public final class SdkPojoConversionUtils { private static final Logger log = Logger.loggerFor(SdkPojoConversionUtils.class); private static final HashSet<String> PUT_OBJECT_REQUEST_TO_UPLOAD_PART_FIELDS_TO_IGNORE = new HashSet<>(Arrays.asList("ChecksumSHA1", "ChecksumSHA256", "ContentMD5", "ChecksumCRC32C", "ChecksumCRC32")); private SdkPojoConversionUtils() { } public static UploadPartRequest toUploadPartRequest(PutObjectRequest putObjectRequest, int partNumber, String uploadId) { UploadPartRequest.Builder builder = UploadPartRequest.builder(); setSdkFields(builder, putObjectRequest, PUT_OBJECT_REQUEST_TO_UPLOAD_PART_FIELDS_TO_IGNORE); return builder.uploadId(uploadId).partNumber(partNumber).build(); } public static CreateMultipartUploadRequest toCreateMultipartUploadRequest(PutObjectRequest putObjectRequest) { CreateMultipartUploadRequest.Builder builder = CreateMultipartUploadRequest.builder(); setSdkFields(builder, putObjectRequest); return builder.build(); } public static HeadObjectRequest toHeadObjectRequest(CopyObjectRequest copyObjectRequest) { // We can't set SdkFields directly because the fields in CopyObjectRequest do not match 100% with the ones in // HeadObjectRequest return HeadObjectRequest.builder() .bucket(copyObjectRequest.sourceBucket()) .key(copyObjectRequest.sourceKey()) .versionId(copyObjectRequest.sourceVersionId()) .ifMatch(copyObjectRequest.copySourceIfMatch()) .ifModifiedSince(copyObjectRequest.copySourceIfModifiedSince()) .ifNoneMatch(copyObjectRequest.copySourceIfNoneMatch()) .ifUnmodifiedSince(copyObjectRequest.copySourceIfUnmodifiedSince()) .expectedBucketOwner(copyObjectRequest.expectedSourceBucketOwner()) .sseCustomerAlgorithm(copyObjectRequest.copySourceSSECustomerAlgorithm()) .sseCustomerKey(copyObjectRequest.copySourceSSECustomerKey()) .sseCustomerKeyMD5(copyObjectRequest.copySourceSSECustomerKeyMD5()) .build(); } public static CompletedPart toCompletedPart(CopyPartResult copyPartResult, int partNumber) { CompletedPart.Builder builder = CompletedPart.builder(); setSdkFields(builder, copyPartResult); return builder.partNumber(partNumber).build(); } public static CompletedPart toCompletedPart(UploadPartResponse partResponse, int partNumber) { CompletedPart.Builder builder = CompletedPart.builder(); setSdkFields(builder, partResponse); return builder.partNumber(partNumber).build(); } private static void setSdkFields(SdkPojo targetBuilder, SdkPojo sourceObject) { setSdkFields(targetBuilder, sourceObject, new HashSet<>()); } private static void setSdkFields(SdkPojo targetBuilder, SdkPojo sourceObject, Set<String> fieldsToIgnore) { Map<String, Object> sourceFields = retrieveSdkFields(sourceObject, sourceObject.sdkFields()); List<SdkField<?>> targetSdkFields = targetBuilder.sdkFields(); for (SdkField<?> field : targetSdkFields) { if (fieldsToIgnore.contains(field.memberName())) { continue; } field.set(targetBuilder, sourceFields.getOrDefault(field.memberName(), null)); } } public static CreateMultipartUploadRequest toCreateMultipartUploadRequest(CopyObjectRequest copyObjectRequest) { CreateMultipartUploadRequest.Builder builder = CreateMultipartUploadRequest.builder(); setSdkFields(builder, copyObjectRequest); builder.bucket(copyObjectRequest.destinationBucket()); builder.key(copyObjectRequest.destinationKey()); return builder.build(); } public static CopyObjectResponse toCopyObjectResponse(CompleteMultipartUploadResponse response) { CopyObjectResponse.Builder builder = CopyObjectResponse.builder(); setSdkFields(builder, response); builder.responseMetadata(response.responseMetadata()); builder.sdkHttpResponse(response.sdkHttpResponse()); return builder.copyObjectResult(toCopyObjectResult(response)) .build(); } private static CopyObjectResult toCopyObjectResult(CompleteMultipartUploadResponse response) { CopyObjectResult.Builder builder = CopyObjectResult.builder(); setSdkFields(builder, response); return builder.build(); } public static AbortMultipartUploadRequest.Builder toAbortMultipartUploadRequest(CopyObjectRequest copyObjectRequest) { AbortMultipartUploadRequest.Builder builder = AbortMultipartUploadRequest.builder(); setSdkFields(builder, copyObjectRequest); builder.bucket(copyObjectRequest.destinationBucket()); builder.key(copyObjectRequest.destinationKey()); return builder; } public static AbortMultipartUploadRequest.Builder toAbortMultipartUploadRequest(PutObjectRequest putObjectRequest) { AbortMultipartUploadRequest.Builder builder = AbortMultipartUploadRequest.builder(); setSdkFields(builder, putObjectRequest); return builder; } public static UploadPartCopyRequest toUploadPartCopyRequest(CopyObjectRequest copyObjectRequest, int partNumber, String uploadId, String range) { UploadPartCopyRequest.Builder builder = UploadPartCopyRequest.builder(); setSdkFields(builder, copyObjectRequest); return builder.copySourceRange(range) .partNumber(partNumber) .uploadId(uploadId) .bucket(copyObjectRequest.destinationBucket()) .key(copyObjectRequest.destinationKey()) .build(); } public static PutObjectResponse toPutObjectResponse(CompleteMultipartUploadResponse response) { PutObjectResponse.Builder builder = PutObjectResponse.builder(); setSdkFields(builder, response); builder.responseMetadata(response.responseMetadata()); builder.sdkHttpResponse(response.sdkHttpResponse()); return builder.build(); } private static Map<String, Object> retrieveSdkFields(SdkPojo sourceObject, List<SdkField<?>> sdkFields) { return sdkFields.stream().collect( HashMap::new, (map, field) -> map.put(field.memberName(), field.getValueOrDefault(sourceObject)), Map::putAll); } }
4,823
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/multipart/UploadObjectHelper.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.multipart; import java.util.concurrent.CompletableFuture; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.services.s3.S3AsyncClient; import software.amazon.awssdk.services.s3.model.PutObjectRequest; import software.amazon.awssdk.services.s3.model.PutObjectResponse; import software.amazon.awssdk.utils.Logger; /** * An internal helper class that automatically uses multipart upload based on the size of the object. */ @SdkInternalApi public final class UploadObjectHelper { private static final Logger log = Logger.loggerFor(UploadObjectHelper.class); private final S3AsyncClient s3AsyncClient; private final long partSizeInBytes; private final GenericMultipartHelper<PutObjectRequest, PutObjectResponse> genericMultipartHelper; private final long apiCallBufferSize; private final long multipartUploadThresholdInBytes; private final UploadWithKnownContentLengthHelper uploadWithKnownContentLength; private final UploadWithUnknownContentLengthHelper uploadWithUnknownContentLength; public UploadObjectHelper(S3AsyncClient s3AsyncClient, MultipartConfigurationResolver resolver) { this.s3AsyncClient = s3AsyncClient; this.partSizeInBytes = resolver.minimalPartSizeInBytes(); this.genericMultipartHelper = new GenericMultipartHelper<>(s3AsyncClient, SdkPojoConversionUtils::toAbortMultipartUploadRequest, SdkPojoConversionUtils::toPutObjectResponse); this.apiCallBufferSize = resolver.apiCallBufferSize(); this.multipartUploadThresholdInBytes = resolver.thresholdInBytes(); this.uploadWithKnownContentLength = new UploadWithKnownContentLengthHelper(s3AsyncClient, partSizeInBytes, multipartUploadThresholdInBytes, apiCallBufferSize); this.uploadWithUnknownContentLength = new UploadWithUnknownContentLengthHelper(s3AsyncClient, partSizeInBytes, multipartUploadThresholdInBytes, apiCallBufferSize); } public CompletableFuture<PutObjectResponse> uploadObject(PutObjectRequest putObjectRequest, AsyncRequestBody asyncRequestBody) { Long contentLength = asyncRequestBody.contentLength().orElseGet(putObjectRequest::contentLength); if (contentLength == null) { return uploadWithUnknownContentLength.uploadObject(putObjectRequest, asyncRequestBody); } else { return uploadWithKnownContentLength.uploadObject(putObjectRequest, asyncRequestBody, contentLength.longValue()); } } }
4,824
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/multipart/UploadWithKnownContentLengthHelper.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.multipart; import java.util.Collection; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReferenceArray; import java.util.function.Consumer; import java.util.stream.IntStream; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.services.s3.S3AsyncClient; import software.amazon.awssdk.services.s3.model.CompletedPart; import software.amazon.awssdk.services.s3.model.CreateMultipartUploadResponse; import software.amazon.awssdk.services.s3.model.PutObjectRequest; import software.amazon.awssdk.services.s3.model.PutObjectResponse; import software.amazon.awssdk.services.s3.model.UploadPartRequest; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Pair; /** * An internal helper class that automatically uses multipart upload based on the size of the object. */ @SdkInternalApi public final class UploadWithKnownContentLengthHelper { private static final Logger log = Logger.loggerFor(UploadWithKnownContentLengthHelper.class); private final S3AsyncClient s3AsyncClient; private final long partSizeInBytes; private final GenericMultipartHelper<PutObjectRequest, PutObjectResponse> genericMultipartHelper; private final long maxMemoryUsageInBytes; private final long multipartUploadThresholdInBytes; private final MultipartUploadHelper multipartUploadHelper; public UploadWithKnownContentLengthHelper(S3AsyncClient s3AsyncClient, long partSizeInBytes, long multipartUploadThresholdInBytes, long maxMemoryUsageInBytes) { this.s3AsyncClient = s3AsyncClient; this.partSizeInBytes = partSizeInBytes; this.genericMultipartHelper = new GenericMultipartHelper<>(s3AsyncClient, SdkPojoConversionUtils::toAbortMultipartUploadRequest, SdkPojoConversionUtils::toPutObjectResponse); this.maxMemoryUsageInBytes = maxMemoryUsageInBytes; this.multipartUploadThresholdInBytes = multipartUploadThresholdInBytes; this.multipartUploadHelper = new MultipartUploadHelper(s3AsyncClient, partSizeInBytes, multipartUploadThresholdInBytes, maxMemoryUsageInBytes); } public CompletableFuture<PutObjectResponse> uploadObject(PutObjectRequest putObjectRequest, AsyncRequestBody asyncRequestBody, long contentLength) { CompletableFuture<PutObjectResponse> returnFuture = new CompletableFuture<>(); try { if (contentLength > multipartUploadThresholdInBytes && contentLength > partSizeInBytes) { log.debug(() -> "Starting the upload as multipart upload request"); uploadInParts(putObjectRequest, contentLength, asyncRequestBody, returnFuture); } else { log.debug(() -> "Starting the upload as a single upload part request"); multipartUploadHelper.uploadInOneChunk(putObjectRequest, asyncRequestBody, returnFuture); } } catch (Throwable throwable) { returnFuture.completeExceptionally(throwable); } return returnFuture; } private void uploadInParts(PutObjectRequest putObjectRequest, long contentLength, AsyncRequestBody asyncRequestBody, CompletableFuture<PutObjectResponse> returnFuture) { CompletableFuture<CreateMultipartUploadResponse> createMultipartUploadFuture = multipartUploadHelper.createMultipartUpload(putObjectRequest, returnFuture); createMultipartUploadFuture.whenComplete((createMultipartUploadResponse, throwable) -> { if (throwable != null) { genericMultipartHelper.handleException(returnFuture, () -> "Failed to initiate multipart upload", throwable); } else { log.debug(() -> "Initiated a new multipart upload, uploadId: " + createMultipartUploadResponse.uploadId()); doUploadInParts(Pair.of(putObjectRequest, asyncRequestBody), contentLength, returnFuture, createMultipartUploadResponse.uploadId()); } }); } private void doUploadInParts(Pair<PutObjectRequest, AsyncRequestBody> request, long contentLength, CompletableFuture<PutObjectResponse> returnFuture, String uploadId) { long optimalPartSize = genericMultipartHelper.calculateOptimalPartSizeFor(contentLength, partSizeInBytes); int partCount = genericMultipartHelper.determinePartCount(contentLength, optimalPartSize); if (optimalPartSize > partSizeInBytes) { log.debug(() -> String.format("Configured partSize is %d, but using %d to prevent reaching maximum number of parts " + "allowed", partSizeInBytes, optimalPartSize)); } log.debug(() -> String.format("Starting multipart upload with partCount: %d, optimalPartSize: %d", partCount, optimalPartSize)); MpuRequestContext mpuRequestContext = new MpuRequestContext(request, contentLength, optimalPartSize, uploadId); request.right() .split(b -> b.chunkSizeInBytes(mpuRequestContext.partSize) .bufferSizeInBytes(maxMemoryUsageInBytes)) .subscribe(new KnownContentLengthAsyncRequestBodySubscriber(mpuRequestContext, returnFuture)); } private static final class MpuRequestContext { private final Pair<PutObjectRequest, AsyncRequestBody> request; private final long contentLength; private final long partSize; private final String uploadId; private MpuRequestContext(Pair<PutObjectRequest, AsyncRequestBody> request, long contentLength, long partSize, String uploadId) { this.request = request; this.contentLength = contentLength; this.partSize = partSize; this.uploadId = uploadId; } } private class KnownContentLengthAsyncRequestBodySubscriber implements Subscriber<AsyncRequestBody> { /** * The number of AsyncRequestBody has been received but yet to be processed */ private final AtomicInteger asyncRequestBodyInFlight = new AtomicInteger(0); /** * Indicates whether CompleteMultipart has been initiated or not. */ private final AtomicBoolean completedMultipartInitiated = new AtomicBoolean(false); private final AtomicBoolean failureActionInitiated = new AtomicBoolean(false); private final AtomicInteger partNumber = new AtomicInteger(1); private final AtomicReferenceArray<CompletedPart> completedParts; private final String uploadId; private final Collection<CompletableFuture<CompletedPart>> futures = new ConcurrentLinkedQueue<>(); private final PutObjectRequest putObjectRequest; private final CompletableFuture<PutObjectResponse> returnFuture; private Subscription subscription; private volatile boolean isDone; KnownContentLengthAsyncRequestBodySubscriber(MpuRequestContext mpuRequestContext, CompletableFuture<PutObjectResponse> returnFuture) { long optimalPartSize = genericMultipartHelper.calculateOptimalPartSizeFor(mpuRequestContext.contentLength, partSizeInBytes); int partCount = genericMultipartHelper.determinePartCount(mpuRequestContext.contentLength, optimalPartSize); this.putObjectRequest = mpuRequestContext.request.left(); this.returnFuture = returnFuture; this.completedParts = new AtomicReferenceArray<>(partCount); this.uploadId = mpuRequestContext.uploadId; } @Override public void onSubscribe(Subscription s) { if (this.subscription != null) { log.warn(() -> "The subscriber has already been subscribed. Cancelling the incoming subscription"); subscription.cancel(); return; } this.subscription = s; s.request(1); returnFuture.whenComplete((r, t) -> { if (t != null) { s.cancel(); if (failureActionInitiated.compareAndSet(false, true)) { multipartUploadHelper.failRequestsElegantly(futures, t, uploadId, returnFuture, putObjectRequest); } } }); } @Override public void onNext(AsyncRequestBody asyncRequestBody) { log.trace(() -> "Received asyncRequestBody " + asyncRequestBody.contentLength()); asyncRequestBodyInFlight.incrementAndGet(); UploadPartRequest uploadRequest = SdkPojoConversionUtils.toUploadPartRequest(putObjectRequest, partNumber.getAndIncrement(), uploadId); Consumer<CompletedPart> completedPartConsumer = completedPart -> completedParts.set(completedPart.partNumber() - 1, completedPart); multipartUploadHelper.sendIndividualUploadPartRequest(uploadId, completedPartConsumer, futures, Pair.of(uploadRequest, asyncRequestBody)) .whenComplete((r, t) -> { if (t != null) { if (failureActionInitiated.compareAndSet(false, true)) { multipartUploadHelper.failRequestsElegantly(futures, t, uploadId, returnFuture, putObjectRequest); } } else { completeMultipartUploadIfFinish(asyncRequestBodyInFlight.decrementAndGet()); } }); subscription.request(1); } @Override public void onError(Throwable t) { log.debug(() -> "Received onError ", t); if (failureActionInitiated.compareAndSet(false, true)) { multipartUploadHelper.failRequestsElegantly(futures, t, uploadId, returnFuture, putObjectRequest); } } @Override public void onComplete() { log.debug(() -> "Received onComplete()"); isDone = true; completeMultipartUploadIfFinish(asyncRequestBodyInFlight.get()); } private void completeMultipartUploadIfFinish(int requestsInFlight) { if (isDone && requestsInFlight == 0 && completedMultipartInitiated.compareAndSet(false, true)) { CompletedPart[] parts = IntStream.range(0, completedParts.length()) .mapToObj(completedParts::get) .toArray(CompletedPart[]::new); multipartUploadHelper.completeMultipartUpload(returnFuture, uploadId, parts, putObjectRequest); } } } }
4,825
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/multipart/MultipartConfigurationResolver.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.multipart; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.services.s3.multipart.MultipartConfiguration; import software.amazon.awssdk.utils.Validate; /** * Internal utility class to resolve {@link MultipartConfiguration}. */ @SdkInternalApi public final class MultipartConfigurationResolver { private static final long DEFAULT_MIN_PART_SIZE = 8L * 1024 * 1024; private final long minimalPartSizeInBytes; private final long apiCallBufferSize; private final long thresholdInBytes; public MultipartConfigurationResolver(MultipartConfiguration multipartConfiguration) { Validate.notNull(multipartConfiguration, "multipartConfiguration"); this.minimalPartSizeInBytes = Validate.getOrDefault(multipartConfiguration.minimumPartSizeInBytes(), () -> DEFAULT_MIN_PART_SIZE); this.apiCallBufferSize = Validate.getOrDefault(multipartConfiguration.apiCallBufferSizeInBytes(), () -> minimalPartSizeInBytes * 4); this.thresholdInBytes = Validate.getOrDefault(multipartConfiguration.thresholdInBytes(), () -> minimalPartSizeInBytes); } public long minimalPartSizeInBytes() { return minimalPartSizeInBytes; } public long thresholdInBytes() { return thresholdInBytes; } public long apiCallBufferSize() { return apiCallBufferSize; } }
4,826
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/multipart/GenericMultipartHelper.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.multipart; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.concurrent.atomic.AtomicReferenceArray; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.IntStream; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.exception.SdkException; import software.amazon.awssdk.services.s3.S3AsyncClient; import software.amazon.awssdk.services.s3.model.AbortMultipartUploadRequest; import software.amazon.awssdk.services.s3.model.CompleteMultipartUploadRequest; import software.amazon.awssdk.services.s3.model.CompleteMultipartUploadResponse; import software.amazon.awssdk.services.s3.model.CompletedMultipartUpload; import software.amazon.awssdk.services.s3.model.CompletedPart; import software.amazon.awssdk.services.s3.model.S3Request; import software.amazon.awssdk.services.s3.model.S3Response; import software.amazon.awssdk.utils.Logger; @SdkInternalApi public final class GenericMultipartHelper<RequestT extends S3Request, ResponseT extends S3Response> { private static final Logger log = Logger.loggerFor(GenericMultipartHelper.class); /** * The max number of parts on S3 side is 10,000 */ private static final long MAX_UPLOAD_PARTS = 10_000; private final S3AsyncClient s3AsyncClient; private final Function<RequestT, AbortMultipartUploadRequest.Builder> abortMultipartUploadRequestConverter; private final Function<CompleteMultipartUploadResponse, ResponseT> responseConverter; public GenericMultipartHelper(S3AsyncClient s3AsyncClient, Function<RequestT, AbortMultipartUploadRequest.Builder> abortMultipartUploadRequestConverter, Function<CompleteMultipartUploadResponse, ResponseT> responseConverter) { this.s3AsyncClient = s3AsyncClient; this.abortMultipartUploadRequestConverter = abortMultipartUploadRequestConverter; this.responseConverter = responseConverter; } public void handleException(CompletableFuture<ResponseT> returnFuture, Supplier<String> message, Throwable throwable) { Throwable cause = throwable instanceof CompletionException ? throwable.getCause() : throwable; if (cause instanceof Error || cause instanceof SdkException) { cause.addSuppressed(SdkClientException.create(message.get())); returnFuture.completeExceptionally(cause); } else { SdkClientException exception = SdkClientException.create(message.get(), cause); returnFuture.completeExceptionally(exception); } } public long calculateOptimalPartSizeFor(long contentLengthOfSource, long partSizeInBytes) { double optimalPartSize = contentLengthOfSource / (double) MAX_UPLOAD_PARTS; optimalPartSize = Math.ceil(optimalPartSize); return (long) Math.max(optimalPartSize, partSizeInBytes); } public int determinePartCount(long contentLength, long partSize) { return (int) Math.ceil(contentLength / (double) partSize); } public CompletableFuture<CompleteMultipartUploadResponse> completeMultipartUpload( RequestT request, String uploadId, CompletedPart[] parts) { log.debug(() -> String.format("Sending completeMultipartUploadRequest, uploadId: %s", uploadId)); CompleteMultipartUploadRequest completeMultipartUploadRequest = CompleteMultipartUploadRequest.builder() .bucket(request.getValueForField("Bucket", String.class).get()) .key(request.getValueForField("Key", String.class).get()) .uploadId(uploadId) .multipartUpload(CompletedMultipartUpload.builder() .parts(parts) .build()) .build(); return s3AsyncClient.completeMultipartUpload(completeMultipartUploadRequest); } public CompletableFuture<CompleteMultipartUploadResponse> completeMultipartUpload( RequestT request, String uploadId, AtomicReferenceArray<CompletedPart> completedParts) { CompletedPart[] parts = IntStream.range(0, completedParts.length()) .mapToObj(completedParts::get) .toArray(CompletedPart[]::new); return completeMultipartUpload(request, uploadId, parts); } public BiFunction<CompleteMultipartUploadResponse, Throwable, Void> handleExceptionOrResponse( RequestT request, CompletableFuture<ResponseT> returnFuture, String uploadId) { return (completeMultipartUploadResponse, throwable) -> { if (throwable != null) { cleanUpParts(uploadId, abortMultipartUploadRequestConverter.apply(request)); handleException(returnFuture, () -> "Failed to send multipart requests", throwable); } else { returnFuture.complete(responseConverter.apply( completeMultipartUploadResponse)); } return null; }; } public void cleanUpParts(String uploadId, AbortMultipartUploadRequest.Builder abortMultipartUploadRequest) { log.debug(() -> "Aborting multipart upload: " + uploadId); AbortMultipartUploadRequest request = abortMultipartUploadRequest.uploadId(uploadId).build(); s3AsyncClient.abortMultipartUpload(request) .exceptionally(throwable -> { 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. ", uploadId), throwable); return null; }); } }
4,827
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/multipart/MultipartS3AsyncClient.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.multipart; import java.util.concurrent.CompletableFuture; import java.util.function.Function; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.ApiName; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.core.async.AsyncResponseTransformer; import software.amazon.awssdk.services.s3.DelegatingS3AsyncClient; import software.amazon.awssdk.services.s3.S3AsyncClient; import software.amazon.awssdk.services.s3.internal.UserAgentUtils; import software.amazon.awssdk.services.s3.model.CopyObjectRequest; import software.amazon.awssdk.services.s3.model.CopyObjectResponse; import software.amazon.awssdk.services.s3.model.GetObjectRequest; import software.amazon.awssdk.services.s3.model.GetObjectResponse; import software.amazon.awssdk.services.s3.model.PutObjectRequest; import software.amazon.awssdk.services.s3.model.PutObjectResponse; import software.amazon.awssdk.services.s3.model.S3Request; import software.amazon.awssdk.services.s3.multipart.MultipartConfiguration; import software.amazon.awssdk.utils.Validate; /** * An {@link S3AsyncClient} that automatically converts put, copy requests to their respective multipart call. Note: get is not * yet supported. * * @see MultipartConfiguration */ @SdkInternalApi public final class MultipartS3AsyncClient extends DelegatingS3AsyncClient { private static final ApiName USER_AGENT_API_NAME = ApiName.builder().name("hll").version("s3Multipart").build(); private final UploadObjectHelper mpuHelper; private final CopyObjectHelper copyObjectHelper; private MultipartS3AsyncClient(S3AsyncClient delegate, MultipartConfiguration multipartConfiguration) { super(delegate); MultipartConfiguration validConfiguration = Validate.getOrDefault(multipartConfiguration, MultipartConfiguration.builder()::build); MultipartConfigurationResolver resolver = new MultipartConfigurationResolver(validConfiguration); long minPartSizeInBytes = resolver.minimalPartSizeInBytes(); long threshold = resolver.thresholdInBytes(); mpuHelper = new UploadObjectHelper(delegate, resolver); copyObjectHelper = new CopyObjectHelper(delegate, minPartSizeInBytes, threshold); } @Override public CompletableFuture<PutObjectResponse> putObject(PutObjectRequest putObjectRequest, AsyncRequestBody requestBody) { return mpuHelper.uploadObject(putObjectRequest, requestBody); } @Override public CompletableFuture<CopyObjectResponse> copyObject(CopyObjectRequest copyObjectRequest) { return copyObjectHelper.copyObject(copyObjectRequest); } @Override public <ReturnT> CompletableFuture<ReturnT> getObject( GetObjectRequest getObjectRequest, AsyncResponseTransformer<GetObjectResponse, ReturnT> asyncResponseTransformer) { throw new UnsupportedOperationException( "Multipart download is not yet supported. Instead use the CRT based S3 client for multipart download."); } @Override public void close() { delegate().close(); } public static MultipartS3AsyncClient create(S3AsyncClient client, MultipartConfiguration multipartConfiguration) { S3AsyncClient clientWithUserAgent = new DelegatingS3AsyncClient(client) { @Override protected <T extends S3Request, ReturnT> CompletableFuture<ReturnT> invokeOperation(T request, Function<T, CompletableFuture<ReturnT>> operation) { T requestWithUserAgent = UserAgentUtils.applyUserAgentInfo(request, c -> c.addApiName(USER_AGENT_API_NAME)); return operation.apply(requestWithUserAgent); } }; return new MultipartS3AsyncClient(clientWithUserAgent, multipartConfiguration); } }
4,828
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/multipart/UploadWithUnknownContentLengthHelper.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.multipart; import java.util.Collection; import java.util.Comparator; import java.util.Queue; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.core.async.SdkPublisher; import software.amazon.awssdk.services.s3.S3AsyncClient; import software.amazon.awssdk.services.s3.model.CompletedPart; import software.amazon.awssdk.services.s3.model.CreateMultipartUploadResponse; import software.amazon.awssdk.services.s3.model.PutObjectRequest; import software.amazon.awssdk.services.s3.model.PutObjectResponse; import software.amazon.awssdk.services.s3.model.UploadPartRequest; import software.amazon.awssdk.utils.CompletableFutureUtils; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Pair; /** * An internal helper class that uploads streams with unknown content length. */ @SdkInternalApi public final class UploadWithUnknownContentLengthHelper { private static final Logger log = Logger.loggerFor(UploadWithUnknownContentLengthHelper.class); private final S3AsyncClient s3AsyncClient; private final long partSizeInBytes; private final GenericMultipartHelper<PutObjectRequest, PutObjectResponse> genericMultipartHelper; private final long maxMemoryUsageInBytes; private final long multipartUploadThresholdInBytes; private final MultipartUploadHelper multipartUploadHelper; public UploadWithUnknownContentLengthHelper(S3AsyncClient s3AsyncClient, long partSizeInBytes, long multipartUploadThresholdInBytes, long maxMemoryUsageInBytes) { this.s3AsyncClient = s3AsyncClient; this.partSizeInBytes = partSizeInBytes; this.genericMultipartHelper = new GenericMultipartHelper<>(s3AsyncClient, SdkPojoConversionUtils::toAbortMultipartUploadRequest, SdkPojoConversionUtils::toPutObjectResponse); this.maxMemoryUsageInBytes = maxMemoryUsageInBytes; this.multipartUploadThresholdInBytes = multipartUploadThresholdInBytes; this.multipartUploadHelper = new MultipartUploadHelper(s3AsyncClient, partSizeInBytes, multipartUploadThresholdInBytes, maxMemoryUsageInBytes); } public CompletableFuture<PutObjectResponse> uploadObject(PutObjectRequest putObjectRequest, AsyncRequestBody asyncRequestBody) { CompletableFuture<PutObjectResponse> returnFuture = new CompletableFuture<>(); SdkPublisher<AsyncRequestBody> splitAsyncRequestBodyResponse = asyncRequestBody.split(b -> b.chunkSizeInBytes(partSizeInBytes) .bufferSizeInBytes(maxMemoryUsageInBytes)); splitAsyncRequestBodyResponse.subscribe(new UnknownContentLengthAsyncRequestBodySubscriber(partSizeInBytes, putObjectRequest, returnFuture)); return returnFuture; } private class UnknownContentLengthAsyncRequestBodySubscriber implements Subscriber<AsyncRequestBody> { /** * Indicates whether this is the first async request body or not. */ private final AtomicBoolean isFirstAsyncRequestBody = new AtomicBoolean(true); /** * Indicates whether CreateMultipartUpload has been initiated or not */ private final AtomicBoolean createMultipartUploadInitiated = new AtomicBoolean(false); /** * Indicates whether CompleteMultipart has been initiated or not. */ private final AtomicBoolean completedMultipartInitiated = new AtomicBoolean(false); /** * The number of AsyncRequestBody has been received but yet to be processed */ private final AtomicInteger asyncRequestBodyInFlight = new AtomicInteger(0); private final AtomicBoolean failureActionInitiated = new AtomicBoolean(false); private AtomicInteger partNumber = new AtomicInteger(1); private final Queue<CompletedPart> completedParts = new ConcurrentLinkedQueue<>(); private final Collection<CompletableFuture<CompletedPart>> futures = new ConcurrentLinkedQueue<>(); private final CompletableFuture<String> uploadIdFuture = new CompletableFuture<>(); private final long maximumChunkSizeInByte; private final PutObjectRequest putObjectRequest; private final CompletableFuture<PutObjectResponse> returnFuture; private Subscription subscription; private AsyncRequestBody firstRequestBody; private String uploadId; private volatile boolean isDone; UnknownContentLengthAsyncRequestBodySubscriber(long maximumChunkSizeInByte, PutObjectRequest putObjectRequest, CompletableFuture<PutObjectResponse> returnFuture) { this.maximumChunkSizeInByte = maximumChunkSizeInByte; this.putObjectRequest = putObjectRequest; this.returnFuture = returnFuture; } @Override public void onSubscribe(Subscription s) { if (this.subscription != null) { log.warn(() -> "The subscriber has already been subscribed. Cancelling the incoming subscription"); subscription.cancel(); return; } this.subscription = s; s.request(1); returnFuture.whenComplete((r, t) -> { if (t != null) { s.cancel(); multipartUploadHelper.cancelingOtherOngoingRequests(futures, t); } }); } @Override public void onNext(AsyncRequestBody asyncRequestBody) { log.trace(() -> "Received asyncRequestBody " + asyncRequestBody.contentLength()); asyncRequestBodyInFlight.incrementAndGet(); if (isFirstAsyncRequestBody.compareAndSet(true, false)) { log.trace(() -> "Received first async request body"); // If this is the first AsyncRequestBody received, request another one because we don't know if there is more firstRequestBody = asyncRequestBody; subscription.request(1); return; } // If there are more than 1 AsyncRequestBodies, then we know we need to upload this // object using MPU if (createMultipartUploadInitiated.compareAndSet(false, true)) { log.debug(() -> "Starting the upload as multipart upload request"); CompletableFuture<CreateMultipartUploadResponse> createMultipartUploadFuture = multipartUploadHelper.createMultipartUpload(putObjectRequest, returnFuture); createMultipartUploadFuture.whenComplete((createMultipartUploadResponse, throwable) -> { if (throwable != null) { genericMultipartHelper.handleException(returnFuture, () -> "Failed to initiate multipart upload", throwable); subscription.cancel(); } else { uploadId = createMultipartUploadResponse.uploadId(); log.debug(() -> "Initiated a new multipart upload, uploadId: " + uploadId); sendUploadPartRequest(uploadId, firstRequestBody); sendUploadPartRequest(uploadId, asyncRequestBody); // We need to complete the uploadIdFuture *after* the first two requests have been sent uploadIdFuture.complete(uploadId); } }); CompletableFutureUtils.forwardExceptionTo(returnFuture, createMultipartUploadFuture); } else { uploadIdFuture.whenComplete((r, t) -> { sendUploadPartRequest(uploadId, asyncRequestBody); }); } } private void sendUploadPartRequest(String uploadId, AsyncRequestBody asyncRequestBody) { multipartUploadHelper.sendIndividualUploadPartRequest(uploadId, completedParts::add, futures, uploadPart(asyncRequestBody)) .whenComplete((r, t) -> { if (t != null) { if (failureActionInitiated.compareAndSet(false, true)) { multipartUploadHelper.failRequestsElegantly(futures, t, uploadId, returnFuture, putObjectRequest); } } else { completeMultipartUploadIfFinish(asyncRequestBodyInFlight.decrementAndGet()); } }); synchronized (this) { subscription.request(1); }; } private Pair<UploadPartRequest, AsyncRequestBody> uploadPart(AsyncRequestBody asyncRequestBody) { UploadPartRequest uploadRequest = SdkPojoConversionUtils.toUploadPartRequest(putObjectRequest, partNumber.getAndIncrement(), uploadId); return Pair.of(uploadRequest, asyncRequestBody); } @Override public void onError(Throwable t) { log.debug(() -> "Received onError() ", t); if (failureActionInitiated.compareAndSet(false, true)) { multipartUploadHelper.failRequestsElegantly(futures, t, uploadId, returnFuture, putObjectRequest); } } @Override public void onComplete() { log.debug(() -> "Received onComplete()"); // If CreateMultipartUpload has not been initiated at this point, we know this is a single object upload if (createMultipartUploadInitiated.get() == false) { log.debug(() -> "Starting the upload as a single object upload request"); multipartUploadHelper.uploadInOneChunk(putObjectRequest, firstRequestBody, returnFuture); } else { isDone = true; completeMultipartUploadIfFinish(asyncRequestBodyInFlight.get()); } } private void completeMultipartUploadIfFinish(int requestsInFlight) { if (isDone && requestsInFlight == 0 && completedMultipartInitiated.compareAndSet(false, true)) { CompletedPart[] parts = completedParts.stream() .sorted(Comparator.comparingInt(CompletedPart::partNumber)) .toArray(CompletedPart[]::new); multipartUploadHelper.completeMultipartUpload(returnFuture, uploadId, parts, putObjectRequest); } } } }
4,829
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/crt/S3InternalSdkHttpExecutionAttribute.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.crt; import java.nio.file.Path; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.interceptor.trait.HttpChecksum; import software.amazon.awssdk.crt.s3.ResumeToken; import software.amazon.awssdk.http.SdkHttpExecutionAttribute; import software.amazon.awssdk.regions.Region; @SdkInternalApi public final class S3InternalSdkHttpExecutionAttribute<T> extends SdkHttpExecutionAttribute<T> { /** * The key to indicate the name of the operation */ public static final S3InternalSdkHttpExecutionAttribute<String> OPERATION_NAME = new S3InternalSdkHttpExecutionAttribute<>(String.class); public static final S3InternalSdkHttpExecutionAttribute<HttpChecksum> HTTP_CHECKSUM = new S3InternalSdkHttpExecutionAttribute<>(HttpChecksum.class); public static final S3InternalSdkHttpExecutionAttribute<ResumeToken> CRT_PAUSE_RESUME_TOKEN = new S3InternalSdkHttpExecutionAttribute<>(ResumeToken.class); public static final S3InternalSdkHttpExecutionAttribute<Region> SIGNING_REGION = new S3InternalSdkHttpExecutionAttribute<>(Region.class); public static final S3InternalSdkHttpExecutionAttribute<Path> OBJECT_FILE_PATH = new S3InternalSdkHttpExecutionAttribute<>(Path.class); private S3InternalSdkHttpExecutionAttribute(Class<T> valueClass) { super(valueClass); } }
4,830
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/crt/CrtChecksumUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.crt; import java.util.List; import java.util.stream.Collectors; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.interceptor.trait.HttpChecksum; import software.amazon.awssdk.crt.s3.ChecksumAlgorithm; import software.amazon.awssdk.crt.s3.ChecksumConfig; import software.amazon.awssdk.crt.s3.S3MetaRequestOptions; @SdkInternalApi public final class CrtChecksumUtils { private static final ChecksumAlgorithm DEFAULT_CHECKSUM_ALGO = ChecksumAlgorithm.CRC32; private CrtChecksumUtils() { } /** * CRT checksum is only enabled for PUT_OBJECT and GET_OBJECT, for everything else, * we rely on SDK checksum implementation */ public static ChecksumConfig checksumConfig(HttpChecksum httpChecksum, S3MetaRequestOptions.MetaRequestType requestType, boolean checksumValidationEnabled) { if (checksumNotApplicable(requestType, httpChecksum)) { return new ChecksumConfig(); } ChecksumAlgorithm checksumAlgorithm = crtChecksumAlgorithm(httpChecksum, requestType, checksumValidationEnabled); boolean validateChecksum = validateResponseChecksum(httpChecksum, requestType, checksumValidationEnabled); ChecksumConfig.ChecksumLocation checksumLocation = checksumAlgorithm == ChecksumAlgorithm.NONE ? ChecksumConfig.ChecksumLocation.NONE : ChecksumConfig.ChecksumLocation.TRAILER; return new ChecksumConfig() .withChecksumAlgorithm(checksumAlgorithm) .withValidateChecksum(validateChecksum) .withChecksumLocation(checksumLocation) .withValidateChecksumAlgorithmList(checksumAlgorithmList(httpChecksum)); } private static boolean checksumNotApplicable(S3MetaRequestOptions.MetaRequestType requestType, HttpChecksum httpChecksum) { if (requestType != S3MetaRequestOptions.MetaRequestType.PUT_OBJECT && requestType != S3MetaRequestOptions.MetaRequestType.GET_OBJECT) { return true; } return httpChecksum == null; } private static List<ChecksumAlgorithm> checksumAlgorithmList(HttpChecksum httpChecksum) { if (httpChecksum.responseAlgorithms() == null) { return null; } return httpChecksum.responseAlgorithms() .stream() .map(CrtChecksumUtils::toCrtChecksumAlgorithm) .collect(Collectors.toList()); } private static ChecksumAlgorithm crtChecksumAlgorithm(HttpChecksum httpChecksum, S3MetaRequestOptions.MetaRequestType requestType, boolean checksumValidationEnabled) { if (requestType != S3MetaRequestOptions.MetaRequestType.PUT_OBJECT) { return ChecksumAlgorithm.NONE; } if (httpChecksum.requestAlgorithm() == null) { return checksumValidationEnabled ? DEFAULT_CHECKSUM_ALGO : ChecksumAlgorithm.NONE; } return toCrtChecksumAlgorithm(httpChecksum.requestAlgorithm()); } private static ChecksumAlgorithm toCrtChecksumAlgorithm(String sdkChecksum) { return ChecksumAlgorithm.valueOf(sdkChecksum.toUpperCase()); } /** * Only validate response checksum if this is getObject operation AND it supports checksum validation AND if either of the * following applies: 1. checksum validation is enabled at request level via request validation mode OR 2. checksum validation * is enabled at client level */ private static boolean validateResponseChecksum(HttpChecksum httpChecksum, S3MetaRequestOptions.MetaRequestType requestType, boolean checksumValidationEnabled) { if (requestType != S3MetaRequestOptions.MetaRequestType.GET_OBJECT) { return false; } return checksumValidationEnabled || httpChecksum.requestValidationMode() != null; } }
4,831
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/crt/S3CrtRequestBodyStreamAdapter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.crt; import java.nio.ByteBuffer; import java.util.concurrent.atomic.AtomicBoolean; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.crt.http.HttpRequestBodyStream; import software.amazon.awssdk.http.async.SdkHttpContentPublisher; import software.amazon.awssdk.utils.async.ByteBufferStoringSubscriber; /** * Adapts an SDK {@link software.amazon.awssdk.core.async.AsyncRequestBody} to CRT's {@link HttpRequestBodyStream}. */ @SdkInternalApi public final class S3CrtRequestBodyStreamAdapter implements HttpRequestBodyStream { private static final long MINIMUM_BYTES_BUFFERED = 1024 * 1024L; private final SdkHttpContentPublisher bodyPublisher; private final ByteBufferStoringSubscriber requestBodySubscriber; private final AtomicBoolean subscribed = new AtomicBoolean(false); public S3CrtRequestBodyStreamAdapter(SdkHttpContentPublisher bodyPublisher) { this.bodyPublisher = bodyPublisher; this.requestBodySubscriber = new ByteBufferStoringSubscriber(MINIMUM_BYTES_BUFFERED); } @Override public boolean sendRequestBody(ByteBuffer outBuffer) { if (subscribed.compareAndSet(false, true)) { bodyPublisher.subscribe(requestBodySubscriber); } return requestBodySubscriber.transferTo(outBuffer) == ByteBufferStoringSubscriber.TransferResult.END_OF_STREAM; } @Override public long getLength() { return bodyPublisher.contentLength().orElse(0L); } }
4,832
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/crt/DefaultS3CrtAsyncClient.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.crt; import static software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute.AUTH_SCHEMES; import static software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute.SDK_HTTP_EXECUTION_ATTRIBUTES; import static software.amazon.awssdk.services.s3.internal.crt.S3InternalSdkHttpExecutionAttribute.HTTP_CHECKSUM; import static software.amazon.awssdk.services.s3.internal.crt.S3InternalSdkHttpExecutionAttribute.OPERATION_NAME; import static software.amazon.awssdk.services.s3.internal.crt.S3InternalSdkHttpExecutionAttribute.SIGNING_REGION; import static software.amazon.awssdk.services.s3.internal.crt.S3NativeClientConfiguration.DEFAULT_PART_SIZE_IN_BYTES; import java.net.URI; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.SdkTestInternalApi; import software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute; import software.amazon.awssdk.awscore.AwsRequest; import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.checksums.ChecksumValidation; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.core.client.config.SdkAdvancedClientOption; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttribute; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.core.interceptor.SdkExecutionAttribute; import software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute; import software.amazon.awssdk.core.internal.util.ClassLoaderHelper; import software.amazon.awssdk.core.retry.RetryPolicy; import software.amazon.awssdk.core.signer.NoOpSigner; import software.amazon.awssdk.crt.io.ExponentialBackoffRetryOptions; import software.amazon.awssdk.crt.io.StandardRetryOptions; import software.amazon.awssdk.http.SdkHttpExecutionAttributes; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.DelegatingS3AsyncClient; import software.amazon.awssdk.services.s3.S3AsyncClient; import software.amazon.awssdk.services.s3.S3Configuration; import software.amazon.awssdk.services.s3.S3CrtAsyncClientBuilder; import software.amazon.awssdk.services.s3.crt.S3CrtHttpConfiguration; import software.amazon.awssdk.services.s3.crt.S3CrtRetryConfiguration; import software.amazon.awssdk.services.s3.internal.multipart.CopyObjectHelper; import software.amazon.awssdk.services.s3.model.CopyObjectRequest; import software.amazon.awssdk.services.s3.model.CopyObjectResponse; import software.amazon.awssdk.services.s3.model.GetObjectRequest; import software.amazon.awssdk.services.s3.model.PutObjectRequest; import software.amazon.awssdk.services.s3.model.PutObjectResponse; import software.amazon.awssdk.utils.CollectionUtils; import software.amazon.awssdk.utils.Validate; @SdkInternalApi public final class DefaultS3CrtAsyncClient extends DelegatingS3AsyncClient implements S3CrtAsyncClient { public static final ExecutionAttribute<Path> OBJECT_FILE_PATH = new ExecutionAttribute<>("objectFilePath"); private static final String CRT_CLIENT_CLASSPATH = "software.amazon.awssdk.crt.s3.S3Client"; private final CopyObjectHelper copyObjectHelper; private DefaultS3CrtAsyncClient(DefaultS3CrtClientBuilder builder) { super(initializeS3AsyncClient(builder)); long partSizeInBytes = builder.minimalPartSizeInBytes == null ? DEFAULT_PART_SIZE_IN_BYTES : builder.minimalPartSizeInBytes; long thresholdInBytes = builder.thresholdInBytes == null ? partSizeInBytes : builder.thresholdInBytes; this.copyObjectHelper = new CopyObjectHelper((S3AsyncClient) delegate(), partSizeInBytes, thresholdInBytes); } @Override public CompletableFuture<PutObjectResponse> putObject(PutObjectRequest putObjectRequest, Path sourcePath) { AwsRequestOverrideConfiguration overrideConfig = putObjectRequest.overrideConfiguration() .map(config -> config.toBuilder().putExecutionAttribute(OBJECT_FILE_PATH, sourcePath)) .orElseGet(() -> AwsRequestOverrideConfiguration.builder() .putExecutionAttribute(OBJECT_FILE_PATH, sourcePath)) .build(); return putObject(putObjectRequest.toBuilder().overrideConfiguration(overrideConfig).build(), new CrtContentLengthOnlyAsyncFileRequestBody(sourcePath)); } @Override public CompletableFuture<CopyObjectResponse> copyObject(CopyObjectRequest copyObjectRequest) { return copyObjectHelper.copyObject(copyObjectRequest); } private static S3AsyncClient initializeS3AsyncClient(DefaultS3CrtClientBuilder builder) { ClientOverrideConfiguration.Builder overrideConfigurationBuilder = ClientOverrideConfiguration.builder() // Disable checksum for streaming operations, retry policy and signer because they are // handled in crt .putAdvancedOption(SdkAdvancedClientOption.SIGNER, new NoOpSigner()) .putExecutionAttribute(SdkExecutionAttribute.HTTP_RESPONSE_CHECKSUM_VALIDATION, ChecksumValidation.FORCE_SKIP) .retryPolicy(RetryPolicy.none()) .addExecutionInterceptor(new ValidateRequestInterceptor()) .addExecutionInterceptor(new AttachHttpAttributesExecutionInterceptor()); if (builder.executionInterceptors != null) { builder.executionInterceptors.forEach(overrideConfigurationBuilder::addExecutionInterceptor); } return S3AsyncClient.builder() // Disable checksum for streaming operations, it is handled in CRT. Checksumming for non-streaming // operations is still handled in HttpChecksumStage .serviceConfiguration(S3Configuration.builder() .checksumValidationEnabled(false) .build()) .region(builder.region) .endpointOverride(builder.endpointOverride) .credentialsProvider(builder.credentialsProvider) .overrideConfiguration(overrideConfigurationBuilder.build()) .accelerate(builder.accelerate) .forcePathStyle(builder.forcePathStyle) .crossRegionAccessEnabled(builder.crossRegionAccessEnabled) .httpClientBuilder(initializeS3CrtAsyncHttpClient(builder)) .build(); } private static S3CrtAsyncHttpClient.Builder initializeS3CrtAsyncHttpClient(DefaultS3CrtClientBuilder builder) { validateCrtInClassPath(); Validate.isPositiveOrNull(builder.readBufferSizeInBytes, "initialReadBufferSizeInBytes"); Validate.isPositiveOrNull(builder.maxConcurrency, "maxConcurrency"); Validate.isPositiveOrNull(builder.targetThroughputInGbps, "targetThroughputInGbps"); Validate.isPositiveOrNull(builder.minimalPartSizeInBytes, "minimalPartSizeInBytes"); Validate.isPositiveOrNull(builder.thresholdInBytes, "thresholdInBytes"); S3NativeClientConfiguration.Builder nativeClientBuilder = S3NativeClientConfiguration.builder() .checksumValidationEnabled(builder.checksumValidationEnabled) .targetThroughputInGbps(builder.targetThroughputInGbps) .partSizeInBytes(builder.minimalPartSizeInBytes) .maxConcurrency(builder.maxConcurrency) .signingRegion(builder.region == null ? null : builder.region.id()) .endpointOverride(builder.endpointOverride) .credentialsProvider(builder.credentialsProvider) .readBufferSizeInBytes(builder.readBufferSizeInBytes) .httpConfiguration(builder.httpConfiguration) .thresholdInBytes(builder.thresholdInBytes); if (builder.retryConfiguration != null) { nativeClientBuilder.standardRetryOptions( new StandardRetryOptions() .withBackoffRetryOptions(new ExponentialBackoffRetryOptions() .withMaxRetries(builder.retryConfiguration.numRetries()))); } return S3CrtAsyncHttpClient.builder() .s3ClientConfiguration(nativeClientBuilder.build()); } public static final class DefaultS3CrtClientBuilder implements S3CrtAsyncClientBuilder { private Long readBufferSizeInBytes; private IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider; private Region region; private Long minimalPartSizeInBytes; private Double targetThroughputInGbps; private Integer maxConcurrency; private URI endpointOverride; private Boolean checksumValidationEnabled; private S3CrtHttpConfiguration httpConfiguration; private Boolean accelerate; private Boolean forcePathStyle; private List<ExecutionInterceptor> executionInterceptors; private S3CrtRetryConfiguration retryConfiguration; private boolean crossRegionAccessEnabled; private Long thresholdInBytes; @Override public S3CrtAsyncClientBuilder credentialsProvider( IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider) { this.credentialsProvider = credentialsProvider; return this; } @Override public S3CrtAsyncClientBuilder region(Region region) { this.region = region; return this; } @Override public S3CrtAsyncClientBuilder minimumPartSizeInBytes(Long partSizeBytes) { this.minimalPartSizeInBytes = partSizeBytes; return this; } @Override public S3CrtAsyncClientBuilder targetThroughputInGbps(Double targetThroughputInGbps) { this.targetThroughputInGbps = targetThroughputInGbps; return this; } @Override public S3CrtAsyncClientBuilder maxConcurrency(Integer maxConcurrency) { this.maxConcurrency = maxConcurrency; return this; } @Override public S3CrtAsyncClientBuilder endpointOverride(URI endpointOverride) { this.endpointOverride = endpointOverride; return this; } @Override public S3CrtAsyncClientBuilder checksumValidationEnabled(Boolean checksumValidationEnabled) { this.checksumValidationEnabled = checksumValidationEnabled; return this; } @Override public S3CrtAsyncClientBuilder initialReadBufferSizeInBytes(Long readBufferSizeInBytes) { this.readBufferSizeInBytes = readBufferSizeInBytes; return this; } @Override public S3CrtAsyncClientBuilder httpConfiguration(S3CrtHttpConfiguration configuration) { this.httpConfiguration = configuration; return this; } @Override public S3CrtAsyncClientBuilder accelerate(Boolean accelerate) { this.accelerate = accelerate; return this; } @Override public S3CrtAsyncClientBuilder forcePathStyle(Boolean forcePathStyle) { this.forcePathStyle = forcePathStyle; return this; } @SdkTestInternalApi S3CrtAsyncClientBuilder addExecutionInterceptor(ExecutionInterceptor executionInterceptor) { if (executionInterceptors == null) { this.executionInterceptors = new ArrayList<>(); } executionInterceptors.add(executionInterceptor); return this; } @Override public S3CrtAsyncClientBuilder retryConfiguration(S3CrtRetryConfiguration retryConfiguration) { this.retryConfiguration = retryConfiguration; return this; } @Override public S3CrtAsyncClientBuilder crossRegionAccessEnabled(Boolean crossRegionAccessEnabled) { this.crossRegionAccessEnabled = crossRegionAccessEnabled; return this; } @Override public S3CrtAsyncClientBuilder thresholdInBytes(Long thresholdInBytes) { this.thresholdInBytes = thresholdInBytes; return this; } @Override public S3CrtAsyncClient build() { return new DefaultS3CrtAsyncClient(this); } } private static final class AttachHttpAttributesExecutionInterceptor implements ExecutionInterceptor { @Override public void beforeExecution(Context.BeforeExecution context, ExecutionAttributes executionAttributes) { // Hack to disable new SRA path because we still rely on HttpChecksumStage to perform checksum for // non-streaming operation. // TODO: remove this once CRT supports checksum for default requests executionAttributes.putAttribute(AUTH_SCHEMES, null); } @Override public void afterMarshalling(Context.AfterMarshalling context, ExecutionAttributes executionAttributes) { SdkHttpExecutionAttributes existingHttpAttributes = executionAttributes.getAttribute(SDK_HTTP_EXECUTION_ATTRIBUTES); SdkHttpExecutionAttributes.Builder builder = existingHttpAttributes != null ? existingHttpAttributes.toBuilder() : SdkHttpExecutionAttributes.builder(); SdkHttpExecutionAttributes attributes = builder.put(OPERATION_NAME, executionAttributes.getAttribute(SdkExecutionAttribute.OPERATION_NAME)) .put(HTTP_CHECKSUM, executionAttributes.getAttribute(SdkInternalExecutionAttribute.HTTP_CHECKSUM)) .put(SIGNING_REGION, executionAttributes.getAttribute(AwsSignerExecutionAttribute.SIGNING_REGION)) .put(S3InternalSdkHttpExecutionAttribute.OBJECT_FILE_PATH, executionAttributes.getAttribute(OBJECT_FILE_PATH)) .build(); // For putObject and getObject, we rely on CRT to perform checksum validation disableChecksumForPutAndGet(context, executionAttributes); executionAttributes.putAttribute(SDK_HTTP_EXECUTION_ATTRIBUTES, attributes); } private static void disableChecksumForPutAndGet(Context.AfterMarshalling context, ExecutionAttributes executionAttributes) { if (context.request() instanceof PutObjectRequest || context.request() instanceof GetObjectRequest) { // TODO: we can remove this once we are fully on SRA signing AND CRT supports checksum for default requests // Clear HTTP_CHECKSUM and RESOLVED_CHECKSUM_SPECS to disable SDK flexible checksum implementation. executionAttributes.putAttribute(SdkInternalExecutionAttribute.HTTP_CHECKSUM, null); executionAttributes.putAttribute(SdkInternalExecutionAttribute.RESOLVED_CHECKSUM_SPECS, null); } } } private static final class ValidateRequestInterceptor implements ExecutionInterceptor { @Override public void beforeExecution(Context.BeforeExecution context, ExecutionAttributes executionAttributes) { validateOverrideConfiguration(context.request()); } private static void validateOverrideConfiguration(SdkRequest request) { if (!(request instanceof AwsRequest)) { return; } if (request.overrideConfiguration().isPresent()) { AwsRequestOverrideConfiguration overrideConfiguration = (AwsRequestOverrideConfiguration) request.overrideConfiguration().get(); if (overrideConfiguration.signer().isPresent()) { throw new UnsupportedOperationException("Request-level signer override is not supported"); } // TODO: support request-level credential override if (overrideConfiguration.credentialsIdentityProvider().isPresent()) { throw new UnsupportedOperationException("Request-level credentials override is not supported"); } if (!CollectionUtils.isNullOrEmpty(overrideConfiguration.metricPublishers())) { throw new UnsupportedOperationException("Request-level Metric Publishers override is not supported"); } if (overrideConfiguration.apiCallAttemptTimeout().isPresent()) { throw new UnsupportedOperationException("Request-level apiCallAttemptTimeout override is not supported"); } } } } private static void validateCrtInClassPath() { try { ClassLoaderHelper.loadClass(CRT_CLIENT_CLASSPATH, false); } catch (ClassNotFoundException e) { throw new IllegalStateException("Could not load classes from AWS Common Runtime (CRT) library." + "software.amazon.awssdk.crt:crt is a required dependency; make sure you have it " + "on the classpath.", e); } } }
4,833
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/crt/S3NativeClientConfiguration.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.crt; import static software.amazon.awssdk.crtcore.CrtConfigurationUtils.resolveHttpMonitoringOptions; import static software.amazon.awssdk.crtcore.CrtConfigurationUtils.resolveProxy; import java.net.URI; import java.time.Duration; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.crt.auth.credentials.CredentialsProvider; import software.amazon.awssdk.crt.http.HttpMonitoringOptions; import software.amazon.awssdk.crt.http.HttpProxyOptions; import software.amazon.awssdk.crt.io.ClientBootstrap; import software.amazon.awssdk.crt.io.StandardRetryOptions; import software.amazon.awssdk.crt.io.TlsCipherPreference; import software.amazon.awssdk.crt.io.TlsContext; import software.amazon.awssdk.crt.io.TlsContextOptions; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.regions.providers.DefaultAwsRegionProviderChain; import software.amazon.awssdk.services.s3.crt.S3CrtHttpConfiguration; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.SdkAutoCloseable; /** * Internal client configuration resolver */ @SdkInternalApi public class S3NativeClientConfiguration implements SdkAutoCloseable { static final long DEFAULT_PART_SIZE_IN_BYTES = 8L * 1024 * 1024; private static final Logger log = Logger.loggerFor(S3NativeClientConfiguration.class); private static final long DEFAULT_TARGET_THROUGHPUT_IN_GBPS = 10; private final String signingRegion; private final StandardRetryOptions standardRetryOptions; private final ClientBootstrap clientBootstrap; private final CrtCredentialsProviderAdapter credentialProviderAdapter; private final CredentialsProvider credentialsProvider; private final long partSizeInBytes; private final long thresholdInBytes; private final double targetThroughputInGbps; private final int maxConcurrency; private final URI endpointOverride; private final boolean checksumValidationEnabled; private final Long readBufferSizeInBytes; private final TlsContext tlsContext; private final HttpProxyOptions proxyOptions; private final Duration connectionTimeout; private final HttpMonitoringOptions httpMonitoringOptions; private final Boolean useEnvironmentVariableProxyOptionsValues; public S3NativeClientConfiguration(Builder builder) { this.signingRegion = builder.signingRegion == null ? DefaultAwsRegionProviderChain.builder().build().getRegion().id() : builder.signingRegion; this.clientBootstrap = new ClientBootstrap(null, null); TlsContextOptions clientTlsContextOptions = TlsContextOptions.createDefaultClient() .withCipherPreference(TlsCipherPreference.TLS_CIPHER_SYSTEM_DEFAULT); if (builder.httpConfiguration != null && builder.httpConfiguration.trustAllCertificatesEnabled() != null) { log.warn(() -> "SSL Certificate verification is disabled. " + "This is not a safe setting and should only be used for testing."); clientTlsContextOptions.withVerifyPeer(!builder.httpConfiguration.trustAllCertificatesEnabled()); } this.tlsContext = new TlsContext(clientTlsContextOptions); this.credentialProviderAdapter = builder.credentialsProvider == null ? new CrtCredentialsProviderAdapter(DefaultCredentialsProvider.create()) : new CrtCredentialsProviderAdapter(builder.credentialsProvider); this.credentialsProvider = credentialProviderAdapter.crtCredentials(); this.partSizeInBytes = builder.partSizeInBytes == null ? DEFAULT_PART_SIZE_IN_BYTES : builder.partSizeInBytes; this.thresholdInBytes = builder.thresholdInBytes == null ? this.partSizeInBytes : builder.thresholdInBytes; this.targetThroughputInGbps = builder.targetThroughputInGbps == null ? DEFAULT_TARGET_THROUGHPUT_IN_GBPS : builder.targetThroughputInGbps; // Using 0 so that CRT will calculate it based on targetThroughputGbps this.maxConcurrency = builder.maxConcurrency == null ? 0 : builder.maxConcurrency; this.endpointOverride = builder.endpointOverride; this.checksumValidationEnabled = builder.checksumValidationEnabled == null || builder.checksumValidationEnabled; this.readBufferSizeInBytes = builder.readBufferSizeInBytes == null ? partSizeInBytes * 10 : builder.readBufferSizeInBytes; if (builder.httpConfiguration != null) { this.proxyOptions = resolveProxy(builder.httpConfiguration.proxyConfiguration(), tlsContext).orElse(null); this.connectionTimeout = builder.httpConfiguration.connectionTimeout(); this.httpMonitoringOptions = resolveHttpMonitoringOptions(builder.httpConfiguration.healthConfiguration()).orElse(null); } else { this.proxyOptions = null; this.connectionTimeout = null; this.httpMonitoringOptions = null; } this.standardRetryOptions = builder.standardRetryOptions; this.useEnvironmentVariableProxyOptionsValues = resolveUseEnvironmentVariableValues(builder); } private static Boolean resolveUseEnvironmentVariableValues(Builder builder) { if (builder != null && builder.httpConfiguration != null) { if (builder.httpConfiguration.proxyConfiguration() != null) { return builder.httpConfiguration.proxyConfiguration().isUseEnvironmentVariableValues(); } } return true; } public Boolean isUseEnvironmentVariableValues() { return useEnvironmentVariableProxyOptionsValues; } public HttpMonitoringOptions httpMonitoringOptions() { return httpMonitoringOptions; } public HttpProxyOptions proxyOptions() { return proxyOptions; } public Duration connectionTimeout() { return connectionTimeout; } public static Builder builder() { return new Builder(); } public String signingRegion() { return signingRegion; } public ClientBootstrap clientBootstrap() { return clientBootstrap; } public CredentialsProvider credentialsProvider() { return credentialsProvider; } public TlsContext tlsContext() { return tlsContext; } public long partSizeBytes() { return partSizeInBytes; } public long thresholdInBytes() { return thresholdInBytes; } public double targetThroughputInGbps() { return targetThroughputInGbps; } public int maxConcurrency() { return maxConcurrency; } public StandardRetryOptions standardRetryOptions() { return standardRetryOptions; } public URI endpointOverride() { return endpointOverride; } public boolean checksumValidationEnabled() { return checksumValidationEnabled; } public Long readBufferSizeInBytes() { return readBufferSizeInBytes; } @Override public void close() { clientBootstrap.close(); tlsContext.close(); credentialProviderAdapter.close(); } public static final class Builder { private Long readBufferSizeInBytes; private String signingRegion; private IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider; private Long partSizeInBytes; private Double targetThroughputInGbps; private Integer maxConcurrency; private URI endpointOverride; private Boolean checksumValidationEnabled; private S3CrtHttpConfiguration httpConfiguration; private StandardRetryOptions standardRetryOptions; private Long thresholdInBytes; private Builder() { } public Builder signingRegion(String signingRegion) { this.signingRegion = signingRegion; return this; } public Builder credentialsProvider(IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider) { this.credentialsProvider = credentialsProvider; return this; } public Builder partSizeInBytes(Long partSizeInBytes) { this.partSizeInBytes = partSizeInBytes; return this; } public Builder targetThroughputInGbps(Double targetThroughputInGbps) { this.targetThroughputInGbps = targetThroughputInGbps; return this; } public Builder maxConcurrency(Integer maxConcurrency) { this.maxConcurrency = maxConcurrency; return this; } public Builder endpointOverride(URI endpointOverride) { this.endpointOverride = endpointOverride; return this; } /** * Option to disable checksum validation of an object stored in S3. */ public Builder checksumValidationEnabled(Boolean checksumValidationEnabled) { this.checksumValidationEnabled = checksumValidationEnabled; return this; } public S3NativeClientConfiguration build() { return new S3NativeClientConfiguration(this); } public Builder readBufferSizeInBytes(Long readBufferSizeInBytes) { this.readBufferSizeInBytes = readBufferSizeInBytes; return this; } public Builder httpConfiguration(S3CrtHttpConfiguration httpConfiguration) { this.httpConfiguration = httpConfiguration; return this; } public Builder standardRetryOptions(StandardRetryOptions standardRetryOptions) { this.standardRetryOptions = standardRetryOptions; return this; } public Builder thresholdInBytes(Long thresholdInBytes) { this.thresholdInBytes = thresholdInBytes; return this; } } }
4,834
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/crt/S3CrtResponseHandlerAdapter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.crt; import static software.amazon.awssdk.utils.FunctionalUtils.runAndLogError; import java.nio.ByteBuffer; import java.util.concurrent.CompletableFuture; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.async.listener.PublisherListener; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.crt.CRT; import software.amazon.awssdk.crt.http.HttpHeader; import software.amazon.awssdk.crt.s3.S3FinishedResponseContext; import software.amazon.awssdk.crt.s3.S3MetaRequest; import software.amazon.awssdk.crt.s3.S3MetaRequestProgress; import software.amazon.awssdk.crt.s3.S3MetaRequestResponseHandler; import software.amazon.awssdk.http.SdkCancellationException; import software.amazon.awssdk.http.SdkHttpResponse; import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.async.SimplePublisher; /** * Adapts {@link SdkAsyncHttpResponseHandler} to {@link S3MetaRequestResponseHandler}. */ @SdkInternalApi public final class S3CrtResponseHandlerAdapter implements S3MetaRequestResponseHandler { private static final Logger log = Logger.loggerFor(S3CrtResponseHandlerAdapter.class); private final CompletableFuture<Void> resultFuture; private final SdkAsyncHttpResponseHandler responseHandler; private final SimplePublisher<ByteBuffer> responsePublisher = new SimplePublisher<>(); private final SdkHttpResponse.Builder respBuilder = SdkHttpResponse.builder(); private volatile S3MetaRequest metaRequest; private final PublisherListener<S3MetaRequestProgress> progressListener; public S3CrtResponseHandlerAdapter(CompletableFuture<Void> executeFuture, SdkAsyncHttpResponseHandler responseHandler, PublisherListener<S3MetaRequestProgress> progressListener) { this.resultFuture = executeFuture; this.responseHandler = responseHandler; this.progressListener = progressListener == null ? new NoOpPublisherListener() : progressListener; } @Override public void onResponseHeaders(int statusCode, HttpHeader[] headers) { for (HttpHeader h : headers) { respBuilder.appendHeader(h.getName(), h.getValue()); } respBuilder.statusCode(statusCode); responseHandler.onHeaders(respBuilder.build()); responseHandler.onStream(responsePublisher); } @Override public int onResponseBody(ByteBuffer bodyBytesIn, long objectRangeStart, long objectRangeEnd) { if (bodyBytesIn == null) { failResponseHandlerAndFuture(new IllegalStateException("ByteBuffer delivered is null")); return 0; } int bytesReceived = bodyBytesIn.remaining(); CompletableFuture<Void> writeFuture = responsePublisher.send(bodyBytesIn); writeFuture.whenComplete((result, failure) -> { if (failure != null) { failResponseHandlerAndFuture(failure); return; } metaRequest.incrementReadWindow(bytesReceived); }); // Returning 0 to disable flow control because we manually increase read window above return 0; } @Override public void onFinished(S3FinishedResponseContext context) { int crtCode = context.getErrorCode(); if (crtCode != CRT.AWS_CRT_SUCCESS) { handleError(context); } else { onSuccessfulResponseComplete(); } } private void onSuccessfulResponseComplete() { responsePublisher.complete().whenComplete((result, failure) -> { if (failure != null) { failResponseHandlerAndFuture(failure); return; } this.progressListener.subscriberOnComplete(); completeFutureAndCloseRequest(); }); } private void completeFutureAndCloseRequest() { resultFuture.complete(null); runAndLogError(log.logger(), "Exception thrown in S3MetaRequest#close, ignoring", () -> metaRequest.close()); } public void cancelRequest() { SdkCancellationException sdkClientException = new SdkCancellationException("request is cancelled"); failResponseHandlerAndFuture(sdkClientException); } private void handleError(S3FinishedResponseContext context) { int crtCode = context.getErrorCode(); int responseStatus = context.getResponseStatus(); byte[] errorPayload = context.getErrorPayload(); if (isErrorResponse(responseStatus) && errorPayload != null) { onErrorResponseComplete(errorPayload); } else { Throwable cause = context.getCause(); SdkClientException sdkClientException = SdkClientException.create("Failed to send the request: " + CRT.awsErrorString(crtCode), cause); failResponseHandlerAndFuture(sdkClientException); } } private void onErrorResponseComplete(byte[] errorPayload) { responsePublisher.send(ByteBuffer.wrap(errorPayload)) .thenRun(responsePublisher::complete) .handle((ignore, throwable) -> { if (throwable != null) { failResponseHandlerAndFuture(throwable); return null; } completeFutureAndCloseRequest(); return null; }); } private void failResponseHandlerAndFuture(Throwable exception) { resultFuture.completeExceptionally(exception); runAndLogError(log.logger(), "Exception thrown in SdkAsyncHttpResponseHandler#onError, ignoring", () -> responseHandler.onError(exception)); runAndLogError(log.logger(), "Exception thrown in S3MetaRequest#close, ignoring", () -> metaRequest.close()); } private static boolean isErrorResponse(int responseStatus) { return responseStatus != 0; } public void metaRequest(S3MetaRequest s3MetaRequest) { metaRequest = s3MetaRequest; } @Override public void onProgress(S3MetaRequestProgress progress) { this.progressListener.subscriberOnNext(progress); } private static class NoOpPublisherListener implements PublisherListener<S3MetaRequestProgress> { } }
4,835
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/crt/CrtCredentialsProviderAdapter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.crt; import java.nio.charset.StandardCharsets; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.crt.auth.credentials.Credentials; import software.amazon.awssdk.crt.auth.credentials.CredentialsProvider; import software.amazon.awssdk.crt.auth.credentials.DelegateCredentialsProvider; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.identity.spi.AwsSessionCredentialsIdentity; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.utils.CompletableFutureUtils; import software.amazon.awssdk.utils.SdkAutoCloseable; /** * Adapts an SDK {@link AwsCredentialsProvider} to CRT {@link CredentialsProvider} */ @SdkInternalApi public final class CrtCredentialsProviderAdapter implements SdkAutoCloseable { private final IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider; private final CredentialsProvider crtCredentials; public CrtCredentialsProviderAdapter(IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider) { this.credentialsProvider = credentialsProvider; this.crtCredentials = new DelegateCredentialsProvider.DelegateCredentialsProviderBuilder() .withHandler(() -> { if (credentialsProvider instanceof AnonymousCredentialsProvider) { return Credentials.createAnonymousCredentials(); } AwsCredentialsIdentity sdkCredentials = CompletableFutureUtils.joinLikeSync(credentialsProvider.resolveIdentity()); byte[] accessKey = sdkCredentials.accessKeyId().getBytes(StandardCharsets.UTF_8); byte[] secreteKey = sdkCredentials.secretAccessKey().getBytes(StandardCharsets.UTF_8); byte[] sessionTokens = null; if (sdkCredentials instanceof AwsSessionCredentialsIdentity) { sessionTokens = ((AwsSessionCredentialsIdentity) sdkCredentials).sessionToken().getBytes(StandardCharsets.UTF_8); } return new Credentials(accessKey, secreteKey, sessionTokens); }).build(); } public CredentialsProvider crtCredentials() { return crtCredentials; } @Override public void close() { if (credentialsProvider instanceof SdkAutoCloseable) { ((SdkAutoCloseable) credentialsProvider).close(); } crtCredentials.close(); } }
4,836
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/crt/S3CrtAsyncClient.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.crt; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.services.s3.S3AsyncClient; import software.amazon.awssdk.services.s3.S3CrtAsyncClientBuilder; /** * Service client for accessing Amazon S3 asynchronously using the AWS Common Runtime S3 client. This can be created using the * static {@link #builder()} method. */ @SdkInternalApi public interface S3CrtAsyncClient extends S3AsyncClient { /** * Create a builder that can be used to configure and create a {@link S3AsyncClient}. */ static S3CrtAsyncClientBuilder builder() { return new DefaultS3CrtAsyncClient.DefaultS3CrtClientBuilder(); } }
4,837
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/crt/S3MetaRequestPauseObservable.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.crt; import java.util.function.Function; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.crt.s3.ResumeToken; import software.amazon.awssdk.crt.s3.S3MetaRequest; /** * An observable that notifies the observer {@link S3CrtAsyncHttpClient} to pause the request. */ @SdkInternalApi public class S3MetaRequestPauseObservable { private final Function<S3MetaRequest, ResumeToken> pause; private volatile S3MetaRequest request; public S3MetaRequestPauseObservable() { this.pause = S3MetaRequest::pause; } /** * Subscribe {@link S3MetaRequest} to be potentially paused later. */ public void subscribe(S3MetaRequest request) { this.request = request; } /** * Pause the request */ public ResumeToken pause() { return pause.apply(request); } }
4,838
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/crt/UploadPartCopyRequestIterable.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.crt; import java.util.Iterator; import java.util.NoSuchElementException; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.pagination.sync.SdkIterable; import software.amazon.awssdk.services.s3.internal.multipart.SdkPojoConversionUtils; import software.amazon.awssdk.services.s3.model.CopyObjectRequest; import software.amazon.awssdk.services.s3.model.UploadPartCopyRequest; /** * Iterable class to generate {@link UploadPartCopyRequest}s */ @SdkInternalApi public final class UploadPartCopyRequestIterable implements SdkIterable<UploadPartCopyRequest> { private final String uploadId; private final long optimalPartSize; private final CopyObjectRequest copyObjectRequest; private long remainingBytes; private int partNumber = 1; private long offset = 0; public UploadPartCopyRequestIterable(String uploadId, long partSize, CopyObjectRequest copyObjectRequest, long remainingBytes) { this.uploadId = uploadId; this.optimalPartSize = partSize; this.copyObjectRequest = copyObjectRequest; this.remainingBytes = remainingBytes; } @Override public Iterator<UploadPartCopyRequest> iterator() { return new UploadPartCopyRequestIterator(); } private class UploadPartCopyRequestIterator implements Iterator<UploadPartCopyRequest> { @Override public boolean hasNext() { return remainingBytes > 0; } @Override public UploadPartCopyRequest next() { if (!hasNext()) { throw new NoSuchElementException("No UploadPartCopyRequest available"); } long partSize = Math.min(optimalPartSize, remainingBytes); String range = range(partSize); UploadPartCopyRequest uploadPartCopyRequest = SdkPojoConversionUtils.toUploadPartCopyRequest(copyObjectRequest, partNumber, uploadId, range); partNumber++; offset += partSize; remainingBytes -= partSize; return uploadPartCopyRequest; } private String range(long partSize) { return "bytes=" + offset + "-" + (offset + partSize - 1); } } }
4,839
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/crt/S3CrtAsyncHttpClient.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.crt; 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.CrtChecksumUtils.checksumConfig; import static software.amazon.awssdk.services.s3.internal.crt.S3InternalSdkHttpExecutionAttribute.CRT_PAUSE_RESUME_TOKEN; import static software.amazon.awssdk.services.s3.internal.crt.S3InternalSdkHttpExecutionAttribute.HTTP_CHECKSUM; import static software.amazon.awssdk.services.s3.internal.crt.S3InternalSdkHttpExecutionAttribute.OBJECT_FILE_PATH; import static software.amazon.awssdk.services.s3.internal.crt.S3InternalSdkHttpExecutionAttribute.OPERATION_NAME; import static software.amazon.awssdk.services.s3.internal.crt.S3InternalSdkHttpExecutionAttribute.SIGNING_REGION; import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely; import java.net.URI; import java.nio.file.Path; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.concurrent.CompletableFuture; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.SdkTestInternalApi; import software.amazon.awssdk.core.interceptor.trait.HttpChecksum; import software.amazon.awssdk.crt.auth.signing.AwsSigningConfig; import software.amazon.awssdk.crt.http.HttpHeader; import software.amazon.awssdk.crt.http.HttpProxyEnvironmentVariableSetting; import software.amazon.awssdk.crt.http.HttpRequest; import software.amazon.awssdk.crt.s3.ChecksumConfig; import software.amazon.awssdk.crt.s3.ResumeToken; import software.amazon.awssdk.crt.s3.S3Client; import software.amazon.awssdk.crt.s3.S3ClientOptions; import software.amazon.awssdk.crt.s3.S3MetaRequest; import software.amazon.awssdk.crt.s3.S3MetaRequestOptions; import software.amazon.awssdk.http.Header; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.http.async.AsyncExecuteRequest; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.utils.AttributeMap; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.NumericUtils; import software.amazon.awssdk.utils.http.SdkHttpUtils; /** * An implementation of {@link SdkAsyncHttpClient} that uses an CRT S3 HTTP client {@link S3Client} to communicate with S3. * Note that it does not work with other services */ @SdkInternalApi public final class S3CrtAsyncHttpClient implements SdkAsyncHttpClient { private static final Logger log = Logger.loggerFor(S3CrtAsyncHttpClient.class); private final S3Client crtS3Client; private final S3NativeClientConfiguration s3NativeClientConfiguration; private final S3ClientOptions s3ClientOptions; private S3CrtAsyncHttpClient(Builder builder) { s3NativeClientConfiguration = builder.clientConfiguration; Long initialWindowSize = s3NativeClientConfiguration.readBufferSizeInBytes(); this.s3ClientOptions = new S3ClientOptions().withRegion(s3NativeClientConfiguration.signingRegion()) .withEndpoint(s3NativeClientConfiguration.endpointOverride() == null ? null : s3NativeClientConfiguration.endpointOverride().toString()) .withCredentialsProvider(s3NativeClientConfiguration.credentialsProvider()) .withClientBootstrap(s3NativeClientConfiguration.clientBootstrap()) .withTlsContext(s3NativeClientConfiguration.tlsContext()) .withPartSize(s3NativeClientConfiguration.partSizeBytes()) .withMultipartUploadThreshold(s3NativeClientConfiguration.thresholdInBytes()) .withComputeContentMd5(false) .withMaxConnections(s3NativeClientConfiguration.maxConcurrency()) .withThroughputTargetGbps(s3NativeClientConfiguration.targetThroughputInGbps()) .withInitialReadWindowSize(initialWindowSize) .withReadBackpressureEnabled(true); if (s3NativeClientConfiguration.standardRetryOptions() != null) { this.s3ClientOptions.withStandardRetryOptions(s3NativeClientConfiguration.standardRetryOptions()); } if (Boolean.FALSE.equals(s3NativeClientConfiguration.isUseEnvironmentVariableValues())) { s3ClientOptions.withProxyEnvironmentVariableSetting(disabledHttpProxyEnvironmentVariableSetting()); } Optional.ofNullable(s3NativeClientConfiguration.proxyOptions()).ifPresent(s3ClientOptions::withProxyOptions); Optional.ofNullable(s3NativeClientConfiguration.connectionTimeout()) .map(Duration::toMillis) .map(NumericUtils::saturatedCast) .ifPresent(s3ClientOptions::withConnectTimeoutMs); Optional.ofNullable(s3NativeClientConfiguration.httpMonitoringOptions()) .ifPresent(s3ClientOptions::withHttpMonitoringOptions); this.crtS3Client = new S3Client(s3ClientOptions); } @SdkTestInternalApi S3CrtAsyncHttpClient(S3Client crtS3Client, S3NativeClientConfiguration nativeClientConfiguration) { this.crtS3Client = crtS3Client; this.s3NativeClientConfiguration = nativeClientConfiguration; this.s3ClientOptions = null; } @SdkTestInternalApi public S3ClientOptions s3ClientOptions() { return s3ClientOptions; } @Override public CompletableFuture<Void> execute(AsyncExecuteRequest asyncRequest) { CompletableFuture<Void> executeFuture = new CompletableFuture<>(); URI uri = asyncRequest.request().getUri(); HttpRequest httpRequest = toCrtRequest(asyncRequest); S3CrtResponseHandlerAdapter responseHandler = new S3CrtResponseHandlerAdapter(executeFuture, asyncRequest.responseHandler(), asyncRequest.httpExecutionAttributes().getAttribute(CRT_PROGRESS_LISTENER)); S3MetaRequestOptions.MetaRequestType requestType = requestType(asyncRequest); HttpChecksum httpChecksum = asyncRequest.httpExecutionAttributes().getAttribute(HTTP_CHECKSUM); ResumeToken resumeToken = asyncRequest.httpExecutionAttributes().getAttribute(CRT_PAUSE_RESUME_TOKEN); Region signingRegion = asyncRequest.httpExecutionAttributes().getAttribute(SIGNING_REGION); Path requestFilePath = asyncRequest.httpExecutionAttributes().getAttribute(OBJECT_FILE_PATH); ChecksumConfig checksumConfig = checksumConfig(httpChecksum, requestType, s3NativeClientConfiguration.checksumValidationEnabled()); URI endpoint = getEndpoint(uri); S3MetaRequestOptions requestOptions = new S3MetaRequestOptions() .withHttpRequest(httpRequest) .withMetaRequestType(requestType) .withChecksumConfig(checksumConfig) .withEndpoint(endpoint) .withResponseHandler(responseHandler) .withResumeToken(resumeToken) .withRequestFilePath(requestFilePath); // Create a new SigningConfig object only if the signing region has changed from the previously configured region. if (signingRegion != null && !s3ClientOptions.getRegion().equals(signingRegion.id())) { requestOptions.withSigningConfig( AwsSigningConfig.getDefaultS3SigningConfig(signingRegion.id(), s3ClientOptions.getCredentialsProvider())); } S3MetaRequest s3MetaRequest = crtS3Client.makeMetaRequest(requestOptions); S3MetaRequestPauseObservable observable = asyncRequest.httpExecutionAttributes().getAttribute(METAREQUEST_PAUSE_OBSERVABLE); responseHandler.metaRequest(s3MetaRequest); if (observable != null) { observable.subscribe(s3MetaRequest); } addCancelCallback(executeFuture, s3MetaRequest, responseHandler); return executeFuture; } private static URI getEndpoint(URI uri) { return invokeSafely(() -> new URI(uri.getScheme(), null, uri.getHost(), uri.getPort(), null, null, null)); } @Override public String clientName() { return "s3crt"; } private static S3MetaRequestOptions.MetaRequestType requestType(AsyncExecuteRequest asyncRequest) { String operationName = asyncRequest.httpExecutionAttributes().getAttribute(OPERATION_NAME); if (operationName != null) { switch (operationName) { case "GetObject": return S3MetaRequestOptions.MetaRequestType.GET_OBJECT; case "PutObject": return S3MetaRequestOptions.MetaRequestType.PUT_OBJECT; default: return S3MetaRequestOptions.MetaRequestType.DEFAULT; } } return S3MetaRequestOptions.MetaRequestType.DEFAULT; } private static void addCancelCallback(CompletableFuture<Void> executeFuture, S3MetaRequest s3MetaRequest, S3CrtResponseHandlerAdapter responseHandler) { executeFuture.whenComplete((r, t) -> { if (executeFuture.isCancelled()) { log.debug(() -> "The request is cancelled, cancelling meta request"); responseHandler.cancelRequest(); s3MetaRequest.cancel(); } }); } private static HttpRequest toCrtRequest(AsyncExecuteRequest asyncRequest) { SdkHttpRequest sdkRequest = asyncRequest.request(); Path requestFilePath = asyncRequest.httpExecutionAttributes().getAttribute(OBJECT_FILE_PATH); String method = sdkRequest.method().name(); String encodedPath = sdkRequest.encodedPath(); if (encodedPath == null || encodedPath.isEmpty()) { encodedPath = "/"; } String encodedQueryString = sdkRequest.encodedQueryParameters() .map(value -> "?" + value) .orElse(""); HttpHeader[] crtHeaderArray = createHttpHeaderList(asyncRequest).toArray(new HttpHeader[0]); S3CrtRequestBodyStreamAdapter sdkToCrtRequestPublisher = requestFilePath == null ? new S3CrtRequestBodyStreamAdapter(asyncRequest.requestContentPublisher()) : null; return new HttpRequest(method, encodedPath + encodedQueryString, crtHeaderArray, sdkToCrtRequestPublisher); } @Override public void close() { s3NativeClientConfiguration.close(); crtS3Client.close(); } public static Builder builder() { return new Builder(); } public static final class Builder implements SdkAsyncHttpClient.Builder<S3CrtAsyncHttpClient.Builder> { private S3NativeClientConfiguration clientConfiguration; public Builder s3ClientConfiguration(S3NativeClientConfiguration clientConfiguration) { this.clientConfiguration = clientConfiguration; return this; } @Override public SdkAsyncHttpClient build() { return new S3CrtAsyncHttpClient(this); } @Override public SdkAsyncHttpClient buildWithDefaults(AttributeMap serviceDefaults) { // Intentionally ignore serviceDefaults return build(); } } private static List<HttpHeader> createHttpHeaderList(AsyncExecuteRequest asyncRequest) { SdkHttpRequest sdkRequest = asyncRequest.request(); List<HttpHeader> crtHeaderList = new ArrayList<>(); // Set Host Header if needed if (!sdkRequest.firstMatchingHeader(Header.HOST).isPresent()) { String hostHeader = getHostHeaderValue(asyncRequest.request()); crtHeaderList.add(new HttpHeader(Header.HOST, hostHeader)); } // Set Content-Length if needed Optional<Long> contentLength = asyncRequest.requestContentPublisher().contentLength(); if (!sdkRequest.firstMatchingHeader(Header.CONTENT_LENGTH).isPresent() && contentLength.isPresent()) { crtHeaderList.add(new HttpHeader(Header.CONTENT_LENGTH, Long.toString(contentLength.get()))); } // Add the rest of the Headers sdkRequest.forEachHeader((key, value) -> value.stream().map(val -> new HttpHeader(key, val)) .forEach(crtHeaderList::add)); return crtHeaderList; } private static String getHostHeaderValue(SdkHttpRequest request) { return SdkHttpUtils.isUsingStandardPort(request.protocol(), request.port()) ? request.host() : request.host() + ":" + request.port(); } private static HttpProxyEnvironmentVariableSetting disabledHttpProxyEnvironmentVariableSetting() { HttpProxyEnvironmentVariableSetting proxyEnvSetting = new HttpProxyEnvironmentVariableSetting(); proxyEnvSetting.setEnvironmentVariableType(HttpProxyEnvironmentVariableSetting.HttpProxyEnvironmentVariableType.DISABLED); return proxyEnvSetting; } }
4,840
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/crt/CrtContentLengthOnlyAsyncFileRequestBody.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.crt; import java.nio.ByteBuffer; import java.nio.file.Path; import java.util.Optional; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.async.AsyncRequestBody; @SdkInternalApi public final class CrtContentLengthOnlyAsyncFileRequestBody implements AsyncRequestBody { private final AsyncRequestBody asyncRequestBody; public CrtContentLengthOnlyAsyncFileRequestBody(Path path) { this.asyncRequestBody = AsyncRequestBody.fromFile(path); } @Override public Optional<Long> contentLength() { return asyncRequestBody.contentLength(); } @Override public void subscribe(Subscriber<? super ByteBuffer> subscriber) { subscriber.onSubscribe(new Subscription() { @Override public void request(long l) { subscriber.onError(new IllegalStateException("subscription not supported")); } @Override public void cancel() { } }); } }
4,841
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/resource/S3ResourceType.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.resource; import software.amazon.awssdk.annotations.SdkInternalApi; /** * An enum representing the types of resources supported by S3. Each resource type below will have a * concrete implementation of {@link S3Resource}. */ @SdkInternalApi public enum S3ResourceType { /** * A specific S3 bucket. Implemented by {@link S3BucketResource}. */ BUCKET("bucket_name"), /** * An access point that fronts a bucket. Implemented by {@link S3AccessPointResource}. */ ACCESS_POINT("accesspoint"), /** * A specific S3 object (bucket and key). Implemented by {@link S3ObjectResource}. */ OBJECT("object"), /** * An outpost access point. Implemented by {@link S3OutpostResource}. */ OUTPOST("outpost"), /** * An object lambda access point. Implemented by {@link S3ObjectLambdaResource} */ OBJECT_LAMBDA("object-lambda"); private final String value; S3ResourceType(String value) { this.value = value; } /** * @return The canonical string value of this resource type. */ @Override public String toString() { return value; } /** * Use this in place of valueOf. * * @param value real value * @return S3ResourceType corresponding to the value * @throws IllegalArgumentException If the specified value does not map to one of the known values in this enum. */ public static S3ResourceType fromValue(String value) { if (value == null || "".equals(value)) { throw new IllegalArgumentException("Value cannot be null or empty!"); } for (S3ResourceType enumEntry : S3ResourceType.values()) { if (enumEntry.toString().equals(value)) { return enumEntry; } } throw new IllegalArgumentException("Cannot create enum from " + value + " value!"); } }
4,842
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/resource/S3ArnUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.resource; import java.util.Optional; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.arns.Arn; import software.amazon.awssdk.arns.ArnResource; import software.amazon.awssdk.utils.StringUtils; @SdkInternalApi public class S3ArnUtils { private static final int OUTPOST_ID_START_INDEX = "outpost".length() + 1; private S3ArnUtils() { } public static S3AccessPointResource parseS3AccessPointArn(Arn arn) { return S3AccessPointResource.builder() .partition(arn.partition()) .region(arn.region().orElse(null)) .accountId(arn.accountId().orElse(null)) .accessPointName(arn.resource().resource()) .build(); } public static IntermediateOutpostResource parseOutpostArn(Arn arn) { String resource = arn.resourceAsString(); Integer outpostIdEndIndex = null; for (int i = OUTPOST_ID_START_INDEX; i < resource.length(); ++i) { char ch = resource.charAt(i); if (ch == ':' || ch == '/') { outpostIdEndIndex = i; break; } } if (outpostIdEndIndex == null) { throw new IllegalArgumentException("Invalid format for S3 outpost ARN, missing outpostId"); } String outpostId = resource.substring(OUTPOST_ID_START_INDEX, outpostIdEndIndex); if (StringUtils.isEmpty(outpostId)) { throw new IllegalArgumentException("Invalid format for S3 outpost ARN, missing outpostId"); } String subresource = resource.substring(outpostIdEndIndex + 1); if (StringUtils.isEmpty(subresource)) { throw new IllegalArgumentException("Invalid format for S3 outpost ARN"); } return IntermediateOutpostResource.builder() .outpostId(outpostId) .outpostSubresource(ArnResource.fromString(subresource)) .build(); } public static Optional<S3ResourceType> getArnType(String arnString) { try { Arn arn = Arn.fromString(arnString); String resourceType = arn.resource().resourceType().get(); S3ResourceType s3ResourceType = S3ResourceType.fromValue(resourceType); return Optional.of(s3ResourceType); } catch (Exception ignored) { return Optional.empty(); } } }
4,843
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/resource/S3AccessPointResource.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.resource; import java.util.EnumSet; import java.util.Optional; import java.util.Set; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.auth.signer.SignerLoader; import software.amazon.awssdk.core.signer.Signer; import software.amazon.awssdk.utils.StringUtils; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * An {@link S3Resource} that represents an S3 access point. */ @SdkInternalApi public final class S3AccessPointResource implements S3Resource, ToCopyableBuilder<S3AccessPointResource.Builder, S3AccessPointResource> { private static final S3ResourceType S3_RESOURCE_TYPE = S3ResourceType.ACCESS_POINT; private static final Set<S3ResourceType> VALID_PARENT_RESOURCE_TYPES = EnumSet.of(S3ResourceType.OUTPOST, S3ResourceType.OBJECT_LAMBDA); private final String partition; private final String region; private final String accountId; private final String accessPointName; private final S3Resource parentS3Resource; private S3AccessPointResource(Builder b) { this.accessPointName = Validate.paramNotBlank(b.accessPointName, "accessPointName"); if (b.parentS3Resource == null) { this.parentS3Resource = null; this.partition = Validate.paramNotBlank(b.partition, "partition"); this.region = b.region; this.accountId = Validate.paramNotBlank(b.accountId, "accountId"); } else { this.parentS3Resource = validateParentS3Resource(b.parentS3Resource); Validate.isTrue(b.partition == null, "partition cannot be set on builder if it has parent resource"); Validate.isTrue(b.region == null, "region cannot be set on builder if it has parent resource"); Validate.isTrue(b.accountId == null, "accountId cannot be set on builder if it has parent resource"); this.partition = parentS3Resource.partition().orElse(null); this.region = parentS3Resource.region().orElse(null); this.accountId = parentS3Resource.accountId().orElse(null); } } /** * Get a new builder for this class. * @return A newly initialized instance of a builder. */ public static Builder builder() { return new Builder(); } /** * Gets the resource type for this access point. * @return This will always return "access_point". */ @Override public String type() { return S3_RESOURCE_TYPE.toString(); } @Override public Optional<S3Resource> parentS3Resource() { return Optional.ofNullable(parentS3Resource); } /** * Gets the AWS partition name associated with this access point (e.g.: 'aws'). * @return the name of the partition. */ @Override public Optional<String> partition() { return Optional.ofNullable(this.partition); } /** * Gets the AWS region name associated with this bucket (e.g.: 'us-east-1'). * @return the name of the region. */ @Override public Optional<String> region() { return Optional.ofNullable(this.region); } /** * Gets the AWS account ID associated with this bucket. * @return the AWS account ID. */ @Override public Optional<String> accountId() { return Optional.ofNullable(this.accountId); } /** * Gets the name of the access point. * @return the name of the access point. */ public String accessPointName() { return this.accessPointName; } @Override public Optional<Signer> overrideSigner() { return StringUtils.isEmpty(region) ? Optional.of(SignerLoader.getS3SigV4aSigner()) : Optional.empty(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } S3AccessPointResource that = (S3AccessPointResource) o; if (partition != null ? ! partition.equals(that.partition) : that.partition != null) { return false; } if (region != null ? ! region.equals(that.region) : that.region != null) { return false; } if (accountId != null ? ! accountId.equals(that.accountId) : that.accountId != null) { return false; } if (parentS3Resource != null ? ! parentS3Resource.equals(that.parentS3Resource) : that.parentS3Resource != null) { return false; } return accessPointName.equals(that.accessPointName); } @Override public int hashCode() { int result = partition != null ? partition.hashCode() : 0; result = 31 * result + (region != null ? region.hashCode() : 0); result = 31 * result + (accountId != null ? accountId.hashCode() : 0); result = 31 * result + accessPointName.hashCode(); result = 31 * result + (parentS3Resource != null ? parentS3Resource.hashCode() : 0); return result; } @Override public Builder toBuilder() { return builder() .partition(partition) .region(region) .accountId(accountId) .accessPointName(accessPointName); } private S3Resource validateParentS3Resource(S3Resource parentS3Resource) { String invalidParentResourceTypeMessage = "Invalid 'parentS3Resource' type. An S3 access point resource must be " + "associated with an outpost or object lambda parent resource."; VALID_PARENT_RESOURCE_TYPES.stream() .filter(r -> r.toString().equals(parentS3Resource.type())) .findAny() .orElseThrow(() -> new IllegalArgumentException(invalidParentResourceTypeMessage)); return parentS3Resource; } /** * A builder for {@link S3AccessPointResource} objects. */ public static final class Builder implements CopyableBuilder<Builder, S3AccessPointResource> { private String partition; private String region; private String accountId; private String accessPointName; private S3Resource parentS3Resource; private Builder() { } public void setPartition(String partition) { partition(partition); } /** * The AWS partition associated with the access point. */ public Builder partition(String partition) { this.partition = partition; return this; } public void setRegion(String region) { region(region); } /** * The AWS region associated with the access point. */ public Builder region(String region) { this.region = region; return this; } public void setAccountId(String accountId) { accountId(accountId); } /** * The AWS account ID associated with the access point. */ public Builder accountId(String accountId) { this.accountId = accountId; return this; } public void setAccessPointName(String accessPointName) { accessPointName(accessPointName); } /** * The name of the S3 access point. */ public Builder accessPointName(String accessPointName) { this.accessPointName = accessPointName; return this; } /** * The S3 resource this access point is associated with (contained within). Only {@link S3OutpostResource} * is a valid parent resource types. */ public Builder parentS3Resource(S3Resource parentS3Resource) { this.parentS3Resource = parentS3Resource; return this; } /** * Builds an instance of {@link S3AccessPointResource}. */ @Override public S3AccessPointResource build() { return new S3AccessPointResource(this); } } }
4,844
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/resource/S3ObjectResource.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.resource; import java.util.Optional; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.utils.Validate; /** * An {@link S3Resource} that represents an S3 object. */ @SdkInternalApi public final class S3ObjectResource implements S3Resource { private static final S3ResourceType S3_RESOURCE_TYPE = S3ResourceType.OBJECT; private final S3Resource parentS3Resource; private final String key; private S3ObjectResource(Builder b) { this.parentS3Resource = validateParentS3Resource(b.parentS3Resource); this.key = Validate.paramNotBlank(b.key, "key"); } /** * Get a new builder for this class. * @return A newly initialized instance of a builder. */ public static Builder builder() { return new Builder(); } /** * Gets the resource type for this S3 object. * @return This will always return "object". */ @Override public String type() { return S3_RESOURCE_TYPE.toString(); } /** * Gets the AWS partition name associated with the S3 object (e.g.: 'aws'). * @return the name of the partition. */ @Override public Optional<String> partition() { return parentS3Resource.partition(); } /** * Gets the AWS region name associated with the S3 object (e.g.: 'us-east-1'). * @return the name of the region or null if the region has not been specified (e.g. the resource is in the * global namespace). */ @Override public Optional<String> region() { return parentS3Resource.region(); } /** * Gets the AWS account ID associated with the S3 object if it has been specified. * @return the optional AWS account ID or empty if the account ID has not been specified. */ @Override public Optional<String> accountId() { return parentS3Resource.accountId(); } /** * Gets the key of the S3 object. * @return the key of the S3 object. */ public String key() { return this.key; } @Override public Optional<S3Resource> parentS3Resource() { return Optional.of(parentS3Resource); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } S3ObjectResource that = (S3ObjectResource) o; if (parentS3Resource != null ? !parentS3Resource.equals(that.parentS3Resource) : that.parentS3Resource != null) { return false; } return key != null ? key.equals(that.key) : that.key == null; } @Override public int hashCode() { int result = parentS3Resource != null ? parentS3Resource.hashCode() : 0; result = 31 * result + (key != null ? key.hashCode() : 0); return result; } private S3Resource validateParentS3Resource(S3Resource parentS3Resource) { Validate.paramNotNull(parentS3Resource, "parentS3Resource"); if (!S3ResourceType.ACCESS_POINT.toString().equals(parentS3Resource.type()) && !S3ResourceType.BUCKET.toString().equals(parentS3Resource.type())) { throw new IllegalArgumentException("Invalid 'parentS3Resource' type. An S3 object resource must be " + "associated with either a bucket or access-point parent resource."); } return parentS3Resource; } /** * A builder for {@link S3ObjectResource} objects. */ public static final class Builder { private S3Resource parentS3Resource; private String key; private Builder() { } /** * The key of the S3 object. */ public Builder key(String key) { this.key = key; return this; } /** * The S3 resource this object is associated with (contained within). Only {@link S3BucketResource} and * {@link S3AccessPointResource} are valid parent resource types. */ public Builder parentS3Resource(S3Resource parentS3Resource) { this.parentS3Resource = parentS3Resource; return this; } /** * Builds an instance of {@link S3BucketResource}. */ public S3ObjectResource build() { return new S3ObjectResource(this); } } }
4,845
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/resource/IntermediateOutpostResource.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.resource; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.arns.ArnResource; import software.amazon.awssdk.utils.StringUtils; import software.amazon.awssdk.utils.Validate; /** * The intermediate outpost resource */ @SdkInternalApi public final class IntermediateOutpostResource { private final String outpostId; private final ArnResource outpostSubresource; private IntermediateOutpostResource(Builder builder) { this.outpostId = Validate.paramNotBlank(builder.outpostId, "outpostId"); this.outpostSubresource = Validate.notNull(builder.outpostSubresource, "outpostSubresource"); Validate.isTrue(StringUtils.isNotBlank(builder.outpostSubresource.resource()), "Invalid format for S3 Outpost ARN"); Validate.isTrue(builder.outpostSubresource.resourceType().isPresent(), "Invalid format for S3 Outpost ARN"); } public static Builder builder() { return new Builder(); } /** * @return the ID of the outpost */ public String outpostId() { return outpostId; } /** * @return the outpost subresource */ public ArnResource outpostSubresource() { return outpostSubresource; } public static final class Builder { private String outpostId; private ArnResource outpostSubresource; private Builder() { } /** * Sets the outpostSubResource * * @param outpostSubResource The new outpostSubResource value. * @return This object for method chaining. */ public Builder outpostSubresource(ArnResource outpostSubResource) { this.outpostSubresource = outpostSubResource; return this; } /** * Sets the outpostId * * @param outpostId The new outpostId value. * @return This object for method chaining. */ public Builder outpostId(String outpostId) { this.outpostId = outpostId; return this; } public IntermediateOutpostResource build() { return new IntermediateOutpostResource(this); } } }
4,846
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/resource/OutpostResourceType.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.resource; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.utils.StringUtils; /** * An enum representing the types of resources supported by S3 outpost. Each resource type below will have a * concrete implementation of {@link S3OutpostResource}. */ @SdkInternalApi public enum OutpostResourceType { /** * A specific S3 outpost bucket. */ OUTPOST_BUCKET("bucket"), /** * An outpost access point */ OUTPOST_ACCESS_POINT("accesspoint"); private final String value; OutpostResourceType(String value) { this.value = value; } /** * @return The canonical string value of this resource type. */ @Override public String toString() { return value; } /** * Use this in place of valueOf. * * @param value real value * @return S3ResourceType corresponding to the value * @throws IllegalArgumentException If the specified value does not map to one of the known values in this enum. */ public static OutpostResourceType fromValue(String value) { if (StringUtils.isEmpty(value)) { throw new IllegalArgumentException("value cannot be null or empty!"); } for (OutpostResourceType enumEntry : OutpostResourceType.values()) { if (enumEntry.toString().equals(value)) { return enumEntry; } } throw new IllegalArgumentException("Cannot create enum from " + value + " value!"); } }
4,847
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/resource/S3OutpostResource.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.resource; import java.util.Optional; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.utils.Validate; /** * An {@link S3Resource} that represents an S3 outpost resource */ @SdkInternalApi public final class S3OutpostResource implements S3Resource { private final String partition; private final String region; private final String accountId; private final String outpostId; private S3OutpostResource(Builder b) { this.partition = Validate.paramNotBlank(b.partition, "partition"); this.region = Validate.paramNotBlank(b.region, "region"); this.accountId = Validate.paramNotBlank(b.accountId, "accountId"); this.outpostId = Validate.paramNotBlank(b.outpostId, "outpostId"); } /** * Get a new builder for this class. * @return A newly initialized instance of a builder. */ public static Builder builder() { return new Builder(); } /** * Gets the resource type for this access point. * @return This will always return "accesspoint". */ @Override public String type() { return S3ResourceType.OUTPOST.toString(); } /** * Gets the AWS partition name associated with this access point (e.g.: 'aws'). * @return the name of the partition. */ @Override public Optional<String> partition() { return Optional.ofNullable(this.partition); } /** * Gets the AWS region name associated with this bucket (e.g.: 'us-east-1'). * @return the name of the region. */ @Override public Optional<String> region() { return Optional.ofNullable(this.region); } /** * Gets the AWS account ID associated with this bucket. * @return the AWS account ID. */ @Override public Optional<String> accountId() { return Optional.ofNullable(this.accountId); } /** * Gets the outpost ID * @return the outpost ID. */ public String outpostId() { return this.outpostId; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } S3OutpostResource that = (S3OutpostResource) o; if (partition != null ? !partition.equals(that.partition) : that.partition != null) { return false; } if (region != null ? !region.equals(that.region) : that.region != null) { return false; } if (accountId != null ? !accountId.equals(that.accountId) : that.accountId != null) { return false; } return outpostId.equals(that.outpostId); } @Override public int hashCode() { int result = partition != null ? partition.hashCode() : 0; result = 31 * result + (region != null ? region.hashCode() : 0); result = 31 * result + (accountId != null ? accountId.hashCode() : 0); result = 31 * result + outpostId.hashCode(); return result; } /** * A builder for {@link S3OutpostResource} objects. */ public static final class Builder { private String outpostId; private String partition; private String region; private String accountId; private Builder() { } /** * The AWS partition associated with the access point. */ public Builder partition(String partition) { this.partition = partition; return this; } /** * The AWS region associated with the access point. */ public Builder region(String region) { this.region = region; return this; } /** * The AWS account ID associated with the access point. */ public Builder accountId(String accountId) { this.accountId = accountId; return this; } /** * The Id of the outpost */ public Builder outpostId(String outpostId) { this.outpostId = outpostId; return this; } /** * Builds an instance of {@link S3OutpostResource}. */ public S3OutpostResource build() { return new S3OutpostResource(this); } } }
4,848
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/resource/S3ArnConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.resource; import static software.amazon.awssdk.services.s3.internal.resource.S3ArnUtils.parseOutpostArn; import java.util.regex.Matcher; import java.util.regex.Pattern; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.arns.Arn; import software.amazon.awssdk.arns.ArnResource; /** * An implementation of {@link ArnConverter} that can be used to convert valid {@link Arn} representations of s3 * resources into {@link S3Resource} objects. To fetch an instance of this class, use the singleton getter method * {@link #create()}. */ @SdkInternalApi public final class S3ArnConverter implements ArnConverter<S3Resource> { private static final S3ArnConverter INSTANCE = new S3ArnConverter(); private static final Pattern OBJECT_AP_PATTERN = Pattern.compile("^([0-9a-zA-Z-]+)/object/(.*)$"); private static final String OBJECT_LAMBDA_SERVICE = "s3-object-lambda"; private S3ArnConverter() { } /** * Gets a static singleton instance of an {@link S3ArnConverter}. * @return A static instance of an {@link S3ArnConverter}. */ public static S3ArnConverter create() { return INSTANCE; } /** * Converts a valid ARN representation of an S3 resource into a {@link S3Resource} object. * @param arn The ARN to convert. * @return An {@link S3Resource} object as specified by the ARN. * @throws IllegalArgumentException if the ARN is not a valid representation of an S3 resource supported by this * SDK. */ @Override public S3Resource convertArn(Arn arn) { if (isV1Arn(arn)) { return convertV1Arn(arn); } S3ResourceType s3ResourceType; String resourceType = arn.resource().resourceType() .orElseThrow(() -> new IllegalArgumentException("Unknown ARN type")); try { s3ResourceType = S3ResourceType.fromValue(resourceType); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Unknown ARN type '" + arn.resource().resourceType().get() + "'"); } // OBJECT is a sub-resource under ACCESS_POINT and BUCKET and will not be recognized as a primary ARN resource // type switch (s3ResourceType) { case ACCESS_POINT: return parseS3AccessPointArn(arn); case BUCKET: return parseS3BucketArn(arn); case OUTPOST: return parseS3OutpostAccessPointArn(arn); default: throw new IllegalArgumentException("Unknown ARN type '" + s3ResourceType + "'"); } } private S3Resource convertV1Arn(Arn arn) { String resource = arn.resourceAsString(); String[] splitResource = resource.split("/", 2); if (splitResource.length > 1) { // Bucket/key S3BucketResource parentBucket = S3BucketResource.builder() .partition(arn.partition()) .bucketName(splitResource[0]) .build(); return S3ObjectResource.builder() .parentS3Resource(parentBucket) .key(splitResource[1]) .build(); } else { // Just bucket return S3BucketResource.builder() .partition(arn.partition()) .bucketName(resource) .build(); } } private S3BucketResource parseS3BucketArn(Arn arn) { return S3BucketResource.builder() .partition(arn.partition()) .region(arn.region().orElse(null)) .accountId(arn.accountId().orElse(null)) .bucketName(arn.resource().resource()) .build(); } private S3Resource parseS3AccessPointArn(Arn arn) { Matcher objectMatcher = OBJECT_AP_PATTERN.matcher(arn.resource().resource()); if (objectMatcher.matches()) { // ARN is actually an object addressed through an access-point String accessPointName = objectMatcher.group(1); String objectKey = objectMatcher.group(2); S3AccessPointResource parentResource = S3AccessPointResource.builder() .partition(arn.partition()) .region(arn.region().orElse(null)) .accountId(arn.accountId().orElse(null)) .accessPointName(accessPointName) .build(); return S3ObjectResource.builder() .parentS3Resource(parentResource) .key(objectKey) .build(); } if (OBJECT_LAMBDA_SERVICE.equals(arn.service())) { return parseS3ObjectLambdaAccessPointArn(arn); } return S3AccessPointResource.builder() .partition(arn.partition()) .region(arn.region().orElse(null)) .accountId(arn.accountId().orElse(null)) .accessPointName(arn.resource().resource()) .build(); } private S3Resource parseS3OutpostAccessPointArn(Arn arn) { IntermediateOutpostResource intermediateOutpostResource = parseOutpostArn(arn); ArnResource outpostSubResource = intermediateOutpostResource.outpostSubresource(); String resourceType = outpostSubResource.resourceType() .orElseThrow(() -> new IllegalArgumentException("Unknown ARN type")); if (!OutpostResourceType.OUTPOST_ACCESS_POINT.toString().equals(resourceType)) { throw new IllegalArgumentException("Unknown outpost ARN type '" + outpostSubResource.resourceType() + "'"); } return S3AccessPointResource.builder() .accessPointName(outpostSubResource.resource()) .parentS3Resource(S3OutpostResource.builder() .partition(arn.partition()) .region(arn.region().orElse(null)) .accountId(arn.accountId().orElse(null)) .outpostId(intermediateOutpostResource.outpostId()) .build()) .build(); } private S3Resource parseS3ObjectLambdaAccessPointArn(Arn arn) { if (arn.resource().qualifier().isPresent()) { throw new IllegalArgumentException("S3 object lambda access point arn shouldn't contain any sub resources."); } S3ObjectLambdaResource objectLambdaResource = S3ObjectLambdaResource.builder() .accountId(arn.accountId().orElse(null)) .region(arn.region().orElse(null)) .partition(arn.partition()) .accessPointName(arn.resource().resource()) .build(); return S3AccessPointResource.builder() .accessPointName(objectLambdaResource.accessPointName()) .parentS3Resource(objectLambdaResource) .build(); } private boolean isV1Arn(Arn arn) { return !arn.accountId().isPresent() && !arn.region().isPresent(); } }
4,849
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/resource/S3OutpostAccessPointBuilder.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.resource; import static software.amazon.awssdk.utils.HostnameValidator.validateHostnameCompliant; import static software.amazon.awssdk.utils.http.SdkHttpUtils.urlEncode; import java.net.URI; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.exception.SdkClientException; /** * This class is used to construct an endpoint for an S3 outpost access point. */ @SdkInternalApi public final class S3OutpostAccessPointBuilder { private URI endpointOverride; private String accessPointName; private String outpostId; private String region; private String accountId; private String protocol; private String domain; private S3OutpostAccessPointBuilder() { } /** * Create a new instance of this builder class. */ public static S3OutpostAccessPointBuilder create() { return new S3OutpostAccessPointBuilder(); } /** * The endpoint override configured on the client (null if no endpoint override was set). */ public S3OutpostAccessPointBuilder endpointOverride(URI endpointOverride) { this.endpointOverride = endpointOverride; return this; } public S3OutpostAccessPointBuilder accessPointName(String accessPointName) { this.accessPointName = accessPointName; return this; } public S3OutpostAccessPointBuilder region(String region) { this.region = region; return this; } public S3OutpostAccessPointBuilder accountId(String accountId) { this.accountId = accountId; return this; } public S3OutpostAccessPointBuilder outpostId(String outpostId) { this.outpostId = outpostId; return this; } public S3OutpostAccessPointBuilder protocol(String protocol) { this.protocol = protocol; return this; } public S3OutpostAccessPointBuilder domain(String domain) { this.domain = domain; return this; } /** * Generate an endpoint URI with no path that maps to the Outpost Access Point information stored in this builder. */ public URI toUri() { validateHostnameCompliant(outpostId, "outpostId", "outpost ARN"); validateHostnameCompliant(accountId, "accountId", "outpost ARN"); validateHostnameCompliant(accessPointName, "accessPointName", "outpost ARN"); String uri; if (endpointOverride == null) { uri = String.format("%s://%s-%s.%s.s3-outposts.%s.%s", protocol, accessPointName, accountId, outpostId, region, domain); } else { StringBuilder uriSuffix = new StringBuilder(endpointOverride.getHost()); if (endpointOverride.getPort() > 0) { uriSuffix.append(":").append(endpointOverride.getPort()); } if (endpointOverride.getPath() != null) { uriSuffix.append(endpointOverride.getPath()); } uri = String.format("%s://%s-%s.%s.%s", protocol, urlEncode(accessPointName), accountId, outpostId, uriSuffix); } URI result = URI.create(uri); if (result.getHost() == null) { throw SdkClientException.create("Request resulted in an invalid URI: " + result); } return result; } }
4,850
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/resource/S3Resource.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.resource; import java.util.Optional; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.core.signer.Signer; /** * A representation of an AWS S3 resource. See {@link S3ResourceType} for a list and description of all valid types. */ @SdkProtectedApi public interface S3Resource extends AwsResource { /** * Gets the type of S3 resource represented by this object (e.g.: 'bucket_name'). See {@link S3ResourceType} for * a list and description of all valid types. * @return the string name of the S3 resource type. */ String type(); /** * Gets the optional parent resource. * @return the optional parent resource. */ default Optional<S3Resource> parentS3Resource() { return Optional.empty(); } default Optional<Signer> overrideSigner() { return Optional.empty(); } }
4,851
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/resource/S3BucketResource.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.resource; import java.util.Optional; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * An {@link S3Resource} that represents an S3 bucket. */ @SdkInternalApi public final class S3BucketResource implements S3Resource, ToCopyableBuilder<S3BucketResource.Builder, S3BucketResource> { private static final S3ResourceType S3_RESOURCE_TYPE = S3ResourceType.BUCKET; private final String partition; private final String region; private final String accountId; private final String bucketName; private S3BucketResource(Builder b) { this.bucketName = Validate.paramNotBlank(b.bucketName, "bucketName"); this.partition = b.partition; this.region = b.region; this.accountId = b.accountId; } /** * Get a new builder for this class. * @return A newly initialized instance of a builder. */ public static Builder builder() { return new Builder(); } /** * Gets the resource type for this bucket. * @return This will always return "bucket_name". */ @Override public String type() { return S3_RESOURCE_TYPE.toString(); } /** * Gets the AWS partition name associated with this bucket (e.g.: 'aws') if one has been specified. * @return the optional name of the partition or empty if it has not been specified. */ @Override public Optional<String> partition() { return Optional.ofNullable(this.partition); } /** * Gets the AWS region name associated with this bucket (e.g.: 'us-east-1') if one has been specified. * @return the optional name of the region or empty if the region has not been specified (e.g. the resource is in * the global namespace). */ @Override public Optional<String> region() { return Optional.ofNullable(this.region); } /** * Gets the AWS account ID associated with this bucket if one has been specified. * @return the optional AWS account ID or empty if the account ID has not been specified. */ @Override public Optional<String> accountId() { return Optional.ofNullable(this.accountId); } /** * Gets the name of the bucket. * @return the name of the bucket. */ public String bucketName() { return this.bucketName; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } S3BucketResource that = (S3BucketResource) o; if (partition != null ? ! partition.equals(that.partition) : that.partition != null) { return false; } if (region != null ? ! region.equals(that.region) : that.region != null) { return false; } if (accountId != null ? ! accountId.equals(that.accountId) : that.accountId != null) { return false; } return bucketName.equals(that.bucketName); } @Override public int hashCode() { int result = partition != null ? partition.hashCode() : 0; result = 31 * result + (region != null ? region.hashCode() : 0); result = 31 * result + (accountId != null ? accountId.hashCode() : 0); result = 31 * result + bucketName.hashCode(); return result; } @Override public Builder toBuilder() { return builder() .partition(partition) .region(region) .accountId(accountId) .bucketName(bucketName); } /** * A builder for {@link S3BucketResource} objects. */ public static final class Builder implements CopyableBuilder<Builder, S3BucketResource> { private String partition; private String region; private String accountId; private String bucketName; private Builder() { } public void setPartition(String partition) { partition(partition); } /** * The AWS partition associated with the bucket. */ public Builder partition(String partition) { this.partition = partition; return this; } public void setRegion(String region) { region(region); } /** * The AWS region associated with the bucket. This property is optional. */ public Builder region(String region) { this.region = region; return this; } public void setAccountId(String accountId) { accountId(accountId); } /** * The AWS account ID associated with the bucket. This property is optional. */ public Builder accountId(String accountId) { this.accountId = accountId; return this; } public void setBucketName(String bucketName) { bucketName(bucketName); } /** * The name of the S3 bucket. */ public Builder bucketName(String bucketName) { this.bucketName = bucketName; return this; } /** * Builds an instance of {@link S3BucketResource}. */ @Override public S3BucketResource build() { return new S3BucketResource(this); } } }
4,852
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/resource/S3ObjectLambdaEndpointBuilder.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.resource; import static software.amazon.awssdk.utils.HostnameValidator.validateHostnameCompliant; import java.net.URI; import software.amazon.awssdk.annotations.SdkInternalApi; /** * This class is used to construct an endpoint for an S3 Object Lambda access point. */ @SdkInternalApi public class S3ObjectLambdaEndpointBuilder { private URI endpointOverride; private String accessPointName; private String region; private String accountId; private String protocol; private String domain; private Boolean fipsEnabled; private Boolean dualstackEnabled; private S3ObjectLambdaEndpointBuilder() { } /** * Create a new instance of this builder class. */ public static S3ObjectLambdaEndpointBuilder create() { return new S3ObjectLambdaEndpointBuilder(); } /** * The endpoint override configured on the client (null if no endpoint override was set). */ public S3ObjectLambdaEndpointBuilder endpointOverride(URI endpointOverride) { this.endpointOverride = endpointOverride; return this; } public S3ObjectLambdaEndpointBuilder accessPointName(String accessPointName) { this.accessPointName = accessPointName; return this; } public S3ObjectLambdaEndpointBuilder region(String region) { this.region = region; return this; } public S3ObjectLambdaEndpointBuilder accountId(String accountId) { this.accountId = accountId; return this; } public S3ObjectLambdaEndpointBuilder protocol(String protocol) { this.protocol = protocol; return this; } public S3ObjectLambdaEndpointBuilder domain(String domain) { this.domain = domain; return this; } public S3ObjectLambdaEndpointBuilder fipsEnabled(Boolean fipsEnabled) { this.fipsEnabled = fipsEnabled; return this; } public S3ObjectLambdaEndpointBuilder dualstackEnabled(Boolean dualstackEnabled) { this.dualstackEnabled = dualstackEnabled; return this; } public URI toUri() { validateHostnameCompliant(accountId, "accountId", "object lambda ARN"); validateHostnameCompliant(accessPointName, "accessPointName", "object lambda ARN"); String fipsSegment = Boolean.TRUE.equals(fipsEnabled) ? "-fips" : ""; String uriString; if (endpointOverride == null) { if (Boolean.TRUE.equals(dualstackEnabled)) { throw new IllegalStateException("S3 Object Lambda does not support Dual stack endpoints."); } uriString = String.format("%s://%s-%s.s3-object-lambda%s.%s.%s", protocol, accessPointName, accountId, fipsSegment, region, domain); } else { StringBuilder uriSuffix = new StringBuilder(endpointOverride.getHost()); if (endpointOverride.getPort() > 0) { uriSuffix.append(":").append(endpointOverride.getPort()); } if (endpointOverride.getPath() != null) { uriSuffix.append(endpointOverride.getPath()); } uriString = String.format("%s://%s-%s.%s", protocol, accessPointName, accountId, uriSuffix); } return URI.create(uriString); } }
4,853
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/resource/AwsResource.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.resource; import java.util.Optional; import software.amazon.awssdk.annotations.SdkInternalApi; /** * An abstract representation of an AWS Resource. Provides an interface to properties that are common across all AWS * resource types. Services may provide concrete implementations that can be found in each service module. */ @SdkInternalApi public interface AwsResource { /** * Gets the partition associated with the AWS Resource (e.g.: 'aws') if one has been specified. * @return the optional value for the partition. */ Optional<String> partition(); /** * Gets the region associated with the AWS Resource (e.g.: 'us-east-1') if one has been specified. * @return the optional value for the region. */ Optional<String> region(); /** * Gets the account ID associated with the AWS Resource if one has been specified. * @return the optional value for the account ID. */ Optional<String> accountId(); }
4,854
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/resource/ArnConverter.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.resource; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.arns.Arn; /** * An interface for converting an AWS ARN into a service specific {@link AwsResource}. Services that model * their own AWS resources will provide a specific implementation of this ARN parser. * <p> * @param <T> The service specific representation of {@link AwsResource}. */ @SdkInternalApi @FunctionalInterface public interface ArnConverter<T extends AwsResource> { /** * Converts an AWS ARN into a service specific {@link AwsResource}. * * @param arn The ARN to convert. * @return A service specific {@link AwsResource}. */ T convertArn(Arn arn); }
4,855
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/resource/S3AccessPointBuilder.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.resource; import static software.amazon.awssdk.utils.http.SdkHttpUtils.urlEncode; import java.net.URI; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Stream; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.utils.StringUtils; import software.amazon.awssdk.utils.Validate; /** * This class is used to construct an endpoint host for an S3 access point. */ @SdkInternalApi public class S3AccessPointBuilder { private static final Pattern HOSTNAME_COMPLIANT_PATTERN = Pattern.compile("[A-Za-z0-9\\-]+"); private static final int HOSTNAME_MAX_LENGTH = 63; private URI endpointOverride; private Boolean dualstackEnabled; private String accessPointName; private String region; private String accountId; private String protocol; private String domain; private Boolean fipsEnabled; /** * Create a new instance of this builder class. */ public static S3AccessPointBuilder create() { return new S3AccessPointBuilder(); } /** * The endpoint override configured on the client (null if no endpoint override was set). */ public S3AccessPointBuilder endpointOverride(URI endpointOverride) { this.endpointOverride = endpointOverride; return this; } /** * Enable DualStack endpoint. */ public S3AccessPointBuilder dualstackEnabled(Boolean dualstackEnabled) { this.dualstackEnabled = dualstackEnabled; return this; } /** * Enable fips in endpoint. */ public S3AccessPointBuilder fipsEnabled(Boolean fipsEnabled) { this.fipsEnabled = fipsEnabled; return this; } /** * The S3 Access Point name. */ public S3AccessPointBuilder accessPointName(String accessPointName) { this.accessPointName = accessPointName; return this; } /** * The AWS region hosting the Access Point. */ public S3AccessPointBuilder region(String region) { this.region = region; return this; } /** * The ID of the AWS Account the Access Point is associated with. */ public S3AccessPointBuilder accountId(String accountId) { this.accountId = accountId; return this; } /** * The protocol to be used with the endpoint URI. */ public S3AccessPointBuilder protocol(String protocol) { this.protocol = protocol; return this; } /** * The TLD for the access point. */ public S3AccessPointBuilder domain(String domain) { this.domain = domain; return this; } /** * Generate an endpoint URI with no path that maps to the Access Point information stored in this builder. */ public URI toUri() { validateComponents(); String uriString = hasEndpointOverride() ? createEndpointOverrideUri() : createAccesspointUri(); URI result = URI.create(uriString); if (result.getHost() == null) { throw SdkClientException.create("Request resulted in an invalid URI: " + result); } return result; } private boolean hasEndpointOverride() { return endpointOverride != null; } private String createAccesspointUri() { String uri; if (isGlobal()) { uri = String.format("%s://%s.accesspoint.s3-global.%s", protocol, urlEncode(accessPointName), domain); } else { String fipsSegment = Boolean.TRUE.equals(fipsEnabled) ? "-fips" : ""; String dualStackSegment = Boolean.TRUE.equals(dualstackEnabled) ? ".dualstack" : ""; uri = String.format("%s://%s-%s.s3-accesspoint%s%s.%s.%s", protocol, urlEncode(accessPointName), accountId, fipsSegment, dualStackSegment, region, domain); } return uri; } private String createEndpointOverrideUri() { String uri; Validate.isTrue(!Boolean.TRUE.equals(fipsEnabled), "FIPS regions are not supported with an endpoint override specified"); Validate.isTrue(!Boolean.TRUE.equals(dualstackEnabled), "Dual stack is not supported with an endpoint override specified"); StringBuilder uriSuffix = new StringBuilder(endpointOverride.getHost()); if (endpointOverride.getPort() > 0) { uriSuffix.append(":").append(endpointOverride.getPort()); } if (endpointOverride.getPath() != null) { uriSuffix.append(endpointOverride.getPath()); } if (isGlobal()) { uri = String.format("%s://%s.%s", protocol, urlEncode(accessPointName), uriSuffix); } else { uri = String.format("%s://%s-%s.%s", protocol, urlEncode(accessPointName), accountId, uriSuffix); } return uri; } private boolean isGlobal() { return StringUtils.isEmpty(region); } private void validateComponents() { validateHostnameCompliant(accountId, "accountId"); if (isGlobal()) { Stream.of(accessPointName.split("\\.")) .forEach(segment -> validateHostnameCompliant(segment, segment)); } else { validateHostnameCompliant(accessPointName, "accessPointName"); } } private static void validateHostnameCompliant(String hostnameComponent, String paramName) { if (hostnameComponent.isEmpty()) { throw new IllegalArgumentException( String.format("An S3 Access Point ARN has been passed that is not valid: the required '%s' " + "component is missing.", paramName)); } if (hostnameComponent.length() > HOSTNAME_MAX_LENGTH) { throw new IllegalArgumentException( String.format("An S3 Access Point ARN has been passed that is not valid: the '%s' " + "component exceeds the maximum length of %d characters.", paramName, HOSTNAME_MAX_LENGTH)); } Matcher m = HOSTNAME_COMPLIANT_PATTERN.matcher(hostnameComponent); if (!m.matches()) { throw new IllegalArgumentException( String.format("An S3 Access Point ARN has been passed that is not valid: the '%s' " + "component must only contain alphanumeric characters and dashes.", paramName)); } } }
4,856
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/resource/S3ObjectLambdaResource.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.resource; import java.util.Optional; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * An {@link S3Resource} that represents an S3 Object Lambda resource. */ @SdkInternalApi public final class S3ObjectLambdaResource implements S3Resource, ToCopyableBuilder<S3ObjectLambdaResource.Builder, S3ObjectLambdaResource> { private final String partition; private final String region; private final String accountId; private final String accessPointName; private S3ObjectLambdaResource(Builder b) { this.partition = Validate.paramNotBlank(b.partition, "partition"); this.region = Validate.paramNotBlank(b.region, "region"); this.accountId = Validate.paramNotBlank(b.accountId, "accountId"); this.accessPointName = Validate.paramNotBlank(b.accessPointName, "accessPointName"); } /** * Get a new builder for this class. * @return A newly initialized instance of a builder. */ public static Builder builder() { return new Builder(); } /** * Gets the resource type for this object lambda. * @return This will always return "object_lambda". */ @Override public String type() { return S3ResourceType.OBJECT_LAMBDA.toString(); } /** * Gets the AWS partition name associated with this access point (e.g.: 'aws'). * @return the name of the partition. */ @Override public Optional<String> partition() { return Optional.ofNullable(partition); } /** * Gets the AWS region name associated with this bucket (e.g.: 'us-east-1'). * @return the name of the region. */ @Override public Optional<String> region() { return Optional.ofNullable(region); } /** * Gets the AWS account ID associated with this bucket. * @return the AWS account ID. */ @Override public Optional<String> accountId() { return Optional.ofNullable(accountId); } /** * Gets the name of the access point. * @return the name of the access point. */ public String accessPointName() { return this.accessPointName; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } S3ObjectLambdaResource that = (S3ObjectLambdaResource) o; if (partition != null ? !partition.equals(that.partition) : that.partition != null) { return false; } if (region != null ? !region.equals(that.region) : that.region != null) { return false; } if (accountId != null ? !accountId.equals(that.accountId) : that.accountId != null) { return false; } return accessPointName != null ? accessPointName.equals(that.accessPointName) : that.accessPointName == null; } @Override public int hashCode() { int result = partition != null ? partition.hashCode() : 0; result = 31 * result + (region != null ? region.hashCode() : 0); result = 31 * result + (accountId != null ? accountId.hashCode() : 0); result = 31 * result + (accessPointName != null ? accessPointName.hashCode() : 0); return result; } @Override public S3ObjectLambdaResource.Builder toBuilder() { return builder() .partition(partition) .region(region) .accountId(accountId) .accessPointName(accessPointName); } /** * A builder for {@link S3ObjectLambdaResource} objects. */ public static final class Builder implements CopyableBuilder<Builder, S3ObjectLambdaResource> { private String partition; private String region; private String accountId; private String accessPointName; private Builder() { } public void setPartition(String partition) { partition(partition); } /** * The AWS partition associated with the access point. */ public Builder partition(String partition) { this.partition = partition; return this; } public void setRegion(String region) { region(region); } /** * The AWS region associated with the access point. */ public Builder region(String region) { this.region = region; return this; } public void setAccountId(String accountId) { accountId(accountId); } /** * The AWS account ID associated with the access point. */ public Builder accountId(String accountId) { this.accountId = accountId; return this; } public void setAccessPointName(String accessPointName) { accessPointName(accessPointName); } /** * The name of the S3 access point. */ public Builder accessPointName(String accessPointName) { this.accessPointName = accessPointName; return this; } /** * Builds an instance of {@link S3ObjectLambdaResource}. */ @Override public S3ObjectLambdaResource build() { return new S3ObjectLambdaResource(this); } } }
4,857
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/client/S3SyncClientDecorator.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.client; import java.util.ArrayList; import java.util.List; import java.util.function.Predicate; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.endpoints.S3ClientContextParams; import software.amazon.awssdk.services.s3.internal.crossregion.S3CrossRegionSyncClient; import software.amazon.awssdk.utils.AttributeMap; import software.amazon.awssdk.utils.ConditionalDecorator; @SdkInternalApi public class S3SyncClientDecorator { public S3SyncClientDecorator() { } public S3Client decorate(S3Client base, SdkClientConfiguration clientConfiguration, AttributeMap clientContextParams) { List<ConditionalDecorator<S3Client>> decorators = new ArrayList<>(); decorators.add(ConditionalDecorator.create(isCrossRegionEnabledSync(clientContextParams), S3CrossRegionSyncClient::new)); return ConditionalDecorator.decorate(base, decorators); } private Predicate<S3Client> isCrossRegionEnabledSync(AttributeMap clientContextParams) { Boolean crossRegionEnabled = clientContextParams.get(S3ClientContextParams.CROSS_REGION_ACCESS_ENABLED); return client -> crossRegionEnabled != null && crossRegionEnabled.booleanValue(); } }
4,858
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/client/S3AsyncClientDecorator.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.client; import java.util.ArrayList; import java.util.List; import java.util.function.Predicate; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.services.s3.S3AsyncClient; import software.amazon.awssdk.services.s3.endpoints.S3ClientContextParams; import software.amazon.awssdk.services.s3.internal.crossregion.S3CrossRegionAsyncClient; import software.amazon.awssdk.services.s3.internal.multipart.MultipartS3AsyncClient; import software.amazon.awssdk.services.s3.multipart.MultipartConfiguration; import software.amazon.awssdk.utils.AttributeMap; import software.amazon.awssdk.utils.ConditionalDecorator; @SdkInternalApi public class S3AsyncClientDecorator { public static final AttributeMap.Key<MultipartConfiguration> MULTIPART_CONFIGURATION_KEY = new AttributeMap.Key<MultipartConfiguration>(MultipartConfiguration.class){}; public static final AttributeMap.Key<Boolean> MULTIPART_ENABLED_KEY = new AttributeMap.Key<Boolean>(Boolean.class){}; public S3AsyncClientDecorator() { } public S3AsyncClient decorate(S3AsyncClient base, SdkClientConfiguration clientConfiguration, AttributeMap clientContextParams) { List<ConditionalDecorator<S3AsyncClient>> decorators = new ArrayList<>(); decorators.add(ConditionalDecorator.create( isCrossRegionEnabledAsync(clientContextParams), S3CrossRegionAsyncClient::new)); decorators.add(ConditionalDecorator.create( isMultipartEnable(clientContextParams), client -> { MultipartConfiguration multipartConfiguration = clientContextParams.get(MULTIPART_CONFIGURATION_KEY); return MultipartS3AsyncClient.create(client, multipartConfiguration); })); return ConditionalDecorator.decorate(base, decorators); } private Predicate<S3AsyncClient> isCrossRegionEnabledAsync(AttributeMap clientContextParams) { Boolean crossRegionEnabled = clientContextParams.get(S3ClientContextParams.CROSS_REGION_ACCESS_ENABLED); return client -> crossRegionEnabled != null && crossRegionEnabled.booleanValue(); } private Predicate<S3AsyncClient> isMultipartEnable(AttributeMap clientContextParams) { Boolean multipartEnabled = clientContextParams.get(MULTIPART_ENABLED_KEY); return client -> multipartEnabled != null && multipartEnabled.booleanValue(); } }
4,859
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/handlers/StreamingRequestInterceptor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.handlers; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.services.s3.model.PutObjectRequest; import software.amazon.awssdk.services.s3.model.UploadPartRequest; /** * Interceptor to add an 'Expect: 100-continue' header to the HTTP Request if it represents a PUT Object request. */ @SdkInternalApi //TODO: This should be generalized for all streaming requests public final class StreamingRequestInterceptor implements ExecutionInterceptor { @Override public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { if (context.request() instanceof PutObjectRequest || context.request() instanceof UploadPartRequest) { return context.httpRequest().toBuilder().putHeader("Expect", "100-continue").build(); } return context.httpRequest(); } }
4,860
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/handlers/DecodeUrlEncodedResponseInterceptor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.handlers; import static software.amazon.awssdk.utils.http.SdkHttpUtils.urlDecode; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkResponse; 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.CommonPrefix; import software.amazon.awssdk.services.s3.model.EncodingType; import software.amazon.awssdk.services.s3.model.ListMultipartUploadsResponse; import software.amazon.awssdk.services.s3.model.ListObjectVersionsResponse; import software.amazon.awssdk.services.s3.model.ListObjectsResponse; import software.amazon.awssdk.services.s3.model.ListObjectsV2Response; import software.amazon.awssdk.services.s3.model.MultipartUpload; import software.amazon.awssdk.services.s3.model.ObjectVersion; import software.amazon.awssdk.services.s3.model.S3Object; /** * Encoding type affects the following values in the response: * <ul> * <li>V1: Delimiter, Marker, Prefix, NextMarker, Key</li> * <li>V2: Delimiter, Prefix, Key, and StartAfter</li> * </ul> * <p> * See <a * href="https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGET.html">https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGET.html</a> * and <a * href="https://docs.aws.amazon.com/AmazonS3/latest/API/v2-RESTBucketGET.html">https://docs.aws.amazon.com/AmazonS3/latest/API/v2-RESTBucketGET.html</a> */ @SdkInternalApi public final class DecodeUrlEncodedResponseInterceptor implements ExecutionInterceptor { @Override public SdkResponse modifyResponse(Context.ModifyResponse context, ExecutionAttributes executionAttributes) { SdkResponse response = context.response(); if (shouldHandle(response)) { if (response instanceof ListObjectsResponse) { return modifyListObjectsResponse((ListObjectsResponse) response); } if (response instanceof ListObjectsV2Response) { return modifyListObjectsV2Response((ListObjectsV2Response) response); } if (response instanceof ListObjectVersionsResponse) { return modifyListObjectVersionsResponse((ListObjectVersionsResponse) response); } if (response instanceof ListMultipartUploadsResponse) { return modifyListMultipartUploadsResponse((ListMultipartUploadsResponse) response); } } return response; } private static boolean shouldHandle(SdkResponse sdkResponse) { return sdkResponse.getValueForField("EncodingType", String.class) .map(et -> EncodingType.URL.toString().equals(et)) .orElse(false); } // Elements to decode: Delimiter, Marker, Prefix, NextMarker, Key private static SdkResponse modifyListObjectsResponse(ListObjectsResponse response) { return response.toBuilder() .delimiter(urlDecode(response.delimiter())) .marker(urlDecode(response.marker())) .prefix(urlDecode(response.prefix())) .nextMarker(urlDecode(response.nextMarker())) .contents(decodeContents(response.contents())) .commonPrefixes(decodeCommonPrefixes(response.commonPrefixes())) .build(); } // Elements to decode: Delimiter, Prefix, Key, and StartAfter private static SdkResponse modifyListObjectsV2Response(ListObjectsV2Response response) { return response.toBuilder() .delimiter(urlDecode(response.delimiter())) .prefix(urlDecode(response.prefix())) .startAfter(urlDecode(response.startAfter())) .contents(decodeContents(response.contents())) .commonPrefixes(decodeCommonPrefixes(response.commonPrefixes())) .build(); } // https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListObjectVersions.html // Elements to decode: Delimiter, KeyMarker, NextKeyMarker, Prefix private SdkResponse modifyListObjectVersionsResponse(ListObjectVersionsResponse response) { return response.toBuilder() .prefix(urlDecode(response.prefix())) .keyMarker(urlDecode(response.keyMarker())) .delimiter(urlDecode(response.delimiter())) .nextKeyMarker(urlDecode(response.nextKeyMarker())) .commonPrefixes(decodeCommonPrefixes(response.commonPrefixes())) .versions(decodeObjectVersions(response.versions())) .build(); } // https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListMultipartUploads.html // Elements to decode: Delimiter, KeyMarker, NextKeyMarker, Prefix, Key private SdkResponse modifyListMultipartUploadsResponse(ListMultipartUploadsResponse response) { return response.toBuilder() .delimiter(urlDecode(response.delimiter())) .keyMarker(urlDecode(response.keyMarker())) .nextKeyMarker(urlDecode(response.nextKeyMarker())) .prefix(urlDecode(response.prefix())) .commonPrefixes(decodeCommonPrefixes(response.commonPrefixes())) .uploads(decodeMultipartUpload(response.uploads())) .build(); } private static List<S3Object> decodeContents(List<S3Object> contents) { if (contents == null) { return null; } return Collections.unmodifiableList(contents.stream() .map(o -> o.toBuilder().key(urlDecode(o.key())).build()) .collect(Collectors.toList())); } private static List<ObjectVersion> decodeObjectVersions(List<ObjectVersion> objectVersions) { if (objectVersions == null) { return null; } return Collections.unmodifiableList(objectVersions.stream() .map(o -> o.toBuilder().key(urlDecode(o.key())).build()) .collect(Collectors.toList())); } private static List<CommonPrefix> decodeCommonPrefixes(List<CommonPrefix> commonPrefixes) { if (commonPrefixes == null) { return null; } return Collections.unmodifiableList(commonPrefixes.stream() .map(p -> p.toBuilder().prefix(urlDecode(p.prefix())).build()) .collect(Collectors.toList())); } private static List<MultipartUpload> decodeMultipartUpload(List<MultipartUpload> multipartUploads) { if (multipartUploads == null) { return null; } return Collections.unmodifiableList(multipartUploads.stream() .map(u -> u.toBuilder().key(urlDecode(u.key())).build()) .collect(Collectors.toList())); } }
4,861
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/handlers/EnableChunkedEncodingInterceptor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.handlers; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute; import software.amazon.awssdk.auth.signer.S3SignerExecutionAttribute; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.services.s3.S3Configuration; import software.amazon.awssdk.services.s3.model.PutObjectRequest; import software.amazon.awssdk.services.s3.model.UploadPartRequest; /** * Interceptor to enable chunked encoding on specific upload operations if the option does not already have a value. * <p> * This affects the following requests: * <ul> * <li>{@link PutObjectRequest}</li> * <li>{@link UploadPartRequest}</li> * </ul> */ @SdkInternalApi public final class EnableChunkedEncodingInterceptor implements ExecutionInterceptor { @Override public SdkRequest modifyRequest(Context.ModifyRequest context, ExecutionAttributes executionAttributes) { SdkRequest sdkRequest = context.request(); if (sdkRequest instanceof PutObjectRequest || sdkRequest instanceof UploadPartRequest) { S3Configuration serviceConfiguration = (S3Configuration) executionAttributes.getAttribute(AwsSignerExecutionAttribute.SERVICE_CONFIG); boolean enableChunkedEncoding; if (serviceConfiguration != null) { enableChunkedEncoding = serviceConfiguration.chunkedEncodingEnabled(); } else { enableChunkedEncoding = true; } executionAttributes.putAttributeIfAbsent(S3SignerExecutionAttribute.ENABLE_CHUNKED_ENCODING, enableChunkedEncoding); } return sdkRequest; } }
4,862
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/handlers/GetBucketPolicyInterceptor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.handlers; import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.Optional; import java.util.function.Predicate; import org.reactivestreams.Publisher; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.core.internal.async.SdkPublishers; import software.amazon.awssdk.http.AbortableInputStream; import software.amazon.awssdk.services.s3.model.GetBucketPolicyRequest; import software.amazon.awssdk.utils.IoUtils; import software.amazon.awssdk.utils.StringInputStream; /** * GetBucketPolicy returns just JSON so we wrap in XML so that it is unmarshalled correctly. */ @SdkInternalApi public final class GetBucketPolicyInterceptor implements ExecutionInterceptor { private static final String XML_ENVELOPE_PREFIX = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Policy><![CDATA["; private static final String XML_ENVELOPE_SUFFIX = "]]></Policy>"; private static final Predicate<Context.ModifyHttpResponse> INTERCEPTOR_CONTEXT_PREDICATE = context -> context.request() instanceof GetBucketPolicyRequest && context.httpResponse().isSuccessful(); @Override public Optional<InputStream> modifyHttpResponseContent(Context.ModifyHttpResponse context, ExecutionAttributes executionAttributes) { if (INTERCEPTOR_CONTEXT_PREDICATE.test(context)) { String policy = context.responseBody() .map(r -> invokeSafely(() -> IoUtils.toUtf8String(r))) .orElse(null); if (policy != null) { String xml = XML_ENVELOPE_PREFIX + policy + XML_ENVELOPE_SUFFIX; return Optional.of(AbortableInputStream.create(new StringInputStream(xml))); } } return context.responseBody(); } @Override public Optional<Publisher<ByteBuffer>> modifyAsyncHttpResponseContent(Context.ModifyHttpResponse context, ExecutionAttributes executionAttributes) { if (INTERCEPTOR_CONTEXT_PREDICATE.test(context)) { return context.responsePublisher().map( body -> SdkPublishers.envelopeWrappedPublisher(body, XML_ENVELOPE_PREFIX, XML_ENVELOPE_SUFFIX)); } return context.responsePublisher(); } }
4,863
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/handlers/ConfigureSignerInterceptor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.handlers; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; /** * Don't double-url-encode or normalize path elements for S3, as per * https://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html */ @SdkInternalApi public final class ConfigureSignerInterceptor implements ExecutionInterceptor { @Override public void beforeExecution(Context.BeforeExecution context, ExecutionAttributes executionAttributes) { executionAttributes.putAttribute(AwsSignerExecutionAttribute.SIGNER_DOUBLE_URL_ENCODE, Boolean.FALSE); executionAttributes.putAttribute(AwsSignerExecutionAttribute.SIGNER_NORMALIZE_PATH, Boolean.FALSE); } }
4,864
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/handlers/EnableTrailingChecksumInterceptor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.handlers; import static software.amazon.awssdk.services.s3.checksums.ChecksumConstant.ENABLE_CHECKSUM_REQUEST_HEADER; import static software.amazon.awssdk.services.s3.checksums.ChecksumConstant.ENABLE_MD5_CHECKSUM_HEADER_VALUE; import static software.amazon.awssdk.services.s3.checksums.ChecksumConstant.S3_MD5_CHECKSUM_LENGTH; import static software.amazon.awssdk.services.s3.checksums.ChecksumsEnabledValidator.getObjectChecksumEnabledPerRequest; import static software.amazon.awssdk.services.s3.checksums.ChecksumsEnabledValidator.getObjectChecksumEnabledPerResponse; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkResponse; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.http.SdkHttpResponse; import software.amazon.awssdk.services.s3.model.GetObjectRequest; import software.amazon.awssdk.services.s3.model.GetObjectResponse; import software.amazon.awssdk.utils.Validate; @SdkInternalApi public final class EnableTrailingChecksumInterceptor implements ExecutionInterceptor { /** * Append trailing checksum header for {@link GetObjectRequest} if trailing checksum is enabled from config. */ @Override public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { if (getObjectChecksumEnabledPerRequest(context.request(), executionAttributes)) { return context.httpRequest().toBuilder().putHeader(ENABLE_CHECKSUM_REQUEST_HEADER, ENABLE_MD5_CHECKSUM_HEADER_VALUE) .build(); } return context.httpRequest(); } /** * Subtract the contentLength of {@link GetObjectResponse} if trailing checksums is enabled. */ @Override public SdkResponse modifyResponse(Context.ModifyResponse context, ExecutionAttributes executionAttributes) { SdkResponse response = context.response(); SdkHttpResponse httpResponse = context.httpResponse(); if (getObjectChecksumEnabledPerResponse(context.request(), httpResponse)) { GetObjectResponse getResponse = (GetObjectResponse) response; Long contentLength = getResponse.contentLength(); Validate.notNull(contentLength, "Service returned null 'Content-Length'."); return getResponse.toBuilder() .contentLength(contentLength - S3_MD5_CHECKSUM_LENGTH) .build(); } return response; } }
4,865
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/handlers/CopySourceInterceptor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.handlers; import static software.amazon.awssdk.utils.http.SdkHttpUtils.urlEncodeIgnoreSlashes; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.interceptor.Context.ModifyRequest; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.services.s3.internal.resource.S3ArnUtils; import software.amazon.awssdk.services.s3.internal.resource.S3ResourceType; import software.amazon.awssdk.services.s3.model.CopyObjectRequest; import software.amazon.awssdk.services.s3.model.PutObjectRequest; import software.amazon.awssdk.services.s3.model.UploadPartCopyRequest; import software.amazon.awssdk.utils.Validate; /** * This interceptor transforms the {@code sourceBucket}, {@code sourceKey}, and {@code sourceVersionId} parameters for * {@link CopyObjectRequest} and {@link UploadPartCopyRequest} into a {@code copySource} parameter. The logic needed to * construct a {@code copySource} can be considered non-trivial, so this interceptor facilitates allowing users to * use higher-level constructs that more closely match other APIs, like {@link PutObjectRequest}. Additionally, this * interceptor is responsible for URL encoding the relevant portions of the {@code copySource} value. * <p> * <a href="https://docs.aws.amazon.com/AmazonS3/latest/API/API_CopyObject.html#API_CopyObject_RequestParameters">API_CopyObject_RequestParameters</a> * <p> * <a href="https://docs.aws.amazon.com/AmazonS3/latest/API/API_UploadPartCopy.html#API_UploadPartCopy_RequestParameters">API_UploadPartCopy_RequestParameters</a> */ @SdkInternalApi public final class CopySourceInterceptor implements ExecutionInterceptor { @Override public SdkRequest modifyRequest(ModifyRequest context, ExecutionAttributes executionAttributes) { SdkRequest request = context.request(); if (request instanceof CopyObjectRequest) { return modifyCopyObjectRequest((CopyObjectRequest) request); } if (request instanceof UploadPartCopyRequest) { return modifyUploadPartCopyRequest((UploadPartCopyRequest) request); } return request; } private static SdkRequest modifyCopyObjectRequest(CopyObjectRequest request) { if (request.copySource() != null) { requireNotSet(request.sourceBucket(), "sourceBucket"); requireNotSet(request.sourceKey(), "sourceKey"); requireNotSet(request.sourceVersionId(), "sourceVersionId"); return request; } String copySource = constructCopySource( requireSet(request.sourceBucket(), "sourceBucket"), requireSet(request.sourceKey(), "sourceKey"), request.sourceVersionId() ); return request.toBuilder() .sourceBucket(null) .sourceKey(null) .sourceVersionId(null) .copySource(copySource) .build(); } private static SdkRequest modifyUploadPartCopyRequest(UploadPartCopyRequest request) { if (request.copySource() != null) { requireNotSet(request.sourceBucket(), "sourceBucket"); requireNotSet(request.sourceKey(), "sourceKey"); requireNotSet(request.sourceVersionId(), "sourceVersionId"); return request; } String copySource = constructCopySource( requireSet(request.sourceBucket(), "sourceBucket"), requireSet(request.sourceKey(), "sourceKey"), request.sourceVersionId() ); return request.toBuilder() .sourceBucket(null) .sourceKey(null) .sourceVersionId(null) .copySource(copySource) .build(); } private static String constructCopySource(String sourceBucket, String sourceKey, String sourceVersionId) { StringBuilder copySource = new StringBuilder(); copySource.append(urlEncodeIgnoreSlashes(sourceBucket)); S3ArnUtils.getArnType(sourceBucket).ifPresent(arnType -> { if (arnType == S3ResourceType.ACCESS_POINT || arnType == S3ResourceType.OUTPOST) { copySource.append("/object"); } }); copySource.append("/"); copySource.append(urlEncodeIgnoreSlashes(sourceKey)); if (sourceVersionId != null) { copySource.append("?versionId="); copySource.append(urlEncodeIgnoreSlashes(sourceVersionId)); } return copySource.toString(); } private static void requireNotSet(Object value, String paramName) { Validate.isTrue(value == null, "Parameter 'copySource' must not be used in conjunction with '%s'", paramName); } private static <T> T requireSet(T value, String paramName) { Validate.isTrue(value != null, "Parameter '%s' must not be null", paramName); return value; } }
4,866
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/handlers/CreateBucketInterceptor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.handlers; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.awscore.AwsExecutionAttribute; 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.regions.Region; import software.amazon.awssdk.services.s3.internal.BucketUtils; import software.amazon.awssdk.services.s3.model.CreateBucketConfiguration; import software.amazon.awssdk.services.s3.model.CreateBucketRequest; @SdkInternalApi public final class CreateBucketInterceptor implements ExecutionInterceptor { @Override public SdkRequest modifyRequest(Context.ModifyRequest context, ExecutionAttributes executionAttributes) { SdkRequest sdkRequest = context.request(); if (sdkRequest instanceof CreateBucketRequest) { CreateBucketRequest request = (CreateBucketRequest) sdkRequest; validateBucketNameIsS3Compatible(request.bucket()); if (request.createBucketConfiguration() == null || request.createBucketConfiguration().locationConstraint() == null) { Region region = executionAttributes.getAttribute(AwsExecutionAttribute.AWS_REGION); sdkRequest = request.toBuilder() .createBucketConfiguration(toLocationConstraint(region)) .build(); } } return sdkRequest; } private CreateBucketConfiguration toLocationConstraint(Region region) { if (region.equals(Region.US_EAST_1)) { // us-east-1 requires no location restraint. See http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUT.html return null; } return CreateBucketConfiguration.builder() .locationConstraint(region.id()) .build(); } /** * Validates that the name of the bucket being requested to be created * is a valid S3 bucket name according to their guidelines. If the bucket * name is not valid, an {@link IllegalArgumentException} is thrown. See * {@link BucketUtils#isValidDnsBucketName(String, boolean)} for additional * details. * * @param bucketName Name of the bucket */ private void validateBucketNameIsS3Compatible(String bucketName) { BucketUtils.isValidDnsBucketName(bucketName, true); } }
4,867
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/handlers/CreateMultipartUploadRequestInterceptor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.handlers; import static software.amazon.awssdk.http.Header.CONTENT_LENGTH; import static software.amazon.awssdk.http.Header.CONTENT_TYPE; import java.io.ByteArrayInputStream; import java.util.Optional; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.services.s3.model.CreateMultipartUploadRequest; @SdkInternalApi public class CreateMultipartUploadRequestInterceptor implements ExecutionInterceptor { @Override public Optional<RequestBody> modifyHttpContent(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { if (context.request() instanceof CreateMultipartUploadRequest) { return Optional.of(RequestBody.fromInputStream(new ByteArrayInputStream(new byte[0]), 0)); } return context.requestBody(); } @Override public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { if (context.request() instanceof CreateMultipartUploadRequest) { SdkHttpRequest.Builder builder = context.httpRequest() .toBuilder() .putHeader(CONTENT_LENGTH, String.valueOf(0)); if (!context.httpRequest().firstMatchingHeader(CONTENT_TYPE).isPresent()) { builder.putHeader(CONTENT_TYPE, "binary/octet-stream"); } return builder.build(); } return context.httpRequest(); } }
4,868
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/handlers/DisablePayloadSigningInterceptor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.handlers; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.auth.signer.S3SignerExecutionAttribute; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; /** * Disables payload signing for all S3 operations. * * <p>TODO(sra-identity-auth): After S3's migration to the SRA, we should use signer properties in the auth scheme resolver. */ @SdkInternalApi public class DisablePayloadSigningInterceptor implements ExecutionInterceptor { @Override public void beforeExecution(Context.BeforeExecution context, ExecutionAttributes executionAttributes) { executionAttributes.putAttributeIfAbsent(S3SignerExecutionAttribute.ENABLE_PAYLOAD_SIGNING, false); } }
4,869
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/handlers/GetObjectInterceptor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.handlers; import java.util.Optional; import java.util.regex.Pattern; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkResponse; import software.amazon.awssdk.core.checksums.Algorithm; import software.amazon.awssdk.core.checksums.ChecksumSpecs; import software.amazon.awssdk.core.checksums.ChecksumValidation; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.core.interceptor.SdkExecutionAttribute; import software.amazon.awssdk.core.internal.util.HttpChecksumResolver; import software.amazon.awssdk.core.internal.util.HttpChecksumUtils; import software.amazon.awssdk.http.SdkHttpResponse; import software.amazon.awssdk.services.s3.model.GetObjectRequest; import software.amazon.awssdk.services.s3.model.GetObjectResponse; import software.amazon.awssdk.utils.Pair; /** * Interceptor for {@link GetObjectRequest} messages. */ @SdkInternalApi public class GetObjectInterceptor implements ExecutionInterceptor { public static final Pattern MULTIPART_CHECKSUM_PATTERN = Pattern.compile(".*-\\d+$"); @Override public void afterTransmission(Context.AfterTransmission context, ExecutionAttributes executionAttributes) { if (!(context.request() instanceof GetObjectRequest)) { return; } ChecksumSpecs resolvedChecksumSpecs = HttpChecksumResolver.getResolvedChecksumSpecs(executionAttributes); if (HttpChecksumUtils.isHttpChecksumValidationEnabled(resolvedChecksumSpecs)) { Pair<Algorithm, String> algorithmChecksumValuePair = HttpChecksumUtils.getAlgorithmChecksumValuePair(context.httpResponse(), resolvedChecksumSpecs); // Multipart uploaded objects the received Checksum is the checksum of checksums of individual parts and part number. if (algorithmChecksumValuePair != null && algorithmChecksumValuePair.right() != null) { if (MULTIPART_CHECKSUM_PATTERN.matcher(algorithmChecksumValuePair.right()).matches()) { executionAttributes.putAttribute(SdkExecutionAttribute.HTTP_RESPONSE_CHECKSUM_VALIDATION, ChecksumValidation.FORCE_SKIP); } } } } @Override public SdkResponse modifyResponse(Context.ModifyResponse context, ExecutionAttributes executionAttributes) { SdkResponse response = context.response(); if (!(response instanceof GetObjectResponse)) { return response; } return fixContentRange(response, context.httpResponse()); } /** * S3 currently returns content-range in two possible headers: Content-Range or x-amz-content-range based on the x-amz-te in * the request. This will check the x-amz-content-range if the modeled header (Content-Range) wasn't populated. */ private SdkResponse fixContentRange(SdkResponse sdkResponse, SdkHttpResponse httpResponse) { // Use the modeled content range header, if the service returned it. GetObjectResponse getObjectResponse = (GetObjectResponse) sdkResponse; if (getObjectResponse.contentRange() != null) { return getObjectResponse; } // If the service didn't use the modeled content range header, check the x-amz-content-range header. Optional<String> xAmzContentRange = httpResponse.firstMatchingHeader("x-amz-content-range"); if (!xAmzContentRange.isPresent()) { return getObjectResponse; } return getObjectResponse.copy(r -> r.contentRange(xAmzContentRange.get())); } }
4,870
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/handlers/AsyncChecksumValidationInterceptor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.handlers; import static software.amazon.awssdk.core.ClientType.ASYNC; import static software.amazon.awssdk.services.s3.checksums.ChecksumConstant.CONTENT_LENGTH_HEADER; import static software.amazon.awssdk.services.s3.checksums.ChecksumsEnabledValidator.CHECKSUM; import static software.amazon.awssdk.services.s3.checksums.ChecksumsEnabledValidator.getObjectChecksumEnabledPerResponse; import static software.amazon.awssdk.services.s3.checksums.ChecksumsEnabledValidator.responseChecksumIsValid; import static software.amazon.awssdk.services.s3.checksums.ChecksumsEnabledValidator.shouldRecordChecksum; import static software.amazon.awssdk.services.s3.checksums.ChecksumsEnabledValidator.validatePutObjectChecksum; import java.nio.ByteBuffer; import java.util.Optional; import org.reactivestreams.Publisher; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.core.checksums.Md5Checksum; import software.amazon.awssdk.core.checksums.SdkChecksum; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttribute; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.services.s3.checksums.ChecksumCalculatingAsyncRequestBody; import software.amazon.awssdk.services.s3.checksums.ChecksumValidatingPublisher; import software.amazon.awssdk.services.s3.model.PutObjectResponse; @SdkInternalApi public final class AsyncChecksumValidationInterceptor implements ExecutionInterceptor { private static ExecutionAttribute<Boolean> ASYNC_RECORDING_CHECKSUM = new ExecutionAttribute<>("asyncRecordingChecksum"); @Override public Optional<AsyncRequestBody> modifyAsyncHttpContent(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { boolean shouldRecordChecksum = shouldRecordChecksum(context.request(), ASYNC, executionAttributes, context.httpRequest()); if (shouldRecordChecksum && context.asyncRequestBody().isPresent()) { SdkChecksum checksum = new Md5Checksum(); executionAttributes.putAttribute(ASYNC_RECORDING_CHECKSUM, true); executionAttributes.putAttribute(CHECKSUM, checksum); return Optional.of(new ChecksumCalculatingAsyncRequestBody(context.httpRequest(), context.asyncRequestBody().get(), checksum)); } return context.asyncRequestBody(); } @Override public Optional<Publisher<ByteBuffer>> modifyAsyncHttpResponseContent(Context.ModifyHttpResponse context, ExecutionAttributes executionAttributes) { if (getObjectChecksumEnabledPerResponse(context.request(), context.httpResponse()) && context.responsePublisher().isPresent()) { long contentLength = context.httpResponse() .firstMatchingHeader(CONTENT_LENGTH_HEADER) .map(Long::parseLong) .orElse(0L); SdkChecksum checksum = new Md5Checksum(); executionAttributes.putAttribute(CHECKSUM, checksum); if (contentLength > 0) { return Optional.of(new ChecksumValidatingPublisher(context.responsePublisher().get(), checksum, contentLength)); } } return context.responsePublisher(); } @Override public void afterUnmarshalling(Context.AfterUnmarshalling context, ExecutionAttributes executionAttributes) { boolean recordingChecksum = Boolean.TRUE.equals(executionAttributes.getAttribute(ASYNC_RECORDING_CHECKSUM)); boolean responseChecksumIsValid = responseChecksumIsValid(context.httpResponse()); if (recordingChecksum && responseChecksumIsValid) { validatePutObjectChecksum((PutObjectResponse) context.response(), executionAttributes); } } }
4,871
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/handlers/SyncChecksumValidationInterceptor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.handlers; import static software.amazon.awssdk.core.ClientType.SYNC; import static software.amazon.awssdk.services.s3.checksums.ChecksumConstant.CONTENT_LENGTH_HEADER; import static software.amazon.awssdk.services.s3.checksums.ChecksumsEnabledValidator.CHECKSUM; import static software.amazon.awssdk.services.s3.checksums.ChecksumsEnabledValidator.getObjectChecksumEnabledPerResponse; import static software.amazon.awssdk.services.s3.checksums.ChecksumsEnabledValidator.responseChecksumIsValid; import static software.amazon.awssdk.services.s3.checksums.ChecksumsEnabledValidator.shouldRecordChecksum; import static software.amazon.awssdk.services.s3.checksums.ChecksumsEnabledValidator.validatePutObjectChecksum; import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely; import java.io.InputStream; import java.util.Optional; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.checksums.Md5Checksum; import software.amazon.awssdk.core.checksums.SdkChecksum; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttribute; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.http.ContentStreamProvider; import software.amazon.awssdk.services.s3.checksums.ChecksumCalculatingInputStream; import software.amazon.awssdk.services.s3.checksums.ChecksumValidatingInputStream; import software.amazon.awssdk.services.s3.model.PutObjectResponse; @SdkInternalApi public final class SyncChecksumValidationInterceptor implements ExecutionInterceptor { private static ExecutionAttribute<Boolean> SYNC_RECORDING_CHECKSUM = new ExecutionAttribute<>("syncRecordingChecksum"); @Override public Optional<RequestBody> modifyHttpContent(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { if (shouldRecordChecksum(context.request(), SYNC, executionAttributes, context.httpRequest()) && context.requestBody().isPresent()) { SdkChecksum checksum = new Md5Checksum(); executionAttributes.putAttribute(CHECKSUM, checksum); executionAttributes.putAttribute(SYNC_RECORDING_CHECKSUM, true); RequestBody requestBody = context.requestBody().get(); ChecksumCalculatingStreamProvider streamProvider = new ChecksumCalculatingStreamProvider(requestBody.contentStreamProvider(), checksum); return Optional.of(RequestBody.fromContentProvider(streamProvider, requestBody.contentLength(), requestBody.contentType())); } return context.requestBody(); } @Override public Optional<InputStream> modifyHttpResponseContent(Context.ModifyHttpResponse context, ExecutionAttributes executionAttributes) { if (getObjectChecksumEnabledPerResponse(context.request(), context.httpResponse()) && context.responseBody().isPresent()) { SdkChecksum checksum = new Md5Checksum(); long contentLength = context.httpResponse() .firstMatchingHeader(CONTENT_LENGTH_HEADER) .map(Long::parseLong) .orElse(0L); if (contentLength > 0) { return Optional.of(new ChecksumValidatingInputStream(context.responseBody().get(), checksum, contentLength)); } } return context.responseBody(); } @Override public void afterUnmarshalling(Context.AfterUnmarshalling context, ExecutionAttributes executionAttributes) { boolean recordingChecksum = Boolean.TRUE.equals(executionAttributes.getAttribute(SYNC_RECORDING_CHECKSUM)); boolean responseChecksumIsValid = responseChecksumIsValid(context.httpResponse()); if (recordingChecksum && responseChecksumIsValid) { validatePutObjectChecksum((PutObjectResponse) context.response(), executionAttributes); } } static final class ChecksumCalculatingStreamProvider implements ContentStreamProvider { private final SdkChecksum checksum; private InputStream currentStream; private final ContentStreamProvider underlyingInputStreamProvider; ChecksumCalculatingStreamProvider(ContentStreamProvider underlyingInputStreamProvider, SdkChecksum checksum) { this.underlyingInputStreamProvider = underlyingInputStreamProvider; this.checksum = checksum; } @Override public InputStream newStream() { closeCurrentStream(); currentStream = invokeSafely(() -> new ChecksumCalculatingInputStream(underlyingInputStreamProvider.newStream(), checksum)); return currentStream; } private void closeCurrentStream() { checksum.reset(); if (currentStream != null) { invokeSafely(currentStream::close); currentStream = null; } } } }
4,872
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/handlers/ExceptionTranslationInterceptor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.handlers; import java.util.Optional; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.awscore.exception.AwsErrorDetails; 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.HeadBucketRequest; import software.amazon.awssdk.services.s3.model.HeadObjectRequest; import software.amazon.awssdk.services.s3.model.NoSuchBucketException; import software.amazon.awssdk.services.s3.model.NoSuchKeyException; import software.amazon.awssdk.services.s3.model.S3Exception; /** * Translate S3Exception for the API calls that do not contain the detailed error code. */ @SdkInternalApi public final class ExceptionTranslationInterceptor implements ExecutionInterceptor { @Override public Throwable modifyException(Context.FailedExecution context, ExecutionAttributes executionAttributes) { if (!isS3Exception404(context.exception()) || !isHeadRequest(context.request())) { return context.exception(); } String message = context.exception().getMessage(); S3Exception exception = (S3Exception) (context.exception()); String requestIdFromHeader = exception.awsErrorDetails() .sdkHttpResponse() .firstMatchingHeader("x-amz-request-id") .orElse(null); String requestId = Optional.ofNullable(exception.requestId()).orElse(requestIdFromHeader); AwsErrorDetails errorDetails = exception.awsErrorDetails(); if (context.request() instanceof HeadObjectRequest) { return NoSuchKeyException.builder() .awsErrorDetails(fillErrorDetails(errorDetails, "NoSuchKey", "The specified key does not exist.")) .statusCode(404) .requestId(requestId) .message(message) .build(); } if (context.request() instanceof HeadBucketRequest) { return NoSuchBucketException.builder() .awsErrorDetails(fillErrorDetails(errorDetails, "NoSuchBucket", "The specified bucket does not exist.")) .statusCode(404) .requestId(requestId) .message(message) .build(); } return context.exception(); } private AwsErrorDetails fillErrorDetails(AwsErrorDetails original, String errorCode, String errorMessage) { return original.toBuilder().errorMessage(errorMessage).errorCode(errorCode).build(); } private boolean isHeadRequest(SdkRequest request) { return (request instanceof HeadObjectRequest || request instanceof HeadBucketRequest); } private boolean isS3Exception404(Throwable thrown) { if (!(thrown instanceof S3Exception)) { return false; } return ((S3Exception) thrown).statusCode() == 404; } }
4,873
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/settingproviders/DisableMultiRegionProviderChain.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.settingproviders; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.profiles.ProfileFileSystemSetting; import software.amazon.awssdk.utils.Logger; /** * {@link DisableMultiRegionProvider} implementation that chains together multiple disable multi-region providers. */ @SdkInternalApi public final class DisableMultiRegionProviderChain implements DisableMultiRegionProvider { private static final Logger log = Logger.loggerFor(DisableMultiRegionProvider.class); private static final String SETTING = "disableMultiRegion"; private final List<DisableMultiRegionProvider> providers; private DisableMultiRegionProviderChain(List<DisableMultiRegionProvider> providers) { this.providers = providers; } /** * Creates a default {@link DisableMultiRegionProviderChain}. * * <p> * AWS disable multi-region provider that looks for the disable flag in this order: * * <ol> * <li>Check if 'aws.s3DisableMultiRegionAccessPoints' system property is set.</li> * <li>Check if 'AWS_S3_DISABLE_MULTIREGION_ACCESS_POINTS' environment is set.</li> * <li>Check if 's3_disable_multiregion_access_points' profile file configuration is set.</li> * </ol> */ public static DisableMultiRegionProviderChain create() { return create(ProfileFile::defaultProfileFile, ProfileFileSystemSetting.AWS_PROFILE.getStringValueOrThrow()); } public static DisableMultiRegionProviderChain create(ProfileFile profileFile, String profileName) { return new DisableMultiRegionProviderChain(Arrays.asList( SystemsSettingsDisableMultiRegionProvider.create(), ProfileDisableMultiRegionProvider.create(profileFile, profileName))); } public static DisableMultiRegionProviderChain create(Supplier<ProfileFile> profileFile, String profileName) { return new DisableMultiRegionProviderChain(Arrays.asList( SystemsSettingsDisableMultiRegionProvider.create(), ProfileDisableMultiRegionProvider.create(profileFile, profileName))); } @Override public Optional<Boolean> resolve() { for (DisableMultiRegionProvider provider : providers) { try { Optional<Boolean> value = provider.resolve(); if (value.isPresent()) { return value; } } catch (Exception ex) { log.warn(() -> "Failed to retrieve " + SETTING + " from " + provider, ex); } } return Optional.empty(); } }
4,874
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/settingproviders/ProfileDisableMultiRegionProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.settingproviders; import java.util.Optional; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.profiles.ProfileFileSystemSetting; import software.amazon.awssdk.utils.StringUtils; /** * Loads configuration from the {@link ProfileFile#defaultProfileFile()} using the default profile name. */ @SdkInternalApi public final class ProfileDisableMultiRegionProvider implements DisableMultiRegionProvider { /** * Property name for specifying whether or not multi-region should be disabled. */ private static final String AWS_DISABLE_MULTI_REGION = "s3_disable_multiregion_access_points"; private final Supplier<ProfileFile> profileFile; private final String profileName; private ProfileDisableMultiRegionProvider(Supplier<ProfileFile> profileFile, String profileName) { this.profileFile = profileFile; this.profileName = profileName; } public static ProfileDisableMultiRegionProvider create() { return new ProfileDisableMultiRegionProvider(ProfileFile::defaultProfileFile, ProfileFileSystemSetting.AWS_PROFILE.getStringValueOrThrow()); } public static ProfileDisableMultiRegionProvider create(ProfileFile profileFile, String profileName) { return new ProfileDisableMultiRegionProvider(() -> profileFile, profileName); } public static ProfileDisableMultiRegionProvider create(Supplier<ProfileFile> profileFile, String profileName) { return new ProfileDisableMultiRegionProvider(profileFile, profileName); } @Override public Optional<Boolean> resolve() { return profileFile.get() .profile(profileName) .map(p -> p.properties().get(AWS_DISABLE_MULTI_REGION)) .map(StringUtils::safeStringToBoolean); } }
4,875
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/settingproviders/ProfileUseArnRegionProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.settingproviders; import java.util.Optional; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.profiles.ProfileFileSystemSetting; import software.amazon.awssdk.utils.StringUtils; /** * Loads useArnRegion configuration from the {@link ProfileFile#defaultProfileFile()} using the default profile name. */ @SdkInternalApi public final class ProfileUseArnRegionProvider implements UseArnRegionProvider { /** * Property name for specifying whether or not to use arn region should be enabled. */ private static final String AWS_USE_ARN_REGION = "s3_use_arn_region"; private final Supplier<ProfileFile> profileFile; private final String profileName; private ProfileUseArnRegionProvider(Supplier<ProfileFile> profileFile, String profileName) { this.profileFile = profileFile; this.profileName = profileName; } public static ProfileUseArnRegionProvider create() { return new ProfileUseArnRegionProvider(ProfileFile::defaultProfileFile, ProfileFileSystemSetting.AWS_PROFILE.getStringValueOrThrow()); } public static ProfileUseArnRegionProvider create(ProfileFile profileFile, String profileName) { return new ProfileUseArnRegionProvider(() -> profileFile, profileName); } public static ProfileUseArnRegionProvider create(Supplier<ProfileFile> profileFile, String profileName) { return new ProfileUseArnRegionProvider(profileFile, profileName); } @Override public Optional<Boolean> resolveUseArnRegion() { return profileFile.get() .profile(profileName) .map(p -> p.properties().get(AWS_USE_ARN_REGION)) .map(StringUtils::safeStringToBoolean); } }
4,876
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/settingproviders/UseArnRegionProviderChain.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.settingproviders; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.profiles.ProfileFileSystemSetting; import software.amazon.awssdk.utils.Logger; /** * {@link UseArnRegionProvider} implementation that chains together multiple useArnRegion providers. */ @SdkInternalApi public final class UseArnRegionProviderChain implements UseArnRegionProvider { private static final Logger log = Logger.loggerFor(UseArnRegionProvider.class); private final List<UseArnRegionProvider> providers; private UseArnRegionProviderChain(List<UseArnRegionProvider> providers) { this.providers = providers; } /** * Creates a default {@link UseArnRegionProviderChain}. * * <p> * AWS use arn region provider that looks for the useArnRegion in this order: * * <ol> * <li>Check if 'aws.s3UseArnRegion' system property is set.</li> * <li>Check if 'AWS_USE_ARN_REGION' environment variable is set.</li> * <li>Check if 's3_use_arn_region' profile file configuration is set.</li> * </ol> */ public static UseArnRegionProviderChain create() { return create(ProfileFile::defaultProfileFile, ProfileFileSystemSetting.AWS_PROFILE.getStringValueOrThrow()); } public static UseArnRegionProviderChain create(ProfileFile profileFile, String profileName) { return new UseArnRegionProviderChain(Arrays.asList(SystemsSettingsUseArnRegionProvider.create(), ProfileUseArnRegionProvider.create(profileFile, profileName))); } public static UseArnRegionProviderChain create(Supplier<ProfileFile> profileFile, String profileName) { return new UseArnRegionProviderChain(Arrays.asList(SystemsSettingsUseArnRegionProvider.create(), ProfileUseArnRegionProvider.create(profileFile, profileName))); } @Override public Optional<Boolean> resolveUseArnRegion() { for (UseArnRegionProvider provider : providers) { try { Optional<Boolean> useArnRegion = provider.resolveUseArnRegion(); if (useArnRegion.isPresent()) { return useArnRegion; } } catch (Exception ex) { log.warn(() -> "Failed to retrieve useArnRegion from " + provider, ex); } } return Optional.empty(); } }
4,877
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/settingproviders/SystemsSettingsDisableMultiRegionProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.settingproviders; import java.util.Optional; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.services.s3.S3SystemSetting; /** * {@link DisableMultiRegionProvider} implementation that loads configuration from system properties * and environment variables. */ @SdkInternalApi public final class SystemsSettingsDisableMultiRegionProvider implements DisableMultiRegionProvider { private SystemsSettingsDisableMultiRegionProvider() { } public static SystemsSettingsDisableMultiRegionProvider create() { return new SystemsSettingsDisableMultiRegionProvider(); } @Override public Optional<Boolean> resolve() { return S3SystemSetting.AWS_S3_DISABLE_MULTIREGION_ACCESS_POINTS.getBooleanValue(); } }
4,878
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/settingproviders/DisableMultiRegionProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.settingproviders; import java.util.Optional; import software.amazon.awssdk.annotations.SdkInternalApi; /** * Interface for loading disable multi-region configuration. */ @FunctionalInterface @SdkInternalApi public interface DisableMultiRegionProvider { /** * @return whether multi-region is disabled, or empty if it is not configured. */ Optional<Boolean> resolve(); }
4,879
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/settingproviders/UseArnRegionProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.settingproviders; import java.util.Optional; import software.amazon.awssdk.annotations.SdkInternalApi; /** * Interface for loading useArnRegion configuration. */ @FunctionalInterface @SdkInternalApi public interface UseArnRegionProvider { /** * @return whether use-arn-region is enabled, or empty if it is not configured. */ Optional<Boolean> resolveUseArnRegion(); }
4,880
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/settingproviders/SystemsSettingsUseArnRegionProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.settingproviders; import java.util.Optional; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.services.s3.S3SystemSetting; /** * {@link UseArnRegionProvider} implementation that loads userArnRegion configuration from system properties * and environment variables. */ @SdkInternalApi public final class SystemsSettingsUseArnRegionProvider implements UseArnRegionProvider { private SystemsSettingsUseArnRegionProvider() { } public static SystemsSettingsUseArnRegionProvider create() { return new SystemsSettingsUseArnRegionProvider(); } @Override public Optional<Boolean> resolveUseArnRegion() { return S3SystemSetting.AWS_S3_USE_ARN_REGION.getBooleanValue(); } }
4,881
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/crossregion/S3CrossRegionSyncClient.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.crossregion; import static software.amazon.awssdk.services.s3.internal.crossregion.utils.CrossRegionUtils.getBucketRegionFromException; import static software.amazon.awssdk.services.s3.internal.crossregion.utils.CrossRegionUtils.isS3RedirectException; import static software.amazon.awssdk.services.s3.internal.crossregion.utils.CrossRegionUtils.requestWithDecoratedEndpointProvider; import static software.amazon.awssdk.services.s3.internal.crossregion.utils.CrossRegionUtils.updateUserAgentInConfig; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.DelegatingS3Client; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.HeadBucketRequest; import software.amazon.awssdk.services.s3.model.S3Exception; import software.amazon.awssdk.services.s3.model.S3Request; /** * Decorator S3 Sync client that will fetch the region name whenever there is Redirect 301 error due to cross region bucket * access. */ @SdkInternalApi public final class S3CrossRegionSyncClient extends DelegatingS3Client { private final Map<String, Region> bucketToRegionCache = new ConcurrentHashMap<>(); public S3CrossRegionSyncClient(S3Client s3Client) { super(s3Client); } private static <T extends S3Request> Optional<String> bucketNameFromRequest(T request) { return request.getValueForField("Bucket", String.class); } @Override protected <T extends S3Request, ReturnT> ReturnT invokeOperation(T request, Function<T, ReturnT> operation) { Optional<String> bucketRequest = bucketNameFromRequest(request); AwsRequestOverrideConfiguration overrideConfiguration = updateUserAgentInConfig(request); T userAgentUpdatedRequest = (T) request.toBuilder().overrideConfiguration(overrideConfiguration).build(); if (!bucketRequest.isPresent()) { return operation.apply(userAgentUpdatedRequest); } String bucketName = bucketRequest.get(); try { if (bucketToRegionCache.containsKey(bucketName)) { return operation.apply( requestWithDecoratedEndpointProvider(userAgentUpdatedRequest, () -> bucketToRegionCache.get(bucketName), serviceClientConfiguration().endpointProvider().get())); } return operation.apply(userAgentUpdatedRequest); } catch (S3Exception exception) { if (isS3RedirectException(exception)) { updateCacheFromRedirectException(exception, bucketName); return operation.apply( requestWithDecoratedEndpointProvider( userAgentUpdatedRequest, () -> bucketToRegionCache.computeIfAbsent(bucketName, this::fetchBucketRegion), serviceClientConfiguration().endpointProvider().get())); } throw exception; } } private void updateCacheFromRedirectException(S3Exception exception, String bucketName) { Optional<String> regionStr = getBucketRegionFromException(exception); // If redirected, clear previous values due to region change. bucketToRegionCache.remove(bucketName); regionStr.ifPresent(region -> bucketToRegionCache.put(bucketName, Region.of(region))); } private Region fetchBucketRegion(String bucketName) { try { ((S3Client) delegate()).headBucket(HeadBucketRequest.builder().bucket(bucketName).build()); } catch (S3Exception exception) { if (isS3RedirectException(exception)) { return Region.of(getBucketRegionFromException(exception).orElseThrow(() -> exception)); } throw exception; } return null; } }
4,882
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/crossregion/S3CrossRegionAsyncClient.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.crossregion; import static software.amazon.awssdk.services.s3.internal.crossregion.utils.CrossRegionUtils.getBucketRegionFromException; import static software.amazon.awssdk.services.s3.internal.crossregion.utils.CrossRegionUtils.isS3RedirectException; import static software.amazon.awssdk.services.s3.internal.crossregion.utils.CrossRegionUtils.requestWithDecoratedEndpointProvider; import static software.amazon.awssdk.services.s3.internal.crossregion.utils.CrossRegionUtils.updateUserAgentInConfig; import java.util.Map; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.function.BiConsumer; import java.util.function.Function; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.DelegatingS3AsyncClient; import software.amazon.awssdk.services.s3.S3AsyncClient; import software.amazon.awssdk.services.s3.model.S3Exception; import software.amazon.awssdk.services.s3.model.S3Request; import software.amazon.awssdk.utils.CompletableFutureUtils; @SdkInternalApi public final class S3CrossRegionAsyncClient extends DelegatingS3AsyncClient { private final Map<String, Region> bucketToRegionCache = new ConcurrentHashMap<>(); public S3CrossRegionAsyncClient(S3AsyncClient s3Client) { super(s3Client); } @Override protected <T extends S3Request, ReturnT> CompletableFuture<ReturnT> invokeOperation( T request, Function<T, CompletableFuture<ReturnT>> operation) { Optional<String> bucket = request.getValueForField("Bucket", String.class); AwsRequestOverrideConfiguration overrideConfiguration = updateUserAgentInConfig(request); T userAgentUpdatedRequest = (T) request.toBuilder().overrideConfiguration(overrideConfiguration).build(); if (!bucket.isPresent()) { return operation.apply(userAgentUpdatedRequest); } String bucketName = bucket.get(); CompletableFuture<ReturnT> returnFuture = new CompletableFuture<>(); CompletableFuture<ReturnT> apiOperationFuture = bucketToRegionCache.containsKey(bucketName) ? operation.apply( requestWithDecoratedEndpointProvider( userAgentUpdatedRequest, () -> bucketToRegionCache.get(bucketName), serviceClientConfiguration().endpointProvider().get() ) ) : operation.apply(userAgentUpdatedRequest); apiOperationFuture.whenComplete(redirectToCrossRegionIfRedirectException(operation, userAgentUpdatedRequest, bucketName, returnFuture)); return returnFuture; } private <T extends S3Request, ReturnT> BiConsumer<ReturnT, Throwable> redirectToCrossRegionIfRedirectException( Function<T, CompletableFuture<ReturnT>> operation, T userAgentUpdatedRequest, String bucketName, CompletableFuture<ReturnT> returnFuture) { return (response, throwable) -> { if (throwable != null) { if (isS3RedirectException(throwable)) { bucketToRegionCache.remove(bucketName); requestWithCrossRegion(userAgentUpdatedRequest, operation, bucketName, returnFuture, throwable); } else { returnFuture.completeExceptionally(throwable); } } else { returnFuture.complete(response); } }; } private <T extends S3Request, ReturnT> void requestWithCrossRegion(T request, Function<T, CompletableFuture<ReturnT>> operation, String bucketName, CompletableFuture<ReturnT> returnFuture, Throwable throwable) { Optional<String> bucketRegionFromException = getBucketRegionFromException((S3Exception) throwable.getCause()); if (bucketRegionFromException.isPresent()) { sendRequestWithRightRegion(request, operation, bucketName, returnFuture, bucketRegionFromException.get()); } else { fetchRegionAndSendRequest(request, operation, bucketName, returnFuture); } } private <T extends S3Request, ReturnT> void fetchRegionAndSendRequest(T request, Function<T, CompletableFuture<ReturnT>> operation, String bucketName, CompletableFuture<ReturnT> returnFuture) { // // TODO: Need to change codegen of Delegating Client to avoid the cast, have taken a backlog item to fix this. ((S3AsyncClient) delegate()).headBucket(b -> b.bucket(bucketName)).whenComplete((response, throwable) -> { if (throwable != null) { if (isS3RedirectException(throwable)) { bucketToRegionCache.remove(bucketName); Optional<String> bucketRegion = getBucketRegionFromException((S3Exception) throwable.getCause()); if (bucketRegion.isPresent()) { sendRequestWithRightRegion(request, operation, bucketName, returnFuture, bucketRegion.get()); } else { returnFuture.completeExceptionally(throwable); } } else { returnFuture.completeExceptionally(throwable); } } }); } private <T extends S3Request, ReturnT> void sendRequestWithRightRegion(T request, Function<T, CompletableFuture<ReturnT>> operation, String bucketName, CompletableFuture<ReturnT> returnFuture, String region) { bucketToRegionCache.put(bucketName, Region.of(region)); CompletableFuture<ReturnT> newFuture = operation.apply( requestWithDecoratedEndpointProvider(request, () -> Region.of(region), serviceClientConfiguration().endpointProvider().get())); CompletableFutureUtils.forwardResultTo(newFuture, returnFuture); CompletableFutureUtils.forwardExceptionTo(returnFuture, newFuture); } }
4,883
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/crossregion
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/crossregion/endpointprovider/BucketEndpointProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.crossregion.endpointprovider; import java.util.concurrent.CompletableFuture; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.endpoints.Endpoint; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.endpoints.S3EndpointParams; import software.amazon.awssdk.services.s3.endpoints.S3EndpointProvider; /** * Decorator S3EndpointProvider which updates the region with the one that is supplied during its instantiation. */ @SdkInternalApi public class BucketEndpointProvider implements S3EndpointProvider { private final S3EndpointProvider delegateEndPointProvider; private final Supplier<Region> regionSupplier; private BucketEndpointProvider(S3EndpointProvider delegateEndPointProvider, Supplier<Region> regionSupplier) { this.delegateEndPointProvider = delegateEndPointProvider; this.regionSupplier = regionSupplier; } public static BucketEndpointProvider create(S3EndpointProvider delegateEndPointProvider, Supplier<Region> regionSupplier) { return new BucketEndpointProvider(delegateEndPointProvider, regionSupplier); } @Override public CompletableFuture<Endpoint> resolveEndpoint(S3EndpointParams endpointParams) { Region crossRegion = regionSupplier.get(); return delegateEndPointProvider.resolveEndpoint( crossRegion != null ? endpointParams.copy(c -> c.region(crossRegion)) : endpointParams); } }
4,884
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/crossregion
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/internal/crossregion/utils/CrossRegionUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.internal.crossregion.utils; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.concurrent.CompletionException; import java.util.function.Consumer; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration; import software.amazon.awssdk.awscore.exception.AwsErrorDetails; import software.amazon.awssdk.core.ApiName; import software.amazon.awssdk.endpoints.EndpointProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.endpoints.S3EndpointProvider; import software.amazon.awssdk.services.s3.internal.crossregion.endpointprovider.BucketEndpointProvider; import software.amazon.awssdk.services.s3.model.S3Exception; import software.amazon.awssdk.services.s3.model.S3Request; @SdkInternalApi public final class CrossRegionUtils { public static final int REDIRECT_STATUS_CODE = 301; public static final int TEMPORARY_REDIRECT_STATUS_CODE = 307; public static final String AMZ_BUCKET_REGION_HEADER = "x-amz-bucket-region"; private static final List<Integer> REDIRECT_STATUS_CODES = Arrays.asList(REDIRECT_STATUS_CODE, TEMPORARY_REDIRECT_STATUS_CODE); private static final List<String> REDIRECT_ERROR_CODES = Collections.singletonList("AuthorizationHeaderMalformed"); private static final ApiName API_NAME = ApiName.builder().version("cross-region").name("hll").build(); private static final Consumer<AwsRequestOverrideConfiguration.Builder> USER_AGENT_APPLIER = b -> b.addApiName(API_NAME); private CrossRegionUtils() { } public static Optional<String> getBucketRegionFromException(S3Exception exception) { return exception.awsErrorDetails() .sdkHttpResponse() .firstMatchingHeader(AMZ_BUCKET_REGION_HEADER); } public static boolean isS3RedirectException(Throwable exception) { Throwable exceptionToBeChecked = exception instanceof CompletionException ? exception.getCause() : exception; return exceptionToBeChecked instanceof S3Exception && isRedirectError((S3Exception) exceptionToBeChecked); } private static boolean isRedirectError(S3Exception exceptionToBeChecked) { if (REDIRECT_STATUS_CODES.stream().anyMatch(status -> status.equals(exceptionToBeChecked.statusCode()))) { return true; } if (getBucketRegionFromException(exceptionToBeChecked).isPresent()) { return true; } AwsErrorDetails awsErrorDetails = exceptionToBeChecked.awsErrorDetails(); return awsErrorDetails != null && REDIRECT_ERROR_CODES.stream().anyMatch(code -> code.equals(awsErrorDetails.errorCode())); } @SuppressWarnings("unchecked") public static <T extends S3Request> T requestWithDecoratedEndpointProvider(T request, Supplier<Region> regionSupplier, EndpointProvider clientEndpointProvider) { AwsRequestOverrideConfiguration requestOverrideConfig = request.overrideConfiguration().orElseGet(() -> AwsRequestOverrideConfiguration.builder().build()); S3EndpointProvider delegateEndpointProvider = (S3EndpointProvider) requestOverrideConfig.endpointProvider() .orElse(clientEndpointProvider); return (T) request.toBuilder() .overrideConfiguration( requestOverrideConfig.toBuilder() .endpointProvider( BucketEndpointProvider.create(delegateEndpointProvider, regionSupplier)) .build()) .build(); } public static <T extends S3Request> AwsRequestOverrideConfiguration updateUserAgentInConfig(T request) { return request.overrideConfiguration().map(c -> c.toBuilder() .applyMutation(USER_AGENT_APPLIER) .build()) .orElseGet(() -> AwsRequestOverrideConfiguration.builder() .applyMutation(USER_AGENT_APPLIER) .build()); } }
4,885
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/checksums/ChecksumsEnabledValidator.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.checksums; import static software.amazon.awssdk.services.s3.checksums.ChecksumConstant.CHECKSUM_ENABLED_RESPONSE_HEADER; import static software.amazon.awssdk.services.s3.checksums.ChecksumConstant.ENABLE_MD5_CHECKSUM_HEADER_VALUE; import static software.amazon.awssdk.services.s3.checksums.ChecksumConstant.SERVER_SIDE_CUSTOMER_ENCRYPTION_HEADER; import static software.amazon.awssdk.services.s3.checksums.ChecksumConstant.SERVER_SIDE_ENCRYPTION_HEADER; import static software.amazon.awssdk.services.s3.model.ServerSideEncryption.AWS_KMS; import java.util.Arrays; import java.util.Optional; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute; import software.amazon.awssdk.core.ClientType; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.checksums.ChecksumSpecs; import software.amazon.awssdk.core.checksums.SdkChecksum; import software.amazon.awssdk.core.exception.RetryableException; import software.amazon.awssdk.core.interceptor.ExecutionAttribute; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.SdkExecutionAttribute; import software.amazon.awssdk.http.SdkHttpHeaders; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.http.SdkHttpResponse; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.S3Configuration; import software.amazon.awssdk.services.s3.internal.handlers.AsyncChecksumValidationInterceptor; import software.amazon.awssdk.services.s3.internal.handlers.SyncChecksumValidationInterceptor; import software.amazon.awssdk.services.s3.model.GetObjectRequest; import software.amazon.awssdk.services.s3.model.PutObjectRequest; import software.amazon.awssdk.services.s3.model.PutObjectResponse; import software.amazon.awssdk.utils.BinaryUtils; import software.amazon.awssdk.utils.StringUtils; import software.amazon.awssdk.utils.internal.Base16Lower; /** * Class used by {@link SyncChecksumValidationInterceptor} and * {@link AsyncChecksumValidationInterceptor} to determine if trailing checksums * should be enabled for a given request. */ @SdkInternalApi public final class ChecksumsEnabledValidator { public static final ExecutionAttribute<SdkChecksum> CHECKSUM = new ExecutionAttribute<>("checksum"); private ChecksumsEnabledValidator() { } /** * Checks if trailing checksum is enabled for {@link S3Client#getObject(GetObjectRequest)} per request. * * @param request the request * @param executionAttributes the executionAttributes * @return true if trailing checksums is enabled, false otherwise */ public static boolean getObjectChecksumEnabledPerRequest(SdkRequest request, ExecutionAttributes executionAttributes) { return request instanceof GetObjectRequest && checksumEnabledPerConfig(executionAttributes); } /** * Checks if trailing checksum is enabled for {@link S3Client#getObject(GetObjectRequest)} per response. * * @param request the request * @param responseHeaders the response headers * @return true if trailing checksums is enabled, false otherwise */ public static boolean getObjectChecksumEnabledPerResponse(SdkRequest request, SdkHttpHeaders responseHeaders) { return request instanceof GetObjectRequest && checksumEnabledPerResponse(responseHeaders); } /** * Validates that checksums should be enabled based on {@link ClientType} and the presence * or S3 specific headers. * * @param expectedClientType - The expected client type for enabling checksums * @param executionAttributes - {@link ExecutionAttributes} to determine the actual client type * @return If trailing checksums should be enabled for this request. */ public static boolean shouldRecordChecksum(SdkRequest sdkRequest, ClientType expectedClientType, ExecutionAttributes executionAttributes, SdkHttpRequest httpRequest) { if (!(sdkRequest instanceof PutObjectRequest)) { return false; } ClientType actualClientType = executionAttributes.getAttribute(SdkExecutionAttribute.CLIENT_TYPE); if (expectedClientType != actualClientType) { return false; } if (hasServerSideEncryptionHeader(httpRequest)) { return false; } //Checksum validation is done at Service side when HTTP Checksum algorithm attribute is set. if (isHttpCheckSumValidationEnabled(executionAttributes)) { return false; } return checksumEnabledPerConfig(executionAttributes); } private static boolean isHttpCheckSumValidationEnabled(ExecutionAttributes executionAttributes) { Optional<ChecksumSpecs> resolvedChecksum = executionAttributes.getOptionalAttribute(SdkExecutionAttribute.RESOLVED_CHECKSUM_SPECS); if (resolvedChecksum.isPresent()) { ChecksumSpecs checksumSpecs = resolvedChecksum.get(); return checksumSpecs.algorithm() != null; } return false; } public static boolean responseChecksumIsValid(SdkHttpResponse httpResponse) { return !hasServerSideEncryptionHeader(httpResponse); } private static boolean hasServerSideEncryptionHeader(SdkHttpHeaders httpRequest) { // S3 doesn't support trailing checksums for customer encryption if (httpRequest.firstMatchingHeader(SERVER_SIDE_CUSTOMER_ENCRYPTION_HEADER).isPresent()) { return true; } // S3 doesn't support trailing checksums for KMS encrypted objects if (httpRequest.firstMatchingHeader(SERVER_SIDE_ENCRYPTION_HEADER) .filter(h -> h.contains(AWS_KMS.toString())) .isPresent()) { return true; } return false; } /** * Client side validation for {@link PutObjectRequest} * * @param response the response * @param executionAttributes the execution attributes */ public static void validatePutObjectChecksum(PutObjectResponse response, ExecutionAttributes executionAttributes) { SdkChecksum checksum = executionAttributes.getAttribute(CHECKSUM); if (response.eTag() != null) { String contentMd5 = BinaryUtils.toBase64(checksum.getChecksumBytes()); byte[] digest = BinaryUtils.fromBase64(contentMd5); byte[] ssHash = Base16Lower.decode(StringUtils.replace(response.eTag(), "\"", "")); if (!Arrays.equals(digest, ssHash)) { throw RetryableException.create( String.format("Data read has a different checksum than expected. Was 0x%s, but expected 0x%s. " + "This commonly means that the data was corrupted between the client and " + "service. Note: Despite this error, the upload still completed and was persisted in S3.", BinaryUtils.toHex(digest), BinaryUtils.toHex(ssHash))); } } } /** * Check the response header to see if the trailing checksum is enabled. * * @param responseHeaders the SdkHttpHeaders * @return true if the trailing checksum is present in the header, false otherwise. */ private static boolean checksumEnabledPerResponse(SdkHttpHeaders responseHeaders) { return responseHeaders.firstMatchingHeader(CHECKSUM_ENABLED_RESPONSE_HEADER) .filter(b -> b.equals(ENABLE_MD5_CHECKSUM_HEADER_VALUE)) .isPresent(); } /** * Check the {@link S3Configuration#checksumValidationEnabled()} to see if the checksum is enabled. * * @param executionAttributes the execution attributes * @return true if the trailing checksum is enabled in the config, false otherwise. */ private static boolean checksumEnabledPerConfig(ExecutionAttributes executionAttributes) { S3Configuration serviceConfiguration = (S3Configuration) executionAttributes.getAttribute(AwsSignerExecutionAttribute.SERVICE_CONFIG); return serviceConfiguration == null || serviceConfiguration.checksumValidationEnabled(); } }
4,886
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/checksums/ChecksumValidatingPublisher.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.checksums; import static java.lang.Math.toIntExact; import java.nio.ByteBuffer; import java.util.Arrays; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.async.SdkPublisher; import software.amazon.awssdk.core.checksums.SdkChecksum; import software.amazon.awssdk.core.exception.RetryableException; import software.amazon.awssdk.utils.BinaryUtils; @SdkInternalApi public final class ChecksumValidatingPublisher implements SdkPublisher<ByteBuffer> { private final Publisher<ByteBuffer> publisher; private final SdkChecksum sdkChecksum; private final long contentLength; public ChecksumValidatingPublisher(Publisher<ByteBuffer> publisher, SdkChecksum sdkChecksum, long contentLength) { this.publisher = publisher; this.sdkChecksum = sdkChecksum; this.contentLength = contentLength; } @Override public void subscribe(Subscriber<? super ByteBuffer> s) { if (contentLength > 0) { publisher.subscribe(new ChecksumValidatingSubscriber(s, sdkChecksum, contentLength)); } else { publisher.subscribe(new ChecksumSkippingSubscriber(s)); } } private static class ChecksumValidatingSubscriber implements Subscriber<ByteBuffer> { private static final int CHECKSUM_SIZE = 16; private final Subscriber<? super ByteBuffer> wrapped; private final SdkChecksum sdkChecksum; private final long strippedLength; private byte[] streamChecksum = new byte[CHECKSUM_SIZE]; private long lengthRead = 0; ChecksumValidatingSubscriber(Subscriber<? super ByteBuffer> wrapped, SdkChecksum sdkChecksum, long contentLength) { this.wrapped = wrapped; this.sdkChecksum = sdkChecksum; this.strippedLength = contentLength - CHECKSUM_SIZE; } @Override public void onSubscribe(Subscription s) { wrapped.onSubscribe(s); } @Override public void onNext(ByteBuffer byteBuffer) { byte[] buf = BinaryUtils.copyBytesFrom(byteBuffer); if (lengthRead < strippedLength) { int toUpdate = (int) Math.min(strippedLength - lengthRead, buf.length); sdkChecksum.update(buf, 0, toUpdate); } lengthRead += buf.length; if (lengthRead >= strippedLength) { // Incoming buffer contains at least a bit of the checksum // Code below covers both cases of the incoming buffer relative to checksum border // a) buffer starts before checksum border and extends into checksum // |<------ data ------->|<--cksum-->| <--- original data // |<---buffer--->| <--- incoming buffer // |<------->| <--- checksum bytes so far // |<-->| <--- bufChecksumOffset // | <--- streamChecksumOffset // b) buffer starts at or after checksum border // |<------ data ------->|<--cksum-->| <--- original data // |<-->| <--- incoming buffer // |<------>| <--- checksum bytes so far // | <--- bufChecksumOffset // |<->| <--- streamChecksumOffset int cksumBytesSoFar = toIntExact(lengthRead - strippedLength); int bufChecksumOffset = (buf.length > cksumBytesSoFar) ? (buf.length - cksumBytesSoFar) : 0; int streamChecksumOffset = (buf.length > cksumBytesSoFar) ? 0 : (cksumBytesSoFar - buf.length); int cksumBytes = Math.min(cksumBytesSoFar, buf.length); System.arraycopy(buf, bufChecksumOffset, streamChecksum, streamChecksumOffset, cksumBytes); if (buf.length > cksumBytesSoFar) { wrapped.onNext(ByteBuffer.wrap(Arrays.copyOfRange(buf, 0, buf.length - cksumBytesSoFar))); } else { // Always be sure to satisfy the wrapped publisher's demand. wrapped.onNext(ByteBuffer.allocate(0)); // TODO: The most efficient implementation would request more from the upstream publisher instead of relying // on the downstream publisher to do that, but that's much more complicated: it requires tracking // outstanding demand from the downstream publisher. Long-term we should migrate to an RxJava publisher // implementation to reduce how error-prone our publisher implementations are. } } else { // Incoming buffer totally excludes the checksum wrapped.onNext(byteBuffer); } } @Override public void onError(Throwable t) { wrapped.onError(t); } @Override public void onComplete() { if (strippedLength > 0) { byte[] computedChecksum = sdkChecksum.getChecksumBytes(); if (!Arrays.equals(computedChecksum, streamChecksum)) { onError(RetryableException.create( String.format("Data read has a different checksum than expected. Was 0x%s, but expected 0x%s. " + "Common causes: (1) You modified a request ByteBuffer before it could be " + "written to the service. Please ensure your data source does not modify the " + " byte buffers after you pass them to the SDK. (2) The data was corrupted between the " + "client and service. Note: Despite this error, the upload still completed and was " + "persisted in S3.", BinaryUtils.toHex(computedChecksum), BinaryUtils.toHex(streamChecksum)))); return; // Return after onError and not call onComplete below } } wrapped.onComplete(); } } private static class ChecksumSkippingSubscriber implements Subscriber<ByteBuffer> { private static final int CHECKSUM_SIZE = 16; private final Subscriber<? super ByteBuffer> wrapped; ChecksumSkippingSubscriber(Subscriber<? super ByteBuffer> wrapped) { this.wrapped = wrapped; } @Override public void onSubscribe(Subscription s) { wrapped.onSubscribe(s); } @Override public void onNext(ByteBuffer byteBuffer) { byte[] buf = BinaryUtils.copyBytesFrom(byteBuffer); wrapped.onNext(ByteBuffer.wrap(Arrays.copyOfRange(buf, 0, buf.length - CHECKSUM_SIZE))); } @Override public void onError(Throwable t) { wrapped.onError(t); } @Override public void onComplete() { wrapped.onComplete(); } } }
4,887
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/checksums/ChecksumCalculatingAsyncRequestBody.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.checksums; import java.nio.ByteBuffer; import java.util.Optional; import java.util.concurrent.atomic.AtomicLong; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.core.checksums.SdkChecksum; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.utils.BinaryUtils; @SdkInternalApi public class ChecksumCalculatingAsyncRequestBody implements AsyncRequestBody { private final Long contentLength; private final AsyncRequestBody wrapped; private final SdkChecksum sdkChecksum; public ChecksumCalculatingAsyncRequestBody(SdkHttpRequest request, AsyncRequestBody wrapped, SdkChecksum sdkChecksum) { this.contentLength = request.firstMatchingHeader("Content-Length") .map(Long::parseLong) .orElseGet(() -> wrapped.contentLength() .orElse(null)); this.wrapped = wrapped; this.sdkChecksum = sdkChecksum; } @Override public Optional<Long> contentLength() { return wrapped.contentLength(); } @Override public String contentType() { return wrapped.contentType(); } @Override public void subscribe(Subscriber<? super ByteBuffer> s) { sdkChecksum.reset(); wrapped.subscribe(new ChecksumCalculatingSubscriber(s, sdkChecksum, contentLength)); } private static final class ChecksumCalculatingSubscriber implements Subscriber<ByteBuffer> { private final AtomicLong contentRead = new AtomicLong(0); private final Subscriber<? super ByteBuffer> wrapped; private final SdkChecksum checksum; private final Long contentLength; ChecksumCalculatingSubscriber(Subscriber<? super ByteBuffer> wrapped, SdkChecksum sdkChecksum, Long contentLength) { this.wrapped = wrapped; this.checksum = sdkChecksum; this.contentLength = contentLength; } @Override public void onSubscribe(Subscription s) { wrapped.onSubscribe(s); } @Override public void onNext(ByteBuffer byteBuffer) { int amountToReadFromByteBuffer = getAmountToReadFromByteBuffer(byteBuffer); if (amountToReadFromByteBuffer > 0) { byte[] buf = BinaryUtils.copyBytesFrom(byteBuffer, amountToReadFromByteBuffer); checksum.update(buf, 0, amountToReadFromByteBuffer); } wrapped.onNext(byteBuffer); } private int getAmountToReadFromByteBuffer(ByteBuffer byteBuffer) { // If content length is null, we should include everything in the checksum because the stream is essentially // unbounded. if (contentLength == null) { return byteBuffer.remaining(); } long amountReadSoFar = contentRead.getAndAdd(byteBuffer.remaining()); long amountRemaining = Math.max(0, contentLength - amountReadSoFar); if (amountRemaining > byteBuffer.remaining()) { return byteBuffer.remaining(); } else { return Math.toIntExact(amountRemaining); } } @Override public void onError(Throwable t) { wrapped.onError(t); } @Override public void onComplete() { wrapped.onComplete(); } } }
4,888
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/checksums/ChecksumCalculatingInputStream.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.checksums; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.checksums.SdkChecksum; @SdkInternalApi public class ChecksumCalculatingInputStream extends FilterInputStream { private final SdkChecksum checkSum; private final InputStream inputStream; private boolean endOfStream = false; /** * Creates an input stream using the specified Checksum. * * @param in the input stream to read * @param cksum the Checksum implementation to use for computing the checksum */ public ChecksumCalculatingInputStream(final InputStream in, final SdkChecksum cksum) { super(in); inputStream = in; checkSum = cksum; } /** * Reads from the underlying stream. If the end of the stream is reached, the * running checksum will be appended a byte at a time (1 per read call). * * @return byte read, if eos has been reached, -1 will be returned. */ @Override public int read() throws IOException { int read = -1; if (!endOfStream) { read = inputStream.read(); if (read != -1) { checkSum.update(read); } if (read == -1) { endOfStream = true; } } return read; } /** * Reads up to len bytes at a time from the input stream, updates the checksum. If the end of the stream has been reached * the checksum will be appended to the last 4 bytes. * * @param buf buffer to write into * @param off offset in the buffer to write to * @param len maximum number of bytes to attempt to read. * @return number of bytes written into buf, otherwise -1 will be returned to indicate eos. */ @Override public int read(byte[] buf, int off, int len) throws IOException { if (buf == null) { throw new NullPointerException(); } int read = -1; if (!endOfStream) { read = inputStream.read(buf, off, len); if (read != -1) { checkSum.update(buf, off, read); } if (read == -1) { endOfStream = true; } } return read; } /** * Resets stream state, including the running checksum. */ @Override public synchronized void reset() throws IOException { inputStream.reset(); checkSum.reset(); endOfStream = false; } public byte[] getChecksumBytes() { return checkSum.getChecksumBytes(); } }
4,889
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/checksums/ChecksumValidatingInputStream.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.checksums; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.checksums.SdkChecksum; import software.amazon.awssdk.core.exception.RetryableException; import software.amazon.awssdk.http.Abortable; import software.amazon.awssdk.utils.BinaryUtils; @SdkInternalApi public class ChecksumValidatingInputStream extends InputStream implements Abortable { private static final int CHECKSUM_SIZE = 16; private final SdkChecksum checkSum; private final InputStream inputStream; private long strippedLength; private byte[] streamChecksum = new byte[CHECKSUM_SIZE]; private long lengthRead = 0; // Preserve the computed checksum because some InputStream readers (e.g., java.util.Properties) read more than once at the // end of the stream. private byte[] computedChecksum; /** * Creates an input stream using the specified Checksum, input stream, and length. * * @param in the input stream * @param cksum the Checksum implementation * @param streamLength the total length of the expected stream (including the extra 4 bytes on the end). */ public ChecksumValidatingInputStream(InputStream in, SdkChecksum cksum, long streamLength) { inputStream = in; checkSum = cksum; this.strippedLength = streamLength - CHECKSUM_SIZE; } /** * Reads one byte at a time from the input stream, updates the checksum. If the end of the stream has been reached * the checksum will be compared to the stream's checksum amd a SdkClientException will be thrown. * * @return byte read, if a read happened, otherwise -1 will be returned to indicate eos. */ @Override public int read() throws IOException { int read = inputStream.read(); if (read != -1 && lengthRead < strippedLength) { checkSum.update(read); } if (read != -1) { lengthRead++; } if (read != -1 && lengthRead == strippedLength) { int byteRead = -1; byteRead = inputStream.read(); while (byteRead != -1 && lengthRead < strippedLength + CHECKSUM_SIZE) { int index = Math.min((int) (lengthRead - strippedLength), CHECKSUM_SIZE - 1); streamChecksum[index] = (byte) byteRead; lengthRead++; byteRead = inputStream.read(); } } if (read == -1) { validateAndThrow(); } return read; } /** * Reads up to len bytes at a time from the input stream, updates the checksum. If the end of the stream has been reached * the checksum will be compared to the stream's checksum amd a SdkClientException will be thrown. * * @param buf buffer to write into * @param off offset in the buffer to write to * @param len maximum number of bytes to attempt to read. * @return number of bytes written into buf, otherwise -1 will be returned to indicate eos. */ @Override public int read(byte[] buf, int off, int len) throws IOException { if (buf == null) { throw new NullPointerException(); } int read = -1; if (lengthRead < strippedLength) { long maxRead = Math.min(Integer.MAX_VALUE, strippedLength - lengthRead); int maxIterRead = (int) Math.min(maxRead, len); read = inputStream.read(buf, off, maxIterRead); int toUpdate = (int) Math.min(strippedLength - lengthRead, read); if (toUpdate > 0) { checkSum.update(buf, off, toUpdate); } lengthRead += read >= 0 ? read : 0; } if (lengthRead >= strippedLength) { int byteRead = 0; while ((byteRead = inputStream.read()) != -1) { int index = Math.min((int) (lengthRead - strippedLength), CHECKSUM_SIZE - 1); streamChecksum[index] = (byte) byteRead; lengthRead++; } if (read == -1) { validateAndThrow(); } } return read; } /** * Resets stream state, including the running checksum. */ @Override public synchronized void reset() throws IOException { inputStream.reset(); checkSum.reset(); lengthRead = 0; for (int i = 0; i < CHECKSUM_SIZE; i++) { streamChecksum[i] = 0; } } @Override public void abort() { if (inputStream instanceof Abortable) { ((Abortable) inputStream).abort(); } } @Override public void close() throws IOException { inputStream.close(); } private void validateAndThrow() { if (computedChecksum == null) { computedChecksum = checkSum.getChecksumBytes(); } if (!Arrays.equals(computedChecksum, streamChecksum)) { throw RetryableException.create( String.format("Data read has a different checksum than expected. Was 0x%s, but expected 0x%s. " + "This commonly means that the data was corrupted between the client and " + "service.", BinaryUtils.toHex(computedChecksum), BinaryUtils.toHex(streamChecksum))); } } }
4,890
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/checksums/ChecksumConstant.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.checksums; import software.amazon.awssdk.annotations.SdkInternalApi; @SdkInternalApi public final class ChecksumConstant { /** * Header name for the content-length of an S3 object. */ public static final String CONTENT_LENGTH_HEADER = "Content-Length"; /** * Header name for specifying S3 to send a trailing checksum. */ public static final String ENABLE_CHECKSUM_REQUEST_HEADER = "x-amz-te"; /** * Header name for specifying if trailing checksums were sent on an object. */ public static final String CHECKSUM_ENABLED_RESPONSE_HEADER = "x-amz-transfer-encoding"; /** * Header value for specifying MD5 as the trailing checksum of an object. */ public static final String ENABLE_MD5_CHECKSUM_HEADER_VALUE = "append-md5"; /** * Header value for specifying server side encryption. */ public static final String SERVER_SIDE_ENCRYPTION_HEADER = "x-amz-server-side-encryption"; /** * Header value for specifying server side encryption with a customer managed key. */ public static final String SERVER_SIDE_CUSTOMER_ENCRYPTION_HEADER = "x-amz-server-side-encryption-customer-algorithm"; /** * Length of an MD5 checksum in bytes. */ public static final int S3_MD5_CHECKSUM_LENGTH = 16; private ChecksumConstant() { } }
4,891
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/multipart/MultipartConfiguration.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.multipart; import java.util.function.Consumer; import software.amazon.awssdk.annotations.SdkPublicApi; 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.S3AsyncClientBuilder; import software.amazon.awssdk.services.s3.model.CopyObjectRequest; import software.amazon.awssdk.services.s3.model.GetObjectRequest; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * Class that hold configuration properties related to multipart operation for a {@link S3AsyncClient}. Passing this class to the * {@link S3AsyncClientBuilder#multipartConfiguration(MultipartConfiguration)} will enable automatic conversion of * {@link S3AsyncClient#putObject(Consumer, AsyncRequestBody)}, {@link S3AsyncClient#copyObject(CopyObjectRequest)} to their * respective multipart operation. * <p> * <em>Note</em>: The multipart operation for {@link S3AsyncClient#getObject(GetObjectRequest, AsyncResponseTransformer)} is * temporarily disabled and will result in throwing a {@link UnsupportedOperationException} if called when configured for * multipart operation. */ @SdkPublicApi public final class MultipartConfiguration implements ToCopyableBuilder<MultipartConfiguration.Builder, MultipartConfiguration> { private final Long thresholdInBytes; private final Long minimumPartSizeInBytes; private final Long apiCallBufferSizeInBytes; private MultipartConfiguration(DefaultMultipartConfigBuilder builder) { this.thresholdInBytes = builder.thresholdInBytes; this.minimumPartSizeInBytes = builder.minimumPartSizeInBytes; this.apiCallBufferSizeInBytes = builder.apiCallBufferSizeInBytes; } public static Builder builder() { return new DefaultMultipartConfigBuilder(); } @Override public Builder toBuilder() { return builder() .apiCallBufferSizeInBytes(apiCallBufferSizeInBytes) .minimumPartSizeInBytes(minimumPartSizeInBytes) .thresholdInBytes(thresholdInBytes); } /** * Indicates the value of the configured threshold, in bytes. Any request whose size is less than the configured value will * not use multipart operation * @return the value of the configured threshold. */ public Long thresholdInBytes() { return this.thresholdInBytes; } /** * Indicated the size, in bytes, of each individual part of the part requests. The actual part size used might be bigger to * conforms to the maximum number of parts allowed per multipart requests. * @return the value of the configured part size. */ public Long minimumPartSizeInBytes() { return this.minimumPartSizeInBytes; } /** * The maximum memory, in bytes, that the SDK will use to buffer requests content into memory. * @return the value of the configured maximum memory usage. */ public Long apiCallBufferSizeInBytes() { return this.apiCallBufferSizeInBytes; } /** * Builder for a {@link MultipartConfiguration}. */ public interface Builder extends CopyableBuilder<Builder, MultipartConfiguration> { /** * Configure the size threshold, in bytes, for when to use multipart upload. Uploads/copies over this size will * automatically use a multipart upload strategy, while uploads/copies smaller than this threshold will use a single * connection to upload/copy the whole object. * * <p> * Multipart uploads are easier to recover from and also potentially faster than single part uploads, especially when the * upload parts can be uploaded in parallel. Because there are additional network API calls, small objects are still * recommended to use a single connection for the upload. See * <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/mpuoverview.html">Uploading and copying objects using * multipart upload</a>. * * <p> * By default, it is the same as {@link #minimumPartSizeInBytes(Long)}. * * @param thresholdInBytes the value of the threshold to set. * @return an instance of this builder. */ Builder thresholdInBytes(Long thresholdInBytes); /** * Indicates the value of the configured threshold. * @return the value of the threshold. */ Long thresholdInBytes(); /** * Configures the part size, in bytes, to be used in each individual part requests. * Only used for putObject and copyObject operations. * <p> * When uploading large payload, the size of the payload of each individual part requests might actually be * bigger than * the configured value since there is a limit to the maximum number of parts possible per multipart request. If the * configured part size would lead to a number of parts higher than the maximum allowed, a larger part size will be * calculated instead to allow fewer part to be uploaded, to avoid the limit imposed on the maximum number of parts. * <p> * In the case where the {@code minimumPartSizeInBytes} is set to a value higher than the {@code thresholdInBytes}, when * the client receive a request with a size smaller than a single part multipart operation will <em>NOT</em> be performed * even if the size of the request is larger than the threshold. * <p> * Default value: 8 Mib * * @param minimumPartSizeInBytes the value of the part size to set * @return an instance of this builder. */ Builder minimumPartSizeInBytes(Long minimumPartSizeInBytes); /** * Indicated the value of the part configured size. * @return the value of the part size */ Long minimumPartSizeInBytes(); /** * Configures the maximum amount of memory, in bytes, the SDK will use to buffer content of requests in memory. * Increasing this value may lead to better performance at the cost of using more memory. * <p> * Default value: If not specified, the SDK will use the equivalent of four parts worth of memory, so 32 Mib by default. * * @param apiCallBufferSizeInBytes the value of the maximum memory usage. * @return an instance of this builder. */ Builder apiCallBufferSizeInBytes(Long apiCallBufferSizeInBytes); /** * Indicates the value of the maximum memory usage that the SDK will use. * @return the value of the maximum memory usage. */ Long apiCallBufferSizeInBytes(); } private static class DefaultMultipartConfigBuilder implements Builder { private Long thresholdInBytes; private Long minimumPartSizeInBytes; private Long apiCallBufferSizeInBytes; public Builder thresholdInBytes(Long thresholdInBytes) { this.thresholdInBytes = thresholdInBytes; return this; } public Long thresholdInBytes() { return this.thresholdInBytes; } public Builder minimumPartSizeInBytes(Long minimumPartSizeInBytes) { this.minimumPartSizeInBytes = minimumPartSizeInBytes; return this; } public Long minimumPartSizeInBytes() { return this.minimumPartSizeInBytes; } @Override public Builder apiCallBufferSizeInBytes(Long maximumMemoryUsageInBytes) { this.apiCallBufferSizeInBytes = maximumMemoryUsageInBytes; return this; } @Override public Long apiCallBufferSizeInBytes() { return apiCallBufferSizeInBytes; } @Override public MultipartConfiguration build() { return new MultipartConfiguration(this); } } }
4,892
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/presigner/S3Presigner.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.presigner; import java.net.URI; import java.net.URLConnection; import java.util.function.Consumer; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.awscore.presigner.PresignedRequest; import software.amazon.awssdk.awscore.presigner.SdkPresigner; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.regions.providers.DefaultAwsRegionProviderChain; import software.amazon.awssdk.services.s3.S3Configuration; import software.amazon.awssdk.services.s3.internal.signing.DefaultS3Presigner; import software.amazon.awssdk.services.s3.model.AbortMultipartUploadRequest; import software.amazon.awssdk.services.s3.model.CompleteMultipartUploadRequest; import software.amazon.awssdk.services.s3.model.CreateMultipartUploadRequest; import software.amazon.awssdk.services.s3.model.DeleteObjectRequest; import software.amazon.awssdk.services.s3.model.GetObjectRequest; import software.amazon.awssdk.services.s3.model.PutObjectRequest; import software.amazon.awssdk.services.s3.model.UploadPartRequest; import software.amazon.awssdk.services.s3.presigner.model.AbortMultipartUploadPresignRequest; import software.amazon.awssdk.services.s3.presigner.model.CompleteMultipartUploadPresignRequest; import software.amazon.awssdk.services.s3.presigner.model.CreateMultipartUploadPresignRequest; import software.amazon.awssdk.services.s3.presigner.model.DeleteObjectPresignRequest; import software.amazon.awssdk.services.s3.presigner.model.GetObjectPresignRequest; import software.amazon.awssdk.services.s3.presigner.model.PresignedAbortMultipartUploadRequest; import software.amazon.awssdk.services.s3.presigner.model.PresignedCompleteMultipartUploadRequest; import software.amazon.awssdk.services.s3.presigner.model.PresignedCreateMultipartUploadRequest; import software.amazon.awssdk.services.s3.presigner.model.PresignedDeleteObjectRequest; import software.amazon.awssdk.services.s3.presigner.model.PresignedGetObjectRequest; import software.amazon.awssdk.services.s3.presigner.model.PresignedPutObjectRequest; import software.amazon.awssdk.services.s3.presigner.model.PresignedUploadPartRequest; import software.amazon.awssdk.services.s3.presigner.model.PutObjectPresignRequest; import software.amazon.awssdk.services.s3.presigner.model.UploadPartPresignRequest; /** * Enables signing an S3 {@link SdkRequest} so that it can be executed without requiring any additional authentication on the * part of the caller. * <p/> * * For example: if Alice has access to an S3 object, and she wants to temporarily share access to that object with Bob, she * can generate a pre-signed {@link GetObjectRequest} to secure share with Bob so that he can download the object without * requiring access to Alice's credentials. * <p/> * * <h2>Signature Duration</h2> * <p/> * * Pre-signed requests are only valid for a finite period of time, referred to as the signature duration. This signature * duration is configured when the request is generated, and cannot be longer than 7 days. Attempting to generate a signature * longer than 7 days in the future will fail at generation time. Attempting to use a pre-signed request after the signature * duration has passed will result in an access denied response from the service. * <p/> * * <h3>Example Usage</h3> * <p/> * * <pre> * {@code * // Create an S3Presigner using the default region and credentials. * // This is usually done at application startup, because creating a presigner can be expensive. * S3Presigner presigner = S3Presigner.create(); * * // Create a GetObjectRequest to be pre-signed * GetObjectRequest getObjectRequest = * GetObjectRequest.builder() * .bucket("my-bucket") * .key("my-key") * .build(); * * // Create a GetObjectPresignRequest to specify the signature duration * GetObjectPresignRequest getObjectPresignRequest = * GetObjectPresignRequest.builder() * .signatureDuration(Duration.ofMinutes(10)) * .getObjectRequest(getObjectRequest) * .build(); * * // Generate the presigned request * PresignedGetObjectRequest presignedGetObjectRequest = * presigner.presignGetObject(getObjectPresignRequest); * * // Log the presigned URL, for example. * System.out.println("Presigned URL: " + presignedGetObjectRequest.url()); * * // It is recommended to close the S3Presigner when it is done being used, because some credential * // providers (e.g. if your AWS profile is configured to assume an STS role) require system resources * // that need to be freed. If you are using one S3Presigner per application (as recommended), this * // usually is not needed. * presigner.close(); * } * </pre> * <p/> * * <h2>Browser Compatibility</h2> * <p/> * * Some pre-signed requests can be executed by a web browser. These "browser compatible" pre-signed requests * do not require the customer to send anything other than a "host" header when performing an HTTP GET against * the pre-signed URL. * <p/> * * Whether a pre-signed request is "browser compatible" can be determined by checking the * {@link PresignedRequest#isBrowserExecutable()} flag. It is recommended to always check this flag when the pre-signed * request needs to be executed by a browser, because some request fields will result in the pre-signed request not * being browser-compatible. * <p /> * * <h3>Configurations that affect browser compatibility</h3> * <h4>Enabling Checking Validation</h4> * If checksum validations are enabled, the presigned URL will no longer be browser compatible because it adds a signed header * that must be included in the HTTP request. * * Checksum validation is disabled in the presigner by default, but when using a custom {@link S3Configuration} when enabling * features like path style access or accelerate mode, it must be explicitly disabled: * * <pre> * S3Presigner presigner = S3Presigner.builder() * .serviceConfiguration(S3Configuration.builder() * .checksumValidationEnabled(false) * .build()) * .build(); * </pre> * * * <h2>Executing a Pre-Signed Request from Java code</h2> * <p /> * * Browser-compatible requests (see above) can be executed using a web browser. All pre-signed requests can be executed * from Java code. This documentation describes two methods for executing a pre-signed request: (1) using the JDK's * {@link URLConnection} class, (2) using an SDK synchronous {@link SdkHttpClient} class. * * <p /> * <i>Using {code URLConnection}:</i> * * <p /> * <pre> * // Create a pre-signed request using one of the "presign" methods on S3Presigner * PresignedRequest presignedRequest = ...; * * // Create a JDK HttpURLConnection for communicating with S3 * HttpURLConnection connection = (HttpURLConnection) presignedRequest.url().openConnection(); * * // Specify any headers that are needed by the service (not needed when isBrowserExecutable is true) * presignedRequest.httpRequest().headers().forEach((header, values) -> { * values.forEach(value -> { * connection.addRequestProperty(header, value); * }); * }); * * // Send any request payload that is needed by the service (not needed when isBrowserExecutable is true) * if (presignedRequest.signedPayload().isPresent()) { * connection.setDoOutput(true); * try (InputStream signedPayload = presignedRequest.signedPayload().get().asInputStream(); * OutputStream httpOutputStream = connection.getOutputStream()) { * IoUtils.copy(signedPayload, httpOutputStream); * } * } * * // Download the result of executing the request * try (InputStream content = connection.getInputStream()) { * System.out.println("Service returned response: "); * IoUtils.copy(content, System.out); * } * </pre> * <p /> * * <i>Using {code SdkHttpClient}:</i> * <p /> * * <pre> * // Create a pre-signed request using one of the "presign" methods on S3Presigner * PresignedRequest presignedRequest = ...; * * // Create an SdkHttpClient using one of the implementations provided by the SDK * SdkHttpClient httpClient = ApacheHttpClient.builder().build(); // or UrlConnectionHttpClient.create() * * // Specify any request payload that is needed by the service (not needed when isBrowserExecutable is true) * ContentStreamProvider requestPayload = * presignedRequest.signedPayload() * .map(SdkBytes::asContentStreamProvider) * .orElse(null); * * // Create the request for sending to the service * HttpExecuteRequest request = * HttpExecuteRequest.builder() * .request(presignedRequest.httpRequest()) * .contentStreamProvider(requestPayload) * .build(); * * // Call the service * HttpExecuteResponse response = httpClient.prepareRequest(request).call(); * * // Download the result of executing the request * if (response.responseBody().isPresent()) { * try (InputStream responseStream = response.responseBody().get()) { * System.out.println("Service returned response: "); * IoUtils.copy(content, System.out); * } * } * </pre> */ @SdkPublicApi @Immutable @ThreadSafe public interface S3Presigner extends SdkPresigner { /** * Create an {@link S3Presigner} with default configuration. The region will be loaded from the * {@link DefaultAwsRegionProviderChain} and credentials will be loaded from the {@link DefaultCredentialsProvider}. * <p/> * This is usually done at application startup, because creating a presigner can be expensive. It is recommended to * {@link #close()} the {@code S3Presigner} when it is done being used. */ static S3Presigner create() { return builder().build(); } /** * Create an {@link S3Presigner.Builder} that can be used to configure and create a {@link S3Presigner}. * <p/> * This is usually done at application startup, because creating a presigner can be expensive. It is recommended to * {@link #close()} the {@code S3Presigner} when it is done being used. */ static Builder builder() { return DefaultS3Presigner.builder(); } /** * Presign a {@link GetObjectRequest} so that it can be executed at a later time without requiring additional * signing or authentication. * <p/> * * <b>Example Usage</b> * <p/> * * <pre> * {@code * S3Presigner presigner = ...; * * // Create a GetObjectRequest to be pre-signed * GetObjectRequest getObjectRequest = ...; * * // Create a GetObjectPresignRequest to specify the signature duration * GetObjectPresignRequest getObjectPresignRequest = * GetObjectPresignRequest.builder() * .signatureDuration(Duration.ofMinutes(10)) * .getObjectRequest(request) * .build(); * * // Generate the presigned request * PresignedGetObjectRequest presignedGetObjectRequest = * presigner.presignGetObject(getObjectPresignRequest); * * if (presignedGetObjectRequest.isBrowserExecutable()) * System.out.println("The pre-signed request can be executed using a web browser by " + * "visiting the following URL: " + presignedGetObjectRequest.url()); * else * System.out.println("The pre-signed request has an HTTP method, headers or a payload " + * "that prohibits it from being executed by a web browser. See the S3Presigner " + * "class-level documentation for an example of how to execute this pre-signed " + * "request from Java code."); * } * </pre> */ PresignedGetObjectRequest presignGetObject(GetObjectPresignRequest request); /** * Presign a {@link GetObjectRequest} so that it can be executed at a later time without requiring additional * signing or authentication. * <p /> * This is a shorter method of invoking {@link #presignGetObject(GetObjectPresignRequest)} without needing * to call {@code GetObjectPresignRequest.builder()} or {@code .build()}. * * @see #presignGetObject(GetObjectPresignRequest) */ default PresignedGetObjectRequest presignGetObject(Consumer<GetObjectPresignRequest.Builder> request) { GetObjectPresignRequest.Builder builder = GetObjectPresignRequest.builder(); request.accept(builder); return presignGetObject(builder.build()); } /** * Presign a {@link PutObjectRequest} so that it can be executed at a later time without requiring additional * signing or authentication. * <p> * <b>Example Usage</b> * * <pre> * {@code * S3Presigner presigner = ...; * * // Create a PutObjectRequest to be pre-signed * PutObjectRequest putObjectRequest = ...; * * // Create a PutObjectPresignRequest to specify the signature duration * PutObjectPresignRequest putObjectPresignRequest = * PutObjectPresignRequest.builder() * .signatureDuration(Duration.ofMinutes(10)) * .putObjectRequest(request) * .build(); * * // Generate the presigned request * PresignedPutObjectRequest presignedPutObjectRequest = * presigner.presignPutObject(putObjectPresignRequest); * } * </pre> */ PresignedPutObjectRequest presignPutObject(PutObjectPresignRequest request); /** * Presign a {@link PutObjectRequest} so that it can be executed at a later time without requiring additional * signing or authentication. * <p> * This is a shorter method of invoking {@link #presignPutObject(PutObjectPresignRequest)} without needing * to call {@code PutObjectPresignRequest.builder()} or {@code .build()}. * * @see #presignPutObject(PutObjectPresignRequest) */ default PresignedPutObjectRequest presignPutObject(Consumer<PutObjectPresignRequest.Builder> request) { PutObjectPresignRequest.Builder builder = PutObjectPresignRequest.builder(); request.accept(builder); return presignPutObject(builder.build()); } /** * Presign a {@link DeleteObjectRequest} so that it can be executed at a later time without requiring additional * signing or authentication. * <p> * <b>Example Usage</b> * * <pre> * {@code * S3Presigner presigner = ...; * * // Create a DeleteObjectRequest to be pre-signed * DeleteObjectRequest deleteObjectRequest = ...; * * // Create a PutObjectPresignRequest to specify the signature duration * DeleteObjectPresignRequest deleteObjectPresignRequest = * DeleteObjectPresignRequest.builder() * .signatureDuration(Duration.ofMinutes(10)) * .deleteObjectRequest(deleteObjectRequest) * .build(); * * // Generate the presigned request * PresignedDeleteObjectRequest presignedDeleteObjectRequest = * presigner.presignDeleteObject(deleteObjectPresignRequest); * } * </pre> */ PresignedDeleteObjectRequest presignDeleteObject(DeleteObjectPresignRequest request); /** * Presign a {@link DeleteObjectRequest} so that it can be executed at a later time without requiring additional * signing or authentication. * <p> * This is a shorter method of invoking {@link #presignDeleteObject(DeleteObjectPresignRequest)} without needing * to call {@code DeleteObjectPresignRequest.builder()} or {@code .build()}. * * @see #presignDeleteObject(PresignedDeleteObjectRequest) */ default PresignedDeleteObjectRequest presignDeleteObject(Consumer<DeleteObjectPresignRequest.Builder> request) { DeleteObjectPresignRequest.Builder builder = DeleteObjectPresignRequest.builder(); request.accept(builder); return presignDeleteObject(builder.build()); } /** * Presign a {@link CreateMultipartUploadRequest} so that it can be executed at a later time without requiring additional * signing or authentication. * <p> * <b>Example Usage</b> * * <pre> * {@code * S3Presigner presigner = ...; * * // Create a CreateMultipartUploadRequest to be pre-signed * CreateMultipartUploadRequest createMultipartUploadRequest = ...; * * // Create a CreateMultipartUploadPresignRequest to specify the signature duration * CreateMultipartUploadPresignRequest createMultipartUploadPresignRequest = * CreateMultipartUploadPresignRequest.builder() * .signatureDuration(Duration.ofMinutes(10)) * .createMultipartUploadRequest(request) * .build(); * * // Generate the presigned request * PresignedCreateMultipartUploadRequest presignedCreateMultipartUploadRequest = * presigner.presignCreateMultipartUpload(createMultipartUploadPresignRequest); * } * </pre> */ PresignedCreateMultipartUploadRequest presignCreateMultipartUpload(CreateMultipartUploadPresignRequest request); /** * Presign a {@link CreateMultipartUploadRequest} so that it can be executed at a later time without requiring additional * signing or authentication. * <p> * This is a shorter method of invoking {@link #presignCreateMultipartUpload(CreateMultipartUploadPresignRequest)} without * needing to call {@code CreateMultipartUploadPresignRequest.builder()} or {@code .build()}. * * @see #presignCreateMultipartUpload(CreateMultipartUploadPresignRequest) */ default PresignedCreateMultipartUploadRequest presignCreateMultipartUpload( Consumer<CreateMultipartUploadPresignRequest.Builder> request) { CreateMultipartUploadPresignRequest.Builder builder = CreateMultipartUploadPresignRequest.builder(); request.accept(builder); return presignCreateMultipartUpload(builder.build()); } /** * Presign a {@link UploadPartRequest} so that it can be executed at a later time without requiring additional * signing or authentication. * <p> * * <b>Example Usage</b> * * <pre> * {@code * S3Presigner presigner = ...; * * // Create a UploadPartRequest to be pre-signed * UploadPartRequest uploadPartRequest = ...; * * // Create a UploadPartPresignRequest to specify the signature duration * UploadPartPresignRequest uploadPartPresignRequest = * UploadPartPresignRequest.builder() * .signatureDuration(Duration.ofMinutes(10)) * .uploadPartRequest(request) * .build(); * * // Generate the presigned request * PresignedUploadPartRequest presignedUploadPartRequest = * presigner.presignUploadPart(uploadPartPresignRequest); * } * </pre> */ PresignedUploadPartRequest presignUploadPart(UploadPartPresignRequest request); /** * Presign a {@link UploadPartRequest} so that it can be executed at a later time without requiring additional * signing or authentication. * <p> * This is a shorter method of invoking {@link #presignUploadPart(UploadPartPresignRequest)} without needing * to call {@code UploadPartPresignRequest.builder()} or {@code .build()}. * * @see #presignUploadPart(UploadPartPresignRequest) */ default PresignedUploadPartRequest presignUploadPart(Consumer<UploadPartPresignRequest.Builder> request) { UploadPartPresignRequest.Builder builder = UploadPartPresignRequest.builder(); request.accept(builder); return presignUploadPart(builder.build()); } /** * Presign a {@link CompleteMultipartUploadRequest} so that it can be executed at a later time without requiring additional * signing or authentication. * <p> * * <b>Example Usage</b> * * <pre> * {@code * S3Presigner presigner = ...; * * // Complete a CompleteMultipartUploadRequest to be pre-signed * CompleteMultipartUploadRequest completeMultipartUploadRequest = ...; * * // Create a CompleteMultipartUploadPresignRequest to specify the signature duration * CompleteMultipartUploadPresignRequest completeMultipartUploadPresignRequest = * CompleteMultipartUploadPresignRequest.builder() * .signatureDuration(Duration.ofMinutes(10)) * .completeMultipartUploadRequest(request) * .build(); * * // Generate the presigned request * PresignedCompleteMultipartUploadRequest presignedCompleteMultipartUploadRequest = * presigner.presignCompleteMultipartUpload(completeMultipartUploadPresignRequest); * } * </pre> */ PresignedCompleteMultipartUploadRequest presignCompleteMultipartUpload(CompleteMultipartUploadPresignRequest request); /** * Presign a {@link CompleteMultipartUploadRequest} so that it can be executed at a later time without requiring additional * signing or authentication. * <p> * This is a shorter method of invoking {@link #presignCompleteMultipartUpload(CompleteMultipartUploadPresignRequest)} without * needing to call {@code CompleteMultipartUploadPresignRequest.builder()} or {@code .build()}. * * @see #presignCompleteMultipartUpload(CompleteMultipartUploadPresignRequest) */ default PresignedCompleteMultipartUploadRequest presignCompleteMultipartUpload( Consumer<CompleteMultipartUploadPresignRequest.Builder> request) { CompleteMultipartUploadPresignRequest.Builder builder = CompleteMultipartUploadPresignRequest.builder(); request.accept(builder); return presignCompleteMultipartUpload(builder.build()); } /** * Presign a {@link AbortMultipartUploadRequest} so that it can be executed at a later time without requiring additional * signing or authentication. * <p> * * <b>Example Usage</b> * * <pre> * {@code * S3Presigner presigner = ...; * * // Complete a AbortMultipartUploadRequest to be pre-signed * AbortMultipartUploadRequest abortMultipartUploadRequest = ...; * * // Create a AbortMultipartUploadPresignRequest to specify the signature duration * AbortMultipartUploadPresignRequest abortMultipartUploadPresignRequest = * AbortMultipartUploadPresignRequest.builder() * .signatureDuration(Duration.ofMinutes(10)) * .abortMultipartUploadRequest(request) * .build(); * * // Generate the presigned request * PresignedAbortMultipartUploadRequest presignedAbortMultipartUploadRequest = * presigner.presignAbortMultipartUpload(abortMultipartUploadPresignRequest); * } * </pre> */ PresignedAbortMultipartUploadRequest presignAbortMultipartUpload(AbortMultipartUploadPresignRequest request); /** * Presign a {@link AbortMultipartUploadRequest} so that it can be executed at a later time without requiring additional * signing or authentication. * <p> * This is a shorter method of invoking {@link #presignAbortMultipartUpload(AbortMultipartUploadPresignRequest)} without * needing to call {@code AbortMultipartUploadPresignRequest.builder()} or {@code .build()}. * * @see #presignAbortMultipartUpload(AbortMultipartUploadPresignRequest) */ default PresignedAbortMultipartUploadRequest presignAbortMultipartUpload( Consumer<AbortMultipartUploadPresignRequest.Builder> request) { AbortMultipartUploadPresignRequest.Builder builder = AbortMultipartUploadPresignRequest.builder(); request.accept(builder); return presignAbortMultipartUpload(builder.build()); } /** * A builder for creating {@link S3Presigner}s. Created using {@link #builder()}. */ @SdkPublicApi @NotThreadSafe interface Builder extends SdkPresigner.Builder { /** * Allows providing a custom S3 serviceConfiguration by providing a {@link S3Configuration} object; * * Note: chunkedEncodingEnabled and checksumValidationEnabled do not apply to presigned requests. * * @param serviceConfiguration {@link S3Configuration} * @return this Builder */ Builder serviceConfiguration(S3Configuration serviceConfiguration); @Override Builder region(Region region); @Override default Builder credentialsProvider(AwsCredentialsProvider credentialsProvider) { return credentialsProvider((IdentityProvider<? extends AwsCredentialsIdentity>) credentialsProvider); } @Override Builder credentialsProvider(IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider); @Override Builder dualstackEnabled(Boolean dualstackEnabled); @Override Builder fipsEnabled(Boolean dualstackEnabled); @Override Builder endpointOverride(URI endpointOverride); @Override S3Presigner build(); } }
4,893
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/presigner
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/presigner/model/GetObjectPresignRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.presigner.model; import java.time.Duration; import java.util.function.Consumer; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.awscore.presigner.PresignRequest; import software.amazon.awssdk.services.s3.model.GetObjectRequest; import software.amazon.awssdk.services.s3.presigner.S3Presigner; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * A request to pre-sign a {@link GetObjectRequest} so that it can be executed at a later time without requiring additional * signing or authentication. * * @see S3Presigner#presignGetObject(GetObjectPresignRequest) * @see #builder() */ @SdkPublicApi @Immutable @ThreadSafe public final class GetObjectPresignRequest extends PresignRequest implements ToCopyableBuilder<GetObjectPresignRequest.Builder, GetObjectPresignRequest> { private final GetObjectRequest getObjectRequest; private GetObjectPresignRequest(DefaultBuilder builder) { super(builder); this.getObjectRequest = Validate.notNull(builder.getObjectRequest, "getObjectRequest"); } /** * Create a builder that can be used to create a {@link GetObjectPresignRequest}. * * @see S3Presigner#presignGetObject(GetObjectPresignRequest) */ public static Builder builder() { return new DefaultBuilder(); } /** * Retrieve the {@link GetObjectRequest} that should be presigned. */ public GetObjectRequest getObjectRequest() { return getObjectRequest; } @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; } if (!super.equals(o)) { return false; } GetObjectPresignRequest that = (GetObjectPresignRequest) o; return getObjectRequest.equals(that.getObjectRequest); } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + getObjectRequest.hashCode(); return result; } /** * A builder for a {@link GetObjectPresignRequest}, created with {@link #builder()}. */ @SdkPublicApi @NotThreadSafe public interface Builder extends PresignRequest.Builder, CopyableBuilder<GetObjectPresignRequest.Builder, GetObjectPresignRequest> { /** * Configure the {@link GetObjectRequest} that should be presigned. */ Builder getObjectRequest(GetObjectRequest getObjectRequest); /** * Configure the {@link GetObjectRequest} that should be presigned. * <p/> * This is a convenience method for invoking {@link #getObjectRequest(GetObjectRequest)} without needing to invoke * {@code GetObjectRequest.builder()} or {@code build()}. */ default Builder getObjectRequest(Consumer<GetObjectRequest.Builder> getObjectRequest) { GetObjectRequest.Builder builder = GetObjectRequest.builder(); getObjectRequest.accept(builder); return getObjectRequest(builder.build()); } @Override Builder signatureDuration(Duration signatureDuration); @Override GetObjectPresignRequest build(); } @SdkInternalApi private static final class DefaultBuilder extends PresignRequest.DefaultBuilder<DefaultBuilder> implements Builder { private GetObjectRequest getObjectRequest; private DefaultBuilder() { } private DefaultBuilder(GetObjectPresignRequest request) { super(request); this.getObjectRequest = request.getObjectRequest; } @Override public Builder getObjectRequest(GetObjectRequest getObjectRequest) { this.getObjectRequest = getObjectRequest; return this; } @Override public GetObjectPresignRequest build() { return new GetObjectPresignRequest(this); } } }
4,894
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/presigner
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/presigner/model/PresignedUploadPartRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.presigner.model; import java.time.Instant; import java.util.List; import java.util.Map; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.awscore.presigner.PresignedRequest; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.services.s3.model.UploadPartRequest; import software.amazon.awssdk.services.s3.presigner.S3Presigner; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * A pre-signed {@link UploadPartRequest} that can be executed at a later time without requiring additional signing or * authentication. * * @see S3Presigner#presignUploadPart(UploadPartPresignRequest) * @see #builder() */ @SdkPublicApi @Immutable @ThreadSafe public class PresignedUploadPartRequest extends PresignedRequest implements ToCopyableBuilder<PresignedUploadPartRequest.Builder, PresignedUploadPartRequest> { private PresignedUploadPartRequest(DefaultBuilder builder) { super(builder); } /** * Create a builder that can be used to create a {@link PresignedUploadPartRequest}. * * @see S3Presigner#presignUploadPart(UploadPartPresignRequest) */ public static Builder builder() { return new DefaultBuilder(); } @Override public Builder toBuilder() { return new DefaultBuilder(this); } /** * A builder for a {@link PresignedUploadPartRequest}, created with {@link #builder()}. */ @SdkPublicApi @NotThreadSafe public interface Builder extends PresignedRequest.Builder, CopyableBuilder<PresignedUploadPartRequest.Builder, PresignedUploadPartRequest> { @Override Builder expiration(Instant expiration); @Override Builder isBrowserExecutable(Boolean isBrowserExecutable); @Override Builder signedHeaders(Map<String, List<String>> signedHeaders); @Override Builder signedPayload(SdkBytes signedPayload); @Override Builder httpRequest(SdkHttpRequest httpRequest); @Override PresignedUploadPartRequest build(); } @SdkInternalApi private static final class DefaultBuilder extends PresignedRequest.DefaultBuilder<DefaultBuilder> implements Builder { private DefaultBuilder() { } private DefaultBuilder(PresignedUploadPartRequest request) { super(request); } @Override public PresignedUploadPartRequest build() { return new PresignedUploadPartRequest(this); } } }
4,895
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/presigner
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/presigner/model/PresignedDeleteObjectRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.presigner.model; import java.time.Instant; import java.util.List; import java.util.Map; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.awscore.presigner.PresignedRequest; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.services.s3.model.DeleteObjectRequest; import software.amazon.awssdk.services.s3.presigner.S3Presigner; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * A pre-signed a {@link DeleteObjectRequest} that can be executed at a later time without requiring additional signing or * authentication. * * @see S3Presigner#presignDeleteObject(DeleteObjectPresignRequest) * @see #builder() */ @SdkPublicApi @Immutable @ThreadSafe public class PresignedDeleteObjectRequest extends PresignedRequest implements ToCopyableBuilder<PresignedDeleteObjectRequest.Builder, PresignedDeleteObjectRequest> { protected PresignedDeleteObjectRequest(DefaultBuilder builder) { super(builder); } @Override public Builder toBuilder() { return new DefaultBuilder(this); } /** * Create a builder that can be used to create a {@link PresignedDeleteObjectRequest}. * * @see S3Presigner#presignDeleteObject(DeleteObjectPresignRequest) */ public static Builder builder() { return new DefaultBuilder(); } /** * A builder for a {@link PresignedDeleteObjectRequest}, created with {@link #builder()}. */ @SdkPublicApi @NotThreadSafe public interface Builder extends PresignedRequest.Builder, CopyableBuilder<PresignedDeleteObjectRequest.Builder, PresignedDeleteObjectRequest> { @Override Builder expiration(Instant expiration); @Override Builder isBrowserExecutable(Boolean isBrowserExecutable); @Override Builder signedHeaders(Map<String, List<String>> signedHeaders); @Override Builder signedPayload(SdkBytes signedPayload); @Override Builder httpRequest(SdkHttpRequest httpRequest); @Override PresignedDeleteObjectRequest build(); } @SdkInternalApi private static final class DefaultBuilder extends PresignedRequest.DefaultBuilder<DefaultBuilder> implements PresignedDeleteObjectRequest.Builder { private DefaultBuilder() { } private DefaultBuilder(PresignedDeleteObjectRequest presignedDeleteObjectRequest) { super(presignedDeleteObjectRequest); } @Override public PresignedDeleteObjectRequest build() { return new PresignedDeleteObjectRequest(this); } } }
4,896
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/presigner
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/presigner/model/PresignedCompleteMultipartUploadRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.presigner.model; import java.time.Instant; import java.util.List; import java.util.Map; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.awscore.presigner.PresignedRequest; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.services.s3.model.CompleteMultipartUploadRequest; import software.amazon.awssdk.services.s3.presigner.S3Presigner; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * A pre-signed {@link CompleteMultipartUploadRequest} that can be executed at a later time without requiring additional signing * or authentication. * * @see S3Presigner#presignCompleteMultipartUpload(CompleteMultipartUploadPresignRequest) * @see #builder() */ @SdkPublicApi @Immutable @ThreadSafe public class PresignedCompleteMultipartUploadRequest extends PresignedRequest implements ToCopyableBuilder<PresignedCompleteMultipartUploadRequest.Builder, PresignedCompleteMultipartUploadRequest> { private PresignedCompleteMultipartUploadRequest(DefaultBuilder builder) { super(builder); } /** * Create a builder that can be used to create a {@link PresignedCompleteMultipartUploadRequest}. * * @see S3Presigner#presignCompleteMultipartUpload(CompleteMultipartUploadPresignRequest) */ public static Builder builder() { return new DefaultBuilder(); } @Override public Builder toBuilder() { return new DefaultBuilder(this); } /** * A builder for a {@link PresignedCompleteMultipartUploadRequest}, created with {@link #builder()}. */ @SdkPublicApi @NotThreadSafe public interface Builder extends PresignedRequest.Builder, CopyableBuilder<PresignedCompleteMultipartUploadRequest.Builder, PresignedCompleteMultipartUploadRequest> { @Override Builder expiration(Instant expiration); @Override Builder isBrowserExecutable(Boolean isBrowserExecutable); @Override Builder signedHeaders(Map<String, List<String>> signedHeaders); @Override Builder signedPayload(SdkBytes signedPayload); @Override Builder httpRequest(SdkHttpRequest httpRequest); @Override PresignedCompleteMultipartUploadRequest build(); } @SdkInternalApi private static final class DefaultBuilder extends PresignedRequest.DefaultBuilder<DefaultBuilder> implements Builder { private DefaultBuilder() { } private DefaultBuilder(PresignedCompleteMultipartUploadRequest request) { super(request); } @Override public PresignedCompleteMultipartUploadRequest build() { return new PresignedCompleteMultipartUploadRequest(this); } } }
4,897
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/presigner
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/presigner/model/UploadPartPresignRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.presigner.model; import java.time.Duration; import java.util.function.Consumer; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.awscore.presigner.PresignRequest; import software.amazon.awssdk.services.s3.model.UploadPartRequest; import software.amazon.awssdk.services.s3.presigner.S3Presigner; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * A request to pre-sign a {@link UploadPartRequest} so that it can be executed at a later time without requiring additional * signing or authentication. * * @see S3Presigner#presignUploadPart(UploadPartPresignRequest) * @see #builder() */ @SdkPublicApi @Immutable @ThreadSafe public final class UploadPartPresignRequest extends PresignRequest implements ToCopyableBuilder<UploadPartPresignRequest.Builder, UploadPartPresignRequest> { private final UploadPartRequest uploadPartRequest; private UploadPartPresignRequest(DefaultBuilder builder) { super(builder); this.uploadPartRequest = Validate.notNull(builder.uploadPartRequest, "uploadPartRequest"); } /** * Create a builder that can be used to create a {@link UploadPartPresignRequest}. * * @see S3Presigner#presignUploadPart(UploadPartPresignRequest) */ public static Builder builder() { return new DefaultBuilder(); } /** * Retrieve the {@link UploadPartRequest} that should be presigned. */ public UploadPartRequest uploadPartRequest() { return uploadPartRequest; } @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; } if (!super.equals(o)) { return false; } UploadPartPresignRequest that = (UploadPartPresignRequest) o; return uploadPartRequest.equals(that.uploadPartRequest); } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + uploadPartRequest.hashCode(); return result; } /** * A builder for a {@link UploadPartPresignRequest}, created with {@link #builder()}. */ @SdkPublicApi @NotThreadSafe public interface Builder extends PresignRequest.Builder, CopyableBuilder<UploadPartPresignRequest.Builder, UploadPartPresignRequest> { /** * Configure the {@link UploadPartRequest} that should be presigned. */ Builder uploadPartRequest(UploadPartRequest uploadPartRequest); /** * Configure the {@link UploadPartRequest} that should be presigned. * <p/> * This is a convenience method for invoking {@link #uploadPartRequest(UploadPartRequest)} without needing to invoke * {@code UploadPartRequest.builder()} or {@code build()}. */ default Builder uploadPartRequest(Consumer<UploadPartRequest.Builder> uploadPartRequest) { UploadPartRequest.Builder builder = UploadPartRequest.builder(); uploadPartRequest.accept(builder); return uploadPartRequest(builder.build()); } @Override Builder signatureDuration(Duration signatureDuration); @Override UploadPartPresignRequest build(); } @SdkInternalApi private static final class DefaultBuilder extends PresignRequest.DefaultBuilder<DefaultBuilder> implements Builder { private UploadPartRequest uploadPartRequest; private DefaultBuilder() { } private DefaultBuilder(UploadPartPresignRequest request) { super(request); this.uploadPartRequest = request.uploadPartRequest; } @Override public Builder uploadPartRequest(UploadPartRequest uploadPartRequest) { this.uploadPartRequest = uploadPartRequest; return this; } @Override public UploadPartPresignRequest build() { return new UploadPartPresignRequest(this); } } }
4,898
0
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/presigner
Create_ds/aws-sdk-java-v2/services/s3/src/main/java/software/amazon/awssdk/services/s3/presigner/model/PresignedPutObjectRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.s3.presigner.model; import java.time.Instant; import java.util.List; import java.util.Map; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.awscore.presigner.PresignedRequest; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.services.s3.model.PutObjectRequest; import software.amazon.awssdk.services.s3.presigner.S3Presigner; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * A pre-signed a {@link PutObjectRequest} that can be executed at a later time without requiring additional signing or * authentication. * * @see S3Presigner#presignPutObject(PutObjectPresignRequest) * @see #builder() */ @SdkPublicApi @Immutable @ThreadSafe public class PresignedPutObjectRequest extends PresignedRequest implements ToCopyableBuilder<PresignedPutObjectRequest.Builder, PresignedPutObjectRequest> { private PresignedPutObjectRequest(DefaultBuilder builder) { super(builder); } /** * Create a builder that can be used to create a {@link PresignedPutObjectRequest}. * * @see S3Presigner#presignPutObject(PutObjectPresignRequest) */ public static Builder builder() { return new DefaultBuilder(); } @Override public Builder toBuilder() { return new DefaultBuilder(this); } /** * A builder for a {@link PresignedPutObjectRequest}, created with {@link #builder()}. */ @SdkPublicApi @NotThreadSafe public interface Builder extends PresignedRequest.Builder, CopyableBuilder<PresignedPutObjectRequest.Builder, PresignedPutObjectRequest> { @Override Builder expiration(Instant expiration); @Override Builder isBrowserExecutable(Boolean isBrowserExecutable); @Override Builder signedHeaders(Map<String, List<String>> signedHeaders); @Override Builder signedPayload(SdkBytes signedPayload); @Override Builder httpRequest(SdkHttpRequest httpRequest); @Override PresignedPutObjectRequest build(); } @SdkInternalApi private static final class DefaultBuilder extends PresignedRequest.DefaultBuilder<DefaultBuilder> implements Builder { private DefaultBuilder() { } private DefaultBuilder(PresignedPutObjectRequest request) { super(request); } @Override public PresignedPutObjectRequest build() { return new PresignedPutObjectRequest(this); } } }
4,899