index int64 0 0 | repo_id stringlengths 26 205 | file_path stringlengths 51 246 | content stringlengths 8 433k | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/aws-sdk-java-v2/services/s3/src/it/java/software/amazon/awssdk/services | Create_ds/aws-sdk-java-v2/services/s3/src/it/java/software/amazon/awssdk/services/s3/CreateBucketIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.s3;
import static org.assertj.core.api.Assertions.assertThat;
import static software.amazon.awssdk.testutils.service.S3BucketUtils.temporaryBucketName;
import org.junit.AfterClass;
import org.junit.Test;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.model.CreateBucketRequest;
import software.amazon.awssdk.services.s3.utils.S3TestUtils;
import software.amazon.awssdk.testutils.Waiter;
public class CreateBucketIntegrationTest extends S3IntegrationTestBase {
private static final String BUCKET_NAME = temporaryBucketName("java-create-bucket-integ-test");
private static final String US_EAST_1_BUCKET_NAME = temporaryBucketName("java-create-bucket-integ-test");
private static final S3Client US_EAST_1_CLIENT = S3Client.builder()
.region(Region.US_EAST_1)
.credentialsProvider(CREDENTIALS_PROVIDER_CHAIN)
.build();
@AfterClass
public static void cleanup() {
deleteBucketAndAllContents(BUCKET_NAME);
S3TestUtils.deleteBucketAndAllContents(US_EAST_1_CLIENT, US_EAST_1_BUCKET_NAME);
US_EAST_1_CLIENT.close();
}
@Test
public void createBucket_InUsEast1_Succeeds() {
US_EAST_1_CLIENT.createBucket(CreateBucketRequest.builder().bucket(US_EAST_1_BUCKET_NAME).build());
String region = Waiter.run(() -> US_EAST_1_CLIENT.getBucketLocation(r -> r.bucket(US_EAST_1_BUCKET_NAME)))
.orFail()
.locationConstraintAsString();
assertThat(region).isEqualToIgnoringCase("");
}
@Test
public void createBucket_Succeeds_WithoutSpecifyingBucketLocation() {
S3Client client = S3Client.builder().region(Region.US_WEST_2).credentialsProvider(CREDENTIALS_PROVIDER_CHAIN).build();
client.createBucket(CreateBucketRequest.builder().bucket(BUCKET_NAME).build());
String region = Waiter.run(() -> client.getBucketLocation(r -> r.bucket(BUCKET_NAME)))
.orFail()
.locationConstraintAsString();
assertThat(region).isEqualToIgnoringCase("us-west-2");
}
@Test(expected = IllegalArgumentException.class)
public void createBucket_ThrowsIllegalArgumentException_WhenBucketNameIsLessThan3Characters() {
s3.createBucket(CreateBucketRequest.builder().bucket("s3").build());
}
@Test(expected = IllegalArgumentException.class)
public void createBucket_ThrowsIllegalArgumentException_WhenBucketNameIsGreaterThan63Characters() {
s3.createBucket(CreateBucketRequest.builder()
.bucket("wajb5vwtlkhx4ow1t9e6l39rdy7amxxyttryfdw4y4nwomxervpti82lphi5plm8")
.build());
}
@Test(expected = IllegalArgumentException.class)
public void createBucket_ThrowsIllegalArgumentException_WhenBucketNameIsIpAddress() {
s3.createBucket(CreateBucketRequest.builder()
.bucket("127.0.0.1")
.build());
}
@Test(expected = IllegalArgumentException.class)
public void createBucket_ThrowsIllegalArgumentException_WhenBucketNameContainsUpperCaseCharacters() {
s3.createBucket(CreateBucketRequest.builder()
.bucket("UPPERCASE")
.build());
}
@Test(expected = IllegalArgumentException.class)
public void createBucket_ThrowsIllegalArgumentException_WhenBucketNameContainsWhiteSpace() {
s3.createBucket(CreateBucketRequest.builder()
.bucket("white space")
.build());
}
@Test(expected = IllegalArgumentException.class)
public void createBucket_ThrowsIllegalArgumentException_WhenBucketNameBeginsWithPeriod() {
s3.createBucket(CreateBucketRequest.builder()
.bucket(".period")
.build());
}
@Test(expected = IllegalArgumentException.class)
public void createBucket_ThrowsIllegalArgumentException_WhenBucketNameContainsAdjacentPeriods() {
s3.createBucket(CreateBucketRequest.builder()
.bucket("..period")
.build());
}
@Test(expected = IllegalArgumentException.class)
public void createBucket_ThrowsIllegalArgumentException_WhenBucketNameBeginsWithADash() {
s3.createBucket(CreateBucketRequest.builder()
.bucket("-dash")
.build());
}
@Test(expected = IllegalArgumentException.class)
public void createBucket_ThrowsIllegalArgumentException_WhenBucketNameHasDashAdjacentAPeriod() {
s3.createBucket(CreateBucketRequest.builder()
.bucket("-.dashperiod")
.build());
}
}
| 4,500 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/it/java/software/amazon/awssdk/services | Create_ds/aws-sdk-java-v2/services/s3/src/it/java/software/amazon/awssdk/services/s3/S3ListObjectsV2IntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.s3;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.Matchers.isEmptyString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static software.amazon.awssdk.testutils.service.S3BucketUtils.temporaryBucketName;
import java.io.File;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.s3.model.ListObjectsV2Request;
import software.amazon.awssdk.services.s3.model.ListObjectsV2Response;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.S3Object;
import software.amazon.awssdk.testutils.RandomTempFile;
/**
* Integration tests for the listObjectsV2 operation in the Amazon S3 Java
* client.
*/
public class S3ListObjectsV2IntegrationTest extends S3IntegrationTestBase {
/**
* One hour in milliseconds for verifying that a last modified date is recent.
*/
private static final long ONE_HOUR_IN_MILLISECONDS = 1000 * 60 * 60;
/**
* Content length for sample keys created by these tests.
*/
private static final long CONTENT_LENGTH = 123;
private static final String KEY_NAME_WITH_SPECIAL_CHARS = "special-chars-@$%";
private static final int BUCKET_OBJECTS = 15;
/**
* The name of the bucket created, used, and deleted by these tests.
*/
private static String bucketName = temporaryBucketName("list-objects-integ-test");
/**
* List of all keys created by these tests.
*/
private static List<String> keys = new ArrayList<>();
/**
* Releases all resources created in this test.
*/
@AfterClass
public static void tearDown() {
deleteBucketAndAllContents(bucketName);
}
/**
* Creates all the test resources for the tests.
*/
@BeforeClass
public static void createResources() throws Exception {
createBucket(bucketName);
NumberFormat numberFormatter = new DecimalFormat("##00");
for (int i = 1; i <= BUCKET_OBJECTS; i++) {
createKey("key-" + numberFormatter.format(i));
}
createKey("aaaaa");
createKey("aaaaa/aaaaa/aaaaa");
createKey("aaaaa/aaaaa+a");
createKey("aaaaa/aaaaa//aaaaa");
createKey(KEY_NAME_WITH_SPECIAL_CHARS);
}
/**
* Creates a test object in S3 with the specified name, using random ASCII
* data of the default content length as defined in this test class.
*
* @param key The key under which to create the object in this test class'
* test bucket.
*/
private static void createKey(String key) throws Exception {
File file = new RandomTempFile("list-objects-integ-test-" + new Date().getTime(), CONTENT_LENGTH);
s3.putObject(PutObjectRequest.builder()
.bucket(bucketName)
.key(key)
.build(),
RequestBody.fromFile(file));
keys.add(key);
}
/*
* Individual Tests
*/
@Test
public void testListNoParameters() {
ListObjectsV2Response result = s3.listObjectsV2(ListObjectsV2Request.builder().bucket(bucketName).build());
List<S3Object> objects = result.contents();
assertEquals(keys.size(), objects.size());
assertThat(keys.size(), equalTo(result.keyCount()));
assertEquals(bucketName, result.name());
assertS3ObjectSummariesAreValid(objects, false);
assertNotNull(result.maxKeys());
// We didn't use a delimiter, so we expect these to be empty/null
assertNull(result.delimiter());
// We don't expect any truncated results
assertFalse(result.isTruncated());
assertNull(result.nextContinuationToken());
// We didn't set other request parameters, so we expect them to be empty
assertNull(result.encodingType());
assertThat(result.prefix(), equalTo(""));
assertNull(result.continuationToken());
}
@Test
public void testListWithPrefixAndStartAfter() {
String prefix = "key";
String startAfter = "key-01";
ListObjectsV2Response result = s3.listObjectsV2(ListObjectsV2Request.builder()
.bucket(bucketName)
.prefix(prefix)
.startAfter(startAfter)
.build());
List<S3Object> objects = result.contents();
assertEquals(BUCKET_OBJECTS - 1, objects.size());
assertEquals(bucketName, result.name());
assertS3ObjectSummariesAreValid(objects, false);
assertEquals(startAfter, result.startAfter());
assertEquals(prefix, result.prefix());
// We didn't use a delimiter, so we expect it to be empty/null
assertNull(result.delimiter());
// We don't expect any truncated results
assertFalse(result.isTruncated());
assertNull(result.nextContinuationToken());
// We didn't set any other request parameters, so we expect them to be
// set to the defaults.
assertTrue(result.maxKeys() >= 1000);
assertNull(result.encodingType());
}
@Test
public void testListWithPrefixAndDelimiter() {
String prefix = "a";
String delimiter = "/";
ListObjectsV2Response result = s3.listObjectsV2(ListObjectsV2Request.builder()
.bucket(bucketName)
.prefix(prefix)
.delimiter(delimiter)
.build());
List<S3Object> objects = result.contents();
assertEquals(1, objects.size());
assertEquals(bucketName, result.name());
assertS3ObjectSummariesAreValid(objects, false);
assertEquals(prefix, result.prefix());
assertEquals(delimiter, result.delimiter());
// We don't expect any truncated results
assertFalse(result.isTruncated());
assertNull(result.nextContinuationToken());
// We didn't set other request parameters, so we expect them to be empty
assertNull(result.startAfter());
assertNull(result.encodingType());
assertTrue(result.maxKeys() >= 1000);
}
@Test
public void testListWithMaxKeys() {
int maxKeys = 4;
ListObjectsV2Response result = s3.listObjectsV2(ListObjectsV2Request.builder()
.bucket(bucketName)
.maxKeys(maxKeys)
.build());
List<S3Object> objects = result.contents();
assertEquals(maxKeys, objects.size());
assertEquals(bucketName, result.name());
assertThat(maxKeys, equalTo(result.maxKeys()));
assertS3ObjectSummariesAreValid(objects, false);
// We didn't use a delimiter, so we expect this to be empty/null
assertNull(result.delimiter());
// We expect truncated results since we set maxKeys
assertTrue(result.isTruncated());
assertNotNull(result.nextContinuationToken());
assertTrue(result.nextContinuationToken().length() > 1);
// URL encoding is requested by default
// We didn't set other request parameters, so we expect them to be empty
assertNull(result.encodingType());
assertThat(result.prefix(), isEmptyString());
assertNull(result.startAfter());
assertNull(result.delimiter());
}
@Test
public void testListWithEncodingType() {
String encodingType = "url";
ListObjectsV2Response result = s3.listObjectsV2(ListObjectsV2Request.builder()
.bucket(bucketName)
.prefix(KEY_NAME_WITH_SPECIAL_CHARS)
.encodingType(encodingType)
.build());
List<S3Object> objects = result.contents();
// EncodingType should be returned in the response.
assertEquals(encodingType, result.encodingTypeAsString());
System.out.println(result.contents().get(0).key());
// The key name returned in the response should have been decoded
// from the URL encoded form S3 returned us.
assertEquals(KEY_NAME_WITH_SPECIAL_CHARS,
objects.get(0).key());
}
@Test
public void testListWithFetchOwner() {
ListObjectsV2Response result = s3.listObjectsV2(ListObjectsV2Request.builder()
.bucket(bucketName)
.fetchOwner(true)
.build());
List<S3Object> objects = result.contents();
assertS3ObjectSummariesAreValid(objects, true);
}
/*
* Private Test Utilities
*/
@Test
public void testListPagination() {
int firstRequestMaxKeys = 4;
String prefix = "key";
ListObjectsV2Response result = s3.listObjectsV2(ListObjectsV2Request.builder()
.bucket(bucketName)
.prefix(prefix)
.maxKeys(firstRequestMaxKeys)
.build());
List<S3Object> objects = result.contents();
assertEquals(firstRequestMaxKeys, objects.size());
assertEquals(bucketName, result.name());
assertEquals(prefix, result.prefix());
assertNotNull(result.nextContinuationToken());
assertTrue(result.isTruncated());
assertS3ObjectSummariesAreValid(objects, false);
for (int i = 0; i < firstRequestMaxKeys; i++) {
assertEquals(keys.get(i), objects.get(i).key());
}
ListObjectsV2Response nextResults = s3.listObjectsV2(ListObjectsV2Request.builder()
.bucket(bucketName)
.prefix(prefix)
.continuationToken(
result.nextContinuationToken())
.build());
List<S3Object> nextObjects = nextResults.contents();
assertNull(nextResults.nextContinuationToken());
assertEquals(nextResults.continuationToken(), result.nextContinuationToken());
assertFalse(nextResults.isTruncated());
assertEquals(prefix, nextResults.prefix());
assertS3ObjectSummariesAreValid(nextObjects, false);
assertEquals(nextObjects.size(), BUCKET_OBJECTS - firstRequestMaxKeys);
}
/**
* Asserts that a list of S3Object objects are valid, by checking
* that expected fields are not null or empty, that ETag values don't
* contain leading or trailing quotes, that the last modified date is
* recent, etc.
*
* @param objectSummaries The list of objects to validate.
* @param shouldIncludeOwner Whether owner information was requested and should be present in results.
*/
private void assertS3ObjectSummariesAreValid(List<S3Object> objectSummaries,
boolean shouldIncludeOwner) {
for (java.util.Iterator iterator = objectSummaries.iterator(); iterator.hasNext(); ) {
S3Object obj = (S3Object) iterator.next();
assertTrue(obj.eTag().length() > 1);
assertTrue(obj.key().length() > 1);
// Verify that the last modified date is within an hour
assertNotNull(obj.lastModified());
long offset = obj.lastModified().toEpochMilli() - Instant.now().toEpochMilli();
assertTrue(offset < ONE_HOUR_IN_MILLISECONDS);
assertTrue(obj.storageClassAsString().length() > 1);
if (shouldIncludeOwner) {
assertNotNull(obj.owner());
assertTrue(obj.owner().displayName().length() > 1);
assertTrue(obj.owner().id().length() > 1);
}
}
}
}
| 4,501 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/it/java/software/amazon/awssdk/services | Create_ds/aws-sdk-java-v2/services/s3/src/it/java/software/amazon/awssdk/services/s3/BucketInventoryConfigurationIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.s3;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static software.amazon.awssdk.testutils.service.S3BucketUtils.temporaryBucketName;
import java.util.ArrayList;
import java.util.List;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.s3.model.DeleteBucketInventoryConfigurationRequest;
import software.amazon.awssdk.services.s3.model.GetBucketInventoryConfigurationRequest;
import software.amazon.awssdk.services.s3.model.InventoryConfiguration;
import software.amazon.awssdk.services.s3.model.InventoryDestination;
import software.amazon.awssdk.services.s3.model.InventoryFilter;
import software.amazon.awssdk.services.s3.model.InventoryFormat;
import software.amazon.awssdk.services.s3.model.InventoryFrequency;
import software.amazon.awssdk.services.s3.model.InventoryIncludedObjectVersions;
import software.amazon.awssdk.services.s3.model.InventoryOptionalField;
import software.amazon.awssdk.services.s3.model.InventoryS3BucketDestination;
import software.amazon.awssdk.services.s3.model.InventorySchedule;
import software.amazon.awssdk.services.s3.model.ListBucketInventoryConfigurationsRequest;
import software.amazon.awssdk.services.s3.model.PutBucketInventoryConfigurationRequest;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.testutils.RandomTempFile;
public class BucketInventoryConfigurationIntegrationTest extends S3IntegrationTestBase {
/**
* The bucket created and used by these tests.
*/
private static final String BUCKET_NAME = temporaryBucketName("java-bucket-inventory-integ-test");
private static final String BUCKET_ARN = "arn:aws:s3:::" + BUCKET_NAME;
/**
* The key used in these tests.
*/
private static final String KEY = "key";
@BeforeClass
public static void setUpFixture() throws Exception {
S3IntegrationTestBase.setUp();
createBucket(BUCKET_NAME);
s3.putObject(PutObjectRequest.builder()
.bucket(BUCKET_NAME)
.key(KEY)
.build(),
RequestBody.fromFile(new RandomTempFile("foo", 1024)));
}
@AfterClass
public static void tearDownFixture() {
deleteBucketAndAllContents(BUCKET_NAME);
}
@Test
public void testInventoryConfiguration_works_properly_with_setting_only_required_fields() throws Exception {
String configId = "id";
InventoryS3BucketDestination s3BucketDestination = InventoryS3BucketDestination.builder()
.bucket(BUCKET_ARN)
.format(InventoryFormat.CSV)
.build();
InventoryDestination destination = InventoryDestination.builder().s3BucketDestination(s3BucketDestination).build();
InventoryConfiguration config = InventoryConfiguration.builder()
.isEnabled(true)
.id(configId)
.destination(destination)
.includedObjectVersions(InventoryIncludedObjectVersions.ALL)
.schedule(InventorySchedule.builder()
.frequency(InventoryFrequency.DAILY)
.build())
.build();
s3.putBucketInventoryConfiguration(PutBucketInventoryConfigurationRequest.builder()
.bucket(BUCKET_NAME)
.inventoryConfiguration(config)
.id(configId)
.build());
config = s3.getBucketInventoryConfiguration(GetBucketInventoryConfigurationRequest.builder()
.bucket(BUCKET_NAME)
.id(configId)
.build())
.inventoryConfiguration();
assertEquals(configId, config.id());
assertTrue(config.isEnabled());
assertEquals(InventoryIncludedObjectVersions.ALL, config.includedObjectVersions());
assertEquals(InventoryFrequency.DAILY, config.schedule().frequency());
s3BucketDestination = config.destination().s3BucketDestination();
assertEquals(BUCKET_ARN, s3BucketDestination.bucket());
assertEquals(InventoryFormat.CSV, s3BucketDestination.format());
assertNull(s3BucketDestination.accountId());
assertNull(s3BucketDestination.prefix());
s3.deleteBucketInventoryConfiguration(DeleteBucketInventoryConfigurationRequest.builder()
.bucket(BUCKET_NAME)
.id(configId)
.build());
List<InventoryConfiguration> configurations = s3.listBucketInventoryConfigurations(
ListBucketInventoryConfigurationsRequest.builder()
.bucket(BUCKET_NAME)
.build())
.inventoryConfigurationList();
assertTrue(configurations.isEmpty());
}
@Test
public void testInventoryConfiguration_with_filter() throws Exception {
String configId = "id";
String prefix = "prefix";
String accountId = "test-account";
List<String> optionalFields = new ArrayList<String>() {
{
add(InventoryOptionalField.E_TAG.toString());
add(InventoryOptionalField.SIZE.toString());
}
};
InventoryS3BucketDestination s3BucketDestination = InventoryS3BucketDestination.builder()
.bucket(BUCKET_ARN)
.format(InventoryFormat.CSV)
.accountId(accountId)
.prefix(prefix)
.build();
InventoryDestination destination = InventoryDestination.builder().s3BucketDestination(s3BucketDestination).build();
InventoryConfiguration config = InventoryConfiguration.builder()
.isEnabled(true)
.id(configId)
.destination(destination)
.includedObjectVersions(InventoryIncludedObjectVersions.ALL)
.schedule(InventorySchedule.builder()
.frequency(InventoryFrequency.DAILY)
.build())
.filter(InventoryFilter.builder().prefix(prefix).build())
.optionalFieldsWithStrings(optionalFields)
.build();
s3.putBucketInventoryConfiguration(PutBucketInventoryConfigurationRequest.builder()
.bucket(BUCKET_NAME)
.inventoryConfiguration(config)
.id(configId)
.build());
config = s3.getBucketInventoryConfiguration(GetBucketInventoryConfigurationRequest.builder().bucket(BUCKET_NAME)
.id(configId)
.build())
.inventoryConfiguration();
assertEquals(configId, config.id());
assertTrue(config.isEnabled());
assertEquals(InventoryIncludedObjectVersions.ALL, config.includedObjectVersions());
assertEquals(InventoryFrequency.DAILY, config.schedule().frequency());
s3BucketDestination = config.destination().s3BucketDestination();
assertEquals(BUCKET_ARN, s3BucketDestination.bucket());
assertEquals(InventoryFormat.CSV, s3BucketDestination.format());
assertEquals(accountId, s3BucketDestination.accountId());
assertEquals(prefix, s3BucketDestination.prefix());
assertEquals(prefix, config.filter().prefix());
assertTrue(config.optionalFieldsAsStrings().containsAll(optionalFields));
s3.deleteBucketInventoryConfiguration(DeleteBucketInventoryConfigurationRequest.builder()
.bucket(BUCKET_NAME)
.id(configId)
.build());
}
}
| 4,502 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/it/java/software/amazon/awssdk/services | Create_ds/aws-sdk-java-v2/services/s3/src/it/java/software/amazon/awssdk/services/s3/CopySourceIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.s3;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static software.amazon.awssdk.testutils.service.S3BucketUtils.temporaryBucketName;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.s3.internal.handlers.CopySourceInterceptor;
import software.amazon.awssdk.services.s3.model.BucketVersioningStatus;
import software.amazon.awssdk.services.s3.model.CopyObjectRequest;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.PutObjectResponse;
/**
* Integration tests for the {@code sourceBucket}, {@code sourceKey}, and {@code sourceVersionId} parameters for
* {@link CopyObjectRequest}. Specifically, we ensure that users are able to seamlessly use the same input for both the
* {@link PutObjectRequest} key and the {@link CopyObjectRequest} source key (and not be required to manually URL encode the
* COPY source key). This also effectively tests for parity with the SDK v1 behavior.
*
* @see CopySourceInterceptor
*/
@RunWith(Parameterized.class)
public class CopySourceIntegrationTest extends S3IntegrationTestBase {
private static final String SOURCE_UNVERSIONED_BUCKET_NAME = temporaryBucketName("copy-source-integ-test-src");
private static final String SOURCE_VERSIONED_BUCKET_NAME = temporaryBucketName("copy-source-integ-test-versioned-src");
private static final String DESTINATION_BUCKET_NAME = temporaryBucketName("copy-source-integ-test-dest");
@BeforeClass
public static void initializeTestData() throws Exception {
createBucket(SOURCE_UNVERSIONED_BUCKET_NAME);
createBucket(SOURCE_VERSIONED_BUCKET_NAME);
s3.putBucketVersioning(r -> r
.bucket(SOURCE_VERSIONED_BUCKET_NAME)
.versioningConfiguration(v -> v.status(BucketVersioningStatus.ENABLED)));
createBucket(DESTINATION_BUCKET_NAME);
}
@AfterClass
public static void tearDown() {
deleteBucketAndAllContents(SOURCE_UNVERSIONED_BUCKET_NAME);
deleteBucketAndAllContents(SOURCE_VERSIONED_BUCKET_NAME);
deleteBucketAndAllContents(DESTINATION_BUCKET_NAME);
}
@Parameters
public static Collection<String> parameters() throws Exception {
return Arrays.asList(
"simpleKey",
"key/with/slashes",
"\uD83E\uDEA3",
"specialChars/ +!#$&'()*,:;=?@\"",
"%20"
);
}
private final String key;
public CopySourceIntegrationTest(String key) {
this.key = key;
}
@Test
public void copyObject_WithoutVersion_AcceptsSameKeyAsPut() throws Exception {
String originalContent = UUID.randomUUID().toString();
s3.putObject(PutObjectRequest.builder()
.bucket(SOURCE_UNVERSIONED_BUCKET_NAME)
.key(key)
.build(), RequestBody.fromString(originalContent, StandardCharsets.UTF_8));
s3.copyObject(CopyObjectRequest.builder()
.sourceBucket(SOURCE_UNVERSIONED_BUCKET_NAME)
.sourceKey(key)
.destinationBucket(DESTINATION_BUCKET_NAME)
.destinationKey(key)
.build());
String copiedContent = s3.getObjectAsBytes(GetObjectRequest.builder()
.bucket(DESTINATION_BUCKET_NAME)
.key(key)
.build()).asUtf8String();
assertThat(copiedContent, is(originalContent));
}
/**
* Test that we can correctly copy versioned source objects.
* <p>
* Motivated by: https://github.com/aws/aws-sdk-js/issues/727
*/
@Test
public void copyObject_WithVersion_AcceptsSameKeyAsPut() throws Exception {
Map<String, String> versionToContentMap = new HashMap<>();
int numVersionsToCreate = 3;
for (int i = 0; i < numVersionsToCreate; i++) {
String originalContent = UUID.randomUUID().toString();
PutObjectResponse response = s3.putObject(PutObjectRequest.builder()
.bucket(SOURCE_VERSIONED_BUCKET_NAME)
.key(key)
.build(),
RequestBody.fromString(originalContent, StandardCharsets.UTF_8));
versionToContentMap.put(response.versionId(), originalContent);
}
versionToContentMap.forEach((versionId, originalContent) -> {
s3.copyObject(CopyObjectRequest.builder()
.sourceBucket(SOURCE_VERSIONED_BUCKET_NAME)
.sourceKey(key)
.sourceVersionId(versionId)
.destinationBucket(DESTINATION_BUCKET_NAME)
.destinationKey(key)
.build());
String copiedContent = s3.getObjectAsBytes(GetObjectRequest.builder()
.bucket(DESTINATION_BUCKET_NAME)
.key(key)
.build()).asUtf8String();
assertThat(copiedContent, is(originalContent));
});
}
}
| 4,503 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/it/java/software/amazon/awssdk/services | Create_ds/aws-sdk-java-v2/services/s3/src/it/java/software/amazon/awssdk/services/s3/S3IntegrationTestBase.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.s3;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.BeforeClass;
import software.amazon.awssdk.core.ClientType;
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.crt.Log;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.model.BucketLocationConstraint;
import software.amazon.awssdk.services.s3.model.CreateBucketConfiguration;
import software.amazon.awssdk.services.s3.model.CreateBucketRequest;
import software.amazon.awssdk.services.s3.model.S3Exception;
import software.amazon.awssdk.services.s3.utils.S3TestUtils;
import software.amazon.awssdk.testutils.service.AwsTestBase;
/**
* Base class for S3 integration tests. Loads AWS credentials from a properties
* file and creates an S3 client for callers to use.
*/
public class S3IntegrationTestBase extends AwsTestBase {
protected static final Region DEFAULT_REGION = Region.US_WEST_2;
/**
* The S3 client for all tests to use.
*/
protected static S3Client s3;
protected static S3AsyncClient s3Async;
/**
* Loads the AWS account info for the integration tests and creates an S3
* client for tests to use.
*/
@BeforeClass
public static void setUp() throws Exception {
Log.initLoggingToStdout(Log.LogLevel.Warn);
s3 = s3ClientBuilder().build();
s3Async = s3AsyncClientBuilder().build();
}
protected static S3ClientBuilder s3ClientBuilder() {
return S3Client.builder()
.region(DEFAULT_REGION)
.credentialsProvider(CREDENTIALS_PROVIDER_CHAIN)
.overrideConfiguration(o -> o.addExecutionInterceptor(
new UserAgentVerifyingExecutionInterceptor("Apache", ClientType.SYNC)));
}
protected static S3AsyncClientBuilder s3AsyncClientBuilder() {
return S3AsyncClient.builder()
.region(DEFAULT_REGION)
.credentialsProvider(CREDENTIALS_PROVIDER_CHAIN)
.overrideConfiguration(o -> o.addExecutionInterceptor(
new UserAgentVerifyingExecutionInterceptor("NettyNio", ClientType.ASYNC)));
}
protected static S3CrtAsyncClientBuilder crtClientBuilder() {
return S3AsyncClient.crtBuilder()
.region(DEFAULT_REGION)
.credentialsProvider(CREDENTIALS_PROVIDER_CHAIN);
}
protected static void createBucket(String bucketName) {
createBucket(bucketName, 0);
}
private static void createBucket(String bucketName, int retryCount) {
try {
s3.createBucket(
CreateBucketRequest.builder()
.bucket(bucketName)
.createBucketConfiguration(
CreateBucketConfiguration.builder()
.locationConstraint(BucketLocationConstraint.US_WEST_2)
.build())
.build());
} catch (S3Exception e) {
System.err.println("Error attempting to create bucket: " + bucketName);
if (e.awsErrorDetails().errorCode().equals("BucketAlreadyOwnedByYou")) {
System.err.printf("%s bucket already exists, likely leaked by a previous run\n", bucketName);
} else if (e.awsErrorDetails().errorCode().equals("TooManyBuckets")) {
System.err.println("Printing all buckets for debug:");
s3.listBuckets().buckets().forEach(System.err::println);
if (retryCount < 2) {
System.err.println("Retrying...");
createBucket(bucketName, retryCount + 1);
} else {
throw e;
}
} else {
throw e;
}
}
s3.waiter().waitUntilBucketExists(r -> r.bucket(bucketName));
}
protected static void deleteBucketAndAllContents(String bucketName) {
S3TestUtils.deleteBucketAndAllContents(s3, bucketName);
}
protected static class UserAgentVerifyingExecutionInterceptor implements ExecutionInterceptor {
private final String clientName;
private final ClientType clientType;
public UserAgentVerifyingExecutionInterceptor(String clientName, ClientType clientType) {
this.clientName = clientName;
this.clientType = clientType;
}
@Override
public void beforeTransmission(Context.BeforeTransmission context, ExecutionAttributes executionAttributes) {
assertThat(context.httpRequest().firstMatchingHeader("User-Agent").get()).containsIgnoringCase("io/" + clientType.name());
assertThat(context.httpRequest().firstMatchingHeader("User-Agent").get()).containsIgnoringCase("http/" + clientName);
}
}
}
| 4,504 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/it/java/software/amazon/awssdk/services | Create_ds/aws-sdk-java-v2/services/s3/src/it/java/software/amazon/awssdk/services/s3/UploadMultiplePartIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.concurrent.Callable;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.s3.model.AbortMultipartUploadRequest;
import software.amazon.awssdk.services.s3.model.AbortMultipartUploadResponse;
import software.amazon.awssdk.services.s3.model.CompleteMultipartUploadRequest;
import software.amazon.awssdk.services.s3.model.CompleteMultipartUploadResponse;
import software.amazon.awssdk.services.s3.model.CreateMultipartUploadResponse;
import software.amazon.awssdk.services.s3.model.ListMultipartUploadsResponse;
import software.amazon.awssdk.services.s3.model.UploadPartRequest;
import software.amazon.awssdk.services.s3.model.UploadPartResponse;
public class UploadMultiplePartIntegrationTest extends UploadMultiplePartTestBase {
@Override
public Callable<CreateMultipartUploadResponse> createMultipartUpload(String bucket, String key) {
return () -> s3.createMultipartUpload(b -> b.bucket(bucket).key(key));
}
@Override
public Callable<UploadPartResponse> uploadPart(UploadPartRequest request, String requestBody) {
return () -> s3.uploadPart(request, RequestBody.fromString(requestBody));
}
@Override
public Callable<ListMultipartUploadsResponse> listMultipartUploads(String bucket) {
return () -> s3.listMultipartUploads(b -> b.bucket(bucket));
}
@Override
public Callable<CompleteMultipartUploadResponse> completeMultipartUpload(CompleteMultipartUploadRequest request) {
return () -> s3.completeMultipartUpload(request);
}
@Override
public Callable<AbortMultipartUploadResponse> abortMultipartUploadResponseCallable(AbortMultipartUploadRequest request) {
return () -> s3.abortMultipartUpload(request);
}
}
| 4,505 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/it/java/software/amazon/awssdk/services | Create_ds/aws-sdk-java-v2/services/s3/src/it/java/software/amazon/awssdk/services/s3/AsyncMissingUploadIdRequestIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.concurrent.Callable;
import java.util.concurrent.CompletionException;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.services.s3.model.AbortMultipartUploadRequest;
import software.amazon.awssdk.services.s3.model.AbortMultipartUploadResponse;
import software.amazon.awssdk.services.s3.model.CompleteMultipartUploadRequest;
import software.amazon.awssdk.services.s3.model.CompleteMultipartUploadResponse;
import software.amazon.awssdk.services.s3.model.CreateMultipartUploadResponse;
import software.amazon.awssdk.services.s3.model.ListMultipartUploadsResponse;
import software.amazon.awssdk.services.s3.model.ListPartsRequest;
import software.amazon.awssdk.services.s3.model.ListPartsResponse;
import software.amazon.awssdk.services.s3.model.UploadPartRequest;
import software.amazon.awssdk.services.s3.model.UploadPartResponse;
public class AsyncMissingUploadIdRequestIntegrationTest extends MissingUploadIdRequestTestBase {
@Override
public Callable<CreateMultipartUploadResponse> createMultipartUpload(String bucket, String key) {
return () -> s3Async.createMultipartUpload(b -> b.bucket(bucket).key(key)).join();
}
@Override
public Callable<UploadPartResponse> uploadPart(UploadPartRequest request, String requestBody) {
return () -> s3Async.uploadPart(request, AsyncRequestBody.fromString(requestBody)).join();
}
@Override
public Callable<ListMultipartUploadsResponse> listMultipartUploads(String bucket) {
return () -> s3Async.listMultipartUploads(b -> b.bucket(bucket)).join();
}
@Override
public Callable<ListPartsResponse> listParts(ListPartsRequest request) {
return () -> s3Async.listParts(request).join();
}
@Override
public Callable<CompleteMultipartUploadResponse> completeMultipartUpload(CompleteMultipartUploadRequest request) {
return () -> s3Async.completeMultipartUpload(request).join();
}
@Override
public Callable<AbortMultipartUploadResponse> abortMultipartUploadResponseCallable(AbortMultipartUploadRequest request) {
return () -> s3Async.abortMultipartUpload(request).join();
}
@Override
public Class<? extends Exception> expectedException() {
return CompletionException.class;
}
}
| 4,506 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/it/java/software/amazon/awssdk/services | Create_ds/aws-sdk-java-v2/services/s3/src/it/java/software/amazon/awssdk/services/s3/BucketAnalyticsConfigurationIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.s3;
import static junit.framework.TestCase.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static software.amazon.awssdk.testutils.service.S3BucketUtils.temporaryBucketName;
import java.util.List;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.s3.model.AnalyticsConfiguration;
import software.amazon.awssdk.services.s3.model.AnalyticsExportDestination;
import software.amazon.awssdk.services.s3.model.AnalyticsFilter;
import software.amazon.awssdk.services.s3.model.AnalyticsS3BucketDestination;
import software.amazon.awssdk.services.s3.model.AnalyticsS3ExportFileFormat;
import software.amazon.awssdk.services.s3.model.CreateBucketConfiguration;
import software.amazon.awssdk.services.s3.model.CreateBucketRequest;
import software.amazon.awssdk.services.s3.model.DeleteBucketAnalyticsConfigurationRequest;
import software.amazon.awssdk.services.s3.model.GetBucketAnalyticsConfigurationRequest;
import software.amazon.awssdk.services.s3.model.ListBucketAnalyticsConfigurationsRequest;
import software.amazon.awssdk.services.s3.model.ListBucketAnalyticsConfigurationsResponse;
import software.amazon.awssdk.services.s3.model.PutBucketAnalyticsConfigurationRequest;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.S3Exception;
import software.amazon.awssdk.services.s3.model.StorageClassAnalysis;
import software.amazon.awssdk.services.s3.model.StorageClassAnalysisDataExport;
import software.amazon.awssdk.services.s3.model.StorageClassAnalysisSchemaVersion;
import software.amazon.awssdk.services.s3.model.Tag;
import software.amazon.awssdk.testutils.RandomTempFile;
public class BucketAnalyticsConfigurationIntegrationTest extends S3IntegrationTestBase {
/**
* The bucket created and used by these tests.
*/
private static final String BUCKET_NAME = temporaryBucketName("java-bucket-analytics-integ-test");
private static final String BUCKET_ARN = "arn:aws:s3:::" + BUCKET_NAME;
/**
* The key used in these tests.
*/
private static final String KEY = "key";
@BeforeClass
public static void setUpFixture() throws Exception {
S3IntegrationTestBase.setUp();
s3.createBucket(CreateBucketRequest.builder()
.bucket(BUCKET_NAME)
.createBucketConfiguration(CreateBucketConfiguration.builder()
.locationConstraint("us-west-2")
.build())
.build());
s3.putObject(PutObjectRequest.builder()
.bucket(BUCKET_NAME)
.key(KEY)
.build(), RequestBody.fromFile(new RandomTempFile("foo", 1024)));
}
@AfterClass
public static void tearDownFixture() {
deleteBucketAndAllContents(BUCKET_NAME);
}
@Test
public void testAnalyticsConfiguration_works_properly_with_setting_only_required_fields() throws Exception {
String configId = "id";
AnalyticsConfiguration config = AnalyticsConfiguration.builder()
.id(configId)
.storageClassAnalysis(getStorageClassAnalysis())
.build();
s3.putBucketAnalyticsConfiguration(PutBucketAnalyticsConfigurationRequest.builder()
.bucket(BUCKET_NAME)
.analyticsConfiguration(config)
.id(configId)
.build());
AnalyticsConfiguration returnedConfig = s3
.getBucketAnalyticsConfiguration(GetBucketAnalyticsConfigurationRequest.builder()
.bucket(BUCKET_NAME)
.id(configId)
.build())
.analyticsConfiguration();
assertEquals(configId, returnedConfig.id());
assertNull(returnedConfig.filter());
assertEquals(StorageClassAnalysisSchemaVersion.V_1,
returnedConfig.storageClassAnalysis().dataExport().outputSchemaVersion());
AnalyticsS3BucketDestination s3BucketDestination =
returnedConfig.storageClassAnalysis().dataExport().destination().s3BucketDestination();
assertEquals(BUCKET_ARN, s3BucketDestination.bucket());
assertEquals(AnalyticsS3ExportFileFormat.CSV, s3BucketDestination.format());
assertNull(s3BucketDestination.bucketAccountId());
assertNull(s3BucketDestination.prefix());
}
@Test
public void testDeleteBucketAnalyticsConfiguration() throws Exception {
String configId = "id";
AnalyticsConfiguration config = AnalyticsConfiguration.builder()
.id(configId)
.storageClassAnalysis(getStorageClassAnalysis())
.build();
s3.putBucketAnalyticsConfiguration(PutBucketAnalyticsConfigurationRequest.builder()
.bucket(BUCKET_NAME)
.analyticsConfiguration(config)
.id(configId)
.build());
assertNotNull(s3.getBucketAnalyticsConfiguration(GetBucketAnalyticsConfigurationRequest.builder()
.bucket(BUCKET_NAME)
.id(configId)
.build())
.analyticsConfiguration());
s3.deleteBucketAnalyticsConfiguration(DeleteBucketAnalyticsConfigurationRequest.builder()
.bucket(BUCKET_NAME)
.id(configId)
.build());
ListBucketAnalyticsConfigurationsResponse result =
s3.listBucketAnalyticsConfigurations(ListBucketAnalyticsConfigurationsRequest.builder()
.bucket(BUCKET_NAME)
.build());
assertTrue(result.analyticsConfigurationList().isEmpty());
}
@Test
public void testListBucketAnalyticsConfiguration() throws Exception {
String configId = "id";
String configId2 = "id2";
AnalyticsConfiguration config = AnalyticsConfiguration.builder()
.id(configId)
.storageClassAnalysis(getStorageClassAnalysis())
.build();
AnalyticsConfiguration config2 = AnalyticsConfiguration.builder()
.id(configId2)
.storageClassAnalysis(getStorageClassAnalysis())
.build();
s3.putBucketAnalyticsConfiguration(PutBucketAnalyticsConfigurationRequest.builder()
.bucket(BUCKET_NAME)
.analyticsConfiguration(config)
.id(configId)
.build());
s3.putBucketAnalyticsConfiguration(PutBucketAnalyticsConfigurationRequest.builder()
.bucket(BUCKET_NAME)
.analyticsConfiguration(config2)
.id(configId2)
.build());
ListBucketAnalyticsConfigurationsResponse result = s3.listBucketAnalyticsConfigurations(
ListBucketAnalyticsConfigurationsRequest.builder().bucket(BUCKET_NAME).build());
List<AnalyticsConfiguration> analyticsConfigurationList = result.analyticsConfigurationList();
assertNull(result.continuationToken());
assertNull(result.nextContinuationToken());
assertFalse(result.isTruncated());
assertEquals(2, analyticsConfigurationList.size());
assertEquals(configId, analyticsConfigurationList.get(0).id());
assertEquals(configId2, analyticsConfigurationList.get(1).id());
s3.deleteBucketAnalyticsConfiguration(DeleteBucketAnalyticsConfigurationRequest.builder()
.bucket(BUCKET_NAME)
.id(configId)
.build());
s3.deleteBucketAnalyticsConfiguration(DeleteBucketAnalyticsConfigurationRequest.builder()
.bucket(BUCKET_NAME)
.id(configId2)
.build());
}
@Test(expected = S3Exception.class)
public void testAnalyticsConfiguration_works_properly_with_emptyFilter() throws Exception {
String configId = "id";
AnalyticsConfiguration config = AnalyticsConfiguration.builder()
.id(configId)
.filter(AnalyticsFilter.builder()
.build())
.storageClassAnalysis(getStorageClassAnalysis())
.build();
s3.putBucketAnalyticsConfiguration(PutBucketAnalyticsConfigurationRequest.builder()
.bucket(BUCKET_NAME)
.analyticsConfiguration(config)
.id(configId)
.build());
}
@Test(expected = S3Exception.class)
public void testAnalyticsConfiguration_works_properly_with_emptyPrefix() throws Exception {
String configId = "id";
AnalyticsConfiguration config = AnalyticsConfiguration.builder()
.id(configId)
.filter(AnalyticsFilter.builder()
.prefix("")
.build())
.storageClassAnalysis(getStorageClassAnalysis())
.build();
s3.putBucketAnalyticsConfiguration(PutBucketAnalyticsConfigurationRequest.builder()
.bucket(BUCKET_NAME)
.analyticsConfiguration(config)
.id(configId)
.build());
}
@Test
public void testAnalyticsConfiguration_works_properly_with_onlyTag() throws Exception {
String configId = "id";
AnalyticsConfiguration config = AnalyticsConfiguration.builder()
.id(configId)
.filter(AnalyticsFilter.builder()
.tag(Tag.builder()
.key("key")
.value("value")
.build())
.build())
.storageClassAnalysis(getStorageClassAnalysis())
.build();
s3.putBucketAnalyticsConfiguration(PutBucketAnalyticsConfigurationRequest.builder()
.bucket(BUCKET_NAME)
.analyticsConfiguration(config)
.id(configId)
.build());
config = s3.getBucketAnalyticsConfiguration(GetBucketAnalyticsConfigurationRequest.builder()
.bucket(BUCKET_NAME)
.id(configId)
.build())
.analyticsConfiguration();
assertEquals(configId, config.id());
assertEquals("key", config.filter().tag().key());
assertEquals("value", config.filter().tag().value());
assertEquals(StorageClassAnalysisSchemaVersion.V_1,
config.storageClassAnalysis().dataExport().outputSchemaVersion());
AnalyticsS3BucketDestination s3BucketDestination = config.storageClassAnalysis().dataExport().destination()
.s3BucketDestination();
assertEquals(BUCKET_ARN, s3BucketDestination.bucket());
assertEquals(AnalyticsS3ExportFileFormat.CSV, s3BucketDestination.format());
assertNull(s3BucketDestination.bucketAccountId());
assertNull(s3BucketDestination.prefix());
}
@Test(expected = SdkClientException.class)
public void setBucketAnalyticsConfiguration_fails_when_requiredfield_is_missing() throws Exception {
String configId = "id";
StorageClassAnalysisDataExport dataExport = StorageClassAnalysisDataExport.builder()
.outputSchemaVersion(
StorageClassAnalysisSchemaVersion.V_1)
.destination(
AnalyticsExportDestination.builder()
.build())
.build();
AnalyticsConfiguration config = AnalyticsConfiguration.builder()
.id(configId)
.storageClassAnalysis(StorageClassAnalysis.builder()
.dataExport(dataExport)
.build())
.build();
s3.putBucketAnalyticsConfiguration(PutBucketAnalyticsConfigurationRequest.builder()
.bucket(BUCKET_NAME)
.analyticsConfiguration(config)
.id(configId)
.build());
}
private StorageClassAnalysis getStorageClassAnalysis() {
AnalyticsS3BucketDestination s3BucketDestination = AnalyticsS3BucketDestination.builder()
.bucket(BUCKET_ARN)
.format(AnalyticsS3ExportFileFormat.CSV)
.build();
return StorageClassAnalysis.builder()
.dataExport(StorageClassAnalysisDataExport.builder()
.outputSchemaVersion(
StorageClassAnalysisSchemaVersion.V_1)
.destination(AnalyticsExportDestination.builder()
.s3BucketDestination(
s3BucketDestination)
.build())
.build())
.build();
}
}
| 4,507 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/it/java/software/amazon/awssdk/services | Create_ds/aws-sdk-java-v2/services/s3/src/it/java/software/amazon/awssdk/services/s3/ObjectTaggingIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.s3;
import static org.assertj.core.api.Assertions.assertThat;
import static software.amazon.awssdk.testutils.service.S3BucketUtils.temporaryBucketName;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.s3.model.BucketVersioningStatus;
import software.amazon.awssdk.services.s3.model.CompletedMultipartUpload;
import software.amazon.awssdk.services.s3.model.CopyObjectRequest;
import software.amazon.awssdk.services.s3.model.DeleteObjectTaggingRequest;
import software.amazon.awssdk.services.s3.model.GetObjectTaggingRequest;
import software.amazon.awssdk.services.s3.model.GetObjectTaggingResponse;
import software.amazon.awssdk.services.s3.model.PutBucketVersioningRequest;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.Tag;
import software.amazon.awssdk.services.s3.model.Tagging;
import software.amazon.awssdk.services.s3.model.UploadPartResponse;
import software.amazon.awssdk.services.s3.model.VersioningConfiguration;
/**
* Integration tests for object tagging support.
*/
public class ObjectTaggingIntegrationTest extends S3IntegrationTestBase {
private static final String KEY_PREFIX = "tagged-object-";
private static final String BUCKET = temporaryBucketName("java-object-tagging-bucket-");
@BeforeClass
public static void setUp() throws Exception {
S3IntegrationTestBase.setUp();
createBucket(BUCKET);
s3.putBucketVersioning(PutBucketVersioningRequest.builder()
.bucket(BUCKET)
.versioningConfiguration(
VersioningConfiguration.builder()
.status(BucketVersioningStatus.ENABLED)
.build())
.build());
}
@AfterClass
public static void tearDown() {
deleteBucketAndAllContents(BUCKET);
}
@Test
public void putObject_WithTagging_Succeeds() {
Tagging tags = Tagging.builder()
.tagSet(Tag.builder()
.key("foo")
.value("1").build(), Tag.builder()
.key("bar")
.value("2").build(), Tag.builder()
.key("baz")
.value("3").build())
.build();
String key = makeNewKey();
s3.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(key)
.tagging(tags)
.build(),
RequestBody.empty());
GetObjectTaggingResponse response = s3.getObjectTagging(GetObjectTaggingRequest.builder()
.bucket(BUCKET)
.key(key)
.build());
assertThat(tags.tagSet().size()).isEqualTo(s3.getObjectTagging(GetObjectTaggingRequest.builder()
.bucket(BUCKET)
.key(key)
.build())
.tagSet().size());
}
@Test
public void getObjectTagging_Succeeds() {
List<Tag> tagSet = tags();
Tagging tags = Tagging.builder().tagSet(tagSet).build();
String key = makeNewKey();
s3.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(key)
.tagging(tags)
.build(), RequestBody.empty());
List<Tag> getTaggingResult = s3.getObjectTagging(GetObjectTaggingRequest.builder()
.bucket(BUCKET)
.key(key)
.build())
.tagSet();
assertThat(getTaggingResult).containsExactlyInAnyOrder(tags.tagSet().toArray(new Tag[tags.tagSet().size()]));
}
@Test
public void putObjectTagging_Succeeds_WithUrlEncodedTags() {
List<Tag> tagSet = new ArrayList<>();
tagSet.add(Tag.builder().key("foo").value("bar @baz").build());
tagSet.add(Tag.builder().key("foo bar").value("baz").build());
tagSet.add(Tag.builder().key("foo/bar").value("baz").build());
Tagging tags = Tagging.builder().tagSet(tagSet).build();
String key = makeNewKey();
s3.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(key)
.tagging(tags)
.build(), RequestBody.empty());
List<Tag> getTaggingResult = s3.getObjectTagging(GetObjectTaggingRequest.builder()
.bucket(BUCKET)
.key(key)
.build())
.tagSet();
assertThat(getTaggingResult).containsExactlyInAnyOrder(tags.tagSet().toArray(new Tag[tags.tagSet().size()]));
}
@Test
public void copyObject_Succeeds_WithNewTags() {
List<Tag> tagSet = tags();
Tagging tags = Tagging.builder().tagSet(tagSet).build();
String key = makeNewKey();
s3.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(key)
.tagging(tags)
.build(), RequestBody.empty());
String destKey = makeNewKey();
List<Tag> tagSet2 = new ArrayList<>();
tagSet2.add(Tag.builder().key("foo1").value("1").build());
tagSet2.add(Tag.builder().key("bar2").value("2").build());
Tagging tagsCopy = Tagging.builder().tagSet(tagSet).build();
s3.copyObject(CopyObjectRequest.builder()
.copySource(BUCKET + "/" + key)
.bucket(BUCKET)
.key(destKey)
.tagging(tagsCopy)
.build());
List<Tag> getTaggingResult = s3.getObjectTagging(GetObjectTaggingRequest.builder()
.bucket(BUCKET)
.key(key)
.build())
.tagSet();
assertThat(getTaggingResult).containsExactlyInAnyOrder(tagsCopy.tagSet().toArray(new Tag[tagsCopy.tagSet().size()]));
}
private List<Tag> tags() {
List<Tag> tagSet = new ArrayList<>();
tagSet.add(Tag.builder().key("foo").value("1").build());
tagSet.add(Tag.builder().key("bar").value("2").build());
tagSet.add(Tag.builder().key("baz").value("3").build());
return tagSet;
}
@Test
public void multipartUploadWithNewTags_shouldSucceed() {
List<Tag> tagSet = tags();
Tagging tags = Tagging.builder().tagSet(tagSet).build();
String key = makeNewKey();
String uploadId =
s3.createMultipartUpload(b -> b.tagging(tags).bucket(BUCKET).key(key)).uploadId();
UploadPartResponse uploadPartResponse = s3.uploadPart(b -> b.bucket(BUCKET).key(key).partNumber(1).uploadId(uploadId),
RequestBody.fromString(RandomStringUtils.random(1000)));
CompletedMultipartUpload parts =
CompletedMultipartUpload.builder().parts(p -> p.partNumber(1).eTag(uploadPartResponse.eTag()).build()).build();
s3.completeMultipartUpload(b -> b.bucket(BUCKET).key(key).multipartUpload(parts).uploadId(uploadId).build());
List<Tag> getTaggingResult = s3.getObjectTagging(GetObjectTaggingRequest.builder()
.bucket(BUCKET)
.key(key)
.build())
.tagSet();
assertThat(getTaggingResult).containsExactlyInAnyOrder(tags.tagSet().toArray(new Tag[0]));
}
@Test
public void testDeleteObjectTagging() {
List<Tag> tagSet = tags();
Tagging tags = Tagging.builder().tagSet(tagSet).build();
String key = makeNewKey();
s3.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(key)
.tagging(tags)
.build(), RequestBody.empty());
s3.deleteObjectTagging(DeleteObjectTaggingRequest.builder().bucket(BUCKET).key(key).build());
List<Tag> getTaggingResult = s3.getObjectTagging(GetObjectTaggingRequest.builder()
.bucket(BUCKET)
.key(key)
.build())
.tagSet();
assertThat(getTaggingResult.size()).isEqualTo(0);
}
@Test
public void testEmptyTagging_shouldNotThrowException() {
Tagging tags = Tagging.builder().build();
String key = makeNewKey();
s3.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(key)
.tagging(tags)
.build(), RequestBody.empty());
List<Tag> getTaggingResult = s3.getObjectTagging(GetObjectTaggingRequest.builder()
.bucket(BUCKET)
.key(key)
.build())
.tagSet();
assertThat(getTaggingResult.size()).isEqualTo(0);
}
private String makeNewKey() {
return KEY_PREFIX + System.currentTimeMillis();
}
}
| 4,508 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/it/java/software/amazon/awssdk/services | Create_ds/aws-sdk-java-v2/services/s3/src/it/java/software/amazon/awssdk/services/s3/UploadMultiplePartTestBase.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.s3;
import static org.assertj.core.api.Assertions.assertThat;
import static software.amazon.awssdk.testutils.service.S3BucketUtils.temporaryBucketName;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import software.amazon.awssdk.core.ResponseBytes;
import software.amazon.awssdk.core.sync.ResponseTransformer;
import software.amazon.awssdk.services.s3.model.AbortMultipartUploadRequest;
import software.amazon.awssdk.services.s3.model.AbortMultipartUploadResponse;
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.CreateMultipartUploadResponse;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.services.s3.model.ListMultipartUploadsResponse;
import software.amazon.awssdk.services.s3.model.MultipartUpload;
import software.amazon.awssdk.services.s3.model.UploadPartRequest;
import software.amazon.awssdk.services.s3.model.UploadPartResponse;
/**
* Base classes to test S3Client and S3AsyncClient upload multiple part functions.
*/
public abstract class UploadMultiplePartTestBase extends S3IntegrationTestBase {
private static final String BUCKET = temporaryBucketName(AsyncUploadMultiplePartIntegrationTest.class);
private static final String CONTENT = RandomStringUtils.randomAscii(1000);
@BeforeClass
public static void setupFixture() {
createBucket(BUCKET);
}
@AfterClass
public static void tearDownFixture() {
deleteBucketAndAllContents(BUCKET);
}
@Test
public void uploadMultiplePart_complete() throws Exception {
String key = "uploadMultiplePart_complete";
// 1. Initiate multipartUpload request
String uploadId = initiateMultipartUpload(key);
int partCount = 1;
List<String> contentsToUpload = new ArrayList<>();
// 2. Upload each part
List<UploadPartResponse> uploadPartResponses = uploadParts(key, uploadId, partCount, contentsToUpload);
List<CompletedPart> completedParts = new ArrayList<>();
for (int i = 0; i < uploadPartResponses.size(); i++) {
int partNumber = i + 1;
UploadPartResponse response = uploadPartResponses.get(i);
completedParts.add(CompletedPart.builder().eTag(response.eTag()).partNumber(partNumber).build());
}
// 3. Complete multipart upload
CompleteMultipartUploadResponse completeMultipartUploadResponse =
completeMultipartUpload(CompleteMultipartUploadRequest.builder().bucket(BUCKET)
.key(key)
.uploadId(uploadId)
.multipartUpload(CompletedMultipartUpload.builder()
.parts(completedParts)
.build()).build()).call();
assertThat(completeMultipartUploadResponse).isNotNull();
verifyMultipartUploadResult(key, contentsToUpload);
}
@Test
public void uploadMultiplePart_abort() throws Exception {
String key = "uploadMultiplePart_abort";
// 1. Initiate multipartUpload request
String uploadId = initiateMultipartUpload(key);
int partCount = 3;
// 2. Upload each part
List<String> contentsToUpload = new ArrayList<>();
List<UploadPartResponse> uploadPartResponses = uploadParts(key, uploadId, partCount, contentsToUpload);
// 3. abort the multipart upload
AbortMultipartUploadResponse abortMultipartUploadResponse =
abortMultipartUploadResponseCallable(AbortMultipartUploadRequest.builder().bucket(BUCKET).key(key).uploadId(uploadId).build()).call();
// Verify no in-progress multipart uploads
ListMultipartUploadsResponse listMultipartUploadsResponse = listMultipartUploads(BUCKET).call();
List<MultipartUpload> uploads = listMultipartUploadsResponse.uploads();
assertThat(uploads).isEmpty();
}
private void verifyMultipartUploadResult(String key, List<String> contentsToUpload) throws Exception {
ResponseBytes<GetObjectResponse> objectAsBytes = s3.getObject(b -> b.bucket(BUCKET).key(key),
ResponseTransformer.toBytes());
String appendedString = String.join("", contentsToUpload);
assertThat(objectAsBytes.asUtf8String()).isEqualTo(appendedString);
}
private List<UploadPartResponse> uploadParts(String key, String uploadId, int partCount, List<String> contentsToUpload) throws Exception {
List<UploadPartResponse> uploadPartResponses = new ArrayList<>();
for (int i = 0; i < partCount; i++) {
int partNumber = i + 1;
contentsToUpload.add(CONTENT);
UploadPartRequest uploadPartRequest = UploadPartRequest.builder().bucket(BUCKET).key(key)
.uploadId(uploadId)
.partNumber(partNumber)
.build();
uploadPartResponses.add(uploadPart(uploadPartRequest, CONTENT).call());
}
return uploadPartResponses;
}
private String initiateMultipartUpload(String key) throws Exception {
return createMultipartUpload(BUCKET, key).call().uploadId();
}
public abstract Callable<CreateMultipartUploadResponse> createMultipartUpload(String bucket, String key);
public abstract Callable<UploadPartResponse> uploadPart(UploadPartRequest request, String requestBody);
public abstract Callable<ListMultipartUploadsResponse> listMultipartUploads(String bucket);
public abstract Callable<CompleteMultipartUploadResponse> completeMultipartUpload(CompleteMultipartUploadRequest request);
public abstract Callable<AbortMultipartUploadResponse> abortMultipartUploadResponseCallable(AbortMultipartUploadRequest request);
}
| 4,509 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/it/java/software/amazon/awssdk/services | Create_ds/aws-sdk-java-v2/services/s3/src/it/java/software/amazon/awssdk/services/s3/ListObjectsIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.s3;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static software.amazon.awssdk.testutils.service.S3BucketUtils.temporaryBucketName;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.s3.model.EncodingType;
import software.amazon.awssdk.services.s3.model.ListObjectsRequest;
import software.amazon.awssdk.services.s3.model.ListObjectsResponse;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.S3Object;
/**
* Integration tests for the listObjects operation in the Amazon S3 Java
* client.
*/
public class ListObjectsIntegrationTest extends S3IntegrationTestBase {
/**
* One hour in milliseconds for verifying that a last modified date is recent.
*/
private static final long ONE_HOUR_IN_MILLISECONDS = 1000 * 60 * 60;
private static final String KEY_NAME_WITH_SPECIAL_CHARS = "special-chars-@$%";
private static final int BUCKET_OBJECTS = 15;
/**
* The name of the bucket created, used, and deleted by these tests.
*/
private static String bucketName = temporaryBucketName("list-objects-integ-test");
/**
* List of all keys created by these tests.
*/
private static List<String> keys = new ArrayList<>();
/**
* Releases all resources created in this test.
*/
@AfterClass
public static void tearDown() {
deleteBucketAndAllContents(bucketName);
}
/**
* Creates all the test resources for the tests.
*/
@BeforeClass
public static void createResources() throws Exception {
createBucket(bucketName);
NumberFormat numberFormatter = new DecimalFormat("##00");
for (int i = 1; i <= BUCKET_OBJECTS; i++) {
createKey("key-" + numberFormatter.format(i));
}
createKey("aaaaa");
createKey("aaaaa/aaaaa/aaaaa");
createKey("aaaaa/aaaaa+a");
createKey("aaaaa/aaaaa//aaaaa");
createKey(KEY_NAME_WITH_SPECIAL_CHARS);
}
private static void createKey(String key) {
s3.putObject(PutObjectRequest.builder()
.bucket(bucketName)
.key(key)
.build(),
RequestBody.fromString(RandomStringUtils.random(1000)));
keys.add(key);
}
@Test
public void listObjectsNoParameters() {
ListObjectsResponse result = s3.listObjects(ListObjectsRequest.builder().bucket(bucketName).build());
List<S3Object> objects = result.contents();
assertEquals(keys.size(), objects.size());
assertEquals(bucketName, result.name());
assertS3ObjectSummariesAreValid(objects);
assertNotNull(result.maxKeys());
// We didn't use a delimiter, so we expect these to be empty/null
assertNull(result.delimiter());
// We don't expect any truncated results
assertFalse(result.isTruncated());
// We didn't set other request parameters, so we expect them to be empty
assertNull(result.encodingType());
assertThat(result.prefix()).isEmpty();
}
@Test
public void listObjectsWithAllElements() {
String delimiter = "/";
String marker = "aaa";
ListObjectsResponse result = s3.listObjects(ListObjectsRequest.builder()
.bucket(bucketName)
.prefix(KEY_NAME_WITH_SPECIAL_CHARS)
.marker(marker)
.encodingType(EncodingType.URL)
.delimiter(delimiter)
.build());
List<S3Object> objects = result.contents();
assertEquals(bucketName, result.name());
assertS3ObjectSummariesAreValid(objects);
assertEquals(marker, result.marker());
assertEquals(delimiter, result.delimiter());
assertEquals(KEY_NAME_WITH_SPECIAL_CHARS, result.prefix());
assertFalse(result.isTruncated());
assertTrue(result.maxKeys() >= 1000);
}
@Test
public void listObjectsWithMaxKeys() {
int maxKeys = 4;
ListObjectsResponse result = s3.listObjects(ListObjectsRequest.builder()
.bucket(bucketName)
.maxKeys(maxKeys)
.build());
List<S3Object> objects = result.contents();
assertEquals(maxKeys, objects.size());
assertEquals(bucketName, result.name());
assertThat(maxKeys).isEqualTo(result.maxKeys());
assertS3ObjectSummariesAreValid(objects);
// We didn't use a delimiter, so we expect this to be empty/null
assertNull(result.delimiter());
// We expect truncated results since we set maxKeys
assertTrue(result.isTruncated());
// URL encoding is requested by default
// We didn't set other request parameters, so we expect them to be empty
assertNull(result.encodingType());
assertThat(result.prefix()).isEmpty();
assertNull(result.delimiter());
}
/**
* Asserts that a list of S3Object objects are valid, by checking
* that expected fields are not null or empty, that ETag values don't
* contain leading or trailing quotes, that the last modified date is
* recent, etc.
* @param objectSummaries The list of objects to validate.
*
*/
private void assertS3ObjectSummariesAreValid(List<S3Object> objectSummaries) {
for (S3Object obj : objectSummaries) {
assertTrue(obj.eTag().length() > 1);
assertTrue(obj.key().length() > 1);
// Verify that the last modified date is within an hour
assertNotNull(obj.lastModified());
long offset = obj.lastModified().toEpochMilli() - Instant.now().toEpochMilli();
assertTrue(offset < ONE_HOUR_IN_MILLISECONDS);
assertTrue(obj.storageClassAsString().length() > 1);
}
}
}
| 4,510 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/it/java/software/amazon/awssdk/services | Create_ds/aws-sdk-java-v2/services/s3/src/it/java/software/amazon/awssdk/services/s3/AsyncUploadMultiplePartIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.concurrent.Callable;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.services.s3.model.AbortMultipartUploadRequest;
import software.amazon.awssdk.services.s3.model.AbortMultipartUploadResponse;
import software.amazon.awssdk.services.s3.model.CompleteMultipartUploadRequest;
import software.amazon.awssdk.services.s3.model.CompleteMultipartUploadResponse;
import software.amazon.awssdk.services.s3.model.CreateMultipartUploadResponse;
import software.amazon.awssdk.services.s3.model.ListMultipartUploadsResponse;
import software.amazon.awssdk.services.s3.model.UploadPartRequest;
import software.amazon.awssdk.services.s3.model.UploadPartResponse;
public class AsyncUploadMultiplePartIntegrationTest extends UploadMultiplePartTestBase {
@Override
public Callable<CreateMultipartUploadResponse> createMultipartUpload(String bucket, String key) {
return () -> s3Async.createMultipartUpload(b -> b.bucket(bucket).key(key)).join();
}
@Override
public Callable<UploadPartResponse> uploadPart(UploadPartRequest request, String requestBody) {
return () -> s3Async.uploadPart(request, AsyncRequestBody.fromString(requestBody)).join();
}
@Override
public Callable<ListMultipartUploadsResponse> listMultipartUploads(String bucket) {
return () -> s3Async.listMultipartUploads(b -> b.bucket(bucket)).join();
}
@Override
public Callable<CompleteMultipartUploadResponse> completeMultipartUpload(CompleteMultipartUploadRequest request) {
return () -> s3Async.completeMultipartUpload(request).join();
}
@Override
public Callable<AbortMultipartUploadResponse> abortMultipartUploadResponseCallable(AbortMultipartUploadRequest request) {
return () -> s3Async.abortMultipartUpload(request).join();
}
}
| 4,511 |
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/signer/PayloadSigningIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.signer;
import static org.assertj.core.api.Assertions.assertThat;
import static software.amazon.awssdk.testutils.service.S3BucketUtils.temporaryBucketName;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
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;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.http.SdkHttpHeaders;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.S3IntegrationTestBase;
import software.amazon.awssdk.services.s3.utils.S3TestUtils;
/**
* This is an integration test to verify that payload signing for synchronous requests work as intended.
*/
public class PayloadSigningIntegrationTest extends S3IntegrationTestBase {
private static final String BUCKET = temporaryBucketName(PayloadSigningIntegrationTest.class);
private static final String KEY = "key";
private static final String SIGNED_PAYLOAD_HEADER_VALUE = "STREAMING-AWS4-HMAC-SHA256-PAYLOAD";
private static final String UNSIGNED_PAYLOAD_HEADER_VALUE = "UNSIGNED-PAYLOAD";
private static final CapturingInterceptor capturingInterceptor = new CapturingInterceptor();
@BeforeClass
public static void setup() throws Exception {
S3IntegrationTestBase.setUp();
createBucket(BUCKET);
}
@AfterClass
public static void teardown() {
S3TestUtils.deleteBucketAndAllContents(s3, BUCKET);
s3.close();
}
@Before
public void methodSetup() {
capturingInterceptor.reset();
}
@Test
public void standardSyncApacheHttpClient_unsignedPayload() {
S3Client syncClient = s3ClientBuilder()
.overrideConfiguration(o -> o.addExecutionInterceptor(capturingInterceptor))
.build();
assertThat(syncClient.putObject(b -> b.bucket(BUCKET).key(KEY),
RequestBody.fromBytes("helloworld".getBytes()))).isNotNull();
List<String> capturedSha256Values = getSha256Values();
assertThat(capturedSha256Values).containsExactly(UNSIGNED_PAYLOAD_HEADER_VALUE);
syncClient.close();
}
@Test
public void standardSyncApacheHttpClient_httpCauses_signedPayload() {
S3Client syncClient = s3ClientBuilder()
.endpointOverride(URI.create("http://s3.us-west-2.amazonaws.com"))
.overrideConfiguration(o -> o.addExecutionInterceptor(capturingInterceptor))
.build();
assertThat(syncClient.putObject(b -> b.bucket(BUCKET).key(KEY),
RequestBody.fromBytes("helloworld".getBytes()))).isNotNull();
List<String> capturedSha256Values = getSha256Values();
assertThat(capturedSha256Values).containsExactly(SIGNED_PAYLOAD_HEADER_VALUE);
syncClient.close();
}
@Test
public void standardSyncApacheHttpClient_manuallyEnabled_signedPayload() {
S3Client syncClient = s3ClientBuilder()
.overrideConfiguration(o -> o.addExecutionInterceptor(capturingInterceptor)
.addExecutionInterceptor(new PayloadSigningInterceptor()))
.build();
assertThat(syncClient.putObject(b -> b.bucket(BUCKET).key(KEY),
RequestBody.fromBytes("helloworld".getBytes()))).isNotNull();
List<String> capturedSha256Values = getSha256Values();
assertThat(capturedSha256Values).containsExactly(SIGNED_PAYLOAD_HEADER_VALUE);
syncClient.close();
}
private List<String> getSha256Values() {
return capturingInterceptor.capturedRequests().stream()
.map(SdkHttpHeaders::headers)
.map(m -> m.getOrDefault("x-amz-content-sha256", Collections.emptyList()))
.flatMap(Collection::stream).collect(Collectors.toList());
}
private static class CapturingInterceptor implements ExecutionInterceptor {
private final List<SdkHttpRequest> capturedRequests = new ArrayList<>();
@Override
public void beforeTransmission(Context.BeforeTransmission context, ExecutionAttributes executionAttributes) {
capturedRequests.add(context.httpRequest());
}
public void reset() {
capturedRequests.clear();
}
public List<SdkHttpRequest> capturedRequests() {
return capturedRequests;
}
}
private static class PayloadSigningInterceptor implements ExecutionInterceptor {
@Override
public Optional<RequestBody> modifyHttpContent(Context.ModifyHttpRequest context,
ExecutionAttributes executionAttributes) {
executionAttributes.putAttribute(S3SignerExecutionAttribute.ENABLE_PAYLOAD_SIGNING, true);
if (!context.requestBody().isPresent() && context.httpRequest().method().equals(SdkHttpMethod.POST)) {
return Optional.of(RequestBody.fromBytes(new byte[0]));
}
return context.requestBody();
}
}
}
| 4,512 |
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/signer/AwsS3V4SignerIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.signer;
import static org.junit.Assert.assertEquals;
import static software.amazon.awssdk.core.client.config.SdkAdvancedClientOption.SIGNER;
import static software.amazon.awssdk.testutils.service.S3BucketUtils.temporaryBucketName;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.IOUtils;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import software.amazon.awssdk.auth.credentials.AwsCredentials;
import software.amazon.awssdk.auth.signer.Aws4Signer;
import software.amazon.awssdk.auth.signer.AwsS3V4Signer;
import software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute;
import software.amazon.awssdk.auth.signer.params.Aws4PresignerParams;
import software.amazon.awssdk.auth.signer.params.AwsS3V4SignerParams;
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.http.HttpExecuteRequest;
import software.amazon.awssdk.http.HttpExecuteResponse;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.S3ClientBuilder;
import software.amazon.awssdk.services.s3.S3IntegrationTestBase;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.S3Exception;
import software.amazon.awssdk.utils.IoUtils;
public class AwsS3V4SignerIntegrationTest extends S3IntegrationTestBase {
private static final AwsCredentials awsCredentials = CREDENTIALS_PROVIDER_CHAIN.resolveCredentials();
private static final String SIGNING_NAME = "s3";
private static final String BUCKET_NAME = temporaryBucketName("s3-signer-integ-test");
private static final String KEY = "test-key";
private static final String CONTENT = "Hello world";
@BeforeClass
public static void setup() {
createBucket(BUCKET_NAME);
s3.putObject(PutObjectRequest.builder()
.bucket(BUCKET_NAME)
.key(KEY)
.build(),
RequestBody.fromString(CONTENT));
}
@AfterClass
public static void cleanUp() {
deleteBucketAndAllContents(BUCKET_NAME);
}
@Test
public void testGetObject() {
String response = s3.getObjectAsBytes(req -> req.bucket(BUCKET_NAME).key(KEY))
.asString(StandardCharsets.UTF_8);
assertEquals(CONTENT, response);
}
@Test (expected = S3Exception.class)
public void test_UsingSdkClient_WithIncorrectSigner_SetInConfig() {
S3Client customClient = getClientBuilder()
.overrideConfiguration(ClientOverrideConfiguration.builder()
.putAdvancedOption(SIGNER, Aws4Signer.create())
.build())
.build();
customClient.getObjectAsBytes(req -> req.bucket(BUCKET_NAME).key(KEY))
.asString(StandardCharsets.UTF_8);
}
@Test
public void test_UsingSdkClient_WithCorrectSigner_SetInConfig() {
S3Client customClient = getClientBuilder()
.overrideConfiguration(ClientOverrideConfiguration.builder()
.putAdvancedOption(SIGNER, AwsS3V4Signer.create())
.build())
.build();
String response = customClient.getObjectAsBytes(req -> req.bucket(BUCKET_NAME).key(KEY))
.asString(StandardCharsets.UTF_8);
assertEquals(CONTENT, response);
}
@Test
public void test_SignMethod_WithModeledParam_And_WithoutUsingSdkClient() throws Exception {
AwsS3V4Signer signer = AwsS3V4Signer.create();
SdkHttpFullRequest httpFullRequest = generateBasicGetRequest();
// sign the request
SdkHttpFullRequest signedRequest = signer.sign(httpFullRequest, constructSignerParams());
SdkHttpClient httpClient = ApacheHttpClient.builder().build();
HttpExecuteResponse response = httpClient.prepareRequest(HttpExecuteRequest.builder().request(signedRequest).build())
.call();
assertEquals("Non success http status code", 200, response.httpResponse().statusCode());
String actualResult = IoUtils.toUtf8String(response.responseBody().get());
assertEquals(CONTENT, actualResult);
}
@Test
public void test_SignMethod_WithExecutionAttributes_And_WithoutUsingSdkClient() throws Exception {
AwsS3V4Signer signer = AwsS3V4Signer.create();
SdkHttpFullRequest httpFullRequest = generateBasicGetRequest();
// sign the request
SdkHttpFullRequest signedRequest = signer.sign(httpFullRequest, constructExecutionAttributes());
SdkHttpClient httpClient = ApacheHttpClient.builder().build();
HttpExecuteResponse response = httpClient.prepareRequest(HttpExecuteRequest.builder().request(signedRequest).build())
.call();
assertEquals("Non success http status code", 200, response.httpResponse().statusCode());
String actualResult = IoUtils.toUtf8String(response.responseBody().get());
assertEquals(CONTENT, actualResult);
}
@Test
public void testPresigning() throws MalformedURLException {
AwsS3V4Signer signer = AwsS3V4Signer.create();
SdkHttpFullRequest httpFullRequest = generateBasicGetRequest();
SdkHttpFullRequest signedRequest = signer.presign(httpFullRequest, constructPresignerParams());
URL presignedUri = signedRequest.getUri().toURL();
assertEquals(CONTENT, getContentFromPresignedUrl(presignedUri));
}
private String getContentFromPresignedUrl(URL url) {
HttpURLConnection httpConn = null;
try {
httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream inputStream = httpConn.getInputStream();
return IOUtils.toString(inputStream, StandardCharsets.UTF_8);
} else {
throw new RuntimeException("No file to download. Server replied HTTP code: " + responseCode);
}
} catch (IOException e) {
throw new UncheckedIOException(e);
} finally {
if (httpConn != null) {
httpConn.disconnect();
}
}
}
private SdkHttpFullRequest generateBasicGetRequest() {
return SdkHttpFullRequest.builder()
.method(SdkHttpMethod.GET)
.protocol("https")
.host(getHost())
.encodedPath(getPath())
.build();
}
private String getHost() {
return String.format("%s.s3-%s.amazonaws.com", BUCKET_NAME, DEFAULT_REGION.id());
}
private String getPath() {
return String.format("/%s", KEY);
}
private AwsS3V4SignerParams constructSignerParams() {
return AwsS3V4SignerParams.builder()
.doubleUrlEncode(Boolean.FALSE)
.awsCredentials(awsCredentials)
.signingName(SIGNING_NAME)
.signingRegion(DEFAULT_REGION)
.build();
}
private Aws4PresignerParams constructPresignerParams() {
return Aws4PresignerParams.builder()
.doubleUrlEncode(Boolean.FALSE)
.awsCredentials(awsCredentials)
.signingName(SIGNING_NAME)
.signingRegion(DEFAULT_REGION)
.build();
}
private ExecutionAttributes constructExecutionAttributes() {
return new ExecutionAttributes()
.putAttribute(AwsSignerExecutionAttribute.AWS_CREDENTIALS, awsCredentials)
.putAttribute(AwsSignerExecutionAttribute.SERVICE_SIGNING_NAME, SIGNING_NAME)
.putAttribute(AwsSignerExecutionAttribute.SIGNING_REGION, DEFAULT_REGION);
}
private static S3ClientBuilder getClientBuilder() {
return S3Client.builder()
.region(DEFAULT_REGION)
.credentialsProvider(CREDENTIALS_PROVIDER_CHAIN);
}
}
| 4,513 |
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/utils/S3TestUtils.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.utils;
import java.rmi.NoSuchObjectException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.Bucket;
import software.amazon.awssdk.services.s3.model.DeleteBucketRequest;
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
import software.amazon.awssdk.services.s3.model.ExpirationStatus;
import software.amazon.awssdk.services.s3.model.ListObjectVersionsRequest;
import software.amazon.awssdk.services.s3.model.ListObjectVersionsResponse;
import software.amazon.awssdk.services.s3.model.ListObjectsRequest;
import software.amazon.awssdk.services.s3.model.ListObjectsResponse;
import software.amazon.awssdk.services.s3.model.NoSuchBucketException;
import software.amazon.awssdk.services.s3.model.S3Object;
import software.amazon.awssdk.testutils.Waiter;
import software.amazon.awssdk.utils.Logger;
public class S3TestUtils {
private static final Logger log = Logger.loggerFor(S3TestUtils.class);
private static final String TEST_BUCKET_PREFIX = "s3-test-bucket-";
private static final String NON_DNS_COMPATIBLE_TEST_BUCKET_PREFIX = "s3.test.bucket.";
private static Map<Class<?>, List<Runnable>> cleanupTasks = new ConcurrentHashMap<>();
public static String getTestBucket(S3Client s3) {
return getBucketWithPrefix(s3, TEST_BUCKET_PREFIX);
}
public static String getNonDnsCompatibleTestBucket(S3Client s3) {
return getBucketWithPrefix(s3, NON_DNS_COMPATIBLE_TEST_BUCKET_PREFIX);
}
private static String getBucketWithPrefix(S3Client s3, String bucketPrefix) {
String testBucket =
s3.listBuckets()
.buckets()
.stream()
.map(Bucket::name)
.filter(name -> name.startsWith(bucketPrefix))
.findAny()
.orElse(null);
if (testBucket == null) {
String newTestBucket = bucketPrefix + UUID.randomUUID();
s3.createBucket(r -> r.bucket(newTestBucket));
Waiter.run(() -> s3.headBucket(r -> r.bucket(newTestBucket)))
.ignoringException(NoSuchBucketException.class)
.orFail();
testBucket = newTestBucket;
}
String finalTestBucket = testBucket;
s3.putBucketLifecycleConfiguration(blc -> blc
.bucket(finalTestBucket)
.lifecycleConfiguration(lc -> lc
.rules(r -> r.expiration(ex -> ex.days(1))
.status(ExpirationStatus.ENABLED)
.filter(f -> f.prefix(""))
.id("delete-old"))));
return finalTestBucket;
}
public static void putObject(Class<?> testClass, S3Client s3, String bucketName, String objectKey, String content) {
s3.putObject(r -> r.bucket(bucketName).key(objectKey), RequestBody.fromString(content));
Waiter.run(() -> s3.getObjectAcl(r -> r.bucket(bucketName).key(objectKey)))
.ignoringException(NoSuchBucketException.class, NoSuchObjectException.class)
.orFail();
addCleanupTask(testClass, () -> s3.deleteObject(r -> r.bucket(bucketName).key(objectKey)));
}
public static void addCleanupTask(Class<?> testClass, Runnable cleanupTask) {
cleanupTasks.compute(testClass, (k, tasks) -> {
if (tasks == null) {
tasks = new ArrayList<>();
}
tasks.add(cleanupTask);
return tasks;
});
}
public static void runCleanupTasks(Class<?> testClass) {
List<Runnable> tasksToRun = cleanupTasks.remove(testClass);
tasksToRun.forEach(r -> {
try {
r.run();
} catch (Exception e) {
log.warn(() -> "Test cleanup task failed. The failure will be ignored.", e);
}
});
}
public static void deleteBucketAndAllContents(S3Client s3, String bucketName) {
try {
System.out.println("Deleting S3 bucket: " + bucketName);
ListObjectsResponse response = Waiter.run(() -> s3.listObjects(r -> r.bucket(bucketName)))
.ignoringException(NoSuchBucketException.class)
.orFail();
List<S3Object> objectListing = response.contents();
if (objectListing != null) {
while (true) {
for (Iterator<?> iterator = objectListing.iterator(); iterator.hasNext(); ) {
S3Object objectSummary = (S3Object) iterator.next();
s3.deleteObject(DeleteObjectRequest.builder().bucket(bucketName).key(objectSummary.key()).build());
}
if (response.isTruncated()) {
objectListing = s3.listObjects(ListObjectsRequest.builder()
.bucket(bucketName)
.marker(response.marker())
.build())
.contents();
} else {
break;
}
}
}
ListObjectVersionsResponse versions = s3
.listObjectVersions(ListObjectVersionsRequest.builder().bucket(bucketName).build());
if (versions.deleteMarkers() != null) {
versions.deleteMarkers().forEach(v -> s3.deleteObject(DeleteObjectRequest.builder()
.versionId(v.versionId())
.bucket(bucketName)
.key(v.key())
.build()));
}
if (versions.versions() != null) {
versions.versions().forEach(v -> s3.deleteObject(DeleteObjectRequest.builder()
.versionId(v.versionId())
.bucket(bucketName)
.key(v.key())
.build()));
}
s3.deleteBucket(DeleteBucketRequest.builder().bucket(bucketName).build());
} catch (Exception e) {
System.err.println("Failed to delete bucket: " + bucketName);
e.printStackTrace();
}
}
}
| 4,514 |
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/multipart/S3ClientMultiPartCopyIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Fail.fail;
import static software.amazon.awssdk.services.s3.model.ServerSideEncryption.AES256;
import static software.amazon.awssdk.services.s3.utils.ChecksumUtils.computeCheckSum;
import static software.amazon.awssdk.testutils.service.S3BucketUtils.temporaryBucketName;
import java.nio.ByteBuffer;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
import javax.crypto.KeyGenerator;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import software.amazon.awssdk.core.ClientType;
import software.amazon.awssdk.core.ResponseBytes;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.core.sync.ResponseTransformer;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.S3IntegrationTestBase;
import software.amazon.awssdk.services.s3.internal.crt.S3CrtAsyncClient;
import software.amazon.awssdk.services.s3.model.CopyObjectResponse;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.services.s3.model.MetadataDirective;
import software.amazon.awssdk.utils.Md5Utils;
@Timeout(value = 3, unit = TimeUnit.MINUTES)
public class S3ClientMultiPartCopyIntegrationTest extends S3IntegrationTestBase {
private static final String BUCKET = temporaryBucketName(S3ClientMultiPartCopyIntegrationTest.class);
private static final String ORIGINAL_OBJ = "test_file.dat";
private static final String COPIED_OBJ = "test_file_copy.dat";
private static final String ORIGINAL_OBJ_SPECIAL_CHARACTER = "original-special-chars-@$%";
private static final String COPIED_OBJ_SPECIAL_CHARACTER = "special-special-chars-@$%";
private static final long OBJ_SIZE = ThreadLocalRandom.current().nextLong(8 * 1024 * 1024, 16 * 1024 * 1024 + 1);
private static final long SMALL_OBJ_SIZE = 1024 * 1024;
private static S3AsyncClient s3CrtAsyncClient;
private static S3AsyncClient s3MpuClient;
@BeforeAll
public static void setUp() throws Exception {
S3IntegrationTestBase.setUp();
createBucket(BUCKET);
s3CrtAsyncClient = S3CrtAsyncClient.builder()
.credentialsProvider(CREDENTIALS_PROVIDER_CHAIN)
.region(DEFAULT_REGION)
.build();
s3MpuClient = S3AsyncClient.builder()
.region(DEFAULT_REGION)
.credentialsProvider(CREDENTIALS_PROVIDER_CHAIN)
.overrideConfiguration(o -> o.addExecutionInterceptor(
new UserAgentVerifyingExecutionInterceptor("NettyNio", ClientType.ASYNC)))
.multipartEnabled(true)
.build();
}
@AfterAll
public static void teardown() throws Exception {
s3CrtAsyncClient.close();
s3MpuClient.close();
deleteBucketAndAllContents(BUCKET);
}
public static Stream<S3AsyncClient> s3AsyncClient() {
return Stream.of(s3MpuClient, s3CrtAsyncClient);
}
@ParameterizedTest(autoCloseArguments = false)
@MethodSource("s3AsyncClient")
void copy_singlePart_hasSameContent(S3AsyncClient s3AsyncClient) {
byte[] originalContent = randomBytes(SMALL_OBJ_SIZE);
createOriginalObject(originalContent, ORIGINAL_OBJ);
copyObject(ORIGINAL_OBJ, COPIED_OBJ, s3AsyncClient);
validateCopiedObject(originalContent, ORIGINAL_OBJ);
}
@ParameterizedTest(autoCloseArguments = false)
@MethodSource("s3AsyncClient")
void copy_copiedObject_hasSameContent(S3AsyncClient s3AsyncClient) {
byte[] originalContent = randomBytes(OBJ_SIZE);
createOriginalObject(originalContent, ORIGINAL_OBJ);
copyObject(ORIGINAL_OBJ, COPIED_OBJ, s3AsyncClient);
validateCopiedObject(originalContent, ORIGINAL_OBJ);
}
@ParameterizedTest(autoCloseArguments = false)
@MethodSource("s3AsyncClient")
void copy_specialCharacters_hasSameContent(S3AsyncClient s3AsyncClient) {
byte[] originalContent = randomBytes(OBJ_SIZE);
createOriginalObject(originalContent, ORIGINAL_OBJ_SPECIAL_CHARACTER);
copyObject(ORIGINAL_OBJ_SPECIAL_CHARACTER, COPIED_OBJ_SPECIAL_CHARACTER, s3AsyncClient);
validateCopiedObject(originalContent, COPIED_OBJ_SPECIAL_CHARACTER);
}
@ParameterizedTest(autoCloseArguments = false)
@MethodSource("s3AsyncClient")
void copy_ssecServerSideEncryption_shouldSucceed(S3AsyncClient s3AsyncClient) {
byte[] originalContent = randomBytes(OBJ_SIZE);
byte[] secretKey = generateSecretKey();
String b64Key = Base64.getEncoder().encodeToString(secretKey);
String b64KeyMd5 = Md5Utils.md5AsBase64(secretKey);
byte[] newSecretKey = generateSecretKey();
String newB64Key = Base64.getEncoder().encodeToString(newSecretKey);
String newB64KeyMd5 = Md5Utils.md5AsBase64(newSecretKey);
s3AsyncClient.putObject(r -> r.bucket(BUCKET)
.key(ORIGINAL_OBJ)
.sseCustomerKey(b64Key)
.sseCustomerAlgorithm(AES256.name())
.sseCustomerKeyMD5(b64KeyMd5),
AsyncRequestBody.fromBytes(originalContent)).join();
CompletableFuture<CopyObjectResponse> future = s3AsyncClient.copyObject(c -> c
.sourceBucket(BUCKET)
.sourceKey(ORIGINAL_OBJ)
.metadataDirective(MetadataDirective.REPLACE)
.sseCustomerAlgorithm(AES256.name())
.sseCustomerKey(newB64Key)
.sseCustomerKeyMD5(newB64KeyMd5)
.copySourceSSECustomerAlgorithm(AES256.name())
.copySourceSSECustomerKey(b64Key)
.copySourceSSECustomerKeyMD5(b64KeyMd5)
.destinationBucket(BUCKET)
.destinationKey(COPIED_OBJ));
CopyObjectResponse copyObjectResponse = future.join();
assertThat(copyObjectResponse.responseMetadata().requestId()).isNotNull();
assertThat(copyObjectResponse.sdkHttpResponse()).isNotNull();
}
private static byte[] generateSecretKey() {
KeyGenerator generator;
try {
generator = KeyGenerator.getInstance("AES");
generator.init(256, new SecureRandom());
return generator.generateKey().getEncoded();
} catch (Exception e) {
fail("Unable to generate symmetric key: " + e.getMessage());
return null;
}
}
private void createOriginalObject(byte[] originalContent, String originalKey) {
s3CrtAsyncClient.putObject(r -> r.bucket(BUCKET)
.key(originalKey),
AsyncRequestBody.fromBytes(originalContent)).join();
}
private void copyObject(String original, String destination, S3AsyncClient s3AsyncClient) {
CompletableFuture<CopyObjectResponse> future = s3AsyncClient.copyObject(c -> c
.sourceBucket(BUCKET)
.sourceKey(original)
.destinationBucket(BUCKET)
.destinationKey(destination));
CopyObjectResponse copyObjectResponse = future.join();
assertThat(copyObjectResponse.responseMetadata().requestId()).isNotNull();
assertThat(copyObjectResponse.sdkHttpResponse()).isNotNull();
}
private void validateCopiedObject(byte[] originalContent, String originalKey) {
ResponseBytes<GetObjectResponse> copiedObject = s3.getObject(r -> r.bucket(BUCKET)
.key(originalKey),
ResponseTransformer.toBytes());
assertThat(computeCheckSum(copiedObject.asByteBuffer())).isEqualTo(computeCheckSum(ByteBuffer.wrap(originalContent)));
}
public static byte[] randomBytes(long size) {
byte[] bytes = new byte[Math.toIntExact(size)];
ThreadLocalRandom.current().nextBytes(bytes);
return bytes;
}
}
| 4,515 |
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/multipart/S3MultipartClientPutObjectIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 static java.util.concurrent.TimeUnit.SECONDS;
import static org.assertj.core.api.Assertions.assertThat;
import static software.amazon.awssdk.testutils.service.S3BucketUtils.temporaryBucketName;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.util.Optional;
import java.util.UUID;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.reactivestreams.Subscriber;
import software.amazon.awssdk.core.ClientType;
import software.amazon.awssdk.core.ResponseInputStream;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.core.internal.async.FileAsyncRequestBody;
import software.amazon.awssdk.core.sync.ResponseTransformer;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.S3IntegrationTestBase;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.services.s3.utils.ChecksumUtils;
@Timeout(value = 30, unit = SECONDS)
public class S3MultipartClientPutObjectIntegrationTest extends S3IntegrationTestBase {
private static final String TEST_BUCKET = temporaryBucketName(S3MultipartClientPutObjectIntegrationTest.class);
private static final String TEST_KEY = "testfile.dat";
private static final int OBJ_SIZE = 19 * 1024 * 1024;
private static File testFile;
private static S3AsyncClient mpuS3Client;
@BeforeAll
public static void setup() throws Exception {
S3IntegrationTestBase.setUp();
S3IntegrationTestBase.createBucket(TEST_BUCKET);
byte[] CONTENT =
RandomStringUtils.randomAscii(OBJ_SIZE).getBytes(Charset.defaultCharset());
testFile = File.createTempFile("SplittingPublisherTest", UUID.randomUUID().toString());
Files.write(testFile.toPath(), CONTENT);
mpuS3Client = S3AsyncClient
.builder()
.region(DEFAULT_REGION)
.credentialsProvider(CREDENTIALS_PROVIDER_CHAIN)
.overrideConfiguration(o -> o.addExecutionInterceptor(
new UserAgentVerifyingExecutionInterceptor("NettyNio", ClientType.ASYNC)))
.multipartEnabled(true)
.build();
}
@AfterAll
public static void teardown() throws Exception {
mpuS3Client.close();
testFile.delete();
deleteBucketAndAllContents(TEST_BUCKET);
}
@Test
void putObject_fileRequestBody_objectSentCorrectly() throws Exception {
AsyncRequestBody body = AsyncRequestBody.fromFile(testFile.toPath());
mpuS3Client.putObject(r -> r.bucket(TEST_BUCKET).key(TEST_KEY), body).join();
ResponseInputStream<GetObjectResponse> objContent =
S3IntegrationTestBase.s3.getObject(r -> r.bucket(TEST_BUCKET).key(TEST_KEY),
ResponseTransformer.toInputStream());
assertThat(objContent.response().contentLength()).isEqualTo(testFile.length());
byte[] expectedSum = ChecksumUtils.computeCheckSum(Files.newInputStream(testFile.toPath()));
assertThat(ChecksumUtils.computeCheckSum(objContent)).isEqualTo(expectedSum);
}
@Test
void putObject_byteAsyncRequestBody_objectSentCorrectly() throws Exception {
byte[] bytes = RandomStringUtils.randomAscii(OBJ_SIZE).getBytes(Charset.defaultCharset());
AsyncRequestBody body = AsyncRequestBody.fromBytes(bytes);
mpuS3Client.putObject(r -> r.bucket(TEST_BUCKET).key(TEST_KEY), body).join();
ResponseInputStream<GetObjectResponse> objContent =
S3IntegrationTestBase.s3.getObject(r -> r.bucket(TEST_BUCKET).key(TEST_KEY),
ResponseTransformer.toInputStream());
assertThat(objContent.response().contentLength()).isEqualTo(OBJ_SIZE);
byte[] expectedSum = ChecksumUtils.computeCheckSum(new ByteArrayInputStream(bytes));
assertThat(ChecksumUtils.computeCheckSum(objContent)).isEqualTo(expectedSum);
}
@Test
void putObject_unknownContentLength_objectSentCorrectly() throws Exception {
AsyncRequestBody body = FileAsyncRequestBody.builder()
.path(testFile.toPath())
.build();
mpuS3Client.putObject(r -> r.bucket(TEST_BUCKET).key(TEST_KEY), new AsyncRequestBody() {
@Override
public Optional<Long> contentLength() {
return Optional.empty();
}
@Override
public void subscribe(Subscriber<? super ByteBuffer> s) {
body.subscribe(s);
}
}).get(30, SECONDS);
ResponseInputStream<GetObjectResponse> objContent =
S3IntegrationTestBase.s3.getObject(r -> r.bucket(TEST_BUCKET).key(TEST_KEY),
ResponseTransformer.toInputStream());
assertThat(objContent.response().contentLength()).isEqualTo(testFile.length());
byte[] expectedSum = ChecksumUtils.computeCheckSum(Files.newInputStream(testFile.toPath()));
assertThat(ChecksumUtils.computeCheckSum(objContent)).isEqualTo(expectedSum);
}
}
| 4,516 |
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/crt/S3CrtClientPutObjectIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.crt;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static software.amazon.awssdk.testutils.service.S3BucketUtils.temporaryBucketName;
import io.reactivex.Flowable;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.util.List;
import java.util.Optional;
import java.util.Random;
import java.util.concurrent.CompletionException;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.reactivestreams.Subscriber;
import software.amazon.awssdk.core.ResponseBytes;
import software.amazon.awssdk.core.ResponseInputStream;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.sync.ResponseTransformer;
import software.amazon.awssdk.crt.CrtResource;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.S3IntegrationTestBase;
import software.amazon.awssdk.services.s3.internal.crt.CrtContentLengthOnlyAsyncFileRequestBody;
import software.amazon.awssdk.services.s3.internal.crt.S3CrtAsyncClient;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.services.s3.utils.ChecksumUtils;
import software.amazon.awssdk.testutils.RandomTempFile;
import software.amazon.awssdk.testutils.service.AwsTestBase;
public class S3CrtClientPutObjectIntegrationTest extends S3IntegrationTestBase {
private static final String TEST_BUCKET = temporaryBucketName(S3CrtClientPutObjectIntegrationTest.class);
private static final String TEST_KEY = "8mib_file.dat";
private static final int OBJ_SIZE = 10 * 1024 * 1024;
private static RandomTempFile testFile;
private static S3AsyncClient s3Crt;
@BeforeAll
public static void setup() throws Exception {
S3IntegrationTestBase.setUp();
S3IntegrationTestBase.createBucket(TEST_BUCKET);
testFile = new RandomTempFile(TEST_KEY, OBJ_SIZE);
s3Crt = S3CrtAsyncClient.builder()
.credentialsProvider(AwsTestBase.CREDENTIALS_PROVIDER_CHAIN)
.region(S3IntegrationTestBase.DEFAULT_REGION)
.build();
}
@AfterAll
public static void teardown() throws IOException {
S3IntegrationTestBase.deleteBucketAndAllContents(TEST_BUCKET);
Files.delete(testFile.toPath());
s3Crt.close();
CrtResource.waitForNoResources();
}
@Test
void putObject_fileRequestBody_objectSentCorrectly() throws Exception {
AsyncRequestBody body = AsyncRequestBody.fromFile(testFile.toPath());
s3Crt.putObject(r -> r.bucket(TEST_BUCKET).key(TEST_KEY), body).join();
ResponseInputStream<GetObjectResponse> objContent = S3IntegrationTestBase.s3.getObject(r -> r.bucket(TEST_BUCKET).key(TEST_KEY),
ResponseTransformer.toInputStream());
byte[] expectedSum = ChecksumUtils.computeCheckSum(Files.newInputStream(testFile.toPath()));
Assertions.assertThat(ChecksumUtils.computeCheckSum(objContent)).isEqualTo(expectedSum);
}
@Test
void putObject_file_objectSentCorrectly() throws Exception {
s3Crt.putObject(r -> r.bucket(TEST_BUCKET).key(TEST_KEY), testFile.toPath()).join();
ResponseInputStream<GetObjectResponse> objContent = S3IntegrationTestBase.s3.getObject(r -> r.bucket(TEST_BUCKET).key(TEST_KEY),
ResponseTransformer.toInputStream());
byte[] expectedSum = ChecksumUtils.computeCheckSum(Files.newInputStream(testFile.toPath()));
Assertions.assertThat(ChecksumUtils.computeCheckSum(objContent)).isEqualTo(expectedSum);
}
@Test
void putObject_failsFor_CrtContentLengthOnlyAsyncFileRequestBody() {
assertThatThrownBy(() ->
s3Crt.putObject(r -> r.bucket(TEST_BUCKET).key(TEST_KEY),
new CrtContentLengthOnlyAsyncFileRequestBody(testFile.toPath())).join())
.isInstanceOf(CompletionException.class)
.hasCauseInstanceOf(SdkClientException.class);
}
@Test
void putObject_byteBufferBody_objectSentCorrectly() {
byte[] data = new byte[16384];
new Random().nextBytes(data);
ByteBuffer byteBuffer = ByteBuffer.wrap(data);
AsyncRequestBody body = AsyncRequestBody.fromByteBuffer(byteBuffer);
s3Crt.putObject(r -> r.bucket(TEST_BUCKET).key(TEST_KEY), body).join();
ResponseBytes<GetObjectResponse> responseBytes = S3IntegrationTestBase.s3.getObject(r -> r.bucket(TEST_BUCKET).key(TEST_KEY),
ResponseTransformer.toBytes());
byte[] expectedSum = ChecksumUtils.computeCheckSum(byteBuffer);
Assertions.assertThat(ChecksumUtils.computeCheckSum(responseBytes.asByteBuffer())).isEqualTo(expectedSum);
}
@Test
void putObject_customRequestBody_objectSentCorrectly() throws IOException {
Random rng = new Random();
int bufferSize = 16384;
int nBuffers = 15;
List<ByteBuffer> bodyData = Stream.generate(() -> {
byte[] data = new byte[bufferSize];
rng.nextBytes(data);
return ByteBuffer.wrap(data);
}).limit(nBuffers).collect(Collectors.toList());
long contentLength = bufferSize * nBuffers;
byte[] expectedSum = ChecksumUtils.computeCheckSum(bodyData);
Flowable<ByteBuffer> publisher = Flowable.fromIterable(bodyData);
AsyncRequestBody customRequestBody = new AsyncRequestBody() {
@Override
public Optional<Long> contentLength() {
return Optional.of(contentLength);
}
@Override
public void subscribe(Subscriber<? super ByteBuffer> subscriber) {
publisher.subscribe(subscriber);
}
};
s3Crt.putObject(r -> r.bucket(TEST_BUCKET).key(TEST_KEY), customRequestBody).join();
ResponseInputStream<GetObjectResponse> objContent = S3IntegrationTestBase.s3.getObject(r -> r.bucket(TEST_BUCKET).key(TEST_KEY),
ResponseTransformer.toInputStream());
Assertions.assertThat(ChecksumUtils.computeCheckSum(objContent)).isEqualTo(expectedSum);
}
}
| 4,517 |
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/crt/ChecksumIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.crt;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static software.amazon.awssdk.testutils.service.S3BucketUtils.temporaryBucketName;
import java.io.IOException;
import java.nio.file.Files;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.ResponseBytes;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.core.async.AsyncResponseTransformer;
import software.amazon.awssdk.crt.CrtResource;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.S3IntegrationTestBase;
import software.amazon.awssdk.services.s3.internal.crt.S3CrtAsyncClient;
import software.amazon.awssdk.services.s3.model.ChecksumAlgorithm;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.services.s3.model.PutObjectResponse;
import software.amazon.awssdk.services.s3.model.PutObjectTaggingResponse;
import software.amazon.awssdk.services.s3.model.Tag;
import software.amazon.awssdk.services.s3.model.Tagging;
import software.amazon.awssdk.testutils.RandomTempFile;
import software.amazon.awssdk.testutils.service.AwsTestBase;
public class ChecksumIntegrationTest extends S3IntegrationTestBase {
private static final String TEST_BUCKET = temporaryBucketName(ChecksumIntegrationTest.class);
private static final String TEST_KEY = "10mib_file.dat";
private static final int OBJ_SIZE = 10 * 1024 * 1024;
private static RandomTempFile testFile;
private static S3AsyncClient s3Crt;
@BeforeAll
public static void setup() throws Exception {
S3IntegrationTestBase.setUp();
S3IntegrationTestBase.createBucket(TEST_BUCKET);
testFile = new RandomTempFile(TEST_KEY, OBJ_SIZE);
s3Crt = S3CrtAsyncClient.builder()
.credentialsProvider(AwsTestBase.CREDENTIALS_PROVIDER_CHAIN)
.region(S3IntegrationTestBase.DEFAULT_REGION)
.build();
}
@AfterAll
public static void teardown() throws IOException {
S3IntegrationTestBase.deleteBucketAndAllContents(TEST_BUCKET);
Files.delete(testFile.toPath());
s3Crt.close();
CrtResource.waitForNoResources();
}
@Test
void noChecksumCustomization_crc32ShouldBeUsed() {
AsyncRequestBody body = AsyncRequestBody.fromFile(testFile.toPath());
PutObjectResponse putObjectResponse =
s3Crt.putObject(r -> r.bucket(TEST_BUCKET).key(TEST_KEY), body).join();
assertThat(putObjectResponse).isNotNull();
ResponseBytes<GetObjectResponse> getObjectResponseResponseBytes =
s3Crt.getObject(r -> r.bucket(TEST_BUCKET).key(TEST_KEY).partNumber(1), AsyncResponseTransformer.toBytes()).join();
String getObjectChecksum = getObjectResponseResponseBytes.response().checksumCRC32();
assertThat(getObjectChecksum).isNotNull();
}
@Test
void putObject_checksumProvidedInRequest_shouldTakePrecendence() {
AsyncRequestBody body = AsyncRequestBody.fromFile(testFile.toPath());
PutObjectResponse putObjectResponse =
s3Crt.putObject(r -> r.bucket(TEST_BUCKET).key(TEST_KEY).checksumAlgorithm(ChecksumAlgorithm.SHA1), body).join();
assertThat(putObjectResponse).isNotNull();
ResponseBytes<GetObjectResponse> getObjectResponseResponseBytes =
s3Crt.getObject(r -> r.bucket(TEST_BUCKET).key(TEST_KEY).partNumber(1), AsyncResponseTransformer.toBytes()).join();
String getObjectChecksum = getObjectResponseResponseBytes.response().checksumSHA1();
assertThat(getObjectChecksum).isNotNull();
}
@Test
void checksumDisabled_shouldNotPerformChecksumValidationByDefault() {
try (S3AsyncClient s3Crt = S3CrtAsyncClient.builder()
.credentialsProvider(AwsTestBase.CREDENTIALS_PROVIDER_CHAIN)
.region(S3IntegrationTestBase.DEFAULT_REGION)
.checksumValidationEnabled(Boolean.FALSE)
.build()) {
AsyncRequestBody body = AsyncRequestBody.fromFile(testFile.toPath());
PutObjectResponse putObjectResponse =
s3Crt.putObject(r -> r.bucket(TEST_BUCKET).key(TEST_KEY), body).join();
assertThat(putObjectResponse.checksumCRC32()).isNull();
ResponseBytes<GetObjectResponse> getObjectResponseResponseBytes =
s3Crt.getObject(r -> r.bucket(TEST_BUCKET).key(TEST_KEY), AsyncResponseTransformer.toBytes()).join();
assertThat(getObjectResponseResponseBytes.response().checksumCRC32()).isNull();
}
}
@Test
void nonStreamingOperation_specifyChecksum_shouldWork() {
s3Crt.putObject(p -> p.bucket(TEST_BUCKET).key(TEST_KEY), AsyncRequestBody.fromString("helloworld")).join();
// checksum is required for this operation
PutObjectTaggingResponse putBucketAclResponse =
s3Crt.putObjectTagging(p -> p.bucket(TEST_BUCKET).key(TEST_KEY)
.checksumAlgorithm(ChecksumAlgorithm.SHA1)
.tagging(Tagging.builder().tagSet(Tag.builder().key("test").
value("value").build()).build()))
.join();
assertThat(putBucketAclResponse).isNotNull();
}
}
| 4,518 |
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/crt/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.crt;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static software.amazon.awssdk.services.s3.multipart.S3ClientMultiPartCopyIntegrationTest.randomBytes;
import static software.amazon.awssdk.services.s3.utils.ChecksumUtils.computeCheckSum;
import static software.amazon.awssdk.testutils.service.S3BucketUtils.temporaryBucketName;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadLocalRandom;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.ResponseBytes;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.core.async.AsyncResponseTransformer;
import software.amazon.awssdk.core.sync.ResponseTransformer;
import software.amazon.awssdk.crt.CrtResource;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.S3IntegrationTestBase;
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.S3Exception;
import software.amazon.awssdk.testutils.RandomTempFile;
import software.amazon.awssdk.testutils.service.AwsTestBase;
public class S3CrossRegionCrtIntegrationTest extends S3IntegrationTestBase {
public static final Region CROSS_REGION = Region.EU_CENTRAL_1;
private static final String BUCKET = temporaryBucketName(S3CrossRegionCrtIntegrationTest.class);
private static final String KEY = "key";
private static final String ORIGINAL_OBJ = "test_file.dat";
private static final String COPIED_OBJ = "test_file_copy.dat";
private static final long OBJ_SIZE = ThreadLocalRandom.current().nextLong(8 * 1024, 16 * 1024 + 1);
private static S3AsyncClient crtClient;
private static File file;
private static ExecutorService executorService;
@BeforeAll
public static void setup() throws Exception {
S3IntegrationTestBase.setUp();
S3IntegrationTestBase.createBucket(BUCKET);
crtClient = S3AsyncClient.crtBuilder()
.region(CROSS_REGION)
.crossRegionAccessEnabled(true)
.credentialsProvider(AwsTestBase.CREDENTIALS_PROVIDER_CHAIN)
.build();
file = new RandomTempFile(10_000);
S3IntegrationTestBase.s3.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(KEY)
.build(), file.toPath());
executorService = Executors.newFixedThreadPool(2);
}
@AfterAll
public static void cleanup() {
crtClient.close();
S3IntegrationTestBase.deleteBucketAndAllContents(BUCKET);
executorService.shutdown();
CrtResource.waitForNoResources();
}
@Test
void crossRegionClient_getObject() throws IOException {
byte[] bytes =
crtClient.getObject(b -> b.bucket(BUCKET).key(KEY), AsyncResponseTransformer.toBytes()).join().asByteArray();
assertThat(bytes).isEqualTo(Files.readAllBytes(file.toPath()));
}
@Test
void putObjectNoSuchBucket() {
assertThatThrownBy(() -> crtClient.getObject(GetObjectRequest.builder().bucket("nonExistingTestBucket" + UUID.randomUUID()).key(KEY).build(),
AsyncResponseTransformer.toBytes()).get())
.hasCauseInstanceOf(S3Exception.class)
.satisfies(throwable -> assertThat(throwable.getCause()).satisfies(cause -> assertThat(((S3Exception) cause).statusCode()).isEqualTo(404)));
}
@Test
void copy_copiedObject_hasSameContent() {
byte[] originalContent = randomBytes(OBJ_SIZE);
createOriginalObject(originalContent, ORIGINAL_OBJ);
copyObject(ORIGINAL_OBJ, COPIED_OBJ);
validateCopiedObject(originalContent, ORIGINAL_OBJ);
}
private void copyObject(String original, String destination) {
CompletableFuture<CopyObjectResponse> future = crtClient.copyObject(c -> c
.sourceBucket(BUCKET)
.sourceKey(original)
.destinationBucket(BUCKET)
.destinationKey(destination));
CopyObjectResponse copyObjectResponse = future.join();
assertThat(copyObjectResponse.responseMetadata().requestId()).isNotNull();
assertThat(copyObjectResponse.sdkHttpResponse()).isNotNull();
}
@Test
void putObject_byteBufferBody_objectSentCorrectly() {
byte[] data = new byte[16384];
new Random().nextBytes(data);
ByteBuffer byteBuffer = ByteBuffer.wrap(data);
AsyncRequestBody body = AsyncRequestBody.fromByteBuffer(byteBuffer);
crtClient.putObject(r -> r.bucket(BUCKET).key(KEY), body).join();
ResponseBytes<GetObjectResponse> responseBytes = S3IntegrationTestBase.s3.getObject(r -> r.bucket(BUCKET).key(KEY),
ResponseTransformer.toBytes());
byte[] expectedSum = computeCheckSum(byteBuffer);
assertThat(computeCheckSum(responseBytes.asByteBuffer())).isEqualTo(expectedSum);
}
private void validateCopiedObject(byte[] originalContent, String originalKey) {
ResponseBytes<GetObjectResponse> copiedObject = s3.getObject(r -> r.bucket(BUCKET)
.key(originalKey),
ResponseTransformer.toBytes());
assertThat(computeCheckSum(copiedObject.asByteBuffer())).isEqualTo(computeCheckSum(ByteBuffer.wrap(originalContent)));
}
private void createOriginalObject(byte[] originalContent, String originalKey) {
crtClient.putObject(r -> r.bucket(BUCKET)
.key(originalKey),
AsyncRequestBody.fromBytes(originalContent)).join();
}
}
| 4,519 |
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/crt/S3CrtGetObjectIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.crt;
import static org.assertj.core.api.Assertions.assertThat;
import static software.amazon.awssdk.testutils.service.S3BucketUtils.temporaryBucketName;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.async.AsyncResponseTransformer;
import software.amazon.awssdk.crt.CrtResource;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.S3IntegrationTestBase;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.testutils.RandomTempFile;
import software.amazon.awssdk.testutils.service.AwsTestBase;
import software.amazon.awssdk.utils.Md5Utils;
public class S3CrtGetObjectIntegrationTest extends S3IntegrationTestBase {
private static final String BUCKET = temporaryBucketName(S3CrtGetObjectIntegrationTest.class);
private static final String KEY = "key";
private static S3AsyncClient crtClient;
private static File file;
private static ExecutorService executorService;
@BeforeAll
public static void setup() throws Exception {
S3IntegrationTestBase.setUp();
S3IntegrationTestBase.createBucket(BUCKET);
crtClient = S3AsyncClient.crtBuilder()
.region(S3IntegrationTestBase.DEFAULT_REGION)
.credentialsProvider(AwsTestBase.CREDENTIALS_PROVIDER_CHAIN)
.build();
file = new RandomTempFile(10_000);
S3IntegrationTestBase.s3.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(KEY)
.build(), file.toPath());
executorService = Executors.newFixedThreadPool(2);
}
@AfterAll
public static void cleanup() {
crtClient.close();
S3IntegrationTestBase.deleteBucketAndAllContents(BUCKET);
executorService.shutdown();
CrtResource.waitForNoResources();
}
@Test
void getObject_toFiles() throws IOException {
Path path = RandomTempFile.randomUncreatedFile().toPath();
GetObjectResponse response =
crtClient.getObject(b -> b.bucket(BUCKET).key(KEY), AsyncResponseTransformer.toFile(path)).join();
assertThat(Md5Utils.md5AsBase64(path.toFile())).isEqualTo(Md5Utils.md5AsBase64(file));
}
@Test
void getObject_toBytes() throws IOException {
byte[] bytes =
crtClient.getObject(b -> b.bucket(BUCKET).key(KEY), AsyncResponseTransformer.toBytes()).join().asByteArray();
assertThat(bytes).isEqualTo(Files.readAllBytes(file.toPath()));
}
@Test
void getObject_customResponseTransformer() {
crtClient.getObject(b -> b.bucket(BUCKET).key(KEY),
new TestResponseTransformer()).join();
}
}
| 4,520 |
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/crt/CrtExceptionTransformationIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.crt;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static software.amazon.awssdk.testutils.service.S3BucketUtils.temporaryBucketName;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.UUID;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.async.AsyncResponseTransformer;
import software.amazon.awssdk.crt.CrtResource;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.S3IntegrationTestBase;
import software.amazon.awssdk.services.s3.internal.crt.S3CrtAsyncClient;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.NoSuchBucketException;
import software.amazon.awssdk.services.s3.model.NoSuchKeyException;
import software.amazon.awssdk.services.s3.model.S3Exception;
import software.amazon.awssdk.testutils.RandomTempFile;
import software.amazon.awssdk.testutils.service.AwsTestBase;
public class CrtExceptionTransformationIntegrationTest extends S3IntegrationTestBase {
private static final String BUCKET = temporaryBucketName(CrtExceptionTransformationIntegrationTest.class);
private static final String KEY = "some-key";
private static S3AsyncClient s3Crt;
@BeforeAll
public static void setupFixture() throws Exception {
S3IntegrationTestBase.setUp();
S3IntegrationTestBase.createBucket(BUCKET);
s3Crt = S3CrtAsyncClient.builder()
.credentialsProvider(AwsTestBase.CREDENTIALS_PROVIDER_CHAIN)
.region(S3IntegrationTestBase.DEFAULT_REGION)
.build();
}
@AfterAll
public static void tearDownFixture() {
S3IntegrationTestBase.deleteBucketAndAllContents(BUCKET);
s3Crt.close();
CrtResource.waitForNoResources();
}
@Test
void getObjectNoSuchKey() {
assertThatThrownBy(() -> s3Crt.getObject(GetObjectRequest.builder().bucket(BUCKET).key("randomKey").build(),
AsyncResponseTransformer.toBytes()).get())
.hasCauseInstanceOf(S3Exception.class)
.satisfies(throwable -> assertThat(throwable.getCause()).satisfies(cause -> assertThat(((S3Exception) cause).statusCode()).isEqualTo(404)));
}
@Test
void getObjectNoSuchBucket() {
assertThatThrownBy(() -> s3Crt.getObject(GetObjectRequest.builder().bucket("nonExistingTestBucket" + UUID.randomUUID()).key(KEY).build(),
AsyncResponseTransformer.toBytes()).get())
.hasCauseInstanceOf(S3Exception.class)
.satisfies(throwable -> assertThat(throwable.getCause()).satisfies(cause -> assertThat(((S3Exception) cause).statusCode()).isEqualTo(404)));
}
@Test
void putObjectNoSuchKey() {
assertThatThrownBy(() -> s3Crt.getObject(GetObjectRequest.builder().bucket(BUCKET).key("someRandomKey").build(),
AsyncResponseTransformer.toBytes()).get())
.hasCauseInstanceOf(S3Exception.class)
.satisfies(throwable -> assertThat(throwable.getCause()).satisfies(cause -> assertThat(((S3Exception) cause).statusCode()).isEqualTo(404)));
}
@Test
void putObjectNoSuchBucket() {
assertThatThrownBy(() -> s3Crt.getObject(GetObjectRequest.builder().bucket("nonExistingTestBucket" + UUID.randomUUID()).key(KEY).build(),
AsyncResponseTransformer.toBytes()).get())
.hasCauseInstanceOf(S3Exception.class)
.satisfies(throwable -> assertThat(throwable.getCause()).satisfies(cause -> assertThat(((S3Exception) cause).statusCode()).isEqualTo(404)));
}
} | 4,521 |
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/crt/TestResponseTransformer.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.crt;
import static org.assertj.core.api.Assertions.assertThat;
import java.nio.ByteBuffer;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.core.async.AsyncResponseTransformer;
import software.amazon.awssdk.core.async.SdkPublisher;
import software.amazon.awssdk.http.async.SimpleSubscriber;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
public final class TestResponseTransformer implements AsyncResponseTransformer<GetObjectResponse, Void> {
private CompletableFuture<Void> future;
@Override
public CompletableFuture<Void> prepare() {
future = new CompletableFuture<>();
return future;
}
@Override
public void onResponse(GetObjectResponse response) {
assertThat(response).isNotNull();
}
@Override
public void onStream(SdkPublisher<ByteBuffer> publisher) {
publisher.subscribe(new SimpleSubscriber(b -> {
}) {
@Override
public void onComplete() {
super.onComplete();
future.complete(null);
}
});
}
@Override
public void exceptionOccurred(Throwable error) {
future.completeExceptionally(error);
}
} | 4,522 |
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/checksum/HttpChecksumIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.checksum;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static software.amazon.awssdk.services.s3.utils.ChecksumUtils.KB;
import static software.amazon.awssdk.services.s3.utils.ChecksumUtils.createDataOfSize;
import static software.amazon.awssdk.testutils.service.S3BucketUtils.temporaryBucketName;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.stream.Collectors;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.authcrt.signer.internal.DefaultAwsCrtS3V4aSigner;
import software.amazon.awssdk.core.HttpChecksumConstant;
import software.amazon.awssdk.core.ResponseInputStream;
import software.amazon.awssdk.core.checksums.Algorithm;
import software.amazon.awssdk.core.checksums.ChecksumValidation;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.S3Client;
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.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.S3Exception;
import software.amazon.awssdk.services.s3.utils.CaptureChecksumValidationInterceptor;
import software.amazon.awssdk.services.s3.utils.ChecksumUtils;
import software.amazon.awssdk.testutils.RandomTempFile;
public class HttpChecksumIntegrationTest extends S3IntegrationTestBase {
public static final int HUGE_MSG_SIZE = 1600 * KB;
protected static final String KEY = "some-key";
private static final String BUCKET = temporaryBucketName(HttpChecksumIntegrationTest.class);
public static CaptureChecksumValidationInterceptor interceptor = new CaptureChecksumValidationInterceptor();
protected static S3Client s3Https;
protected static S3AsyncClient s3HttpAsync;
@BeforeAll
public static void setUp() throws Exception {
// Http Client to generate Signed request
s3 = s3ClientBuilder().overrideConfiguration(o -> o.addExecutionInterceptor(interceptor))
.endpointOverride(URI.create("http://s3." + DEFAULT_REGION + ".amazonaws.com")).build();
s3Async = s3AsyncClientBuilder().overrideConfiguration(o -> o.addExecutionInterceptor(interceptor)).build();
s3Https = s3ClientBuilder().overrideConfiguration(o -> o.addExecutionInterceptor(interceptor)).build();
// Http Client to generate Signed request
s3HttpAsync = s3AsyncClientBuilder().overrideConfiguration(o -> o.addExecutionInterceptor(interceptor))
.endpointOverride(URI.create("http://s3." + DEFAULT_REGION + ".amazonaws.com")).build();
createBucket(BUCKET);
s3.waiter().waitUntilBucketExists(s ->s.bucket(BUCKET));
interceptor.reset();
}
@AfterAll
public static void tearDown() {
deleteBucketAndAllContents(BUCKET);
}
@AfterEach
public void clear() {
interceptor.reset();
}
@Test
public void validHeaderChecksumCalculatedBySdkClient() {
PutObjectResponse putObjectResponse = s3Https.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.checksumAlgorithm(ChecksumAlgorithm.CRC32)
.key(KEY)
.build(), RequestBody.fromString("Hello world"));
assertThat(interceptor.requestChecksumInTrailer()).isEqualTo("x-amz-checksum-crc32");
assertThat(interceptor.contentEncoding()).isEqualTo(HttpChecksumConstant.AWS_CHUNKED_HEADER);
assertThat(interceptor.requestChecksumInHeader()).isNull();
assertThat(putObjectResponse.sdkHttpResponse().firstMatchingHeader("x-amz-checksum-crc32"))
.hasValue("i9aeUg==");
}
@Test
public void validHeaderChecksumSentDirectlyInTheField() {
PutObjectResponse putObjectResponse = s3Https.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.checksumAlgorithm(ChecksumAlgorithm.CRC32)
.contentEncoding("gzip")
.checksumCRC32("i9aeUg==")
.key(KEY)
.build(), RequestBody.fromString("Hello world"));
assertThat(interceptor.requestChecksumInHeader()).isEqualTo("i9aeUg==");
assertThat(interceptor.requestChecksumInTrailer()).isNull();
assertThat(interceptor.contentEncoding()).isEqualTo("gzip");
assertThat(putObjectResponse.sdkHttpResponse().firstMatchingHeader("x-amz-checksum-crc32")).hasValue("i9aeUg==");
}
@Test
public void validHeaderChecksumSentDirectlyInTheFieldAndFeatureEnabled() {
PutObjectResponse putObjectResponse = s3Https.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.checksumAlgorithm(ChecksumAlgorithm.CRC32)
.checksumCRC32("i9aeUg==")
.key(KEY)
.build(), RequestBody.fromString("Hello world"));
assertThat(interceptor.requestChecksumInHeader()).isEqualTo("i9aeUg==");
assertThat(interceptor.requestChecksumInTrailer()).isNull();
assertThat(putObjectResponse.sdkHttpResponse().firstMatchingHeader("x-amz-checksum-crc32")).hasValue("i9aeUg==");
}
@Test
public void invalidHeaderChecksumCalculatedByUserNotOverWrittenBySdkClient() {
assertThatExceptionOfType(S3Exception.class).isThrownBy(
() -> s3Https.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.checksumCRC32("i9aeUgg=")
.key(KEY)
.build(),
RequestBody.fromString("Hello world")))
.withMessageContaining("Value for x-amz-checksum-crc32 header is invalid");
}
@Test
public void syncValidUnsignedTrailerChecksumCalculatedBySdkClient() throws InterruptedException {
s3Https.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(KEY)
.checksumAlgorithm(ChecksumAlgorithm.CRC32)
.build(), RequestBody.fromString("Hello world"));
assertThat(interceptor.requestChecksumInTrailer()).isEqualTo("x-amz-checksum-crc32");
assertThat(interceptor.requestChecksumInHeader()).isNull();
ResponseInputStream<GetObjectResponse> s3HttpsObject =
s3Https.getObject(GetObjectRequest.builder().bucket(BUCKET).key(KEY).checksumMode(ChecksumMode.ENABLED).build());
String text = new BufferedReader(
new InputStreamReader(s3HttpsObject, StandardCharsets.UTF_8))
.lines()
.collect(Collectors.joining("\n"));
assertThat(interceptor.validationAlgorithm()).isEqualTo(Algorithm.CRC32);
assertThat(interceptor.responseValidation()).isEqualTo(ChecksumValidation.VALIDATED);
assertThat(text).isEqualTo("Hello world");
}
@Test
public void syncValidSignedTrailerChecksumCalculatedBySdkClient() {
s3.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(KEY)
.checksumAlgorithm(ChecksumAlgorithm.CRC32)
.build(), RequestBody.fromString("Hello world"));
assertThat(interceptor.requestChecksumInTrailer()).isEqualTo("x-amz-checksum-crc32");
assertThat(interceptor.requestChecksumInHeader()).isNull();
ResponseInputStream<GetObjectResponse> s3HttpsObject =
s3.getObject(GetObjectRequest.builder()
.bucket(BUCKET)
.key(KEY)
.checksumMode(ChecksumMode.ENABLED)
.build());
String text = new BufferedReader(
new InputStreamReader(s3HttpsObject, StandardCharsets.UTF_8))
.lines()
.collect(Collectors.joining("\n"));
assertThat(interceptor.contentEncoding()).isEmpty();
assertThat(interceptor.validationAlgorithm()).isEqualTo(Algorithm.CRC32);
assertThat(interceptor.responseValidation()).isEqualTo(ChecksumValidation.VALIDATED);
assertThat(text).isEqualTo("Hello world");
}
@Test
public void syncValidSignedTrailerChecksumCalculatedBySdkClient_Empty_String() {
s3.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(KEY)
.contentEncoding("gzip")
.checksumAlgorithm(ChecksumAlgorithm.CRC32)
.build(), RequestBody.fromString(""));
assertThat(interceptor.requestChecksumInTrailer()).isEqualTo("x-amz-checksum-crc32");
assertThat(interceptor.contentEncoding()).isEqualTo("gzip,aws-chunked");
assertThat(interceptor.requestChecksumInHeader()).isNull();
ResponseInputStream<GetObjectResponse> s3HttpsObject =
s3.getObject(GetObjectRequest.builder().bucket(BUCKET).key(KEY).checksumMode(ChecksumMode.ENABLED).build());
String text = new BufferedReader(
new InputStreamReader(s3HttpsObject, StandardCharsets.UTF_8))
.lines()
.collect(Collectors.joining("\n"));
assertThat(interceptor.validationAlgorithm()).isEqualTo(Algorithm.CRC32);
assertThat(interceptor.responseValidation()).isEqualTo(ChecksumValidation.VALIDATED);
assertThat(text).isEqualTo("");
}
@Test
public void syncValidSignedTrailerChecksumCalculatedBySdkClientWithSigv4a() {
s3.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(KEY)
.checksumAlgorithm(ChecksumAlgorithm.CRC32)
.overrideConfiguration(o -> o.signer(DefaultAwsCrtS3V4aSigner.create()))
.build(), RequestBody.fromString("Hello world"));
assertThat(interceptor.requestChecksumInTrailer()).isEqualTo("x-amz-checksum-crc32");
assertThat(interceptor.requestChecksumInHeader()).isNull();
ResponseInputStream<GetObjectResponse> s3HttpsObject =
s3.getObject(GetObjectRequest.builder().bucket(BUCKET).key(KEY).checksumMode(ChecksumMode.ENABLED).build());
String text = new BufferedReader(
new InputStreamReader(s3HttpsObject, StandardCharsets.UTF_8))
.lines()
.collect(Collectors.joining("\n"));
assertThat(interceptor.validationAlgorithm()).isEqualTo(Algorithm.CRC32);
assertThat(interceptor.responseValidation()).isEqualTo(ChecksumValidation.VALIDATED);
assertThat(text).isEqualTo("Hello world");
}
@Test
public void syncValidSignedTrailerChecksumCalculatedBySdkClientWithSigv4a_withContentEncoding() {
s3.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(KEY)
.checksumAlgorithm(ChecksumAlgorithm.CRC32)
.contentEncoding("gzip")
.overrideConfiguration(o -> o.signer(DefaultAwsCrtS3V4aSigner.create()))
.build(), RequestBody.fromString("Hello world"));
assertThat(interceptor.requestChecksumInTrailer()).isEqualTo("x-amz-checksum-crc32");
assertThat(interceptor.contentEncoding()).isEqualTo("gzip,aws-chunked");
assertThat(interceptor.requestChecksumInHeader()).isNull();
ResponseInputStream<GetObjectResponse> s3HttpsObject =
s3.getObject(GetObjectRequest.builder().bucket(BUCKET).key(KEY).checksumMode(ChecksumMode.ENABLED).build());
String text = new BufferedReader(
new InputStreamReader(s3HttpsObject, StandardCharsets.UTF_8))
.lines()
.collect(Collectors.joining("\n"));
assertThat(interceptor.validationAlgorithm()).isEqualTo(Algorithm.CRC32);
assertThat(interceptor.responseValidation()).isEqualTo(ChecksumValidation.VALIDATED);
assertThat(text).isEqualTo("Hello world");
}
@Test
public void syncUnsignedPayloadForHugeMessage() throws InterruptedException {
s3Https.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(KEY)
.checksumAlgorithm(ChecksumAlgorithm.CRC32)
.contentEncoding("gzip")
.build(), RequestBody.fromString(createDataOfSize(HUGE_MSG_SIZE, 'a')));
assertThat(interceptor.requestChecksumInTrailer()).isEqualTo("x-amz-checksum-crc32");
assertThat(interceptor.contentEncoding()).isEqualTo("gzip,aws-chunked");
assertThat(interceptor.requestChecksumInHeader()).isNull();
Thread.sleep(1000);
ResponseInputStream<GetObjectResponse> s3HttpsObject = s3Https.getObject(
GetObjectRequest.builder()
.bucket(BUCKET)
.checksumMode(ChecksumMode.ENABLED)
.key(KEY)
.build());
String text = new BufferedReader(
new InputStreamReader(s3HttpsObject, StandardCharsets.UTF_8))
.lines()
.collect(Collectors.joining("\n"));
assertThat(interceptor.validationAlgorithm()).isEqualTo(Algorithm.CRC32);
assertThat(interceptor.responseValidation()).isEqualTo(ChecksumValidation.VALIDATED);
assertThat(text).isEqualTo(createDataOfSize(HUGE_MSG_SIZE, 'a'));
}
@Test
public void syncSignedPayloadForHugeMessage() {
s3.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(KEY)
.checksumAlgorithm(ChecksumAlgorithm.CRC32)
.build(), RequestBody.fromString(createDataOfSize(HUGE_MSG_SIZE, 'a')));
assertThat(interceptor.requestChecksumInTrailer()).isEqualTo("x-amz-checksum-crc32");
assertThat(interceptor.requestChecksumInHeader()).isNull();
ResponseInputStream<GetObjectResponse> s3HttpsObject = s3.getObject(
GetObjectRequest.builder()
.bucket(BUCKET)
.checksumMode(ChecksumMode.ENABLED)
.key(KEY)
.build());
String text = new BufferedReader(
new InputStreamReader(s3HttpsObject, StandardCharsets.UTF_8))
.lines()
.collect(Collectors.joining("\n"));
assertThat(interceptor.validationAlgorithm()).isEqualTo(Algorithm.CRC32);
assertThat(interceptor.responseValidation()).isEqualTo(ChecksumValidation.VALIDATED);
assertThat(text).isEqualTo(createDataOfSize(HUGE_MSG_SIZE, 'a'));
}
@Test
public void syncUnsignedPayloadMultiPartForHugeMessage() throws InterruptedException {
s3Https.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(KEY)
.checksumAlgorithm(ChecksumAlgorithm.CRC32)
.build(), RequestBody.fromString(createDataOfSize(HUGE_MSG_SIZE, 'a')));
assertThat(interceptor.requestChecksumInTrailer()).isEqualTo("x-amz-checksum-crc32");
assertThat(interceptor.requestChecksumInHeader()).isNull();
ResponseInputStream<GetObjectResponse> s3HttpsObject = s3Https.getObject(
GetObjectRequest.builder()
.bucket(BUCKET)
.key(KEY)
.build());
String text = new BufferedReader(
new InputStreamReader(s3HttpsObject, StandardCharsets.UTF_8))
.lines()
.collect(Collectors.joining("\n"));
assertThat(interceptor.validationAlgorithm()).isNull();
assertThat(interceptor.responseValidation()).isNull();
assertThat(text).isEqualTo(createDataOfSize(HUGE_MSG_SIZE, 'a'));
}
@Test
public void syncValidUnsignedTrailerChecksumCalculatedBySdkClient_withSmallFileRequestBody() throws InterruptedException,
IOException {
File randomFileOfFixedLength = new RandomTempFile(10 * KB);
s3Https.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(KEY)
.checksumAlgorithm(ChecksumAlgorithm.CRC32)
.build(), RequestBody.fromFile(randomFileOfFixedLength.toPath()));
assertThat(interceptor.requestChecksumInTrailer()).isEqualTo("x-amz-checksum-crc32");
assertThat(interceptor.requestChecksumInHeader()).isNull();
ResponseInputStream<GetObjectResponse> s3HttpsObject =
s3Https.getObject(GetObjectRequest.builder().bucket(BUCKET).key(KEY).checksumMode(ChecksumMode.ENABLED).build());
String text = new BufferedReader(
new InputStreamReader(s3HttpsObject, StandardCharsets.UTF_8))
.lines()
.collect(Collectors.joining("\n"));
assertThat(interceptor.validationAlgorithm()).isEqualTo(Algorithm.CRC32);
assertThat(interceptor.responseValidation()).isEqualTo(ChecksumValidation.VALIDATED);
byte[] bytes = Files.readAllBytes(randomFileOfFixedLength.toPath());
assertThat(text).isEqualTo(new String(bytes));
}
@Test
public void syncValidUnsignedTrailerChecksumCalculatedBySdkClient_withHugeFileRequestBody() throws IOException {
File randomFileOfFixedLength = new RandomTempFile(34 * KB);
s3Https.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(KEY)
.checksumAlgorithm(ChecksumAlgorithm.CRC32)
.build(), RequestBody.fromFile(randomFileOfFixedLength.toPath()));
assertThat(interceptor.requestChecksumInTrailer()).isEqualTo("x-amz-checksum-crc32");
assertThat(interceptor.requestChecksumInHeader()).isNull();
ResponseInputStream<GetObjectResponse> s3HttpsObject =
s3Https.getObject(GetObjectRequest.builder().bucket(BUCKET).key(KEY).checksumMode(ChecksumMode.ENABLED).build());
String text = new BufferedReader(
new InputStreamReader(s3HttpsObject, StandardCharsets.UTF_8))
.lines()
.collect(Collectors.joining("\n"));
assertThat(interceptor.validationAlgorithm()).isEqualTo(Algorithm.CRC32);
assertThat(interceptor.responseValidation()).isEqualTo(ChecksumValidation.VALIDATED);
byte[] bytes = Files.readAllBytes(randomFileOfFixedLength.toPath());
assertThat(text).isEqualTo(new String(bytes));
}
}
| 4,523 |
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/checksum/AsyncHttpChecksumIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.checksum;
import static org.assertj.core.api.Assertions.assertThat;
import static software.amazon.awssdk.services.s3.utils.ChecksumUtils.KB;
import static software.amazon.awssdk.services.s3.utils.ChecksumUtils.createDataOfSize;
import static software.amazon.awssdk.testutils.service.S3BucketUtils.temporaryBucketName;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.util.concurrent.CompletableFuture;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import software.amazon.awssdk.auth.signer.S3SignerExecutionAttribute;
import software.amazon.awssdk.authcrt.signer.internal.DefaultAwsCrtS3V4aSigner;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.core.async.AsyncResponseTransformer;
import software.amazon.awssdk.core.checksums.Algorithm;
import software.amazon.awssdk.core.checksums.ChecksumValidation;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.internal.async.FileAsyncRequestBody;
import software.amazon.awssdk.services.s3.S3AsyncClient;
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.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.PutObjectResponse;
import software.amazon.awssdk.services.s3.utils.CaptureChecksumValidationInterceptor;
import software.amazon.awssdk.testutils.RandomTempFile;
public class AsyncHttpChecksumIntegrationTest extends S3IntegrationTestBase {
protected static final String KEY = "some-key";
private static final String BUCKET = temporaryBucketName(AsyncHttpChecksumIntegrationTest.class);
public static CaptureChecksumValidationInterceptor interceptor = new CaptureChecksumValidationInterceptor();
protected static S3AsyncClient s3HttpAsync;
@BeforeAll
public static void setUp() throws Exception {
s3 = s3ClientBuilder().build();
s3Async = s3AsyncClientBuilder().overrideConfiguration(o -> o.addExecutionInterceptor(interceptor)).build();
// Http Client to generate Signed request
s3HttpAsync = s3AsyncClientBuilder().overrideConfiguration(o -> o.addExecutionInterceptor(interceptor))
.endpointOverride(URI.create("http://s3." + DEFAULT_REGION + ".amazonaws.com")).build();
createBucket(BUCKET);
s3.waiter().waitUntilBucketExists(s -> s.bucket(BUCKET));
interceptor.reset();
}
@AfterEach
public void clear() {
interceptor.reset();
}
@AfterAll
public static void tearDown() {
deleteBucketAndAllContents(BUCKET);
}
@Test
void asyncValidUnsignedTrailerChecksumCalculatedBySdkClient() {
s3Async.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(KEY)
.overrideConfiguration(o -> o.signer(DefaultAwsCrtS3V4aSigner.create()))
.checksumAlgorithm(ChecksumAlgorithm.CRC32)
.build(), AsyncRequestBody.fromString("Hello world")).join();
assertThat(interceptor.requestChecksumInTrailer()).isEqualTo("x-amz-checksum-crc32");
assertThat(interceptor.requestChecksumInHeader()).isNull();
String response = s3Async.getObject(GetObjectRequest.builder().bucket(BUCKET)
.key(KEY).checksumMode(ChecksumMode.ENABLED)
.build(), AsyncResponseTransformer.toBytes()).join().asUtf8String();
assertThat(interceptor.validationAlgorithm()).isEqualTo(Algorithm.CRC32);
assertThat(interceptor.responseValidation()).isEqualTo(ChecksumValidation.VALIDATED);
assertThat(response).isEqualTo("Hello world");
}
@Test
void asyncHttpsValidUnsignedTrailerChecksumCalculatedBySdkClient_withSmallRequestBody() throws InterruptedException {
s3Async.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(KEY)
.checksumAlgorithm(ChecksumAlgorithm.CRC32)
.build(), AsyncRequestBody.fromString("Hello world")).join();
assertThat(interceptor.requestChecksumInTrailer()).isEqualTo("x-amz-checksum-crc32");
assertThat(interceptor.requestChecksumInHeader()).isNull();
assertThat(interceptor.contentEncoding()).isEqualTo("aws-chunked");
String response = s3Async.getObject(GetObjectRequest.builder().bucket(BUCKET)
.key(KEY).checksumMode(ChecksumMode.ENABLED)
.build(), AsyncResponseTransformer.toBytes()).join().asUtf8String();
assertThat(interceptor.validationAlgorithm()).isEqualTo(Algorithm.CRC32);
assertThat(interceptor.responseValidation()).isEqualTo(ChecksumValidation.VALIDATED);
assertThat(response).isEqualTo("Hello world");
}
@ParameterizedTest
@ValueSource(ints = {1 * KB, 3 * KB, 12 * KB, 16 * KB, 17 * KB, 32 * KB, 33 * KB})
void asyncHttpsValidUnsignedTrailerChecksumCalculatedBySdkClient_withHugeRequestBody(int dataSize) throws InterruptedException {
s3Async.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(KEY)
.contentEncoding("gzip")
.checksumAlgorithm(ChecksumAlgorithm.CRC32)
.build(), AsyncRequestBody.fromString(createDataOfSize(64 * KB, 'a'))).join();
assertThat(interceptor.requestChecksumInTrailer()).isEqualTo("x-amz-checksum-crc32");
assertThat(interceptor.requestChecksumInHeader()).isNull();
assertThat(interceptor.contentEncoding()).isEqualTo("gzip,aws-chunked");
String response = s3Async.getObject(GetObjectRequest.builder().bucket(BUCKET)
.key(KEY).checksumMode(ChecksumMode.ENABLED)
.build(), AsyncResponseTransformer.toBytes()).join().asUtf8String();
assertThat(interceptor.validationAlgorithm()).isEqualTo(Algorithm.CRC32);
assertThat(interceptor.responseValidation()).isEqualTo(ChecksumValidation.VALIDATED);
assertThat(response).isEqualTo(createDataOfSize(64 * KB, 'a'));
}
@ParameterizedTest
@ValueSource(ints = {1 * KB, 12 * KB, 16 * KB, 17 * KB, 32 * KB, 33 * KB, 65 * KB})
void asyncHttpsValidUnsignedTrailerChecksumCalculatedBySdkClient_withDifferentChunkSize_OfFileAsyncFileRequestBody
(int chunkSize) throws IOException {
File randomFileOfFixedLength = new RandomTempFile(32 * KB + 23);
s3Async.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(KEY)
.checksumAlgorithm(ChecksumAlgorithm.CRC32)
.build(), FileAsyncRequestBody.builder().path(randomFileOfFixedLength.toPath())
.chunkSizeInBytes(chunkSize)
.build()).join();
assertThat(interceptor.requestChecksumInTrailer()).isEqualTo("x-amz-checksum-crc32");
assertThat(interceptor.requestChecksumInHeader()).isNull();
String response = s3Async.getObject(GetObjectRequest.builder().bucket(BUCKET)
.key(KEY).checksumMode(ChecksumMode.ENABLED)
.build(), AsyncResponseTransformer.toBytes()).join().asUtf8String();
assertThat(interceptor.validationAlgorithm()).isEqualTo(Algorithm.CRC32);
assertThat(interceptor.responseValidation()).isEqualTo(ChecksumValidation.VALIDATED);
byte[] bytes = Files.readAllBytes(randomFileOfFixedLength.toPath());
assertThat(response).isEqualTo(new String(bytes));
}
/**
* Test two async call made back to back with different sizes parameterized to test for different chunk sizes
*/
@ParameterizedTest
@ValueSource(ints = {1 * KB, 12 * KB, 16 * KB, 17 * KB, 32 * KB, 33 * KB})
void asyncHttpsValidUnsignedTrailer_TwoRequests_withDifferentChunkSize_OfFileAsyncFileRequestBody(int chunkSize)
throws IOException {
File randomFileOfFixedLengthOne = new RandomTempFile(64 * KB);
File randomFileOfFixedLengthTwo = new RandomTempFile(17 * KB);
CompletableFuture<PutObjectResponse> putObjectFutureOne =
s3Async.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(KEY)
.checksumAlgorithm(ChecksumAlgorithm.CRC32)
.build(),
FileAsyncRequestBody.builder().path(randomFileOfFixedLengthOne.toPath()).chunkSizeInBytes(chunkSize).build());
String keyTwo = KEY + "_two";
CompletableFuture<PutObjectResponse> putObjectFutureTwo =
s3Async.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(keyTwo)
.checksumAlgorithm(ChecksumAlgorithm.CRC32)
.build(),
FileAsyncRequestBody.builder().path(randomFileOfFixedLengthTwo.toPath()).chunkSizeInBytes(chunkSize).build());
putObjectFutureOne.join();
putObjectFutureTwo.join();
assertThat(interceptor.requestChecksumInTrailer()).isEqualTo("x-amz-checksum-crc32");
assertThat(interceptor.requestChecksumInHeader()).isNull();
String response = s3Async.getObject(GetObjectRequest.builder().bucket(BUCKET)
.key(KEY).checksumMode(ChecksumMode.ENABLED)
.build(), AsyncResponseTransformer.toBytes()).join().asUtf8String();
String responseTwo = s3Async.getObject(GetObjectRequest.builder().bucket(BUCKET)
.key(keyTwo).checksumMode(ChecksumMode.ENABLED)
.build(), AsyncResponseTransformer.toBytes()).join().asUtf8String();
assertThat(interceptor.validationAlgorithm()).isEqualTo(Algorithm.CRC32);
assertThat(interceptor.responseValidation()).isEqualTo(ChecksumValidation.VALIDATED);
assertThat(response).isEqualTo(new String(Files.readAllBytes(randomFileOfFixedLengthOne.toPath())));
assertThat(responseTwo).isEqualTo(new String(Files.readAllBytes(randomFileOfFixedLengthTwo.toPath())));
}
@Disabled("Http Async Signing is not supported for S3")
void asyncValidSignedTrailerChecksumCalculatedBySdkClient() {
ExecutionAttributes executionAttributes = ExecutionAttributes.builder()
.put(S3SignerExecutionAttribute.ENABLE_PAYLOAD_SIGNING,
true).build();
s3HttpAsync.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.overrideConfiguration(o -> o.executionAttributes(executionAttributes))
.key(KEY)
.build(), AsyncRequestBody.fromString("Hello world")).join();
String response = s3HttpAsync.getObject(GetObjectRequest.builder().bucket(BUCKET)
.key(KEY)
.build(), AsyncResponseTransformer.toBytes()).join()
.asUtf8String();
assertThat(response).isEqualTo("Hello world");
}
/**
* S3 clients by default don't do payload signing. But when http is used, payload signing is expected to be enforced. But
* payload signing is not currently supported in async path (for both pre/post SRA signers).
* However, this test passes, because of https://github
* .com/aws/aws-sdk-java-v2/blob/38e221bd815af31a6c6b91557499af155103c21a/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal/AbstractAwsS3V4Signer.java#L279-L285.
* Keeping this test enabled, to ensure moving to SRA Identity & Auth, does not break current behavior.
* TODO: Update this test with right asserts when payload signing is supported in async.
*/
@Test
public void putObject_with_bufferCreatedFromEmptyString() {
s3HttpAsync.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(KEY)
.checksumAlgorithm(ChecksumAlgorithm.CRC32)
.build(), AsyncRequestBody.fromString(""))
.join();
assertThat(interceptor.requestChecksumInTrailer()).isEqualTo("x-amz-checksum-crc32");
String response = s3HttpAsync.getObject(GetObjectRequest.builder().bucket(BUCKET)
.key(KEY)
.checksumMode(ChecksumMode.ENABLED)
.build(), AsyncResponseTransformer.toBytes()).join()
.asUtf8String();
assertThat(interceptor.responseValidation()).isEqualTo(ChecksumValidation.VALIDATED);
assertThat(response).isEqualTo("");
}
/**
* S3 clients by default don't do payload signing. But when http is used, payload signing is expected to be enforced. But
* payload signing is not currently supported in async path (for both pre/post SRA signers).
* However, this test passes, because of https://github
* .com/aws/aws-sdk-java-v2/blob/38e221bd815af31a6c6b91557499af155103c21a/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal/AbstractAwsS3V4Signer.java#L279-L285.
* Keeping this test enabled, to ensure moving to SRA Identity & Auth, does not break current behavior.
* TODO: Update this test with right asserts when payload signing is supported in async.
*/
@Test
public void putObject_with_bufferCreatedFromZeroCapacityByteBuffer() {
ByteBuffer content = ByteBuffer.allocate(0);
s3HttpAsync.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(KEY)
.checksumAlgorithm(ChecksumAlgorithm.CRC32)
.build(), AsyncRequestBody.fromByteBuffer(content))
.join();
assertThat(interceptor.requestChecksumInTrailer()).isEqualTo("x-amz-checksum-crc32");
String response = s3HttpAsync.getObject(GetObjectRequest.builder().bucket(BUCKET)
.key(KEY)
.checksumMode(ChecksumMode.ENABLED)
.build(), AsyncResponseTransformer.toBytes()).join()
.asUtf8String();
assertThat(interceptor.responseValidation()).isEqualTo(ChecksumValidation.VALIDATED);
assertThat(response).isEqualTo("");
}
}
| 4,524 |
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/S3CrossRegionAsyncIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 software.amazon.awssdk.services.s3.S3AsyncClient;
public class S3CrossRegionAsyncIntegrationTest extends S3CrossRegionAsyncIntegrationTestBase {
private static final String BUCKET = temporaryBucketName(S3CrossRegionAsyncIntegrationTest.class);
@BeforeAll
static void setUpClass() {
s3 = s3ClientBuilder().build();
createBucket(BUCKET);
}
@AfterAll
static void clearClass() {
deleteBucketAndAllContents(BUCKET);
}
@BeforeEach
public void initialize() {
crossRegionS3Client = S3AsyncClient.builder()
.region(CROSS_REGION)
.crossRegionAccessEnabled(true)
.build();
}
@Override
protected String bucketName() {
return BUCKET;
}
}
| 4,525 |
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/S3CrossRegionSyncIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import software.amazon.awssdk.core.ResponseBytes;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.core.sync.ResponseTransformer;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
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.ListObjectsV2Response;
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 class S3CrossRegionSyncIntegrationTest extends S3CrossRegionIntegrationTestBase {
private static final String BUCKET = temporaryBucketName(S3CrossRegionSyncIntegrationTest.class);
private S3Client crossRegionS3Client;
@BeforeAll
static void setUpClass() {
s3 = s3ClientBuilder().build();
createBucket(BUCKET);
}
@AfterAll
static void clearClass() {
deleteBucketAndAllContents(BUCKET);
}
@BeforeEach
public void initialize() {
crossRegionS3Client = S3Client.builder()
.region(Region.US_EAST_1)
.crossRegionAccessEnabled(true)
.build();
}
@Override
protected List<S3Object> paginatedAPICall(ListObjectsV2Request listObjectsV2Request) {
List<S3Object> resultS3Object = new ArrayList<>();
Iterator<ListObjectsV2Response> v2ResponseIterator =
crossRegionS3Client.listObjectsV2Paginator(listObjectsV2Request).iterator();
while (v2ResponseIterator.hasNext()) {
v2ResponseIterator.next().contents().forEach(a -> resultS3Object.add(a));
}
return resultS3Object;
}
@Override
protected DeleteObjectsResponse postObjectAPICall(DeleteObjectsRequest deleteObjectsRequest) {
return crossRegionS3Client.deleteObjects(deleteObjectsRequest);
}
@Override
protected HeadBucketResponse headAPICall(HeadBucketRequest headBucketRequest) {
return crossRegionS3Client.headBucket(headBucketRequest);
}
@Override
protected DeleteObjectResponse deleteObjectAPICall(DeleteObjectRequest deleteObjectRequest) {
return crossRegionS3Client.deleteObject(deleteObjectRequest);
}
@Override
protected PutObjectResponse putAPICall(PutObjectRequest putObjectRequest, String testString) {
return crossRegionS3Client.putObject(putObjectRequest, RequestBody.fromString(testString));
}
@Override
protected ResponseBytes<GetObjectResponse> getAPICall(GetObjectRequest getObjectRequest) {
return crossRegionS3Client.getObject(getObjectRequest, ResponseTransformer.toBytes());
}
@Override
protected String bucketName() {
return BUCKET;
}
}
| 4,526 |
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,527 |
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,528 |
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,529 |
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,530 |
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,531 |
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,532 |
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,533 |
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,534 |
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,535 |
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,536 |
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,537 |
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,538 |
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,539 |
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,540 |
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,541 |
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,542 |
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,543 |
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,544 |
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,545 |
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,546 |
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,547 |
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,548 |
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,549 |
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,550 |
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,551 |
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,552 |
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,553 |
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,554 |
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,555 |
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,556 |
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,557 |
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,558 |
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,559 |
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,560 |
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,561 |
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,562 |
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,563 |
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,564 |
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,565 |
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,566 |
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,567 |
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,568 |
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,569 |
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,570 |
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,571 |
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,572 |
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,573 |
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,574 |
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,575 |
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,576 |
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,577 |
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,578 |
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,579 |
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,580 |
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,581 |
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,582 |
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,583 |
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,584 |
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,585 |
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,586 |
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,587 |
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,588 |
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,589 |
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,590 |
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,591 |
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,592 |
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,593 |
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,594 |
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,595 |
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,596 |
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,597 |
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,598 |
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,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.