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/test/java/software/amazon/awssdk/services/s3/internal | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal/endpoints/UseGlobalEndpointResolverProfileFileTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 static org.assertj.core.api.Assertions.assertThat;
import java.util.function.Supplier;
import org.junit.jupiter.api.Test;
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.regions.Region;
import software.amazon.awssdk.regions.ServiceMetadataAdvancedOption;
import software.amazon.awssdk.utils.StringInputStream;
class UseGlobalEndpointResolverProfileFileTest {
@Test
void resolve_nonUsEast1_resolvesToFalse() {
SdkClientConfiguration config = SdkClientConfiguration.builder().build();
UseGlobalEndpointResolver resolver = new UseGlobalEndpointResolver(config);
assertThat(resolver.resolve(Region.AF_SOUTH_1)).isFalse();
}
@Test
void resolve_nullProfileFileSupplierAndNullDefaultRegionalEndpoint_resolvesToTrue() {
SdkClientConfiguration config = SdkClientConfiguration
.builder()
.option(SdkClientOption.PROFILE_FILE_SUPPLIER, null)
.option(SdkClientOption.PROFILE_NAME, "regional_s3_endpoint")
.build();
UseGlobalEndpointResolver resolver = new UseGlobalEndpointResolver(config);
assertThat(resolver.resolve(Region.US_EAST_1)).isTrue();
}
@Test
void resolve_nullProfileFileSupplierAndDefaultRegionalEndPointLegacy_resolvesToTrue() {
SdkClientConfiguration config = SdkClientConfiguration
.builder()
.option(ServiceMetadataAdvancedOption.DEFAULT_S3_US_EAST_1_REGIONAL_ENDPOINT, "legacy")
.option(SdkClientOption.PROFILE_FILE_SUPPLIER, null)
.option(SdkClientOption.PROFILE_NAME, "regional_s3_endpoint")
.build();
UseGlobalEndpointResolver resolver = new UseGlobalEndpointResolver(config);
assertThat(resolver.resolve(Region.US_EAST_1)).isTrue();
}
@Test
void resolve_nullProfileFileSupplierAndDefaultRegionalEndPointRegional_resolvesToFalse() {
SdkClientConfiguration config = SdkClientConfiguration
.builder()
.option(ServiceMetadataAdvancedOption.DEFAULT_S3_US_EAST_1_REGIONAL_ENDPOINT, "regional")
.option(SdkClientOption.PROFILE_FILE_SUPPLIER, null)
.option(SdkClientOption.PROFILE_NAME, "regional_s3_endpoint")
.build();
UseGlobalEndpointResolver resolver = new UseGlobalEndpointResolver(config);
assertThat(resolver.resolve(Region.US_EAST_1)).isFalse();
}
@Test
void resolve_nullProfileFileSupplier_resolvesToTrue() {
Supplier<ProfileFile> supplier = null;
SdkClientConfiguration config = SdkClientConfiguration
.builder()
.option(SdkClientOption.PROFILE_FILE_SUPPLIER, supplier)
.option(SdkClientOption.PROFILE_NAME, "regional_s3_endpoint")
.build();
UseGlobalEndpointResolver resolver = new UseGlobalEndpointResolver(config);
assertThat(resolver.resolve(Region.US_EAST_1)).isTrue();
}
@Test
void resolve_profileFileSupplierRegionalEndpointLegacy_resolvesToTrue() {
ProfileFile file = configuration("[profile regional_s3_endpoint]\n"
+ "s3_us_east_1_regional_endpoint = legacy");
Supplier<ProfileFile> supplier = () -> file;
SdkClientConfiguration config = SdkClientConfiguration
.builder()
.option(SdkClientOption.PROFILE_FILE_SUPPLIER, supplier)
.option(SdkClientOption.PROFILE_NAME, "regional_s3_endpoint")
.build();
UseGlobalEndpointResolver resolver = new UseGlobalEndpointResolver(config);
assertThat(resolver.resolve(Region.US_EAST_1)).isTrue();
}
@Test
void resolve_profileFileSupplierRegionalEndpointRegional_resolvesToFalse() {
ProfileFile file = configuration("[profile regional_s3_endpoint]\n"
+ "s3_us_east_1_regional_endpoint = regional");
Supplier<ProfileFile> supplier = () -> file;
SdkClientConfiguration config = SdkClientConfiguration
.builder()
.option(SdkClientOption.PROFILE_FILE_SUPPLIER, supplier)
.option(SdkClientOption.PROFILE_NAME, "regional_s3_endpoint")
.build();
UseGlobalEndpointResolver resolver = new UseGlobalEndpointResolver(config);
assertThat(resolver.resolve(Region.US_EAST_1)).isFalse();
}
private ProfileFile configuration(String string) {
return ProfileFile.builder()
.content(new StringInputStream(string))
.type(ProfileFile.Type.CONFIGURATION)
.build();
}
}
| 4,400 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal/endpoints/UseGlobalEndpointResolverTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 static org.assertj.core.api.Assertions.assertThat;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collection;
import java.util.function.Supplier;
import org.apache.hc.core5.http.Chars;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
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.regions.Region;
import software.amazon.awssdk.regions.ServiceMetadataAdvancedOption;
import software.amazon.awssdk.testutils.EnvironmentVariableHelper;
import software.amazon.awssdk.utils.StringInputStream;
import software.amazon.awssdk.utils.Validate;
@RunWith(Parameterized.class)
public class UseGlobalEndpointResolverTest {
private static final EnvironmentVariableHelper ENVIRONMENT_VARIABLE_HELPER = new EnvironmentVariableHelper();
@Parameterized.Parameter
public TestData testData;
@Parameterized.Parameters
public static Collection<Object> data() {
return Arrays.asList(new Object[] {
// Test defaults
new TestData(null, null, null, null, true),
// Test precedence
new TestData("regional", null, null, null, false),
new TestData("test", "regional", "/s3_regional_config_profile.tst", "regional",
true),
new TestData(null, "regional", "/s3_regional_config_profile.tst", "non-regional",
false),
new TestData(null, null, "/s3_regional_config_profile.tst", "non-regional", false),
new TestData(null, null, null, "regional", false),
// Test capitalization standardization
new TestData("rEgIONal", null, null, null, false),
new TestData(null, "rEgIONal", null, null, false),
new TestData(null, null, "/s3_regional_config_profile_mixed_case.tst", null, false),
new TestData(null, null, null, "rEgIONal", false),
// Test other value
new TestData("othervalue", null, null, null, true),
new TestData(null, "dafsad", null, null, true),
new TestData(null, null, "/s3_regional_config_profile_non_regional.tst", null, true),
new TestData(null, null, null, "somehtingelse", true),
// Test property value is regional, but resolve region is not IAD
new TestData("regional", null, null, null, Region.US_WEST_2, false),
new TestData(null, "regional", null, null, Region.US_WEST_2, false),
new TestData(null, null, "/s3_regional_config_profile.tst", null, Region.US_WEST_2, false),
new TestData(null, null, null, "regional", Region.US_WEST_2, false),
});
}
@After
public void methodSetup() {
ENVIRONMENT_VARIABLE_HELPER.reset();
System.clearProperty(SdkSystemSetting.AWS_S3_US_EAST_1_REGIONAL_ENDPOINT.property());
}
@Test
public void differentCombinationOfConfigs_shouldResolveCorrectly() {
SdkClientConfiguration.Builder configBuilder = SdkClientConfiguration.builder();
configBuilder.option(ServiceMetadataAdvancedOption.DEFAULT_S3_US_EAST_1_REGIONAL_ENDPOINT, testData.advancedOption);
if (testData.envVarValue != null) {
ENVIRONMENT_VARIABLE_HELPER.set(SdkSystemSetting.AWS_S3_US_EAST_1_REGIONAL_ENDPOINT.environmentVariable(),
testData.envVarValue);
}
if (testData.systemProperty != null) {
System.setProperty(SdkSystemSetting.AWS_S3_US_EAST_1_REGIONAL_ENDPOINT.property(), testData.systemProperty);
}
if (testData.configFile != null) {
String diskLocationForFile = diskLocationForConfig(testData.configFile);
Validate.isTrue(Files.isReadable(Paths.get(diskLocationForFile)), diskLocationForFile + " is not readable.");
ProfileFile file = ProfileFile.builder()
.content(Paths.get(diskLocationForFile))
.type(ProfileFile.Type.CONFIGURATION)
.build();
configBuilder.option(SdkClientOption.PROFILE_FILE_SUPPLIER, () -> file)
.option(SdkClientOption.PROFILE_NAME, "regional_s3_endpoint");
}
UseGlobalEndpointResolver resolver = new UseGlobalEndpointResolver(configBuilder.build());
assertThat(resolver.resolve(Region.US_EAST_1)).isEqualTo(testData.expected);
}
private String diskLocationForConfig(String configFileName) {
return getClass().getResource(configFileName).getFile();
}
private static class TestData {
private final String envVarValue;
private final String systemProperty;
private final String configFile;
private final String advancedOption;
private final Region inputRegion;
private final boolean expected;
TestData(String systemProperty, String envVarValue, String configFile, String advancedOption, boolean expected) {
this(systemProperty, envVarValue, configFile, advancedOption, Region.US_EAST_1, expected);
}
TestData(String systemProperty, String envVarValue, String configFile, String advancedOption,
Region inputRegion, boolean expected) {
this.envVarValue = envVarValue;
this.systemProperty = systemProperty;
this.configFile = configFile;
this.advancedOption = advancedOption;
this.inputRegion = inputRegion;
this.expected = expected;
}
}
}
| 4,401 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal/endpoints/S3ObjectLambdaOperationEndpointBuilderTest.java | package software.amazon.awssdk.services.s3.internal.endpoints;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import java.net.URI;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public class S3ObjectLambdaOperationEndpointBuilderTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void toUri_buildsCorrectEndpoint() {
URI endpoint = S3ObjectLambdaOperationEndpointBuilder.create()
.domain("my-domain.com")
.protocol("https")
.region("us-west-2")
.toUri();
assertThat(endpoint.toString(), is("https://s3-object-lambda.us-west-2.my-domain.com"));
}
@Test
public void toUri_disallowsNullProtocol() {
thrown.expect(NullPointerException.class);
S3ObjectLambdaOperationEndpointBuilder.create()
.domain("my-domain.com")
.protocol(null)
.region("us-west-2")
.toUri();
}
@Test
public void toUri_disallowsEmptyProtocol() {
thrown.expect(IllegalArgumentException.class);
S3ObjectLambdaOperationEndpointBuilder.create()
.domain("my-domain.com")
.protocol("")
.region("us-west-2")
.toUri();
}
@Test
public void toUri_disallowsNullRegion() {
thrown.expect(NullPointerException.class);
S3ObjectLambdaOperationEndpointBuilder.create()
.domain("my-domain.com")
.protocol("https")
.region(null)
.toUri();
}
@Test
public void toUri_disallowsEmptyRegion() {
thrown.expect(IllegalArgumentException.class);
S3ObjectLambdaOperationEndpointBuilder.create()
.domain("my-domain.com")
.protocol("https")
.region("")
.toUri();
}
@Test
public void toUri_disallowsNullDomain() {
thrown.expect(NullPointerException.class);
S3ObjectLambdaOperationEndpointBuilder.create()
.domain(null)
.protocol("https")
.region("region")
.toUri();
}
@Test
public void toUri_disallowsEmptyDomain() {
thrown.expect(IllegalArgumentException.class);
S3ObjectLambdaOperationEndpointBuilder.create()
.domain("")
.protocol("https")
.region("region")
.toUri();
}
}
| 4,402 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal/endpoints/S3EndpointResolverContextTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertNull;
import java.net.URI;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Configuration;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
public class S3EndpointResolverContextTest {
@Test
public void toBuilder_minimal() {
S3EndpointResolverContext context = S3EndpointResolverContext.builder().build();
assertNull(context.originalRequest());
assertNull(context.region());
assertNull(context.serviceConfiguration());
assertNull(context.request());
}
@Test
public void toBuilder_maximal() {
S3Configuration serviceConfiguration = S3Configuration.builder().build();
SdkHttpFullRequest httpRequest = SdkHttpFullRequest.builder().protocol("http").host("host").method(SdkHttpMethod.POST).build();
URI endpoint = URI.create("https://endpoint.com");
S3EndpointResolverContext context = S3EndpointResolverContext.builder()
.endpointOverride(endpoint)
.originalRequest(PutObjectRequest.builder().build())
.region(Region.US_EAST_1)
.serviceConfiguration(serviceConfiguration)
.request(httpRequest)
.build();
assertThat(context.endpointOverride()).isEqualTo(endpoint);
assertThat(context.originalRequest()).isInstanceOf(PutObjectRequest.class);
assertThat(context.region()).isEqualTo(Region.US_EAST_1);
assertThat(context.serviceConfiguration()).isEqualTo(serviceConfiguration);
assertThat(context.request()).isEqualTo(httpRequest);
}
}
| 4,403 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal/multipart/MultipartClientUserAgentTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.assertj.core.api.Assertions.assertThat;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.ApiName;
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.HttpExecuteResponse;
import software.amazon.awssdk.http.SdkHttpResponse;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.testutils.service.http.MockAsyncHttpClient;
class MultipartClientUserAgentTest {
private MockAsyncHttpClient mockAsyncHttpClient;
private UserAgentInterceptor userAgentInterceptor;
private S3AsyncClient s3Client;
@BeforeEach
void init() {
this.mockAsyncHttpClient = new MockAsyncHttpClient();
this.userAgentInterceptor = new UserAgentInterceptor();
s3Client = S3AsyncClient.builder()
.httpClient(mockAsyncHttpClient)
.endpointOverride(URI.create("http://localhost"))
.overrideConfiguration(c -> c.addExecutionInterceptor(userAgentInterceptor))
.multipartConfiguration(c -> c.minimumPartSizeInBytes(512L).thresholdInBytes(512L))
.multipartEnabled(true)
.region(Region.US_EAST_1)
.build();
}
@AfterEach
void reset() {
this.mockAsyncHttpClient.reset();
}
@Test
void validateUserAgent_nonMultipartMethod() throws Exception {
HttpExecuteResponse response = HttpExecuteResponse.builder()
.response(SdkHttpResponse.builder().statusCode(200).build())
.build();
mockAsyncHttpClient.stubResponses(response);
s3Client.headObject(req -> req.key("mock").bucket("mock")).get();
assertThat(userAgentInterceptor.apiNames)
.anyMatch(api -> "hll".equals(api.name()) && "s3Multipart".equals(api.version()));
}
private static final class UserAgentInterceptor implements ExecutionInterceptor {
private final List<ApiName> apiNames = new ArrayList<>();
@Override
public void beforeTransmission(Context.BeforeTransmission context, ExecutionAttributes executionAttributes) {
context.request().overrideConfiguration().ifPresent(c -> apiNames.addAll(c.apiNames()));
}
}
}
| 4,404 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal/multipart/S3MultipartClientBuilderTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.multipart.MultipartConfiguration;
class S3MultipartClientBuilderTest {
@Test
void multipartEnabledWithConfig_shouldBuildMultipartClient() {
S3AsyncClient client = S3AsyncClient.builder()
.multipartEnabled(true)
.multipartConfiguration(MultipartConfiguration.builder().build())
.region(Region.US_EAST_1)
.build();
assertThat(client).isInstanceOf(MultipartS3AsyncClient.class);
}
@Test
void multipartEnabledWithoutConfig_shouldBuildMultipartClient() {
S3AsyncClient client = S3AsyncClient.builder()
.multipartEnabled(true)
.region(Region.US_EAST_1)
.build();
assertThat(client).isInstanceOf(MultipartS3AsyncClient.class);
}
@Test
void multipartDisabledWithConfig_shouldNotBuildMultipartClient() {
S3AsyncClient client = S3AsyncClient.builder()
.multipartEnabled(false)
.multipartConfiguration(b -> b.apiCallBufferSizeInBytes(1024L))
.region(Region.US_EAST_1)
.build();
assertThat(client).isNotInstanceOf(MultipartS3AsyncClient.class);
}
@Test
void noMultipart_shouldNotBeMultipartClient() {
S3AsyncClient client = S3AsyncClient.builder()
.region(Region.US_EAST_1)
.build();
assertThat(client).isNotInstanceOf(MultipartS3AsyncClient.class);
}
}
| 4,405 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal/multipart/MultipartConfigurationResolverTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.services.s3.multipart.MultipartConfiguration;
public class MultipartConfigurationResolverTest {
@Test
void resolveThresholdInBytes_valueNotProvided_shouldSameAsPartSize() {
MultipartConfiguration configuration = MultipartConfiguration.builder()
.minimumPartSizeInBytes(10L)
.build();
MultipartConfigurationResolver resolver = new MultipartConfigurationResolver(configuration);
assertThat(resolver.thresholdInBytes()).isEqualTo(10L);
}
@Test
void resolveThresholdInBytes_valueProvided_shouldHonor() {
MultipartConfiguration configuration = MultipartConfiguration.builder()
.minimumPartSizeInBytes(1L)
.thresholdInBytes(12L)
.build();
MultipartConfigurationResolver resolver = new MultipartConfigurationResolver(configuration);
assertThat(resolver.thresholdInBytes()).isEqualTo(12L);
}
@Test
void resolveApiCallBufferSize_valueProvided_shouldHonor() {
MultipartConfiguration configuration = MultipartConfiguration.builder()
.apiCallBufferSizeInBytes(100L)
.build();
MultipartConfigurationResolver resolver = new MultipartConfigurationResolver(configuration);
assertThat(resolver.apiCallBufferSize()).isEqualTo(100L);
}
@Test
void resolveApiCallBufferSize_valueNotProvided_shouldComputeBasedOnPartSize() {
MultipartConfiguration configuration = MultipartConfiguration.builder()
.minimumPartSizeInBytes(10L)
.build();
MultipartConfigurationResolver resolver = new MultipartConfigurationResolver(configuration);
assertThat(resolver.apiCallBufferSize()).isEqualTo(40L);
}
@Test
void valueProvidedForAllFields_shouldHonor() {
MultipartConfiguration configuration = MultipartConfiguration.builder()
.minimumPartSizeInBytes(10L)
.thresholdInBytes(8L)
.apiCallBufferSizeInBytes(3L)
.build();
MultipartConfigurationResolver resolver = new MultipartConfigurationResolver(configuration);
assertThat(resolver.minimalPartSizeInBytes()).isEqualTo(10L);
assertThat(resolver.thresholdInBytes()).isEqualTo(8L);
assertThat(resolver.apiCallBufferSize()).isEqualTo(3L);
}
@Test
void noValueProvided_shouldUseDefault() {
MultipartConfigurationResolver resolver = new MultipartConfigurationResolver(MultipartConfiguration.builder()
.build());
assertThat(resolver.minimalPartSizeInBytes()).isEqualTo(8L * 1024 * 1024);
assertThat(resolver.thresholdInBytes()).isEqualTo(8L * 1024 * 1024);
assertThat(resolver.apiCallBufferSize()).isEqualTo(8L * 1024 * 1024 * 4);
}
}
| 4,406 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal/multipart/UploadObjectHelperTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static software.amazon.awssdk.services.s3.internal.multipart.MpuTestUtils.stubSuccessfulCompleteMultipartCall;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.mockito.stubbing.OngoingStubbing;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.services.s3.S3AsyncClient;
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.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.services.s3.multipart.MultipartConfiguration;
import software.amazon.awssdk.testutils.RandomTempFile;
import software.amazon.awssdk.utils.CompletableFutureUtils;
public class UploadObjectHelperTest {
private static final String BUCKET = "bucket";
private static final String KEY = "key";
private static final long PART_SIZE = 8 * 1024;
// Should contain four parts: [8KB, 8KB, 8KB, 1KB]
private static final long MPU_CONTENT_SIZE = 25 * 1024;
private static final long THRESHOLD = 10 * 1024;
private static final String UPLOAD_ID = "1234";
private static RandomTempFile testFile;
private UploadObjectHelper uploadHelper;
private S3AsyncClient s3AsyncClient;
@BeforeAll
public static void beforeAll() throws IOException {
testFile = new RandomTempFile("testfile.dat", MPU_CONTENT_SIZE);
}
@AfterAll
public static void afterAll() throws Exception {
testFile.delete();
}
public static Stream<AsyncRequestBody> asyncRequestBody() {
return Stream.of(new UnknownContentLengthAsyncRequestBody(AsyncRequestBody.fromFile(testFile)),
AsyncRequestBody.fromFile(testFile));
}
@BeforeEach
public void beforeEach() {
s3AsyncClient = Mockito.mock(S3AsyncClient.class);
uploadHelper = new UploadObjectHelper(s3AsyncClient,
new MultipartConfigurationResolver(MultipartConfiguration.builder()
.minimumPartSizeInBytes(PART_SIZE)
.thresholdInBytes(THRESHOLD)
.thresholdInBytes(PART_SIZE * 2)
.build()));
}
@ParameterizedTest
@ValueSource(longs = {THRESHOLD, PART_SIZE, THRESHOLD - 1, PART_SIZE - 1})
void uploadObject_contentLengthDoesNotExceedThresholdAndPartSize_shouldUploadInOneChunk(long contentLength) {
PutObjectRequest putObjectRequest = putObjectRequest(contentLength);
AsyncRequestBody asyncRequestBody = Mockito.mock(AsyncRequestBody.class);
CompletableFuture<PutObjectResponse> completedFuture =
CompletableFuture.completedFuture(PutObjectResponse.builder().build());
when(s3AsyncClient.putObject(putObjectRequest, asyncRequestBody)).thenReturn(completedFuture);
uploadHelper.uploadObject(putObjectRequest, asyncRequestBody).join();
Mockito.verify(s3AsyncClient).putObject(putObjectRequest, asyncRequestBody);
}
@ParameterizedTest
@ValueSource(longs = {PART_SIZE, PART_SIZE - 1})
void uploadObject_unKnownContentLengthDoesNotExceedPartSize_shouldUploadInOneChunk(long contentLength) {
PutObjectRequest putObjectRequest = putObjectRequest(contentLength);
AsyncRequestBody asyncRequestBody =
new UnknownContentLengthAsyncRequestBody(AsyncRequestBody.fromBytes(RandomStringUtils.randomAscii(Math.toIntExact(contentLength))
.getBytes(StandardCharsets.UTF_8)));
CompletableFuture<PutObjectResponse> completedFuture =
CompletableFuture.completedFuture(PutObjectResponse.builder().build());
when(s3AsyncClient.putObject(putObjectRequest, asyncRequestBody)).thenReturn(completedFuture);
uploadHelper.uploadObject(putObjectRequest, asyncRequestBody).join();
Mockito.verify(s3AsyncClient).putObject(putObjectRequest, asyncRequestBody);
}
@ParameterizedTest
@MethodSource("asyncRequestBody")
void uploadObject_contentLengthExceedThresholdAndPartSize_shouldUseMPU(AsyncRequestBody asyncRequestBody) {
PutObjectRequest putObjectRequest = putObjectRequest(null);
MpuTestUtils.stubSuccessfulCreateMultipartCall(UPLOAD_ID, s3AsyncClient);
stubSuccessfulUploadPartCalls();
stubSuccessfulCompleteMultipartCall(BUCKET, KEY, s3AsyncClient);
uploadHelper.uploadObject(putObjectRequest, asyncRequestBody).join();
ArgumentCaptor<UploadPartRequest> requestArgumentCaptor = ArgumentCaptor.forClass(UploadPartRequest.class);
ArgumentCaptor<AsyncRequestBody> requestBodyArgumentCaptor = ArgumentCaptor.forClass(AsyncRequestBody.class);
verify(s3AsyncClient, times(4)).uploadPart(requestArgumentCaptor.capture(),
requestBodyArgumentCaptor.capture());
List<UploadPartRequest> actualRequests = requestArgumentCaptor.getAllValues();
List<AsyncRequestBody> actualRequestBodies = requestBodyArgumentCaptor.getAllValues();
assertThat(actualRequestBodies).hasSize(4);
assertThat(actualRequests).hasSize(4);
for (int i = 0; i < actualRequests.size(); i++) {
UploadPartRequest request = actualRequests.get(i);
AsyncRequestBody requestBody = actualRequestBodies.get(i);
assertThat(request.partNumber()).isEqualTo( i + 1);
assertThat(request.bucket()).isEqualTo(BUCKET);
assertThat(request.key()).isEqualTo(KEY);
if (i == actualRequests.size() - 1) {
assertThat(requestBody.contentLength()).hasValue(1024L);
} else{
assertThat(requestBody.contentLength()).hasValue(PART_SIZE);
}
}
}
/**
* The second part failed, it should cancel ongoing part(first part).
*/
@ParameterizedTest
@MethodSource("asyncRequestBody")
void mpu_onePartFailed_shouldFailOtherPartsAndAbort(AsyncRequestBody asyncRequestBody) {
PutObjectRequest putObjectRequest = putObjectRequest(MPU_CONTENT_SIZE);
MpuTestUtils.stubSuccessfulCreateMultipartCall(UPLOAD_ID, s3AsyncClient);
CompletableFuture<UploadPartResponse> ongoingRequest = new CompletableFuture<>();
SdkClientException exception = SdkClientException.create("request failed");
OngoingStubbing<CompletableFuture<UploadPartResponse>> ongoingStubbing =
when(s3AsyncClient.uploadPart(any(UploadPartRequest.class), any(AsyncRequestBody.class))).thenReturn(ongoingRequest);
stubFailedUploadPartCalls(ongoingStubbing, exception);
when(s3AsyncClient.abortMultipartUpload(any(AbortMultipartUploadRequest.class)))
.thenReturn(CompletableFuture.completedFuture(AbortMultipartUploadResponse.builder().build()));
CompletableFuture<PutObjectResponse> future = uploadHelper.uploadObject(putObjectRequest,
asyncRequestBody);
assertThatThrownBy(() -> future.get(100, TimeUnit.MILLISECONDS))
.hasStackTraceContaining("Failed to send multipart upload requests").hasCause(exception);
verify(s3AsyncClient, never()).completeMultipartUpload(any(CompleteMultipartUploadRequest.class));
ArgumentCaptor<AbortMultipartUploadRequest> argumentCaptor = ArgumentCaptor.forClass(AbortMultipartUploadRequest.class);
verify(s3AsyncClient).abortMultipartUpload(argumentCaptor.capture());
AbortMultipartUploadRequest actualRequest = argumentCaptor.getValue();
assertThat(actualRequest.uploadId()).isEqualTo(UPLOAD_ID);
try {
ongoingRequest.get(100, TimeUnit.MILLISECONDS);
fail("no exception thrown");
} catch (Exception e) {
assertThat(e.getCause()).isEqualTo(exception);
}
}
/**
* This test is not parameterized because for unknown content length, the progress is nondeterministic. For example, we
* don't know if it has created multipart upload when we cancel the future.
*/
@Test
void upload_knownContentLengthCancelResponseFuture_shouldCancelCreateMultipart() {
PutObjectRequest putObjectRequest = putObjectRequest(null);
CompletableFuture<CreateMultipartUploadResponse> createMultipartFuture = new CompletableFuture<>();
when(s3AsyncClient.createMultipartUpload(any(CreateMultipartUploadRequest.class)))
.thenReturn(createMultipartFuture);
CompletableFuture<PutObjectResponse> future =
uploadHelper.uploadObject(putObjectRequest, AsyncRequestBody.fromFile(testFile));
future.cancel(true);
assertThat(createMultipartFuture).isCancelled();
}
@Test
void upload_knownContentLengthCancelResponseFuture_shouldCancelUploadPart() {
PutObjectRequest putObjectRequest = putObjectRequest(null);
CompletableFuture<CreateMultipartUploadResponse> createMultipartFuture = new CompletableFuture<>();
MpuTestUtils.stubSuccessfulCreateMultipartCall(UPLOAD_ID, s3AsyncClient);
CompletableFuture<UploadPartResponse> ongoingRequest = new CompletableFuture<>();
when(s3AsyncClient.uploadPart(any(UploadPartRequest.class),
any(AsyncRequestBody.class))).thenReturn(ongoingRequest);
CompletableFuture<PutObjectResponse> future =
uploadHelper.uploadObject(putObjectRequest, AsyncRequestBody.fromFile(testFile));
when(s3AsyncClient.abortMultipartUpload(any(AbortMultipartUploadRequest.class)))
.thenReturn(CompletableFuture.completedFuture(AbortMultipartUploadResponse.builder().build()));
future.cancel(true);
try {
ongoingRequest.join();
fail("no exception");
} catch (Exception exception) {
assertThat(ongoingRequest).isCancelled();
}
}
@ParameterizedTest
@MethodSource("asyncRequestBody")
void uploadObject_createMultipartUploadFailed_shouldFail(AsyncRequestBody asyncRequestBody) {
PutObjectRequest putObjectRequest = putObjectRequest(null);
SdkClientException exception = SdkClientException.create("CompleteMultipartUpload failed");
CompletableFuture<CreateMultipartUploadResponse> createMultipartUploadFuture =
CompletableFutureUtils.failedFuture(exception);
when(s3AsyncClient.createMultipartUpload(any(CreateMultipartUploadRequest.class)))
.thenReturn(createMultipartUploadFuture);
CompletableFuture<PutObjectResponse> future = uploadHelper.uploadObject(putObjectRequest,
asyncRequestBody);
assertThatThrownBy(future::join).hasStackTraceContaining("Failed to initiate multipart upload")
.hasCause(exception);
}
@ParameterizedTest
@MethodSource("asyncRequestBody")
void uploadObject_completeMultipartFailed_shouldFailAndAbort(AsyncRequestBody asyncRequestBody) {
PutObjectRequest putObjectRequest = putObjectRequest(null);
MpuTestUtils.stubSuccessfulCreateMultipartCall(UPLOAD_ID, s3AsyncClient);
stubSuccessfulUploadPartCalls();
SdkClientException exception = SdkClientException.create("CompleteMultipartUpload failed");
CompletableFuture<CompleteMultipartUploadResponse> completeMultipartUploadFuture =
CompletableFutureUtils.failedFuture(exception);
when(s3AsyncClient.completeMultipartUpload(any(CompleteMultipartUploadRequest.class)))
.thenReturn(completeMultipartUploadFuture);
when(s3AsyncClient.abortMultipartUpload(any(AbortMultipartUploadRequest.class)))
.thenReturn(CompletableFuture.completedFuture(AbortMultipartUploadResponse.builder().build()));
CompletableFuture<PutObjectResponse> future = uploadHelper.uploadObject(putObjectRequest,
asyncRequestBody);
assertThatThrownBy(future::join).hasCause(exception)
.hasStackTraceContaining("Failed to send multipart requests");
}
@ParameterizedTest()
@ValueSource(booleans = {false, true})
void uploadObject_requestBodyOnError_shouldFailAndAbort(boolean contentLengthKnown) {
PutObjectRequest putObjectRequest = putObjectRequest(null);
Exception exception = new RuntimeException("error");
Long contentLength = contentLengthKnown ? MPU_CONTENT_SIZE : null;
ErroneousAsyncRequestBody erroneousAsyncRequestBody =
new ErroneousAsyncRequestBody(contentLength, exception);
MpuTestUtils.stubSuccessfulCreateMultipartCall(UPLOAD_ID, s3AsyncClient);
stubSuccessfulUploadPartCalls();
when(s3AsyncClient.abortMultipartUpload(any(AbortMultipartUploadRequest.class)))
.thenReturn(CompletableFuture.completedFuture(AbortMultipartUploadResponse.builder().build()));
CompletableFuture<PutObjectResponse> future = uploadHelper.uploadObject(putObjectRequest,
erroneousAsyncRequestBody);
assertThatThrownBy(future::join).hasMessageContaining("Failed to send multipart upload requests")
.hasRootCause(exception);
}
private static PutObjectRequest putObjectRequest(Long contentLength) {
return PutObjectRequest.builder()
.bucket(BUCKET)
.key(KEY)
.contentLength(contentLength)
.build();
}
private void stubSuccessfulUploadPartCalls() {
when(s3AsyncClient.uploadPart(any(UploadPartRequest.class), any(AsyncRequestBody.class)))
.thenAnswer(new Answer<CompletableFuture<UploadPartResponse>>() {
int numberOfCalls = 0;
@Override
public CompletableFuture<UploadPartResponse> answer(InvocationOnMock invocationOnMock) {
AsyncRequestBody AsyncRequestBody = invocationOnMock.getArgument(1);
// Draining the request body
AsyncRequestBody.subscribe(b -> {});
numberOfCalls++;
return CompletableFuture.completedFuture(UploadPartResponse.builder()
.checksumCRC32("crc" + numberOfCalls)
.build());
}
});
}
private OngoingStubbing<CompletableFuture<UploadPartResponse>> stubFailedUploadPartCalls(OngoingStubbing<CompletableFuture<UploadPartResponse>> stubbing, Exception exception) {
return stubbing.thenAnswer(new Answer<CompletableFuture<UploadPartResponse>>() {
@Override
public CompletableFuture<UploadPartResponse> answer(InvocationOnMock invocationOnMock) {
AsyncRequestBody AsyncRequestBody = invocationOnMock.getArgument(1);
// Draining the request body
AsyncRequestBody.subscribe(b -> {});
return CompletableFutureUtils.failedFuture(exception);
}
});
}
private static class UnknownContentLengthAsyncRequestBody implements AsyncRequestBody {
private final AsyncRequestBody delegate;
private volatile boolean cancelled;
public UnknownContentLengthAsyncRequestBody(AsyncRequestBody asyncRequestBody) {
this.delegate = asyncRequestBody;
}
@Override
public Optional<Long> contentLength() {
return Optional.empty();
}
@Override
public void subscribe(Subscriber<? super ByteBuffer> s) {
delegate.subscribe(s);
}
}
private static class ErroneousAsyncRequestBody implements AsyncRequestBody {
private volatile boolean isDone;
private final Long contentLength;
private final Exception exception;
private ErroneousAsyncRequestBody(Long contentLength, Exception exception) {
this.contentLength = contentLength;
this.exception = exception;
}
@Override
public Optional<Long> contentLength() {
return Optional.ofNullable(contentLength);
}
@Override
public void subscribe(Subscriber<? super ByteBuffer> s) {
s.onSubscribe(new Subscription() {
@Override
public void request(long n) {
if (isDone) {
return;
}
isDone = true;
s.onNext(ByteBuffer.wrap(RandomStringUtils.randomAscii(Math.toIntExact(PART_SIZE)).getBytes(StandardCharsets.UTF_8)));
s.onNext(ByteBuffer.wrap(RandomStringUtils.randomAscii(Math.toIntExact(PART_SIZE)).getBytes(StandardCharsets.UTF_8)));
s.onError(exception);
}
@Override
public void cancel() {
}
});
}
}
}
| 4,407 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal/multipart/MpuTestUtils.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.model.CompleteMultipartUploadRequest;
import software.amazon.awssdk.services.s3.model.CompleteMultipartUploadResponse;
import software.amazon.awssdk.services.s3.model.CreateMultipartUploadRequest;
import software.amazon.awssdk.services.s3.model.CreateMultipartUploadResponse;
import software.amazon.awssdk.services.s3.model.HeadObjectRequest;
import software.amazon.awssdk.services.s3.model.HeadObjectResponse;
public final class MpuTestUtils {
private MpuTestUtils() {
}
public static void stubSuccessfulHeadObjectCall(long contentLength, S3AsyncClient s3AsyncClient) {
CompletableFuture<HeadObjectResponse> headFuture =
CompletableFuture.completedFuture(HeadObjectResponse.builder()
.contentLength(contentLength)
.build());
when(s3AsyncClient.headObject(any(HeadObjectRequest.class)))
.thenReturn(headFuture);
}
public static void stubSuccessfulCreateMultipartCall(String mpuId, S3AsyncClient s3AsyncClient) {
CompletableFuture<CreateMultipartUploadResponse> createMultipartUploadFuture =
CompletableFuture.completedFuture(CreateMultipartUploadResponse.builder()
.uploadId(mpuId)
.build());
when(s3AsyncClient.createMultipartUpload(any(CreateMultipartUploadRequest.class)))
.thenReturn(createMultipartUploadFuture);
}
public static void stubSuccessfulCompleteMultipartCall(String bucket, String key, S3AsyncClient s3AsyncClient) {
CompletableFuture<CompleteMultipartUploadResponse> completeMultipartUploadFuture =
CompletableFuture.completedFuture(CompleteMultipartUploadResponse.builder()
.bucket(bucket)
.key(key)
.build());
when(s3AsyncClient.completeMultipartUpload(any(CompleteMultipartUploadRequest.class)))
.thenReturn(completeMultipartUploadFuture);
}
}
| 4,408 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal/multipart/SdkPojoConversionUtilsTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.assertj.core.api.Assertions.assertThat;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.awscore.DefaultAwsResponseMetadata;
import software.amazon.awssdk.core.SdkField;
import software.amazon.awssdk.core.SdkPojo;
import software.amazon.awssdk.http.SdkHttpFullResponse;
import software.amazon.awssdk.services.s3.internal.multipart.SdkPojoConversionUtils;
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.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.S3ResponseMetadata;
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;
class SdkPojoConversionUtilsTest {
private static final Logger log = Logger.loggerFor(SdkPojoConversionUtils.class);
private static final Random RNG = new Random();
@Test
void toHeadObject_shouldCopyProperties() {
CopyObjectRequest randomCopyObject = randomCopyObjectRequest();
HeadObjectRequest convertedToHeadObject = SdkPojoConversionUtils.toHeadObjectRequest(randomCopyObject);
Set<String> fieldsToIgnore = new HashSet<>(Arrays.asList("ExpectedBucketOwner",
"RequestPayer",
"Bucket",
"Key",
"SSECustomerKeyMD5",
"SSECustomerKey",
"SSECustomerAlgorithm"));
verifyFieldsAreCopied(randomCopyObject, convertedToHeadObject, fieldsToIgnore,
CopyObjectRequest.builder().sdkFields(),
HeadObjectRequest.builder().sdkFields());
}
@Test
void toCompletedPart_copy_shouldCopyProperties() {
CopyPartResult.Builder fromObject = CopyPartResult.builder();
setFieldsToRandomValues(fromObject.sdkFields(), fromObject);
CopyPartResult result = fromObject.build();
CompletedPart convertedCompletedPart = SdkPojoConversionUtils.toCompletedPart(result, 1);
verifyFieldsAreCopied(result, convertedCompletedPart, new HashSet<>(),
CopyPartResult.builder().sdkFields(),
CompletedPart.builder().sdkFields());
assertThat(convertedCompletedPart.partNumber()).isEqualTo(1);
}
@Test
void toCreateMultipartUploadRequest_copyObject_shouldCopyProperties() {
CopyObjectRequest randomCopyObject = randomCopyObjectRequest();
CreateMultipartUploadRequest convertedRequest = SdkPojoConversionUtils.toCreateMultipartUploadRequest(randomCopyObject);
Set<String> fieldsToIgnore = new HashSet<>();
verifyFieldsAreCopied(randomCopyObject, convertedRequest, fieldsToIgnore,
CopyObjectRequest.builder().sdkFields(),
CreateMultipartUploadRequest.builder().sdkFields());
}
@Test
void toCopyObjectResponse_shouldCopyProperties() {
CompleteMultipartUploadResponse.Builder responseBuilder = CompleteMultipartUploadResponse.builder();
setFieldsToRandomValues(responseBuilder.sdkFields(), responseBuilder);
S3ResponseMetadata s3ResponseMetadata = S3ResponseMetadata.create(DefaultAwsResponseMetadata.create(new HashMap<>()));
SdkHttpFullResponse sdkHttpFullResponse = SdkHttpFullResponse.builder().statusCode(200).build();
responseBuilder.responseMetadata(s3ResponseMetadata).sdkHttpResponse(sdkHttpFullResponse);
CompleteMultipartUploadResponse result = responseBuilder.build();
CopyObjectResponse convertedRequest = SdkPojoConversionUtils.toCopyObjectResponse(result);
Set<String> fieldsToIgnore = new HashSet<>();
verifyFieldsAreCopied(result, convertedRequest, fieldsToIgnore,
CompleteMultipartUploadResponse.builder().sdkFields(),
CopyObjectResponse.builder().sdkFields());
assertThat(convertedRequest.sdkHttpResponse()).isEqualTo(sdkHttpFullResponse);
assertThat(convertedRequest.responseMetadata()).isEqualTo(s3ResponseMetadata);
}
@Test
void toAbortMultipartUploadRequest_copyObject_shouldCopyProperties() {
CopyObjectRequest randomCopyObject = randomCopyObjectRequest();
AbortMultipartUploadRequest convertedRequest = SdkPojoConversionUtils.toAbortMultipartUploadRequest(randomCopyObject).build();
Set<String> fieldsToIgnore = new HashSet<>();
verifyFieldsAreCopied(randomCopyObject, convertedRequest, fieldsToIgnore,
CopyObjectRequest.builder().sdkFields(),
AbortMultipartUploadRequest.builder().sdkFields());
}
@Test
void toAbortMultipartUploadRequest_putObject_shouldCopyProperties() {
PutObjectRequest randomCopyObject = randomPutObjectRequest();
AbortMultipartUploadRequest convertedRequest = SdkPojoConversionUtils.toAbortMultipartUploadRequest(randomCopyObject).build();
Set<String> fieldsToIgnore = new HashSet<>();
verifyFieldsAreCopied(randomCopyObject, convertedRequest, fieldsToIgnore,
PutObjectRequest.builder().sdkFields(),
AbortMultipartUploadRequest.builder().sdkFields());
}
@Test
void toUploadPartCopyRequest_shouldCopyProperties() {
CopyObjectRequest randomCopyObject = randomCopyObjectRequest();
UploadPartCopyRequest convertedObject = SdkPojoConversionUtils.toUploadPartCopyRequest(randomCopyObject, 1, "id",
"bytes=0-1024");
Set<String> fieldsToIgnore = new HashSet<>(Collections.singletonList("CopySource"));
verifyFieldsAreCopied(randomCopyObject, convertedObject, fieldsToIgnore,
CopyObjectRequest.builder().sdkFields(),
UploadPartCopyRequest.builder().sdkFields());
}
@Test
void toUploadPartRequest_shouldCopyProperties() {
PutObjectRequest randomObject = randomPutObjectRequest();
UploadPartRequest convertedObject = SdkPojoConversionUtils.toUploadPartRequest(randomObject, 1, "id");
Set<String> fieldsToIgnore = new HashSet<>(Arrays.asList("ChecksumCRC32", "ChecksumSHA256", "ContentMD5", "ChecksumSHA1",
"ChecksumCRC32C"));
verifyFieldsAreCopied(randomObject, convertedObject, fieldsToIgnore,
PutObjectRequest.builder().sdkFields(),
UploadPartRequest.builder().sdkFields());
assertThat(convertedObject.partNumber()).isEqualTo(1);
assertThat(convertedObject.uploadId()).isEqualTo("id");
}
@Test
void toPutObjectResponse_shouldCopyProperties() {
CompleteMultipartUploadResponse.Builder builder = CompleteMultipartUploadResponse.builder();
populateFields(builder);
S3ResponseMetadata s3ResponseMetadata = S3ResponseMetadata.create(DefaultAwsResponseMetadata.create(new HashMap<>()));
SdkHttpFullResponse sdkHttpFullResponse = SdkHttpFullResponse.builder().statusCode(200).build();
builder.responseMetadata(s3ResponseMetadata).sdkHttpResponse(sdkHttpFullResponse);
CompleteMultipartUploadResponse randomObject = builder.build();
PutObjectResponse convertedObject = SdkPojoConversionUtils.toPutObjectResponse(randomObject);
Set<String> fieldsToIgnore = new HashSet<>();
verifyFieldsAreCopied(randomObject, convertedObject, fieldsToIgnore,
CompleteMultipartUploadResponse.builder().sdkFields(),
PutObjectResponse.builder().sdkFields());
assertThat(convertedObject.sdkHttpResponse()).isEqualTo(sdkHttpFullResponse);
assertThat(convertedObject.responseMetadata()).isEqualTo(s3ResponseMetadata);
}
@Test
void toCreateMultipartUploadRequest_putObjectRequest_shouldCopyProperties() {
PutObjectRequest randomObject = randomPutObjectRequest();
CreateMultipartUploadRequest convertedObject = SdkPojoConversionUtils.toCreateMultipartUploadRequest(randomObject);
Set<String> fieldsToIgnore = new HashSet<>();
System.out.println(convertedObject);
verifyFieldsAreCopied(randomObject, convertedObject, fieldsToIgnore,
PutObjectRequest.builder().sdkFields(),
CreateMultipartUploadRequest.builder().sdkFields());
}
@Test
void toCompletedPart_putObject_shouldCopyProperties() {
UploadPartResponse.Builder fromObject = UploadPartResponse.builder();
setFieldsToRandomValues(fromObject.sdkFields(), fromObject);
UploadPartResponse result = fromObject.build();
CompletedPart convertedCompletedPart = SdkPojoConversionUtils.toCompletedPart(result, 1);
verifyFieldsAreCopied(result, convertedCompletedPart, new HashSet<>(),
UploadPartResponse.builder().sdkFields(),
CompletedPart.builder().sdkFields());
assertThat(convertedCompletedPart.partNumber()).isEqualTo(1);
}
private static void verifyFieldsAreCopied(SdkPojo requestConvertedFrom,
SdkPojo requestConvertedTo,
Set<String> fieldsToIgnore,
List<SdkField<?>> requestConvertedFromSdkFields,
List<SdkField<?>> requestConvertedToSdkFields) {
Map<String, SdkField<?>> toFields = sdkFieldMap(requestConvertedToSdkFields);
Map<String, SdkField<?>> fromFields = sdkFieldMap(requestConvertedFromSdkFields);
List<String> fieldsNotMatch = new ArrayList<>();
for (Map.Entry<String, SdkField<?>> toObjectEntry : toFields.entrySet()) {
SdkField<?> toField = toObjectEntry.getValue();
if (fieldsToIgnore.contains(toField.memberName())) {
log.info(() -> "Ignoring fields: " + toField.memberName());
continue;
}
SdkField<?> fromField = fromFields.get(toObjectEntry.getKey());
if (fromField == null) {
log.info(() -> String.format("Ignoring field [%s] because the object to convert from does not have such field ",
toField.memberName()));
continue;
}
Object destinationObjValue = toField.getValueOrDefault(requestConvertedTo);
Object sourceObjValue = fromField.getValueOrDefault(requestConvertedFrom);
if (!sourceObjValue.equals(destinationObjValue)) {
fieldsNotMatch.add(toField.memberName());
}
}
assertThat(fieldsNotMatch).withFailMessage("Below fields do not match " + fieldsNotMatch).isEmpty();
}
private CopyObjectRequest randomCopyObjectRequest() {
CopyObjectRequest.Builder builder = CopyObjectRequest.builder();
setFieldsToRandomValues(builder.sdkFields(), builder);
return builder.build();
}
private PutObjectRequest randomPutObjectRequest() {
PutObjectRequest.Builder builder = PutObjectRequest.builder();
setFieldsToRandomValues(builder.sdkFields(), builder);
return builder.build();
}
private void populateFields(SdkPojo pojo) {
setFieldsToRandomValues(pojo.sdkFields(), pojo);
}
private void setFieldsToRandomValues(Collection<SdkField<?>> fields, Object builder) {
for (SdkField<?> f : fields) {
setFieldToRandomValue(f, builder);
}
}
private static void setFieldToRandomValue(SdkField<?> sdkField, Object obj) {
Class<?> targetClass = sdkField.marshallingType().getTargetClass();
if (targetClass.equals(String.class)) {
sdkField.set(obj, RandomStringUtils.randomAlphanumeric(8));
} else if (targetClass.equals(Integer.class)) {
sdkField.set(obj, randomInteger());
} else if (targetClass.equals(Instant.class)) {
sdkField.set(obj, randomInstant());
} else if (targetClass.equals(Map.class)) {
sdkField.set(obj, new HashMap<>());
} else if (targetClass.equals(Boolean.class)) {
sdkField.set(obj, true);
} else if (targetClass.equals(Long.class)) {
sdkField.set(obj, randomLong());
} else {
throw new IllegalArgumentException("Unknown SdkField type: " + targetClass + " name: " + sdkField.memberName());
}
}
private static Map<String, SdkField<?>> sdkFieldMap(Collection<? extends SdkField<?>> sdkFields) {
Map<String, SdkField<?>> map = new HashMap<>(sdkFields.size());
for (SdkField<?> f : sdkFields) {
String locName = f.memberName();
if (map.put(locName, f) != null) {
throw new IllegalArgumentException("Multiple SdkFields map to same location name");
}
}
return map;
}
private static Instant randomInstant() {
return Instant.ofEpochMilli(RNG.nextLong());
}
private static Integer randomInteger() {
return RNG.nextInt();
}
private static long randomLong() {
return RNG.nextLong();
}
}
| 4,409 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal/crt/S3CrtRequestBodyStreamAdapterTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import io.reactivex.Flowable;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import software.amazon.awssdk.http.async.SdkHttpContentPublisher;
class S3CrtRequestBodyStreamAdapterTest {
@Test
void getRequestData_fillsInputBuffer_publisherBuffersAreSmaller() {
int inputBufferSize = 16;
List<ByteBuffer> data = Stream.generate(() -> (byte) 42)
.limit(inputBufferSize)
.map(b -> {
ByteBuffer bb = ByteBuffer.allocate(1);
bb.put(b);
bb.flip();
return bb;
})
.collect(Collectors.toList());
SdkHttpContentPublisher requestBody = requestBody(Flowable.fromIterable(data), 42L);
S3CrtRequestBodyStreamAdapter adapter = new S3CrtRequestBodyStreamAdapter(requestBody);
ByteBuffer inputBuffer = ByteBuffer.allocate(inputBufferSize);
adapter.sendRequestBody(inputBuffer);
assertThat(inputBuffer.remaining()).isEqualTo(0);
}
private static SdkHttpContentPublisher requestBody(Publisher<ByteBuffer> delegate, long size) {
return new SdkHttpContentPublisher() {
@Override
public Optional<Long> contentLength() {
return Optional.of(size);
}
@Override
public void subscribe(Subscriber<? super ByteBuffer> subscriber) {
delegate.subscribe(subscriber);
}
};
}
@Test
public void getRequestData_fillsInputBuffer_publisherBuffersAreLarger() {
int bodySize = 16;
ByteBuffer data = ByteBuffer.allocate(bodySize);
data.put(new byte[bodySize]);
data.flip();
SdkHttpContentPublisher requestBody = requestBody(Flowable.just(data), 16L);
S3CrtRequestBodyStreamAdapter adapter = new S3CrtRequestBodyStreamAdapter(requestBody);
ByteBuffer inputBuffer = ByteBuffer.allocate(1);
for (int i = 0; i < bodySize; ++i) {
adapter.sendRequestBody(inputBuffer);
assertThat(inputBuffer.remaining()).isEqualTo(0);
inputBuffer.flip();
}
}
@Test
public void getRequestData_publisherThrows_surfacesException() {
Publisher<ByteBuffer> errorPublisher = Flowable.error(new RuntimeException("Something wrong happened"));
SdkHttpContentPublisher requestBody = requestBody(errorPublisher, 0L);
S3CrtRequestBodyStreamAdapter adapter = new S3CrtRequestBodyStreamAdapter(requestBody);
assertThatThrownBy(() -> adapter.sendRequestBody(ByteBuffer.allocate(16)))
.isInstanceOf(RuntimeException.class)
.hasMessageContaining("Something wrong happened");
}
@Test
public void getRequestData_publisherThrows_wrapsExceptionIfNotRuntimeException() {
Publisher<ByteBuffer> errorPublisher = Flowable.error(new IOException("Some I/O error happened"));
SdkHttpContentPublisher requestBody = requestBody(errorPublisher, 0L);
S3CrtRequestBodyStreamAdapter adapter = new S3CrtRequestBodyStreamAdapter(requestBody);
assertThatThrownBy(() -> adapter.sendRequestBody(ByteBuffer.allocate(16)))
.isInstanceOf(RuntimeException.class)
.hasCauseInstanceOf(IOException.class);
}
}
| 4,410 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal/crt/S3CrtAsyncHttpClientTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static software.amazon.awssdk.http.Header.CONTENT_LENGTH;
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 java.net.URI;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Stream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import software.amazon.awssdk.core.interceptor.trait.HttpChecksum;
import software.amazon.awssdk.crt.http.HttpProxyEnvironmentVariableSetting;
import software.amazon.awssdk.crt.http.HttpRequest;
import software.amazon.awssdk.crt.io.ExponentialBackoffRetryOptions;
import software.amazon.awssdk.crt.io.StandardRetryOptions;
import software.amazon.awssdk.crt.s3.ChecksumAlgorithm;
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.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.http.async.AsyncExecuteRequest;
import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler;
import software.amazon.awssdk.http.async.SdkHttpContentPublisher;
import software.amazon.awssdk.services.s3.crt.S3CrtHttpConfiguration;
public class S3CrtAsyncHttpClientTest {
private static final URI DEFAULT_ENDPOINT = URI.create("https://127.0.0.1:443");
private S3CrtAsyncHttpClient asyncHttpClient;
private S3NativeClientConfiguration s3NativeClientConfiguration;
private S3Client s3Client;
private SdkAsyncHttpResponseHandler responseHandler;
private SdkHttpContentPublisher contentPublisher;
@BeforeEach
public void methodSetup() {
s3Client = Mockito.mock(S3Client.class);
responseHandler = Mockito.mock(SdkAsyncHttpResponseHandler.class);
contentPublisher = Mockito.mock(SdkHttpContentPublisher.class);
s3NativeClientConfiguration = S3NativeClientConfiguration.builder()
.endpointOverride(DEFAULT_ENDPOINT)
.credentialsProvider(null)
.checksumValidationEnabled(true)
.build();
asyncHttpClient = new S3CrtAsyncHttpClient(s3Client, s3NativeClientConfiguration);
}
private static Stream<Integer> ports() {
return Stream.of(null, 1234, 443);
}
@ParameterizedTest
@MethodSource("ports")
public void defaultRequest_shouldSetMetaRequestOptionsCorrectly(Integer port) {
AsyncExecuteRequest asyncExecuteRequest = getExecuteRequestBuilder(port).build();
S3MetaRequestOptions actual = makeRequest(asyncExecuteRequest);
assertThat(actual.getMetaRequestType()).isEqualTo(S3MetaRequestOptions.MetaRequestType.DEFAULT);
assertThat(actual.getCredentialsProvider()).isNull();
String expectedEndpoint = port == null || port.equals(443) ?
DEFAULT_ENDPOINT.getScheme() + "://" + DEFAULT_ENDPOINT.getHost() :
DEFAULT_ENDPOINT.getScheme() + "://" + DEFAULT_ENDPOINT.getHost() + ":" + port;
assertThat(actual.getEndpoint()).hasToString(expectedEndpoint);
HttpRequest httpRequest = actual.getHttpRequest();
assertThat(httpRequest.getEncodedPath()).isEqualTo("/key");
Map<String, String> headers = httpRequest.getHeaders()
.stream()
.collect(HashMap::new, (m, h) -> m.put(h.getName(), h.getValue())
, Map::putAll);
String expectedPort = port == null || port.equals(443) ? "" : ":" + port;
assertThat(headers).hasSize(4)
.containsEntry("Host", DEFAULT_ENDPOINT.getHost() + expectedPort)
.containsEntry("custom-header", "foobar")
.containsEntry("amz-sdk-invocation-id", "1234")
.containsEntry("Content-Length", "100");
}
@Test
public void getObject_shouldSetMetaRequestTypeCorrectly() {
AsyncExecuteRequest asyncExecuteRequest = getExecuteRequestBuilder().putHttpExecutionAttribute(OPERATION_NAME,
"GetObject").build();
S3MetaRequestOptions actual = makeRequest(asyncExecuteRequest);
assertThat(actual.getMetaRequestType()).isEqualTo(S3MetaRequestOptions.MetaRequestType.GET_OBJECT);
}
@Test
public void putObject_shouldSetMetaRequestTypeCorrectly() {
AsyncExecuteRequest asyncExecuteRequest = getExecuteRequestBuilder().putHttpExecutionAttribute(OPERATION_NAME,
"PutObject").build();
S3MetaRequestOptions actual = makeRequest(asyncExecuteRequest);
assertThat(actual.getMetaRequestType()).isEqualTo(S3MetaRequestOptions.MetaRequestType.PUT_OBJECT);
}
@Test
public void cancelRequest_shouldForwardCancellation() {
AsyncExecuteRequest asyncExecuteRequest = getExecuteRequestBuilder().build();
S3MetaRequest metaRequest = Mockito.mock(S3MetaRequest.class);
when(s3Client.makeMetaRequest(any(S3MetaRequestOptions.class))).thenReturn(metaRequest);
CompletableFuture<Void> future = asyncHttpClient.execute(asyncExecuteRequest);
future.cancel(false);
verify(metaRequest).cancel();
}
@Test
public void nonStreamingOperation_noChecksumAlgoProvided_shouldNotSetByDefault() {
HttpChecksum httpChecksum = HttpChecksum.builder()
.isRequestStreaming(false)
.build();
AsyncExecuteRequest asyncExecuteRequest = getExecuteRequestBuilder().putHttpExecutionAttribute(OPERATION_NAME,
"NonStreaming")
.putHttpExecutionAttribute(HTTP_CHECKSUM,
httpChecksum)
.build();
S3MetaRequestOptions actual = makeRequest(asyncExecuteRequest);
assertThat(actual.getChecksumConfig().getChecksumAlgorithm()).isEqualTo(ChecksumAlgorithm.NONE);
}
@Test
public void nonStreamingOperation_checksumAlgoProvided_shouldNotPassToCrt() {
HttpChecksum httpChecksum = HttpChecksum.builder()
.isRequestStreaming(false)
.requestAlgorithm("SHA1")
.build();
AsyncExecuteRequest asyncExecuteRequest = getExecuteRequestBuilder().putHttpExecutionAttribute(OPERATION_NAME,
"NonStreaming")
.putHttpExecutionAttribute(HTTP_CHECKSUM,
httpChecksum)
.build();
S3MetaRequestOptions actual = makeRequest(asyncExecuteRequest);
assertThat(actual.getChecksumConfig().getChecksumAlgorithm()).isEqualTo(ChecksumAlgorithm.NONE);
}
@Test
public void checksumRequiredOperation_noChecksumAlgoProvided_shouldSetByDefault() {
HttpChecksum httpChecksum = HttpChecksum.builder()
.requestChecksumRequired(true)
.build();
AsyncExecuteRequest asyncExecuteRequest = getExecuteRequestBuilder().putHttpExecutionAttribute(OPERATION_NAME,
"PutObject")
.putHttpExecutionAttribute(HTTP_CHECKSUM,
httpChecksum)
.build();
S3MetaRequestOptions actual = makeRequest(asyncExecuteRequest);
assertThat(actual.getChecksumAlgorithm()).isEqualTo(ChecksumAlgorithm.CRC32);
}
@Test
public void streamingOperation_noChecksumAlgoProvided_shouldSetByDefault() {
HttpChecksum httpChecksum = HttpChecksum.builder()
.isRequestStreaming(true)
.build();
AsyncExecuteRequest asyncExecuteRequest = getExecuteRequestBuilder().putHttpExecutionAttribute(OPERATION_NAME,
"PutObject")
.putHttpExecutionAttribute(HTTP_CHECKSUM,
httpChecksum)
.build();
S3MetaRequestOptions actual = makeRequest(asyncExecuteRequest);
assertThat(actual.getChecksumAlgorithm()).isEqualTo(ChecksumAlgorithm.CRC32);
}
@Test
public void operationWithResponseAlgorithms_validateNotSpecified_shouldValidateByDefault() {
HttpChecksum httpChecksum = HttpChecksum.builder()
.responseAlgorithms("CRC32")
.build();
AsyncExecuteRequest asyncExecuteRequest = getExecuteRequestBuilder().putHttpExecutionAttribute(OPERATION_NAME,
"GetObject")
.putHttpExecutionAttribute(HTTP_CHECKSUM,
httpChecksum)
.build();
S3MetaRequestOptions actual = makeRequest(asyncExecuteRequest);
assertThat(actual.getValidateChecksum()).isTrue();
}
@Test
public void operationWithResponseAlgorithms_optOutValidationFromClient_shouldHonor() {
HttpChecksum httpChecksum = HttpChecksum.builder()
.responseAlgorithms("CRC32")
.build();
s3NativeClientConfiguration = S3NativeClientConfiguration.builder()
.endpointOverride(DEFAULT_ENDPOINT)
.credentialsProvider(null)
.checksumValidationEnabled(false)
.build();
asyncHttpClient = new S3CrtAsyncHttpClient(s3Client, s3NativeClientConfiguration);
AsyncExecuteRequest asyncExecuteRequest = getExecuteRequestBuilder().putHttpExecutionAttribute(OPERATION_NAME,
"GetObject")
.putHttpExecutionAttribute(HTTP_CHECKSUM,
httpChecksum)
.build();
S3MetaRequestOptions actual = makeRequest(asyncExecuteRequest);
assertThat(actual.getValidateChecksum()).isFalse();
}
@Test
public void operationWithResponseAlgorithms_optInFromRequest_shouldHonor() {
HttpChecksum httpChecksum = HttpChecksum.builder()
.responseAlgorithms("CRC32")
.requestValidationMode("Enabled")
.build();
s3NativeClientConfiguration = S3NativeClientConfiguration.builder()
.endpointOverride(DEFAULT_ENDPOINT)
.credentialsProvider(null)
.checksumValidationEnabled(false)
.build();
asyncHttpClient = new S3CrtAsyncHttpClient(s3Client, s3NativeClientConfiguration);
AsyncExecuteRequest asyncExecuteRequest = getExecuteRequestBuilder().putHttpExecutionAttribute(OPERATION_NAME,
"GetObject")
.putHttpExecutionAttribute(HTTP_CHECKSUM,
httpChecksum)
.build();
S3MetaRequestOptions actual = makeRequest(asyncExecuteRequest);
assertThat(actual.getValidateChecksum()).isTrue();
}
private S3MetaRequestOptions makeRequest(AsyncExecuteRequest asyncExecuteRequest) {
ArgumentCaptor<S3MetaRequestOptions> s3MetaRequestOptionsArgumentCaptor =
ArgumentCaptor.forClass(S3MetaRequestOptions.class);
asyncHttpClient.execute(asyncExecuteRequest);
verify(s3Client).makeMetaRequest(s3MetaRequestOptionsArgumentCaptor.capture());
return s3MetaRequestOptionsArgumentCaptor.getValue();
}
@Test
public void streamingOperation_checksumAlgoProvided_shouldTakePrecedence() {
HttpChecksum httpChecksum = HttpChecksum.builder()
.isRequestStreaming(true)
.requestAlgorithm("SHA1")
.build();
AsyncExecuteRequest asyncExecuteRequest = getExecuteRequestBuilder().putHttpExecutionAttribute(OPERATION_NAME,
"PutObject")
.putHttpExecutionAttribute(HTTP_CHECKSUM,
httpChecksum)
.build();
S3MetaRequestOptions actual = makeRequest(asyncExecuteRequest);
assertThat(actual.getChecksumAlgorithm()).isEqualTo(ChecksumAlgorithm.SHA1);
}
@Test
public void closeHttpClient_shouldCloseUnderlyingResources() {
asyncHttpClient.close();
verify(s3Client).close();
s3NativeClientConfiguration.close();
}
@Test
void build_shouldPassThroughParameters() {
S3NativeClientConfiguration configuration =
S3NativeClientConfiguration.builder()
.maxConcurrency(100)
.signingRegion("us-west-2")
.thresholdInBytes(1024L)
.standardRetryOptions(
new StandardRetryOptions()
.withBackoffRetryOptions(new ExponentialBackoffRetryOptions().withMaxRetries(7)))
.httpConfiguration(S3CrtHttpConfiguration.builder()
.connectionTimeout(Duration.ofSeconds(1))
.connectionHealthConfiguration(c -> c.minimumThroughputInBps(1024L)
.minimumThroughputTimeout(Duration.ofSeconds(2)))
.proxyConfiguration(p -> p.host("127.0.0.1").port(8080))
.build())
.build();
S3CrtAsyncHttpClient client =
(S3CrtAsyncHttpClient) S3CrtAsyncHttpClient.builder().s3ClientConfiguration(configuration).build();
S3ClientOptions clientOptions = client.s3ClientOptions();
assertThat(clientOptions.getConnectTimeoutMs()).isEqualTo(1000);
assertThat(clientOptions.getMultiPartUploadThreshold()).isEqualTo(1024);
assertThat(clientOptions.getStandardRetryOptions().getBackoffRetryOptions().getMaxRetries()).isEqualTo(7);
assertThat(clientOptions.getMaxConnections()).isEqualTo(100);
assertThat(clientOptions.getMonitoringOptions()).satisfies(options -> {
assertThat(options.getMinThroughputBytesPerSecond()).isEqualTo(1024);
assertThat(options.getAllowableThroughputFailureIntervalSeconds()).isEqualTo(2);
});
assertThat(clientOptions.getProxyOptions()).satisfies(options -> {
assertThat(options.getHost()).isEqualTo("127.0.0.1");
assertThat(options.getPort()).isEqualTo(8080);
});
assertThat(clientOptions.getMonitoringOptions()).satisfies(options -> {
assertThat(options.getAllowableThroughputFailureIntervalSeconds()).isEqualTo(2);
assertThat(options.getMinThroughputBytesPerSecond()).isEqualTo(1024);
});
assertThat(clientOptions.getMaxConnections()).isEqualTo(100);
}
@Test
void build_partSizeConfigured_shouldApplyToThreshold() {
long partSizeInBytes = 10L;
S3NativeClientConfiguration configuration =
S3NativeClientConfiguration.builder()
.partSizeInBytes(partSizeInBytes)
.build();
S3CrtAsyncHttpClient client =
(S3CrtAsyncHttpClient) S3CrtAsyncHttpClient.builder().s3ClientConfiguration(configuration).build();
S3ClientOptions clientOptions = client.s3ClientOptions();
assertThat(clientOptions.getPartSize()).isEqualTo(partSizeInBytes);
assertThat(clientOptions.getMultiPartUploadThreshold()).isEqualTo(clientOptions.getPartSize());
}
@Test
void build_nullHttpConfiguration() {
S3NativeClientConfiguration configuration =
S3NativeClientConfiguration.builder()
.build();
S3CrtAsyncHttpClient client =
(S3CrtAsyncHttpClient) S3CrtAsyncHttpClient.builder().s3ClientConfiguration(configuration).build();
S3ClientOptions clientOptions = client.s3ClientOptions();
assertThat(clientOptions.getConnectTimeoutMs()).isZero();
assertThat(clientOptions.getMaxConnections()).isZero();
assertThat(clientOptions.getMonitoringOptions()).isNull();
assertThat(clientOptions.getProxyOptions()).isNull();
assertThat(clientOptions.getMonitoringOptions()).isNull();
}
private static Stream<Arguments> s3CrtHttpConfigurations() {
return Stream.of(
Arguments.of(S3CrtHttpConfiguration.builder()
.connectionTimeout(Duration.ofSeconds(1))
.connectionHealthConfiguration(c -> c.minimumThroughputInBps(1024L)
.minimumThroughputTimeout(Duration.ofSeconds(2)))
.proxyConfiguration(p -> p.host("127.0.0.1").port(8080))
.build(),
null,
"S3CrtHttpConfiguration with default useEnvironmentVariableFlag does not set "
+ "HttpProxyEnvironmentVariableSetting"),
Arguments.of(S3CrtHttpConfiguration.builder()
.proxyConfiguration(p -> p.host("127.0.0.1").port(8080).useEnvironmentVariableValues(false))
.build(),
HttpProxyEnvironmentVariableSetting.HttpProxyEnvironmentVariableType.DISABLED,
"S3CrtHttpConfiguration with other settings and useEnvironmentVariableFlag as false sets "
+ "HttpProxyEnvironmentVariableSetting as DISABLED"),
Arguments.of(S3CrtHttpConfiguration.builder().build(),
null, "S3CrtHttpConfiguration as null does not set HttpProxyEnvironmentVariableSetting"),
Arguments.of(S3CrtHttpConfiguration.builder()
.proxyConfiguration(p -> p.useEnvironmentVariableValues(false))
.build(),
HttpProxyEnvironmentVariableSetting.HttpProxyEnvironmentVariableType.DISABLED,
"S3CrtHttpConfiguration with only useEnvironmentVariableFlag as false sets "
+ "HttpProxyEnvironmentVariableSetting as DISABLED"
),
Arguments.of(S3CrtHttpConfiguration.builder()
.proxyConfiguration(p -> p.useEnvironmentVariableValues(true))
.build(),
null,
"S3CrtHttpConfiguration with only useEnvironmentVariableFlag as true sets "
+ "does not set HttpProxyEnvironmentVariableSetting")
);
}
@ParameterizedTest(name = "{index} - {2}.")
@MethodSource("s3CrtHttpConfigurations")
void build_ProxyConfigurationWithEnvironmentVariables(S3CrtHttpConfiguration s3CrtHttpConfiguration,
HttpProxyEnvironmentVariableSetting.HttpProxyEnvironmentVariableType environmentVariableType,
String testCase) {
S3NativeClientConfiguration configuration =
S3NativeClientConfiguration.builder()
.httpConfiguration(s3CrtHttpConfiguration)
.build();
S3CrtAsyncHttpClient client =
(S3CrtAsyncHttpClient) S3CrtAsyncHttpClient.builder().s3ClientConfiguration(configuration).build();
S3ClientOptions clientOptions = client.s3ClientOptions();
if (environmentVariableType == null) {
assertThat(clientOptions.getHttpProxyEnvironmentVariableSetting()).isNull();
} else {
assertThat(clientOptions.getHttpProxyEnvironmentVariableSetting().getEnvironmentVariableType())
.isEqualTo(environmentVariableType);
}
}
private AsyncExecuteRequest.Builder getExecuteRequestBuilder() {
return getExecuteRequestBuilder(443);
}
private AsyncExecuteRequest.Builder getExecuteRequestBuilder(Integer port) {
return AsyncExecuteRequest.builder()
.responseHandler(responseHandler)
.requestContentPublisher(contentPublisher)
.request(SdkHttpRequest.builder()
.protocol(DEFAULT_ENDPOINT.getScheme())
.method(SdkHttpMethod.GET)
.host(DEFAULT_ENDPOINT.getHost())
.port(port)
.encodedPath("/key")
.putHeader(CONTENT_LENGTH, "100")
.putHeader("amz-sdk-invocation-id",
"1234")
.putHeader("custom-header", "foobar")
.build());
}
}
| 4,411 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal/crt/S3CrtResponseHandlerAdapterTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.reactivestreams.Publisher;
import software.amazon.awssdk.core.async.DrainingSubscriber;
import software.amazon.awssdk.core.exception.SdkClientException;
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.http.SdkHttpResponse;
import software.amazon.awssdk.http.async.SdkAsyncHttpResponseHandler;
@RunWith(MockitoJUnitRunner.class)
public class S3CrtResponseHandlerAdapterTest {
private S3CrtResponseHandlerAdapter responseHandlerAdapter;
private TestResponseHandler sdkResponseHandler;
@Mock
private S3FinishedResponseContext context;
@Mock
private S3MetaRequest s3MetaRequest;
private CompletableFuture<Void> future;
@Before
public void setup() {
future = new CompletableFuture<>();
sdkResponseHandler = new TestResponseHandler();
responseHandlerAdapter = new S3CrtResponseHandlerAdapter(future,
sdkResponseHandler,
null);
responseHandlerAdapter.metaRequest(s3MetaRequest);
}
@Test
public void successfulResponse_shouldCompleteFutureSuccessfully() throws Exception {
HttpHeader[] httpHeaders = new HttpHeader[2];
httpHeaders[0] = new HttpHeader("foo", "1");
httpHeaders[1] = new HttpHeader("bar", "2");
int statusCode = 200;
responseHandlerAdapter.onResponseHeaders(statusCode, httpHeaders);
SdkHttpResponse actualSdkHttpResponse = sdkResponseHandler.sdkHttpResponse;
assertThat(actualSdkHttpResponse.statusCode()).isEqualTo(statusCode);
assertThat(actualSdkHttpResponse.firstMatchingHeader("foo")).contains("1");
assertThat(actualSdkHttpResponse.firstMatchingHeader("bar")).contains("2");
stubOnResponseBody();
responseHandlerAdapter.onFinished(stubResponseContext(0, 0, null));
future.get(5, TimeUnit.SECONDS);
assertThat(future).isCompleted();
verify(s3MetaRequest, times(2)).incrementReadWindow(11L);
verify(s3MetaRequest).close();
}
@Test
public void nullByteBuffer_shouldCompleteFutureExceptionally() {
HttpHeader[] httpHeaders = new HttpHeader[2];
httpHeaders[0] = new HttpHeader("foo", "1");
httpHeaders[1] = new HttpHeader("bar", "2");
int statusCode = 200;
responseHandlerAdapter.onResponseHeaders(statusCode, httpHeaders);
responseHandlerAdapter.onResponseBody(null, 0, 0);
Throwable actualException = sdkResponseHandler.error;
assertThat(actualException).isInstanceOf(IllegalStateException.class).hasMessageContaining("ByteBuffer delivered is "
+ "null");
assertThat(future).isCompletedExceptionally();
verify(s3MetaRequest).close();
}
@Test
public void errorResponse_shouldCompleteFutureSuccessfully() {
int statusCode = 400;
responseHandlerAdapter.onResponseHeaders(statusCode, new HttpHeader[0]);
SdkHttpResponse actualSdkHttpResponse = sdkResponseHandler.sdkHttpResponse;
assertThat(actualSdkHttpResponse.statusCode()).isEqualTo(400);
assertThat(actualSdkHttpResponse.headers()).isEmpty();
byte[] errorPayload = "errorResponse".getBytes(StandardCharsets.UTF_8);
stubOnResponseBody();
responseHandlerAdapter.onFinished(stubResponseContext(1, statusCode, errorPayload));
assertThat(future).isCompleted();
verify(s3MetaRequest).close();
}
@Test
public void requestFailed_shouldCompleteFutureExceptionally() {
responseHandlerAdapter.onFinished(stubResponseContext(1, 0, null));
Throwable actualException = sdkResponseHandler.error;
String message = "Failed to send the request";
assertThat(actualException).isInstanceOf(SdkClientException.class).hasMessageContaining(message);
assertThat(future).isCompletedExceptionally();
assertThatThrownBy(() -> future.join()).hasRootCauseInstanceOf(SdkClientException.class).hasMessageContaining(message);
verify(s3MetaRequest).close();
}
@Test
public void requestFailedWithCause_shouldCompleteFutureExceptionallyWithCause() {
RuntimeException cause = new RuntimeException("error");
S3FinishedResponseContext s3FinishedResponseContext = stubResponseContext(1, 0, null);
when(s3FinishedResponseContext.getCause()).thenReturn(cause);
responseHandlerAdapter.onFinished(s3FinishedResponseContext);
Throwable actualException = sdkResponseHandler.error;
String message = "Failed to send the request";
assertThat(actualException).isInstanceOf(SdkClientException.class).hasMessageContaining(message);
assertThat(future).isCompletedExceptionally();
assertThatThrownBy(() -> future.join()).hasRootCause(cause).hasMessageContaining(message);
verify(s3MetaRequest).close();
}
private S3FinishedResponseContext stubResponseContext(int errorCode, int responseStatus, byte[] errorPayload) {
Mockito.reset(context);
when(context.getErrorCode()).thenReturn(errorCode);
when(context.getResponseStatus()).thenReturn(responseStatus);
when(context.getErrorPayload()).thenReturn(errorPayload);
return context;
}
private void stubOnResponseBody() {
responseHandlerAdapter.onResponseBody(ByteBuffer.wrap("helloworld1".getBytes()), 1, 2);
responseHandlerAdapter.onResponseBody(ByteBuffer.wrap("helloworld2".getBytes()), 1, 2);
}
private static final class TestResponseHandler implements SdkAsyncHttpResponseHandler {
private SdkHttpResponse sdkHttpResponse;
private Throwable error;
@Override
public void onHeaders(SdkHttpResponse headers) {
this.sdkHttpResponse = headers;
}
@Override
public void onStream(Publisher<ByteBuffer> stream) {
stream.subscribe(new DrainingSubscriber<>());
}
@Override
public void onError(Throwable error) {
this.error = error;
}
}
}
| 4,412 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal/crt/UploadPartCopyRequestIterableTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.assertj.core.api.Assertions.assertThat;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.services.s3.model.CopyObjectRequest;
import software.amazon.awssdk.services.s3.model.UploadPartCopyRequest;
class UploadPartCopyRequestIterableTest {
@Test
void threeParts_shouldCreateThreeRequests() {
CopyObjectRequest copyObjectRequest = CopyObjectRequest.builder()
.destinationKey("destination")
.destinationBucket("destinationBucket")
.sourceKey("source")
.sourceBucket("sourceBucket")
.build();
UploadPartCopyRequestIterable uploadPartCopyRequests = new UploadPartCopyRequestIterable("id",
1024L,
copyObjectRequest,
3000L);
List<UploadPartCopyRequest> requests = uploadPartCopyRequests.stream().collect(Collectors.toList());
assertThat(requests.size()).isEqualTo(3);
assertThat(requests.get(0).copySourceRange()).isEqualTo("bytes=0-1023");
assertThat(requests.get(1).copySourceRange()).isEqualTo("bytes=1024-2047");
assertThat(requests.get(2).copySourceRange()).isEqualTo("bytes=2048-2999");
}
@Test
void twoParts_shouldCreateTwoRequests() {
CopyObjectRequest copyObjectRequest = CopyObjectRequest.builder()
.destinationKey("destination")
.destinationBucket("destinationBucket")
.sourceKey("source")
.sourceBucket("sourceBucket")
.build();
UploadPartCopyRequestIterable uploadPartCopyRequests = new UploadPartCopyRequestIterable("id",
1024L,
copyObjectRequest,
1025L);
List<UploadPartCopyRequest> requests = uploadPartCopyRequests.stream().collect(Collectors.toList());
assertThat(requests.size()).isEqualTo(2);
assertThat(requests.get(0).copySourceRange()).isEqualTo("bytes=0-1023");
assertThat(requests.get(1).copySourceRange()).isEqualTo("bytes=1024-1024");
}
}
| 4,413 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal/crt/DefaultS3CrtAsyncClientTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.util.concurrent.atomic.AtomicReference;
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.AwsS3V4Signer;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.core.async.AsyncResponseTransformer;
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.SdkInternalExecutionAttribute;
import software.amazon.awssdk.services.s3.DelegatingS3AsyncClient;
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.utils.AttributeMap;
class DefaultS3CrtAsyncClientTest {
@Test
void requestSignerOverrideProvided_shouldThrowException() {
try (S3AsyncClient s3AsyncClient = S3CrtAsyncClient.builder().build()) {
assertThatThrownBy(() -> s3AsyncClient.getObject(
b -> b.bucket("bucket").key("key").overrideConfiguration(o -> o.signer(AwsS3V4Signer.create())),
AsyncResponseTransformer.toBytes()).join()).hasCauseInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(() -> s3AsyncClient.putObject(
b -> b.bucket("bucket").key("key").overrideConfiguration(o -> o.signer(AwsS3V4Signer.create())),
AsyncRequestBody.fromString("foobar")).join()).hasCauseInstanceOf(UnsupportedOperationException.class);
}
}
@Test
void clientContextParamsSetOnBuilder_propagatedToInterceptors() {
AtomicReference<AttributeMap> clientContexParams = new AtomicReference<>();
ExecutionInterceptor paramsCaptor = new ExecutionInterceptor() {
@Override
public void beforeExecution(Context.BeforeExecution context, ExecutionAttributes executionAttributes) {
clientContexParams.set(executionAttributes.getAttribute(SdkInternalExecutionAttribute.CLIENT_CONTEXT_PARAMS));
throw new RuntimeException("BOOM");
}
};
DefaultS3CrtAsyncClient.DefaultS3CrtClientBuilder builder =
(DefaultS3CrtAsyncClient.DefaultS3CrtClientBuilder) S3CrtAsyncClient.builder();
builder.addExecutionInterceptor(paramsCaptor);
try (S3AsyncClient s3AsyncClient = builder.accelerate(false)
.forcePathStyle(true)
.build()) {
assertThatThrownBy(s3AsyncClient.listBuckets()::join).hasMessageContaining("BOOM");
AttributeMap attributeMap = clientContexParams.get();
assertThat(attributeMap.get(S3ClientContextParams.ACCELERATE)).isFalse();
assertThat(attributeMap.get(S3ClientContextParams.FORCE_PATH_STYLE)).isTrue();
assertThat(attributeMap.get(S3ClientContextParams.USE_ARN_REGION)).isFalse();
assertThat(attributeMap.get(S3ClientContextParams.DISABLE_MULTI_REGION_ACCESS_POINTS)).isFalse();
}
}
@ParameterizedTest
@ValueSource(longs = {0, -1L})
void invalidConfig_shouldThrowException(long value) {
assertThatThrownBy(() -> S3AsyncClient.crtBuilder().maxConcurrency((int) value).build()).isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("positive");
assertThatThrownBy(() -> S3AsyncClient.crtBuilder().initialReadBufferSizeInBytes(value).build()).isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining(
"positive");
assertThatThrownBy(() -> S3AsyncClient.crtBuilder().minimumPartSizeInBytes(value).build()).isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining(
"positive");
}
@Test
void crtClient_with_crossRegionAccessEnabled_asTrue(){
S3AsyncClient crossRegionCrtClient = S3AsyncClient.crtBuilder().crossRegionAccessEnabled(true).build();
assertThat(crossRegionCrtClient).isInstanceOf(DefaultS3CrtAsyncClient.class);
assertThat(((DelegatingS3AsyncClient)crossRegionCrtClient).delegate()).isInstanceOf(S3CrossRegionAsyncClient.class);
}
@Test
void crtClient_with_crossRegionAccessEnabled_asFalse(){
S3AsyncClient crossRegionDisabledCrtClient = S3AsyncClient.crtBuilder().crossRegionAccessEnabled(false).build();
assertThat(crossRegionDisabledCrtClient).isInstanceOf(DefaultS3CrtAsyncClient.class);
assertThat(((DelegatingS3AsyncClient)crossRegionDisabledCrtClient).delegate()).isNotInstanceOf(S3CrossRegionAsyncClient.class);
S3AsyncClient defaultCrtClient = S3AsyncClient.crtBuilder().build();
assertThat(defaultCrtClient).isInstanceOf(DefaultS3CrtAsyncClient.class);
assertThat(((DelegatingS3AsyncClient)defaultCrtClient).delegate()).isNotInstanceOf(S3CrossRegionAsyncClient.class);
}
}
| 4,414 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal/crt/CopyObjectHelperTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.internal.multipart.CopyObjectHelper;
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.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.HeadObjectRequest;
import software.amazon.awssdk.services.s3.model.HeadObjectResponse;
import software.amazon.awssdk.services.s3.model.NoSuchBucketException;
import software.amazon.awssdk.services.s3.model.UploadPartCopyRequest;
import software.amazon.awssdk.services.s3.model.UploadPartCopyResponse;
import software.amazon.awssdk.utils.CompletableFutureUtils;
class CopyObjectHelperTest {
private static final String SOURCE_BUCKET = "source";
private static final String SOURCE_KEY = "sourceKey";
private static final String DESTINATION_BUCKET = "destination";
private static final String DESTINATION_KEY = "destinationKey";
private static final String MULTIPART_ID = "multipartId";
private static final Long PART_SIZE_BYTES = 1024L;
private S3AsyncClient s3AsyncClient;
private CopyObjectHelper copyHelper;
private static final long PART_SIZE = 1024L;
private static final long UPLOAD_THRESHOLD = PART_SIZE * 2;
@BeforeEach
public void setUp() {
s3AsyncClient = Mockito.mock(S3AsyncClient.class);
copyHelper = new CopyObjectHelper(s3AsyncClient, PART_SIZE, UPLOAD_THRESHOLD);
}
@Test
void copyObject_HeadObjectRequestFailed_shouldFail() {
NoSuchBucketException exception = NoSuchBucketException.builder().build();
CompletableFuture<HeadObjectResponse> headFuture =
CompletableFutureUtils.failedFuture(exception);
when(s3AsyncClient.headObject(any(HeadObjectRequest.class)))
.thenReturn(headFuture);
CompletableFuture<CopyObjectResponse> future =
copyHelper.copyObject(copyObjectRequest());
assertThatThrownBy(future::join).hasCauseInstanceOf(NoSuchBucketException.class)
.hasStackTraceContaining("Failed to retrieve metadata")
.hasRootCause(exception);
}
@Test
void copyObject_HeadObjectRequestThrowsException_shouldFail() {
RuntimeException exception = new RuntimeException("oops");
when(s3AsyncClient.headObject(any(HeadObjectRequest.class)))
.thenThrow(exception);
CompletableFuture<CopyObjectResponse> future =
copyHelper.copyObject(copyObjectRequest());
assertThatThrownBy(future::join).hasCause(exception);
}
@Test
void singlePartCopy_happyCase_shouldSucceed() {
CopyObjectRequest copyObjectRequest = copyObjectRequest();
stubSuccessfulHeadObjectCall(512L);
CopyObjectResponse expectedResponse = CopyObjectResponse.builder().build();
CompletableFuture<CopyObjectResponse> copyFuture =
CompletableFuture.completedFuture(expectedResponse);
when(s3AsyncClient.copyObject(copyObjectRequest)).thenReturn(copyFuture);
CompletableFuture<CopyObjectResponse> future =
copyHelper.copyObject(copyObjectRequest);
assertThat(future.join()).isEqualTo(expectedResponse);
}
@Test
void copy_doesNotExceedThreshold_shouldUseSingleObjectCopy() {
CopyObjectRequest copyObjectRequest = copyObjectRequest();
stubSuccessfulHeadObjectCall(2000L);
CopyObjectResponse expectedResponse = CopyObjectResponse.builder().build();
CompletableFuture<CopyObjectResponse> copyFuture =
CompletableFuture.completedFuture(expectedResponse);
when(s3AsyncClient.copyObject(copyObjectRequest)).thenReturn(copyFuture);
CompletableFuture<CopyObjectResponse> future =
copyHelper.copyObject(copyObjectRequest);
assertThat(future.join()).isEqualTo(expectedResponse);
}
@Test
void multiPartCopy_fourPartsHappyCase_shouldSucceed() {
CopyObjectRequest copyObjectRequest = copyObjectRequest();
stubSuccessfulHeadObjectCall(4000L);
stubSuccessfulCreateMulipartCall();
stubSuccessfulUploadPartCopyCalls();
stubSuccessfulCompleteMultipartCall();
CompletableFuture<CopyObjectResponse> future =
copyHelper.copyObject(copyObjectRequest);
CopyObjectResponse actualResponse = future.join();
assertThat(actualResponse.copyObjectResult()).isNotNull();
ArgumentCaptor<UploadPartCopyRequest> argumentCaptor = ArgumentCaptor.forClass(UploadPartCopyRequest.class);
verify(s3AsyncClient, times(4)).uploadPartCopy(argumentCaptor.capture());
List<UploadPartCopyRequest> actualUploadPartCopyRequests = argumentCaptor.getAllValues();
assertThat(actualUploadPartCopyRequests).allSatisfy(d -> {
assertThat(d.sourceBucket()).isEqualTo(SOURCE_BUCKET);
assertThat(d.sourceKey()).isEqualTo(SOURCE_KEY);
assertThat(d.destinationBucket()).isEqualTo(DESTINATION_BUCKET);
assertThat(d.destinationKey()).isEqualTo(DESTINATION_KEY);
});
assertThat(actualUploadPartCopyRequests.get(0).copySourceRange()).isEqualTo("bytes=0-1023");
assertThat(actualUploadPartCopyRequests.get(1).copySourceRange()).isEqualTo("bytes=1024-2047");
assertThat(actualUploadPartCopyRequests.get(2).copySourceRange()).isEqualTo("bytes=2048-3071");
assertThat(actualUploadPartCopyRequests.get(3).copySourceRange()).isEqualTo("bytes=3072-3999");
}
/**
* Four parts, after the first part failed, the remaining four futures should be cancelled
*/
@Test
void multiPartCopy_onePartFailed_shouldFailOtherPartsAndAbort() {
CopyObjectRequest copyObjectRequest = copyObjectRequest();
stubSuccessfulHeadObjectCall(4000L);
stubSuccessfulCreateMulipartCall();
SdkClientException exception = SdkClientException.create("failed");
CompletableFuture<UploadPartCopyResponse> uploadPartCopyFuture1 =
CompletableFutureUtils.failedFuture(exception);
CompletableFuture<UploadPartCopyResponse> uploadPartCopyFuture2 = new CompletableFuture<>();
CompletableFuture<UploadPartCopyResponse> uploadPartCopyFuture3 = new CompletableFuture<>();
CompletableFuture<UploadPartCopyResponse> uploadPartCopyFuture4 = new CompletableFuture<>();
when(s3AsyncClient.uploadPartCopy(any(UploadPartCopyRequest.class)))
.thenReturn(uploadPartCopyFuture1, uploadPartCopyFuture2, uploadPartCopyFuture3, uploadPartCopyFuture4);
when(s3AsyncClient.abortMultipartUpload(any(AbortMultipartUploadRequest.class)))
.thenReturn(CompletableFuture.completedFuture(AbortMultipartUploadResponse.builder().build()));
CompletableFuture<CopyObjectResponse> future = copyHelper.copyObject(copyObjectRequest);
assertThatThrownBy(future::join).hasStackTraceContaining("Failed to send multipart requests").hasCause(exception);
verify(s3AsyncClient, never()).completeMultipartUpload(any(CompleteMultipartUploadRequest.class));
ArgumentCaptor<AbortMultipartUploadRequest> argumentCaptor = ArgumentCaptor.forClass(AbortMultipartUploadRequest.class);
verify(s3AsyncClient).abortMultipartUpload(argumentCaptor.capture());
AbortMultipartUploadRequest actualRequest = argumentCaptor.getValue();
assertThat(actualRequest.uploadId()).isEqualTo(MULTIPART_ID);
assertThat(uploadPartCopyFuture2).isCompletedExceptionally();
assertThat(uploadPartCopyFuture3).isCompletedExceptionally();
assertThat(uploadPartCopyFuture4).isCompletedExceptionally();
}
@Test
void multiPartCopy_completeMultipartFailed_shouldFailAndAbort() {
CopyObjectRequest copyObjectRequest = copyObjectRequest();
stubSuccessfulHeadObjectCall(4000L);
stubSuccessfulCreateMulipartCall();
stubSuccessfulUploadPartCopyCalls();
SdkClientException exception = SdkClientException.create("CompleteMultipartUpload failed");
CompletableFuture<CompleteMultipartUploadResponse> completeMultipartUploadFuture =
CompletableFutureUtils.failedFuture(exception);
when(s3AsyncClient.completeMultipartUpload(any(CompleteMultipartUploadRequest.class)))
.thenReturn(completeMultipartUploadFuture);
when(s3AsyncClient.abortMultipartUpload(any(AbortMultipartUploadRequest.class)))
.thenReturn(CompletableFuture.completedFuture(AbortMultipartUploadResponse.builder().build()));
CompletableFuture<CopyObjectResponse> future =
copyHelper.copyObject(copyObjectRequest);
assertThatThrownBy(future::join).hasStackTraceContaining("Failed to send multipart requests").hasCause(exception);
ArgumentCaptor<AbortMultipartUploadRequest> argumentCaptor = ArgumentCaptor.forClass(AbortMultipartUploadRequest.class);
verify(s3AsyncClient).abortMultipartUpload(argumentCaptor.capture());
AbortMultipartUploadRequest actualRequest = argumentCaptor.getValue();
assertThat(actualRequest.uploadId()).isEqualTo(MULTIPART_ID);
}
@Test
void multiPartCopy_contentSizeExceeds10000Parts_shouldAdjustPartSize() {
long contentLength = 1024L * 10_000 * 2; // twice too many parts with configures part size
stubSuccessfulHeadObjectCall(contentLength);
stubSuccessfulCreateMulipartCall();
stubSuccessfulUploadPartCopyCalls();
stubSuccessfulCompleteMultipartCall();
CopyObjectRequest copyObjectRequest = copyObjectRequest();
CompletableFuture<CopyObjectResponse> future = copyHelper.copyObject(copyObjectRequest);
CopyObjectResponse actualResponse = future.join();
assertThat(actualResponse.copyObjectResult()).isNotNull();
ArgumentCaptor<UploadPartCopyRequest> argumentCaptor = ArgumentCaptor.forClass(UploadPartCopyRequest.class);
verify(s3AsyncClient, times(10_000)).uploadPartCopy(argumentCaptor.capture());
List<UploadPartCopyRequest> actualUploadPartCopyRequests = argumentCaptor.getAllValues();
assertThat(actualUploadPartCopyRequests).allSatisfy(d -> {
assertThat(d.sourceBucket()).isEqualTo(SOURCE_BUCKET);
assertThat(d.sourceKey()).isEqualTo(SOURCE_KEY);
assertThat(d.destinationBucket()).isEqualTo(DESTINATION_BUCKET);
assertThat(d.destinationKey()).isEqualTo(DESTINATION_KEY);
});
long expectedPartSize = 2048L;
for (int i = 0; i < actualUploadPartCopyRequests.size(); i++) {
int rangeStart = (int) expectedPartSize * i;
int rangeEnd = (int) (rangeStart + (expectedPartSize - 1));
assertThat(actualUploadPartCopyRequests.get(i).copySourceRange()).isEqualTo(
String.format("bytes=%d-%d", rangeStart, rangeEnd));
}
}
@Test
public void multiPartCopy_sseCHeadersSetInOriginalRequest_includedInCompleteMultipart() {
String customerAlgorithm = "algorithm";
String customerKey = "key";
String customerKeyMd5 = "keyMd5";
CopyObjectRequest copyRequest = copyObjectRequest().copy(r -> r.sseCustomerAlgorithm(customerAlgorithm)
.sseCustomerKey(customerKey)
.sseCustomerKeyMD5(customerKeyMd5));
stubSuccessfulHeadObjectCall(3 * PART_SIZE_BYTES);
stubSuccessfulCreateMulipartCall();
stubSuccessfulUploadPartCopyCalls();
stubSuccessfulCompleteMultipartCall();
copyHelper.copyObject(copyRequest).join();
ArgumentCaptor<CompleteMultipartUploadRequest> completeMultipartCaptor =
ArgumentCaptor.forClass(CompleteMultipartUploadRequest.class);
verify(s3AsyncClient).completeMultipartUpload(completeMultipartCaptor.capture());
CompleteMultipartUploadRequest completeRequest = completeMultipartCaptor.getValue();
assertThat(completeRequest.sseCustomerAlgorithm()).isEqualTo(customerAlgorithm);
assertThat(completeRequest.sseCustomerKey()).isEqualTo(customerKey);
assertThat(completeRequest.sseCustomerKeyMD5()).isEqualTo(customerKeyMd5);
}
@Test
void copy_cancelResponseFuture_shouldPropagate() {
CopyObjectRequest copyObjectRequest = copyObjectRequest();
CompletableFuture<HeadObjectResponse> headFuture = new CompletableFuture<>();
when(s3AsyncClient.headObject(any(HeadObjectRequest.class)))
.thenReturn(headFuture);
CompletableFuture<CopyObjectResponse> future =
copyHelper.copyObject(copyObjectRequest);
future.cancel(true);
assertThat(headFuture).isCancelled();
}
private void stubSuccessfulUploadPartCopyCalls() {
when(s3AsyncClient.uploadPartCopy(any(UploadPartCopyRequest.class)))
.thenAnswer(new Answer<CompletableFuture<UploadPartCopyResponse>>() {
int numberOfCalls = 0;
@Override
public CompletableFuture<UploadPartCopyResponse> answer(InvocationOnMock invocationOnMock) {
numberOfCalls++;
return CompletableFuture.completedFuture(UploadPartCopyResponse.builder().copyPartResult(CopyPartResult.builder()
.checksumCRC32("crc" + numberOfCalls)
.build())
.build());
}
});
}
private void stubSuccessfulCompleteMultipartCall() {
CompletableFuture<CompleteMultipartUploadResponse> completeMultipartUploadFuture =
CompletableFuture.completedFuture(CompleteMultipartUploadResponse.builder()
.bucket(DESTINATION_BUCKET)
.key(DESTINATION_KEY)
.build());
when(s3AsyncClient.completeMultipartUpload(any(CompleteMultipartUploadRequest.class)))
.thenReturn(completeMultipartUploadFuture);
}
private void stubSuccessfulHeadObjectCall(long contentLength) {
CompletableFuture<HeadObjectResponse> headFuture =
CompletableFuture.completedFuture(HeadObjectResponse.builder()
.contentLength(contentLength)
.build());
when(s3AsyncClient.headObject(any(HeadObjectRequest.class)))
.thenReturn(headFuture);
}
private void stubSuccessfulCreateMulipartCall() {
CompletableFuture<CreateMultipartUploadResponse> createMultipartUploadFuture =
CompletableFuture.completedFuture(CreateMultipartUploadResponse.builder()
.uploadId(MULTIPART_ID)
.build());
when(s3AsyncClient.createMultipartUpload(any(CreateMultipartUploadRequest.class)))
.thenReturn(createMultipartUploadFuture);
}
private static CopyObjectRequest copyObjectRequest() {
return CopyObjectRequest.builder()
.sourceBucket(SOURCE_BUCKET)
.sourceKey(SOURCE_KEY)
.destinationBucket(DESTINATION_BUCKET)
.destinationKey(DESTINATION_KEY)
.build();
}
}
| 4,415 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal/crt/CrtChecksumUtilsTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.assertj.core.api.Assertions.assertThat;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import software.amazon.awssdk.core.interceptor.trait.HttpChecksum;
import software.amazon.awssdk.crt.s3.ChecksumAlgorithm;
import software.amazon.awssdk.crt.s3.ChecksumConfig;
import software.amazon.awssdk.crt.s3.S3MetaRequestOptions;
class CrtChecksumUtilsTest {
private static Stream<Arguments> crtChecksumInput() {
List<ChecksumAlgorithm> checksumAlgorithms = new ArrayList<>();
checksumAlgorithms.add(ChecksumAlgorithm.SHA256);
checksumAlgorithms.add(ChecksumAlgorithm.SHA1);
return Stream.of(
// DEFAULT request, should pass empty config
Arguments.of(HttpChecksum.builder().build(), S3MetaRequestOptions.MetaRequestType.DEFAULT, true,
new ChecksumConfig()),
// PUT request with request algorithm, should set algorithm
Arguments.of(HttpChecksum.builder()
.requestAlgorithm("sha256")
.build(),
S3MetaRequestOptions.MetaRequestType.PUT_OBJECT,
true,
new ChecksumConfig().withChecksumAlgorithm(ChecksumAlgorithm.SHA256).withChecksumLocation(ChecksumConfig.ChecksumLocation.TRAILER)),
// PUT request w/o request algorithm, should set default algorithm
Arguments.of(HttpChecksum.builder().build(), S3MetaRequestOptions.MetaRequestType.PUT_OBJECT, true,
new ChecksumConfig().withChecksumAlgorithm(ChecksumAlgorithm.CRC32).withChecksumLocation(ChecksumConfig.ChecksumLocation.TRAILER)),
// PUT request w/o request algorithm and checksum disabled, should pass empty config
Arguments.of(HttpChecksum.builder().build(), S3MetaRequestOptions.MetaRequestType.PUT_OBJECT, false,
new ChecksumConfig()),
// No HttpChecksum, should pass empty config
Arguments.of(null, S3MetaRequestOptions.MetaRequestType.PUT_OBJECT, true,
new ChecksumConfig()),
// GET request w/o validate response algorithm, should set validate to true by default
Arguments.of(HttpChecksum.builder().build(),
S3MetaRequestOptions.MetaRequestType.GET_OBJECT, true,
new ChecksumConfig().withValidateChecksum(true)),
// GET request w/o validate response algorithm, should set validate to true by defaultt
Arguments.of(HttpChecksum.builder().responseAlgorithms("sha256", "sha1").build(),
S3MetaRequestOptions.MetaRequestType.GET_OBJECT, true,
new ChecksumConfig().withValidateChecksum(true).withValidateChecksumAlgorithmList(checksumAlgorithms)),
// GET request with validate response algorithm, should set ChecksumConfig
Arguments.of(HttpChecksum.builder().requestValidationMode("true").build(),
S3MetaRequestOptions.MetaRequestType.GET_OBJECT, true,
new ChecksumConfig().withValidateChecksum(true)),
// GET request w/o requestValidationMode and checksum disabled, should pass empty config
Arguments.of(HttpChecksum.builder().build(),
S3MetaRequestOptions.MetaRequestType.GET_OBJECT, false,
new ChecksumConfig().withValidateChecksum(false)),
// GET request, No HttpChecksum, should pass empty config
Arguments.of(null,
S3MetaRequestOptions.MetaRequestType.GET_OBJECT, true,
new ChecksumConfig())
);
}
@ParameterizedTest
@MethodSource("crtChecksumInput")
void crtChecksumAlgorithm_differentInput(HttpChecksum checksum,
S3MetaRequestOptions.MetaRequestType type,
boolean checksumValidationEnabled,
ChecksumConfig expected) {
assertThat(CrtChecksumUtils.checksumConfig(checksum, type, checksumValidationEnabled)).usingRecursiveComparison().isEqualTo(expected);
}
}
| 4,416 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal/crt/CrtCredentialProviderAdapterTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CompletableFuture;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.AwsSessionCredentials;
import software.amazon.awssdk.auth.credentials.HttpCredentialsProvider;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.crt.auth.credentials.Credentials;
import software.amazon.awssdk.crt.auth.credentials.CredentialsProvider;
import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity;
import software.amazon.awssdk.identity.spi.IdentityProvider;
import software.amazon.awssdk.utils.SdkAutoCloseable;
public class CrtCredentialProviderAdapterTest {
@Test
void crtCredentials_withSession_shouldConvert() {
IdentityProvider<? extends AwsCredentialsIdentity> awsCredentialsProvider = StaticCredentialsProvider
.create(AwsSessionCredentials.create("foo", "bar", "session"));
CredentialsProvider crtCredentialsProvider = new CrtCredentialsProviderAdapter(awsCredentialsProvider)
.crtCredentials();
Credentials credentials = crtCredentialsProvider.getCredentials().join();
assertThat(credentials.getAccessKeyId()).isEqualTo("foo".getBytes(StandardCharsets.UTF_8));
assertThat(credentials.getSecretAccessKey()).isEqualTo("bar".getBytes(StandardCharsets.UTF_8));
assertThat(credentials.getSessionToken()).isEqualTo("session".getBytes(StandardCharsets.UTF_8));
}
@Test
void crtCredentials_withoutSession_shouldConvert() {
IdentityProvider<? extends AwsCredentialsIdentity> awsCredentialsProvider = StaticCredentialsProvider
.create(AwsBasicCredentials.create("foo", "bar"));
CredentialsProvider crtCredentialsProvider = new CrtCredentialsProviderAdapter(awsCredentialsProvider)
.crtCredentials();
Credentials credentials = crtCredentialsProvider.getCredentials().join();
assertThat(credentials.getAccessKeyId()).isEqualTo("foo".getBytes(StandardCharsets.UTF_8));
assertThat(credentials.getSecretAccessKey()).isEqualTo("bar".getBytes(StandardCharsets.UTF_8));
assertThat(credentials.getSessionToken()).isNull();
}
@Test
void crtCredentials_provideAwsCredentials_shouldInvokeResolveAndClose() {
IdentityProvider<? extends AwsCredentialsIdentity> awsCredentialsProvider = Mockito.mock(HttpCredentialsProvider.class);
AwsCredentialsIdentity credentials = AwsCredentialsIdentity.create("foo", "bar");
when(awsCredentialsProvider.resolveIdentity()).thenAnswer(invocation -> CompletableFuture.completedFuture(credentials));
CrtCredentialsProviderAdapter adapter = new CrtCredentialsProviderAdapter(awsCredentialsProvider);
CredentialsProvider crtCredentialsProvider = adapter.crtCredentials();
Credentials crtCredentials = crtCredentialsProvider.getCredentials().join();
assertThat(crtCredentials.getAccessKeyId()).isEqualTo("foo".getBytes(StandardCharsets.UTF_8));
assertThat(crtCredentials.getSecretAccessKey()).isEqualTo("bar".getBytes(StandardCharsets.UTF_8));
verify(awsCredentialsProvider).resolveIdentity();
adapter.close();
verify((SdkAutoCloseable) awsCredentialsProvider).close();
}
@Test
void crtCredentials_anonymousCredentialsProvider_shouldWork() {
IdentityProvider<? extends AwsCredentialsIdentity> awsCredentialsProvider = AnonymousCredentialsProvider.create();
CrtCredentialsProviderAdapter adapter = new CrtCredentialsProviderAdapter(awsCredentialsProvider);
CredentialsProvider crtCredentialsProvider = adapter.crtCredentials();
Credentials crtCredentials = crtCredentialsProvider.getCredentials().join();
assertThat(crtCredentials.getAccessKeyId()).isNull();
assertThat(crtCredentials.getSecretAccessKey()).isNull();
}
}
| 4,417 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal/resource/OutpostAccessPointArnEndpointResolutionTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static software.amazon.awssdk.services.s3.S3MockUtils.mockListObjectsResponse;
import java.net.URI;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.signer.Signer;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.S3ClientBuilder;
import software.amazon.awssdk.services.s3.S3Configuration;
import software.amazon.awssdk.services.s3.model.ListObjectsRequest;
import software.amazon.awssdk.testutils.service.http.MockSyncHttpClient;
/**
* Functional tests for outpost access point ARN
*/
public class OutpostAccessPointArnEndpointResolutionTest {
private MockSyncHttpClient mockHttpClient;
private Signer mockSigner;
@BeforeEach
public void setup() {
mockHttpClient = new MockSyncHttpClient();
mockSigner = (request, executionAttributes) -> request;
}
@Test
public void outpostArn_correctlyRewritesEndpoint() throws Exception {
URI customEndpoint = URI.create("https://myaccesspoint-123456789012.op-01234567890123456.s3-outposts.ap-south-1.amazonaws.com");
mockHttpClient.stubNextResponse(mockListObjectsResponse());
S3Client s3Client = clientBuilder().build();
String outpostArn = "arn:aws:s3-outposts:ap-south-1:123456789012:outpost:op-01234567890123456:accesspoint:myaccesspoint";
s3Client.listObjects(ListObjectsRequest.builder().bucket(outpostArn).build());
assertThat(mockHttpClient.getLastRequest().firstMatchingHeader("Authorization").get()).contains("s3-outposts/aws4_request");
assertEndpointMatches(mockHttpClient.getLastRequest(), customEndpoint.toString());
}
@Test
public void outpostArn_dualstackEnabled_throwsIllegalArgumentException() throws Exception {
mockHttpClient.stubNextResponse(mockListObjectsResponse());
S3Client s3Client = clientBuilder().serviceConfiguration(S3Configuration.builder().dualstackEnabled(true).build()).build();
String outpostArn = "arn:aws:s3-outposts:ap-south-1:123456789012:outpost:op-01234567890123456:accesspoint:myaccesspoint";
assertThatThrownBy(() -> s3Client.listObjects(ListObjectsRequest.builder().bucket(outpostArn).build()))
.isInstanceOf(SdkClientException.class)
.hasMessageContaining("S3 Outposts does not support Dual-stack");
}
@Test
public void outpostArn_dualstackEnabledViaClient_throwsIllegalArgumentException() throws Exception {
mockHttpClient.stubNextResponse(mockListObjectsResponse());
S3Client s3Client = clientBuilder().dualstackEnabled(true).build();
String outpostArn = "arn:aws:s3-outposts:ap-south-1:123456789012:outpost:op-01234567890123456:accesspoint:myaccesspoint";
assertThatThrownBy(() -> s3Client.listObjects(ListObjectsRequest.builder().bucket(outpostArn).build()))
.isInstanceOf(SdkClientException.class)
.hasMessageContaining("S3 Outposts does not support Dual-stack");
}
@Test
public void outpostArn_fipsRegion_throwsIllegalArgumentException() throws Exception {
mockHttpClient.stubNextResponse(mockListObjectsResponse());
S3Client s3Client = clientBuilder().region(Region.of("fips-us-east-1")).serviceConfiguration(S3Configuration.builder().dualstackEnabled(false).build()).build();
String outpostArn = "arn:aws:s3-outposts:us-east-1:123456789012:outpost:op-01234567890123456:accesspoint:myaccesspoint";
assertThatThrownBy(() -> s3Client.listObjects(ListObjectsRequest.builder().bucket(outpostArn).build()))
.isInstanceOf(SdkClientException.class)
.hasMessageContaining("S3 Outposts does not support FIPS");
}
@Test
public void outpostArn_fipsEnabled_throwsIllegalArgumentException() throws Exception {
mockHttpClient.stubNextResponse(mockListObjectsResponse());
S3Client s3Client = clientBuilder().region(Region.US_EAST_1).fipsEnabled(true).build();
String outpostArn = "arn:aws:s3-outposts:us-east-1:123456789012:outpost:op-01234567890123456:accesspoint:myaccesspoint";
assertThatThrownBy(() -> s3Client.listObjects(ListObjectsRequest.builder().bucket(outpostArn).build()))
.isInstanceOf(SdkClientException.class)
.hasMessageContaining("S3 Outposts does not support FIPS");
}
@Test
public void outpostArn_accelerateEnabled_throwsIllegalArgumentException() throws Exception {
mockHttpClient.stubNextResponse(mockListObjectsResponse());
S3Client s3Client = clientBuilder().serviceConfiguration(S3Configuration.builder().accelerateModeEnabled(true).build()).build();
String outpostArn = "arn:aws:s3-outposts:ap-south-1:123456789012:outpost:op-01234567890123456:accesspoint:myaccesspoint";
assertThatThrownBy(() -> s3Client.listObjects(ListObjectsRequest.builder().bucket(outpostArn).build()))
.isInstanceOf(SdkClientException.class)
.hasMessageContaining("S3 Outposts does not support S3 Accelerate");
}
@Test
public void outpostArn_pathStyle_throwsIllegalArgumentException() throws Exception {
mockHttpClient.stubNextResponse(mockListObjectsResponse());
S3Client s3Client = clientBuilder().serviceConfiguration(S3Configuration.builder().pathStyleAccessEnabled(true).build()).build();
String outpostArn = "arn:aws:s3-outposts:ap-south-1:123456789012:outpost:op-01234567890123456:accesspoint:myaccesspoint";
assertThatThrownBy(() -> s3Client.listObjects(ListObjectsRequest.builder().bucket(outpostArn).build()))
.isInstanceOf(SdkClientException.class)
.hasMessageContaining("Path-style addressing cannot be used with ARN buckets");
}
@Test
public void outpostArn_differentRegion_useArnRegionFalse_throwsIllegalArgumentException() throws Exception {
mockHttpClient.stubNextResponse(mockListObjectsResponse());
S3Client s3Client = clientBuilder().build();
String outpostArn = "arn:aws:s3-outposts:us-west-1:123456789012:outpost:op-01234567890123456:accesspoint:myaccesspoint";
assertThatThrownBy(() -> s3Client.listObjects(ListObjectsRequest.builder().bucket(outpostArn).build()))
.isInstanceOf(SdkClientException.class)
.hasMessageContaining("Invalid configuration: region from ARN `us-west-1` does not match client region `ap-south-1` and UseArnRegion is `false`");
}
@Test
public void outpostArn_differentRegion_useArnRegionTrue() throws Exception {
URI customEndpoint = URI.create("https://myaccesspoint-123456789012.op-01234567890123456.s3-outposts.us-west-2.amazonaws.com");
mockHttpClient.stubNextResponse(mockListObjectsResponse());
S3Client s3Client = clientBuilder().serviceConfiguration(b -> b.useArnRegionEnabled(true)).build();
String outpostArn = "arn:aws:s3-outposts:us-west-2:123456789012:outpost:op-01234567890123456:accesspoint:myaccesspoint";
s3Client.listObjects(ListObjectsRequest.builder().bucket(outpostArn).build());
assertEndpointMatches(mockHttpClient.getLastRequest(), customEndpoint.toString());
}
/**
* Assert that the provided request would have gone to the given endpoint.
*
* @param capturedRequest Request captured by mock HTTP client.
* @param endpoint Expected endpoint.
*/
private void assertEndpointMatches(SdkHttpRequest capturedRequest, String endpoint) {
assertThat(capturedRequest.getUri()).isEqualTo(URI.create(endpoint));
}
/**
* @param s3ServiceConfiguration Advanced configuration to use for this client.
* @return A built client with the given advanced configuration.
*/
private S3Client buildClient(S3Configuration s3ServiceConfiguration) {
return clientBuilder()
.serviceConfiguration(s3ServiceConfiguration)
.build();
}
/**
* @return Client builder instance preconfigured with credentials and region using the {@link #mockHttpClient} for transport.
*/
private S3ClientBuilder clientBuilder() {
return S3Client.builder()
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid")))
.region(Region.AP_SOUTH_1)
.httpClient(mockHttpClient);
}
}
| 4,418 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal/resource/S3ObjectLambdaResourceTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
/**
* Tests for {@link S3ObjectLambdaResource}
*/
public class S3ObjectLambdaResourceTest {
private static final String PARTITION = "partition";
private static final String REGION = "region";
private static final String ACCOUNT_ID = "123456789012";
private static final String ACCESS_POINT_NAME = "object-lambda";
@Rule
public ExpectedException exception = ExpectedException.none();
@Test
public void build_allPropertiesSet_returnedFromObject() {
S3ObjectLambdaResource accessPoint = S3ObjectLambdaResource.builder()
.partition(PARTITION)
.region(REGION)
.accountId(ACCOUNT_ID)
.accessPointName(ACCESS_POINT_NAME)
.build();
assertThat(accessPoint.partition().get(), equalTo(PARTITION));
assertThat(accessPoint.region().get(), equalTo(REGION));
assertThat(accessPoint.accountId().get(), equalTo(ACCOUNT_ID));
assertThat(accessPoint.accessPointName(), equalTo(ACCESS_POINT_NAME));
}
@Test
public void build_noPartitionSet_throwsNullPointerException() {
exception.expect(NullPointerException.class);
exception.expectMessage("partition");
S3ObjectLambdaResource.builder()
.region(REGION)
.accountId(ACCOUNT_ID)
.accessPointName(ACCESS_POINT_NAME)
.build();
}
@Test
public void build_noRegionSet_throwsNullPointerException() {
exception.expect(NullPointerException.class);
exception.expectMessage("region");
S3ObjectLambdaResource.builder()
.partition(PARTITION)
.accountId(ACCOUNT_ID)
.accessPointName(ACCESS_POINT_NAME)
.build();
}
@Test
public void build_noAccountIdSet_throwsNullPointerException() {
exception.expect(NullPointerException.class);
exception.expectMessage("account");
S3ObjectLambdaResource.builder()
.partition(PARTITION)
.region(REGION)
.accessPointName(ACCESS_POINT_NAME)
.build();
}
@Test
public void build_noAccessPointNameSet_throwsNullPointerException() {
exception.expect(NullPointerException.class);
exception.expectMessage("accessPointName");
S3ObjectLambdaResource.builder()
.partition(PARTITION)
.region(REGION)
.accountId(ACCOUNT_ID)
.build();
}
@Test
public void build_noPartitionSet_throwsIllegalArgumentException() {
exception.expect(IllegalArgumentException.class);
exception.expectMessage("partition");
S3ObjectLambdaResource.builder()
.partition("")
.region(REGION)
.accountId(ACCOUNT_ID)
.accessPointName(ACCESS_POINT_NAME)
.build();
}
@Test
public void build_noRegionSet_throwsIllegalArgumentException() {
exception.expect(IllegalArgumentException.class);
exception.expectMessage("region");
S3ObjectLambdaResource.builder()
.partition(PARTITION)
.region("")
.accountId(ACCOUNT_ID)
.accessPointName(ACCESS_POINT_NAME)
.build();
}
@Test
public void build_noAccountIdSet_throwsIllegalArgumentException() {
exception.expect(IllegalArgumentException.class);
exception.expectMessage("account");
S3ObjectLambdaResource.builder()
.partition(PARTITION)
.region(REGION)
.accountId("")
.accessPointName(ACCESS_POINT_NAME)
.build();
}
@Test
public void build_noAccessPointNameSet_throwsIllegalArgumentException() {
exception.expect(IllegalArgumentException.class);
exception.expectMessage("accessPointName");
S3ObjectLambdaResource.builder()
.partition(PARTITION)
.region(REGION)
.accountId(ACCOUNT_ID)
.accessPointName("")
.build();
}
@Test
public void hashCode_sameValues_equal() {
S3ObjectLambdaResource resource1 = S3ObjectLambdaResource.builder()
.partition(PARTITION)
.region(REGION)
.accountId(ACCOUNT_ID)
.accessPointName(ACCESS_POINT_NAME)
.build();
S3ObjectLambdaResource resource2 = S3ObjectLambdaResource.builder()
.partition(PARTITION)
.region(REGION)
.accountId(ACCOUNT_ID)
.accessPointName(ACCESS_POINT_NAME)
.build();
assertThat(resource1.hashCode(), equalTo(resource2.hashCode()));
}
@Test
public void hashCode_incorporatesAllMembers_notEqual() {
String dummy = "foo";
S3ObjectLambdaResource accessPoint = S3ObjectLambdaResource.builder()
.partition(PARTITION)
.region(REGION)
.accountId(ACCOUNT_ID)
.accessPointName(ACCESS_POINT_NAME)
.build();
S3ObjectLambdaResource partitionDifferent = S3ObjectLambdaResource.builder()
.partition(dummy)
.region(REGION)
.accountId(ACCOUNT_ID)
.accessPointName(ACCESS_POINT_NAME)
.build();
assertThat(accessPoint.hashCode(), not(equalTo(partitionDifferent.hashCode())));
S3ObjectLambdaResource regionDifferent = S3ObjectLambdaResource.builder()
.partition(PARTITION)
.region(dummy)
.accountId(ACCOUNT_ID)
.accessPointName(ACCESS_POINT_NAME)
.build();
assertThat(accessPoint.hashCode(), not(equalTo(regionDifferent.hashCode())));
S3ObjectLambdaResource accountDifferent = S3ObjectLambdaResource.builder()
.partition(PARTITION)
.region(REGION)
.accountId(dummy)
.accessPointName(ACCESS_POINT_NAME)
.build();
assertThat(accessPoint.hashCode(), not(equalTo(accountDifferent.hashCode())));
S3ObjectLambdaResource accessPointNameDifferent = S3ObjectLambdaResource.builder()
.partition(PARTITION)
.region(REGION)
.accountId(ACCOUNT_ID)
.accessPointName(dummy)
.build();
assertThat(accessPoint.hashCode(), not(equalTo(accessPointNameDifferent.hashCode())));
}
@Test
public void equals_sameValues_isTrue() {
S3ObjectLambdaResource resource1 = S3ObjectLambdaResource.builder()
.partition(PARTITION)
.region(REGION)
.accountId(ACCOUNT_ID)
.accessPointName(ACCESS_POINT_NAME)
.build();
S3ObjectLambdaResource resource2 = S3ObjectLambdaResource.builder()
.partition(PARTITION)
.region(REGION)
.accountId(ACCOUNT_ID)
.accessPointName(ACCESS_POINT_NAME)
.build();
assertThat(resource1.equals(resource2), is(true));
}
@Test
public void equals_incorporatesAllMembers_isFalse() {
String dummy = "foo";
S3ObjectLambdaResource accessPoint = S3ObjectLambdaResource.builder()
.partition(PARTITION)
.region(REGION)
.accountId(ACCOUNT_ID)
.accessPointName(ACCESS_POINT_NAME)
.build();
S3ObjectLambdaResource partitionDifferent = S3ObjectLambdaResource.builder()
.partition(dummy)
.region(REGION)
.accountId(ACCOUNT_ID)
.accessPointName(ACCESS_POINT_NAME)
.build();
assertThat(accessPoint.equals(partitionDifferent), is(false));
S3ObjectLambdaResource regionDifferent = S3ObjectLambdaResource.builder()
.partition(PARTITION)
.region(dummy)
.accountId(ACCOUNT_ID)
.accessPointName(ACCESS_POINT_NAME)
.build();
assertThat(accessPoint.equals(regionDifferent), is(false));
S3ObjectLambdaResource accountDifferent = S3ObjectLambdaResource.builder()
.partition(PARTITION)
.region(REGION)
.accountId(dummy)
.accessPointName(ACCESS_POINT_NAME)
.build();
assertThat(accessPoint.equals(accountDifferent), is(false));
S3ObjectLambdaResource accessPointNameDifferent = S3ObjectLambdaResource.builder()
.partition(PARTITION)
.region(REGION)
.accountId(ACCOUNT_ID)
.accessPointName(dummy)
.build();
assertThat(accessPoint.equals(accessPointNameDifferent), is(false));
}
}
| 4,419 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal/resource/S3AccessPointResourceTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import java.util.Optional;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public class S3AccessPointResourceTest {
@Rule
public ExpectedException exception = ExpectedException.none();
@Test
public void buildWithAllPropertiesSet() {
S3AccessPointResource s3AccessPointResource = S3AccessPointResource.builder()
.accessPointName("access_point-name")
.accountId("account-id")
.partition("partition")
.region("region")
.build();
assertEquals("access_point-name", s3AccessPointResource.accessPointName());
assertEquals(Optional.of("account-id"), s3AccessPointResource.accountId());
assertEquals(Optional.of("partition"), s3AccessPointResource.partition());
assertEquals(Optional.of("region"), s3AccessPointResource.region());
assertEquals("accesspoint", s3AccessPointResource.type());
}
@Test
public void toBuilder() {
S3AccessPointResource s3AccessPointResource = S3AccessPointResource.builder()
.accessPointName("access_point-name")
.accountId("account-id")
.partition("partition")
.region("region")
.build()
.toBuilder()
.build();
assertEquals("access_point-name", s3AccessPointResource.accessPointName());
assertEquals(Optional.of("account-id"), s3AccessPointResource.accountId());
assertEquals(Optional.of("partition"), s3AccessPointResource.partition());
assertEquals(Optional.of("region"), s3AccessPointResource.region());
assertEquals("accesspoint", s3AccessPointResource.type());
}
@Test
public void buildWithBlankRegion() {
S3AccessPointResource s3AccessPointResource = S3AccessPointResource.builder()
.accessPointName("access_point-name")
.accountId("account-id")
.partition("partition")
.region("")
.build();
assertEquals("access_point-name", s3AccessPointResource.accessPointName());
assertEquals(Optional.of("account-id"), s3AccessPointResource.accountId());
assertEquals(Optional.of("partition"), s3AccessPointResource.partition());
assertEquals(Optional.of(""), s3AccessPointResource.region());
assertEquals("accesspoint", s3AccessPointResource.type());
}
@Test
public void buildWithMissingRegion() {
S3AccessPointResource s3AccessPointResource = S3AccessPointResource.builder()
.accessPointName("access_point-name")
.accountId("account-id")
.partition("partition")
.build();
assertEquals("access_point-name", s3AccessPointResource.accessPointName());
assertEquals(Optional.of("account-id"), s3AccessPointResource.accountId());
assertEquals(Optional.of("partition"), s3AccessPointResource.partition());
assertEquals(Optional.empty(), s3AccessPointResource.region());
assertEquals("accesspoint", s3AccessPointResource.type());
}
@Test(expected = IllegalArgumentException.class)
public void buildWithBlankPartition() {
S3AccessPointResource.builder()
.accessPointName("access_point-name")
.accountId("account-id")
.region("region")
.partition("")
.build();
}
@Test(expected = IllegalArgumentException.class)
public void buildWithBlankAccountId() {
S3AccessPointResource.builder()
.accessPointName("access_point-name")
.partition("partition")
.region("region")
.accountId("")
.build();
}
@Test(expected = IllegalArgumentException.class)
public void buildWithBlankAccessPointName() {
S3AccessPointResource.builder()
.accountId("account-id")
.partition("partition")
.region("region")
.accessPointName("")
.build();
}
@Test(expected = NullPointerException.class)
public void buildWithMissingPartition() {
S3AccessPointResource.builder()
.accessPointName("access_point-name")
.accountId("account-id")
.region("region")
.build();
}
@Test(expected = NullPointerException.class)
public void buildWithMissingAccountId() {
S3AccessPointResource.builder()
.accessPointName("access_point-name")
.partition("partition")
.region("region")
.build();
}
@Test(expected = NullPointerException.class)
public void buildWithMissingAccessPointName() {
S3AccessPointResource.builder()
.accountId("account-id")
.partition("partition")
.region("region")
.build();
}
@Test
public void buildWithSetters() {
S3AccessPointResource.Builder builder = S3AccessPointResource.builder();
builder.setAccessPointName("access_point-name");
builder.setAccountId("account-id");
builder.setPartition("partition");
builder.setRegion("region");
S3AccessPointResource s3AccessPointResource = builder.build();
assertEquals("access_point-name", s3AccessPointResource.accessPointName());
assertEquals(Optional.of("account-id"), s3AccessPointResource.accountId());
assertEquals(Optional.of("partition"), s3AccessPointResource.partition());
assertEquals(Optional.of("region"), s3AccessPointResource.region());
assertEquals("accesspoint", s3AccessPointResource.type());
}
@Test
public void equalsHashcode_withoutParent() {
S3AccessPointResource s3BucketResource1 = S3AccessPointResource.builder()
.accessPointName("access_point")
.accountId("account-id")
.partition("partition")
.region("region")
.build();
S3AccessPointResource s3BucketResource2 = S3AccessPointResource.builder()
.accessPointName("access_point")
.accountId("account-id")
.partition("partition")
.region("region")
.build();
S3AccessPointResource s3BucketResource3 = S3AccessPointResource.builder()
.accessPointName("access_point")
.accountId("account-id")
.partition("different-partition")
.region("region")
.build();
assertEquals(s3BucketResource1, s3BucketResource2);
assertEquals(s3BucketResource1.hashCode(), s3BucketResource2.hashCode());
assertNotEquals(s3BucketResource1, s3BucketResource3);
assertNotEquals(s3BucketResource1.hashCode(), s3BucketResource3.hashCode());
}
@Test
public void equalsHashcode_withParent() {
S3OutpostResource parentResource = S3OutpostResource.builder()
.outpostId("1234")
.accountId("account-id")
.partition("partition")
.region("region")
.build();
S3OutpostResource parentResource2 = S3OutpostResource.builder()
.outpostId("5678")
.accountId("account-id")
.partition("partition")
.region("region")
.build();
S3AccessPointResource s3BucketResource1 = S3AccessPointResource.builder()
.accessPointName("access_point")
.parentS3Resource(parentResource)
.build();
S3AccessPointResource s3BucketResource2 = S3AccessPointResource.builder()
.accessPointName("access_point")
.parentS3Resource(parentResource)
.build();
S3AccessPointResource s3BucketResource3 = S3AccessPointResource.builder()
.accessPointName("access_point")
.parentS3Resource(parentResource2)
.build();
assertEquals(s3BucketResource1, s3BucketResource2);
assertEquals(s3BucketResource1.hashCode(), s3BucketResource2.hashCode());
assertNotEquals(s3BucketResource1, s3BucketResource3);
assertNotEquals(s3BucketResource1.hashCode(), s3BucketResource3.hashCode());
}
@Test
public void buildWithOutpostParent() {
S3OutpostResource parentResource = S3OutpostResource.builder()
.outpostId("1234")
.accountId("account-id")
.partition("partition")
.region("region")
.build();
S3AccessPointResource s3AccessPointResource = S3AccessPointResource.builder()
.parentS3Resource(parentResource)
.accessPointName("access-point-name")
.build();
assertEquals("access-point-name", s3AccessPointResource.accessPointName());
assertEquals(Optional.of("account-id"), s3AccessPointResource.accountId());
assertEquals(Optional.of("partition"), s3AccessPointResource.partition());
assertEquals(Optional.of("region"), s3AccessPointResource.region());
assertEquals("accesspoint", s3AccessPointResource.type());
assertEquals(Optional.of(parentResource), s3AccessPointResource.parentS3Resource());
}
@Test
public void buildWithInvalidParent_shouldThrowException() {
exception.expect(IllegalArgumentException.class);
exception.expectMessage("parentS3Resource");
S3BucketResource invalidParent = S3BucketResource.builder()
.bucketName("bucket")
.build();
S3AccessPointResource.builder()
.parentS3Resource(invalidParent)
.accessPointName("access-point-name")
.build();
}
@Test
public void hasParentAndPartition_shouldThrowException() {
exception.expect(IllegalArgumentException.class);
exception.expectMessage("has parent resource");
S3OutpostResource parentResource = S3OutpostResource.builder()
.outpostId("1234")
.accountId("account-id")
.partition("partition")
.region("region")
.build();
S3AccessPointResource.builder()
.accessPointName("access_point")
.partition("partition")
.parentS3Resource(parentResource)
.build();
}
@Test
public void hasParentAndAccountId_shouldThrowException() {
exception.expect(IllegalArgumentException.class);
exception.expectMessage("has parent resource");
S3OutpostResource parentResource = S3OutpostResource.builder()
.outpostId("1234")
.accountId("account-id")
.partition("partition")
.region("region")
.build();
S3AccessPointResource.builder()
.accessPointName("access_point")
.accountId("account id")
.parentS3Resource(parentResource)
.build();
}
@Test
public void hasParentAndRegion_shouldThrowException() {
exception.expect(IllegalArgumentException.class);
exception.expectMessage("has parent resource");
S3OutpostResource parentResource = S3OutpostResource.builder()
.outpostId("1234")
.accountId("account-id")
.partition("partition")
.region("region")
.build();
S3AccessPointResource.builder()
.accessPointName("access_point")
.region("region")
.parentS3Resource(parentResource)
.build();
}
} | 4,420 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal/resource/S3ObjectResourceTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import java.util.Optional;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public class S3ObjectResourceTest {
@Rule
public ExpectedException exception = ExpectedException.none();
@Test
public void buildWithBucketParent() {
S3BucketResource parentResource = S3BucketResource.builder()
.bucketName("bucket")
.accountId("account-id")
.partition("partition")
.region("region")
.build();
S3ObjectResource s3ObjectResource = S3ObjectResource.builder()
.key("key")
.parentS3Resource(parentResource)
.build();
assertEquals("key", s3ObjectResource.key());
assertEquals(Optional.of("account-id"), s3ObjectResource.accountId());
assertEquals(Optional.of("partition"), s3ObjectResource.partition());
assertEquals(Optional.of("region"), s3ObjectResource.region());
assertEquals("object", s3ObjectResource.type());
assertEquals(Optional.of(parentResource), s3ObjectResource.parentS3Resource());
}
@Test
public void buildWithAccessPointParent() {
S3AccessPointResource parentResource = S3AccessPointResource.builder()
.accessPointName("test-ap")
.accountId("account-id")
.partition("partition")
.region("region")
.build();
S3ObjectResource s3ObjectResource = S3ObjectResource.builder()
.key("key")
.parentS3Resource(parentResource)
.build();
assertEquals("key", s3ObjectResource.key());
assertEquals(Optional.of("account-id"), s3ObjectResource.accountId());
assertEquals(Optional.of("partition"), s3ObjectResource.partition());
assertEquals(Optional.of("region"), s3ObjectResource.region());
assertEquals("object", s3ObjectResource.type());
assertEquals(Optional.of(parentResource), s3ObjectResource.parentS3Resource());
}
@Test
public void buildWithInvalidParentType() {
S3Resource fakeS3ObjectResource = new S3Resource() {
@Override
public Optional<String> partition() {
return Optional.empty();
}
@Override
public Optional<String> region() {
return Optional.empty();
}
@Override
public Optional<String> accountId() {
return Optional.empty();
}
@Override
public String type() {
return null;
}
};
exception.expect(IllegalArgumentException.class);
exception.expectMessage("parentS3Resource");
S3ObjectResource.builder()
.parentS3Resource(fakeS3ObjectResource)
.key("key")
.build();
}
@Test
public void buildWithMissingKey() {
S3BucketResource parentResource = S3BucketResource.builder()
.bucketName("bucket")
.accountId("account-id")
.partition("partition")
.region("region")
.build();
exception.expect(NullPointerException.class);
exception.expectMessage("key");
S3ObjectResource.builder()
.parentS3Resource(parentResource)
.build();
}
@Test
public void buildWithMissingParent() {
exception.expect(NullPointerException.class);
exception.expectMessage("parentS3Resource");
S3ObjectResource.builder()
.key("test-key")
.build();
}
@Test
public void equalsAndHashCode_allPropertiesSame() {
S3BucketResource parentResource = S3BucketResource.builder()
.bucketName("bucket")
.accountId("account-id")
.partition("partition")
.region("region")
.build();
S3ObjectResource s3ObjectResource1 = S3ObjectResource.builder()
.key("key")
.parentS3Resource(parentResource)
.build();
S3ObjectResource s3ObjectResource2 = S3ObjectResource.builder()
.key("key")
.parentS3Resource(parentResource)
.build();
assertEquals(s3ObjectResource1, s3ObjectResource2);
assertEquals(s3ObjectResource1.hashCode(), s3ObjectResource2.hashCode());
}
@Test
public void equalsAndHashCode_differentKey() {
S3BucketResource parentResource = S3BucketResource.builder()
.bucketName("bucket")
.accountId("account-id")
.partition("partition")
.region("region")
.build();
S3ObjectResource s3ObjectResource1 = S3ObjectResource.builder()
.key("key1")
.parentS3Resource(parentResource)
.build();
S3ObjectResource s3ObjectResource2 = S3ObjectResource.builder()
.key("key2")
.parentS3Resource(parentResource)
.build();
assertNotEquals(s3ObjectResource1, s3ObjectResource2);
assertNotEquals(s3ObjectResource1.hashCode(), s3ObjectResource2.hashCode());
}
@Test
public void equalsAndHashCode_differentParent() {
S3BucketResource parentResource = S3BucketResource.builder()
.bucketName("bucket")
.accountId("account-id")
.partition("partition")
.region("region")
.build();
S3BucketResource parentResource2 = S3BucketResource.builder()
.bucketName("bucket2")
.accountId("account-id")
.partition("partition")
.region("region")
.build();
S3ObjectResource s3ObjectResource1 = S3ObjectResource.builder()
.key("key")
.parentS3Resource(parentResource)
.build();
S3ObjectResource s3ObjectResource2 = S3ObjectResource.builder()
.key("key")
.parentS3Resource(parentResource2)
.build();
assertNotEquals(s3ObjectResource1, s3ObjectResource2);
assertNotEquals(s3ObjectResource1.hashCode(), s3ObjectResource2.hashCode());
}
} | 4,421 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal/resource/S3ArnUtilsTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import java.util.Optional;
import java.util.UUID;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import software.amazon.awssdk.arns.Arn;
import software.amazon.awssdk.arns.ArnResource;
public class S3ArnUtilsTest {
@Rule
public ExpectedException exception = ExpectedException.none();
@Test
public void parseS3AccessPointArn_shouldParseCorrectly() {
S3AccessPointResource s3AccessPointResource = S3ArnUtils.parseS3AccessPointArn(Arn.builder()
.partition("aws")
.service("s3")
.region("us-east-1")
.accountId("123456789012")
.resource("accesspoint:accesspoint-name")
.build());
assertThat(s3AccessPointResource.accessPointName(), is("accesspoint-name"));
assertThat(s3AccessPointResource.accountId(), is(Optional.of("123456789012")));
assertThat(s3AccessPointResource.partition(), is(Optional.of("aws")));
assertThat(s3AccessPointResource.region(), is(Optional.of("us-east-1")));
assertThat(s3AccessPointResource.type(), is(S3ResourceType.ACCESS_POINT.toString()));
}
@Test
public void parseOutpostArn_arnWithColon_shouldParseCorrectly() {
IntermediateOutpostResource intermediateOutpostResource = S3ArnUtils.parseOutpostArn(Arn.builder()
.partition("aws")
.service("s3")
.region("us-east-1")
.accountId("123456789012")
.resource("outpost:22222:accesspoint:foobar")
.build());
assertThat(intermediateOutpostResource.outpostId(), is("22222"));
assertThat(intermediateOutpostResource.outpostSubresource(), equalTo(ArnResource.fromString("accesspoint:foobar")));
}
@Test
public void parseOutpostArn_arnWithSlash_shouldParseCorrectly() {
IntermediateOutpostResource intermediateOutpostResource = S3ArnUtils.parseOutpostArn(Arn.builder()
.partition("aws")
.service("s3")
.region("us-east-1")
.accountId("123456789012")
.resource("outpost/22222/accesspoint/foobar")
.build());
assertThat(intermediateOutpostResource.outpostId(), is("22222"));
assertThat(intermediateOutpostResource.outpostSubresource(), equalTo(ArnResource.fromString("accesspoint/foobar")));
}
@Test
public void parseOutpostArn_shouldParseCorrectly() {
IntermediateOutpostResource intermediateOutpostResource = S3ArnUtils.parseOutpostArn(Arn.builder()
.partition("aws")
.service("s3")
.region("us-east-1")
.accountId("123456789012")
.resource("outpost:22222:futuresegment:foobar")
.build());
assertThat(intermediateOutpostResource.outpostId(), is("22222"));
assertThat(intermediateOutpostResource.outpostSubresource(), equalTo(ArnResource.fromString("futuresegment/foobar")));
}
@Test
public void parseOutpostArn_malformedArnNullSubresourceType_shouldThrowException() {
exception.expect(IllegalArgumentException.class);
exception.expectMessage("Invalid format");
S3ArnUtils.parseOutpostArn(Arn.builder()
.partition("aws")
.service("s3")
.region("us-east-1")
.accountId("123456789012")
.resource("outpost/22222/")
.build());
}
@Test
public void parseOutpostArn_malformedArnNullSubresource_shouldThrowException() {
exception.expect(IllegalArgumentException.class);
exception.expectMessage("Invalid format for S3 Outpost ARN");
S3ArnUtils.parseOutpostArn(Arn.builder()
.partition("aws")
.service("s3")
.region("us-east-1")
.accountId("123456789012")
.resource("outpost:op-01234567890123456:accesspoint")
.build());
}
@Test
public void parseOutpostArn_malformedArnEmptyOutpostId_shouldThrowException() {
exception.expect(IllegalArgumentException.class);
exception.expectMessage("resource must not be blank or empty");
S3ArnUtils.parseOutpostArn(Arn.builder()
.partition("aws")
.service("s3")
.region("us-east-1")
.accountId("123456789012")
.resource("outpost::accesspoint:name")
.build());
}
@Test
public void getArnType_shouldRecognizeAccessPointArn() {
String arnString = "arn:aws:s3:us-west-2:123456789012:accesspoint/my-access-point";
assertThat(S3ArnUtils.getArnType(arnString), is(Optional.of(S3ResourceType.ACCESS_POINT)));
}
@Test
public void getArnType_shouldRecognizeOutpostArn() {
String arnString = "arn:aws:s3-outposts:us-west-2:123456789012:outpost/my-outpost/bucket/my-bucket";
assertThat(S3ArnUtils.getArnType(arnString), is(Optional.of(S3ResourceType.OUTPOST)));
}
@Test
public void getArnType_shouldNotThrow_onRandomInput() {
String arnString = UUID.randomUUID().toString();
assertThat(S3ArnUtils.getArnType(arnString), is(Optional.empty()));
}
}
| 4,422 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal/resource/S3BucketResourceTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import java.util.Optional;
import org.junit.Test;
public class S3BucketResourceTest {
@Test
public void buildWithAllPropertiesSet() {
S3BucketResource s3BucketResource = S3BucketResource.builder()
.bucketName("bucket")
.accountId("account-id")
.partition("partition")
.region("region")
.build();
assertEquals("bucket", s3BucketResource.bucketName());
assertEquals(Optional.of("account-id"), s3BucketResource.accountId());
assertEquals(Optional.of("partition"), s3BucketResource.partition());
assertEquals(Optional.of("region"), s3BucketResource.region());
assertEquals("bucket_name", s3BucketResource.type());
}
@Test
public void toBuilder() {
S3BucketResource s3BucketResource = S3BucketResource.builder()
.bucketName("bucket")
.accountId("account-id")
.partition("partition")
.region("region")
.build()
.toBuilder()
.build();
assertEquals("bucket", s3BucketResource.bucketName());
assertEquals(Optional.of("account-id"), s3BucketResource.accountId());
assertEquals(Optional.of("partition"), s3BucketResource.partition());
assertEquals(Optional.of("region"), s3BucketResource.region());
assertEquals("bucket_name", s3BucketResource.type());
}
@Test
public void buildWithSetters() {
S3BucketResource.Builder builder = S3BucketResource.builder();
builder.setBucketName("bucket");
builder.setAccountId("account-id");
builder.setPartition("partition");
builder.setRegion("region");
S3BucketResource s3BucketResource = builder.build();
assertEquals("bucket", s3BucketResource.bucketName());
assertEquals(Optional.of("account-id"), s3BucketResource.accountId());
assertEquals(Optional.of("partition"), s3BucketResource.partition());
assertEquals(Optional.of("region"), s3BucketResource.region());
assertEquals("bucket_name", s3BucketResource.type());
}
@Test
public void buildWithMinimalPropertiesSet() {
S3BucketResource s3BucketResource = S3BucketResource.builder()
.bucketName("bucket")
.build();
assertEquals("bucket", s3BucketResource.bucketName());
assertEquals(Optional.empty(), s3BucketResource.accountId());
assertEquals(Optional.empty(), s3BucketResource.partition());
assertEquals(Optional.empty(), s3BucketResource.region());
assertEquals("bucket_name", s3BucketResource.type());
}
@Test(expected = NullPointerException.class)
public void buildWithMissingBucketName() {
S3BucketResource.builder().build();
}
@Test(expected = IllegalArgumentException.class)
public void buildWithBlankBucketName() {
S3BucketResource.builder().bucketName("").build();
}
@Test
public void equals_allProperties() {
S3BucketResource s3BucketResource1 = S3BucketResource.builder()
.bucketName("bucket")
.accountId("account-id")
.partition("partition")
.region("region")
.build();
S3BucketResource s3BucketResource2 = S3BucketResource.builder()
.bucketName("bucket")
.accountId("account-id")
.partition("partition")
.region("region")
.build();
S3BucketResource s3BucketResource3 = S3BucketResource.builder()
.bucketName("bucket")
.accountId("account-id")
.partition("different-partition")
.region("region")
.build();
assertEquals(s3BucketResource1, s3BucketResource2);
assertNotEquals(s3BucketResource1, s3BucketResource3);
}
@Test
public void equals_minimalProperties() {
S3BucketResource s3BucketResource1 = S3BucketResource.builder()
.bucketName("bucket")
.build();
S3BucketResource s3BucketResource2 = S3BucketResource.builder()
.bucketName("bucket")
.build();
S3BucketResource s3BucketResource3 = S3BucketResource.builder()
.bucketName("another-bucket")
.build();
assertEquals(s3BucketResource1, s3BucketResource2);
assertNotEquals(s3BucketResource1, s3BucketResource3);
}
@Test
public void hashcode_allProperties() {
S3BucketResource s3BucketResource1 = S3BucketResource.builder()
.bucketName("bucket")
.accountId("account-id")
.partition("partition")
.region("region")
.build();
S3BucketResource s3BucketResource2 = S3BucketResource.builder()
.bucketName("bucket")
.accountId("account-id")
.partition("partition")
.region("region")
.build();
S3BucketResource s3BucketResource3 = S3BucketResource.builder()
.bucketName("bucket")
.accountId("account-id")
.partition("different-partition")
.region("region")
.build();
assertEquals(s3BucketResource1.hashCode(), s3BucketResource2.hashCode());
assertNotEquals(s3BucketResource1.hashCode(), s3BucketResource3.hashCode());
}
} | 4,423 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal/resource/S3ObjectLambdaEndpointResolutionTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static software.amazon.awssdk.services.s3.S3MockUtils.mockListObjectsResponse;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.S3ClientBuilder;
import software.amazon.awssdk.services.s3.S3Configuration;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.testutils.service.http.MockSyncHttpClient;
public class S3ObjectLambdaEndpointResolutionTest {
private MockSyncHttpClient mockHttpClient;
@BeforeEach
public void setup() throws UnsupportedEncodingException {
mockHttpClient = new MockSyncHttpClient();
mockHttpClient.stubNextResponse(mockListObjectsResponse());
}
// Invalid endpoints tests
@Test
public void objectLambdaArn_crossRegionArn_throwsIllegalArgumentException() {
S3Client s3Client = clientBuilder().build();
String objectLambdaArn = "arn:aws:s3-object-lambda:us-east-1:123456789012:accesspoint/myol";
assertThatThrownBy(() -> s3Client.getObject(GetObjectRequest.builder().bucket(objectLambdaArn).key("obj").build()))
.isInstanceOf(SdkClientException.class)
.hasMessageContaining("Invalid configuration: region from ARN `us-east-1` does not match client region `us-west-2` and UseArnRegion is `false`");
}
@Test
public void objectLambdaArn_dualstackEnabled_throwsIllegalArgumentException() {
S3Client s3Client = clientBuilder().serviceConfiguration(S3Configuration.builder()
.dualstackEnabled(true)
.useArnRegionEnabled(true)
.build()).build();
String objectLambdaArn = "arn:aws:s3-object-lambda:us-west-2:123456789012:accesspoint/myol";
assertThatThrownBy(() -> s3Client.getObject(GetObjectRequest.builder().bucket(objectLambdaArn).key("obj").build()))
.isInstanceOf(SdkClientException.class)
.hasMessageContaining("S3 Object Lambda does not support Dual-stack");
}
@Test
public void objectLambdaArn_crossPartition_throwsIllegalArgumentException() {
S3Client s3Client = clientBuilder().serviceConfiguration(S3Configuration.builder()
.useArnRegionEnabled(true)
.build()).build();
String objectLambdaArn = "arn:aws-cn:s3-object-lambda:cn-north-1:123456789012:accesspoint/myol";
assertThatThrownBy(() -> s3Client.getObject(GetObjectRequest.builder().bucket(objectLambdaArn).key("obj").build()))
.isInstanceOf(SdkClientException.class)
.hasMessageContaining("Client was configured for partition `aws` but ARN (`arn:aws-cn:s3-object-lambda:cn-north-1:123456789012:accesspoint/myol`) has `aws-cn`");
}
@Test
public void objectLambdaArn_accelerateEnabled_throwsIllegalArgumentException() {
S3Client s3Client = clientBuilder().serviceConfiguration(S3Configuration.builder()
.accelerateModeEnabled(true)
.build()).build();
String objectLambdaArn = "arn:aws:s3-object-lambda:us-west-2:123456789012:accesspoint/myol";
assertThatThrownBy(() -> s3Client.getObject(GetObjectRequest.builder().bucket(objectLambdaArn).key("obj").build()))
.isInstanceOf(SdkClientException.class)
.hasMessageContaining("S3 Object Lambda does not support S3 Accelerate");
}
@Test
public void objectLambdaArn_nonS3Arn_throwsIllegalArgumentException() {
S3Client s3Client = clientBuilder().build();
String objectLambdaArn = "arn:aws:sqs:us-west-2:123456789012:someresource";
assertThatThrownBy(() -> s3Client.getObject(GetObjectRequest.builder().bucket(objectLambdaArn).key("obj").build()))
.isInstanceOf(SdkClientException.class)
.hasMessageContaining("Invalid ARN: Unrecognized format: arn:aws:sqs:us-west-2:123456789012:someresource (type: someresource)");
}
@Test
public void objectLambdaArn_nonAccessPointArn_throwsIllegalArgumentException() {
S3Client s3Client = clientBuilder().build();
String objectLambdaArn = "arn:aws:s3-object-lambda:us-west-2:123456789012:bucket_name:mybucket";
assertThatThrownBy(() -> s3Client.getObject(GetObjectRequest.builder().bucket(objectLambdaArn).key("obj").build()))
.isInstanceOf(SdkClientException.class)
.hasMessageContaining("Invalid ARN: Object Lambda ARNs only support `accesspoint` arn types, but found: `bucket_name`");
}
@Test
public void objectLambdaArn_missingRegion_throwsNullPointerException() {
S3Client s3Client = clientBuilder().build();
String objectLambdaArn = "arn:aws:s3-object-lambda::123456789012:accesspoint/myol";
assertThatThrownBy(() -> s3Client.getObject(GetObjectRequest.builder().bucket(objectLambdaArn).key("obj").build()))
.isInstanceOf(SdkClientException.class)
.hasMessageContaining("Invalid ARN: bucket ARN is missing a region");
}
@Test
public void objectLambdaArn_missingAccountId_throwsNullPointerException() {
S3Client s3Client = clientBuilder().build();
String objectLambdaArn = "arn:aws:s3-object-lambda:us-west-2::accesspoint/myol";
assertThatThrownBy(() -> s3Client.getObject(GetObjectRequest.builder().bucket(objectLambdaArn).key("obj").build()))
.isInstanceOf(SdkClientException.class)
.hasMessageContaining("Invalid ARN: Missing account id");
}
@Test
public void objectLambdaArn_accoutIdContainsInvalidCharacters_throwsIllegalArgumentException() {
S3Client s3Client = clientBuilder().build();
String objectLambdaArn = "arn:aws:s3-object-lambda:us-west-2:123.45678.9012:accesspoint:mybucket";
assertThatThrownBy(() -> s3Client.getObject(GetObjectRequest.builder().bucket(objectLambdaArn).key("obj").build()))
.isInstanceOf(SdkClientException.class)
.hasMessageContaining("Invalid ARN: The account id may only contain a-z, A-Z, 0-9 and `-`. Found: `123.45678.9012`");
}
@Test
public void objectLambdaArn_missingAccessPointName_throwsIllegalArgumentException() {
S3Client s3Client = clientBuilder().build();
String objectLambdaArn = "arn:aws:s3-object-lambda:us-west-2:123456789012:accesspoint";
assertThatThrownBy(() -> s3Client.getObject(GetObjectRequest.builder().bucket(objectLambdaArn).key("obj").build()))
.isInstanceOf(SdkClientException.class)
.hasMessageContaining("Invalid ARN: Expected a resource of the format `accesspoint:<accesspoint name>` but no name was provided");
}
@Test
public void objectLambdaArn_accessPointNameContainsInvalidCharacters_star_throwsIllegalArgumentException() {
S3Client s3Client = clientBuilder().build();
String objectLambdaArn = "arn:aws:s3-object-lambda:us-west-2:123456789012:accesspoint:*";
assertThatThrownBy(() -> s3Client.getObject(GetObjectRequest.builder().bucket(objectLambdaArn).key("obj").build()))
.isInstanceOf(SdkClientException.class)
.hasMessageContaining("Invalid ARN: The access point name may only contain a-z, A-Z, 0-9 and `-`. Found: `*`");
}
@Test
public void objectLambdaArn_accessPointNameContainsInvalidCharacters_dot_throwsIllegalArgumentException() {
S3Client s3Client = clientBuilder().build();
String objectLambdaArn = "arn:aws:s3-object-lambda:us-west-2:123456789012:accesspoint:my.bucket";
assertThatThrownBy(() -> s3Client.getObject(GetObjectRequest.builder().bucket(objectLambdaArn).key("obj").build()))
.isInstanceOf(SdkClientException.class)
.hasMessageContaining("Invalid ARN: The access point name may only contain a-z, A-Z, 0-9 and `-`. Found: `my.bucket`");
}
@Test
public void objectLambdaArn_accessPointNameContainsSubResources_throwsIllegalArgumentException() {
S3Client s3Client = clientBuilder().build();
String objectLambdaArn = "arn:aws:s3-object-lambda:us-west-2:123456789012:accesspoint:mybucket:object:foo";
assertThatThrownBy(() -> s3Client.getObject(GetObjectRequest.builder().bucket(objectLambdaArn).key("obj").build()))
.isInstanceOf(SdkClientException.class)
.hasMessageContaining("Invalid ARN: The ARN may only contain a single resource component after `accesspoint`.");
}
// Valid endpoint tests
@Test
public void objectLambdaArn_normalCase_slashDelimiter_resolveEndpointCorrectly() {
URI expectedEndpoint = URI.create("myol-123456789012.s3-object-lambda.us-west-2.amazonaws.com");
S3Client s3Client = clientBuilder().build();
String objectLambdaArn = "arn:aws:s3-object-lambda:us-west-2:123456789012:accesspoint/myol";
s3Client.getObject(GetObjectRequest.builder().bucket(objectLambdaArn).key("obj").build());
assertEndpointMatches(mockHttpClient.getLastRequest(), expectedEndpoint);
}
@Test
public void objectLambdaArn_normalCase_colonDelimiter_resolveEndpointCorrectly() {
URI expectedEndpoint = URI.create("myol-123456789012.s3-object-lambda.us-west-2.amazonaws.com");
S3Client s3Client = clientBuilder().build();
String objectLambdaArn = "arn:aws:s3-object-lambda:us-west-2:123456789012:accesspoint:myol";
s3Client.getObject(GetObjectRequest.builder().bucket(objectLambdaArn).key("obj").build());
assertEndpointMatches(mockHttpClient.getLastRequest(), expectedEndpoint);
}
@Test
public void objectLambdaArn_fips_resolveEndpointCorrectly() {
URI expectedEndpoint = URI.create("myol-123456789012.s3-object-lambda-fips.us-west-2.amazonaws.com");
S3Client s3Client = clientBuilder().fipsEnabled(true).build();
String objectLambdaArn = "arn:aws:s3-object-lambda:us-west-2:123456789012:accesspoint/myol";
s3Client.getObject(GetObjectRequest.builder().bucket(objectLambdaArn).key("obj").build());
assertEndpointMatches(mockHttpClient.getLastRequest(), expectedEndpoint);
}
@Test
public void objectLambdaArn_crossRegion_useArnRegionTrue_resolveEndpointCorrectly() {
URI expectedEndpoint = URI.create("myol-123456789012.s3-object-lambda.us-east-1.amazonaws.com");
S3Client s3Client = clientBuilder().serviceConfiguration(S3Configuration.builder()
.useArnRegionEnabled(true)
.build()).build();
String objectLambdaArn = "arn:aws:s3-object-lambda:us-east-1:123456789012:accesspoint/myol";
s3Client.getObject(GetObjectRequest.builder().bucket(objectLambdaArn).key("obj").build());
assertEndpointMatches(mockHttpClient.getLastRequest(), expectedEndpoint);
}
@Test
public void objectLambdaArn_externalRegion_useArnRegionTrue_resolveEndpointCorrectly() {
URI expectedEndpoint = URI.create("myol-123456789012.s3-object-lambda.us-east-1.amazonaws.com");
S3Client s3Client = clientBuilder().region(Region.of("s3-external-1"))
.serviceConfiguration(S3Configuration.builder()
.useArnRegionEnabled(true)
.build())
.build();
String objectLambdaArn = "arn:aws:s3-object-lambda:us-east-1:123456789012:accesspoint/myol";
s3Client.getObject(GetObjectRequest.builder().bucket(objectLambdaArn).key("obj").build());
assertEndpointMatches(mockHttpClient.getLastRequest(), expectedEndpoint);
}
@Test
public void objectLambdaArn_globalRegion_useArnRegionTrue_resolveEndpointCorrectly() {
URI expectedEndpoint = URI.create("myol-123456789012.s3-object-lambda.us-east-1.amazonaws.com");
S3Client s3Client = clientBuilder().region(Region.of("aws-global"))
.serviceConfiguration(S3Configuration.builder()
.useArnRegionEnabled(true)
.build())
.build();
String objectLambdaArn = "arn:aws:s3-object-lambda:us-east-1:123456789012:accesspoint/myol";
s3Client.getObject(GetObjectRequest.builder().bucket(objectLambdaArn).key("obj").build());
assertEndpointMatches(mockHttpClient.getLastRequest(), expectedEndpoint);
}
@Test
public void objectLambdaArn_cnPartitionSameRegion_useArnRegionTrue_resolveEndpointCorrectly() {
URI expectedEndpoint = URI.create("myol-123456789012.s3-object-lambda.cn-north-1.amazonaws.com.cn");
S3Client s3Client = clientBuilder().region(Region.of("cn-north-1"))
.serviceConfiguration(S3Configuration.builder()
.useArnRegionEnabled(true)
.build())
.build();
String objectLambdaArn = "arn:aws-cn:s3-object-lambda:cn-north-1:123456789012:accesspoint/myol";
s3Client.getObject(GetObjectRequest.builder().bucket(objectLambdaArn).key("obj").build());
assertEndpointMatches(mockHttpClient.getLastRequest(), expectedEndpoint);
}
@Test
public void objectLambdaArn_cnPartitionSameRegion_useArnRegionFalse_resolveEndpointCorrectly() {
URI expectedEndpoint = URI.create("myol-123456789012.s3-object-lambda.cn-north-1.amazonaws.com.cn");
S3Client s3Client = clientBuilder().region(Region.of("cn-north-1")).build();
String objectLambdaArn = "arn:aws-cn:s3-object-lambda:cn-north-1:123456789012:accesspoint/myol";
s3Client.getObject(GetObjectRequest.builder().bucket(objectLambdaArn).key("obj").build());
assertEndpointMatches(mockHttpClient.getLastRequest(), expectedEndpoint);
}
@Test
public void objectLambdaArn_cnPartitionCrossRegion_useArnRegionTrue_resolveEndpointCorrectly() {
URI expectedEndpoint = URI.create("myol-123456789012.s3-object-lambda.cn-northwest-1.amazonaws.com.cn");
S3Client s3Client = clientBuilder().region(Region.of("cn-north-1"))
.serviceConfiguration(S3Configuration.builder()
.useArnRegionEnabled(true)
.build())
.build();
String objectLambdaArn = "arn:aws-cn:s3-object-lambda:cn-northwest-1:123456789012:accesspoint/myol";
s3Client.getObject(GetObjectRequest.builder().bucket(objectLambdaArn).key("obj").build());
assertEndpointMatches(mockHttpClient.getLastRequest(), expectedEndpoint);
}
@Test
public void objectLambdaArn_govRegion_useArnRegionTrue_resolveEndpointCorrectly() {
URI expectedEndpoint = URI.create("myol-123456789012.s3-object-lambda.us-gov-east-1.amazonaws.com");
S3Client s3Client = clientBuilder().region(Region.of("us-gov-east-1"))
.serviceConfiguration(S3Configuration.builder()
.useArnRegionEnabled(true)
.build())
.build();
String objectLambdaArn = "arn:aws-us-gov:s3-object-lambda:us-gov-east-1:123456789012:accesspoint/myol";
s3Client.getObject(GetObjectRequest.builder().bucket(objectLambdaArn).key("obj").build());
assertEndpointMatches(mockHttpClient.getLastRequest(), expectedEndpoint);
}
@Test
public void objectLambdaArn_customizeEndpoint_resolveEndpointCorrectly() throws Exception {
URI customEndpoint = URI.create("myol-123456789012.my-endpoint.com");
S3Client s3Client = clientBuilder().endpointOverride(URI.create("http://my-endpoint.com")).build();
String objectLambdaArn = "arn:aws:s3-object-lambda:us-west-2:123456789012:accesspoint/myol";
s3Client.getObject(GetObjectRequest.builder().bucket(objectLambdaArn).key("obj").build());
assertEndpointMatches(mockHttpClient.getLastRequest(), customEndpoint);
}
/**
* Assert that the provided request would have gone to the given endpoint.
*
* @param capturedRequest Request captured by mock HTTP client.
* @param endpoint Expected endpoint.
*/
private void assertEndpointMatches(SdkHttpRequest capturedRequest, URI endpoint) {
assertThat(capturedRequest.host()).isEqualTo(endpoint.toString());
}
/**
* @return Client builder instance preconfigured with credentials and region using the {@link #mockHttpClient} for transport.
*/
private S3ClientBuilder clientBuilder() {
return S3Client.builder()
.credentialsProvider(StaticCredentialsProvider
.create(AwsBasicCredentials.create("akid", "skid")))
.region(Region.US_WEST_2)
.httpClient(mockHttpClient);
}
}
| 4,424 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal/resource/S3AccessPointBuilderTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import java.net.URI;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public class S3AccessPointBuilderTest {
private static final String LONG_STRING_64 = "1234567890123456789012345678901234567890123456789012345678901234";
@Rule
public ExpectedException exception = ExpectedException.none();
@Test
public void toURI_noDualstack() {
URI result = S3AccessPointBuilder.create()
.accessPointName("access-point")
.accountId("account-id")
.region("region")
.protocol("protocol")
.domain("domain")
.toUri();
assertThat(result, is(URI.create("protocol://access-point-account-id.s3-accesspoint.region.domain")));
}
@Test
public void toURI_dualstack() {
URI result = S3AccessPointBuilder.create()
.accessPointName("access-point")
.accountId("account-id")
.region("region")
.protocol("protocol")
.domain("domain")
.dualstackEnabled(true)
.toUri();
assertThat(result,
is(URI.create("protocol://access-point-account-id.s3-accesspoint.dualstack.region.domain")));
}
@Test
public void toURI_FipsEnabled() {
URI result = S3AccessPointBuilder.create()
.accessPointName("access-point")
.accountId("account-id")
.region("region")
.protocol("protocol")
.domain("domain")
.fipsEnabled(true)
.toUri();
assertThat(result, is(URI.create("protocol://access-point-account-id.s3-accesspoint-fips.region.domain")));
}
@Test
public void toURI_accessPointNameWithSlashes_throwsIllegalArgumentException() {
assertThatThrownBy(() -> S3AccessPointBuilder.create()
.accessPointName("access/point")
.accountId("account-id")
.region("region")
.protocol("protocol")
.domain("domain")
.toUri())
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("accessPointName")
.hasMessageContaining("alphanumeric");
}
@Test
public void toURI_accountIdWithSlashes_throwsIllegalArgumentException() {
assertThatThrownBy(() -> S3AccessPointBuilder.create()
.accessPointName("accesspoint")
.accountId("account/id")
.region("region")
.protocol("protocol")
.domain("domain")
.toUri())
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("accountId")
.hasMessageContaining("alphanumeric");
}
@Test
public void toURI_accessPointNameWithTooLongString_throwsIllegalArgumentException() {
assertThatThrownBy(() -> S3AccessPointBuilder.create()
.accessPointName(LONG_STRING_64)
.accountId("account-id")
.region("region")
.protocol("protocol")
.domain("domain")
.toUri())
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("accessPointName")
.hasMessageContaining("63"); // max length
}
@Test
public void toURI_accountIdWithTooLongString_throwsIllegalArgumentException() {
assertThatThrownBy(() -> S3AccessPointBuilder.create()
.accessPointName("accesspoint")
.accountId(LONG_STRING_64)
.region("region")
.protocol("protocol")
.domain("domain")
.toUri())
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("accountId")
.hasMessageContaining("63"); // max length
}
@Test
public void toURI_accessPointNameWithEmptyString_throwsIllegalArgumentException() {
assertThatThrownBy(() -> S3AccessPointBuilder.create()
.accessPointName("")
.accountId("account-id")
.region("region")
.protocol("protocol")
.domain("domain")
.toUri())
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("accessPointName")
.hasMessageContaining("missing");
}
@Test
public void toURI_accountIdWithEmptyString_throwsIllegalArgumentException() {
assertThatThrownBy(() -> S3AccessPointBuilder.create()
.accessPointName("accesspoint")
.accountId("")
.region("region")
.protocol("protocol")
.domain("domain")
.toUri())
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("accountId")
.hasMessageContaining("missing");
}
@Test
public void toURI_accessPointNameWithUrlEncodedCharacters_throwsIllegalArgumentException() {
assertThatThrownBy(() -> S3AccessPointBuilder.create()
.accessPointName("access%2fpoint")
.accountId("account-id")
.region("region")
.protocol("protocol")
.domain("domain")
.toUri())
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("accessPointName")
.hasMessageContaining("alphanumeric");
}
@Test
public void toURI_accountIdWithUrlEncodedCharacters_throwsIllegalArgumentException() {
assertThatThrownBy(() -> S3AccessPointBuilder.create()
.accessPointName("accesspoint")
.accountId("account%2fid")
.region("region")
.protocol("protocol")
.domain("domain")
.toUri())
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("accountId")
.hasMessageContaining("alphanumeric");
}
@Test
public void toURI_noRegion_returnsGlobalEndpoint() {
URI result = S3AccessPointBuilder.create()
.accessPointName("access-point")
.accountId("account-id")
.region("")
.protocol("protocol")
.domain("domain")
.toUri();
assertThat(result, is(URI.create("protocol://access-point.accesspoint.s3-global.domain")));
}
@Test
public void toURI_noRegion_accessPointNameWithDots_returnsGlobalEndpoint() {
URI result = S3AccessPointBuilder.create()
.accessPointName("access-point.foobar")
.accountId("account-id")
.region("")
.protocol("protocol")
.domain("domain")
.toUri();
assertThat(result, is(URI.create("protocol://access-point.foobar.accesspoint.s3-global.domain")));
}
@Test
public void toURI_noRegion_accessPointNameWithDots_segmentHasInvalidLength() {
assertThatThrownBy(() -> S3AccessPointBuilder.create()
.accessPointName("access-point." + LONG_STRING_64)
.accountId("account-id")
.region("")
.protocol("protocol")
.domain("domain")
.toUri())
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("63")
.hasMessageContaining(LONG_STRING_64);
}
@Test
public void toURI_noRegion_accessPointNameWithDots_segmentHasInvalidCharacters() {
assertThatThrownBy(() -> S3AccessPointBuilder.create()
.accessPointName("access-point" + "." + "%2ffoobar")
.accountId("account-id")
.region("")
.protocol("protocol")
.domain("domain")
.toUri())
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("alphanumeric")
.hasMessageContaining("%2ffoobar");
}
} | 4,425 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal/resource/MultiRegionAccessPointEndpointResolutionTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static software.amazon.awssdk.services.s3.S3MockUtils.mockListObjectsResponse;
import java.net.URI;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.S3ClientBuilder;
import software.amazon.awssdk.services.s3.S3Configuration;
import software.amazon.awssdk.services.s3.model.ListObjectsRequest;
import software.amazon.awssdk.testutils.service.http.MockHttpClient;
import software.amazon.awssdk.testutils.service.http.MockSyncHttpClient;
/**
* Functional tests for multi-region access point ARN
*/
public class MultiRegionAccessPointEndpointResolutionTest {
private final static String MULTI_REGION_ARN = "arn:aws:s3::123456789012:accesspoint:mfzwi23gnjvgw.mrap";
private final static URI MULTI_REGION_ENDPOINT =
URI.create("https://mfzwi23gnjvgw.mrap.accesspoint.s3-global.amazonaws.com");
private MockHttpClient mockHttpClient;
@BeforeEach
public void setup() {
mockHttpClient = new MockSyncHttpClient();
}
@Test
public void multiRegionArn_correctlyRewritesEndpoint() throws Exception {
mockHttpClient.stubNextResponse(mockListObjectsResponse());
S3Client s3Client = clientBuilder().serviceConfiguration(S3Configuration.builder().build()).build();
s3Client.listObjects(ListObjectsRequest.builder().bucket(MULTI_REGION_ARN).build());
assertEndpointMatches(mockHttpClient.getLastRequest(), MULTI_REGION_ENDPOINT.toString());
}
@Test
public void multiRegionArn_useArnRegionEnabled_correctlyRewritesEndpoint() throws Exception {
mockHttpClient.stubNextResponse(mockListObjectsResponse());
S3Client s3Client = clientBuilder().serviceConfiguration(S3Configuration.builder()
.useArnRegionEnabled(true)
.build())
.build();
s3Client.listObjects(ListObjectsRequest.builder().bucket(MULTI_REGION_ARN).build());
assertEndpointMatches(mockHttpClient.getLastRequest(), MULTI_REGION_ENDPOINT.toString());
}
/* @Test
public void multiRegionArn_customEndpoint_throwsIllegalArgumentException() throws Exception {
URI customEndpoint = URI.create("https://foobar.amazonaws.com");
mockHttpClient.stubNextResponse(mockListObjectsResponse());
S3Client s3Client = clientBuilder().endpointOverride(customEndpoint).build();
assertThatThrownBy(() -> s3Client.listObjects(ListObjectsRequest.builder().bucket(MULTI_REGION_ARN).build()))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("endpoint override");
}*/
@Test
public void multiRegionArn_dualstackEnabled_throwsIllegalArgumentException() throws Exception {
mockHttpClient.stubNextResponse(mockListObjectsResponse());
S3Client s3Client = clientBuilder().serviceConfiguration(S3Configuration.builder()
.dualstackEnabled(true)
.build())
.build();
assertThatThrownBy(() -> s3Client.listObjects(ListObjectsRequest.builder().bucket(MULTI_REGION_ARN).build()))
.isInstanceOf(SdkClientException.class)
.hasMessageContaining("S3 MRAP does not support dual-stack");
}
@Test
public void multiRegionArn_fipsRegion_throwsIllegalArgumentException() throws Exception {
mockHttpClient.stubNextResponse(mockListObjectsResponse());
S3Client s3Client = clientBuilder().region(Region.of("us-west-2"))
.fipsEnabled(true)
.serviceConfiguration(S3Configuration.builder()
.dualstackEnabled(false)
.build())
.build();
assertThatThrownBy(() -> s3Client.listObjects(ListObjectsRequest.builder().bucket(MULTI_REGION_ARN).build()))
.isInstanceOf(SdkClientException.class)
.hasMessageContaining("S3 MRAP does not support FIPS");
}
@Test
public void multiRegionArn_accelerateEnabled_throwsIllegalArgumentException() throws Exception {
mockHttpClient.stubNextResponse(mockListObjectsResponse());
S3Client s3Client = clientBuilder().serviceConfiguration(S3Configuration.builder()
.accelerateModeEnabled(true)
.build())
.build();
assertThatThrownBy(() -> s3Client.listObjects(ListObjectsRequest.builder().bucket(MULTI_REGION_ARN).build()))
.isInstanceOf(SdkClientException.class)
.hasMessageContaining("S3 MRAP does not support S3 Accelerate");
}
@Test
public void multiRegionArn_pathStyle_throwsIllegalArgumentException() throws Exception {
mockHttpClient.stubNextResponse(mockListObjectsResponse());
S3Client s3Client = clientBuilder().serviceConfiguration(S3Configuration.builder()
.pathStyleAccessEnabled(true)
.build())
.build();
assertThatThrownBy(() -> s3Client.listObjects(ListObjectsRequest.builder().bucket(MULTI_REGION_ARN).build()))
.isInstanceOf(SdkClientException.class)
.hasMessageContaining("Path-style addressing cannot be used with ARN buckets");
}
@Test
public void multiRegionArn_differentRegion_useArnRegionTrue() throws Exception {
mockHttpClient.stubNextResponse(mockListObjectsResponse());
S3Client s3Client = clientBuilder().build();
s3Client.listObjects(ListObjectsRequest.builder().bucket(MULTI_REGION_ARN).build());
assertEndpointMatches(mockHttpClient.getLastRequest(), MULTI_REGION_ENDPOINT.toString());
}
/**
* Assert that the provided request would have gone to the given endpoint.
*
* @param capturedRequest Request captured by mock HTTP client.
* @param endpoint Expected endpoint.
*/
private void assertEndpointMatches(SdkHttpRequest capturedRequest, String endpoint) {
assertThat(capturedRequest.getUri()).isEqualTo(URI.create(endpoint));
}
/**
* @return Client builder instance preconfigured with credentials and region using the {@link #mockHttpClient} for transport.
*/
private S3ClientBuilder clientBuilder() {
return S3Client.builder()
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid")))
.region(Region.AP_SOUTH_1)
.httpClient((MockSyncHttpClient) mockHttpClient);
}
}
| 4,426 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal/resource/S3ArnConverterTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import java.util.Optional;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import software.amazon.awssdk.arns.Arn;
public class S3ArnConverterTest {
private static final S3ArnConverter S3_ARN_PARSER = S3ArnConverter.create();
private static final String ACCOUNT_ID = "123456789012";
@Rule
public ExpectedException exception = ExpectedException.none();
@Test
public void parseArn_objectThroughAp_v2Arn() {
S3Resource resource = S3_ARN_PARSER.convertArn(Arn.builder()
.partition("aws")
.service("s3")
.region("us-east-1")
.accountId("123456789012")
.resource("accesspoint:test-ap/object/test-key")
.build());
assertThat(resource, instanceOf(S3ObjectResource.class));
S3ObjectResource s3ObjectResource = (S3ObjectResource) resource;
assertThat(s3ObjectResource.parentS3Resource().get(), instanceOf(S3AccessPointResource.class));
S3AccessPointResource s3AccessPointResource = (S3AccessPointResource)s3ObjectResource.parentS3Resource().get();
assertThat(s3AccessPointResource.accessPointName(), is("test-ap"));
assertThat(s3ObjectResource.key(), is("test-key"));
assertThat(s3ObjectResource.accountId(), is(Optional.of("123456789012")));
assertThat(s3ObjectResource.partition(), is(Optional.of("aws")));
assertThat(s3ObjectResource.region(), is(Optional.of("us-east-1")));
assertThat(s3ObjectResource.type(), is(S3ResourceType.OBJECT.toString()));
}
@Test
public void parseArn_object_v1Arn() {
S3Resource resource = S3_ARN_PARSER.convertArn(Arn.builder()
.partition("aws")
.service("s3")
.resource("bucket/key")
.build());
assertThat(resource, instanceOf(S3ObjectResource.class));
S3ObjectResource s3ObjectResource = (S3ObjectResource) resource;
assertThat(s3ObjectResource.parentS3Resource().get(), instanceOf(S3BucketResource.class));
S3BucketResource s3BucketResource = (S3BucketResource) s3ObjectResource.parentS3Resource().get();
assertThat(s3BucketResource.bucketName(), is("bucket"));
assertThat(s3ObjectResource.key(), is("key"));
assertThat(s3ObjectResource.accountId(), is(Optional.empty()));
assertThat(s3ObjectResource.partition(), is(Optional.of("aws")));
assertThat(s3ObjectResource.region(), is(Optional.empty()));
assertThat(s3ObjectResource.type(), is(S3ResourceType.OBJECT.toString()));
}
@Test
public void parseArn_accessPoint() {
S3Resource resource = S3_ARN_PARSER.convertArn(Arn.builder()
.partition("aws")
.service("s3")
.region("us-east-1")
.accountId("123456789012")
.resource("accesspoint:accesspoint-name")
.build());
assertThat(resource, instanceOf(S3AccessPointResource.class));
S3AccessPointResource s3EndpointResource = (S3AccessPointResource) resource;
assertThat(s3EndpointResource.accessPointName(), is("accesspoint-name"));
assertThat(s3EndpointResource.accountId(), is(Optional.of("123456789012")));
assertThat(s3EndpointResource.partition(), is(Optional.of("aws")));
assertThat(s3EndpointResource.region(), is(Optional.of("us-east-1")));
assertThat(s3EndpointResource.type(), is(S3ResourceType.ACCESS_POINT.toString()));
}
@Test
public void parseArn_accessPoint_withQualifier() {
S3Resource resource = S3_ARN_PARSER.convertArn(Arn.builder()
.partition("aws")
.service("s3")
.region("us-east-1")
.accountId("123456789012")
.resource("accesspoint:accesspoint-name:1214234234")
.build());
assertThat(resource, instanceOf(S3AccessPointResource.class));
S3AccessPointResource s3EndpointResource = (S3AccessPointResource) resource;
assertThat(s3EndpointResource.accessPointName(), is("accesspoint-name"));
assertThat(s3EndpointResource.accountId(), is(Optional.of("123456789012")));
assertThat(s3EndpointResource.partition(), is(Optional.of("aws")));
assertThat(s3EndpointResource.region(), is(Optional.of("us-east-1")));
assertThat(s3EndpointResource.type(), is(S3ResourceType.ACCESS_POINT.toString()));
}
@Test
public void parseArn_v1Bucket() {
S3Resource resource = S3_ARN_PARSER.convertArn(Arn.builder()
.partition("aws")
.service("s3")
.resource("bucket-name")
.build());
assertThat(resource, instanceOf(S3BucketResource.class));
S3BucketResource s3BucketResource = (S3BucketResource) resource;
assertThat(s3BucketResource.bucketName(), is("bucket-name"));
assertThat(s3BucketResource.accountId(), is(Optional.empty()));
assertThat(s3BucketResource.partition(), is(Optional.of("aws")));
assertThat(s3BucketResource.region(), is(Optional.empty()));
assertThat(s3BucketResource.type(), is(S3ResourceType.BUCKET.toString()));
}
@Test
public void parseArn_v2Bucket() {
S3Resource resource = S3_ARN_PARSER.convertArn(Arn.builder()
.partition("aws")
.service("s3")
.region("us-east-1")
.accountId("123456789012")
.resource("bucket_name:bucket-name")
.build());
assertThat(resource, instanceOf(S3BucketResource.class));
S3BucketResource s3BucketResource = (S3BucketResource) resource;
assertThat(s3BucketResource.bucketName(), is("bucket-name"));
assertThat(s3BucketResource.accountId(), is(Optional.of("123456789012")));
assertThat(s3BucketResource.partition(), is(Optional.of("aws")));
assertThat(s3BucketResource.region(), is(Optional.of("us-east-1")));
assertThat(s3BucketResource.type(), is(S3ResourceType.BUCKET.toString()));
}
@Test
public void parseArn_unknownResource() {
exception.expect(IllegalArgumentException.class);
exception.expectMessage("ARN type");
S3_ARN_PARSER.convertArn(Arn.builder()
.partition("aws")
.service("s3")
.region("us-east-1")
.accountId("123456789012")
.resource("unknown:foobar")
.build());
}
@Test
public void parseArn_bucket_noName() {
exception.expect(IllegalArgumentException.class);
S3_ARN_PARSER.convertArn(Arn.builder()
.partition("aws")
.service("s3")
.region("us-east-1")
.accountId("123456789012")
.resource("bucket_name:")
.build());
}
@Test
public void parseArn_accesspoint_noName() {
exception.expect(IllegalArgumentException.class);
S3_ARN_PARSER.convertArn(Arn.builder()
.partition("aws")
.service("s3")
.region("us-east-1")
.accountId("123456789012")
.resource("access_point:")
.build());
}
@Test
public void parseArn_object_v2Arn_noKey() {
exception.expect(IllegalArgumentException.class);
S3_ARN_PARSER.convertArn(Arn.builder()
.partition("aws")
.service("s3")
.region("us-east-1")
.accountId("123456789012")
.resource("object:bucket")
.build());
}
@Test
public void parseArn_object_v2Arn_emptyBucket() {
exception.expect(IllegalArgumentException.class);
S3_ARN_PARSER.convertArn(Arn.builder()
.partition("aws")
.service("s3")
.region("us-east-1")
.accountId("123456789012")
.resource("object:/key")
.build());
}
@Test
public void parseArn_object_v2Arn_emptyKey() {
exception.expect(IllegalArgumentException.class);
S3_ARN_PARSER.convertArn(Arn.builder()
.partition("aws")
.service("s3")
.region("us-east-1")
.accountId("123456789012")
.resource("object:bucket/")
.build());
}
@Test
public void parseArn_object_v1Arn_emptyKey() {
exception.expect(IllegalArgumentException.class);
S3_ARN_PARSER.convertArn(Arn.builder()
.partition("aws")
.service("s3")
.resource("bucket/")
.build());
}
@Test
public void parseArn_object_v1Arn_emptyBucket() {
exception.expect(IllegalArgumentException.class);
S3_ARN_PARSER.convertArn(Arn.builder()
.partition("aws")
.service("s3")
.resource("/key")
.build());
}
@Test
public void parseArn_unknownType_throwsCorrectException() {
exception.expect(IllegalArgumentException.class);
exception.expectMessage("invalidType");
S3_ARN_PARSER.convertArn(Arn.builder()
.partition("aws")
.service("s3")
.region("us-east-1")
.accountId("123456789012")
.resource("invalidType:something")
.build());
}
@Test
public void parseArn_outpostAccessPoint_slash() {
S3Resource resource = S3_ARN_PARSER.convertArn(Arn.builder()
.partition("aws")
.service("s3")
.region("us-east-1")
.accountId(ACCOUNT_ID)
.resource("outpost/22222/accesspoint/foobar")
.build());
assertThat(resource, instanceOf(S3AccessPointResource.class));
S3AccessPointResource s3AccessPointResource = (S3AccessPointResource) resource;
assertThat(s3AccessPointResource.accessPointName(), is("foobar"));
assertThat(s3AccessPointResource.parentS3Resource().get(), instanceOf(S3OutpostResource.class));
S3OutpostResource outpostResource = (S3OutpostResource)s3AccessPointResource.parentS3Resource().get();
assertThat(outpostResource.accountId(), is(Optional.of(ACCOUNT_ID)));
assertThat(outpostResource.partition(), is(Optional.of("aws")));
assertThat(outpostResource.region(), is(Optional.of("us-east-1")));
assertThat(outpostResource.outpostId(), is("22222"));
assertThat(outpostResource.type(), is(S3ResourceType.OUTPOST.toString()));
}
@Test
public void parseArn_outpostAccessPoint_colon() {
S3Resource resource = S3_ARN_PARSER.convertArn(Arn.builder()
.partition("aws")
.service("s3")
.region("us-east-1")
.accountId(ACCOUNT_ID)
.resource("outpost:22222:accesspoint:foobar")
.build());
assertThat(resource, instanceOf(S3AccessPointResource.class));
S3AccessPointResource s3AccessPointResource = (S3AccessPointResource) resource;
assertThat(s3AccessPointResource.accessPointName(), is("foobar"));
assertThat(s3AccessPointResource.parentS3Resource().get(), instanceOf(S3OutpostResource.class));
S3OutpostResource outpostResource = (S3OutpostResource)s3AccessPointResource.parentS3Resource().get();
assertThat(outpostResource.accountId(), is(Optional.of(ACCOUNT_ID)));
assertThat(outpostResource.partition(), is(Optional.of("aws")));
assertThat(outpostResource.region(), is(Optional.of("us-east-1")));
assertThat(outpostResource.outpostId(), is("22222"));
assertThat(outpostResource.type(), is(S3ResourceType.OUTPOST.toString()));
}
@Test
public void parseArn_globalAccessPoint_slash() {
S3Resource resource = S3_ARN_PARSER.convertArn(Arn.builder()
.partition("aws")
.service("s3")
.region("")
.accountId(ACCOUNT_ID)
.resource("accesspoint/mfzwi23gnjvgw.mrap")
.build());
assertThat(resource, instanceOf(S3AccessPointResource.class));
S3AccessPointResource s3AccessPointResource = (S3AccessPointResource) resource;
assertThat(s3AccessPointResource.type(), is(S3ResourceType.ACCESS_POINT.toString()));
assertThat(s3AccessPointResource.accessPointName(), is("mfzwi23gnjvgw.mrap"));
assertThat(s3AccessPointResource.accountId(), is(Optional.of(ACCOUNT_ID)));
assertThat(s3AccessPointResource.partition(), is(Optional.of("aws")));
assertThat(s3AccessPointResource.region(), is(Optional.empty()));
}
@Test
public void parseArn_globalAccessPoint_colon() {
S3Resource resource = S3_ARN_PARSER.convertArn(Arn.builder()
.partition("aws")
.service("s3")
.region("")
.accountId(ACCOUNT_ID)
.resource("accesspoint:mfzwi23gnjvgw.mrap")
.build());
assertThat(resource, instanceOf(S3AccessPointResource.class));
S3AccessPointResource s3AccessPointResource = (S3AccessPointResource) resource;
assertThat(s3AccessPointResource.type(), is(S3ResourceType.ACCESS_POINT.toString()));
assertThat(s3AccessPointResource.accessPointName(), is("mfzwi23gnjvgw.mrap"));
assertThat(s3AccessPointResource.accountId(), is(Optional.of(ACCOUNT_ID)));
assertThat(s3AccessPointResource.partition(), is(Optional.of("aws")));
assertThat(s3AccessPointResource.region(), is(Optional.empty()));
}
@Test
public void parseArn_globalAccessPoint_colon_multiple_dots() {
S3Resource resource = S3_ARN_PARSER.convertArn(Arn.builder()
.partition("aws")
.service("s3")
.region("")
.accountId(ACCOUNT_ID)
.resource("accesspoint:name.with.dot")
.build());
assertThat(resource, instanceOf(S3AccessPointResource.class));
S3AccessPointResource s3AccessPointResource = (S3AccessPointResource) resource;
assertThat(s3AccessPointResource.type(), is(S3ResourceType.ACCESS_POINT.toString()));
assertThat(s3AccessPointResource.accessPointName(), is("name.with.dot"));
assertThat(s3AccessPointResource.accountId(), is(Optional.of(ACCOUNT_ID)));
assertThat(s3AccessPointResource.partition(), is(Optional.of("aws")));
assertThat(s3AccessPointResource.region(), is(Optional.empty()));
}
@Test
public void parseArn_invalidOutpostAccessPointMissingAccessPointName_shouldThrowException() {
exception.expect(IllegalArgumentException.class);
exception.expectMessage("Invalid format");
S3_ARN_PARSER.convertArn(Arn.builder()
.partition("aws")
.service("s3")
.region("us-east-1")
.accountId(ACCOUNT_ID)
.resource("outpost:op-01234567890123456:accesspoint")
.build());
}
@Test
public void parseArn_invalidOutpostAccessPointMissingOutpostId_shouldThrowException() {
exception.expect(IllegalArgumentException.class);
exception.expectMessage("Invalid format");
S3_ARN_PARSER.convertArn(Arn.builder()
.partition("aws")
.service("s3")
.region("us-east-1")
.accountId(ACCOUNT_ID)
.resource("outpost/myaccesspoint")
.build());
}
@Test
public void parseArn_malformedOutpostArn_shouldThrowException() {
exception.expect(IllegalArgumentException.class);
exception.expectMessage("Unknown outpost ARN type");
S3_ARN_PARSER.convertArn(Arn.builder()
.partition("aws")
.service("s3")
.region("us-east-1")
.accountId(ACCOUNT_ID)
.resource("outpost:1:accesspoin1:1")
.build());
}
@Test
public void parseArn_objectLambda_slash() {
Arn arn = Arn.fromString("arn:aws:s3-object-lambda:us-west-2:123456789012:accesspoint/my-lambda");
S3Resource resource = S3_ARN_PARSER.convertArn(arn);
assertThat(resource.type(), is("accesspoint"));
S3ObjectLambdaResource objectLambdaResource = (S3ObjectLambdaResource) resource.parentS3Resource().get();
assertThat(objectLambdaResource.type(), is("object-lambda"));
assertThat(objectLambdaResource.region().get(), is("us-west-2"));
assertThat(objectLambdaResource.partition().get(), is("aws"));
assertThat(objectLambdaResource.accountId().get(), is("123456789012"));
assertThat(objectLambdaResource.accessPointName(), is("my-lambda"));
}
@Test
public void parseArn_objectLambda_colon() {
Arn arn = Arn.fromString("arn:aws:s3-object-lambda:us-west-2:123456789012:accesspoint:my-lambda");
S3Resource resource = S3_ARN_PARSER.convertArn(arn);
assertThat(resource.type(), is("accesspoint"));
S3ObjectLambdaResource objectLambdaResource = (S3ObjectLambdaResource) resource.parentS3Resource().get();
assertThat(objectLambdaResource.type(), is("object-lambda"));
assertThat(objectLambdaResource.region().get(), is("us-west-2"));
assertThat(objectLambdaResource.partition().get(), is("aws"));
assertThat(objectLambdaResource.accountId().get(), is("123456789012"));
assertThat(objectLambdaResource.accessPointName(), is("my-lambda"));
}
@Test
public void parseArn_objectLambda_noName_slash() {
exception.expect(IllegalArgumentException.class);
exception.expectMessage("resource must not be blank or empty");
S3_ARN_PARSER.convertArn(Arn.fromString("arn:aws:s3-object-lambda:us-west-2:123456789012:accesspoint/"));
}
@Test
public void parseArn_objectLambda_noName_colon() {
exception.expect(IllegalArgumentException.class);
exception.expectMessage("resource must not be blank or empty");
S3_ARN_PARSER.convertArn(Arn.fromString("arn:aws:s3-object-lambda:us-west-2:123456789012:accesspoint:"));
}
} | 4,427 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal/handlers/GetBucketPolicyInterceptorTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.assertj.core.api.Assertions.assertThat;
import static software.amazon.awssdk.services.s3.utils.InterceptorTestUtils.modifyHttpResponseContent;
import java.io.InputStream;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.interceptor.Context;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.http.SdkHttpResponse;
import software.amazon.awssdk.services.s3.model.GetBucketPolicyRequest;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
public class GetBucketPolicyInterceptorTest {
private GetBucketPolicyInterceptor interceptor = new GetBucketPolicyInterceptor();
@Test
public void getBucketPolicy_shouldModifyResponseContent() {
GetBucketPolicyRequest request = GetBucketPolicyRequest.builder().build();
Context.ModifyHttpResponse context = modifyHttpResponseContent(request, SdkHttpResponse.builder()
.statusCode(200)
.build());
Optional<InputStream> inputStream = interceptor.modifyHttpResponseContent(context, new ExecutionAttributes());
assertThat(inputStream).isNotEqualTo(context.responseBody());
}
@Test
public void nonGetBucketPolicyResponse_ShouldNotModifyResponse() {
GetObjectRequest request = GetObjectRequest.builder().build();
Context.ModifyHttpResponse context = modifyHttpResponseContent(request, SdkHttpResponse.builder().statusCode(200).build());
Optional<InputStream> inputStream = interceptor.modifyHttpResponseContent(context, new ExecutionAttributes());
assertThat(inputStream).isEqualTo(context.responseBody());
}
@Test
public void errorResponseShouldNotModifyResponse() {
GetBucketPolicyRequest request = GetBucketPolicyRequest.builder().build();
Context.ModifyHttpResponse context = modifyHttpResponseContent(request, SdkHttpResponse.builder().statusCode(404).build());
Optional<InputStream> inputStream = interceptor.modifyHttpResponseContent(context, new ExecutionAttributes());
assertThat(inputStream).isEqualTo(context.responseBody());
}
}
| 4,428 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal/handlers/AsyncChecksumValidationInterceptorTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Java6Assertions.assertThatThrownBy;
import static software.amazon.awssdk.core.ClientType.ASYNC;
import static software.amazon.awssdk.core.interceptor.SdkExecutionAttribute.CLIENT_TYPE;
import static software.amazon.awssdk.core.interceptor.SdkExecutionAttribute.SERVICE_CONFIG;
import static software.amazon.awssdk.services.s3.checksums.ChecksumConstant.CHECKSUM_ENABLED_RESPONSE_HEADER;
import static software.amazon.awssdk.services.s3.checksums.ChecksumConstant.CONTENT_LENGTH_HEADER;
import static software.amazon.awssdk.services.s3.checksums.ChecksumConstant.ENABLE_MD5_CHECKSUM_HEADER_VALUE;
import static software.amazon.awssdk.services.s3.checksums.ChecksumConstant.SERVER_SIDE_ENCRYPTION_HEADER;
import static software.amazon.awssdk.services.s3.checksums.ChecksumsEnabledValidator.CHECKSUM;
import static software.amazon.awssdk.services.s3.model.ServerSideEncryption.AWS_KMS;
import java.net.URI;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import org.reactivestreams.Publisher;
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.ExecutionAttributes;
import software.amazon.awssdk.core.interceptor.InterceptorContext;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.http.SdkHttpResponse;
import software.amazon.awssdk.services.s3.S3Configuration;
import software.amazon.awssdk.services.s3.checksums.ChecksumCalculatingAsyncRequestBody;
import software.amazon.awssdk.services.s3.checksums.ChecksumValidatingPublisher;
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.InterceptorTestUtils;
import software.amazon.awssdk.utils.internal.Base16Lower;
public class AsyncChecksumValidationInterceptorTest {
private static final byte[] CONTENT_BYTES = "CONTENT".getBytes(Charset.forName("UTF-8"));
private static final String VALID_CHECKSUM = Base16Lower.encodeAsString(checkSumFor(CONTENT_BYTES).getChecksumBytes());
private static final String INVALID_CHECKSUM = "3902ee7e149eb8313a34757e89e21af6";
private AsyncChecksumValidationInterceptor interceptor = new AsyncChecksumValidationInterceptor();
@Test
public void modifyAsyncHttpContent_putObjectRequestChecksumEnabled_shouldWrapChecksumRequestBody() {
ExecutionAttributes executionAttributes = getExecutionAttributes();
Context.ModifyHttpRequest modifyHttpRequest =
InterceptorTestUtils.modifyHttpRequestContext(PutObjectRequest.builder().build());
Optional<AsyncRequestBody> asyncRequestBody = interceptor.modifyAsyncHttpContent(modifyHttpRequest,
executionAttributes);
assertThat(asyncRequestBody.isPresent()).isTrue();
assertThat(executionAttributes.getAttribute(CHECKSUM)).isNotNull();
assertThat(asyncRequestBody.get()).isExactlyInstanceOf(ChecksumCalculatingAsyncRequestBody.class);
}
@Test
public void modifyAsyncHttpContent_nonPutObjectRequest_shouldNotModify() {
ExecutionAttributes executionAttributes = getExecutionAttributes();
Context.ModifyHttpRequest modifyHttpRequest =
InterceptorTestUtils.modifyHttpRequestContext(GetObjectRequest.builder().build());
Optional<AsyncRequestBody> asyncRequestBody = interceptor.modifyAsyncHttpContent(modifyHttpRequest,
executionAttributes);
assertThat(asyncRequestBody).isEqualTo(modifyHttpRequest.asyncRequestBody());
}
@Test
public void modifyAsyncHttpContent_putObjectRequest_checksumDisabled_shouldNotModify() {
ExecutionAttributes executionAttributes = getExecutionAttributesWithChecksumDisabled();
Context.ModifyHttpRequest modifyHttpRequest =
InterceptorTestUtils.modifyHttpRequestContext(GetObjectRequest.builder().build());
Optional<AsyncRequestBody> asyncRequestBody = interceptor.modifyAsyncHttpContent(modifyHttpRequest,
executionAttributes);
assertThat(asyncRequestBody).isEqualTo(modifyHttpRequest.asyncRequestBody());
}
@Test
public void modifyAsyncHttpResponseContent_getObjectRequest_checksumEnabled_shouldWrapChecksumValidatingPublisher() {
SdkHttpResponse sdkHttpResponse = getSdkHttpResponseWithChecksumHeader();
Context.ModifyHttpResponse modifyHttpResponse =
InterceptorTestUtils.modifyHttpResponse(GetObjectRequest.builder().build(), sdkHttpResponse);
Optional<Publisher<ByteBuffer>> publisher = interceptor.modifyAsyncHttpResponseContent(modifyHttpResponse,
getExecutionAttributes());
assertThat(publisher.get()).isExactlyInstanceOf(ChecksumValidatingPublisher.class);
}
@Test
public void modifyAsyncHttpResponseContent_getObjectRequest_responseDoesNotContainChecksum_shouldNotModify() {
ExecutionAttributes executionAttributes = getExecutionAttributesWithChecksumDisabled();
SdkHttpResponse sdkHttpResponse = SdkHttpResponse.builder()
.putHeader(CONTENT_LENGTH_HEADER, "100")
.build();
Context.ModifyHttpResponse modifyHttpResponse =
InterceptorTestUtils.modifyHttpResponse(GetObjectRequest.builder().build(), sdkHttpResponse);
Optional<Publisher<ByteBuffer>> publisher = interceptor.modifyAsyncHttpResponseContent(modifyHttpResponse,
executionAttributes);
assertThat(publisher).isEqualTo(modifyHttpResponse.responsePublisher());
}
@Test
public void modifyAsyncHttpResponseContent_nonGetObjectRequest_shouldNotModify() {
ExecutionAttributes executionAttributes = getExecutionAttributes();
SdkHttpResponse sdkHttpResponse = getSdkHttpResponseWithChecksumHeader();
sdkHttpResponse.toBuilder().clearHeaders();
Context.ModifyHttpResponse modifyHttpResponse =
InterceptorTestUtils.modifyHttpResponse(PutObjectRequest.builder().build(), sdkHttpResponse);
Optional<Publisher<ByteBuffer>> publisher = interceptor.modifyAsyncHttpResponseContent(modifyHttpResponse,
executionAttributes);
assertThat(publisher).isEqualTo(modifyHttpResponse.responsePublisher());
}
@Test
public void afterUnmarshalling_putObjectRequest_shouldValidateChecksum() {
SdkHttpResponse sdkHttpResponse = getSdkHttpResponseWithChecksumHeader();
PutObjectResponse response = PutObjectResponse.builder()
.eTag(VALID_CHECKSUM)
.build();
PutObjectRequest putObjectRequest = PutObjectRequest.builder()
.build();
SdkHttpRequest sdkHttpRequest = SdkHttpFullRequest.builder()
.uri(URI.create("http://localhost:8080"))
.method(SdkHttpMethod.PUT)
.build();
Context.AfterUnmarshalling afterUnmarshallingContext =
InterceptorTestUtils.afterUnmarshallingContext(putObjectRequest, sdkHttpRequest, response, sdkHttpResponse);
interceptor.afterUnmarshalling(afterUnmarshallingContext, getExecutionAttributesWithChecksum());
}
@Test
public void afterUnmarshalling_putObjectRequest_shouldValidateChecksum_throwExceptionIfInvalid() {
SdkHttpResponse sdkHttpResponse = getSdkHttpResponseWithChecksumHeader();
PutObjectResponse response = PutObjectResponse.builder()
.eTag(INVALID_CHECKSUM)
.build();
PutObjectRequest putObjectRequest = PutObjectRequest.builder().build();
SdkHttpRequest sdkHttpRequest = SdkHttpFullRequest.builder()
.uri(URI.create("http://localhost:8080"))
.method(SdkHttpMethod.PUT)
.build();
Context.AfterUnmarshalling afterUnmarshallingContext =
InterceptorContext.builder()
.request(putObjectRequest)
.httpRequest(sdkHttpRequest)
.response(response)
.httpResponse(sdkHttpResponse)
.asyncRequestBody(AsyncRequestBody.fromString("Test"))
.build();
ExecutionAttributes attributes = getExecutionAttributesWithChecksum();
interceptor.modifyAsyncHttpContent(afterUnmarshallingContext, attributes);
assertThatThrownBy(() -> interceptor.afterUnmarshalling(afterUnmarshallingContext, attributes))
.hasMessageContaining("Data read has a different checksum than expected.");
}
@Test
public void afterUnmarshalling_putObjectRequest_with_SSE_shouldNotValidateChecksum() {
SdkHttpResponse sdkHttpResponse = getSdkHttpResponseWithChecksumHeader();
PutObjectResponse response = PutObjectResponse.builder()
.eTag(INVALID_CHECKSUM)
.build();
PutObjectRequest putObjectRequest = PutObjectRequest.builder().build();
SdkHttpRequest sdkHttpRequest = SdkHttpFullRequest.builder()
.putHeader(SERVER_SIDE_ENCRYPTION_HEADER, AWS_KMS.toString())
.putHeader("x-amz-server-side-encryption-aws-kms-key-id", ENABLE_MD5_CHECKSUM_HEADER_VALUE)
.uri(URI.create("http://localhost:8080"))
.method(SdkHttpMethod.PUT)
.build();
Context.AfterUnmarshalling afterUnmarshallingContext =
InterceptorTestUtils.afterUnmarshallingContext(putObjectRequest, sdkHttpRequest, response, sdkHttpResponse);
interceptor.afterUnmarshalling(afterUnmarshallingContext, getExecutionAttributesWithChecksum());
}
private ExecutionAttributes getExecutionAttributesWithChecksum() {
SdkChecksum checksum = checkSumFor(CONTENT_BYTES);
return getExecutionAttributes().putAttribute(CHECKSUM, checksum);
}
private ExecutionAttributes getExecutionAttributes() {
ExecutionAttributes executionAttributes = new ExecutionAttributes();
executionAttributes.putAttribute(CLIENT_TYPE, ASYNC);
return executionAttributes;
}
private SdkHttpResponse getSdkHttpResponseWithChecksumHeader() {
return SdkHttpResponse.builder()
.putHeader(CONTENT_LENGTH_HEADER, "100")
.putHeader(CHECKSUM_ENABLED_RESPONSE_HEADER, ENABLE_MD5_CHECKSUM_HEADER_VALUE)
.build();
}
private ExecutionAttributes getExecutionAttributesWithChecksumDisabled() {
ExecutionAttributes executionAttributes = getExecutionAttributes();
executionAttributes.putAttribute(SERVICE_CONFIG, S3Configuration.builder().checksumValidationEnabled(false).build());
return executionAttributes;
}
private static SdkChecksum checkSumFor(byte[] bytes) {
SdkChecksum checksum = new Md5Checksum();
checksum.update(bytes, 0, bytes.length);
return checksum;
}
}
| 4,429 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal/handlers/PutObjectHeaderTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.any;
import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl;
import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
import static com.github.tomakehurst.wiremock.client.WireMock.putRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
import static com.github.tomakehurst.wiremock.client.WireMock.verify;
import static org.assertj.core.api.Assertions.assertThat;
import static software.amazon.awssdk.http.Header.CONTENT_LENGTH;
import static software.amazon.awssdk.http.Header.CONTENT_TYPE;
import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.core.internal.util.Mimetype;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.S3Configuration;
import software.amazon.awssdk.services.s3.model.HeadObjectResponse;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.testutils.RandomTempFile;
public class PutObjectHeaderTest {
@Rule
public WireMockRule mockServer = new WireMockRule(0);
private S3Client s3Client;
private PutObjectRequest putObjectRequest;
@Before
public void setup() {
s3Client = S3Client.builder()
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid")))
.region(Region.US_WEST_2).endpointOverride(URI.create(getEndpoint()))
.serviceConfiguration(S3Configuration.builder().checksumValidationEnabled(false).pathStyleAccessEnabled(true).build())
.build();
putObjectRequest = PutObjectRequest.builder().bucket("test").key("test").build();
}
private String getEndpoint() {
return "http://localhost:" + mockServer.port();
}
@Test
public void putObjectBytes_headerShouldContainContentType() {
stubFor(any(urlMatching(".*"))
.willReturn(response()));
s3Client.putObject(PutObjectRequest.builder().bucket("test").key("test").build(), RequestBody.fromBytes("Hello World".getBytes()));
verify(putRequestedFor(anyUrl()).withHeader(CONTENT_TYPE, equalTo(Mimetype.MIMETYPE_OCTET_STREAM)));
}
@Test
public void putObjectFile_headerShouldContainContentType() throws IOException {
File file = new RandomTempFile("test.html", 10);
stubFor(any(urlMatching(".*"))
.willReturn(response()));
s3Client.putObject(putObjectRequest, RequestBody.fromFile(file));
verify(putRequestedFor(anyUrl()).withHeader(CONTENT_TYPE, equalTo("text/html")));
}
@Test
public void putObject_gzipFile_hasProperContentType() throws IOException {
File file = new RandomTempFile("test.gz", 10);
stubFor(any(urlMatching(".*"))
.willReturn(response()));
s3Client.putObject(putObjectRequest, RequestBody.fromFile(file));
verify(putRequestedFor(anyUrl()).withHeader(CONTENT_TYPE, equalTo("application/gzip")));
}
@Test
public void putObject_gzipFile_shouldNotOverrideContentTypeInRequest() throws IOException {
File file = new RandomTempFile("test.gz", 10);
String contentType = "something";
stubFor(any(urlMatching(".*"))
.willReturn(response()));
s3Client.putObject(putObjectRequest.toBuilder().contentType(contentType).build(),
RequestBody.fromFile(file));
verify(putRequestedFor(anyUrl()).withHeader(CONTENT_TYPE, equalTo(contentType)));
}
@Test
public void putObjectUnknownFileExtension_contentTypeDefaultToBeStream() throws IOException {
File file = new RandomTempFile("test.unknown", 10);
stubFor(any(urlMatching(".*"))
.willReturn(response()));
s3Client.putObject(putObjectRequest, RequestBody.fromFile(file));
verify(putRequestedFor(anyUrl()).withHeader(CONTENT_TYPE, equalTo(Mimetype.MIMETYPE_OCTET_STREAM)));
}
@Test
public void putObjectWithContentTypeHeader_shouldNotOverrideContentTypeInRequest() throws IOException {
stubFor(any(urlMatching(".*"))
.willReturn(response()));
String contentType = "something";
putObjectRequest = putObjectRequest.toBuilder().contentType(contentType).build();
s3Client.putObject(putObjectRequest, RequestBody.fromString("test"));
verify(putRequestedFor(anyUrl()).withHeader(CONTENT_TYPE, equalTo(contentType)));
}
@Test
public void putObjectWithContentTypeHeader_shouldNotOverrideContentTypeInRawConfig() throws IOException {
stubFor(any(urlMatching(".*"))
.willReturn(response()));
String contentType = "hello world";
putObjectRequest = (PutObjectRequest) putObjectRequest.toBuilder().overrideConfiguration(b -> b.putHeader(CONTENT_TYPE, contentType)).build();
s3Client.putObject(putObjectRequest, RequestBody.fromString("test"));
verify(putRequestedFor(anyUrl()).withHeader(CONTENT_TYPE, equalTo(contentType)));
}
@Test
public void headObject_userMetadataReturnMixedCaseMetadata() {
String lowerCaseMetadataPrefix = "x-amz-meta-";
String mixedCaseMetadataPrefix = "X-AmZ-MEta-";
String metadataKey = "foo";
String mixedCaseMetadataKey = "bAr";
stubFor(any(urlMatching(".*"))
.willReturn(response().withHeader(lowerCaseMetadataPrefix + metadataKey, "test")
.withHeader(mixedCaseMetadataPrefix + mixedCaseMetadataKey, "test")));
HeadObjectResponse headObjectResponse = s3Client.headObject(b -> b.key("key").bucket("bucket"));
assertThat(headObjectResponse.metadata()).containsKey(metadataKey);
assertThat(headObjectResponse.metadata()).containsKey(mixedCaseMetadataKey);
}
private ResponseDefinitionBuilder response() {
return aResponse().withStatus(200).withHeader(CONTENT_LENGTH, "0").withBody("");
}
}
| 4,430 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal/handlers/CopySourceInterceptorTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy;
import java.util.Arrays;
import java.util.Collection;
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.interceptor.ExecutionAttributes;
import software.amazon.awssdk.services.s3.model.CopyObjectRequest;
import software.amazon.awssdk.services.s3.model.UploadPartCopyRequest;
@RunWith(Parameterized.class)
public class CopySourceInterceptorTest {
private final CopySourceInterceptor interceptor = new CopySourceInterceptor();
@Parameters
public static Collection<String[]> parameters() throws Exception {
return Arrays.asList(new String[][] {
{"bucket", "simpleKey", null,
"bucket/simpleKey"},
{"bucket", "key/with/slashes", null,
"bucket/key/with/slashes"},
{"bucket", "\uD83E\uDEA3", null,
"bucket/%F0%9F%AA%A3"},
{"bucket", "specialChars._ +!#$&'()*,:;=?@\"", null,
"bucket/specialChars._%20%2B%21%23%24%26%27%28%29%2A%2C%3A%3B%3D%3F%40%22"},
{"bucket", "%20", null,
"bucket/%2520"},
{"bucket", "key/with/version", "ZJlqdTGGfnWjRWjm.WtQc5XRTNJn3sz_",
"bucket/key/with/version?versionId=ZJlqdTGGfnWjRWjm.WtQc5XRTNJn3sz_"},
{"source-bucke-e00000144705073101keauk155va6smod88ynqbeta0--op-s3", "CT-debug-Info-16", null,
"source-bucke-e00000144705073101keauk155va6smod88ynqbeta0--op-s3/CT-debug-Info-16"},
{"source-bucke-e00000144705073101keauk155va6smod88ynqbeta0--op-s3", "CT-debug-Info-16", "123",
"source-bucke-e00000144705073101keauk155va6smod88ynqbeta0--op-s3/CT-debug-Info-16?versionId=123"},
{"arn:aws:s3-outposts:us-west-2:123456789012:outpost/my-outpost/bucket/my-bucket", "my-key", null,
"arn%3Aaws%3As3-outposts%3Aus-west-2%3A123456789012%3Aoutpost/my-outpost/bucket/my-bucket/object/my-key"},
{"arn:aws:s3-outposts:us-west-2:123456789012:outpost/my-outpost/bucket/my-bucket", "my-key", "123",
"arn%3Aaws%3As3-outposts%3Aus-west-2%3A123456789012%3Aoutpost/my-outpost/bucket/my-bucket/object/my-key?versionId=123"},
{"arn:aws:s3:us-west-2:123456789012:accesspoint/my-access-point", "my-key", null,
"arn%3Aaws%3As3%3Aus-west-2%3A123456789012%3Aaccesspoint/my-access-point/object/my-key"},
{"arn:aws:s3:us-west-2:123456789012:accesspoint/my-access-point", "my-key", "123",
"arn%3Aaws%3As3%3Aus-west-2%3A123456789012%3Aaccesspoint/my-access-point/object/my-key?versionId=123"}
});
}
private final String sourceBucket;
private final String sourceKey;
private final String sourceVersionId;
private final String expectedCopySource;
public CopySourceInterceptorTest(String sourceBucket, String sourceKey, String sourceVersionId, String expectedCopySource) {
this.sourceBucket = sourceBucket;
this.sourceKey = sourceKey;
this.sourceVersionId = sourceVersionId;
this.expectedCopySource = expectedCopySource;
}
@Test
public void modifyRequest_ConstructsUrlEncodedCopySource_whenCopyObjectRequest() {
CopyObjectRequest originalRequest = CopyObjectRequest.builder()
.sourceBucket(sourceBucket)
.sourceKey(sourceKey)
.sourceVersionId(sourceVersionId)
.build();
CopyObjectRequest modifiedRequest = (CopyObjectRequest) interceptor
.modifyRequest(() -> originalRequest, new ExecutionAttributes());
assertThat(modifiedRequest.copySource()).isEqualTo(expectedCopySource);
}
@Test
public void modifyRequest_ConstructsUrlEncodedCopySource_whenUploadPartCopyRequest() {
UploadPartCopyRequest originalRequest = UploadPartCopyRequest.builder()
.sourceBucket(sourceBucket)
.sourceKey(sourceKey)
.sourceVersionId(sourceVersionId)
.build();
UploadPartCopyRequest modifiedRequest = (UploadPartCopyRequest) interceptor
.modifyRequest(() -> originalRequest, new ExecutionAttributes());
assertThat(modifiedRequest.copySource()).isEqualTo(expectedCopySource);
}
@Test
public void modifyRequest_Throws_whenCopySourceUsedWithSourceBucket_withCopyObjectRequest() {
CopyObjectRequest originalRequest = CopyObjectRequest.builder()
.sourceBucket(sourceBucket)
.sourceKey(sourceKey)
.sourceVersionId(sourceVersionId)
.copySource("copySource")
.build();
assertThatThrownBy(() -> {
interceptor.modifyRequest(() -> originalRequest, new ExecutionAttributes());
}).isInstanceOf(IllegalArgumentException.class)
.hasMessage("Parameter 'copySource' must not be used in conjunction with 'sourceBucket'");
}
@Test
public void modifyRequest_Throws_whenCopySourceUsedWithSourceBucket_withUploadPartCopyRequest() {
UploadPartCopyRequest originalRequest = UploadPartCopyRequest.builder()
.sourceBucket(sourceBucket)
.sourceKey(sourceKey)
.sourceVersionId(sourceVersionId)
.copySource("copySource")
.build();
assertThatThrownBy(() -> {
interceptor.modifyRequest(() -> originalRequest, new ExecutionAttributes());
}).isInstanceOf(IllegalArgumentException.class)
.hasMessage("Parameter 'copySource' must not be used in conjunction with 'sourceBucket'");
}
@Test
public void modifyRequest_Throws_whenSourceBucketNotSpecified_withCopyObjectRequest() {
CopyObjectRequest originalRequest = CopyObjectRequest.builder()
.sourceKey(sourceKey)
.sourceVersionId(sourceVersionId)
.build();
assertThatThrownBy(() -> {
interceptor.modifyRequest(() -> originalRequest, new ExecutionAttributes());
}).isInstanceOf(IllegalArgumentException.class)
.hasMessage("Parameter 'sourceBucket' must not be null");
}
@Test
public void modifyRequest_Throws_whenSourceBucketNotSpecified_withUploadPartCopyRequest() {
UploadPartCopyRequest originalRequest = UploadPartCopyRequest.builder()
.sourceKey(sourceKey)
.sourceVersionId(sourceVersionId)
.build();
assertThatThrownBy(() -> {
interceptor.modifyRequest(() -> originalRequest, new ExecutionAttributes());
}).isInstanceOf(IllegalArgumentException.class)
.hasMessage("Parameter 'sourceBucket' must not be null");
}
@Test
public void modifyRequest_Throws_whenSourceKeyNotSpecified_withCopyObjectRequest() {
CopyObjectRequest originalRequest = CopyObjectRequest.builder()
.sourceBucket(sourceBucket)
.sourceVersionId(sourceVersionId)
.build();
assertThatThrownBy(() -> {
interceptor.modifyRequest(() -> originalRequest, new ExecutionAttributes());
}).isInstanceOf(IllegalArgumentException.class)
.hasMessage("Parameter 'sourceKey' must not be null");
}
@Test
public void modifyRequest_Throws_whenSourceKeyNotSpecified_withUploadPartCopyRequest() {
UploadPartCopyRequest originalRequest = UploadPartCopyRequest.builder()
.sourceBucket(sourceBucket)
.sourceVersionId(sourceVersionId)
.build();
assertThatThrownBy(() -> {
interceptor.modifyRequest(() -> originalRequest, new ExecutionAttributes());
}).isInstanceOf(IllegalArgumentException.class)
.hasMessage("Parameter 'sourceKey' must not be null");
}
}
| 4,431 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal/handlers/SyncChecksumValidationInterceptorTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Java6Assertions.assertThatThrownBy;
import static software.amazon.awssdk.core.ClientType.SYNC;
import static software.amazon.awssdk.core.interceptor.SdkExecutionAttribute.CLIENT_TYPE;
import static software.amazon.awssdk.core.interceptor.SdkExecutionAttribute.SERVICE_CONFIG;
import static software.amazon.awssdk.services.s3.checksums.ChecksumConstant.CHECKSUM_ENABLED_RESPONSE_HEADER;
import static software.amazon.awssdk.services.s3.checksums.ChecksumConstant.CONTENT_LENGTH_HEADER;
import static software.amazon.awssdk.services.s3.checksums.ChecksumConstant.ENABLE_MD5_CHECKSUM_HEADER_VALUE;
import static software.amazon.awssdk.services.s3.checksums.ChecksumConstant.SERVER_SIDE_ENCRYPTION_HEADER;
import static software.amazon.awssdk.services.s3.checksums.ChecksumsEnabledValidator.CHECKSUM;
import static software.amazon.awssdk.services.s3.model.ServerSideEncryption.AWS_KMS;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.Test;
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.ExecutionAttributes;
import software.amazon.awssdk.core.interceptor.InterceptorContext;
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.SdkHttpResponse;
import software.amazon.awssdk.services.s3.S3Configuration;
import software.amazon.awssdk.services.s3.checksums.ChecksumCalculatingInputStream;
import software.amazon.awssdk.services.s3.checksums.ChecksumValidatingInputStream;
import software.amazon.awssdk.services.s3.internal.handlers.SyncChecksumValidationInterceptor.ChecksumCalculatingStreamProvider;
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.InterceptorTestUtils;
import software.amazon.awssdk.utils.IoUtils;
import software.amazon.awssdk.utils.StringInputStream;
import software.amazon.awssdk.utils.internal.Base16Lower;
public class SyncChecksumValidationInterceptorTest {
private static final byte[] CONTENT_BYTES = "CONTENT".getBytes(Charset.forName("UTF-8"));
private static final String VALID_CHECKSUM = Base16Lower.encodeAsString(checkSumFor(CONTENT_BYTES).getChecksumBytes());
private static final String INVALID_CHECKSUM = "3902ee7e149eb8313a34757e89e21af6";
private SyncChecksumValidationInterceptor interceptor = new SyncChecksumValidationInterceptor();
@Test
public void modifyHttpContent_putObjectRequestChecksumEnabled_shouldWrapChecksumRequestBody() {
ExecutionAttributes executionAttributes = getExecutionAttributes();
Context.ModifyHttpRequest modifyHttpRequest =
InterceptorTestUtils.modifyHttpRequestContext(PutObjectRequest.builder().build());
Optional<RequestBody> requestBody = interceptor.modifyHttpContent(modifyHttpRequest,
executionAttributes);
assertThat(requestBody.isPresent()).isTrue();
assertThat(executionAttributes.getAttribute(CHECKSUM)).isNotNull();
assertThat(requestBody.get().contentStreamProvider()).isNotEqualTo(modifyHttpRequest.requestBody().get());
}
@Test
public void modifyHttpContent_nonPutObjectRequest_shouldNotModify() {
ExecutionAttributes executionAttributes = getExecutionAttributes();
Context.ModifyHttpRequest modifyHttpRequest =
InterceptorTestUtils.modifyHttpRequestContext(GetObjectRequest.builder().build());
Optional<RequestBody> requestBody = interceptor.modifyHttpContent(modifyHttpRequest,
executionAttributes);
assertThat(requestBody).isEqualTo(modifyHttpRequest.requestBody());
}
@Test
public void modifyHttpContent_putObjectRequest_checksumDisabled_shouldNotModify() {
ExecutionAttributes executionAttributes = getExecutionAttributesWithChecksumDisabled();
Context.ModifyHttpRequest modifyHttpRequest =
InterceptorTestUtils.modifyHttpRequestContext(GetObjectRequest.builder().build());
Optional<RequestBody> requestBody = interceptor.modifyHttpContent(modifyHttpRequest,
executionAttributes);
assertThat(requestBody).isEqualTo(modifyHttpRequest.requestBody());
}
@Test
public void modifyHttpResponseContent_getObjectRequest_checksumEnabled_shouldWrapChecksumValidatingPublisher() {
SdkHttpResponse sdkHttpResponse = getSdkHttpResponseWithChecksumHeader();
Context.ModifyHttpResponse modifyHttpResponse =
InterceptorTestUtils.modifyHttpResponse(GetObjectRequest.builder().build(), sdkHttpResponse);
Optional<InputStream> publisher = interceptor.modifyHttpResponseContent(modifyHttpResponse,
getExecutionAttributes());
assertThat(publisher.get()).isExactlyInstanceOf(ChecksumValidatingInputStream.class);
}
@Test
public void modifyHttpResponseContent_getObjectRequest_responseDoesNotContainChecksum_shouldNotModify() {
ExecutionAttributes executionAttributes = getExecutionAttributesWithChecksumDisabled();
SdkHttpResponse sdkHttpResponse = SdkHttpResponse.builder()
.putHeader(CONTENT_LENGTH_HEADER, "100")
.build();
Context.ModifyHttpResponse modifyHttpResponse =
InterceptorTestUtils.modifyHttpResponse(GetObjectRequest.builder().build(), sdkHttpResponse);
Optional<InputStream> publisher = interceptor.modifyHttpResponseContent(modifyHttpResponse,
executionAttributes);
assertThat(publisher).isEqualTo(modifyHttpResponse.responseBody());
}
@Test
public void modifyHttpResponseContent_nonGetObjectRequest_shouldNotModify() {
ExecutionAttributes executionAttributes = getExecutionAttributes();
SdkHttpResponse sdkHttpResponse = getSdkHttpResponseWithChecksumHeader();
sdkHttpResponse.toBuilder().clearHeaders();
Context.ModifyHttpResponse modifyHttpResponse =
InterceptorTestUtils.modifyHttpResponse(PutObjectRequest.builder().build(), sdkHttpResponse);
Optional<InputStream> publisher = interceptor.modifyHttpResponseContent(modifyHttpResponse,
executionAttributes);
assertThat(publisher).isEqualTo(modifyHttpResponse.responseBody());
}
@Test
public void checksumCalculatingStreamProvider_shouldReturnNewStreamResetChecksum() throws IOException {
List<CloseAwareStream> closeAwareStreams = new ArrayList<>();
ContentStreamProvider underlyingStreamProvider = () -> {
CloseAwareStream stream = new CloseAwareStream(new StringInputStream("helloWorld"));
closeAwareStreams.add(stream);
return stream;
};
SdkChecksum checksum = new Md5Checksum();
ChecksumCalculatingStreamProvider checksumCalculatingStreamProvider =
new ChecksumCalculatingStreamProvider(underlyingStreamProvider, checksum);
ChecksumCalculatingInputStream currentStream = (ChecksumCalculatingInputStream) checksumCalculatingStreamProvider.newStream();
IoUtils.drainInputStream(currentStream);
byte[] checksumBytes = currentStream.getChecksumBytes();
ChecksumCalculatingInputStream newStream = (ChecksumCalculatingInputStream) checksumCalculatingStreamProvider.newStream();
assertThat(closeAwareStreams.get(0).isClosed).isTrue();
IoUtils.drainInputStream(newStream);
byte[] newStreamChecksumBytes = newStream.getChecksumBytes();
assertThat(getChecksum(checksumBytes)).isEqualTo(getChecksum(newStreamChecksumBytes));
newStream.close();
}
@Test
public void afterUnmarshalling_putObjectRequest_shouldValidateChecksum() {
SdkHttpResponse sdkHttpResponse = getSdkHttpResponseWithChecksumHeader();
PutObjectResponse response = PutObjectResponse.builder()
.eTag(VALID_CHECKSUM)
.build();
PutObjectRequest putObjectRequest = PutObjectRequest.builder()
.build();
SdkHttpRequest sdkHttpRequest = SdkHttpFullRequest.builder()
.uri(URI.create("http://localhost:8080"))
.method(SdkHttpMethod.PUT)
.build();
Context.AfterUnmarshalling afterUnmarshallingContext =
InterceptorTestUtils.afterUnmarshallingContext(putObjectRequest, sdkHttpRequest, response, sdkHttpResponse);
interceptor.afterUnmarshalling(afterUnmarshallingContext, getExecutionAttributesWithChecksum());
}
@Test
public void afterUnmarshalling_putObjectRequest_shouldValidateChecksum_throwExceptionIfInvalid() {
SdkHttpResponse sdkHttpResponse = getSdkHttpResponseWithChecksumHeader();
PutObjectResponse response = PutObjectResponse.builder()
.eTag(INVALID_CHECKSUM)
.build();
PutObjectRequest putObjectRequest = PutObjectRequest.builder().build();
SdkHttpRequest sdkHttpRequest = SdkHttpFullRequest.builder()
.uri(URI.create("http://localhost:8080"))
.method(SdkHttpMethod.PUT)
.contentStreamProvider(() -> new StringInputStream("Test"))
.build();
Context.AfterUnmarshalling afterUnmarshallingContext =
InterceptorContext.builder()
.request(putObjectRequest)
.httpRequest(sdkHttpRequest)
.response(response)
.httpResponse(sdkHttpResponse)
.requestBody(RequestBody.fromString("Test"))
.build();
ExecutionAttributes attributes = getExecutionAttributesWithChecksum();
interceptor.modifyHttpContent(afterUnmarshallingContext, attributes);
assertThatThrownBy(() -> interceptor.afterUnmarshalling(afterUnmarshallingContext, attributes))
.hasMessageContaining("Data read has a different checksum than expected.");
}
@Test
public void afterUnmarshalling_putObjectRequest_with_SSE_shouldNotValidateChecksum() {
SdkHttpResponse sdkHttpResponse = getSdkHttpResponseWithChecksumHeader();
PutObjectResponse response = PutObjectResponse.builder()
.eTag(INVALID_CHECKSUM)
.build();
PutObjectRequest putObjectRequest = PutObjectRequest.builder().build();
SdkHttpRequest sdkHttpRequest = SdkHttpFullRequest.builder()
.putHeader(SERVER_SIDE_ENCRYPTION_HEADER, AWS_KMS.toString())
.putHeader("x-amz-server-side-encryption-aws-kms-key-id", ENABLE_MD5_CHECKSUM_HEADER_VALUE)
.uri(URI.create("http://localhost:8080"))
.method(SdkHttpMethod.PUT)
.build();
Context.AfterUnmarshalling afterUnmarshallingContext =
InterceptorTestUtils.afterUnmarshallingContext(putObjectRequest, sdkHttpRequest, response, sdkHttpResponse);
interceptor.afterUnmarshalling(afterUnmarshallingContext, getExecutionAttributesWithChecksum());
}
private static final class CloseAwareStream extends InputStream {
private StringInputStream inputStream;
private boolean isClosed;
private CloseAwareStream(StringInputStream inputStream) {
this.inputStream = inputStream;
}
@Override
public int read() throws IOException {
return inputStream.read();
}
@Override
public void close() throws IOException {
inputStream.close();
isClosed = true;
}
}
private int getChecksum(byte[] checksumBytes) {
ByteBuffer bb = ByteBuffer.wrap(checksumBytes);
return bb.getInt();
}
private ExecutionAttributes getExecutionAttributes() {
ExecutionAttributes executionAttributes = new ExecutionAttributes();
executionAttributes.putAttribute(CLIENT_TYPE, SYNC);
return executionAttributes;
}
private SdkHttpResponse getSdkHttpResponseWithChecksumHeader() {
return SdkHttpResponse.builder()
.putHeader(CONTENT_LENGTH_HEADER, "100")
.putHeader(CHECKSUM_ENABLED_RESPONSE_HEADER, ENABLE_MD5_CHECKSUM_HEADER_VALUE)
.build();
}
private ExecutionAttributes getExecutionAttributesWithChecksumDisabled() {
ExecutionAttributes executionAttributes = getExecutionAttributes();
executionAttributes.putAttribute(SERVICE_CONFIG, S3Configuration.builder().checksumValidationEnabled(false).build());
return executionAttributes;
}
private ExecutionAttributes getExecutionAttributesWithChecksum() {
SdkChecksum checksum = checkSumFor(CONTENT_BYTES);
return getExecutionAttributes().putAttribute(CHECKSUM, checksum);
}
private static SdkChecksum checkSumFor(byte[] bytes) {
SdkChecksum checksum = new Md5Checksum();
checksum.update(bytes, 0, bytes.length);
return checksum;
}
}
| 4,432 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal/handlers/DecodeUrlEncodedResponseInterceptorTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.assertj.core.api.Assertions.assertThat;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;
import org.junit.jupiter.api.Test;
import org.reactivestreams.Publisher;
import software.amazon.awssdk.core.SdkRequest;
import software.amazon.awssdk.core.SdkResponse;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.core.interceptor.Context;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.http.SdkHttpFullResponse;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.services.s3.model.CommonPrefix;
import software.amazon.awssdk.services.s3.model.EncodingType;
import software.amazon.awssdk.services.s3.model.HeadObjectResponse;
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;
/**
* Unit tests for {@link DecodeUrlEncodedResponseInterceptor}.
* <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>
* for information on which parts of the response must are affected by the EncodingType member.
*/
public class DecodeUrlEncodedResponseInterceptorTest {
private static final String TEST_URL_ENCODED = "foo+%3D+bar+baz+%CE%B1+%CE%B2+%F0%9F%98%8A";
private static final String TEST_URL_ENCODED_DELIMITER = "foo+%3D+bar+baz+%CE%B1+%CE%B2+%F0%9F%98%8A+delimiter";
private static final String TEST_URL_ENCODED_NEXT_MARKER = "foo+%3D+bar+baz+%CE%B1+%CE%B2+%F0%9F%98%8A+nextmarker";
private static final String TEST_URL_ENCODED_MARKER = "foo+%3D+bar+baz+%CE%B1+%CE%B2+%F0%9F%98%8A+marker";
private static final String TEST_URL_ENCODED_PREFIX = "foo+%3D+bar+baz+%CE%B1+%CE%B2+%F0%9F%98%8A+prefix";
private static final String TEST_URL_ENCODED_KEY = "foo+%3D+bar+baz+%CE%B1+%CE%B2+%F0%9F%98%8A+key";
private static final String TEST_URL_ENCODED_START_AFTER = "foo+%3D+bar+baz+%CE%B1+%CE%B2+%F0%9F%98%8A+startafter";
// foo = bar baz α β 😊
private static final String TEST_URL_DECODED = "foo = bar baz α β \uD83D\uDE0A";
private static final DecodeUrlEncodedResponseInterceptor INTERCEPTOR = new DecodeUrlEncodedResponseInterceptor();
private static final List<S3Object> TEST_CONTENTS = Arrays.asList(
S3Object.builder().key(TEST_URL_ENCODED).build(),
S3Object.builder().key(TEST_URL_ENCODED).build(),
S3Object.builder().key(TEST_URL_ENCODED).build()
);
private static final List<CommonPrefix> COMMON_PREFIXES = Arrays.asList(CommonPrefix.builder()
.prefix(TEST_URL_ENCODED_PREFIX)
.build());
private static final ListObjectsResponse V1_TEST_ENCODED_RESPONSE = ListObjectsResponse.builder()
.encodingType(EncodingType.URL)
.delimiter(TEST_URL_ENCODED_DELIMITER)
.nextMarker(TEST_URL_ENCODED_NEXT_MARKER)
.prefix(TEST_URL_ENCODED_PREFIX)
.marker(TEST_URL_ENCODED_MARKER)
.contents(TEST_CONTENTS)
.commonPrefixes(COMMON_PREFIXES)
.build();
private static final ListObjectsV2Response V2_TEST_ENCODED_RESPONSE = ListObjectsV2Response.builder()
.encodingType(EncodingType.URL)
.delimiter(TEST_URL_ENCODED_DELIMITER)
.prefix(TEST_URL_ENCODED_PREFIX)
.startAfter(TEST_URL_ENCODED_START_AFTER)
.contents(TEST_CONTENTS)
.commonPrefixes(COMMON_PREFIXES)
.build();
private static final String TEST_URL_ENCODED_NEXT_KEY_MARKER = TEST_URL_ENCODED + "+nextKeyMarker";
private static final String TEST_URL_ENCODED_KEY_MARKER = TEST_URL_ENCODED + "+keyMarker";
private static final ListObjectVersionsResponse TEST_LIST_OBJECT_VERSION_RESPONSE = ListObjectVersionsResponse.builder()
.encodingType(EncodingType.URL)
.delimiter(TEST_URL_ENCODED_DELIMITER)
.prefix(TEST_URL_ENCODED_PREFIX)
.keyMarker(TEST_URL_ENCODED_KEY_MARKER)
.nextKeyMarker(TEST_URL_ENCODED_NEXT_KEY_MARKER)
.commonPrefixes(COMMON_PREFIXES)
.versions(ObjectVersion.builder()
.key(TEST_URL_ENCODED_KEY)
.build())
.build();
private static final ListMultipartUploadsResponse TEST_LIST_MULTIPART_UPLOADS_RESPONSE =
ListMultipartUploadsResponse.builder()
.encodingType(EncodingType.URL)
.delimiter(TEST_URL_ENCODED_DELIMITER)
.prefix(TEST_URL_ENCODED_PREFIX)
.keyMarker(TEST_URL_ENCODED_KEY_MARKER)
.nextKeyMarker(TEST_URL_ENCODED_NEXT_KEY_MARKER)
.uploads(MultipartUpload.builder().key(TEST_URL_ENCODED_KEY).build())
.commonPrefixes(COMMON_PREFIXES)
.build();
@Test
public void encodingTypeSet_decodesListObjectsResponseParts() {
Context.ModifyResponse ctx = newContext(V1_TEST_ENCODED_RESPONSE);
ListObjectsResponse decoded = (ListObjectsResponse) INTERCEPTOR.modifyResponse(ctx, new ExecutionAttributes());
assertDecoded(decoded::delimiter, " delimiter");
assertDecoded(decoded::nextMarker, " nextmarker");
assertDecoded(decoded::prefix, " prefix");
assertDecoded(decoded::marker, " marker");
assertKeysAreDecoded(decoded.contents());
assertCommonPrefixesAreDecoded(decoded.commonPrefixes());
}
@Test
public void encodingTypeSet_decodesListObjectsV2ResponseParts() {
Context.ModifyResponse ctx = newContext(V2_TEST_ENCODED_RESPONSE);
ListObjectsV2Response decoded = (ListObjectsV2Response) INTERCEPTOR.modifyResponse(ctx, new ExecutionAttributes());
assertDecoded(decoded::delimiter, " delimiter");
assertDecoded(decoded::prefix, " prefix");
assertDecoded(decoded::startAfter, " startafter");
assertKeysAreDecoded(decoded.contents());
assertCommonPrefixesAreDecoded(decoded.commonPrefixes());
}
@Test
public void encodingTypeSet_decodesListObjectVersionsResponse() {
Context.ModifyResponse ctx = newContext(TEST_LIST_OBJECT_VERSION_RESPONSE);
ListObjectVersionsResponse decoded = (ListObjectVersionsResponse) INTERCEPTOR.modifyResponse(ctx, new ExecutionAttributes());
assertDecoded(decoded::delimiter, " delimiter");
assertDecoded(decoded::prefix, " prefix");
assertDecoded(decoded::keyMarker, " keyMarker");
assertDecoded(decoded::nextKeyMarker, " nextKeyMarker");
assertCommonPrefixesAreDecoded(decoded.commonPrefixes());
assertVersionsAreDecoded(decoded.versions());
}
@Test
public void encodingTypeSet_decodesListMultipartUploadsResponse() {
Context.ModifyResponse ctx = newContext(TEST_LIST_MULTIPART_UPLOADS_RESPONSE);
ListMultipartUploadsResponse decoded = (ListMultipartUploadsResponse) INTERCEPTOR.modifyResponse(ctx, new ExecutionAttributes());
assertDecoded(decoded::delimiter, " delimiter");
assertDecoded(decoded::prefix, " prefix");
assertDecoded(decoded::keyMarker, " keyMarker");
assertDecoded(decoded::nextKeyMarker, " nextKeyMarker");
assertCommonPrefixesAreDecoded(decoded.commonPrefixes());
assertUploadsAreDecoded(decoded.uploads());
assertCommonPrefixesAreDecoded(decoded.commonPrefixes());
}
@Test
public void encodingTypeNotSet_doesNotDecodeListObjectsResponseParts() {
ListObjectsResponse original = V1_TEST_ENCODED_RESPONSE.toBuilder()
.encodingType((String) null)
.build();
Context.ModifyResponse ctx = newContext(original);
ListObjectsResponse fromInterceptor = (ListObjectsResponse) INTERCEPTOR.modifyResponse(ctx, new ExecutionAttributes());
assertThat(fromInterceptor).isEqualTo(original);
}
@Test
public void encodingTypeNotSet_doesNotDecodeListObjectsV2ResponseParts() {
ListObjectsV2Response original = V2_TEST_ENCODED_RESPONSE.toBuilder()
.encodingType((String) null)
.build();
Context.ModifyResponse ctx = newContext(original);
ListObjectsV2Response fromInterceptor = (ListObjectsV2Response) INTERCEPTOR.modifyResponse(ctx, new ExecutionAttributes());
assertThat(fromInterceptor).isEqualTo(original);
}
@Test
public void otherResponses_shouldNotModifyResponse() {
HeadObjectResponse original = HeadObjectResponse.builder().build();
Context.ModifyResponse ctx = newContext(original);
SdkResponse sdkResponse = INTERCEPTOR.modifyResponse(ctx, new ExecutionAttributes());
assertThat(original.hashCode()).isEqualTo(sdkResponse.hashCode());
}
private void assertKeysAreDecoded(List<S3Object> objects) {
objects.forEach(o -> assertDecoded(o::key));
}
private void assertCommonPrefixesAreDecoded(List<CommonPrefix> commonPrefixes) {
commonPrefixes.forEach(c -> assertDecoded(c::prefix, " prefix"));
}
private void assertDecoded(Supplier<String> supplier) {
assertDecoded(supplier, "");
}
private void assertDecoded(Supplier<String> supplier, String suffix) {
assertThat(supplier.get()).isEqualTo(TEST_URL_DECODED + suffix);
}
private void assertVersionsAreDecoded(List<ObjectVersion> versions) {
versions.forEach(v -> assertDecoded(v::key, " key"));
}
private void assertUploadsAreDecoded(List<MultipartUpload> uploads) {
uploads.forEach(u -> assertDecoded(u::key, " key"));
}
private static Context.ModifyResponse newContext(SdkResponse response) {
return new Context.ModifyResponse() {
@Override
public Optional<Publisher<ByteBuffer>> responsePublisher() {
return null;
}
@Override
public Optional<InputStream> responseBody() {
return null;
}
@Override
public SdkHttpRequest httpRequest() {
return null;
}
@Override
public Optional<RequestBody> requestBody() {
return null;
}
@Override
public Optional<AsyncRequestBody> asyncRequestBody() {
return null;
}
@Override
public SdkResponse response() {
return response;
}
@Override
public SdkHttpFullResponse httpResponse() {
return null;
}
@Override
public SdkRequest request() {
return null;
}
};
}
}
| 4,433 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal/handlers/CreateMultipartUploadRequestInterceptorTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.assertj.core.api.Assertions.assertThat;
import static software.amazon.awssdk.http.Header.CONTENT_LENGTH;
import static software.amazon.awssdk.http.Header.CONTENT_TYPE;
import static software.amazon.awssdk.services.s3.utils.InterceptorTestUtils.sdkHttpFullRequest;
import java.util.Collections;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.interceptor.Context;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.services.s3.model.CreateMultipartUploadRequest;
import software.amazon.awssdk.services.s3.model.GetObjectAclRequest;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.utils.InterceptorTestUtils;
public class CreateMultipartUploadRequestInterceptorTest {
private final CreateMultipartUploadRequestInterceptor interceptor = new CreateMultipartUploadRequestInterceptor();
@Test
public void createMultipartRequest_shouldModifyHttpContent() {
Context.ModifyHttpRequest modifyHttpRequest =
InterceptorTestUtils.modifyHttpRequestContext(CreateMultipartUploadRequest.builder().build());
Optional<RequestBody> requestBody =
interceptor.modifyHttpContent(modifyHttpRequest,
new ExecutionAttributes());
assertThat(modifyHttpRequest.requestBody().get()).isNotEqualTo(requestBody.get());
}
@Test
public void createMultipartRequest_shouldModifyHttpRequest() {
Context.ModifyHttpRequest modifyHttpRequest =
InterceptorTestUtils.modifyHttpRequestContext(CreateMultipartUploadRequest.builder().build());
SdkHttpRequest httpRequest = interceptor.modifyHttpRequest(modifyHttpRequest, new ExecutionAttributes());
assertThat(httpRequest).isNotEqualTo(modifyHttpRequest.httpRequest());
assertThat(httpRequest.headers()).containsEntry(CONTENT_LENGTH, Collections.singletonList("0"));
assertThat(httpRequest.headers()).containsEntry(CONTENT_TYPE, Collections.singletonList("binary/octet-stream"));
}
@Test
public void createMultipartRequest_contentTypePresent_shouldNotModifyContentType() {
String overrideContentType = "application/json";
Context.ModifyHttpRequest modifyHttpRequest =
InterceptorTestUtils.modifyHttpRequestContext(CreateMultipartUploadRequest.builder().build(),
sdkHttpFullRequest().toBuilder()
.putHeader(CONTENT_TYPE, overrideContentType).build());
SdkHttpRequest httpRequest = interceptor.modifyHttpRequest(modifyHttpRequest, new ExecutionAttributes());
assertThat(httpRequest).isNotEqualTo(modifyHttpRequest.httpRequest());
assertThat(httpRequest.headers()).containsEntry(CONTENT_LENGTH, Collections.singletonList("0"));
assertThat(httpRequest.headers()).containsEntry(CONTENT_TYPE, Collections.singletonList(overrideContentType));
}
@Test
public void nonCreateMultipartRequest_shouldNotModifyHttpContent() {
Context.ModifyHttpRequest modifyHttpRequest =
InterceptorTestUtils.modifyHttpRequestContext(PutObjectRequest.builder().build());
Optional<RequestBody> requestBody =
interceptor.modifyHttpContent(modifyHttpRequest,
new ExecutionAttributes());
assertThat(modifyHttpRequest.requestBody().get()).isEqualTo(requestBody.get());
}
@Test
public void nonCreateMultipartRequest_shouldNotModifyHttpRequest() {
Context.ModifyHttpRequest modifyHttpRequest =
InterceptorTestUtils.modifyHttpRequestContext(GetObjectAclRequest.builder().build());
SdkHttpRequest httpRequest = interceptor.modifyHttpRequest(modifyHttpRequest, new ExecutionAttributes());
assertThat(httpRequest).isEqualTo(modifyHttpRequest.httpRequest());
}
}
| 4,434 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal/handlers/CreateBucketInterceptorTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
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.regions.Region;
import software.amazon.awssdk.services.s3.model.CreateBucketConfiguration;
import software.amazon.awssdk.services.s3.model.CreateBucketRequest;
public class CreateBucketInterceptorTest {
@Test
public void modifyRequest_DoesNotOverrideExistingLocationConstraint() {
CreateBucketRequest request = CreateBucketRequest.builder()
.bucket("test-bucket")
.createBucketConfiguration(CreateBucketConfiguration.builder()
.locationConstraint(
"us-west-2")
.build())
.build();
Context.ModifyRequest context = () -> request;
ExecutionAttributes attributes = new ExecutionAttributes()
.putAttribute(AwsExecutionAttribute.AWS_REGION, Region.US_EAST_1);
SdkRequest modifiedRequest = new CreateBucketInterceptor().modifyRequest(context, attributes);
String locationConstraint = ((CreateBucketRequest) modifiedRequest).createBucketConfiguration().locationConstraintAsString();
assertThat(locationConstraint).isEqualToIgnoringCase("us-west-2");
}
@Test
public void modifyRequest_UpdatesLocationConstraint_When_NullCreateBucketConfiguration() {
CreateBucketRequest request = CreateBucketRequest.builder()
.bucket("test-bucket")
.build();
Context.ModifyRequest context = () -> request;
ExecutionAttributes attributes = new ExecutionAttributes()
.putAttribute(AwsExecutionAttribute.AWS_REGION, Region.US_EAST_2);
SdkRequest modifiedRequest = new CreateBucketInterceptor().modifyRequest(context, attributes);
String locationConstraint = ((CreateBucketRequest) modifiedRequest).createBucketConfiguration().locationConstraintAsString();
assertThat(locationConstraint).isEqualToIgnoringCase("us-east-2");
}
@Test
public void modifyRequest_UpdatesLocationConstraint_When_NullLocationConstraint() {
CreateBucketRequest request = CreateBucketRequest.builder()
.bucket("test-bucket")
.createBucketConfiguration(CreateBucketConfiguration.builder()
.build())
.build();
Context.ModifyRequest context = () -> request;
ExecutionAttributes attributes = new ExecutionAttributes()
.putAttribute(AwsExecutionAttribute.AWS_REGION, Region.US_WEST_2);
SdkRequest modifiedRequest = new CreateBucketInterceptor().modifyRequest(context, attributes);
String locationConstraint = ((CreateBucketRequest) modifiedRequest).createBucketConfiguration().locationConstraintAsString();
assertThat(locationConstraint).isEqualToIgnoringCase("us-west-2");
}
/**
* For us-east-1 there must not be a location constraint (or containing CreateBucketConfiguration) sent.
*/
@Test
public void modifyRequest_UsEast1_UsesNullBucketConfiguration() {
CreateBucketRequest request = CreateBucketRequest.builder()
.bucket("test-bucket")
.createBucketConfiguration(CreateBucketConfiguration.builder()
.build())
.build();
Context.ModifyRequest context = () -> request;
ExecutionAttributes attributes = new ExecutionAttributes()
.putAttribute(AwsExecutionAttribute.AWS_REGION, Region.US_EAST_1);
SdkRequest modifiedRequest = new CreateBucketInterceptor().modifyRequest(context, attributes);
assertThat(((CreateBucketRequest) modifiedRequest).createBucketConfiguration()).isNull();
}
}
| 4,435 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal/handlers/StreamingRequestInterceptorTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.assertj.core.api.Assertions.assertThat;
import static software.amazon.awssdk.services.s3.utils.InterceptorTestUtils.modifyHttpRequestContext;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.UploadPartRequest;
public class StreamingRequestInterceptorTest {
private final StreamingRequestInterceptor interceptor = new StreamingRequestInterceptor();
@Test
public void modifyHttpRequest_setsExpect100Continue_whenSdkRequestIsPutObject() {
final SdkHttpRequest modifiedRequest = interceptor.modifyHttpRequest(modifyHttpRequestContext(PutObjectRequest.builder().build()),
new ExecutionAttributes());
assertThat(modifiedRequest.firstMatchingHeader("Expect")).hasValue("100-continue");
}
@Test
public void modifyHttpRequest_setsExpect100Continue_whenSdkRequestIsUploadPart() {
final SdkHttpRequest modifiedRequest =
interceptor.modifyHttpRequest(modifyHttpRequestContext(UploadPartRequest.builder().build()),
new ExecutionAttributes());
assertThat(modifiedRequest.firstMatchingHeader("Expect")).hasValue("100-continue");
}
@Test
public void modifyHttpRequest_doesNotSetExpect_whenSdkRequestIsNotPutObject() {
final SdkHttpRequest modifiedRequest = interceptor.modifyHttpRequest(modifyHttpRequestContext(GetObjectRequest.builder().build()),
new ExecutionAttributes());
assertThat(modifiedRequest.firstMatchingHeader("Expect")).isNotPresent();
}
}
| 4,436 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal/handlers/EnableTrailingChecksumInterceptorTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.assertj.core.api.Assertions.assertThat;
import static software.amazon.awssdk.services.s3.checksums.ChecksumConstant.CHECKSUM_ENABLED_RESPONSE_HEADER;
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.utils.InterceptorTestUtils.modifyHttpRequestContext;
import static software.amazon.awssdk.services.s3.utils.InterceptorTestUtils.modifyResponseContext;
import org.junit.jupiter.api.Test;
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.http.SdkHttpFullResponse;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.services.s3.S3Configuration;
import software.amazon.awssdk.services.s3.model.GetObjectAclRequest;
import software.amazon.awssdk.services.s3.model.GetObjectAclResponse;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
public class EnableTrailingChecksumInterceptorTest {
private EnableTrailingChecksumInterceptor interceptor = new EnableTrailingChecksumInterceptor();
@Test
public void modifyHttpRequest_getObjectTrailingChecksumEnabled_shouldAddTrailingChecksumHeader() {
Context.ModifyHttpRequest modifyHttpRequestContext =
modifyHttpRequestContext(GetObjectRequest.builder().build());
SdkHttpRequest sdkHttpRequest = interceptor.modifyHttpRequest(modifyHttpRequestContext, new ExecutionAttributes());
assertThat(sdkHttpRequest.headers().get(ENABLE_CHECKSUM_REQUEST_HEADER)).containsOnly(ENABLE_MD5_CHECKSUM_HEADER_VALUE);
}
@Test
public void modifyHttpRequest_getObjectTrailingChecksumDisabled_shouldNotModifyHttpRequest() {
Context.ModifyHttpRequest modifyHttpRequestContext =
modifyHttpRequestContext(GetObjectRequest.builder().build());
SdkHttpRequest sdkHttpRequest = interceptor.modifyHttpRequest(modifyHttpRequestContext,
new ExecutionAttributes().putAttribute(AwsSignerExecutionAttribute.SERVICE_CONFIG,
S3Configuration.builder().checksumValidationEnabled(false).build()));
assertThat(sdkHttpRequest).isEqualToComparingFieldByField(modifyHttpRequestContext.httpRequest());
}
@Test
public void modifyHttpRequest_nonGetObjectRequest_shouldNotModifyHttpRequest() {
Context.ModifyHttpRequest modifyHttpRequestContext =
modifyHttpRequestContext(PutObjectRequest.builder().build());
SdkHttpRequest sdkHttpRequest = interceptor.modifyHttpRequest(modifyHttpRequestContext, new ExecutionAttributes());
assertThat(sdkHttpRequest).isEqualToComparingFieldByField(modifyHttpRequestContext.httpRequest());
}
@Test
public void modifyResponse_getObjectResponseContainsChecksumHeader_shouldModifyResponse() {
long contentLength = 50;
GetObjectResponse response = GetObjectResponse.builder().contentLength(contentLength).build();
Context.ModifyResponse modifyResponseContext = modifyResponseContext(
GetObjectRequest.builder().build(),
response,
SdkHttpFullResponse.builder()
.putHeader(CHECKSUM_ENABLED_RESPONSE_HEADER, ENABLE_MD5_CHECKSUM_HEADER_VALUE).build());
GetObjectResponse actualResponse = (GetObjectResponse) interceptor.modifyResponse(modifyResponseContext,
new ExecutionAttributes());
assertThat(actualResponse).isNotEqualTo(response);
assertThat(actualResponse.contentLength()).isEqualTo(contentLength - S3_MD5_CHECKSUM_LENGTH);
}
@Test
public void modifyResponse_getObjectResponseNoChecksumHeader_shouldNotModifyResponse() {
long contentLength = 50;
GetObjectResponse response = GetObjectResponse.builder().contentLength(contentLength).build();
Context.ModifyResponse modifyResponseContext = modifyResponseContext(
GetObjectRequest.builder().build(),
response,
SdkHttpFullResponse.builder().build());
GetObjectResponse actualResponse = (GetObjectResponse) interceptor.modifyResponse(modifyResponseContext,
new ExecutionAttributes());
assertThat(actualResponse).isEqualTo(response);
}
@Test
public void modifyResponse_nonGetObjectResponse_shouldNotModifyResponse() {
GetObjectAclResponse getObjectAclResponse = GetObjectAclResponse.builder().build();
Context.ModifyResponse modifyResponseContext = modifyResponseContext(
GetObjectAclRequest.builder().build(),
getObjectAclResponse,
SdkHttpFullResponse.builder().build());
GetObjectAclResponse actualResponse = (GetObjectAclResponse) interceptor.modifyResponse(modifyResponseContext,
new ExecutionAttributes());
assertThat(actualResponse).isEqualTo(getObjectAclResponse);
}
}
| 4,437 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal/handlers/EnableChunkedEncodingInterceptorTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.assertj.core.api.Assertions.assertThat;
import static software.amazon.awssdk.auth.signer.S3SignerExecutionAttribute.ENABLE_CHUNKED_ENCODING;
import static software.amazon.awssdk.core.interceptor.SdkExecutionAttribute.SERVICE_CONFIG;
import java.net.URI;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.SdkRequest;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.core.interceptor.Context;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.services.s3.S3Configuration;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.UploadPartRequest;
public class EnableChunkedEncodingInterceptorTest {
private final EnableChunkedEncodingInterceptor interceptor = new EnableChunkedEncodingInterceptor();
@Test
public void modifyRequest_EnablesChunckedEncoding_ForPutObectRequest() {
ExecutionAttributes executionAttributes = new ExecutionAttributes();
assertThat(executionAttributes.getAttribute(ENABLE_CHUNKED_ENCODING)).isNull();
interceptor.modifyRequest(context(PutObjectRequest.builder().build()), executionAttributes);
assertThat(executionAttributes.getAttribute(ENABLE_CHUNKED_ENCODING)).isEqualTo(true);
}
@Test
public void modifyRequest_EnablesChunckedEncoding_ForUploadPartRequest() {
ExecutionAttributes executionAttributes = new ExecutionAttributes();
assertThat(executionAttributes.getAttribute(ENABLE_CHUNKED_ENCODING)).isNull();
interceptor.modifyRequest(context(UploadPartRequest.builder().build()), executionAttributes);
assertThat(executionAttributes.getAttribute(ENABLE_CHUNKED_ENCODING)).isEqualTo(true);
}
@Test
public void modifyRequest_DoesNotEnableChunckedEncoding_ForGetObjectRequest() {
ExecutionAttributes executionAttributes = new ExecutionAttributes();
assertThat(executionAttributes.getAttribute(ENABLE_CHUNKED_ENCODING)).isNull();
interceptor.modifyRequest(context(GetObjectRequest.builder().build()), executionAttributes);
assertThat(executionAttributes.getAttribute(ENABLE_CHUNKED_ENCODING)).isNull();
}
@Test
public void modifyRequest_DoesNotOverwriteExistingAttributeValue() {
ExecutionAttributes executionAttributes = new ExecutionAttributes();
interceptor.modifyRequest(context(PutObjectRequest.builder().build()), executionAttributes);
boolean newValue = !executionAttributes.getAttribute(ENABLE_CHUNKED_ENCODING);
executionAttributes.putAttribute(ENABLE_CHUNKED_ENCODING, newValue);
interceptor.modifyRequest(context(PutObjectRequest.builder().build()), executionAttributes);
assertThat(executionAttributes.getAttribute(ENABLE_CHUNKED_ENCODING)).isEqualTo(newValue);
}
@Test
public void modifyRequest_valueOnServiceConfig_TakesPrecedenceOverDefaultEnabled() {
S3Configuration config = S3Configuration.builder()
.chunkedEncodingEnabled(false)
.build();
ExecutionAttributes executionAttributes = new ExecutionAttributes()
.putAttribute(SERVICE_CONFIG, config);
interceptor.modifyRequest(context(PutObjectRequest.builder().build()), executionAttributes);
assertThat(executionAttributes.getAttribute(ENABLE_CHUNKED_ENCODING)).isEqualTo(false);
}
@Test
public void modifyRequest_existingValueInExecutionAttributes_TakesPrecedenceOverClientConfig() {
boolean configValue = false;
S3Configuration config = S3Configuration.builder()
.chunkedEncodingEnabled(configValue)
.build();
ExecutionAttributes executionAttributes = new ExecutionAttributes()
.putAttribute(SERVICE_CONFIG, config)
.putAttribute(ENABLE_CHUNKED_ENCODING, !configValue);
interceptor.modifyRequest(context(PutObjectRequest.builder().build()), executionAttributes);
assertThat(executionAttributes.getAttribute(ENABLE_CHUNKED_ENCODING)).isEqualTo(!configValue);
}
private Context.ModifyHttpRequest context(SdkRequest request) {
return new Context.ModifyHttpRequest() {
@Override
public SdkHttpRequest httpRequest() {
return null;
}
@Override
public Optional<RequestBody> requestBody() {
return null;
}
@Override
public Optional<AsyncRequestBody> asyncRequestBody() {
return null;
}
@Override
public SdkRequest request() {
return request;
}
};
}
private SdkHttpFullRequest sdkHttpFullRequest() {
return SdkHttpFullRequest.builder()
.uri(URI.create("http://test.com:80"))
.method(SdkHttpMethod.GET)
.build();
}
}
| 4,438 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal/handlers/ExceptionTranslationInterceptorTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.awscore.exception.AwsErrorDetails;
import software.amazon.awssdk.core.SdkRequest;
import software.amazon.awssdk.core.interceptor.Context;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.interceptor.InterceptorContext;
import software.amazon.awssdk.core.internal.interceptor.DefaultFailedExecutionContext;
import software.amazon.awssdk.http.SdkHttpFullResponse;
import software.amazon.awssdk.services.s3.model.HeadBucketRequest;
import software.amazon.awssdk.services.s3.model.HeadObjectRequest;
import software.amazon.awssdk.services.s3.model.NoSuchBucketException;
import software.amazon.awssdk.services.s3.model.NoSuchKeyException;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.S3Exception;
public class ExceptionTranslationInterceptorTest {
private static ExceptionTranslationInterceptor interceptor;
@BeforeAll
public static void setup() {
interceptor = new ExceptionTranslationInterceptor();
}
@Test
public void headBucket404_shouldTranslateException() {
S3Exception s3Exception = create404S3Exception();
Context.FailedExecution failedExecution = getFailedExecution(s3Exception,
HeadBucketRequest.builder().build());
assertThat(interceptor.modifyException(failedExecution, new ExecutionAttributes()))
.isExactlyInstanceOf(NoSuchBucketException.class);
}
@Test
public void headObject404_shouldTranslateException() {
S3Exception s3Exception = create404S3Exception();
Context.FailedExecution failedExecution = getFailedExecution(s3Exception,
HeadObjectRequest.builder().build());
assertThat(interceptor.modifyException(failedExecution, new ExecutionAttributes()))
.isExactlyInstanceOf(NoSuchKeyException.class);
}
@Test
public void headObjectOtherException_shouldNotThrowException() {
S3Exception s3Exception = (S3Exception) S3Exception.builder().statusCode(500).build();
Context.FailedExecution failedExecution = getFailedExecution(s3Exception,
HeadObjectRequest.builder().build());
assertThat(interceptor.modifyException(failedExecution, new ExecutionAttributes())).isEqualTo(s3Exception);
}
private Context.FailedExecution getFailedExecution(S3Exception s3Exception, SdkRequest sdkRequest) {
return DefaultFailedExecutionContext.builder().interceptorContext(InterceptorContext.builder()
.request(sdkRequest)
.build()).exception(s3Exception).build();
}
@Test
public void otherRequest_shouldNotThrowException() {
S3Exception s3Exception = create404S3Exception();
Context.FailedExecution failedExecution = getFailedExecution(s3Exception,
PutObjectRequest.builder().build());
assertThat(interceptor.modifyException(failedExecution, new ExecutionAttributes())).isEqualTo(s3Exception);
}
private S3Exception create404S3Exception() {
return (S3Exception) S3Exception.builder()
.awsErrorDetails(AwsErrorDetails.builder()
.sdkHttpResponse(SdkHttpFullResponse.builder()
.build())
.build())
.statusCode(404)
.build();
}
}
| 4,439 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal/settingproviders/ProfileDisableMultiRegionProviderTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.s3.internal.settingproviders;
import static java.lang.Boolean.FALSE;
import static java.lang.Boolean.TRUE;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static software.amazon.awssdk.profiles.ProfileFileSystemSetting.AWS_CONFIG_FILE;
import java.util.Optional;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider;
import software.amazon.awssdk.core.exception.SdkException;
import software.amazon.awssdk.core.interceptor.Context;
import software.amazon.awssdk.core.interceptor.ExecutionInterceptor;
import software.amazon.awssdk.profiles.ProfileFile;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.utils.StringInputStream;
public class ProfileDisableMultiRegionProviderTest {
private ProfileDisableMultiRegionProvider provider = ProfileDisableMultiRegionProvider.create();
@AfterEach
public void clearSystemProperty() {
System.clearProperty(AWS_CONFIG_FILE.property());
}
@Test
public void notSpecified_shouldReturnEmptyOptional() {
assertThat(provider.resolve()).isEqualTo(Optional.empty());
}
@Test
public void specifiedInConfigFile_shouldResolve() {
String configFile = getClass().getResource("ProfileFile_true").getFile();
System.setProperty(AWS_CONFIG_FILE.property(), configFile);
assertThat(provider.resolve()).isEqualTo(Optional.of(TRUE));
}
@Test
public void configFile_mixedSpace() {
String configFile = getClass().getResource("ProfileFile_mixedSpace").getFile();
System.setProperty(AWS_CONFIG_FILE.property(), configFile);
assertThat(provider.resolve()).isEqualTo(Optional.of(TRUE));
}
@Test
public void unsupportedValue_shouldThrowException() {
String configFile = getClass().getResource("ProfileFile_unsupportedValue").getFile();
System.setProperty(AWS_CONFIG_FILE.property(), configFile);
assertThatThrownBy(() -> provider.resolve()).isInstanceOf(IllegalArgumentException.class);
}
@Test
public void resolve_specifiedMultipleValuesInConfigFile_shouldResolveOncePerCall() {
String trueConfigFile = getClass().getResource("ProfileFile_true").getFile();
System.setProperty(AWS_CONFIG_FILE.property(), trueConfigFile);
assertThat(provider.resolve()).isEqualTo(Optional.of(TRUE));
System.clearProperty(AWS_CONFIG_FILE.property());
String falseConfigFile = getClass().getResource("ProfileFile_false").getFile();
System.setProperty(AWS_CONFIG_FILE.property(), falseConfigFile);
assertThat(provider.resolve()).isEqualTo(Optional.of(FALSE));
}
@Test
public void specifiedInOverrideConfig_shouldUse() {
ExecutionInterceptor interceptor = Mockito.spy(AbstractExecutionInterceptor.class);
String profileFileContent =
"[default]\n" +
"s3_disable_multiregion_access_points = true\n";
ProfileFile profileFile = ProfileFile.builder()
.type(ProfileFile.Type.CONFIGURATION)
.content(new StringInputStream(profileFileContent))
.build();
S3Client s3 = S3Client.builder()
.region(Region.US_WEST_2)
.credentialsProvider(AnonymousCredentialsProvider.create())
.overrideConfiguration(c -> c.defaultProfileFile(profileFile)
.defaultProfileName("default")
.addExecutionInterceptor(interceptor)
.retryPolicy(r -> r.numRetries(0)))
.serviceConfiguration(s -> s.useArnRegionEnabled(true))
.build();
String arn = "arn:aws:s3:us-banana-46:12345567890:accesspoint:foo";
assertThatThrownBy(() -> s3.getObject(r -> r.bucket(arn).key("bar"))).isInstanceOf(SdkException.class);
ArgumentCaptor<Context.BeforeTransmission> context = ArgumentCaptor.forClass(Context.BeforeTransmission.class);
Mockito.verify(interceptor).beforeTransmission(context.capture(), any());
String host = context.getValue().httpRequest().host();
assertThat(host).contains("us-banana-46");
}
public static abstract class AbstractExecutionInterceptor implements ExecutionInterceptor {}
}
| 4,440 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal/settingproviders/UseArnRegionProviderChainTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.s3.internal.settingproviders;
import static org.assertj.core.api.Assertions.assertThat;
import static software.amazon.awssdk.profiles.ProfileFileSystemSetting.AWS_CONFIG_FILE;
import static software.amazon.awssdk.services.s3.S3SystemSetting.AWS_S3_USE_ARN_REGION;
import java.util.Optional;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.testutils.EnvironmentVariableHelper;
class UseArnRegionProviderChainTest {
private final EnvironmentVariableHelper helper = new EnvironmentVariableHelper();
@AfterEach
void clearSystemProperty() {
System.clearProperty(AWS_S3_USE_ARN_REGION.property());
System.clearProperty(AWS_CONFIG_FILE.property());
helper.reset();
}
@Test
void notSpecified_shouldReturnEmptyOptional() {
assertThat(UseArnRegionProviderChain.create().resolveUseArnRegion()).isEqualTo(Optional.empty());
}
@Test
void specifiedInBothProviders_systemPropertiesShouldTakePrecedence() {
System.setProperty(AWS_S3_USE_ARN_REGION.property(), "false");
String configFile = getClass().getResource("ProfileFile_true").getFile();
System.setProperty(AWS_CONFIG_FILE.property(), configFile);
assertThat(UseArnRegionProviderChain.create().resolveUseArnRegion()).isEqualTo(Optional.of(Boolean.FALSE));
}
@Test
void systemPropertiesThrowException_shouldUseConfigFile() {
System.setProperty(AWS_S3_USE_ARN_REGION.property(), "foobar");
String configFile = getClass().getResource("ProfileFile_true").getFile();
System.setProperty(AWS_CONFIG_FILE.property(), configFile);
assertThat(UseArnRegionProviderChain.create().resolveUseArnRegion()).isEqualTo(Optional.of(Boolean.TRUE));
}
@Test
void resolveUseArnRegion_systemPropertiesNotSpecifiedConfigFileValueTrue_resolvesOncePerCall() {
String trueConfigFile = getClass().getResource("ProfileFile_true").getFile();
System.setProperty(AWS_CONFIG_FILE.property(), trueConfigFile);
UseArnRegionProviderChain providerChain = UseArnRegionProviderChain.create();
assertThat(providerChain.resolveUseArnRegion()).isEqualTo(Optional.of(Boolean.TRUE));
}
@Test
void resolveUseArnRegion_systemPropertiesNotSpecifiedConfigFileValueFalse_resolvesOncePerCall() {
String falseConfigFile = getClass().getResource("ProfileFile_false").getFile();
System.setProperty(AWS_CONFIG_FILE.property(), falseConfigFile);
UseArnRegionProviderChain providerChain = UseArnRegionProviderChain.create();
assertThat(providerChain.resolveUseArnRegion()).isEqualTo(Optional.of(Boolean.FALSE));
}
@Test
void bothProvidersThrowException_shouldReturnEmpty() {
System.setProperty(AWS_S3_USE_ARN_REGION.property(), "foobar");
String configFile = getClass().getResource("ProfileFile_unsupportedValue").getFile();
System.setProperty(AWS_CONFIG_FILE.property(), configFile);
assertThat(UseArnRegionProviderChain.create().resolveUseArnRegion()).isEqualTo(Optional.empty());
}
}
| 4,441 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal/settingproviders/SystemSettingsUseArnRegionProviderTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.s3.internal.settingproviders;
import static java.lang.Boolean.FALSE;
import static java.lang.Boolean.TRUE;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static software.amazon.awssdk.services.s3.S3SystemSetting.AWS_S3_USE_ARN_REGION;
import java.util.Optional;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.testutils.EnvironmentVariableHelper;
public class SystemSettingsUseArnRegionProviderTest {
private final SystemsSettingsUseArnRegionProvider provider = SystemsSettingsUseArnRegionProvider.create();
private final EnvironmentVariableHelper helper = new EnvironmentVariableHelper();
@AfterEach
public void clearSystemProperty() {
System.clearProperty(AWS_S3_USE_ARN_REGION.property());
helper.reset();
}
@Test
public void notSpecified_shouldReturnEmptyOptional() {
assertThat(provider.resolveUseArnRegion()).isEqualTo(Optional.empty());
}
@Test
public void emptySystemProperties_shouldReturnEmptyOptional() {
System.setProperty(AWS_S3_USE_ARN_REGION.property(), "");
assertThatThrownBy(() -> provider.resolveUseArnRegion()).isInstanceOf(IllegalStateException.class);
}
@Test
public void specifiedInSystemProperties_shouldResolve() {
System.setProperty(AWS_S3_USE_ARN_REGION.property(), "false");
assertThat(provider.resolveUseArnRegion()).isEqualTo(Optional.of(FALSE));
}
@Test
public void specifiedInEnvironmentVariables_shouldResolve() {
helper.set(AWS_S3_USE_ARN_REGION.environmentVariable(), "true");
assertThat(provider.resolveUseArnRegion()).isEqualTo(Optional.of(TRUE));
}
@Test
public void specifiedInBothPlaces_SystemPropertiesShouldTakePrecedence() {
System.setProperty(AWS_S3_USE_ARN_REGION.property(), "true");
helper.set(AWS_S3_USE_ARN_REGION.environmentVariable(), "false");
assertThat(provider.resolveUseArnRegion()).isEqualTo(Optional.of(TRUE));
}
@Test
public void mixedSpace_shouldResolveCorrectly() {
System.setProperty(AWS_S3_USE_ARN_REGION.property(), "tRuE");
assertThat(provider.resolveUseArnRegion()).isEqualTo(Optional.of(TRUE));
}
}
| 4,442 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal/settingproviders/ProfileUseArnRegionProviderTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.s3.internal.settingproviders;
import static java.lang.Boolean.FALSE;
import static java.lang.Boolean.TRUE;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static software.amazon.awssdk.profiles.ProfileFileSystemSetting.AWS_CONFIG_FILE;
import java.util.Optional;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider;
import software.amazon.awssdk.core.exception.SdkException;
import software.amazon.awssdk.core.interceptor.Context;
import software.amazon.awssdk.core.interceptor.ExecutionInterceptor;
import software.amazon.awssdk.profiles.ProfileFile;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.utils.StringInputStream;
public class ProfileUseArnRegionProviderTest {
private ProfileUseArnRegionProvider provider = ProfileUseArnRegionProvider.create();
@AfterEach
public void clearSystemProperty() {
System.clearProperty(AWS_CONFIG_FILE.property());
}
@Test
public void notSpecified_shouldReturnEmptyOptional() {
assertThat(provider.resolveUseArnRegion()).isEqualTo(Optional.empty());
}
@Test
public void specifiedInConfigFile_shouldResolve() {
String configFile = getClass().getResource("ProfileFile_true").getFile();
System.setProperty(AWS_CONFIG_FILE.property(), configFile);
assertThat(provider.resolveUseArnRegion()).isEqualTo(Optional.of(TRUE));
}
@Test
public void configFile_mixedSpace() {
String configFile = getClass().getResource("ProfileFile_mixedSpace").getFile();
System.setProperty(AWS_CONFIG_FILE.property(), configFile);
assertThat(provider.resolveUseArnRegion()).isEqualTo(Optional.of(FALSE));
}
@Test
public void unsupportedValue_shouldThrowException() {
String configFile = getClass().getResource("ProfileFile_unsupportedValue").getFile();
System.setProperty(AWS_CONFIG_FILE.property(), configFile);
assertThatThrownBy(() -> provider.resolveUseArnRegion()).isInstanceOf(IllegalArgumentException.class);
}
@Test
public void commaNoSpace_shouldResolveCorrectly() {
String configFile = getClass().getResource("ProfileFile_noSpace").getFile();
System.setProperty(AWS_CONFIG_FILE.property(), configFile);
assertThat(provider.resolveUseArnRegion()).isEqualTo(Optional.of(FALSE));
}
@Test
public void resolveUseArnRegion_specifiedMultipleValuesInConfigFile_shouldResolveOncePerCall() {
String trueConfigFile = getClass().getResource("ProfileFile_true").getFile();
System.setProperty(AWS_CONFIG_FILE.property(), trueConfigFile);
assertThat(provider.resolveUseArnRegion()).isEqualTo(Optional.of(TRUE));
System.clearProperty(AWS_CONFIG_FILE.property());
String falseConfigFile = getClass().getResource("ProfileFile_false").getFile();
System.setProperty(AWS_CONFIG_FILE.property(), falseConfigFile);
assertThat(provider.resolveUseArnRegion()).isEqualTo(Optional.of(FALSE));
}
@Test
public void specifiedInOverrideConfig_shouldUse() {
ExecutionInterceptor interceptor = Mockito.spy(AbstractExecutionInterceptor.class);
String profileFileContent =
"[default]\n" +
"s3_use_arn_region = true\n";
ProfileFile profileFile = ProfileFile.builder()
.type(ProfileFile.Type.CONFIGURATION)
.content(new StringInputStream(profileFileContent))
.build();
S3Client s3 = S3Client.builder()
.region(Region.US_WEST_2)
.credentialsProvider(AnonymousCredentialsProvider.create())
.overrideConfiguration(c -> c.defaultProfileFile(profileFile)
.defaultProfileName("default")
.addExecutionInterceptor(interceptor)
.retryPolicy(r -> r.numRetries(0)))
.build();
String arn = "arn:aws:s3:us-banana-46:12345567890:accesspoint:foo";
assertThatThrownBy(() -> s3.getObject(r -> r.bucket(arn).key("bar"))).isInstanceOf(SdkException.class);
ArgumentCaptor<Context.BeforeTransmission> context = ArgumentCaptor.forClass(Context.BeforeTransmission.class);
Mockito.verify(interceptor).beforeTransmission(context.capture(), any());
String host = context.getValue().httpRequest().host();
assertThat(host).contains("us-banana-46");
}
public static abstract class AbstractExecutionInterceptor implements ExecutionInterceptor {}
}
| 4,443 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal/settingproviders/SystemSettingsDisableMultiRegionProviderTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.s3.internal.settingproviders;
import static java.lang.Boolean.FALSE;
import static java.lang.Boolean.TRUE;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static software.amazon.awssdk.services.s3.S3SystemSetting.AWS_S3_DISABLE_MULTIREGION_ACCESS_POINTS;
import java.util.Optional;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.testutils.EnvironmentVariableHelper;
public class SystemSettingsDisableMultiRegionProviderTest {
private final SystemsSettingsDisableMultiRegionProvider provider = SystemsSettingsDisableMultiRegionProvider.create();
private final EnvironmentVariableHelper helper = new EnvironmentVariableHelper();
@AfterEach
public void clearSystemProperty() {
System.clearProperty(AWS_S3_DISABLE_MULTIREGION_ACCESS_POINTS.property());
helper.reset();
}
@Test
public void notSpecified_shouldReturnEmptyOptional() {
assertThat(provider.resolve()).isEqualTo(Optional.empty());
}
@Test
public void specifiedInSystemProperties_shouldResolve() {
System.setProperty(AWS_S3_DISABLE_MULTIREGION_ACCESS_POINTS.property(), "false");
assertThat(provider.resolve()).isEqualTo(Optional.of(FALSE));
}
@Test
public void specifiedInEnvironmentVariables_shouldResolve() {
helper.set(AWS_S3_DISABLE_MULTIREGION_ACCESS_POINTS.environmentVariable(), "true");
assertThat(provider.resolve()).isEqualTo(Optional.of(TRUE));
}
@Test
public void specifiedInBothPlaces_SystemPropertiesShouldTakePrecedence() {
System.setProperty(AWS_S3_DISABLE_MULTIREGION_ACCESS_POINTS.property(), "true");
helper.set(AWS_S3_DISABLE_MULTIREGION_ACCESS_POINTS.environmentVariable(), "false");
assertThat(provider.resolve()).isEqualTo(Optional.of(TRUE));
}
@Test
public void mixedSpace_shouldResolveCorrectly() {
System.setProperty(AWS_S3_DISABLE_MULTIREGION_ACCESS_POINTS.property(), "tRuE");
assertThat(provider.resolve()).isEqualTo(Optional.of(TRUE));
}
@Test
public void emptySystemProperties_shouldThrowError() {
System.setProperty(AWS_S3_DISABLE_MULTIREGION_ACCESS_POINTS.property(), "");
assertThatThrownBy(provider::resolve).isInstanceOf(IllegalStateException.class);
}
@Test
public void nonBoolean_shouldThrowError() {
System.setProperty(AWS_S3_DISABLE_MULTIREGION_ACCESS_POINTS.property(), "enable");
assertThatThrownBy(provider::resolve).isInstanceOf(IllegalStateException.class);
}
}
| 4,444 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal/settingproviders/DisableMultiRegionProviderChainTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.s3.internal.settingproviders;
import static org.assertj.core.api.Assertions.assertThat;
import static software.amazon.awssdk.profiles.ProfileFileSystemSetting.AWS_CONFIG_FILE;
import static software.amazon.awssdk.services.s3.S3SystemSetting.AWS_S3_DISABLE_MULTIREGION_ACCESS_POINTS;
import java.util.Optional;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.testutils.EnvironmentVariableHelper;
class DisableMultiRegionProviderChainTest {
private final EnvironmentVariableHelper helper = new EnvironmentVariableHelper();
@AfterEach
void clearSystemProperty() {
System.clearProperty(AWS_S3_DISABLE_MULTIREGION_ACCESS_POINTS.property());
System.clearProperty(AWS_CONFIG_FILE.property());
helper.reset();
}
@Test
void notSpecified_shouldReturnEmptyOptional() {
assertThat(DisableMultiRegionProviderChain.create().resolve()).isEqualTo(Optional.empty());
}
@Test
void specifiedInBothProviders_systemPropertiesShouldTakePrecedence() {
System.setProperty(AWS_S3_DISABLE_MULTIREGION_ACCESS_POINTS.property(), "false");
String configFile = getClass().getResource("ProfileFile_true").getFile();
System.setProperty(AWS_CONFIG_FILE.property(), configFile);
assertThat(DisableMultiRegionProviderChain.create().resolve()).isEqualTo(Optional.of(Boolean.FALSE));
}
@Test
void systemPropertiesThrowException_shouldUseConfigFile() {
System.setProperty(AWS_S3_DISABLE_MULTIREGION_ACCESS_POINTS.property(), "foobar");
String configFile = getClass().getResource("ProfileFile_true").getFile();
System.setProperty(AWS_CONFIG_FILE.property(), configFile);
assertThat(DisableMultiRegionProviderChain.create().resolve()).isEqualTo(Optional.of(Boolean.TRUE));
}
@Test
void systemPropertiesNotSpecified_shouldUseConfigFile() {
String configFile = getClass().getResource("ProfileFile_true").getFile();
System.setProperty(AWS_CONFIG_FILE.property(), configFile);
assertThat(DisableMultiRegionProviderChain.create().resolve()).isEqualTo(Optional.of(Boolean.TRUE));
}
@Test
void resolve_systemPropertiesNotSpecified_shouldResolveOncePerCall() {
String trueConfigFile = getClass().getResource("ProfileFile_true").getFile();
System.setProperty(AWS_CONFIG_FILE.property(), trueConfigFile);
assertThat(DisableMultiRegionProviderChain.create().resolve()).isEqualTo(Optional.of(Boolean.TRUE));
System.clearProperty(AWS_CONFIG_FILE.property());
String falseConfigFile = getClass().getResource("ProfileFile_false").getFile();
System.setProperty(AWS_CONFIG_FILE.property(), falseConfigFile);
assertThat(DisableMultiRegionProviderChain.create().resolve()).isEqualTo(Optional.of(Boolean.FALSE));
}
@Test
void bothProvidersThrowException_shouldReturnEmpty() {
System.setProperty(AWS_S3_DISABLE_MULTIREGION_ACCESS_POINTS.property(), "foobar");
String configFile = getClass().getResource("ProfileFile_unsupportedValue").getFile();
System.setProperty(AWS_CONFIG_FILE.property(), configFile);
assertThat(DisableMultiRegionProviderChain.create().resolve()).isEqualTo(Optional.empty());
}
}
| 4,445 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal/crossregion/S3CrossRegionSyncClientRedirectTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.s3.internal.crossregion;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.junit.jupiter.api.BeforeEach;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.HeadBucketRequest;
import software.amazon.awssdk.services.s3.model.HeadBucketResponse;
import software.amazon.awssdk.services.s3.model.ListBucketsRequest;
import software.amazon.awssdk.services.s3.model.ListBucketsResponse;
import software.amazon.awssdk.services.s3.model.ListObjectsRequest;
import software.amazon.awssdk.services.s3.model.ListObjectsResponse;
import software.amazon.awssdk.services.s3.model.S3Exception;
public class S3CrossRegionSyncClientRedirectTest extends S3CrossRegionRedirectTestBase {
private static S3Client mockDelegateClient;
private S3Client decoratedS3Client;
@BeforeEach
public void setup() {
mockDelegateClient = Mockito.mock(S3Client.class);
decoratedS3Client = new S3CrossRegionSyncClient(mockDelegateClient);
}
@Override
protected void stubApiWithAuthorizationHeaderWithInternalSoftwareError() {
when(mockDelegateClient.headBucket(any(HeadBucketRequest.class)))
.thenThrow(redirectException(500, null, "InternalError", null));
}
@Override
protected void stubHeadBucketRedirectWithAuthorizationHeaderMalformed() {
when(mockDelegateClient.headBucket(any(HeadBucketRequest.class)))
.thenThrow(redirectException(400, CROSS_REGION.id(), "AuthorizationHeaderMalformed", null))
.thenReturn(HeadBucketResponse.builder().build());
}
@Override
protected void stubApiWithAuthorizationHeaderMalformedError() {
when(mockDelegateClient.listObjects(any(ListObjectsRequest.class)))
.thenThrow(redirectException(400, null, "AuthorizationHeaderMalformed", null))
.thenReturn(ListObjectsResponse.builder().contents(S3_OBJECTS).build());
}
@Override
protected void verifyNoBucketCall() {
assertThatExceptionOfType(S3Exception.class)
.isThrownBy(
() -> noBucketCallToService())
.withMessage("Redirect (Service: S3, Status Code: 301, Request ID: 1, "
+ "Extended Request ID: A1)");
}
@Override
protected void verifyNoBucketApiCall(int times, ArgumentCaptor<ListBucketsRequest> requestArgumentCaptor) {
verify(mockDelegateClient, times(times)).listBuckets(requestArgumentCaptor.capture());
}
@Override
protected ListBucketsResponse noBucketCallToService() {
return decoratedS3Client.listBuckets(ListBucketsRequest.builder().build());
}
@Override
protected void stubApiWithNoBucketField() {
when(mockDelegateClient.listBuckets(any(ListBucketsRequest.class)))
.thenThrow(redirectException(301, CROSS_REGION.id(), null, "Redirect"))
.thenReturn(ListBucketsResponse.builder().build());
}
@Override
protected void stubHeadBucketRedirect() {
when(mockDelegateClient.headBucket(any(HeadBucketRequest.class)))
.thenThrow(redirectException(301, CROSS_REGION.id(), null, null))
.thenReturn(HeadBucketResponse.builder().build());
}
@Override
protected void stubRedirectWithNoRegionAndThenSuccess(Integer redirect) {
when(mockDelegateClient.listObjects(any(ListObjectsRequest.class)))
.thenThrow(redirectException(redirect, null, null, null))
.thenReturn(ListObjectsResponse.builder().contents(S3_OBJECTS).build());
}
@Override
protected void stubRedirectThenError(Integer redirect) {
when(mockDelegateClient.listObjects(any(ListObjectsRequest.class)))
.thenThrow(redirectException(redirect, CROSS_REGION.id(), null, null))
.thenThrow(redirectException(400, null, "InvalidArgument", "Invalid id"));
}
@Override
protected void stubRedirectSuccessSuccess(Integer redirect) {
when(mockDelegateClient.listObjects(any(ListObjectsRequest.class)))
.thenThrow(redirectException(redirect, CROSS_REGION.id(), null, null))
.thenReturn(ListObjectsResponse.builder().contents(S3_OBJECTS).build())
.thenReturn(ListObjectsResponse.builder().contents(S3_OBJECTS).build());
}
@Override
protected ListObjectsResponse apiCallToService() {
return decoratedS3Client.listObjects(i -> i.bucket(CROSS_REGION_BUCKET));
}
@Override
protected void verifyTheApiServiceCall(int times, ArgumentCaptor<ListObjectsRequest> requestArgumentCaptor) {
verify(mockDelegateClient, times(times)).listObjects(requestArgumentCaptor.capture());
}
@Override
protected void verifyHeadBucketServiceCall(int times) {
verify(mockDelegateClient, times(times)).headBucket(any(HeadBucketRequest.class));
}
@Override
protected void stubServiceClientConfiguration() {
when(mockDelegateClient.serviceClientConfiguration()).thenReturn(CONFIGURED_ENDPOINT_PROVIDER);
}
@Override
protected void stubClientAPICallWithFirstRedirectThenSuccessWithRegionInErrorResponse(Integer redirect) {
when(mockDelegateClient.listObjects(any(ListObjectsRequest.class)))
.thenThrow(redirectException(301, CROSS_REGION.id(), null, null))
.thenReturn(ListObjectsResponse.builder().contents(S3_OBJECTS).build());
}
}
| 4,446 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal/crossregion/S3CrossRegionRedirectTestBase.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.s3.internal.crossregion;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import java.util.Collections;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import software.amazon.awssdk.awscore.exception.AwsErrorDetails;
import software.amazon.awssdk.awscore.exception.AwsServiceException;
import software.amazon.awssdk.endpoints.EndpointProvider;
import software.amazon.awssdk.http.SdkHttpFullResponse;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3ServiceClientConfiguration;
import software.amazon.awssdk.services.s3.endpoints.S3EndpointProvider;
import software.amazon.awssdk.services.s3.internal.crossregion.endpointprovider.BucketEndpointProvider;
import software.amazon.awssdk.services.s3.model.ListBucketsRequest;
import software.amazon.awssdk.services.s3.model.ListBucketsResponse;
import software.amazon.awssdk.services.s3.model.ListObjectsRequest;
import software.amazon.awssdk.services.s3.model.ListObjectsResponse;
import software.amazon.awssdk.services.s3.model.S3Exception;
import software.amazon.awssdk.services.s3.model.S3Object;
public abstract class S3CrossRegionRedirectTestBase {
public static final String X_AMZ_BUCKET_REGION = "x-amz-bucket-region";
protected static final String CROSS_REGION_BUCKET = "anyBucket";
protected static final Region CROSS_REGION = Region.EU_CENTRAL_1;
protected static final Region CHANGED_CROSS_REGION = Region.US_WEST_1;
public static final Region OVERRIDE_CONFIGURED_REGION = Region.US_WEST_2;
protected static final List<S3Object> S3_OBJECTS = Collections.singletonList(S3Object.builder().key("keyObject").build());
protected static final S3ServiceClientConfiguration CONFIGURED_ENDPOINT_PROVIDER =
S3ServiceClientConfiguration.builder().endpointProvider(S3EndpointProvider.defaultProvider()).build();
@ParameterizedTest
@ValueSource(ints = {301, 307})
void decoratorAttemptsToRetryWithRegionNameInErrorResponse(Integer redirect) throws Throwable {
stubServiceClientConfiguration();
stubClientAPICallWithFirstRedirectThenSuccessWithRegionInErrorResponse(redirect);
// Assert retrieved listObject
ListObjectsResponse listObjectsResponse = apiCallToService();
assertThat(listObjectsResponse.contents()).isEqualTo(S3_OBJECTS);
ArgumentCaptor<ListObjectsRequest> requestArgumentCaptor = ArgumentCaptor.forClass(ListObjectsRequest.class);
verifyTheApiServiceCall(2, requestArgumentCaptor);
assertThat(requestArgumentCaptor.getAllValues().get(0).overrideConfiguration().get().endpointProvider()).isNotPresent();
verifyTheEndPointProviderOverridden(1, requestArgumentCaptor, CROSS_REGION.id());
verifyHeadBucketServiceCall(0);
}
@ParameterizedTest
@ValueSource(ints = {301, 307})
void decoratorUsesCache_when_CrossRegionAlreadyPresent(Integer redirect) throws Throwable {
stubServiceClientConfiguration();
stubRedirectSuccessSuccess(redirect);
ListObjectsResponse firstListObjectCall = apiCallToService();
assertThat(firstListObjectCall.contents()).isEqualTo(S3_OBJECTS);
ListObjectsResponse secondListObjectCall = apiCallToService();
assertThat(secondListObjectCall.contents()).isEqualTo(S3_OBJECTS);
ArgumentCaptor<ListObjectsRequest> requestArgumentCaptor = ArgumentCaptor.forClass(ListObjectsRequest.class);
verifyTheApiServiceCall(3, requestArgumentCaptor);
assertThat(requestArgumentCaptor.getAllValues().get(0).overrideConfiguration().get().endpointProvider()).isNotPresent();
verifyTheEndPointProviderOverridden(1, requestArgumentCaptor, CROSS_REGION.id());
verifyTheEndPointProviderOverridden(2, requestArgumentCaptor, CROSS_REGION.id());
verifyHeadBucketServiceCall(0);
}
/**
* Call is redirected to actual end point
* The redirected call fails because of incorrect parameters passed
* This exception should be reported correctly
*/
@ParameterizedTest
@ValueSource(ints = {301, 307})
void apiCallFailure_when_CallFailsAfterRedirection(Integer redirectError) {
stubServiceClientConfiguration();
stubRedirectThenError(redirectError);
assertThatExceptionOfType(S3Exception.class)
.isThrownBy(() -> apiCallToService())
.withMessageContaining("Invalid id (Service: S3, Status Code: 400, Request ID: 1, Extended Request ID: A1)");
verifyHeadBucketServiceCall(0);
}
@ParameterizedTest
@ValueSource(ints = {301, 307})
void headBucketCalled_when_RedirectDoesNotHasRegionName(Integer redirect) throws Throwable {
stubServiceClientConfiguration();
stubRedirectWithNoRegionAndThenSuccess(redirect);
stubHeadBucketRedirect();
ListObjectsResponse listObjectsResponse = apiCallToService();
assertThat(listObjectsResponse.contents()).isEqualTo(S3_OBJECTS);
ArgumentCaptor<ListObjectsRequest> requestArgumentCaptor = ArgumentCaptor.forClass(ListObjectsRequest.class);
verifyTheApiServiceCall(2, requestArgumentCaptor);
assertThat(requestArgumentCaptor.getAllValues().get(0).overrideConfiguration().get().endpointProvider()).isNotPresent();
verifyTheEndPointProviderOverridden(1, requestArgumentCaptor, CROSS_REGION.id());
verifyHeadBucketServiceCall(1);
}
@ParameterizedTest
@ValueSource(ints = {301, 307})
void headBucketCalledAndCached__when_RedirectDoesNotHasRegionName(Integer redirect) throws Throwable {
stubServiceClientConfiguration();
stubRedirectWithNoRegionAndThenSuccess(redirect);
stubHeadBucketRedirect();
ListObjectsResponse firstListObjectCall = apiCallToService();
assertThat(firstListObjectCall.contents()).isEqualTo(S3_OBJECTS);
ArgumentCaptor<ListObjectsRequest> preCacheCaptor = ArgumentCaptor.forClass(ListObjectsRequest.class);
verifyTheApiServiceCall(2, preCacheCaptor);
// We need to get the BucketEndpointProvider in order to update the cache
verifyTheEndPointProviderOverridden(1, preCacheCaptor, CROSS_REGION.id());
ListObjectsResponse secondListObjectCall = apiCallToService();
assertThat(secondListObjectCall.contents()).isEqualTo(S3_OBJECTS);
// We need to captor again so that we get the args used in second API Call
ArgumentCaptor<ListObjectsRequest> overAllPostCacheCaptor = ArgumentCaptor.forClass(ListObjectsRequest.class);
verifyTheApiServiceCall(3, overAllPostCacheCaptor);
assertThat(overAllPostCacheCaptor.getAllValues().get(0).overrideConfiguration().get().endpointProvider()).isNotPresent();
verifyTheEndPointProviderOverridden(1, overAllPostCacheCaptor, CROSS_REGION.id());
verifyTheEndPointProviderOverridden(2, overAllPostCacheCaptor, CROSS_REGION.id());
verifyHeadBucketServiceCall(1);
}
@Test
void requestsAreNotOverridden_when_NoBucketInRequest() throws Throwable {
stubServiceClientConfiguration();
stubApiWithNoBucketField();
stubHeadBucketRedirect();
verifyNoBucketCall();
ArgumentCaptor<ListBucketsRequest> requestArgumentCaptor = ArgumentCaptor.forClass(ListBucketsRequest.class);
verifyHeadBucketServiceCall(0);
verifyNoBucketApiCall(1, requestArgumentCaptor);
assertThat(requestArgumentCaptor.getAllValues().get(0).overrideConfiguration().get().endpointProvider()).isNotPresent();
verifyHeadBucketServiceCall(0);
}
@Test
void given_CrossRegionClient_when_AuthorizationFailureInMainCall_then_RegionRetrievedFromHeadBucketFailureResponse() throws Throwable {
stubServiceClientConfiguration();
stubApiWithAuthorizationHeaderMalformedError() ;
stubHeadBucketRedirect();
ListObjectsResponse firstListObjectCall = apiCallToService();
assertThat(firstListObjectCall.contents()).isEqualTo(S3_OBJECTS);
ArgumentCaptor<ListObjectsRequest> preCacheCaptor = ArgumentCaptor.forClass(ListObjectsRequest.class);
verifyTheApiServiceCall(2, preCacheCaptor);
// We need to get the BucketEndpointProvider in order to update the cache
verifyTheEndPointProviderOverridden(1, preCacheCaptor, CROSS_REGION.id());
ListObjectsResponse secondListObjectCall = apiCallToService();
assertThat(secondListObjectCall.contents()).isEqualTo(S3_OBJECTS);
// We need to captor again so that we get the args used in second API Call
ArgumentCaptor<ListObjectsRequest> overAllPostCacheCaptor = ArgumentCaptor.forClass(ListObjectsRequest.class);
verifyTheApiServiceCall(3, overAllPostCacheCaptor);
assertThat(overAllPostCacheCaptor.getAllValues().get(0).overrideConfiguration().get().endpointProvider()).isNotPresent();
verifyTheEndPointProviderOverridden(1, overAllPostCacheCaptor, CROSS_REGION.id());
verifyTheEndPointProviderOverridden(2, overAllPostCacheCaptor, CROSS_REGION.id());
verifyHeadBucketServiceCall(1);
}
@Test
void given_CrossRegionClient_when_AuthorizationFailureInHeadBucketWithRegion_then_CrossRegionCallSucceeds() throws Throwable {
stubServiceClientConfiguration();
stubApiWithAuthorizationHeaderMalformedError() ;
stubHeadBucketRedirectWithAuthorizationHeaderMalformed();
ListObjectsResponse firstListObjectCall = apiCallToService();
assertThat(firstListObjectCall.contents()).isEqualTo(S3_OBJECTS);
ArgumentCaptor<ListObjectsRequest> preCacheCaptor = ArgumentCaptor.forClass(ListObjectsRequest.class);
verifyTheApiServiceCall(2, preCacheCaptor);
// We need to get the BucketEndpointProvider in order to update the cache
verifyTheEndPointProviderOverridden(1, preCacheCaptor, CROSS_REGION.id());
ListObjectsResponse secondListObjectCall = apiCallToService();
assertThat(secondListObjectCall.contents()).isEqualTo(S3_OBJECTS);
// We need to captor again so that we get the args used in second API Call
ArgumentCaptor<ListObjectsRequest> overAllPostCacheCaptor = ArgumentCaptor.forClass(ListObjectsRequest.class);
verifyTheApiServiceCall(3, overAllPostCacheCaptor);
assertThat(overAllPostCacheCaptor.getAllValues().get(0).overrideConfiguration().get().endpointProvider()).isNotPresent();
verifyTheEndPointProviderOverridden(1, overAllPostCacheCaptor, CROSS_REGION.id());
verifyTheEndPointProviderOverridden(2, overAllPostCacheCaptor, CROSS_REGION.id());
verifyHeadBucketServiceCall(1);
}
protected abstract void stubApiWithAuthorizationHeaderWithInternalSoftwareError();
protected abstract void stubHeadBucketRedirectWithAuthorizationHeaderMalformed();
protected abstract void stubApiWithAuthorizationHeaderMalformedError();
protected abstract void verifyNoBucketCall();
protected abstract void verifyNoBucketApiCall(int i, ArgumentCaptor<ListBucketsRequest> requestArgumentCaptor);
protected abstract ListBucketsResponse noBucketCallToService() throws Throwable;
protected abstract void stubApiWithNoBucketField();
protected abstract void stubHeadBucketRedirect();
protected abstract void stubRedirectWithNoRegionAndThenSuccess(Integer redirect);
protected abstract void stubRedirectThenError(Integer redirect);
protected abstract void stubRedirectSuccessSuccess(Integer redirect);
protected AwsServiceException redirectException(int statusCode, String region, String errorCode, String errorMessage) {
SdkHttpFullResponse.Builder sdkHttpFullResponseBuilder = SdkHttpFullResponse.builder();
if (region != null) {
sdkHttpFullResponseBuilder.appendHeader(X_AMZ_BUCKET_REGION, region);
}
return S3Exception.builder()
.statusCode(statusCode)
.requestId("1")
.extendedRequestId("A1")
.awsErrorDetails(AwsErrorDetails.builder()
.errorMessage(errorMessage)
.sdkHttpResponse(sdkHttpFullResponseBuilder.build())
.errorCode(errorCode)
.serviceName("S3")
.build())
.build();
}
void verifyTheEndPointProviderOverridden(int attempt,
ArgumentCaptor<ListObjectsRequest> requestArgumentCaptor,
String expectedRegion) throws Exception {
EndpointProvider overridenEndpointProvider =
requestArgumentCaptor.getAllValues().get(attempt).overrideConfiguration().get().endpointProvider().get();
assertThat(overridenEndpointProvider).isInstanceOf(BucketEndpointProvider.class);
assertThat(((S3EndpointProvider) overridenEndpointProvider).resolveEndpoint(e -> e.region(Region.US_WEST_2)
.bucket(CROSS_REGION_BUCKET)
.build())
.get().url().getHost())
.isEqualTo("s3." + expectedRegion + ".amazonaws.com");
}
protected abstract ListObjectsResponse apiCallToService() throws Throwable;
protected abstract void verifyTheApiServiceCall(int times, ArgumentCaptor<ListObjectsRequest> requestArgumentCaptor);
protected abstract void verifyHeadBucketServiceCall(int times);
protected abstract void stubServiceClientConfiguration();
protected abstract void stubClientAPICallWithFirstRedirectThenSuccessWithRegionInErrorResponse(Integer redirect);
}
| 4,447 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal/crossregion/S3CrossRegionAsyncClientTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.s3.internal.crossregion;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static software.amazon.awssdk.services.s3.internal.crossregion.S3CrossRegionRedirectTestBase.CHANGED_CROSS_REGION;
import static software.amazon.awssdk.services.s3.internal.crossregion.S3CrossRegionRedirectTestBase.CROSS_REGION;
import static software.amazon.awssdk.services.s3.internal.crossregion.S3CrossRegionRedirectTestBase.CROSS_REGION_BUCKET;
import static software.amazon.awssdk.services.s3.internal.crossregion.S3CrossRegionRedirectTestBase.OVERRIDE_CONFIGURED_REGION;
import static software.amazon.awssdk.services.s3.internal.crossregion.S3CrossRegionRedirectTestBase.X_AMZ_BUCKET_REGION;
import java.net.URI;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import software.amazon.awssdk.core.ResponseBytes;
import software.amazon.awssdk.core.async.AsyncResponseTransformer;
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.SdkInternalExecutionAttribute;
import software.amazon.awssdk.endpoints.EndpointProvider;
import software.amazon.awssdk.http.AbortableInputStream;
import software.amazon.awssdk.http.HttpExecuteResponse;
import software.amazon.awssdk.http.SdkHttpFullResponse;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.http.SdkHttpResponse;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.S3AsyncClientBuilder;
import software.amazon.awssdk.services.s3.endpoints.internal.DefaultS3EndpointProvider;
import software.amazon.awssdk.services.s3.internal.crossregion.endpointprovider.BucketEndpointProvider;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.services.s3.model.ListObjectsV2Response;
import software.amazon.awssdk.services.s3.model.S3Exception;
import software.amazon.awssdk.services.s3.paginators.ListObjectsV2Publisher;
import software.amazon.awssdk.testutils.service.http.MockAsyncHttpClient;
import software.amazon.awssdk.utils.StringInputStream;
import software.amazon.awssdk.utils.StringUtils;
class S3CrossRegionAsyncClientTest {
private static final String ERROR_RESPONSE_FORMAT = "<Error>\\n\\t<Code>%s</Code>\\n</Error>";
private static final String BUCKET = "bucket";
private static final String KEY = "key";
private static final String TOKEN = "token";
private MockAsyncHttpClient mockAsyncHttpClient;
private CaptureInterceptor captureInterceptor;
private S3AsyncClient s3Client;
@BeforeEach
void setUp() {
mockAsyncHttpClient = new MockAsyncHttpClient();
captureInterceptor = new CaptureInterceptor();
s3Client = clientBuilder().build();
}
private static Stream<Arguments> stubSuccessfulRedirectResponses() {
Consumer<MockAsyncHttpClient> redirectStubConsumer = mockAsyncHttpClient ->
mockAsyncHttpClient.stubResponses(customHttpResponseWithUnknownErrorCode(301, CROSS_REGION.id()), successHttpResponse());
Consumer<MockAsyncHttpClient> successStubConsumer = mockAsyncHttpClient ->
mockAsyncHttpClient.stubResponses(successHttpResponse(), successHttpResponse());
Consumer<MockAsyncHttpClient> malFormerAuthError = mockAsyncHttpClient ->
mockAsyncHttpClient.stubResponses(
customHttpResponse(400, "AuthorizationHeaderMalformed", null),
customHttpResponse(400, "AuthorizationHeaderMalformed", CROSS_REGION_BUCKET),
successHttpResponse());
return Stream.of(
Arguments.of(redirectStubConsumer, BucketEndpointProvider.class, "Redirect Error with region in x-amz-bucket-header"),
Arguments.of(successStubConsumer, DefaultS3EndpointProvider.class, "Success response" ),
Arguments.of(malFormerAuthError, BucketEndpointProvider.class, "Authorization Malformed Error with region in x-amz-bucket-header in Head bucket response" )
);
}
private static Stream<Arguments> stubFailureResponses() {
List<SdkHttpMethod> noregionOnHeadBucketHttpMethodListMethodList = Arrays.asList(SdkHttpMethod.GET, SdkHttpMethod.HEAD);
List<SdkHttpMethod> regionOnHeadBucketHttpMethodList = Arrays.asList(SdkHttpMethod.GET, SdkHttpMethod.HEAD, SdkHttpMethod.GET);
List<String> noRegionOnHeadBucket = Arrays.asList(OVERRIDE_CONFIGURED_REGION.toString(),
OVERRIDE_CONFIGURED_REGION.toString());
List<String> regionOnHeadBucket = Arrays.asList(OVERRIDE_CONFIGURED_REGION.toString(),
OVERRIDE_CONFIGURED_REGION.toString(),
CROSS_REGION.id());
Consumer<MockAsyncHttpClient> redirectFailedWithNoRegionFailure = mockAsyncHttpClient ->
mockAsyncHttpClient.stubResponses(customHttpResponseWithUnknownErrorCode(301, null),
customHttpResponseWithUnknownErrorCode(301, null),
successHttpResponse(), successHttpResponse());
Consumer<MockAsyncHttpClient> authMalformedWithNoRegion = mockAsyncHttpClient ->
mockAsyncHttpClient.stubResponses(customHttpResponse(400, "AuthorizationHeaderMalformed", null),
customHttpResponse(400, "AuthorizationHeaderMalformed", null));
Consumer<MockAsyncHttpClient> authMalformedAuthorizationFailureAfterRegionRetrieval = mockAsyncHttpClient ->
mockAsyncHttpClient.stubResponses(customHttpResponse(400, "AuthorizationHeaderMalformed", null),
customHttpResponse(400, "AuthorizationHeaderMalformed", CROSS_REGION.id()),
customHttpResponse(400, "AuthorizationHeaderMalformed", CROSS_REGION.id()));
return Stream.of(
Arguments.of(redirectFailedWithNoRegionFailure, 301, 2, noRegionOnHeadBucket, noregionOnHeadBucketHttpMethodListMethodList),
Arguments.of(authMalformedWithNoRegion, 400, 2, noRegionOnHeadBucket, noregionOnHeadBucketHttpMethodListMethodList),
Arguments.of(authMalformedAuthorizationFailureAfterRegionRetrieval, 400, 3, regionOnHeadBucket,
regionOnHeadBucketHttpMethodList)
);
}
public static HttpExecuteResponse successHttpResponse() {
return HttpExecuteResponse.builder()
.response(SdkHttpResponse.builder()
.statusCode(200)
.build())
.build();
}
public static HttpExecuteResponse customHttpResponseWithUnknownErrorCode(int statusCode, String bucket_region) {
return customHttpResponse(statusCode, "UnknownError", bucket_region);
}
public static HttpExecuteResponse customHttpResponse(int statusCode, String errorCode, String bucket_region) {
SdkHttpFullResponse.Builder httpResponseBuilder = SdkHttpResponse.builder();
if (StringUtils.isNotBlank(bucket_region)) {
httpResponseBuilder.appendHeader(X_AMZ_BUCKET_REGION, bucket_region);
}
return HttpExecuteResponse.builder()
.response(httpResponseBuilder.statusCode(statusCode).build())
.responseBody(AbortableInputStream.create(new StringInputStream(String.format(ERROR_RESPONSE_FORMAT, errorCode))))
.build();
}
@ParameterizedTest(name = "{index} - {2}.")
@MethodSource("stubSuccessfulRedirectResponses")
void given_CrossRegionClientWithNoOverrideConfig_when_StandardOperationIsPerformed_then_SuccessfullyIntercepts(Consumer<MockAsyncHttpClient> stubConsumer,
Class<?> endpointProviderType,
String testCase) {
stubConsumer.accept(mockAsyncHttpClient);
S3AsyncClient crossRegionClient = new S3CrossRegionAsyncClient(s3Client);
crossRegionClient.getObject(r -> r.bucket(BUCKET).key(KEY), AsyncResponseTransformer.toBytes()).join();
assertThat(captureInterceptor.endpointProvider).isInstanceOf(endpointProviderType);
}
@ParameterizedTest(name = "{index} - {2}.")
@MethodSource("stubSuccessfulRedirectResponses")
void given_CrossRegionClientWithExistingOverrideConfig_when_StandardOperationIsPerformed_then_SuccessfullyIntercepts(Consumer<MockAsyncHttpClient> stubConsumer,
Class<?> endpointProviderType,
String testCase) {
stubConsumer.accept(mockAsyncHttpClient);
S3AsyncClient crossRegionClient = new S3CrossRegionAsyncClient(s3Client);
GetObjectRequest request = GetObjectRequest.builder()
.bucket(BUCKET)
.key(KEY)
.overrideConfiguration(o -> o.putHeader("someheader", "somevalue"))
.build();
crossRegionClient.getObject(request, AsyncResponseTransformer.toBytes()).join();
assertThat(captureInterceptor.endpointProvider).isInstanceOf(endpointProviderType);
assertThat(mockAsyncHttpClient.getLastRequest().headers().get("someheader")).isNotNull();
}
@ParameterizedTest(name = "{index} - {2}.")
@MethodSource("stubSuccessfulRedirectResponses")
void given_CrossRegionClient_when_PaginatedOperationIsPerformed_then_DoesNotIntercept(Consumer<MockAsyncHttpClient> stubConsumer,
Class<?> endpointProviderType,
String testCase) throws Exception {
stubConsumer.accept(mockAsyncHttpClient);
S3AsyncClient crossRegionClient = new S3CrossRegionAsyncClient(s3Client);
ListObjectsV2Publisher publisher =
crossRegionClient.listObjectsV2Paginator(r -> r.bucket(BUCKET).continuationToken(TOKEN).build());
CompletableFuture<Void> future = publisher.subscribe(ListObjectsV2Response::contents);
future.get();
assertThat(captureInterceptor.endpointProvider).isInstanceOf(endpointProviderType);
}
@ParameterizedTest(name = "{index} - {2}.")
@MethodSource("stubSuccessfulRedirectResponses")
void given_CrossRegionClientCreatedWithWrapping_when_OperationIsPerformed_then_SuccessfullyIntercepts(Consumer<MockAsyncHttpClient> stubConsumer,
Class<?> endpointProviderType,
String testCase) {
stubConsumer.accept(mockAsyncHttpClient);
S3AsyncClient crossRegionClient = clientBuilder().crossRegionAccessEnabled(true).build();
crossRegionClient.getObject(r -> r.bucket(BUCKET).key(KEY), AsyncResponseTransformer.toBytes()).join();
assertThat(captureInterceptor.endpointProvider).isInstanceOf(endpointProviderType);
}
@Test
void given_CrossRegionClient_when_CallsHeadObjectWithRegionNameNotPresentInFallbackCall_then_RegionNameExtractedFromHeadBucket() {
mockAsyncHttpClient.reset();
mockAsyncHttpClient.stubResponses(customHttpResponseWithUnknownErrorCode(301, null),
customHttpResponseWithUnknownErrorCode(301, CROSS_REGION.id()),
successHttpResponse(), successHttpResponse());
S3AsyncClient crossRegionClient =
clientBuilder().endpointOverride(null).region(OVERRIDE_CONFIGURED_REGION).crossRegionAccessEnabled(true).build();
crossRegionClient.getObject(r -> r.bucket(BUCKET).key(KEY), AsyncResponseTransformer.toBytes()).join();
assertThat(captureInterceptor.endpointProvider).isInstanceOf(BucketEndpointProvider.class);
List<SdkHttpRequest> requests = mockAsyncHttpClient.getRequests();
assertThat(requests).hasSize(3);
assertThat(requests.stream().map(req -> req.host().substring(10, req.host().length() - 14)).collect(Collectors.toList()))
.isEqualTo(Arrays.asList(OVERRIDE_CONFIGURED_REGION.id(),
OVERRIDE_CONFIGURED_REGION.id(),
CROSS_REGION.id()));
assertThat(requests.stream().map(req -> req.method()).collect(Collectors.toList()))
.isEqualTo(Arrays.asList(SdkHttpMethod.GET,
SdkHttpMethod.HEAD,
SdkHttpMethod.GET));
// Resetting the mock client to capture the new API request for second S3 Call.
mockAsyncHttpClient.reset();
mockAsyncHttpClient.stubResponses(successHttpResponse(), successHttpResponse());
crossRegionClient.getObject(r -> r.bucket(BUCKET).key(KEY), AsyncResponseTransformer.toBytes()).join();
List<SdkHttpRequest> postCacheRequests = mockAsyncHttpClient.getRequests();
assertThat(postCacheRequests.stream()
.map(req -> req.host().substring(10, req.host().length() - 14))
.collect(Collectors.toList()))
.isEqualTo(Collections.singletonList(CROSS_REGION.id()));
assertThat(postCacheRequests.stream().map(req -> req.method()).collect(Collectors.toList()))
.isEqualTo(Collections.singletonList(SdkHttpMethod.GET));
assertThat(captureInterceptor.endpointProvider).isInstanceOf(BucketEndpointProvider.class);
}
@ParameterizedTest(name = "{index} - Status code = {1} with HeadBucket bucket regions {3}.")
@MethodSource("stubFailureResponses")
void given_CrossRegionClient_when_CallsHeadObjectErrors_then_ShouldTerminateTheAPI(
Consumer<MockAsyncHttpClient> stubFailureResponses,
Integer statusCode, Integer numberOfRequests,
List<String> redirectedBuckets,
List<SdkHttpMethod> sdkHttpMethods) {
stubFailureResponses.accept(mockAsyncHttpClient);
S3AsyncClient crossRegionClient =
clientBuilder().endpointOverride(null).region(OVERRIDE_CONFIGURED_REGION)
.crossRegionAccessEnabled(true).build();
String errorMessage = String.format("software.amazon.awssdk.services.s3.model.S3Exception: null "
+ "(Service: S3, Status Code: %d, Request ID: null)"
, statusCode);
assertThatExceptionOfType(CompletionException.class)
.isThrownBy(() -> crossRegionClient.getObject(r -> r.bucket(BUCKET).key(KEY), AsyncResponseTransformer.toBytes()).join())
.withMessageContaining(errorMessage);
List<SdkHttpRequest> requests = mockAsyncHttpClient.getRequests();
assertThat(requests).hasSize(numberOfRequests);
assertThat(requests.stream().map(req -> req.host().substring(10, req.host().length() - 14)).collect(Collectors.toList()))
.isEqualTo(redirectedBuckets);
assertThat(requests.stream().map(req -> req.method()).collect(Collectors.toList()))
.isEqualTo(sdkHttpMethods);
}
@Test
void given_CrossRegionClient_when_CallsHeadObjectWithNoRegion_then_ShouldTerminateHeadBucketAPI() {
mockAsyncHttpClient.stubResponses(customHttpResponseWithUnknownErrorCode(301, null),
customHttpResponseWithUnknownErrorCode(301, null),
successHttpResponse(), successHttpResponse());
S3AsyncClient crossRegionClient =
clientBuilder().endpointOverride(null).region(OVERRIDE_CONFIGURED_REGION)
.crossRegionAccessEnabled(true).build();
assertThatExceptionOfType(CompletionException.class)
.isThrownBy(() -> crossRegionClient.getObject(r -> r.bucket(BUCKET).key(KEY), AsyncResponseTransformer.toBytes()).join())
.withMessageContaining("software.amazon.awssdk.services.s3.model.S3Exception: null (Service: S3, Status Code: 301, "
+ "Request ID: null)")
.withCauseInstanceOf(S3Exception.class).withRootCauseExactlyInstanceOf(S3Exception.class);
List<SdkHttpRequest> requests = mockAsyncHttpClient.getRequests();
assertThat(requests).hasSize(2);
assertThat(requests.stream().map(req -> req.host().substring(10, req.host().length() - 14)).collect(Collectors.toList()))
.isEqualTo(Arrays.asList(OVERRIDE_CONFIGURED_REGION.toString(),
OVERRIDE_CONFIGURED_REGION.toString()));
assertThat(requests.stream().map(req -> req.method()).collect(Collectors.toList()))
.isEqualTo(Arrays.asList(SdkHttpMethod.GET,
SdkHttpMethod.HEAD));
}
@Test
void given_CrossRegionClient_when_FutureIsCancelled_then_ShouldCancelTheThread() {
mockAsyncHttpClient.reset();
mockAsyncHttpClient.stubResponses(customHttpResponseWithUnknownErrorCode(301, null),
customHttpResponseWithUnknownErrorCode(301, CROSS_REGION.id()),
successHttpResponse(), successHttpResponse());
S3AsyncClient crossRegionClient =
clientBuilder().endpointOverride(null).region(OVERRIDE_CONFIGURED_REGION).crossRegionAccessEnabled(true).build();
CompletableFuture<ResponseBytes<GetObjectResponse>> completableFuture =
crossRegionClient.getObject(r -> r.bucket(BUCKET).key(KEY), AsyncResponseTransformer.toBytes());
completableFuture.cancel(true);
assertThat(completableFuture.isCancelled()).isTrue();
}
@Test
void given_CrossRegionClient_when_RedirectsAfterCaching_then_ExpectedBehaviorOccurs() {
mockAsyncHttpClient.stubResponses(customHttpResponseWithUnknownErrorCode(301, CROSS_REGION.id()),
successHttpResponse(),
successHttpResponse(),
customHttpResponseWithUnknownErrorCode(301, CHANGED_CROSS_REGION.id()),
successHttpResponse());
S3AsyncClient crossRegionClient =
clientBuilder().endpointOverride(null).region(OVERRIDE_CONFIGURED_REGION).crossRegionAccessEnabled(true).build();
crossRegionClient.getObject(r -> r.bucket(BUCKET).key(KEY), AsyncResponseTransformer.toBytes()).join();
crossRegionClient.getObject(r -> r.bucket(BUCKET).key(KEY), AsyncResponseTransformer.toBytes()).join();
crossRegionClient.getObject(r -> r.bucket(BUCKET).key(KEY), AsyncResponseTransformer.toBytes()).join();
assertThat(captureInterceptor.endpointProvider).isInstanceOf(BucketEndpointProvider.class);
List<SdkHttpRequest> requests = mockAsyncHttpClient.getRequests();
assertThat(requests).hasSize(5);
assertThat(requests.stream().map(req -> req.host().substring(10, req.host().length() - 14)).collect(Collectors.toList()))
.isEqualTo(Arrays.asList(OVERRIDE_CONFIGURED_REGION.toString(),
CROSS_REGION.toString(),
CROSS_REGION.toString(),
CROSS_REGION.toString(),
CHANGED_CROSS_REGION.toString()));
assertThat(requests.stream().map(req -> req.method()).collect(Collectors.toList()))
.isEqualTo(Arrays.asList(SdkHttpMethod.GET, SdkHttpMethod.GET, SdkHttpMethod.GET, SdkHttpMethod.GET,
SdkHttpMethod.GET));
}
@Test
void given_CrossRegionClient_when_RedirectsAfterCaching_withFallbackRedirectWithNoRegion_then_RetriedCallWithRegionSucceeds() {
mockAsyncHttpClient.stubResponses(customHttpResponseWithUnknownErrorCode(301, null),
customHttpResponseWithUnknownErrorCode(301, CROSS_REGION.id()),
successHttpResponse(),
successHttpResponse(),
customHttpResponseWithUnknownErrorCode(301, null),
customHttpResponseWithUnknownErrorCode(301, CHANGED_CROSS_REGION.id()),
successHttpResponse());
S3AsyncClient crossRegionClient =
clientBuilder().endpointOverride(null).region(OVERRIDE_CONFIGURED_REGION).crossRegionAccessEnabled(true).build();
crossRegionClient.getObject(r -> r.bucket(BUCKET).key(KEY), AsyncResponseTransformer.toBytes()).join();
crossRegionClient.getObject(r -> r.bucket(BUCKET).key(KEY), AsyncResponseTransformer.toBytes()).join();
crossRegionClient.getObject(r -> r.bucket(BUCKET).key(KEY), AsyncResponseTransformer.toBytes()).join();
assertThat(captureInterceptor.endpointProvider).isInstanceOf(BucketEndpointProvider.class);
List<SdkHttpRequest> requests = mockAsyncHttpClient.getRequests();
assertThat(requests).hasSize(7);
assertThat(requests.stream().map(req -> req.host().substring(10, req.host().length() - 14)).collect(Collectors.toList()))
.isEqualTo(Arrays.asList(
OVERRIDE_CONFIGURED_REGION.toString(), OVERRIDE_CONFIGURED_REGION.toString(), CROSS_REGION.toString(),
CROSS_REGION.toString(),
CROSS_REGION.toString(), OVERRIDE_CONFIGURED_REGION.toString(),
CHANGED_CROSS_REGION.toString()));
assertThat(requests.stream().map(req -> req.method()).collect(Collectors.toList()))
.isEqualTo(Arrays.asList(SdkHttpMethod.GET, SdkHttpMethod.HEAD, SdkHttpMethod.GET,
SdkHttpMethod.GET,
SdkHttpMethod.GET, SdkHttpMethod.HEAD, SdkHttpMethod.GET));
}
@Test
void given_CrossRegionClient_when_StandardOperation_then_ContainsUserAgent() {
mockAsyncHttpClient.stubResponses(successHttpResponse());
S3AsyncClient crossRegionClient = clientBuilder().crossRegionAccessEnabled(true).build();
crossRegionClient.getObject(r -> r.bucket(BUCKET).key(KEY), AsyncResponseTransformer.toBytes()).join();
assertThat(mockAsyncHttpClient.getLastRequest().firstMatchingHeader("User-Agent").get()).contains("hll/cross-region");
}
@ParameterizedTest(name = "{index} - {2}.")
@MethodSource("stubSuccessfulRedirectResponses")
void given_CrossRegionAccessEnabled_when_SuccessfulResponse_then_EndpointIsUpdated(Consumer<MockAsyncHttpClient> stubConsumer,
Class<?> endpointProviderType,
String testCase) {
stubConsumer.accept(mockAsyncHttpClient);
S3AsyncClient crossRegionClient = clientBuilder().crossRegionAccessEnabled(true).build();
crossRegionClient.getObject(r -> r.bucket(BUCKET).key(KEY), AsyncResponseTransformer.toBytes()).join();
assertThat(captureInterceptor.endpointProvider).isInstanceOf(endpointProviderType);
}
@Test
void given_SimpleClient_when_StandardOperation_then_DoesNotContainCrossRegionUserAgent() {
mockAsyncHttpClient.stubResponses(successHttpResponse());
S3AsyncClient crossRegionClient = clientBuilder().crossRegionAccessEnabled(false).build();
crossRegionClient.getObject(r -> r.bucket(BUCKET).key(KEY), AsyncResponseTransformer.toBytes()).join();
assertThat(mockAsyncHttpClient.getLastRequest().firstMatchingHeader("User-Agent").get()).doesNotContain("hll/cross");
}
private S3AsyncClientBuilder clientBuilder() {
return S3AsyncClient.builder()
.httpClient(mockAsyncHttpClient)
.endpointOverride(URI.create("http://localhost"))
.overrideConfiguration(c -> c.addExecutionInterceptor(captureInterceptor));
}
private static final class CaptureInterceptor implements ExecutionInterceptor {
private EndpointProvider endpointProvider;
@Override
public void beforeMarshalling(Context.BeforeMarshalling context, ExecutionAttributes executionAttributes) {
endpointProvider = executionAttributes.getAttribute(SdkInternalExecutionAttribute.ENDPOINT_PROVIDER);
}
}
}
| 4,448 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal/crossregion/S3CrossRegionAsyncClientRedirectTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.s3.internal.crossregion;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.function.Consumer;
import org.junit.jupiter.api.BeforeEach;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.model.HeadBucketRequest;
import software.amazon.awssdk.services.s3.model.ListBucketsRequest;
import software.amazon.awssdk.services.s3.model.ListBucketsResponse;
import software.amazon.awssdk.services.s3.model.ListObjectsRequest;
import software.amazon.awssdk.services.s3.model.ListObjectsResponse;
import software.amazon.awssdk.services.s3.model.S3Exception;
import software.amazon.awssdk.utils.CompletableFutureUtils;
public class S3CrossRegionAsyncClientRedirectTest extends S3CrossRegionRedirectTestBase {
private static S3AsyncClient mockDelegateAsyncClient;
private S3AsyncClient decoratedS3AsyncClient;
@BeforeEach
public void setup() {
mockDelegateAsyncClient = Mockito.mock(S3AsyncClient.class);
decoratedS3AsyncClient = new S3CrossRegionAsyncClient(mockDelegateAsyncClient);
}
@Override
protected void stubRedirectSuccessSuccess(Integer redirect) {
when(mockDelegateAsyncClient.listObjects(any(ListObjectsRequest.class)))
.thenReturn(CompletableFutureUtils.failedFuture(new CompletionException(redirectException(redirect, CROSS_REGION.id(),
null, null))))
.thenReturn(CompletableFuture.completedFuture(ListObjectsResponse.builder().contents(S3_OBJECTS).build()))
.thenReturn(CompletableFuture.completedFuture(ListObjectsResponse.builder().contents(S3_OBJECTS).build()));
}
@Override
protected ListObjectsResponse apiCallToService() throws Throwable {
try{
return decoratedS3AsyncClient.listObjects(i -> i.bucket(CROSS_REGION_BUCKET)).join();
}catch (CompletionException exception){
throw exception.getCause();
}
}
@Override
protected void verifyTheApiServiceCall(int times, ArgumentCaptor<ListObjectsRequest> requestArgumentCaptor) {
verify(mockDelegateAsyncClient, times(times)).listObjects(requestArgumentCaptor.capture());
}
@Override
protected void stubServiceClientConfiguration() {
when(mockDelegateAsyncClient.serviceClientConfiguration()).thenReturn(CONFIGURED_ENDPOINT_PROVIDER);
}
@Override
protected void stubClientAPICallWithFirstRedirectThenSuccessWithRegionInErrorResponse(Integer redirect) {
when(mockDelegateAsyncClient.listObjects(any(ListObjectsRequest.class)))
.thenReturn(CompletableFutureUtils.failedFuture(new CompletionException(redirectException(redirect, CROSS_REGION.id(), null, null))))
.thenReturn(CompletableFuture.completedFuture(ListObjectsResponse.builder().contents(S3_OBJECTS).build()
));
}
@Override
protected void verifyNoBucketApiCall(int times, ArgumentCaptor<ListBucketsRequest> requestArgumentCaptor) {
verify(mockDelegateAsyncClient, times(times)).listBuckets(requestArgumentCaptor.capture());
}
@Override
protected ListBucketsResponse noBucketCallToService() throws Throwable {
return decoratedS3AsyncClient.listBuckets(ListBucketsRequest.builder().build()).join();
}
@Override
protected void stubApiWithNoBucketField() {
when(mockDelegateAsyncClient.listBuckets(any(ListBucketsRequest.class)))
.thenReturn(CompletableFutureUtils.failedFuture(new CompletionException(redirectException(301, CROSS_REGION.id(), null,
"Redirect"))))
.thenReturn(CompletableFuture.completedFuture(ListBucketsResponse.builder().build()
));
}
@Override
protected void stubHeadBucketRedirect() {
when(mockDelegateAsyncClient.headBucket(any(HeadBucketRequest.class)))
.thenReturn(CompletableFutureUtils.failedFuture(new CompletionException(redirectException(301,CROSS_REGION.id(), null, null))));
when(mockDelegateAsyncClient.headBucket(any(Consumer.class)))
.thenReturn(CompletableFutureUtils.failedFuture(new CompletionException(redirectException(301,CROSS_REGION.id(), null, null))));
}
@Override
protected void stubRedirectWithNoRegionAndThenSuccess(Integer redirect) {
when(mockDelegateAsyncClient.listObjects(any(ListObjectsRequest.class)))
.thenReturn(CompletableFutureUtils.failedFuture(new CompletionException(redirectException(redirect, null, null, null))))
.thenReturn(CompletableFuture.completedFuture(ListObjectsResponse.builder().contents(S3_OBJECTS).build()))
.thenReturn(CompletableFuture.completedFuture(ListObjectsResponse.builder().contents(S3_OBJECTS).build()));
}
@Override
protected void stubRedirectThenError(Integer redirect) {
when(mockDelegateAsyncClient.listObjects(any(ListObjectsRequest.class)))
.thenReturn(CompletableFutureUtils.failedFuture(new CompletionException(redirectException(redirect, CROSS_REGION.id(), null,
null))))
.thenReturn(CompletableFutureUtils.failedFuture(new CompletionException(redirectException(400, null,
"InvalidArgument", "Invalid id"))));
}
@Override
protected void verifyHeadBucketServiceCall(int times) {
verify(mockDelegateAsyncClient, times(times)).headBucket(any(Consumer.class));
}
@Override
protected void stubApiWithAuthorizationHeaderMalformedError() {
when(mockDelegateAsyncClient.listObjects(any(ListObjectsRequest.class)))
.thenReturn(CompletableFutureUtils.failedFuture(
new CompletionException(redirectException(400, null, "AuthorizationHeaderMalformed", null))))
.thenReturn(CompletableFuture.completedFuture(ListObjectsResponse.builder().contents(S3_OBJECTS).build()));
}
@Override
protected void stubApiWithAuthorizationHeaderWithInternalSoftwareError() {
when(mockDelegateAsyncClient.headBucket(any(HeadBucketRequest.class)))
.thenReturn(CompletableFutureUtils.failedFuture(
new CompletionException(redirectException(500,null, "InternalError", null))));
when(mockDelegateAsyncClient.headBucket(any(Consumer.class)))
.thenReturn(CompletableFutureUtils.failedFuture(new CompletionException(redirectException(500,null,
"InternalError", null))));
}
@Override
protected void stubHeadBucketRedirectWithAuthorizationHeaderMalformed() {
when(mockDelegateAsyncClient.headBucket(any(HeadBucketRequest.class)))
.thenReturn(CompletableFutureUtils.failedFuture(
new CompletionException(redirectException(400,CROSS_REGION.id(), "AuthorizationHeaderMalformed", null))));
when(mockDelegateAsyncClient.headBucket(any(Consumer.class)))
.thenReturn(CompletableFutureUtils.failedFuture(
new CompletionException(redirectException(400,CROSS_REGION.id(), "AuthorizationHeaderMalformed", null))));
}
@Override
protected void verifyNoBucketCall() {
assertThatExceptionOfType(CompletionException.class)
.isThrownBy(
() -> noBucketCallToService())
.withCauseInstanceOf(S3Exception.class)
.withMessage("software.amazon.awssdk.services.s3.model.S3Exception: Redirect (Service: S3, Status Code: 301, Request ID: 1, Extended Request ID: A1)");
}
}
| 4,449 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal/crossregion/TestEndpointProvider.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.s3.internal.crossregion;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.endpoints.Endpoint;
import software.amazon.awssdk.services.s3.endpoints.S3EndpointParams;
import software.amazon.awssdk.services.s3.endpoints.S3EndpointProvider;
public class TestEndpointProvider implements S3EndpointProvider {
S3EndpointProvider s3EndpointProvider = S3EndpointProvider.defaultProvider();
@Override
public CompletableFuture<Endpoint> resolveEndpoint(S3EndpointParams endpointParams) {
return s3EndpointProvider.resolveEndpoint(endpointParams.copy(c -> c.bucket("test_prefix_"+endpointParams.bucket())));
}
} | 4,450 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/internal/crossregion/S3CrossRegionSyncClientTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.s3.internal.crossregion;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static software.amazon.awssdk.services.s3.internal.crossregion.S3CrossRegionAsyncClientTest.customHttpResponse;
import static software.amazon.awssdk.services.s3.internal.crossregion.S3CrossRegionAsyncClientTest.customHttpResponseWithUnknownErrorCode;
import static software.amazon.awssdk.services.s3.internal.crossregion.S3CrossRegionAsyncClientTest.successHttpResponse;
import static software.amazon.awssdk.services.s3.internal.crossregion.S3CrossRegionRedirectTestBase.CHANGED_CROSS_REGION;
import static software.amazon.awssdk.services.s3.internal.crossregion.S3CrossRegionRedirectTestBase.CROSS_REGION;
import static software.amazon.awssdk.services.s3.internal.crossregion.S3CrossRegionRedirectTestBase.CROSS_REGION_BUCKET;
import static software.amazon.awssdk.services.s3.internal.crossregion.S3CrossRegionRedirectTestBase.OVERRIDE_CONFIGURED_REGION;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import 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.SdkInternalExecutionAttribute;
import software.amazon.awssdk.endpoints.EndpointProvider;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.S3ClientBuilder;
import software.amazon.awssdk.services.s3.endpoints.internal.DefaultS3EndpointProvider;
import software.amazon.awssdk.services.s3.internal.crossregion.endpointprovider.BucketEndpointProvider;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.ListObjectsV2Response;
import software.amazon.awssdk.services.s3.model.S3Exception;
import software.amazon.awssdk.services.s3.paginators.ListObjectsV2Iterable;
import software.amazon.awssdk.testutils.service.http.MockSyncHttpClient;
class S3CrossRegionSyncClientTest {
private static final String BUCKET = "bucket";
private static final String KEY = "key";
private static final String TOKEN = "token";
private MockSyncHttpClient mockSyncHttpClient ;
private CaptureInterceptor captureInterceptor;
private S3Client defaultS3Client;
@BeforeEach
void setUp() {
mockSyncHttpClient = new MockSyncHttpClient();
captureInterceptor = new CaptureInterceptor();
defaultS3Client = clientBuilder().build();
}
private static Stream<Arguments> stubSuccessfulRedirectResponses() {
Consumer<MockSyncHttpClient> redirectStubConsumer = mockSyncHttpClient ->
mockSyncHttpClient.stubResponses(customHttpResponseWithUnknownErrorCode(301, CROSS_REGION.id()), successHttpResponse());
Consumer<MockSyncHttpClient> successStubConsumer = mockSyncHttpClient ->
mockSyncHttpClient.stubResponses(successHttpResponse(), successHttpResponse());
Consumer<MockSyncHttpClient> malFormerAuthError = mockSyncHttpClient ->
mockSyncHttpClient.stubResponses(
customHttpResponse(400, "AuthorizationHeaderMalformed",null ),
customHttpResponse(400, "AuthorizationHeaderMalformed",CROSS_REGION_BUCKET ),
successHttpResponse());
return Stream.of(
Arguments.of(redirectStubConsumer,
BucketEndpointProvider.class,
"Redirect Error with region in x-amz-bucket-header"),
Arguments.of(successStubConsumer,
DefaultS3EndpointProvider.class,
"Success response" ),
Arguments.of(malFormerAuthError,
BucketEndpointProvider.class,
"Authorization Malformed Error with region in x-amz-bucket-header in Head bucket response" )
);
}
public static Stream<Arguments> stubFailureResponses() {
List<SdkHttpMethod> noregionOnHeadBucketHttpMethodListMethodList = Arrays.asList(SdkHttpMethod.GET, SdkHttpMethod.HEAD);
List<SdkHttpMethod> regionOnHeadBucketHttpMethodList = Arrays.asList(SdkHttpMethod.GET, SdkHttpMethod.HEAD, SdkHttpMethod.GET);
List<String> noRegionOnHeadBucket = Arrays.asList(OVERRIDE_CONFIGURED_REGION.toString(),
OVERRIDE_CONFIGURED_REGION.toString());
List<String> regionOnHeadBucket = Arrays.asList(OVERRIDE_CONFIGURED_REGION.toString(),
OVERRIDE_CONFIGURED_REGION.toString(),
CROSS_REGION.id());
Consumer<MockSyncHttpClient> redirectFailedWithNoRegionFailure = mockSyncHttpClient ->
mockSyncHttpClient.stubResponses(customHttpResponseWithUnknownErrorCode(301, null),
customHttpResponseWithUnknownErrorCode(301, null),
successHttpResponse(), successHttpResponse());
Consumer<MockSyncHttpClient> authMalformedWithNoRegion = mockSyncHttpClient ->
mockSyncHttpClient.stubResponses(customHttpResponse(400, "AuthorizationHeaderMalformed", null),
customHttpResponse(400, "AuthorizationHeaderMalformed", null));
Consumer<MockSyncHttpClient> authMalformedAuthorizationFailureAfterRegionRetrieval = mockSyncHttpClient ->
mockSyncHttpClient.stubResponses(customHttpResponse(400, "AuthorizationHeaderMalformed", null),
customHttpResponse(400, "AuthorizationHeaderMalformed", CROSS_REGION.id()),
customHttpResponse(400, "AuthorizationHeaderMalformed", CROSS_REGION.id()));
return Stream.of(
Arguments.of(redirectFailedWithNoRegionFailure,
301,
2,
noRegionOnHeadBucket,
noregionOnHeadBucketHttpMethodListMethodList
),
Arguments.of(authMalformedWithNoRegion,
400,
2,
noRegionOnHeadBucket,
noregionOnHeadBucketHttpMethodListMethodList
),
Arguments.of(authMalformedAuthorizationFailureAfterRegionRetrieval,
400,
3,
regionOnHeadBucket,
regionOnHeadBucketHttpMethodList
)
);
}
private static Stream<Arguments> stubOverriddenEndpointProviderResponses() {
Consumer<MockSyncHttpClient> redirectStubConsumer = mockSyncHttpClient ->
mockSyncHttpClient.stubResponses(customHttpResponseWithUnknownErrorCode(301, CROSS_REGION.id()), successHttpResponse());
Consumer<MockSyncHttpClient> successStubConsumer = mockSyncHttpClient ->
mockSyncHttpClient.stubResponses(successHttpResponse(), successHttpResponse());
return Stream.of(
Arguments.of(redirectStubConsumer, BucketEndpointProvider.class, CROSS_REGION,
"Redirect error with Region in x-amz-bucket-region header"),
Arguments.of(successStubConsumer, TestEndpointProvider.class, OVERRIDE_CONFIGURED_REGION,
"Success response.")
);
}
@ParameterizedTest(name = "{index} - {2}.")
@MethodSource("stubSuccessfulRedirectResponses")
void given_CrossRegionClientWithNoOverrideConfig_when_StandardOperationIsPerformed_then_SuccessfullyIntercepts(
Consumer<MockSyncHttpClient> stubConsumer,
Class<?> endpointProviderType,
String testCaseName) {
stubConsumer.accept(mockSyncHttpClient);
S3Client crossRegionClient = new S3CrossRegionSyncClient(defaultS3Client);
crossRegionClient.getObject(r -> r.bucket(BUCKET).key(KEY));
assertThat(captureInterceptor.endpointProvider).isInstanceOf(endpointProviderType);
}
@ParameterizedTest(name = "{index} - {2}.")
@MethodSource("stubSuccessfulRedirectResponses")
void given_CrossRegionClientWithExistingOverrideConfig_when_StandardOperationIsPerformed_then_SuccessfullyIntercepts(
Consumer<MockSyncHttpClient> stubConsumer,
Class<?> endpointProviderType,
String testCaseName) {
stubConsumer.accept(mockSyncHttpClient);
S3Client crossRegionClient = new S3CrossRegionSyncClient(defaultS3Client);
GetObjectRequest request = GetObjectRequest.builder()
.bucket(BUCKET)
.key(KEY)
.overrideConfiguration(o -> o.putHeader("someheader", "somevalue"))
.build();
crossRegionClient.getObject(request);
assertThat(captureInterceptor.endpointProvider).isInstanceOf(endpointProviderType);
assertThat(mockSyncHttpClient.getLastRequest().headers().get("someheader")).isNotNull();
}
@ParameterizedTest(name = "{index} - {2}.")
@MethodSource("stubSuccessfulRedirectResponses")
void given_CrossRegionClient_when_PaginatedOperationIsPerformed_then_DoesNotIntercept(Consumer<MockSyncHttpClient> stubConsumer,
Class<?> endpointProviderType,
String testCaseName) {
stubConsumer.accept(mockSyncHttpClient);
S3Client crossRegionClient = new S3CrossRegionSyncClient(defaultS3Client);
ListObjectsV2Iterable iterable =
crossRegionClient.listObjectsV2Paginator(r -> r.bucket(BUCKET).continuationToken(TOKEN).build());
iterable.forEach(ListObjectsV2Response::contents);
assertThat(captureInterceptor.endpointProvider).isInstanceOf(endpointProviderType);
}
@ParameterizedTest(name = "{index} - {2}.")
@MethodSource("stubSuccessfulRedirectResponses")
void given_CrossRegionClientCreatedWithWrapping_when_OperationIsPerformed_then_SuccessfullyIntercepts(Consumer<MockSyncHttpClient> stubConsumer,
Class<?> endpointProviderType,
String testCaseName) {
stubConsumer.accept(mockSyncHttpClient);
S3Client crossRegionClient = clientBuilder().crossRegionAccessEnabled(true).build();
crossRegionClient.getObject(r -> r.bucket(BUCKET).key(KEY));
assertThat(captureInterceptor.endpointProvider).isInstanceOf(endpointProviderType);
}
@ParameterizedTest(name = "{index} - {3}.")
@MethodSource("stubOverriddenEndpointProviderResponses")
void given_CrossRegionClientWithCustomEndpointProvider_when_StandardOperationIsPerformed_then_UsesCustomEndpoint(Consumer<MockSyncHttpClient> stubConsumer,
Class<?> endpointProviderType,
Region region,
String testCaseName) {
stubConsumer.accept(mockSyncHttpClient);
S3Client crossRegionClient = clientBuilder().crossRegionAccessEnabled(true)
.endpointProvider(new TestEndpointProvider())
.region(OVERRIDE_CONFIGURED_REGION)
.build();
GetObjectRequest request = GetObjectRequest.builder()
.bucket(BUCKET)
.key(KEY)
.overrideConfiguration(o -> o.putHeader("someheader", "somevalue")
.endpointProvider(new TestEndpointProvider()))
.build();
crossRegionClient.getObject(request);
assertThat(captureInterceptor.endpointProvider).isInstanceOf(endpointProviderType);
assertThat(mockSyncHttpClient.getLastRequest().headers().get("someheader")).isNotNull();
assertThat(mockSyncHttpClient.getLastRequest().encodedPath()).contains("test_prefix_");
assertThat(mockSyncHttpClient.getLastRequest().host()).contains(region.id());
}
@ParameterizedTest(name = "{index} - {3}.")
@MethodSource("stubOverriddenEndpointProviderResponses")
void given_CrossRegionClientWithCustomEndpointProvider_when_StandardOperationIsPerformed_then_UsesCustomEndpointInClient(Consumer<MockSyncHttpClient> stubConsumer,
Class<?> endpointProviderType,
Region region,
String testCaseName) {
stubConsumer.accept(mockSyncHttpClient);
S3Client crossRegionClient = clientBuilder().crossRegionAccessEnabled(true)
.endpointProvider(new TestEndpointProvider())
.region(OVERRIDE_CONFIGURED_REGION)
.build();
GetObjectRequest request = GetObjectRequest.builder()
.bucket(BUCKET)
.key(KEY)
.overrideConfiguration(o -> o.putHeader("someheader", "somevalue"))
.build();
crossRegionClient.getObject(request);
assertThat(captureInterceptor.endpointProvider).isInstanceOf(endpointProviderType);
assertThat(mockSyncHttpClient.getLastRequest().headers().get("someheader")).isNotNull();
assertThat(mockSyncHttpClient.getLastRequest().encodedPath()).contains("test_prefix_");
assertThat(mockSyncHttpClient.getLastRequest().host()).contains(region.id());
}
@Test
void given_CrossRegionClientWithFallbackCall_when_RegionNameNotPresent_then_CallsHeadObject() {
mockSyncHttpClient.stubResponses(customHttpResponseWithUnknownErrorCode(301, null ),
customHttpResponseWithUnknownErrorCode(301, CROSS_REGION.id() ),
successHttpResponse(), successHttpResponse());
S3Client crossRegionClient =
clientBuilder().endpointOverride(null).region(OVERRIDE_CONFIGURED_REGION).crossRegionAccessEnabled(true).build();
crossRegionClient.getObject(r -> r.bucket(BUCKET).key(KEY));
assertThat(captureInterceptor.endpointProvider).isInstanceOf(BucketEndpointProvider.class);
List<SdkHttpRequest> requests = mockSyncHttpClient.getRequests();
assertThat(requests).hasSize(3);
assertThat(requests.stream().map(req -> req.host().substring(10,req.host().length() - 14 )).collect(Collectors.toList()))
.isEqualTo(Arrays.asList(OVERRIDE_CONFIGURED_REGION.toString(),
OVERRIDE_CONFIGURED_REGION.toString(),
CROSS_REGION.id()));
assertThat(requests.stream().map(req -> req.method()).collect(Collectors.toList()))
.isEqualTo(Arrays.asList(SdkHttpMethod.GET,
SdkHttpMethod.HEAD,
SdkHttpMethod.GET));
// Resetting the mock client to capture the new API request for second S3 Call.
mockSyncHttpClient.reset();
mockSyncHttpClient.stubResponses(successHttpResponse(), successHttpResponse());
crossRegionClient.getObject(r -> r.bucket(BUCKET).key(KEY));
List<SdkHttpRequest> postCacheRequests = mockSyncHttpClient.getRequests();
assertThat(postCacheRequests.stream()
.map(req -> req.host().substring(10,req.host().length() - 14 ))
.collect(Collectors.toList()))
.isEqualTo(Arrays.asList(CROSS_REGION.id()));
assertThat(postCacheRequests.stream().map(req -> req.method()).collect(Collectors.toList()))
.isEqualTo(Arrays.asList(SdkHttpMethod.GET));
assertThat(captureInterceptor.endpointProvider).isInstanceOf(BucketEndpointProvider.class);
}
@Test
void given_crossRegionClient_when_redirectError_then_redirectsAfterCaching() {
mockSyncHttpClient.stubResponses(customHttpResponseWithUnknownErrorCode(301, CROSS_REGION.id()),
successHttpResponse(),
successHttpResponse(),
customHttpResponseWithUnknownErrorCode(301, CHANGED_CROSS_REGION.id()),
successHttpResponse());
S3Client crossRegionClient =
clientBuilder().endpointOverride(null).region(OVERRIDE_CONFIGURED_REGION).crossRegionAccessEnabled(true).build();
crossRegionClient.getObject(r -> r.bucket(BUCKET).key(KEY));
crossRegionClient.getObject(r -> r.bucket(BUCKET).key(KEY));
crossRegionClient.getObject(r -> r.bucket(BUCKET).key(KEY));
assertThat(captureInterceptor.endpointProvider).isInstanceOf(BucketEndpointProvider.class);
List<SdkHttpRequest> requests = mockSyncHttpClient.getRequests();
assertThat(requests).hasSize(5);
assertThat(requests.stream().map(req -> req.host().substring(10,req.host().length() - 14 )).collect(Collectors.toList()))
.isEqualTo(Arrays.asList(OVERRIDE_CONFIGURED_REGION.toString(),
CROSS_REGION.toString(),
CROSS_REGION.toString(),
CROSS_REGION.toString(),
CHANGED_CROSS_REGION.toString()));
assertThat(requests.stream().map(req -> req.method()).collect(Collectors.toList()))
.isEqualTo(Arrays.asList(SdkHttpMethod.GET,SdkHttpMethod.GET,SdkHttpMethod.GET,SdkHttpMethod.GET,SdkHttpMethod.GET));
}
@Test
void given_CrossRegionClient_when_noRegionInHeader_thenFallBackToRegionInHeadBucket() {
mockSyncHttpClient.stubResponses(customHttpResponseWithUnknownErrorCode(301, null ),
customHttpResponseWithUnknownErrorCode(301, CROSS_REGION.id() ),
successHttpResponse(),
successHttpResponse(),
customHttpResponseWithUnknownErrorCode(301, null),
customHttpResponseWithUnknownErrorCode(301, CHANGED_CROSS_REGION.id()),
successHttpResponse());
S3Client crossRegionClient =
clientBuilder().endpointOverride(null).region(OVERRIDE_CONFIGURED_REGION).crossRegionAccessEnabled(true).build();
crossRegionClient.getObject(r -> r.bucket(BUCKET).key(KEY));
crossRegionClient.getObject(r -> r.bucket(BUCKET).key(KEY));
crossRegionClient.getObject(r -> r.bucket(BUCKET).key(KEY));
assertThat(captureInterceptor.endpointProvider).isInstanceOf(BucketEndpointProvider.class);
List<SdkHttpRequest> requests = mockSyncHttpClient.getRequests();
assertThat(requests).hasSize(7);
assertThat(requests.stream().map(req -> req.host().substring(10,req.host().length() - 14 )).collect(Collectors.toList()))
.isEqualTo(Arrays.asList(
OVERRIDE_CONFIGURED_REGION.toString(), OVERRIDE_CONFIGURED_REGION.toString(), CROSS_REGION.toString(),
CROSS_REGION.toString(),
CROSS_REGION.toString(), OVERRIDE_CONFIGURED_REGION.toString(),
CHANGED_CROSS_REGION.toString()));
assertThat(requests.stream().map(req -> req.method()).collect(Collectors.toList()))
.isEqualTo(Arrays.asList(SdkHttpMethod.GET, SdkHttpMethod.HEAD, SdkHttpMethod.GET,
SdkHttpMethod.GET,
SdkHttpMethod.GET, SdkHttpMethod.HEAD, SdkHttpMethod.GET));
}
@ParameterizedTest(name = "{index} - Status code = {1} with HeadBucket bucket regions {3}.")
@MethodSource("stubFailureResponses")
void given_CrossRegionClient_when_CallsHeadObjectErrors_then_ShouldTerminateTheAPI(
Consumer<MockSyncHttpClient> stubFailureResponses,
Integer statusCode, Integer numberOfRequests,
List<String> redirectedBucketRegions,
List<SdkHttpMethod> sdkHttpMethods) {
stubFailureResponses.accept(mockSyncHttpClient);
S3Client crossRegionClient =
clientBuilder().endpointOverride(null).region(OVERRIDE_CONFIGURED_REGION).crossRegionAccessEnabled(true).build();
String description = String.format("Status Code: %d", statusCode);
assertThatExceptionOfType(S3Exception.class)
.isThrownBy(() -> crossRegionClient.getObject(r -> r.bucket(BUCKET).key(KEY)))
.withMessageContaining(description);
List<SdkHttpRequest> requests = mockSyncHttpClient.getRequests();
assertThat(requests).hasSize(numberOfRequests);
assertThat(requests.stream().map(req -> req.host().substring(10,req.host().length() - 14 )).collect(Collectors.toList()))
.isEqualTo(redirectedBucketRegions);
assertThat(requests.stream().map(req -> req.method()).collect(Collectors.toList()))
.isEqualTo(sdkHttpMethods);
}
@Test
void given_CrossRegionClient_when_CallsHeadObjectWithNoRegion_then_ShouldTerminateHeadBucketAPI() {
mockSyncHttpClient.stubResponses(customHttpResponseWithUnknownErrorCode(301, null ),
customHttpResponseWithUnknownErrorCode(301, null ),
successHttpResponse(), successHttpResponse());
S3Client crossRegionClient =
clientBuilder().endpointOverride(null).region(OVERRIDE_CONFIGURED_REGION).crossRegionAccessEnabled(true).build();
assertThatExceptionOfType(S3Exception.class)
.isThrownBy(() -> crossRegionClient.getObject(r -> r.bucket(BUCKET).key(KEY)))
.withMessageContaining("Status Code: 301");
List<SdkHttpRequest> requests = mockSyncHttpClient.getRequests();
assertThat(requests).hasSize(2);
assertThat(requests.stream().map(req -> req.host().substring(10,req.host().length() - 14 )).collect(Collectors.toList()))
.isEqualTo(Arrays.asList(OVERRIDE_CONFIGURED_REGION.toString(),
OVERRIDE_CONFIGURED_REGION.toString()));
assertThat(requests.stream().map(req -> req.method()).collect(Collectors.toList()))
.isEqualTo(Arrays.asList(SdkHttpMethod.GET,
SdkHttpMethod.HEAD));
}
@Test
void given_CrossRegionClient_when_StandardOperation_then_ContainsUserAgent() {
mockSyncHttpClient.stubResponses(successHttpResponse());
S3Client crossRegionClient = clientBuilder().crossRegionAccessEnabled(true).build();
crossRegionClient.getObject(r -> r.bucket(BUCKET).key(KEY));
assertThat(mockSyncHttpClient.getLastRequest().firstMatchingHeader("User-Agent").get()).contains("hll/cross-region");
}
@Test
void given_SimpleClient_when_StandardOperation_then_DoesNotContainCrossRegionUserAgent() {
mockSyncHttpClient.stubResponses(successHttpResponse());
S3Client crossRegionClient = clientBuilder().crossRegionAccessEnabled(false).build();
crossRegionClient.getObject(r -> r.bucket(BUCKET).key(KEY));
assertThat(mockSyncHttpClient.getLastRequest().firstMatchingHeader("User-Agent").get())
.doesNotContain("hll/cross-region");
}
private S3ClientBuilder clientBuilder() {
return S3Client.builder()
.httpClient(mockSyncHttpClient)
.overrideConfiguration(c -> c.addExecutionInterceptor(captureInterceptor));
}
private static final class CaptureInterceptor implements ExecutionInterceptor {
private EndpointProvider endpointProvider;
@Override
public void beforeMarshalling(Context.BeforeMarshalling context, ExecutionAttributes executionAttributes) {
endpointProvider = executionAttributes.getAttribute(SdkInternalExecutionAttribute.ENDPOINT_PROVIDER);
}
}
}
| 4,451 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/utils/ChecksumUtils.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import software.amazon.awssdk.core.checksums.Algorithm;
import software.amazon.awssdk.core.checksums.SdkChecksum;
import software.amazon.awssdk.utils.BinaryUtils;
/**
* Utilities for computing the SHA-256 checksums of various binary objects.
*/
public final class ChecksumUtils {
public static final int KB = 1024;
public static byte[] computeCheckSum(InputStream is) throws IOException {
MessageDigest instance = createMessageDigest();
byte buff[] = new byte[16384];
int read;
while ((read = is.read(buff)) != -1) {
instance.update(buff, 0, read);
}
return instance.digest();
}
public static byte[] computeCheckSum(ByteBuffer bb) {
MessageDigest instance = createMessageDigest();
instance.update(bb);
bb.rewind();
return instance.digest();
}
public static byte[] computeCheckSum(List<ByteBuffer> buffers) {
MessageDigest instance = createMessageDigest();
buffers.forEach(bb -> {
instance.update(bb);
bb.rewind();
});
return instance.digest();
}
private static MessageDigest createMessageDigest() {
try {
return MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Unable to create SHA-256 MessageDigest instance", e);
}
}
public static String calculatedChecksum(String contentString, Algorithm algorithm) {
SdkChecksum sdkChecksum = SdkChecksum.forAlgorithm(algorithm);
for (byte character : contentString.getBytes(StandardCharsets.UTF_8)) {
sdkChecksum.update(character);
}
return BinaryUtils.toBase64(sdkChecksum.getChecksumBytes());
}
public static String createDataOfSize(int dataSize, char contentCharacter) {
return IntStream.range(0, dataSize).mapToObj(i -> String.valueOf(contentCharacter)).collect(Collectors.joining());
}
}
| 4,452 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/utils/CaptureChecksumValidationInterceptor.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 software.amazon.awssdk.core.checksums.Algorithm;
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;
public class CaptureChecksumValidationInterceptor implements ExecutionInterceptor {
private Algorithm validationAlgorithm;
private ChecksumValidation responseValidation;
private String requestChecksumInTrailer;
private String requestChecksumInHeader;
private String contentEncoding;
public String contentEncoding() {
return contentEncoding;
}
public Algorithm validationAlgorithm() {
return validationAlgorithm;
}
public ChecksumValidation responseValidation() {
return responseValidation;
}
public String requestChecksumInTrailer() {
return requestChecksumInTrailer;
}
public String requestChecksumInHeader() {
return requestChecksumInHeader;
}
public void reset() {
validationAlgorithm = null;
responseValidation = null;
requestChecksumInTrailer = null;
requestChecksumInHeader = null;
}
@Override
public void beforeTransmission(Context.BeforeTransmission context, ExecutionAttributes executionAttributes) {
requestChecksumInTrailer =
context.httpRequest().firstMatchingHeader("x-amz-trailer").orElse(null);
requestChecksumInHeader =
context.httpRequest().firstMatchingHeader("x-amz-checksum-crc32").orElse(null);}
@Override
public void afterExecution(Context.AfterExecution context, ExecutionAttributes executionAttributes) {
validationAlgorithm =
executionAttributes.getOptionalAttribute(SdkExecutionAttribute.HTTP_CHECKSUM_VALIDATION_ALGORITHM).orElse(null);
responseValidation =
executionAttributes.getOptionalAttribute(SdkExecutionAttribute.HTTP_RESPONSE_CHECKSUM_VALIDATION).orElse(null);
contentEncoding = String.join(",", context.httpRequest().matchingHeaders("content-encoding"));
}
@Override
public void onExecutionFailure(Context.FailedExecution context, ExecutionAttributes executionAttributes) {
validationAlgorithm =
executionAttributes.getOptionalAttribute(SdkExecutionAttribute.HTTP_CHECKSUM_VALIDATION_ALGORITHM).orElse(null);
responseValidation =
executionAttributes.getOptionalAttribute(SdkExecutionAttribute.HTTP_RESPONSE_CHECKSUM_VALIDATION).orElse(null);
}
} | 4,453 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/utils/InterceptorTestUtils.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.io.InputStream;
import java.net.URI;
import java.nio.ByteBuffer;
import java.util.Optional;
import org.reactivestreams.Publisher;
import software.amazon.awssdk.core.SdkRequest;
import software.amazon.awssdk.core.SdkResponse;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.core.async.EmptyPublisher;
import software.amazon.awssdk.core.interceptor.Context;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.http.SdkHttpResponse;
import software.amazon.awssdk.utils.StringInputStream;
public final class InterceptorTestUtils {
private InterceptorTestUtils() {
}
public static SdkHttpFullRequest sdkHttpFullRequest() {
return SdkHttpFullRequest.builder()
.uri(URI.create("http://localhost:8080"))
.method(SdkHttpMethod.GET)
.build();
}
public static SdkHttpRequest sdkHttpRequest(URI customUri) {
return SdkHttpFullRequest.builder()
.protocol(customUri.getScheme())
.host(customUri.getHost())
.port(customUri.getPort())
.method(SdkHttpMethod.GET)
.encodedPath(customUri.getPath())
.build();
}
public static Context.ModifyHttpResponse modifyHttpResponse(SdkRequest request, SdkHttpResponse sdkHttpResponse) {
Publisher<ByteBuffer> publisher = new EmptyPublisher<>();
InputStream responseBody = new StringInputStream("helloworld");
return new Context.ModifyResponse() {
@Override
public SdkResponse response() {
return null;
}
@Override
public SdkHttpResponse httpResponse() {
return sdkHttpResponse;
}
@Override
public Optional<Publisher<ByteBuffer>> responsePublisher() {
return Optional.of(publisher);
}
@Override
public Optional<InputStream> responseBody() {
return Optional.of(responseBody);
}
@Override
public SdkHttpRequest httpRequest() {
return SdkHttpRequest.builder().build();
}
@Override
public Optional<RequestBody> requestBody() {
return Optional.empty();
}
@Override
public Optional<AsyncRequestBody> asyncRequestBody() {
return Optional.empty();
}
@Override
public SdkRequest request() {
return request;
}
};
}
public static Context.ModifyHttpRequest modifyHttpRequestContext(SdkRequest request) {
return modifyHttpRequestContext(request, sdkHttpFullRequest());
}
public static Context.ModifyHttpRequest modifyHttpRequestContext(SdkRequest request, SdkHttpRequest sdkHttpRequest) {
Optional<RequestBody> requestBody = Optional.of(RequestBody.fromString("helloworld"));
Optional<AsyncRequestBody> asyncRequestBody = Optional.of(AsyncRequestBody.fromString("helloworld"));
return new Context.ModifyHttpRequest() {
@Override
public SdkHttpRequest httpRequest() {
return sdkHttpRequest;
}
@Override
public Optional<RequestBody> requestBody() {
return requestBody;
}
@Override
public Optional<AsyncRequestBody> asyncRequestBody() {
return asyncRequestBody;
}
@Override
public SdkRequest request() {
return request;
}
};
}
public static Context.ModifyResponse modifyResponseContext(SdkRequest request, SdkResponse response, SdkHttpResponse sdkHttpResponse) {
return new Context.ModifyResponse() {
@Override
public SdkResponse response() {
return response;
}
@Override
public SdkHttpResponse httpResponse() {
return sdkHttpResponse;
}
@Override
public Optional<Publisher<ByteBuffer>> responsePublisher() {
return Optional.empty();
}
@Override
public Optional<InputStream> responseBody() {
return Optional.empty();
}
@Override
public SdkHttpRequest httpRequest() {
return null;
}
@Override
public Optional<RequestBody> requestBody() {
return Optional.empty();
}
@Override
public Optional<AsyncRequestBody> asyncRequestBody() {
return Optional.empty();
}
@Override
public SdkRequest request() {
return request;
}
};
}
public static Context.AfterUnmarshalling afterUnmarshallingContext(SdkRequest request, SdkHttpRequest sdkHttpRequest, SdkResponse response, SdkHttpResponse sdkHttpResponse) {
return new Context.AfterUnmarshalling() {
@Override
public SdkResponse response() {
return response;
}
@Override
public SdkHttpResponse httpResponse() {
return sdkHttpResponse;
}
@Override
public Optional<Publisher<ByteBuffer>> responsePublisher() {
return Optional.empty();
}
@Override
public Optional<InputStream> responseBody() {
return Optional.empty();
}
@Override
public SdkHttpRequest httpRequest() {
return sdkHttpRequest;
}
@Override
public Optional<RequestBody> requestBody() {
return Optional.empty();
}
@Override
public Optional<AsyncRequestBody> asyncRequestBody() {
return Optional.empty();
}
@Override
public SdkRequest request() {
return request;
}
};
}
public static Context.ModifyHttpResponse modifyHttpResponseContent(SdkRequest request, SdkHttpResponse sdkHttpResponse) {
InputStream stream = new StringInputStream("hello world");
return new Context.ModifyResponse() {
@Override
public SdkResponse response() {
return null;
}
@Override
public SdkHttpResponse httpResponse() {
return sdkHttpResponse;
}
@Override
public Optional<Publisher<ByteBuffer>> responsePublisher() {
return Optional.empty();
}
@Override
public Optional<InputStream> responseBody() {
return Optional.of(stream);
}
@Override
public SdkHttpRequest httpRequest() {
return null;
}
@Override
public Optional<RequestBody> requestBody() {
return Optional.empty();
}
@Override
public Optional<AsyncRequestBody> asyncRequestBody() {
return Optional.empty();
}
@Override
public SdkRequest request() {
return request;
}
};
}
}
| 4,454 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/checksums/ChecksumCalculatingInputStreamTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.s3.checksums;
import static org.mockito.Mockito.verify;
import java.io.IOException;
import java.io.InputStream;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import software.amazon.awssdk.core.checksums.SdkChecksum;
/**
* Tests for {@link ChecksumCalculatingInputStream}.
*/
@RunWith(MockitoJUnitRunner.class)
public class ChecksumCalculatingInputStreamTest {
@Mock
private InputStream mockStream;
@Mock
private SdkChecksum mockChecksum;
@Test
public void closeMethodClosesWrappedStream() throws IOException {
ChecksumCalculatingInputStream is = new ChecksumCalculatingInputStream(mockStream, mockChecksum);
is.close();
verify(mockStream).close();
}
}
| 4,455 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/checksums/ChecksumsEnabledValidatorTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.s3.checksums;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static software.amazon.awssdk.core.interceptor.SdkExecutionAttribute.CLIENT_TYPE;
import static software.amazon.awssdk.core.interceptor.SdkExecutionAttribute.SERVICE_CONFIG;
import static software.amazon.awssdk.services.s3.checksums.ChecksumConstant.CHECKSUM_ENABLED_RESPONSE_HEADER;
import static software.amazon.awssdk.services.s3.checksums.ChecksumConstant.CONTENT_LENGTH_HEADER;
import static software.amazon.awssdk.services.s3.checksums.ChecksumConstant.ENABLE_MD5_CHECKSUM_HEADER_VALUE;
import static software.amazon.awssdk.services.s3.checksums.ChecksumConstant.SERVER_SIDE_CUSTOMER_ENCRYPTION_HEADER;
import static software.amazon.awssdk.services.s3.checksums.ChecksumConstant.SERVER_SIDE_ENCRYPTION_HEADER;
import static software.amazon.awssdk.services.s3.checksums.ChecksumsEnabledValidator.getObjectChecksumEnabledPerRequest;
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.model.ServerSideEncryption.AWS_KMS;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.ClientType;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpFullResponse;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.http.SdkHttpResponse;
import software.amazon.awssdk.services.s3.S3Configuration;
import software.amazon.awssdk.services.s3.model.GetObjectAclRequest;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.PutBucketAclRequest;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
public class ChecksumsEnabledValidatorTest {
@Test
public void getObjectChecksumEnabledPerRequest_nonGetObjectRequestFalse() {
assertThat(getObjectChecksumEnabledPerRequest(GetObjectAclRequest.builder().build(),
new ExecutionAttributes())).isFalse();
}
@Test
public void getObjectChecksumEnabledPerRequest_defaultReturnTrue() {
assertThat(getObjectChecksumEnabledPerRequest(GetObjectRequest.builder().build(), new ExecutionAttributes())).isTrue();
}
@Test
public void getObjectChecksumEnabledPerRequest_disabledPerConfig() {
assertThat(getObjectChecksumEnabledPerRequest(GetObjectRequest.builder().build(),
getExecutionAttributesWithChecksumDisabled())).isFalse();
}
@Test
public void getObjectChecksumEnabledPerResponse_nonGetObjectRequestFalse() {
assertThat(getObjectChecksumEnabledPerResponse(GetObjectAclRequest.builder().build(),
getSdkHttpResponseWithChecksumHeader())).isFalse();
}
@Test
public void getObjectChecksumEnabledPerResponse_responseContainsChecksumHeader_returnTrue() {
assertThat(getObjectChecksumEnabledPerResponse(GetObjectRequest.builder().build(),
getSdkHttpResponseWithChecksumHeader())).isTrue();
}
@Test
public void getObjectChecksumEnabledPerResponse_responseNotContainsChecksumHeader_returnFalse() {
assertThat(getObjectChecksumEnabledPerResponse(GetObjectRequest.builder().build(),
SdkHttpFullResponse.builder().build())).isFalse();
}
@Test
public void putObjectChecksumEnabled_defaultShouldRecord() {
assertThat(shouldRecordChecksum(PutObjectRequest.builder().build(),
ClientType.SYNC,
getSyncExecutionAttributes(),
emptyHttpRequest().build())).isTrue();
}
@Test
public void putObjectChecksumEnabled_nonPutObjectRequest_false() {
assertThat(shouldRecordChecksum(PutBucketAclRequest.builder().build(),
ClientType.SYNC,
getSyncExecutionAttributes(),
emptyHttpRequest().build())).isFalse();
}
@Test
public void putObjectChecksumEnabled_disabledFromConfig_false() {
ExecutionAttributes executionAttributes = getExecutionAttributesWithChecksumDisabled();
assertThat(shouldRecordChecksum(PutObjectRequest.builder().build(),
ClientType.SYNC,
executionAttributes,
emptyHttpRequest().build())).isFalse();
}
@Test
public void putObjectChecksumEnabled_wrongClientType_false() {
ExecutionAttributes executionAttributes = getSyncExecutionAttributes();
assertThat(shouldRecordChecksum(PutObjectRequest.builder().build(),
ClientType.ASYNC,
executionAttributes,
emptyHttpRequest().build())).isFalse();
}
@Test
public void putObjectChecksumEnabled_serverSideCustomerEncryption_false() {
ExecutionAttributes executionAttributes = getSyncExecutionAttributes();
SdkHttpRequest response = emptyHttpRequest().putHeader(SERVER_SIDE_CUSTOMER_ENCRYPTION_HEADER, "test")
.build();
assertThat(shouldRecordChecksum(PutObjectRequest.builder().build(),
ClientType.SYNC,
executionAttributes,
response)).isFalse();
}
@Test
public void putObjectChecksumEnabled_serverSideEncryption_false() {
ExecutionAttributes executionAttributes = getSyncExecutionAttributes();
SdkHttpRequest response = emptyHttpRequest().putHeader(SERVER_SIDE_ENCRYPTION_HEADER, AWS_KMS.toString())
.build();
assertThat(shouldRecordChecksum(PutObjectRequest.builder().build(),
ClientType.SYNC,
executionAttributes,
response)).isFalse();
}
@Test
public void responseChecksumIsValid_defaultTrue() {
assertThat(responseChecksumIsValid(SdkHttpResponse.builder().build())).isTrue();
}
@Test
public void responseChecksumIsValid_serverSideCustomerEncryption_false() {
SdkHttpResponse response = SdkHttpResponse.builder()
.putHeader(SERVER_SIDE_CUSTOMER_ENCRYPTION_HEADER, "test")
.build();
assertThat(responseChecksumIsValid(response)).isFalse();
}
@Test
public void responseChecksumIsValid_serverSideEncryption_false() {
SdkHttpResponse response = SdkHttpResponse.builder()
.putHeader(SERVER_SIDE_ENCRYPTION_HEADER, AWS_KMS.toString())
.build();
assertThat(responseChecksumIsValid(response)).isFalse();
}
private ExecutionAttributes getSyncExecutionAttributes() {
ExecutionAttributes executionAttributes = new ExecutionAttributes();
executionAttributes.putAttribute(CLIENT_TYPE, ClientType.SYNC);
return executionAttributes;
}
private ExecutionAttributes getExecutionAttributesWithChecksumDisabled() {
ExecutionAttributes executionAttributes = getSyncExecutionAttributes();
executionAttributes.putAttribute(SERVICE_CONFIG, S3Configuration.builder().checksumValidationEnabled(false).build());
return executionAttributes;
}
private SdkHttpResponse getSdkHttpResponseWithChecksumHeader() {
return SdkHttpResponse.builder()
.putHeader(CONTENT_LENGTH_HEADER, "100")
.putHeader(CHECKSUM_ENABLED_RESPONSE_HEADER, ENABLE_MD5_CHECKSUM_HEADER_VALUE)
.build();
}
private SdkHttpRequest.Builder emptyHttpRequest() {
return SdkHttpFullRequest.builder()
.method(SdkHttpMethod.GET)
.protocol("https")
.host("localhost")
.port(80);
}
}
| 4,456 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/checksums/ChecksumResetsOnRetryTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.s3.checksums;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.any;
import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static org.assertj.core.api.Assertions.assertThat;
import static software.amazon.awssdk.core.async.AsyncResponseTransformer.toBytes;
import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder;
import com.github.tomakehurst.wiremock.client.WireMock;
import com.github.tomakehurst.wiremock.core.WireMockConfiguration;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import com.github.tomakehurst.wiremock.stubbing.Scenario;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.function.Consumer;
import org.apache.commons.lang3.ArrayUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.core.ResponseBytes;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.core.sync.RequestBody;
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.GetObjectResponse;
import software.amazon.awssdk.services.s3.model.PutObjectResponse;
import software.amazon.awssdk.utils.BinaryUtils;
/**
* Verifies that the checksum validators are reset on an HTTP retry.
*/
public class ChecksumResetsOnRetryTest {
@Rule
public WireMockRule mockServer = new WireMockRule(new WireMockConfiguration().port(0));
private S3Client s3Client;
private S3AsyncClient s3AsyncClient;
private byte[] body;
private byte[] bodyWithTrailingChecksum;
private String bodyEtag;
@Before
public void setup() {
StaticCredentialsProvider credentials = StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid"));
s3Client = S3Client.builder()
.credentialsProvider(credentials)
.region(Region.US_WEST_2)
.endpointOverride(URI.create("http://localhost:" + mockServer.port()))
.serviceConfiguration(c -> c.pathStyleAccessEnabled(true))
.build();
s3AsyncClient = S3AsyncClient.builder()
.credentialsProvider(credentials)
.region(Region.US_WEST_2)
.endpointOverride(URI.create("http://localhost:" + mockServer.port()))
.serviceConfiguration(c -> c.pathStyleAccessEnabled(true))
.build();
body = "foo".getBytes(StandardCharsets.UTF_8);
String checksumAsHexString = "acbd18db4cc2f85cedef654fccc4a4d8";
bodyEtag = "\"" + checksumAsHexString + "\"";
bodyWithTrailingChecksum = ArrayUtils.addAll(body, BinaryUtils.fromHex(checksumAsHexString));
}
@Test
public void syncPutObject_resetsChecksumOnRetry() {
stubSuccessAfterOneRetry(r -> r.withHeader("ETag", bodyEtag));
PutObjectResponse response = s3Client.putObject(r -> r.bucket("foo").key("bar"), RequestBody.fromBytes(body));
assertThat(response.eTag()).isEqualTo(bodyEtag);
}
@Test
public void asyncPutObject_resetsChecksumOnRetry() {
stubSuccessAfterOneRetry(r -> r.withHeader("ETag", bodyEtag));
PutObjectResponse response = s3AsyncClient.putObject(r -> r.bucket("foo").key("bar"), AsyncRequestBody.fromBytes(body)).join();
assertThat(response.eTag()).isEqualTo(bodyEtag);
}
@Test
public void syncGetObject_resetsChecksumOnRetry() {
stubSuccessAfterOneRetry(r -> r.withHeader("ETag", bodyEtag)
.withHeader("x-amz-transfer-encoding", "append-md5")
.withHeader("content-length", Integer.toString(bodyWithTrailingChecksum.length))
.withBody(bodyWithTrailingChecksum));
ResponseBytes<GetObjectResponse> response = s3Client.getObjectAsBytes(r -> r.bucket("foo").key("bar"));
assertThat(response.response().eTag()).isEqualTo(bodyEtag);
assertThat(response.asByteArray()).isEqualTo(body);
}
@Test
public void asyncGetObject_resetsChecksumOnRetry() {
stubSuccessAfterOneRetry(r -> r.withHeader("ETag", bodyEtag)
.withHeader("x-amz-transfer-encoding", "append-md5")
.withHeader("content-length", Integer.toString(bodyWithTrailingChecksum.length))
.withBody(bodyWithTrailingChecksum));
ResponseBytes<GetObjectResponse> response = s3AsyncClient.getObject(r -> r.bucket("foo").key("bar"), toBytes()).join();
assertThat(response.response().eTag()).isEqualTo(bodyEtag);
assertThat(response.asByteArray()).isEqualTo(body);
}
private void stubSuccessAfterOneRetry(Consumer<ResponseDefinitionBuilder> successfulResponseModifier) {
WireMock.reset();
String scenario = "stubSuccessAfterOneRetry";
stubFor(any(anyUrl())
.willReturn(aResponse().withStatus(500).withBody("<xml></xml>"))
.inScenario(scenario)
.whenScenarioStateIs(Scenario.STARTED)
.willSetStateTo("200"));
ResponseDefinitionBuilder successfulResponse = aResponse().withStatus(200).withBody("<xml></xml>");
successfulResponseModifier.accept(successfulResponse);
stubFor(any(anyUrl())
.willReturn(successfulResponse)
.inScenario(scenario)
.whenScenarioStateIs("200"));
}
}
| 4,457 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/checksums/ChecksumValidatingPublisherTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.s3.checksums;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import software.amazon.awssdk.core.checksums.Md5Checksum;
import software.amazon.awssdk.utils.BinaryUtils;
/**
* Unit test for ChecksumValidatingPublisher
*/
public class ChecksumValidatingPublisherTest {
private static int TEST_DATA_SIZE = 32; // size of the test data, in bytes
private static final int CHECKSUM_SIZE = 16;
private static byte[] testData;
private static byte[] testDataWithoutChecksum;
@BeforeAll
public static void populateData() {
testData = new byte[TEST_DATA_SIZE + CHECKSUM_SIZE];
for (int i = 0; i < TEST_DATA_SIZE; i++) {
testData[i] = (byte)(i & 0x7f);
}
final Md5Checksum checksum = new Md5Checksum();
checksum.update(testData, 0, TEST_DATA_SIZE);
byte[] checksumBytes = checksum.getChecksumBytes();
for (int i = 0; i < CHECKSUM_SIZE; i++) {
testData[TEST_DATA_SIZE + i] = checksumBytes[i];
}
testDataWithoutChecksum = Arrays.copyOfRange(testData, 0, TEST_DATA_SIZE);
}
@Test
public void testSinglePacket() {
final TestPublisher driver = new TestPublisher();
final TestSubscriber s = new TestSubscriber();
final ChecksumValidatingPublisher p = new ChecksumValidatingPublisher(driver, new Md5Checksum(), TEST_DATA_SIZE + CHECKSUM_SIZE);
p.subscribe(s);
driver.doOnNext(ByteBuffer.wrap(testData));
driver.doOnComplete();
assertArrayEquals(testDataWithoutChecksum, s.receivedData());
assertTrue(s.hasCompleted());
assertFalse(s.isOnErrorCalled());
}
@Test
public void testLastChecksumByteCorrupted() {
TestPublisher driver = new TestPublisher();
TestSubscriber s = new TestSubscriber();
ChecksumValidatingPublisher p = new ChecksumValidatingPublisher(driver, new Md5Checksum(), TEST_DATA_SIZE + CHECKSUM_SIZE);
p.subscribe(s);
byte[] incorrectChecksumData = Arrays.copyOfRange(testData, 0, TEST_DATA_SIZE);
incorrectChecksumData[TEST_DATA_SIZE - 1] = (byte) ~incorrectChecksumData[TEST_DATA_SIZE - 1];
driver.doOnNext(ByteBuffer.wrap(incorrectChecksumData));
driver.doOnComplete();
assertFalse(s.hasCompleted());
assertTrue(s.isOnErrorCalled());
}
@Test
public void testTwoPackets() {
for (int i = 1; i < TEST_DATA_SIZE + CHECKSUM_SIZE - 1; i++) {
final TestPublisher driver = new TestPublisher();
final TestSubscriber s = new TestSubscriber();
final ChecksumValidatingPublisher p = new ChecksumValidatingPublisher(driver, new Md5Checksum(), TEST_DATA_SIZE + CHECKSUM_SIZE);
p.subscribe(s);
driver.doOnNext(ByteBuffer.wrap(testData, 0, i));
driver.doOnNext(ByteBuffer.wrap(testData, i, TEST_DATA_SIZE + CHECKSUM_SIZE - i));
driver.doOnComplete();
assertArrayEquals(testDataWithoutChecksum, s.receivedData());
assertTrue(s.hasCompleted());
assertFalse(s.isOnErrorCalled());
}
}
@Test
public void testTinyPackets() {
for (int packetSize = 1; packetSize < CHECKSUM_SIZE; packetSize++) {
final TestPublisher driver = new TestPublisher();
final TestSubscriber s = new TestSubscriber();
final ChecksumValidatingPublisher p = new ChecksumValidatingPublisher(driver, new Md5Checksum(), TEST_DATA_SIZE + CHECKSUM_SIZE);
p.subscribe(s);
int currOffset = 0;
while (currOffset < TEST_DATA_SIZE + CHECKSUM_SIZE) {
final int toSend = Math.min(packetSize, TEST_DATA_SIZE + CHECKSUM_SIZE - currOffset);
driver.doOnNext(ByteBuffer.wrap(testData, currOffset, toSend));
currOffset += toSend;
}
driver.doOnComplete();
assertArrayEquals(testDataWithoutChecksum, s.receivedData());
assertTrue(s.hasCompleted());
assertFalse(s.isOnErrorCalled());
}
}
@Test
public void testUnknownLength() {
// When the length is unknown, the last 16 bytes are treated as a checksum, but are later ignored when completing
final TestPublisher driver = new TestPublisher();
final TestSubscriber s = new TestSubscriber();
final ChecksumValidatingPublisher p = new ChecksumValidatingPublisher(driver, new Md5Checksum(), 0);
p.subscribe(s);
byte[] randomChecksumData = new byte[testData.length];
System.arraycopy(testData, 0, randomChecksumData, 0, TEST_DATA_SIZE);
for (int i = TEST_DATA_SIZE; i < randomChecksumData.length; i++) {
randomChecksumData[i] = (byte)((testData[i] + 1) & 0x7f);
}
driver.doOnNext(ByteBuffer.wrap(randomChecksumData));
driver.doOnComplete();
assertArrayEquals(testDataWithoutChecksum, s.receivedData());
assertTrue(s.hasCompleted());
assertFalse(s.isOnErrorCalled());
}
@Test
public void checksumValidationFailure_throwsSdkClientException_NotNPE() {
final byte[] incorrectData = new byte[0];
final TestPublisher driver = new TestPublisher();
final TestSubscriber s = new TestSubscriber();
final ChecksumValidatingPublisher p = new ChecksumValidatingPublisher(driver, new Md5Checksum(), TEST_DATA_SIZE + CHECKSUM_SIZE);
p.subscribe(s);
driver.doOnNext(ByteBuffer.wrap(incorrectData));
driver.doOnComplete();
assertTrue(s.isOnErrorCalled());
assertFalse(s.hasCompleted());
}
private class TestSubscriber implements Subscriber<ByteBuffer> {
final List<ByteBuffer> received;
boolean completed;
boolean onErrorCalled;
TestSubscriber() {
this.received = new ArrayList<>();
this.completed = false;
}
@Override
public void onSubscribe(Subscription s) {
fail("This method not expected to be invoked");
throw new UnsupportedOperationException("!!!TODO: implement this");
}
@Override
public void onNext(ByteBuffer buffer) {
received.add(buffer);
}
@Override
public void onError(Throwable t) {
onErrorCalled = true;
}
@Override
public void onComplete() {
completed = true;
}
public byte[] receivedData() {
try {
ByteArrayOutputStream os = new ByteArrayOutputStream();
for (ByteBuffer buffer : received) {
os.write(BinaryUtils.copyBytesFrom(buffer));
}
return os.toByteArray();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public boolean hasCompleted() {
return completed;
}
public boolean isOnErrorCalled() {
return onErrorCalled;
}
}
private class TestPublisher implements Publisher<ByteBuffer> {
Subscriber<? super ByteBuffer> s;
@Override
public void subscribe(Subscriber<? super ByteBuffer> s) {
this.s = s;
}
public void doOnNext(ByteBuffer b) {
s.onNext(b);
}
public void doOnComplete() {
s.onComplete();
}
}
}
| 4,458 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/checksums/ChecksumValidatingInputStreamTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.s3.checksums;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.fail;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.checksums.Md5Checksum;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.utils.IoUtils;
public class ChecksumValidatingInputStreamTest {
private static final int TEST_DATA_SIZE = 32;
private static final int CHECKSUM_SIZE = 16;
private static byte[] testData;
private static byte[] testDataWithoutChecksum;
@BeforeAll
public static void populateData() {
testData = new byte[TEST_DATA_SIZE + CHECKSUM_SIZE];
for (int i = 0; i < TEST_DATA_SIZE; i++) {
testData[i] = (byte)(i & 0x7f);
}
Md5Checksum checksum = new Md5Checksum();
checksum.update(testData, 0, TEST_DATA_SIZE);
byte[] checksumBytes = checksum.getChecksumBytes();
for (int i = 0; i < CHECKSUM_SIZE; i++) {
testData[TEST_DATA_SIZE + i] = checksumBytes[i];
}
testDataWithoutChecksum = Arrays.copyOfRange(testData, 0, TEST_DATA_SIZE);
}
@Test
public void validChecksumSucceeds() throws IOException {
InputStream validatingInputStream = newValidatingStream(testData);
byte[] dataFromValidatingStream = IoUtils.toByteArray(validatingInputStream);
assertArrayEquals(testDataWithoutChecksum, dataFromValidatingStream);
}
@Test
public void invalidChecksumFails() throws IOException {
for (int i = 0; i < testData.length; i++) {
// Make sure that corruption of any byte in the test data causes a checksum validation failure.
byte[] corruptedChecksumData = Arrays.copyOf(testData, testData.length);
corruptedChecksumData[i] = (byte) ~corruptedChecksumData[i];
InputStream validatingInputStream = newValidatingStream(corruptedChecksumData);
try {
IoUtils.toByteArray(validatingInputStream);
fail("Corruption at byte " + i + " was not detected.");
} catch (SdkClientException e) {
// Expected
}
}
}
private InputStream newValidatingStream(byte[] dataFromS3) {
return new ChecksumValidatingInputStream(new ByteArrayInputStream(dataFromS3),
new Md5Checksum(),
TEST_DATA_SIZE + CHECKSUM_SIZE);
}
} | 4,459 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/presigner | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/presigner/model/PresignedGetObjectRequestTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.s3.presigner.model;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpRequest;
@RunWith(MockitoJUnitRunner.class)
public class PresignedGetObjectRequestTest {
private static final Map<String, List<String>> FAKE_SIGNED_HEADERS;
private static final URL FAKE_URL;
private static final SdkBytes FAKE_SIGNED_PAYLOAD = SdkBytes.fromString("fake-payload", StandardCharsets.UTF_8);
static {
Map<String, List<String>> map = new HashMap<>();
map.put("fake-key", Collections.unmodifiableList(Arrays.asList("one", "two")));
FAKE_SIGNED_HEADERS = Collections.unmodifiableMap(map);
try {
FAKE_URL = new URL("https://localhost");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Mock
private SdkHttpRequest mockSdkHttpRequest;
@Before
public void setup() throws URISyntaxException {
when(mockSdkHttpRequest.getUri()).thenReturn(FAKE_URL.toURI());
}
private PresignedGetObjectRequest generateMaximal() {
return PresignedGetObjectRequest.builder()
.expiration(Instant.MAX)
.httpRequest(mockSdkHttpRequest)
.signedHeaders(FAKE_SIGNED_HEADERS)
.signedPayload(FAKE_SIGNED_PAYLOAD)
.isBrowserExecutable(false)
.build();
}
private PresignedGetObjectRequest generateMinimal() {
return PresignedGetObjectRequest.builder()
.expiration(Instant.MAX)
.httpRequest(mockSdkHttpRequest)
.signedHeaders(FAKE_SIGNED_HEADERS)
.isBrowserExecutable(false)
.build();
}
@Test
public void build_allProperties() {
PresignedGetObjectRequest presignedGetObjectRequest = generateMaximal();
assertThat(presignedGetObjectRequest.expiration()).isEqualTo(Instant.MAX);
assertThat(presignedGetObjectRequest.httpRequest()).isEqualTo(mockSdkHttpRequest);
assertThat(presignedGetObjectRequest.signedHeaders()).isEqualTo(FAKE_SIGNED_HEADERS);
assertThat(presignedGetObjectRequest.signedPayload()).isEqualTo(Optional.of(FAKE_SIGNED_PAYLOAD));
assertThat(presignedGetObjectRequest.url()).isEqualTo(FAKE_URL);
}
@Test
public void build_minimalProperties() {
PresignedGetObjectRequest presignedGetObjectRequest = generateMinimal();
assertThat(presignedGetObjectRequest.expiration()).isEqualTo(Instant.MAX);
assertThat(presignedGetObjectRequest.httpRequest()).isEqualTo(mockSdkHttpRequest);
assertThat(presignedGetObjectRequest.url()).isEqualTo(FAKE_URL);
assertThat(presignedGetObjectRequest.signedHeaders()).isEqualTo(FAKE_SIGNED_HEADERS);
assertThat(presignedGetObjectRequest.signedPayload()).isEmpty();
}
@Test
public void build_missingProperty_expiration() {
assertThatThrownBy(() -> generateMinimal().toBuilder().expiration(null).build())
.isInstanceOf(NullPointerException.class)
.hasMessageContaining("expiration");
}
@Test
public void build_missingProperty_httpRequest() {
assertThatThrownBy(() -> generateMinimal().toBuilder().httpRequest(null).build())
.isInstanceOf(NullPointerException.class)
.hasMessageContaining("httpRequest");
}
@Test
public void hasSignedPayload_false() {
PresignedGetObjectRequest presignedGetObjectRequest = generateMinimal();
assertThat(presignedGetObjectRequest.signedPayload()).isNotPresent();
}
@Test
public void hasSignedPayload_true() {
PresignedGetObjectRequest presignedGetObjectRequest = generateMaximal();
assertThat(presignedGetObjectRequest.signedPayload()).isPresent();
}
@Test
public void equalsAndHashCode_maximal() {
PresignedGetObjectRequest request = generateMaximal();
PresignedGetObjectRequest otherRequest = generateMaximal();
assertThat(request).isEqualTo(otherRequest);
assertThat(request.hashCode()).isEqualTo(otherRequest.hashCode());
}
@Test
public void equalsAndHashCode_minimal() {
PresignedGetObjectRequest request = generateMinimal();
PresignedGetObjectRequest otherRequest = generateMinimal();
assertThat(request).isEqualTo(otherRequest);
assertThat(request.hashCode()).isEqualTo(otherRequest.hashCode());
}
@Test
public void equalsAndHashCode_differentProperty_httpRequest() throws URISyntaxException {
SdkHttpRequest otherHttpRequest = mock(SdkHttpRequest.class);
when(otherHttpRequest.getUri()).thenReturn(FAKE_URL.toURI());
PresignedGetObjectRequest request = generateMaximal();
PresignedGetObjectRequest otherRequest = request.toBuilder().httpRequest(otherHttpRequest).build();
assertThat(request).isNotEqualTo(otherRequest);
assertThat(request.hashCode()).isNotEqualTo(otherRequest.hashCode());
}
@Test
public void equalsAndHashCode_differentProperty_expiration() {
PresignedGetObjectRequest request = generateMaximal();
PresignedGetObjectRequest otherRequest = request.toBuilder().expiration(Instant.MIN).build();
assertThat(request).isNotEqualTo(otherRequest);
assertThat(request.hashCode()).isNotEqualTo(otherRequest.hashCode());
}
@Test
public void equalsAndHashCode_differentProperty_signedPayload() {
SdkBytes otherSignedPayload = SdkBytes.fromString("other-payload", StandardCharsets.UTF_8);
PresignedGetObjectRequest request = generateMaximal();
PresignedGetObjectRequest otherRequest = request.toBuilder().signedPayload(otherSignedPayload).build();
assertThat(request).isNotEqualTo(otherRequest);
assertThat(request.hashCode()).isNotEqualTo(otherRequest.hashCode());
}
@Test
public void equalsAndHashCode_differentProperty_signedHeaders() {
Map<String, List<String>> otherSignedHeaders = new HashMap<>();
otherSignedHeaders.put("fake-key", Collections.unmodifiableList(Arrays.asList("other-one", "other-two")));
PresignedGetObjectRequest request = generateMaximal();
PresignedGetObjectRequest otherRequest = request.toBuilder().signedHeaders(otherSignedHeaders).build();
assertThat(request).isNotEqualTo(otherRequest);
assertThat(request.hashCode()).isNotEqualTo(otherRequest.hashCode());
}
} | 4,460 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/presigner | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/presigner/model/GetObjectPresignRequestTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.services.s3.presigner.model;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy;
import java.time.Duration;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
public class GetObjectPresignRequestTest {
private static final GetObjectRequest GET_OBJECT_REQUEST = GetObjectRequest.builder()
.bucket("some-bucket")
.key("some-key")
.build();
@Test
public void build_minimal_maximal() {
GetObjectPresignRequest getObjectPresignRequest =
GetObjectPresignRequest.builder()
.getObjectRequest(GET_OBJECT_REQUEST)
.signatureDuration(Duration.ofSeconds(123L))
.build();
assertThat(getObjectPresignRequest.getObjectRequest()).isEqualTo(GET_OBJECT_REQUEST);
assertThat(getObjectPresignRequest.signatureDuration()).isEqualTo(Duration.ofSeconds(123L));
}
@Test
public void build_missingProperty_getObjectRequest() {
assertThatThrownBy(() -> GetObjectPresignRequest.builder()
.signatureDuration(Duration.ofSeconds(123L))
.build())
.isInstanceOf(NullPointerException.class)
.hasMessageContaining("getObjectRequest");
}
@Test
public void build_missingProperty_signatureDuration() {
assertThatThrownBy(() -> GetObjectPresignRequest.builder()
.getObjectRequest(GET_OBJECT_REQUEST)
.build())
.isInstanceOf(NullPointerException.class)
.hasMessageContaining("signatureDuration");
}
@Test
public void toBuilder() {
GetObjectPresignRequest getObjectPresignRequest =
GetObjectPresignRequest.builder()
.getObjectRequest(GET_OBJECT_REQUEST)
.signatureDuration(Duration.ofSeconds(123L))
.build();
GetObjectPresignRequest otherGetObjectPresignRequest = getObjectPresignRequest.toBuilder().build();
assertThat(otherGetObjectPresignRequest.getObjectRequest()).isEqualTo(GET_OBJECT_REQUEST);
assertThat(otherGetObjectPresignRequest.signatureDuration()).isEqualTo(Duration.ofSeconds(123L));
}
@Test
public void equalsAndHashCode_allPropertiesEqual() {
GetObjectPresignRequest getObjectPresignRequest =
GetObjectPresignRequest.builder()
.getObjectRequest(GET_OBJECT_REQUEST)
.signatureDuration(Duration.ofSeconds(123L))
.build();
GetObjectPresignRequest otherGetObjectPresignRequest =
GetObjectPresignRequest.builder()
.getObjectRequest(GET_OBJECT_REQUEST)
.signatureDuration(Duration.ofSeconds(123L))
.build();
assertThat(otherGetObjectPresignRequest).isEqualTo(getObjectPresignRequest);
assertThat(otherGetObjectPresignRequest.hashCode()).isEqualTo(getObjectPresignRequest.hashCode());
}
@Test
public void equalsAndHashCode_differentProperty_getObjectRequest() {
GetObjectRequest otherGetObjectRequest = GetObjectRequest.builder()
.bucket("other-bucket")
.key("other-key")
.build();
GetObjectPresignRequest getObjectPresignRequest =
GetObjectPresignRequest.builder()
.getObjectRequest(GET_OBJECT_REQUEST)
.signatureDuration(Duration.ofSeconds(123L))
.build();
GetObjectPresignRequest otherGetObjectPresignRequest =
GetObjectPresignRequest.builder()
.getObjectRequest(otherGetObjectRequest)
.signatureDuration(Duration.ofSeconds(123L))
.build();
assertThat(otherGetObjectPresignRequest).isNotEqualTo(getObjectPresignRequest);
assertThat(otherGetObjectPresignRequest.hashCode()).isNotEqualTo(getObjectPresignRequest.hashCode());
}
@Test
public void equalsAndHashCode_differentProperty_signatureDuration() {
GetObjectPresignRequest getObjectPresignRequest =
GetObjectPresignRequest.builder()
.getObjectRequest(GET_OBJECT_REQUEST)
.signatureDuration(Duration.ofSeconds(123L))
.build();
GetObjectPresignRequest otherGetObjectPresignRequest =
GetObjectPresignRequest.builder()
.getObjectRequest(GET_OBJECT_REQUEST)
.signatureDuration(Duration.ofSeconds(321L))
.build();
assertThat(otherGetObjectPresignRequest).isNotEqualTo(getObjectPresignRequest);
assertThat(otherGetObjectPresignRequest.hashCode()).isNotEqualTo(getObjectPresignRequest.hashCode());
}
} | 4,461 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/model/ListPartsRequestTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.model;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.S3Client;
class ListPartsRequestTest extends S3RequestTestBase<ListPartsRequest> {
@Override
ListPartsRequest s3RequestWithUploadId(String uploadId) {
return listPartsRequestWithUploadId(uploadId);
}
@Override
ListPartsResponse performRequest(S3Client client, ListPartsRequest request) {
return client.listParts(request);
}
@Override
CompletableFuture<ListPartsResponse> performRequestAsync(S3AsyncClient client, ListPartsRequest request) {
return client.listParts(request);
}
private static ListPartsRequest listPartsRequestWithUploadId(String uploadId) {
return ListPartsRequest.builder()
.bucket("mybucket")
.key("mykey")
.uploadId(uploadId)
.build();
}
} | 4,462 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/model/S3RequestTestBase.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.model;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.any;
import static com.github.tomakehurst.wiremock.client.WireMock.anyRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl;
import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
import static com.github.tomakehurst.wiremock.client.WireMock.verify;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import com.github.tomakehurst.wiremock.junit5.WireMockRuntimeInfo;
import com.github.tomakehurst.wiremock.junit5.WireMockTest;
import java.net.URI;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import org.assertj.core.api.ThrowableAssert;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.core.exception.SdkClientException;
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.S3Configuration;
@WireMockTest
abstract class S3RequestTestBase <T extends S3Request> {
private int wireMockPort;
private S3Client s3Client;
private S3AsyncClient s3AsyncClient;
abstract T s3RequestWithUploadId(String uploadId);
abstract S3Response performRequest(S3Client client, T request);
abstract CompletableFuture<? extends S3Response> performRequestAsync(S3AsyncClient client, T request);
@BeforeEach
void setUp(WireMockRuntimeInfo wmRuntimeInfo) {
wireMockPort = wmRuntimeInfo.getHttpPort();
s3Client = S3Client.builder()
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid",
"skid")))
.region(Region.US_WEST_2)
.endpointOverride(URI.create("http://localhost:" + wireMockPort))
.serviceConfiguration(S3Configuration.builder()
.checksumValidationEnabled(false)
.pathStyleAccessEnabled(true)
.build())
.build();
s3AsyncClient = S3AsyncClient.builder()
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid",
"skid")))
.region(Region.US_WEST_2)
.endpointOverride(URI.create("http://localhost:" + wireMockPort))
.serviceConfiguration(S3Configuration.builder()
.checksumValidationEnabled(false)
.pathStyleAccessEnabled(true)
.build())
.build();
}
@Test
void marshall_syncMissingUploadId_ThrowsException() {
stubAndRespondWith(200,"<xml></xml>");
T request = s3RequestWithUploadId(null);
assertThatThrownBy(() -> performRequest(s3Client, request))
.isInstanceOf(SdkClientException.class)
.hasMessageContaining("Parameter 'uploadId' must not be null");
}
@Test
void marshall_syncEmptyUploadId_encodesAsEmptyValue() {
stubAndRespondWith(200,"<xml></xml>");
T request = s3RequestWithUploadId("");
performRequest(s3Client, request);
verify(anyRequestedFor(anyUrl()).withQueryParam("uploadId", equalTo("")));
}
@Test
void marshall_syncNonEmptyUploadId_encodesValue() {
stubAndRespondWith(200,"<xml></xml>");
T request = s3RequestWithUploadId("123");
performRequest(s3Client, request);
verify(anyRequestedFor(anyUrl()).withQueryParam("uploadId", equalTo("123")));
}
@Test
void marshall_asyncMissingUploadId_ThrowsException() {
stubAndRespondWith(200,"<xml></xml>");
T request = s3RequestWithUploadId(null);
ThrowableAssert.ThrowingCallable throwingCallable = () -> performRequestAsync(s3AsyncClient, request).join();
assertThatThrownBy(throwingCallable)
.isInstanceOf(CompletionException.class)
.hasMessageContaining("Parameter 'uploadId' must not be null");
}
@Test
void marshall_asyncEmptyUploadId_encodesAsEmptyValue() {
stubAndRespondWith(200,"<xml></xml>");
T request = s3RequestWithUploadId("");
performRequestAsync(s3AsyncClient, request).join();
verify(anyRequestedFor(anyUrl()).withQueryParam("uploadId", equalTo("")));
}
@Test
void marshall_asyncNonEmptyUploadId_encodesValue() {
stubAndRespondWith(200,"<xml></xml>");
T request = s3RequestWithUploadId("123");
performRequestAsync(s3AsyncClient, request).join();
verify(anyRequestedFor(anyUrl()).withQueryParam("uploadId", equalTo("123")));
}
private static void stubAndRespondWith(int status, String body) {
stubFor(any(urlMatching(".*"))
.willReturn(aResponse().withStatus(status).withBody(body)));
}
}
| 4,463 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/model/AbortMultipartUploadRequestTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.model;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.S3Client;
class AbortMultipartUploadRequestTest extends S3RequestTestBase<AbortMultipartUploadRequest> {
@Override
AbortMultipartUploadRequest s3RequestWithUploadId(String uploadId) {
return abortMultipartUploadRequestWithUploadId(uploadId);
}
@Override
AbortMultipartUploadResponse performRequest(S3Client client, AbortMultipartUploadRequest request) {
return client.abortMultipartUpload(request);
}
@Override
CompletableFuture<AbortMultipartUploadResponse> performRequestAsync(S3AsyncClient client, AbortMultipartUploadRequest request) {
return client.abortMultipartUpload(request);
}
private static AbortMultipartUploadRequest abortMultipartUploadRequestWithUploadId(String uploadId) {
return AbortMultipartUploadRequest.builder()
.bucket("mybucket")
.key("mykey")
.uploadId(uploadId)
.build();
}
} | 4,464 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/model/UploadPartRequestTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.model;
import java.util.concurrent.CompletableFuture;
import org.apache.commons.lang3.RandomStringUtils;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.S3Client;
class UploadPartRequestTest extends S3RequestTestBase<UploadPartRequest> {
static final RequestBody REQUEST_BODY = RequestBody.fromString(RandomStringUtils.randomAscii(1_000));
static final AsyncRequestBody ASYNC_REQUEST_BODY = AsyncRequestBody.fromString(RandomStringUtils.randomAscii(1_000));
@Override
UploadPartRequest s3RequestWithUploadId(String uploadId) {
return uploadPartRequestWithUploadId(uploadId);
}
@Override
UploadPartResponse performRequest(S3Client client, UploadPartRequest request) {
return client.uploadPart(request, REQUEST_BODY);
}
@Override
CompletableFuture<UploadPartResponse> performRequestAsync(S3AsyncClient client, UploadPartRequest request) {
return client.uploadPart(request, ASYNC_REQUEST_BODY);
}
private static UploadPartRequest uploadPartRequestWithUploadId(String uploadId) {
return UploadPartRequest.builder()
.bucket("mybucket")
.key("mykey")
.uploadId(uploadId)
.partNumber(1)
.build();
}
} | 4,465 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/model/CompleteMultipartUploadRequestTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.model;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.S3Client;
class CompleteMultipartUploadRequestTest extends S3RequestTestBase<CompleteMultipartUploadRequest> {
@Override
CompleteMultipartUploadRequest s3RequestWithUploadId(String uploadId) {
return completeMultipartUploadRequestWithUploadId(uploadId);
}
@Override
CompleteMultipartUploadResponse performRequest(S3Client client, CompleteMultipartUploadRequest request) {
return client.completeMultipartUpload(request);
}
@Override
CompletableFuture<CompleteMultipartUploadResponse> performRequestAsync(S3AsyncClient client,
CompleteMultipartUploadRequest request) {
return client.completeMultipartUpload(request);
}
private static CompleteMultipartUploadRequest completeMultipartUploadRequestWithUploadId(String uploadId) {
return CompleteMultipartUploadRequest.builder()
.bucket("mybucket")
.key("mykey")
.uploadId(uploadId)
.build();
}
} | 4,466 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/crt/S3CrtConnectionHealthConfigurationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 nl.jqno.equalsverifier.EqualsVerifier;
import org.junit.jupiter.api.Test;
class S3CrtConnectionHealthConfigurationTest {
@Test
void equalsHashcode() {
EqualsVerifier.forClass(S3CrtConnectionHealthConfiguration.class)
.withRedefinedSuperclass()
.withNonnullFields("minimumThroughputTimeout")
.verify();
}
}
| 4,467 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/crt/S3CrtHttpConfigurationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 nl.jqno.equalsverifier.EqualsVerifier;
import org.junit.jupiter.api.Test;
class S3CrtHttpConfigurationTest {
@Test
void equalsHashcode() {
EqualsVerifier.forClass(S3CrtHttpConfiguration.class)
.verify();
}
}
| 4,468 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/crt/S3CrtRetryConfigurationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 nl.jqno.equalsverifier.EqualsVerifier;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThatNullPointerException;
class S3CrtRetryConfigurationTest {
@Test
void equalsHashcode() {
EqualsVerifier.forClass(S3CrtRetryConfiguration.class)
.withRedefinedSuperclass()
.verify();
}
@Test
void retryConfigurationWithNoMaxRetriesDefined(){
assertThatNullPointerException().isThrownBy(() ->S3CrtRetryConfiguration.builder().build())
.withMessage("numRetries");
}
}
| 4,469 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/crt/S3CrtProxyConfigurationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 nl.jqno.equalsverifier.EqualsVerifier;
import org.junit.jupiter.api.Test;
class S3CrtProxyConfigurationTest {
@Test
void equalsHashcode() {
EqualsVerifier.forClass(S3CrtProxyConfiguration.class)
.withRedefinedSuperclass()
.verify();
}
}
| 4,470 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3 | Create_ds/aws-sdk-java-v2/services/s3/src/test/java/software/amazon/awssdk/services/s3/bucketaddressingsep/VirtualHostAddressingSepTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.bucketaddressingsep;
import static org.assertj.core.api.Assertions.assertThat;
import static software.amazon.awssdk.services.s3.S3MockUtils.mockListObjectsResponse;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.ListObjectsRequest;
import software.amazon.awssdk.testutils.service.http.MockSyncHttpClient;
@RunWith(Parameterized.class)
public class VirtualHostAddressingSepTest {
private static final String TEST_FILE_PATH = "VirtualAddressingSepTestCases.json";
private MockSyncHttpClient mockHttpClient;
private TestCaseModel testCaseModel;
public VirtualHostAddressingSepTest(TestCaseModel testCaseModel) {
this.testCaseModel = testCaseModel;
}
@Before
public void setup() {
mockHttpClient = new MockSyncHttpClient();
}
@Parameterized.Parameters
public static List<TestCaseModel> testInputs() throws IOException {
final ObjectMapper objectMapper = new ObjectMapper();
TypeFactory typeFactory = objectMapper.getTypeFactory();
InputStream jsonData = VirtualHostAddressingSepTest.class.getResourceAsStream(TEST_FILE_PATH);
return objectMapper.readValue(jsonData,
typeFactory.constructCollectionType(List.class, TestCaseModel.class));
}
@Test
public void assertTestCase() throws UnsupportedEncodingException {
final String bucket = testCaseModel.getBucket();
final String expectedUri = testCaseModel.getExpectedUri();
S3Client s3Client = constructClient(testCaseModel);
mockHttpClient.stubNextResponse(mockListObjectsResponse());
s3Client.listObjects(ListObjectsRequest.builder().bucket(bucket).build());
assertThat(mockHttpClient.getLastRequest().getUri())
.isEqualTo(URI.create(expectedUri));
}
private S3Client constructClient(TestCaseModel testCaseModel) {
return S3Client.builder()
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid")))
.httpClient(mockHttpClient)
.region(Region.of(testCaseModel.getRegion()))
.serviceConfiguration(c -> c.pathStyleAccessEnabled(testCaseModel.isPathStyle())
.accelerateModeEnabled(testCaseModel.isUseS3Accelerate())
.dualstackEnabled(testCaseModel.isUseDualstack()))
.build();
}
private static class TestCaseModel {
private String bucket;
private String configuredAddressingStyle;
private String expectedUri;
private String region;
private boolean useDualstack;
private boolean useS3Accelerate;
public String getBucket() {
return bucket;
}
@JsonProperty("Bucket")
public void setBucket(String bucket) {
this.bucket = bucket;
}
public String getConfiguredAddressingStyle() {
return configuredAddressingStyle;
}
@JsonProperty("ConfiguredAddressingStyle")
public void setConfiguredAddressingStyle(String configuredAddressingStyle) {
this.configuredAddressingStyle = configuredAddressingStyle;
}
public String getExpectedUri() {
return expectedUri;
}
@JsonProperty("ExpectedUri")
public void setExpectedUri(String expectedUri) {
this.expectedUri = expectedUri;
}
public String getRegion() {
return region;
}
@JsonProperty("Region")
public void setRegion(String region) {
this.region = region;
}
public boolean isUseDualstack() {
return useDualstack;
}
@JsonProperty("UseDualstack")
public void setUseDualstack(boolean useDualstack) {
this.useDualstack = useDualstack;
}
public boolean isUseS3Accelerate() {
return useS3Accelerate;
}
@JsonProperty("UseS3Accelerate")
public void setUseS3Accelerate(boolean useS3Accelerate) {
this.useS3Accelerate = useS3Accelerate;
}
public boolean isPathStyle() {
return configuredAddressingStyle.equals("path");
}
}
}
| 4,471 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/it/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/services/s3/src/it/java/software/amazon/awssdk/services/SelectObjectContentIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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;
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.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Stream;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import software.amazon.awssdk.core.async.SdkPublisher;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.S3IntegrationTestBase;
import software.amazon.awssdk.services.s3.model.CSVInput;
import software.amazon.awssdk.services.s3.model.CSVOutput;
import software.amazon.awssdk.services.s3.model.CompressionType;
import software.amazon.awssdk.services.s3.model.ExpressionType;
import software.amazon.awssdk.services.s3.model.InputSerialization;
import software.amazon.awssdk.services.s3.model.OutputSerialization;
import software.amazon.awssdk.services.s3.model.RecordsEvent;
import software.amazon.awssdk.services.s3.model.S3Exception;
import software.amazon.awssdk.services.s3.model.SelectObjectContentEventStream;
import software.amazon.awssdk.services.s3.model.SelectObjectContentEventStream.EventType;
import software.amazon.awssdk.services.s3.model.SelectObjectContentRequest;
import software.amazon.awssdk.services.s3.model.SelectObjectContentResponse;
import software.amazon.awssdk.services.s3.model.SelectObjectContentResponseHandler;
import software.amazon.awssdk.utils.SdkAutoCloseable;
public class SelectObjectContentIntegrationTest extends S3IntegrationTestBase {
private static final String BUCKET_NAME = temporaryBucketName(SelectObjectContentIntegrationTest.class);
private static final String KEY = "test_object.csv";
private static final String CSV_CONTENTS = "A,B\n"
+ "C,D";
private static final String QUERY = "select s._1 from S3Object s";
@BeforeAll
public static void setup() throws Exception {
S3IntegrationTestBase.setUp();
s3.createBucket(r -> r.bucket(BUCKET_NAME));
s3.waiter().waitUntilBucketExists(r -> r.bucket(BUCKET_NAME));
s3.putObject(r -> r.bucket(BUCKET_NAME).key(KEY), RequestBody.fromString(CSV_CONTENTS));
}
private static Stream<S3AsyncClient> s3AsyncClients() {
return Stream.of(crtClientBuilder().build(), s3AsyncClientBuilder().build());
}
@AfterAll
public static void teardown() {
try {
deleteBucketAndAllContents(BUCKET_NAME);
} finally {
s3AsyncClients().forEach(SdkAutoCloseable::close);
s3.close();
}
}
@ParameterizedTest
@MethodSource("s3AsyncClients")
public void selectObjectContent_onResponseInvokedWithResponse(S3AsyncClient client) {
TestHandler handler = new TestHandler();
executeSqlQueryWithHandler(QUERY, handler, client).join();
assertThat(handler.response).isNotNull();
}
@ParameterizedTest
@MethodSource("s3AsyncClients")
public void selectObjectContent_recordsEventUnmarshalledCorrectly(S3AsyncClient client) {
TestHandler handler = new TestHandler();
executeSqlQueryWithHandler(QUERY, handler, client).join();
RecordsEvent recordsEvent = (RecordsEvent) handler.receivedEvents.stream()
.filter(e -> e.sdkEventType() == EventType.RECORDS)
.findFirst()
.orElse(null);
assertThat(recordsEvent.payload().asUtf8String()).contains("A\nC");
}
@ParameterizedTest
@MethodSource("s3AsyncClients")
public void selectObjectContent_invalidQuery_unmarshallsErrorResponse(S3AsyncClient client) {
TestHandler handler = new TestHandler();
CompletableFuture<Void> responseFuture = executeSqlQueryWithHandler("not a query", handler, client);
assertThatThrownBy(responseFuture::join).hasCauseInstanceOf(S3Exception.class);
}
private static CompletableFuture<Void> executeSqlQueryWithHandler(String query, SelectObjectContentResponseHandler handler,
S3AsyncClient client) {
InputSerialization inputSerialization = InputSerialization.builder()
.csv(CSVInput.builder().build())
.compressionType(CompressionType.NONE)
.build();
OutputSerialization outputSerialization = OutputSerialization.builder()
.csv(CSVOutput.builder().build())
.build();
SelectObjectContentRequest select = SelectObjectContentRequest.builder()
.bucket(BUCKET_NAME)
.key(KEY)
.expression(query)
.expressionType(ExpressionType.SQL)
.inputSerialization(inputSerialization)
.outputSerialization(outputSerialization)
.build();
return client.selectObjectContent(select, handler);
}
private static class TestHandler implements SelectObjectContentResponseHandler {
private SelectObjectContentResponse response;
private List<SelectObjectContentEventStream> receivedEvents = new ArrayList<>();
private Throwable exception;
@Override
public void responseReceived(SelectObjectContentResponse response) {
this.response = response;
}
@Override
public void onEventStream(SdkPublisher<SelectObjectContentEventStream> publisher) {
publisher.subscribe(receivedEvents::add);
}
@Override
public void exceptionOccurred(Throwable throwable) {
exception = throwable;
}
@Override
public void complete() {
}
}
}
| 4,472 |
0 | Create_ds/aws-sdk-java-v2/services/s3/src/it/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/services/s3/src/it/java/software/amazon/awssdk/services/BlockHoundInstalledTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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;
import static org.assertj.core.api.Assertions.assertThat;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.EventLoop;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import reactor.blockhound.BlockHound;
import reactor.blockhound.BlockingOperationError;
import reactor.blockhound.integration.BlockHoundIntegration;
import reactor.blockhound.junit.platform.BlockHoundTestExecutionListener;
import software.amazon.awssdk.testutils.service.AwsIntegrationTestBase;
import software.amazon.awssdk.testutils.service.AwsTestBase;
import software.amazon.awssdk.utils.Logger;
/**
* This test ensures that BlockHound is correctly installed for integration tests. The test is somewhat arbitrarily placed in the
* {@code s3} module in order to assert against the configuration of all service integration tests.
* <p>
* BlockHound is installed in one of two ways:
* <ol>
* <li>Using BlockHound's provided {@link BlockHoundTestExecutionListener}, which will be automatically detected by the
* JUnit 5 platform upon initialization.</li>
* <li>Manually calling {@link BlockHound#install(BlockHoundIntegration...)}. This is done as part of static initialization in
* {@link AwsIntegrationTestBase} and {@link AwsTestBase}, which most integration/stability tests extend.
* </ol>
* <p>
* This test ensures BlockHound is correctly installed by intentionally performing a blocking operation on the Netty
* {@link EventLoop} and asserting that a {@link BlockingOperationError} is thrown to forbid it.
*/
class BlockHoundInstalledTest {
private static final Logger log = Logger.loggerFor(BlockHoundInstalledTest.class);
AtomicReference<Throwable> throwableReference;
CountDownLatch latch;
EventLoopGroup bossGroup;
EventLoopGroup workerGroup;
Socket clientSocket;
Channel serverChannel;
@BeforeEach
public void setup() {
throwableReference = new AtomicReference<>();
latch = new CountDownLatch(1);
bossGroup = new NioEventLoopGroup();
workerGroup = new NioEventLoopGroup();
}
@AfterEach
public void teardown() throws Exception {
if (clientSocket != null) {
clientSocket.close();
}
if (serverChannel != null) {
serverChannel.close();
}
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
@Test
void testBlockHoundInstalled() throws Exception {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelDuplexHandler() {
@Override
public void channelActive(ChannelHandlerContext ctx) {
log.info(() -> "Preparing to sleep on the EventLoop to test if BlockHound is installed");
try {
Thread.sleep(1000);
log.info(() -> "BlockHound does not appear to be successfully installed");
} catch (Throwable t) {
log.info(() -> "BlockHound is successfully installed", t);
throwableReference.set(t);
}
latch.countDown();
ctx.fireChannelActive();
}
});
int port = getUnusedPort();
serverChannel = bootstrap.bind(port).sync().channel();
clientSocket = new Socket("localhost", port);
latch.await(5, TimeUnit.SECONDS);
assertThat(throwableReference.get())
.withFailMessage("BlockHound does not appear to be successfully installed. Ensure that either BlockHound.install() "
+ "is called prior to all test executions or that BlockHoundTestExecutionListener is available on "
+ "the class path and correctly detected by JUnit: "
+ "https://github.com/reactor/BlockHound/blob/master/docs/supported_testing_frameworks.md")
.isInstanceOf(BlockingOperationError.class);
}
private static int getUnusedPort() throws IOException {
try (ServerSocket socket = new ServerSocket(0)) {
socket.setReuseAddress(true);
return socket.getLocalPort();
}
}
}
| 4,473 |
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/GetObjectAsyncIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 software.amazon.awssdk.testutils.service.S3BucketUtils.temporaryBucketName;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import software.amazon.awssdk.core.FileTransformerConfiguration;
import software.amazon.awssdk.core.SdkResponse;
import software.amazon.awssdk.core.async.AsyncResponseTransformer;
import software.amazon.awssdk.core.async.ResponsePublisher;
import software.amazon.awssdk.core.async.SdkPublisher;
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
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.async.SimpleSubscriber;
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.testutils.RandomTempFile;
import software.amazon.awssdk.utils.ImmutableMap;
import software.amazon.awssdk.utils.Md5Utils;
public class GetObjectAsyncIntegrationTest extends S3IntegrationTestBase {
private static final String BUCKET = temporaryBucketName(GetObjectAsyncIntegrationTest.class);
private static final String KEY = "some-key";
private final GetObjectRequest getObjectRequest = GetObjectRequest.builder()
.bucket(BUCKET)
.key(KEY)
.build();
private static File file;
@BeforeClass
public static void setupFixture() throws IOException {
createBucket(BUCKET);
file = new RandomTempFile(10_000);
s3Async.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(KEY)
.build(), file.toPath());
s3Async.waiter().waitUntilObjectExists(b -> b.bucket(BUCKET).key(KEY)).join();
}
@AfterClass
public static void tearDownFixture() {
deleteBucketAndAllContents(BUCKET);
file.delete();
}
@Test
public void toFile() throws Exception {
Path path = RandomTempFile.randomUncreatedFile().toPath();
GetObjectResponse response = null;
try {
response = s3Async.getObject(getObjectRequest, path).join();
} finally {
assertEquals(Long.valueOf(path.toFile().length()), response.contentLength());
path.toFile().delete();
}
}
@Test
public void toFile_replaceExisting_shouldReplace() throws Exception {
File fileToWrite = RandomTempFile.createTempFile("temp", UUID.randomUUID().toString());
Files.write(fileToWrite.toPath(), RandomStringUtils.random(1024).getBytes(StandardCharsets.UTF_8));
GetObjectResponse response = null;
try {
AsyncResponseTransformer<GetObjectResponse, GetObjectResponse> transformer =
AsyncResponseTransformer.toFile(fileToWrite, FileTransformerConfiguration.defaultCreateOrReplaceExisting());
s3Async.getObject(getObjectRequest, transformer).join();
} finally {
assertThat(Md5Utils.md5AsBase64(fileToWrite)).isEqualTo(Md5Utils.md5AsBase64(file));
fileToWrite.delete();
}
}
@Test
public void toFile_appendExisting_shouldAppend() throws Exception {
File fileToWrite = RandomTempFile.createTempFile("temp", UUID.randomUUID().toString());
byte[] bytes = RandomStringUtils.random(1024).getBytes(StandardCharsets.UTF_8);
Files.write(fileToWrite.toPath(), bytes);
GetObjectResponse response = null;
try {
AsyncResponseTransformer<GetObjectResponse, GetObjectResponse> transformer =
AsyncResponseTransformer.toFile(fileToWrite, FileTransformerConfiguration.defaultCreateOrAppend());
response = s3Async.getObject(getObjectRequest, transformer).join();
} finally {
assertThat(fileToWrite.length()).isEqualTo(file.length() + bytes.length);
fileToWrite.delete();
}
}
@Test
public void dumpToString() throws IOException {
String returned = s3Async.getObject(getObjectRequest, AsyncResponseTransformer.toBytes()).join().asUtf8String();
assertThat(returned).isEqualTo(new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8));
}
@Test
public void toByteArray() throws IOException {
byte[] returned = s3Async.getObject(getObjectRequest, AsyncResponseTransformer.toBytes()).join().asByteArray();
assertThat(returned).isEqualTo(Files.readAllBytes(file.toPath()));
}
@Test
public void toPublisher() throws IOException {
ResponsePublisher<GetObjectResponse> responsePublisher =
s3Async.getObject(getObjectRequest, AsyncResponseTransformer.toPublisher()).join();
ByteBuffer buf = ByteBuffer.allocate(Math.toIntExact(responsePublisher.response().contentLength()));
CompletableFuture<Void> drainPublisherFuture = responsePublisher.subscribe(buf::put);
drainPublisherFuture.join();
assertThat(buf.array()).isEqualTo(Files.readAllBytes(file.toPath()));
}
@Test
public void customResponseHandler_InterceptorRecievesResponsePojo() throws Exception {
final CompletableFuture<String> cf = new CompletableFuture<>();
try (S3AsyncClient asyncWithInterceptor = createClientWithInterceptor(new AssertingExecutionInterceptor())) {
String result = asyncWithInterceptor
.getObject(getObjectRequest, new AsyncResponseTransformer<GetObjectResponse, String>() {
@Override
public CompletableFuture<String> prepare() {
return cf;
}
@Override
public void onResponse(GetObjectResponse response) {
// POJO returned by modifyResponse should be delivered to the AsyncResponseTransformer
assertThat(response.metadata()).hasEntrySatisfying("x-amz-assert",
s -> assertThat(s).isEqualTo("injected-value"));
}
@Override
public void onStream(SdkPublisher<ByteBuffer> publisher) {
publisher.subscribe(new SimpleSubscriber(b -> {
}) {
@Override
public void onComplete() {
super.onComplete();
cf.complete("result");
}
});
}
@Override
public void exceptionOccurred(Throwable throwable) {
cf.completeExceptionally(throwable);
}
}).join();
assertThat(result).isEqualTo("result");
}
}
private S3AsyncClient createClientWithInterceptor(ExecutionInterceptor assertingInterceptor) {
return s3AsyncClientBuilder()
.overrideConfiguration(ClientOverrideConfiguration.builder()
.addExecutionInterceptor(assertingInterceptor)
.build())
.build();
}
/**
* Asserts that the {@link Context.AfterUnmarshalling#response()} object is an instance of {@link GetObjectResponse}. Also
* modifies the {@link GetObjectResponse} in {@link ExecutionInterceptor#modifyResponse(Context.ModifyResponse,
* ExecutionAttributes)} so we can verify the modified POJO is delivered to the streaming response handlers for sync and
* async.
*/
public static class AssertingExecutionInterceptor implements ExecutionInterceptor {
@Override
public void afterUnmarshalling(Context.AfterUnmarshalling context, ExecutionAttributes executionAttributes) {
// The response object should be the pojo. Not the result type of the AsyncResponseTransformer
assertThat(context.response()).isInstanceOf(GetObjectResponse.class);
}
@Override
public SdkResponse modifyResponse(Context.ModifyResponse context, ExecutionAttributes executionAttributes) {
return ((GetObjectResponse) context.response())
.toBuilder()
.metadata(ImmutableMap.of("x-amz-assert", "injected-value"))
.build();
}
}
}
| 4,474 |
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/MissingUploadIdRequestTestBase.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.assertThatThrownBy;
import static software.amazon.awssdk.testutils.service.S3BucketUtils.temporaryBucketName;
import java.util.ArrayList;
import java.util.Collection;
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.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.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;
/**
* Base classes to test S3Client and S3AsyncClient upload multiple part functions.
*/
public abstract class MissingUploadIdRequestTestBase extends S3IntegrationTestBase {
private static final String BUCKET = temporaryBucketName(AsyncMissingUploadIdRequestIntegrationTest.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 completeMultipartUpload_requestMissingUploadId_throwsException() throws Exception {
String key = "completeMultipartUpload_requestMissingUploadId_throwsException";
// 1. Initiate multipartUpload request
String uploadId = initiateMultipartUpload(key);
int partCount = 1;
Collection<String> contentsToUpload = new ArrayList<>();
// 2. Upload each part
List<UploadPartResponse> uploadPartResponses = uploadParts(key, uploadId, partCount, contentsToUpload);
Collection<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
Callable<CompleteMultipartUploadResponse> completeMultipartUploadRequestCallable =
completeMultipartUpload(CompleteMultipartUploadRequest.builder()
.bucket(BUCKET)
.key(key)
.uploadId(null)
.multipartUpload(CompletedMultipartUpload.builder()
.parts(completedParts)
.build()).build());
assertThatThrownBy(completeMultipartUploadRequestCallable::call).isInstanceOf(expectedException());
}
@Test
public void abortMultipartUpload_requestMissingUploadId_throwsException() throws Exception {
String key = "abortMultipartUpload_requestMissingUploadId_throwsException";
// 1. Initiate multipartUpload request
String uploadId = initiateMultipartUpload(key);
int partCount = 3;
// 2. Upload each part
Collection<String> contentsToUpload = new ArrayList<>();
uploadParts(key, uploadId, partCount, contentsToUpload);
// 3. abort the multipart upload
Callable<AbortMultipartUploadResponse> abortMultipartUploadRequestCallable =
abortMultipartUploadResponseCallable(AbortMultipartUploadRequest.builder()
.bucket(BUCKET)
.key(key)
.uploadId(null)
.build());
assertThatThrownBy(abortMultipartUploadRequestCallable::call).isInstanceOf(expectedException());
}
@Test
public void uploadPart_requestMissingUploadId_throwsException() throws Exception {
String key = "uploadPart_requestMissingUploadId_throwsException";
// 1. Initiate multipartUpload request
initiateMultipartUpload(key);
int partCount = 1;
Collection<String> contentsToUpload = new ArrayList<>();
// 2. Upload each part
assertThatThrownBy(() -> uploadParts(key, null, partCount, contentsToUpload))
.isInstanceOf(expectedException());
}
@Test
public void listParts_requestMissingUploadId_throwsException() throws Exception {
String key = "listParts_requestMissingUploadId_throwsException";
// 1. Initiate multipartUpload request
String uploadId = initiateMultipartUpload(key);
int partCount = 1;
Collection<String> contentsToUpload = new ArrayList<>();
// 2. Upload each part
List<UploadPartResponse> uploadPartResponses = uploadParts(key, uploadId, partCount, contentsToUpload);
Collection<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. List uploaded parts
Callable<ListPartsResponse> listPartsRequestCallable = listParts(ListPartsRequest.builder()
.bucket(BUCKET)
.key(key)
.uploadId(null)
.build());
assertThatThrownBy(listPartsRequestCallable::call).isInstanceOf(expectedException());
}
private List<UploadPartResponse> uploadParts(String key, String uploadId, int partCount, Collection<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<ListPartsResponse> listParts(ListPartsRequest request);
public abstract Callable<CompleteMultipartUploadResponse> completeMultipartUpload(CompleteMultipartUploadRequest request);
public abstract Callable<AbortMultipartUploadResponse> abortMultipartUploadResponseCallable(AbortMultipartUploadRequest request);
public abstract Class<? extends Exception> expectedException();
}
| 4,475 |
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/UrlEncodingIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.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.CreateMultipartUploadResponse;
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.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.UploadPartResponse;
/**
* Integration tests for the operations that support encoding type
*/
public class UrlEncodingIntegrationTest extends S3IntegrationTestBase {
/**
* The name of the bucket created, used, and deleted by these tests.
*/
private static final String BUCKET_NAME = temporaryBucketName(UrlEncodingIntegrationTest.class);
private static final String KEY_NAME_WITH_SPECIAL_CHARS = "filename_@_=_&_?_+_)_.temp";
@BeforeClass
public static void createResources() {
createBucket(BUCKET_NAME);
s3.putObject(PutObjectRequest.builder()
.bucket(BUCKET_NAME)
.key(KEY_NAME_WITH_SPECIAL_CHARS)
.build(), RequestBody.fromString(RandomStringUtils.random(1000)));
}
/**
* Releases all resources created in this test.
*/
@AfterClass
public static void tearDown() {
deleteBucketAndAllContents(BUCKET_NAME);
}
@Test
public void listObjectVersionsWithUrlEncodingType_shouldDecode() {
ListObjectVersionsResponse listObjectVersionsResponse =
s3.listObjectVersions(b -> b.bucket(BUCKET_NAME).encodingType(EncodingType.URL));
listObjectVersionsResponse.versions().forEach(v -> assertKeyIsDecoded(v.key()));
ListObjectVersionsResponse asyncResponse =
s3Async.listObjectVersions(b -> b.bucket(BUCKET_NAME).encodingType(EncodingType.URL)).join();
asyncResponse.versions().forEach(v -> assertKeyIsDecoded(v.key()));
}
@Test
public void listObjectV2WithUrlEncodingType_shouldDecode() {
ListObjectsV2Response listObjectsV2Response =
s3.listObjectsV2(b -> b.bucket(BUCKET_NAME).encodingType(EncodingType.URL));
listObjectsV2Response.contents().forEach(c -> assertKeyIsDecoded(c.key()));
ListObjectVersionsResponse asyncResponse =
s3Async.listObjectVersions(b -> b.bucket(BUCKET_NAME).encodingType(EncodingType.URL)).join();
asyncResponse.versions().forEach(v -> assertKeyIsDecoded(v.key()));
}
@Test
public void listObjectWithUrlEncodingType_shouldDecode() {
ListObjectsResponse listObjectsV2Response =
s3.listObjects(b -> b.bucket(BUCKET_NAME).encodingType(EncodingType.URL));
listObjectsV2Response.contents().forEach(c -> assertKeyIsDecoded(c.key()));
ListObjectVersionsResponse asyncResponse =
s3Async.listObjectVersions(b -> b.bucket(BUCKET_NAME).encodingType(EncodingType.URL)).join();
asyncResponse.versions().forEach(v -> assertKeyIsDecoded(v.key()));
}
@Test
public void listMultipartUploadsWithUrlEncodingType_shouldDecode() {
String uploaddId = null;
try {
CreateMultipartUploadResponse multipartUploadResponse =
s3.createMultipartUpload(b -> b.bucket(BUCKET_NAME).key(KEY_NAME_WITH_SPECIAL_CHARS));
uploaddId = multipartUploadResponse.uploadId();
String finalUploadId = uploaddId;
UploadPartResponse uploadPartResponse = s3.uploadPart(b -> b.bucket(BUCKET_NAME)
.key(KEY_NAME_WITH_SPECIAL_CHARS)
.partNumber(1)
.uploadId(finalUploadId),
RequestBody.fromString(RandomStringUtils.random(1000)));
ListMultipartUploadsResponse listMultipartUploadsResponse =
s3.listMultipartUploads(b -> b.encodingType(EncodingType.URL).bucket(BUCKET_NAME));
listMultipartUploadsResponse.uploads().forEach(upload -> assertThat(upload.key()).isEqualTo(KEY_NAME_WITH_SPECIAL_CHARS));
ListMultipartUploadsResponse asyncListMultipartUploadsResponse =
s3Async.listMultipartUploads(b -> b.encodingType(EncodingType.URL).bucket(BUCKET_NAME)).join();
asyncListMultipartUploadsResponse.uploads().forEach(upload -> assertKeyIsDecoded(upload.key()));
} finally {
if (uploaddId != null) {
String finalUploadId = uploaddId;
s3.abortMultipartUpload(b -> b.bucket(BUCKET_NAME).key(KEY_NAME_WITH_SPECIAL_CHARS).uploadId(finalUploadId));
}
}
}
private void assertKeyIsDecoded(String key) {
assertThat(key).isEqualTo(KEY_NAME_WITH_SPECIAL_CHARS);
}
}
| 4,476 |
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/BucketAccelerateIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 software.amazon.awssdk.testutils.service.S3BucketUtils.temporaryBucketName;
import java.io.File;
import java.util.List;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
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.regions.Region;
import software.amazon.awssdk.services.s3.model.AccelerateConfiguration;
import software.amazon.awssdk.services.s3.model.BucketAccelerateStatus;
import software.amazon.awssdk.services.s3.model.BucketVersioningStatus;
import software.amazon.awssdk.services.s3.model.DeleteBucketTaggingRequest;
import software.amazon.awssdk.services.s3.model.GetBucketAccelerateConfigurationRequest;
import software.amazon.awssdk.services.s3.model.GetBucketTaggingRequest;
import software.amazon.awssdk.services.s3.model.GetBucketVersioningRequest;
import software.amazon.awssdk.services.s3.model.ListBucketsRequest;
import software.amazon.awssdk.services.s3.model.PutBucketAccelerateConfigurationRequest;
import software.amazon.awssdk.services.s3.model.PutBucketTaggingRequest;
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.VersioningConfiguration;
import software.amazon.awssdk.testutils.RandomTempFile;
import software.amazon.awssdk.testutils.retry.AssertCallable;
import software.amazon.awssdk.testutils.retry.RetryableAssertion;
import software.amazon.awssdk.testutils.retry.RetryableParams;
/**
* Integration tests for S3 bucket accelerate configuration.
*/
public class BucketAccelerateIntegrationTest extends S3IntegrationTestBase {
private static final String US_BUCKET_NAME = temporaryBucketName("s3-accelerate-us-east-1");
private static final String KEY_NAME = "key";
private static S3Client accelerateClient;
@BeforeClass
public static void setup() throws Exception {
S3IntegrationTestBase.setUp();
accelerateClient = S3Client.builder()
.region(Region.US_WEST_2)
.credentialsProvider(CREDENTIALS_PROVIDER_CHAIN)
.serviceConfiguration(S3Configuration.builder()
.accelerateModeEnabled(true)
.build())
.overrideConfiguration(o -> o.addExecutionInterceptor(new AccelerateValidatingInterceptor()))
.build();
setUpBuckets();
}
@AfterClass
public static void cleanup() {
deleteBucketAndAllContents(US_BUCKET_NAME);
}
private static void setUpBuckets() {
createBucket(US_BUCKET_NAME);
}
@Test
public void testUpdateAccelerateConfiguration() throws InterruptedException {
String status = s3.getBucketAccelerateConfiguration(GetBucketAccelerateConfigurationRequest.builder()
.bucket(US_BUCKET_NAME)
.build())
.statusAsString();
if (status == null || !status.equals("Enabled")) {
enableAccelerateOnBucket();
}
assertEquals(
BucketAccelerateStatus.ENABLED,
s3.getBucketAccelerateConfiguration(GetBucketAccelerateConfigurationRequest.builder()
.bucket(US_BUCKET_NAME)
.build())
.status());
disableAccelerateOnBucket();
assertEquals(BucketAccelerateStatus.SUSPENDED,
s3.getBucketAccelerateConfiguration(GetBucketAccelerateConfigurationRequest.builder()
.bucket(US_BUCKET_NAME)
.build())
.status());
}
@Test
public void testAccelerateEndpoint() throws Exception {
String status = s3.getBucketAccelerateConfiguration(GetBucketAccelerateConfigurationRequest.builder()
.bucket(US_BUCKET_NAME)
.build())
.statusAsString();
if (status == null || !status.equals("Enabled")) {
enableAccelerateOnBucket();
}
// PutObject
File uploadFile = new RandomTempFile(KEY_NAME, 1000);
try {
accelerateClient.putObject(PutObjectRequest.builder()
.bucket(US_BUCKET_NAME)
.key(KEY_NAME)
.build(),
RequestBody.fromFile(uploadFile));
} catch (Exception e) {
// We really only need to verify the request is using the accelerate endpoint
}
}
private void enableAccelerateOnBucket() throws InterruptedException {
s3.putBucketAccelerateConfiguration(
PutBucketAccelerateConfigurationRequest.builder()
.bucket(US_BUCKET_NAME)
.accelerateConfiguration(AccelerateConfiguration.builder()
.status(BucketAccelerateStatus.ENABLED)
.build())
.build());
// Wait a bit for accelerate to kick in
Thread.sleep(1000);
}
private void disableAccelerateOnBucket() {
s3.putBucketAccelerateConfiguration(
PutBucketAccelerateConfigurationRequest.builder()
.bucket(US_BUCKET_NAME)
.accelerateConfiguration(AccelerateConfiguration.builder()
.status(BucketAccelerateStatus.SUSPENDED)
.build())
.build());
}
@Test
public void testUnsupportedOperationsUnderAccelerateMode() {
try {
accelerateClient.listBuckets(ListBucketsRequest.builder().build());
} catch (Exception e) {
throw e;
//fail("Exception is not expected!");
}
}
private static final class AccelerateValidatingInterceptor implements ExecutionInterceptor {
@Override
public void beforeTransmission(Context.BeforeTransmission context, ExecutionAttributes executionAttributes) {
if (!(context.request() instanceof ListBucketsRequest)) {
assertEquals(context.httpRequest().host(), US_BUCKET_NAME + ".s3-accelerate.amazonaws.com");
}
}
}
}
| 4,477 |
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/UserMetadataIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
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.HeadObjectRequest;
import software.amazon.awssdk.services.s3.model.HeadObjectResponse;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.testutils.RandomTempFile;
public class UserMetadataIntegrationTest extends S3IntegrationTestBase {
/**
* The S3 bucket created and used by these tests.
*/
private static final String BUCKET_NAME = temporaryBucketName("user-metadata-integ-test");
private static final String KEY = "UserMetadataIntegrationTest";
/**
* Length of the data uploaded to S3.
*/
private static final long CONTENT_LENGTH = 345L;
/**
* The file of random data uploaded to S3.
*/
private static File file;
/**
* Creates/populates all the test data needed for these tests (bucket,
* source object, file, source object ETag, etc).
*/
@BeforeClass
public static void initializeTestData() throws Exception {
createBucket(BUCKET_NAME);
file = new RandomTempFile("user-metadata-integ-test-" + new Date().getTime(), CONTENT_LENGTH);
s3.putObject(PutObjectRequest.builder()
.bucket(BUCKET_NAME)
.key(KEY)
.build(), file.toPath());
}
@AfterClass
public static void deleteAllBuckets() {
deleteBucketAndAllContents(BUCKET_NAME);
}
@Test
public void putObject_PutsUserMetadata() throws Exception {
Map<String, String> userMetadata = new HashMap<>();
userMetadata.put("thing1", "IAmThing1");
userMetadata.put("thing2", "IAmThing2");
String mixedCasePrefix = "x-AmZ-mEtA-";
String metadataKey = "test";
final String key = "user-metadata-key";
s3.putObject(PutObjectRequest.builder()
.bucket(BUCKET_NAME)
.key(key)
.metadata(userMetadata)
.overrideConfiguration(b -> b.putHeader(mixedCasePrefix + metadataKey, "test"))
.build(),
RequestBody.fromFile(file));
HeadObjectResponse response = s3.headObject(HeadObjectRequest.builder()
.bucket(BUCKET_NAME)
.key(key)
.build());
Map<String, String> returnedMetadata = response.metadata();
assertThat(returnedMetadata).containsAllEntriesOf(userMetadata);
assertThat(returnedMetadata).containsKey(metadataKey);
}
}
| 4,478 |
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/EmptyQueryStringSignerIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.junit.Test;
public class EmptyQueryStringSignerIntegrationTest extends S3IntegrationTestBase {
@Test
public void emptyQueryStringsDoNotThrowSignatureMismatch() {
s3.listBuckets(r -> r.overrideConfiguration(c -> c.putRawQueryParameter("", (String) null)));
s3.listBuckets(r -> r.overrideConfiguration(c -> c.putRawQueryParameter("", "foo")));
s3.listBuckets(r -> r.overrideConfiguration(c -> c.putRawQueryParameter("", "")));
}
}
| 4,479 |
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/AsyncInOutStreamIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 java.io.IOException;
import java.io.OutputStream;
import java.util.concurrent.CompletableFuture;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import software.amazon.awssdk.core.ResponseInputStream;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.core.async.AsyncResponseTransformer;
import software.amazon.awssdk.core.async.BlockingOutputStreamAsyncRequestBody;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.testutils.service.S3BucketUtils;
/**
* Test InputStream and OutputStream operations on AsyncRequestBody and AsyncResponseTransformer against S3.
*/
public class AsyncInOutStreamIntegrationTest extends S3IntegrationTestBase {
private static final String BUCKET = S3BucketUtils.temporaryBucketName("async-in-out-stream");
/**
* Creates all the test resources for the tests.
*/
@BeforeClass
public static void createResources() {
createBucket(BUCKET);
}
/**
* Releases all resources created in this test.
*/
@AfterClass
public static void tearDown() {
deleteBucketAndAllContents(BUCKET);
}
@Test
public void largeFilePutGet() throws IOException {
long length = 4 * 1024 * 1024; // 4 MB
BlockingOutputStreamAsyncRequestBody body = AsyncRequestBody.forBlockingOutputStream(length);
CompletableFuture<?> response = s3Async.putObject(r -> r.bucket(BUCKET).key("foo"), body);
try (OutputStream os = body.outputStream()) {
for (int i = 0; i < length; i++) {
os.write(i % 255);
}
}
response.join();
try (ResponseInputStream<GetObjectResponse> is =
s3Async.getObject(r -> r.bucket(BUCKET).key("foo"),
AsyncResponseTransformer.toBlockingInputStream())
.join()) {
assertThat(is.response().contentLength()).isEqualTo(length);
for (int i = 0; i < length; i++) {
assertThat(is.read()).isEqualTo(i % 255);
}
}
}
}
| 4,480 |
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/ListObjectsV2PaginatorsIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.equalTo;
import static org.junit.Assert.fail;
import static software.amazon.awssdk.testutils.service.S3BucketUtils.temporaryBucketName;
import io.reactivex.Flowable;
import io.reactivex.Single;
import java.io.File;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.Stream;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
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.services.s3.paginators.ListObjectsV2Iterable;
import software.amazon.awssdk.services.s3.paginators.ListObjectsV2Publisher;
import software.amazon.awssdk.testutils.RandomTempFile;
public class ListObjectsV2PaginatorsIntegrationTest extends S3IntegrationTestBase {
private static final long OBJECT_COUNT = 15;
/**
* Content length for sample keys created by these tests.
*/
private static final long CONTENT_LENGTH = 123;
/**
* The name of the bucket created, used, and deleted by these tests.
*/
private static String bucketName = temporaryBucketName("list-objects-v2-integ-test");
private static String emptyBucketName = temporaryBucketName("list-objects-integ-test-emptybucket");
/**
* List of all keys created by these tests.
*/
private static List<String> keys = new ArrayList<>();
private static final ListObjectsV2Request.Builder requestBuilder = ListObjectsV2Request.builder().maxKeys(3);
/**
* Releases all resources created in this test.
*/
@AfterClass
public static void tearDown() {
deleteBucketAndAllContents(bucketName);
deleteBucketAndAllContents(emptyBucketName);
}
/**
* Creates all the test resources for the tests.
*/
@BeforeClass
public static void createResources() throws Exception {
createBucket(bucketName);
createBucket(emptyBucketName);
NumberFormat numberFormatter = new DecimalFormat("##00");
for (int i = 1; i <= OBJECT_COUNT; i++) {
createKey("key-" + numberFormatter.format(i));
}
}
/**
* 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);
}
@Test
public void test_SyncResponse_onEmptyBucket() {
ListObjectsV2Iterable iterable = s3.listObjectsV2Paginator(requestBuilder.bucket(emptyBucketName).build());
assertThat(iterable.contents().stream().count(), equalTo(0L));
assertThat(iterable.stream()
.flatMap(r -> r.contents() != null ? r.contents().stream() : Stream.empty())
.count(),
equalTo(0L));
}
@Test
public void test_SyncResponse_onNonEmptyBucket() {
ListObjectsV2Iterable iterable = s3.listObjectsV2Paginator(requestBuilder.bucket(bucketName).build());
assertThat(iterable.contents().stream().count(), equalTo(OBJECT_COUNT));
assertThat(iterable.stream().flatMap(r -> r.contents().stream()).count(), equalTo(OBJECT_COUNT));
}
@Test
public void test_AsyncResponse_OnNonEmptyBucket() throws ExecutionException, InterruptedException {
ListObjectsV2Publisher publisher = s3Async.listObjectsV2Paginator(requestBuilder.bucket(bucketName).build());
publisher.subscribe(new Subscriber<ListObjectsV2Response>() {
private Subscription subscription;
private int keyCount;
@Override
public void onSubscribe(Subscription s) {
subscription = s;
keyCount = 0;
subscription.request(2);
}
@Override
public void onNext(ListObjectsV2Response response) {
keyCount += response.keyCount();
subscription.request(1);
subscription.request(2);
}
@Override
public void onError(Throwable t) {
fail("Error receiving response" + t.getMessage());
}
@Override
public void onComplete() {
assertThat(keyCount, equalTo(OBJECT_COUNT));
}
});
Thread.sleep(3_000);
// count objects using forEach
final long[] count = {0};
CompletableFuture<Void> future = publisher.subscribe(response -> {
count[0] += response.keyCount();
});
future.get();
assertThat(count[0], equalTo(OBJECT_COUNT));
// Use ForEach: collect objects into a list
List<S3Object> objects = new ArrayList<>();
CompletableFuture<Void> future2 = publisher.subscribe(response -> {
objects.addAll(response.contents());
});
future2.get();
assertThat(Long.valueOf(objects.size()), equalTo(OBJECT_COUNT));
}
@Test
public void test_AsyncResponse_OnEmptyBucket() throws ExecutionException, InterruptedException {
ListObjectsV2Publisher publisher = s3Async.listObjectsV2Paginator(requestBuilder.bucket(emptyBucketName).build());
final int[] count = {0};
CompletableFuture<Void> future = publisher.subscribe(response -> {
count[0] += response.keyCount();
});
future.get();
assertThat(count[0], equalTo(0));
}
@Test
public void test_AsyncResponse_UsingRxJava() {
ListObjectsV2Publisher publisher = s3Async.listObjectsV2Paginator(requestBuilder.bucket(bucketName).build());
Single<List<S3Object>> objects = Flowable.fromPublisher(publisher)
.flatMapIterable(ListObjectsV2Response::contents)
.toList();
// There are multiple fluent methods to convert Single type to a different form
List<S3Object> objectList = objects.blockingGet();
assertThat(Long.valueOf(objectList.size()), equalTo(OBJECT_COUNT));
}
private class TestSubscriber implements Subscriber<ListObjectsV2Response> {
private Subscription subscription;
private ListObjectsV2Response lastPage;
private final long requestCount;
private long keyCount;
private long requestsCompleted;
private boolean isDone;
public TestSubscriber(long requestCount) {
this.requestCount = requestCount;
}
@Override
public void onSubscribe(Subscription s) {
subscription = s;
subscription.request(requestCount);
}
@Override
public void onNext(ListObjectsV2Response response) {
lastPage = response;
keyCount += response.keyCount();
requestsCompleted++;
}
@Override
public void onError(Throwable t) {
fail("Error receiving response" + t.getMessage());
}
@Override
public void onComplete() {
isDone = true;
}
public long getKeyCount() {
return keyCount;
}
public ListObjectsV2Response getLastPage() {
return lastPage;
}
public boolean isDone() {
return isDone || requestCount == requestsCompleted;
}
}
}
| 4,481 |
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/AsyncServerSideEncryptionIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 software.amazon.awssdk.services.s3.model.ServerSideEncryption.AES256;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Base64;
import java.util.UUID;
import org.junit.Test;
import software.amazon.awssdk.core.async.AsyncResponseTransformer;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.ServerSideEncryption;
import software.amazon.awssdk.testutils.SdkAsserts;
import software.amazon.awssdk.utils.Md5Utils;
public class AsyncServerSideEncryptionIntegrationTest extends ServerSideEncryptionIntegrationTestBase {
@Test
public void sse_AES256_succeeds() throws FileNotFoundException {
String key = UUID.randomUUID().toString();
PutObjectRequest request = PutObjectRequest.builder()
.key(key)
.bucket(BUCKET)
.serverSideEncryption(AES256)
.build();
s3Async.putObject(request, file.toPath()).join();
GetObjectRequest getObjectRequest = GetObjectRequest.builder()
.key(key)
.bucket(BUCKET)
.build();
verifyGetResponse(getObjectRequest);
}
@Test
public void sse_AWSKMS_succeeds() throws FileNotFoundException {
String key = UUID.randomUUID().toString();
PutObjectRequest request = PutObjectRequest.builder()
.key(key)
.bucket(BUCKET)
.serverSideEncryption(ServerSideEncryption.AWS_KMS)
.build();
s3Async.putObject(request, file.toPath()).join();
GetObjectRequest getObjectRequest = GetObjectRequest.builder()
.key(key)
.bucket(BUCKET)
.build();
verifyGetResponse(getObjectRequest);
}
@Test
public void sse_customerManaged_succeeds() throws FileNotFoundException {
String key = UUID.randomUUID().toString();
byte[] secretKey = generateSecretKey();
String b64Key = Base64.getEncoder().encodeToString(secretKey);
String b64KeyMd5 = Md5Utils.md5AsBase64(secretKey);
PutObjectRequest request = PutObjectRequest.builder()
.key(key)
.bucket(BUCKET)
.sseCustomerKey(b64Key)
.sseCustomerAlgorithm(AES256.name())
.sseCustomerKeyMD5(b64KeyMd5)
.build();
s3Async.putObject(request, file.toPath()).join();
GetObjectRequest getObjectRequest = GetObjectRequest.builder()
.key(key)
.bucket(BUCKET)
.sseCustomerKey(b64Key)
.sseCustomerAlgorithm(AES256.name())
.sseCustomerKeyMD5(b64KeyMd5)
.build();
verifyGetResponse(getObjectRequest);
}
@Test
public void sse_onBucket_succeeds() throws FileNotFoundException {
String key = UUID.randomUUID().toString();
PutObjectRequest request = PutObjectRequest.builder()
.key(key)
.bucket(BUCKET_WITH_SSE)
.build();
s3Async.putObject(request, file.toPath()).join();
GetObjectRequest getObjectRequest = GetObjectRequest.builder()
.key(key)
.bucket(BUCKET_WITH_SSE)
.build();
verifyGetResponse(getObjectRequest);
}
private void verifyGetResponse(GetObjectRequest getObjectRequest) throws FileNotFoundException {
String response = s3Async.getObject(getObjectRequest, AsyncResponseTransformer.toBytes()).join().asUtf8String();
SdkAsserts.assertStringEqualsStream(response, new FileInputStream(file));
}
}
| 4,482 |
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/GetObjectIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 software.amazon.awssdk.testutils.service.S3BucketUtils.temporaryBucketName;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Properties;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import software.amazon.awssdk.core.ResponseInputStream;
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
import software.amazon.awssdk.core.interceptor.ExecutionInterceptor;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.core.sync.ResponseTransformer;
import software.amazon.awssdk.services.s3.GetObjectAsyncIntegrationTest.AssertingExecutionInterceptor;
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.testutils.RandomTempFile;
public class GetObjectIntegrationTest extends S3IntegrationTestBase {
private static final String BUCKET = temporaryBucketName(GetObjectIntegrationTest.class);
private static final String KEY = "some-key";
private static final String PROPERTY_KEY = "properties";
private final GetObjectRequest getObjectRequest = GetObjectRequest.builder()
.bucket(BUCKET)
.key(KEY)
.build();
private static File file;
@BeforeClass
public static void setupFixture() throws IOException {
createBucket(BUCKET);
file = new RandomTempFile(10_000);
s3.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(KEY)
.build(), file.toPath());
}
@AfterClass
public static void tearDownFixture() {
deleteBucketAndAllContents(BUCKET);
file.delete();
}
@Test
public void toInputStream() throws Exception {
try (ResponseInputStream<GetObjectResponse> content = s3.getObject(getObjectRequest)) {
}
}
@Test
public void toInputStream_loadFromProperties() throws IOException {
s3.putObject(b -> b.bucket(BUCKET).key(PROPERTY_KEY), RequestBody.fromString("test: test"));
try (ResponseInputStream<GetObjectResponse> object = s3.getObject(b -> b.bucket(BUCKET).key(PROPERTY_KEY),
ResponseTransformer.toInputStream())) {
Properties properties = new Properties();
properties.load(object);
assertThat(properties.getProperty("test")).isEqualTo("test");
}
}
@Test
public void toFile() throws Exception {
Path path = RandomTempFile.randomUncreatedFile().toPath();
GetObjectResponse response = null;
try {
response = s3.getObject(getObjectRequest, path);
} finally {
assertEquals(Long.valueOf(path.toFile().length()), response.contentLength());
path.toFile().delete();
}
}
@Test
public void toOutputStream() throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GetObjectResponse response = s3.getObject(getObjectRequest, ResponseTransformer.toOutputStream(baos));
}
@Test
public void customResponseHandler_InterceptorRecievesResponsePojo() throws Exception {
try (S3Client clientWithInterceptor = createClientWithInterceptor(new AssertingExecutionInterceptor())) {
String result = clientWithInterceptor.getObject(getObjectRequest, (resp, in) -> {
assertThat(resp.metadata()).hasEntrySatisfying("x-amz-assert",
s -> assertThat(s).isEqualTo("injected-value"));
return "result";
});
assertThat(result).isEqualTo("result");
}
}
@Test
public void contentRangeIsReturnedForRangeRequests() {
ResponseInputStream<GetObjectResponse> stream = s3.getObject(getObjectRequest.copy(r -> r.range("bytes=0-1")));
stream.abort();
assertThat(stream.response().contentRange()).isEqualTo("bytes 0-1/10000");
}
private S3Client createClientWithInterceptor(ExecutionInterceptor interceptor) {
return s3ClientBuilder().overrideConfiguration(ClientOverrideConfiguration.builder()
.addExecutionInterceptor(interceptor)
.build())
.build();
}
}
| 4,483 |
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/UploadLargeObjectIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 software.amazon.awssdk.testutils.service.S3BucketUtils.temporaryBucketName;
import java.io.File;
import java.io.IOException;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import software.amazon.awssdk.core.ResponseInputStream;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.testutils.RandomTempFile;
import software.amazon.awssdk.utils.IoUtils;
public class UploadLargeObjectIntegrationTest extends S3IntegrationTestBase {
private static final String BUCKET = temporaryBucketName(UploadLargeObjectIntegrationTest.class);
private static final String ASYNC_KEY = "async-key";
private static final String SYNC_KEY = "sync-key";
private static File file;
@BeforeClass
public static void setupFixture() throws IOException {
createBucket(BUCKET);
file = new RandomTempFile(500 * 1024 * 1024);
}
@AfterClass
public static void tearDownFixture() {
deleteBucketAndAllContents(BUCKET);
file.delete();
}
@Test
public void syncPutLargeObject() {
s3.putObject(b -> b.bucket(BUCKET).key(SYNC_KEY), file.toPath());
verifyResponse(SYNC_KEY);
}
@Test
public void asyncPutLargeObject() {
s3Async.putObject(b -> b.bucket(BUCKET).key(ASYNC_KEY), file.toPath()).join();
verifyResponse(ASYNC_KEY);
}
private void verifyResponse(String key) {
ResponseInputStream<GetObjectResponse> responseInputStream = s3.getObject(b -> b.bucket(BUCKET).key(key));
IoUtils.drainInputStream(responseInputStream);
}
}
| 4,484 |
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/MissingUploadIdRequestIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.exception.SdkClientException;
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.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 MissingUploadIdRequestIntegrationTest extends MissingUploadIdRequestTestBase {
@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<ListPartsResponse> listParts(ListPartsRequest request) {
return () -> s3.listParts(request);
}
@Override
public Callable<CompleteMultipartUploadResponse> completeMultipartUpload(CompleteMultipartUploadRequest request) {
return () -> s3.completeMultipartUpload(request);
}
@Override
public Callable<AbortMultipartUploadResponse> abortMultipartUploadResponseCallable(AbortMultipartUploadRequest request) {
return () -> s3.abortMultipartUpload(request);
}
@Override
public Class<? extends Exception> expectedException() {
return SdkClientException.class;
}
}
| 4,485 |
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/SignedAsyncRequestBodyUploadIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static software.amazon.awssdk.core.client.config.SdkAdvancedClientOption.SIGNER;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
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.AsyncAws4Signer;
import software.amazon.awssdk.core.async.AsyncRequestBody;
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.signer.AsyncSigner;
import software.amazon.awssdk.core.signer.Signer;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpHeaders;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.utils.S3TestUtils;
/**
* This is an integration test to verify that {@link AsyncAws4Signer} is able to correctly sign async requests that
* have a streaming payload.
*/
public class SignedAsyncRequestBodyUploadIntegrationTest extends S3IntegrationTestBase {
private static final String BUCKET = "signed-body-test-" + System.currentTimeMillis();
private static S3AsyncClient testClient;
private static TestSigner mockSigner;
private static final CapturingInterceptor capturingInterceptor = new CapturingInterceptor();
@BeforeClass
public static void setup() throws Exception {
S3IntegrationTestBase.setUp();
// Use a mock so we can introspect easily to verify that the signer was used for the request
mockSigner = mock(TestSigner.class);
AsyncAws4Signer realSigner = AsyncAws4Signer.create();
when(mockSigner.sign(any(SdkHttpFullRequest.class), any(AsyncRequestBody.class), any(ExecutionAttributes.class)))
.thenAnswer(i -> {
SdkHttpFullRequest request = i.getArgument(0, SdkHttpFullRequest.class);
AsyncRequestBody body = i.getArgument(1, AsyncRequestBody.class);
ExecutionAttributes executionAttributes = i.getArgument(2, ExecutionAttributes.class);
return realSigner.sign(request, body, executionAttributes);
});
testClient = s3AsyncClientBuilder()
.overrideConfiguration(o -> o
.putAdvancedOption(SIGNER, mockSigner)
.addExecutionInterceptor(capturingInterceptor))
.build();
createBucket(BUCKET);
}
@AfterClass
public static void teardown() {
S3TestUtils.deleteBucketAndAllContents(s3, BUCKET);
s3.close();
s3Async.close();
testClient.close();
}
@Before
public void methodSetup() {
capturingInterceptor.reset();
}
@Test
public void test_putObject_bodyIsSigned_succeeds() {
PutObjectRequest request = PutObjectRequest.builder()
.bucket(BUCKET).key("test.txt")
// Instructs the signer to include the SHA-256 of the body as a header; bit weird but that's how it's
// done
// See https://github.com/aws/aws-sdk-java-v2/blob/aeb4b5853c8f833f266110f1e01d6e10ea6ac1c5/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal/AbstractAws4Signer.java#L75-L77
.overrideConfiguration(o -> o.putHeader("x-amz-content-sha256", "required"))
.build();
testClient.putObject(request, AsyncRequestBody.fromString("Hello S3")).join();
// Ensure that the client used our signer
verify(mockSigner, atLeastOnce()).sign(
any(SdkHttpFullRequest.class), any(AsyncRequestBody.class), any(ExecutionAttributes.class));
List<String> capturedSha256Values = capturingInterceptor.capturedRequests().stream()
.map(SdkHttpHeaders::headers)
.map(m -> m.getOrDefault("x-amz-content-sha256", Collections.emptyList()))
.flatMap(Collection::stream)
.collect(Collectors.toList());
assertThat(capturedSha256Values)
// echo -n 'Hello S3' | shasum -a 256
.containsExactly("c9f7ed78c073c16bcb2f76fa4a5739cb6cf81677d32fdbeda1d69350d107b6f3");
}
private interface TestSigner extends AsyncSigner, Signer {
}
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;
}
}
}
| 4,486 |
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/GetObjectFaultIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.fail;
import static software.amazon.awssdk.testutils.service.S3BucketUtils.temporaryBucketName;
import java.time.Duration;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
import software.amazon.awssdk.core.exception.ApiCallTimeoutException;
import software.amazon.awssdk.core.exception.NonRetryableException;
import software.amazon.awssdk.core.exception.RetryableException;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.core.sync.ResponseTransformer;
import software.amazon.awssdk.http.AbortableInputStream;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
public class GetObjectFaultIntegrationTest extends S3IntegrationTestBase {
private static final String BUCKET = temporaryBucketName(GetObjectFaultIntegrationTest.class);
private static final String KEY = "some-key";
private static S3Client s3ClientWithTimeout;
@BeforeClass
public static void setupFixture() {
createBucket(BUCKET);
s3.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(KEY)
.build(), RequestBody.fromString("some contents"));
s3ClientWithTimeout = s3ClientBuilder()
.overrideConfiguration(ClientOverrideConfiguration.builder()
.apiCallTimeout(Duration.ofSeconds(5))
.build())
.build();
}
@AfterClass
public static void tearDownFixture() {
deleteBucketAndAllContents(BUCKET);
}
@Test
public void handlerThrowsRetryableException_RetriedUpToLimit() throws Exception {
RequestCountingResponseTransformer<GetObjectResponse, ?> handler = new RequestCountingResponseTransformer<>(
(resp, in) -> {
throw RetryableException.builder().build();
});
assertThatThrownBy(() -> s3.getObject(getObjectRequest(), handler))
.isInstanceOf(SdkClientException.class);
assertThat(handler.currentCallCount()).isEqualTo(4);
}
@Test
public void handlerThrowsNonRetryableException_RequestNotRetried() throws Exception {
RequestCountingResponseTransformer<GetObjectResponse, ?> handler = new RequestCountingResponseTransformer<>(
(resp, in) -> {
throw NonRetryableException.builder().build();
});
assertThatThrownBy(() -> s3.getObject(getObjectRequest(), handler))
.isInstanceOf(SdkClientException.class);
assertThat(handler.currentCallCount()).isEqualTo(1);
}
@Test
public void slowHandlerIsInterrupted() throws Exception {
RequestCountingResponseTransformer<GetObjectResponse, ?> handler = new RequestCountingResponseTransformer<>(
(resp, in) -> {
try {
Thread.sleep(10_000);
fail("Expected Interrupted Exception");
} catch (InterruptedException ie) {
throw ie;
}
return null;
});
assertThatThrownBy(() -> s3ClientWithTimeout.getObject(getObjectRequest(), handler))
.isInstanceOf(ApiCallTimeoutException.class);
assertThat(handler.currentCallCount()).isEqualTo(1);
}
/**
* Customers should be able to just re-interrupt the current thread instead of having to throw {@link InterruptedException}.
*/
@Test
public void slowHandlerIsInterrupted_SetsInterruptFlag() throws Exception {
RequestCountingResponseTransformer<GetObjectResponse, ?> handler = new RequestCountingResponseTransformer<>(
(resp, in) -> {
try {
Thread.sleep(10_000);
fail("Expected Interrupted Exception");
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
throw new RuntimeException("Interrupted");
}
return null;
});
assertThatThrownBy(() -> s3ClientWithTimeout.getObject(getObjectRequest(), handler))
.isInstanceOf(ApiCallTimeoutException.class);
assertThat(handler.currentCallCount()).isEqualTo(1);
assertThat(Thread.currentThread().isInterrupted()).isFalse();
}
/**
* If a response handler does not preserve the interrupt status or throw an {@link InterruptedException} then
* we can't translate the exception to a {@link ApiCallTimeoutException}.
*/
@Test
public void handlerSquashsInterrupt_DoesNotThrowClientTimeoutException() throws Exception {
RequestCountingResponseTransformer<GetObjectResponse, ?> handler = new RequestCountingResponseTransformer<>(
(resp, in) -> {
try {
Thread.sleep(10_000);
fail("Expected Interrupted Exception");
} catch (InterruptedException ie) {
throw new RuntimeException(ie);
}
return null;
});
assertThatThrownBy(() -> s3ClientWithTimeout.getObject(getObjectRequest(), handler))
.isNotInstanceOf(ApiCallTimeoutException.class);
assertThat(handler.currentCallCount()).isEqualTo(1);
assertThat(Thread.currentThread().isInterrupted()).isFalse();
}
private GetObjectRequest getObjectRequest() {
return GetObjectRequest.builder()
.bucket(BUCKET)
.key(KEY)
.build();
}
/**
* Wrapper around a {@link ResponseTransformer} that counts how many times it's been invoked.
*/
private static class RequestCountingResponseTransformer<ResponseT, ReturnT>
implements ResponseTransformer<ResponseT, ReturnT> {
private final ResponseTransformer<ResponseT, ReturnT> delegate;
private final AtomicInteger callCount = new AtomicInteger(0);
private RequestCountingResponseTransformer(ResponseTransformer<ResponseT, ReturnT> delegate) {
this.delegate = delegate;
}
@Override
public ReturnT transform(ResponseT response, AbortableInputStream inputStream) throws Exception {
callCount.incrementAndGet();
return delegate.transform(response, inputStream);
}
@Override
public boolean needsConnectionLeftOpen() {
return delegate.needsConnectionLeftOpen();
}
public int currentCallCount() {
return callCount.get();
}
}
}
| 4,487 |
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/OperationsWithNonStandardResponsesIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static software.amazon.awssdk.testutils.service.S3BucketUtils.temporaryBucketName;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import software.amazon.awssdk.core.auth.policy.Action;
import software.amazon.awssdk.core.auth.policy.Policy;
import software.amazon.awssdk.core.auth.policy.Principal;
import software.amazon.awssdk.core.auth.policy.Resource;
import software.amazon.awssdk.core.auth.policy.Statement;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.model.BucketLocationConstraint;
import software.amazon.awssdk.services.s3.model.DeleteBucketRequest;
import software.amazon.awssdk.services.s3.model.GetBucketLocationRequest;
import software.amazon.awssdk.services.s3.model.GetBucketPolicyRequest;
import software.amazon.awssdk.services.s3.model.GetBucketRequestPaymentRequest;
import software.amazon.awssdk.services.s3.model.Payer;
import software.amazon.awssdk.services.s3.model.PutBucketPolicyRequest;
public final class OperationsWithNonStandardResponsesIntegrationTest extends S3IntegrationTestBase {
/**
* The name of the bucket created, used, and deleted by these tests.
*/
private static String bucketName = temporaryBucketName("single-string-integ-test");
@BeforeClass
public static void setupSuite() {
createBucket(bucketName);
}
@AfterClass
public static void cleanup() {
s3.deleteBucket(DeleteBucketRequest.builder().bucket(bucketName).build());
}
@Test
public void getBucketLocationReturnsAResult() {
GetBucketLocationRequest request = GetBucketLocationRequest.builder().bucket(bucketName).build();
assertThat(s3.getBucketLocation(request).locationConstraint()).isEqualTo(BucketLocationConstraint.US_WEST_2);
}
@Test
public void getBucketLocation_withArn_throwsErrorMessageToUseBucketNameInstead() {
String bucketArn = "arn:aws:s3:::mybucket";
SdkClientException exception = assertThrows(SdkClientException.class,
() -> s3.getBucketLocation(b-> b.bucket(bucketArn).build()));
assertEquals(exception.getMessage(), "Invalid ARN: Unrecognized format: arn:aws:s3:::mybucket (type: mybucket). "
+ "Use the bucket name instead of simple bucket ARNs in GetBucketLocationRequest.");
}
@Test
public void getBucketPolicyReturnsAResult() throws IOException {
String policy = createPolicy();
s3.putBucketPolicy(PutBucketPolicyRequest.builder().bucket(bucketName).policy(policy).build());
GetBucketPolicyRequest request = GetBucketPolicyRequest.builder().bucket(bucketName).build();
String returnedPolicy = s3.getBucketPolicy(request).policy();
assertThat(returnedPolicy).contains("arn:aws:s3:::" + bucketName);
// Asserts that the policy is valid JSON
assertThat(new ObjectMapper().readTree(returnedPolicy)).isInstanceOf(JsonNode.class);
}
@Test
public void getRequestPayerReturnsAResult() {
GetBucketRequestPaymentRequest request = GetBucketRequestPaymentRequest.builder().bucket(bucketName).build();
assertThat(s3.getBucketRequestPayment(request).payer()).isEqualTo(Payer.BUCKET_OWNER);
}
private String createPolicy() {
return new Policy().withStatements(
new Statement(Statement.Effect.Deny)
.withPrincipals(new Principal("*"))
.withResources(new Resource("arn:aws:s3:::" + bucketName + "/*"))
.withActions(new Action("s3:GetObject")))
.toJson();
}
}
| 4,488 |
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/PutObjectIntegrationTest.java |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely;
import java.io.ByteArrayInputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.nio.charset.StandardCharsets;
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.http.ContentStreamProvider;
/**
* Integration tests for {@code PutObject}.
*/
public class PutObjectIntegrationTest extends S3IntegrationTestBase {
private static final String BUCKET = temporaryBucketName(PutObjectIntegrationTest.class);
private static final String KEY = "key";
private static final byte[] CONTENT = "Hello".getBytes(StandardCharsets.UTF_8);
@BeforeClass
public static void setUp() throws Exception {
S3IntegrationTestBase.setUp();
createBucket(BUCKET);
}
@AfterClass
public static void tearDown() {
deleteBucketAndAllContents(BUCKET);
}
@Test
public void objectInputStreamsAreClosed() {
TestContentProvider provider = new TestContentProvider(CONTENT);
s3.putObject(r -> r.bucket(BUCKET).key(KEY), RequestBody.fromContentProvider(provider, CONTENT.length, "binary/octet-stream"));
for (CloseTrackingInputStream is : provider.getCreatedStreams()) {
assertThat(is.isClosed()).isTrue();
}
}
@Test
public void s3Client_usingHttpAndDisableChunkedEncoding() {
try (S3Client s3Client = s3ClientBuilder()
.endpointOverride(URI.create("http://s3.us-west-2.amazonaws.com"))
.serviceConfiguration(S3Configuration.builder()
.chunkedEncodingEnabled(false)
.build())
.build()) {
assertThat(s3Client.putObject(b -> b.bucket(BUCKET).key(KEY), RequestBody.fromBytes(
"helloworld".getBytes()))).isNotNull();
}
}
private static class TestContentProvider implements ContentStreamProvider {
private final byte[] content;
private final List<CloseTrackingInputStream> createdStreams = new ArrayList<>();
private CloseTrackingInputStream currentStream;
private TestContentProvider(byte[] content) {
this.content = content;
}
@Override
public InputStream newStream() {
if (currentStream != null) {
invokeSafely(currentStream::close);
}
currentStream = new CloseTrackingInputStream(new ByteArrayInputStream(content));
createdStreams.add(currentStream);
return currentStream;
}
List<CloseTrackingInputStream> getCreatedStreams() {
return createdStreams;
}
}
private static class CloseTrackingInputStream extends FilterInputStream {
private boolean isClosed = false;
CloseTrackingInputStream(InputStream in) {
super(in);
}
@Override
public void close() throws IOException {
super.close();
isClosed = true;
}
boolean isClosed() {
return isClosed;
}
}
}
| 4,489 |
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/AsyncGetObjectFaultIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.assertj.core.api.Assertions.assertThatThrownBy;
import static software.amazon.awssdk.testutils.service.S3BucketUtils.temporaryBucketName;
import java.nio.ByteBuffer;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import software.amazon.awssdk.core.ResponseBytes;
import software.amazon.awssdk.core.async.AsyncResponseTransformer;
import software.amazon.awssdk.core.async.SdkPublisher;
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
import software.amazon.awssdk.core.exception.ApiCallTimeoutException;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
public class AsyncGetObjectFaultIntegrationTest extends S3IntegrationTestBase {
private static final String BUCKET = temporaryBucketName(AsyncGetObjectFaultIntegrationTest.class);
private static final String KEY = "some-key";
private static S3AsyncClient s3ClientWithTimeout;
@BeforeClass
public static void setupFixture() {
createBucket(BUCKET);
s3.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(KEY)
.build(), RequestBody.fromString("some contents"));
s3ClientWithTimeout = s3AsyncClientBuilder()
.overrideConfiguration(ClientOverrideConfiguration.builder()
.apiCallTimeout(Duration.ofSeconds(1))
.build())
.build();
}
@AfterClass
public static void tearDownFixture() {
deleteBucketAndAllContents(BUCKET);
}
@Test
public void slowTransformer_shouldThrowApiCallTimeoutException() {
SlowResponseTransformer<GetObjectResponse> handler =
new SlowResponseTransformer<>();
assertThatThrownBy(() -> s3ClientWithTimeout.getObject(getObjectRequest(), handler).join())
.hasCauseInstanceOf(ApiCallTimeoutException.class);
assertThat(handler.currentCallCount()).isEqualTo(1);
assertThat(handler.exceptionOccurred).isEqualTo(true);
}
private GetObjectRequest getObjectRequest() {
return GetObjectRequest.builder()
.bucket(BUCKET)
.key(KEY)
.build();
}
/**
* Wrapper around a {@link AsyncResponseTransformer} that counts how many times it's been invoked.
*/
private static class SlowResponseTransformer<ResponseT>
implements AsyncResponseTransformer<ResponseT, ResponseBytes<ResponseT>> {
private final AtomicInteger callCount = new AtomicInteger(0);
private final AsyncResponseTransformer<ResponseT, ResponseBytes<ResponseT>> delegate;
private boolean exceptionOccurred = false;
private SlowResponseTransformer() {
this.delegate = AsyncResponseTransformer.toBytes();
}
public int currentCallCount() {
return callCount.get();
}
@Override
public CompletableFuture<ResponseBytes<ResponseT>> prepare() {
return delegate.prepare()
.thenApply(r -> {
try {
Thread.sleep(2_000);
} catch (InterruptedException e) {
e.printStackTrace();;
}
return r;
});
}
@Override
public void onResponse(ResponseT response) {
callCount.incrementAndGet();
delegate.onResponse(response);
}
@Override
public void onStream(SdkPublisher<ByteBuffer> publisher) {
delegate.onStream(publisher);
}
@Override
public void exceptionOccurred(Throwable throwable) {
delegate.exceptionOccurred(throwable);
exceptionOccurred = true;
}
}
}
| 4,490 |
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/SyncServerSideEncryptionIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 software.amazon.awssdk.services.s3.model.ServerSideEncryption.AES256;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Base64;
import java.util.UUID;
import org.junit.Test;
import software.amazon.awssdk.core.sync.ResponseTransformer;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.ServerSideEncryption;
import software.amazon.awssdk.testutils.SdkAsserts;
import software.amazon.awssdk.utils.Md5Utils;
public class SyncServerSideEncryptionIntegrationTest extends ServerSideEncryptionIntegrationTestBase {
@Test
public void sse_AES256_succeeds() throws Exception {
String key = UUID.randomUUID().toString();
PutObjectRequest request = PutObjectRequest.builder()
.key(key)
.bucket(BUCKET)
.serverSideEncryption(AES256)
.build();
s3.putObject(request, file.toPath());
GetObjectRequest getObjectRequest = GetObjectRequest.builder()
.key(key)
.bucket(BUCKET)
.build();
InputStream response = s3.getObject(getObjectRequest);
SdkAsserts.assertFileEqualsStream(file, response);
}
@Test
public void sse_AWSKMS_succeeds() throws Exception {
String key = UUID.randomUUID().toString();
PutObjectRequest request = PutObjectRequest.builder()
.key(key)
.bucket(BUCKET)
.serverSideEncryption(ServerSideEncryption.AWS_KMS)
.build();
s3.putObject(request, file.toPath());
GetObjectRequest getObjectRequest = GetObjectRequest.builder()
.key(key)
.bucket(BUCKET)
.build();
String response = s3.getObject(getObjectRequest, ResponseTransformer.toBytes()).asUtf8String();
SdkAsserts.assertStringEqualsStream(response, new FileInputStream(file));
}
@Test
public void sse_customerManaged_succeeds() {
String key = UUID.randomUUID().toString();
byte[] secretKey = generateSecretKey();
String b64Key = Base64.getEncoder().encodeToString(secretKey);
String b64KeyMd5 = Md5Utils.md5AsBase64(secretKey);
PutObjectRequest request = PutObjectRequest.builder()
.key(key)
.bucket(BUCKET)
.sseCustomerKey(b64Key)
.sseCustomerAlgorithm(AES256.name())
.sseCustomerKeyMD5(b64KeyMd5)
.build();
s3.putObject(request, file.toPath());
GetObjectRequest getObjectRequest = GetObjectRequest.builder()
.key(key)
.bucket(BUCKET)
.sseCustomerKey(b64Key)
.sseCustomerAlgorithm(AES256.name())
.sseCustomerKeyMD5(b64KeyMd5)
.build();
InputStream response = s3.getObject(getObjectRequest);
SdkAsserts.assertFileEqualsStream(file, response);
}
@Test
public void sse_onBucket_succeeds() throws FileNotFoundException {
String key = UUID.randomUUID().toString();
PutObjectRequest request = PutObjectRequest.builder()
.key(key)
.bucket(BUCKET_WITH_SSE)
.build();
s3.putObject(request, file.toPath());
GetObjectRequest getObjectRequest = GetObjectRequest.builder()
.key(key)
.bucket(BUCKET_WITH_SSE)
.build();
String response = s3.getObject(getObjectRequest, ResponseTransformer.toBytes()).asUtf8String();
SdkAsserts.assertStringEqualsStream(response, new FileInputStream(file));
}
}
| 4,491 |
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/HeadObjectIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.zip.GZIPOutputStream;
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.HeadObjectRequest;
import software.amazon.awssdk.services.s3.model.HeadObjectResponse;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
public class HeadObjectIntegrationTest extends S3IntegrationTestBase {
private static final String BUCKET = temporaryBucketName(HeadObjectIntegrationTest.class);
private static final String GZIPPED_KEY = "some-key";
@BeforeClass
public static void setupFixture() throws IOException {
createBucket(BUCKET);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gzos = new GZIPOutputStream(baos);
gzos.write("Test".getBytes(StandardCharsets.UTF_8));
s3.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(GZIPPED_KEY)
.contentEncoding("gzip")
.build(),
RequestBody.fromBytes(baos.toByteArray()));
}
@Test
public void asyncClientSupportsGzippedObjects() {
HeadObjectResponse response = s3Async.headObject(r -> r.bucket(BUCKET).key(GZIPPED_KEY)).join();
assertThat(response.contentEncoding()).isEqualTo("gzip");
}
@Test
public void syncClientSupportsGzippedObjects() {
HeadObjectResponse response = s3.headObject(r -> r.bucket(BUCKET).key(GZIPPED_KEY));
assertThat(response.contentEncoding()).isEqualTo("gzip");
}
@AfterClass
public static void cleanup() {
deleteBucketAndAllContents(BUCKET);
}
}
| 4,492 |
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/S3PresignerIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.time.Duration;
import java.util.Optional;
import java.util.UUID;
import java.util.function.Consumer;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import software.amazon.awssdk.awscore.presigner.PresignedRequest;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.http.AbortableInputStream;
import software.amazon.awssdk.http.ContentStreamProvider;
import software.amazon.awssdk.http.HttpExecuteRequest;
import software.amazon.awssdk.http.HttpExecuteResponse;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
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.CreateMultipartUploadResponse;
import software.amazon.awssdk.services.s3.model.MultipartUpload;
import software.amazon.awssdk.services.s3.model.RequestPayer;
import software.amazon.awssdk.services.s3.model.UploadPartRequest;
import software.amazon.awssdk.services.s3.model.UploadPartResponse;
import software.amazon.awssdk.services.s3.presigner.S3Presigner;
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.utils.S3TestUtils;
import software.amazon.awssdk.utils.IoUtils;
import software.amazon.awssdk.utils.StringInputStream;
public class S3PresignerIntegrationTest {
private static S3Client client;
private static String testBucket;
private static String testNonDnsCompatibleBucket;
private static String testGetObjectKey;
private static String testObjectContent;
private S3Presigner presigner;
@BeforeClass
public static void setUpClass() {
client = S3Client.create();
testBucket = S3TestUtils.getTestBucket(client);
testNonDnsCompatibleBucket = S3TestUtils.getNonDnsCompatibleTestBucket(client);
testGetObjectKey = generateRandomObjectKey();
testObjectContent = "Howdy!";
S3TestUtils.putObject(S3PresignerIntegrationTest.class, client, testBucket, testGetObjectKey, testObjectContent);
S3TestUtils.putObject(S3PresignerIntegrationTest.class, client, testNonDnsCompatibleBucket, testGetObjectKey, testObjectContent);
}
@AfterClass
public static void tearDownClass() {
S3TestUtils.runCleanupTasks(S3PresignerIntegrationTest.class);
client.close();
}
private static String generateRandomObjectKey() {
return "s3-presigner-it-" + UUID.randomUUID();
}
@Before
public void setUpInstance() {
this.presigner = S3Presigner.create();
}
@After
public void testDownInstance() {
this.presigner.close();
}
@Test
public void browserCompatiblePresignedUrlWorks() throws IOException {
assertThatPresigningWorks(testBucket, testGetObjectKey);
}
@Test
public void bucketsWithScaryCharactersWorks() throws IOException {
assertThatPresigningWorks(testNonDnsCompatibleBucket, testGetObjectKey);
}
@Test
public void keysWithScaryCharactersWorks() throws IOException {
String scaryObjectKey = "a0A!-_.*'()&@:,$=+?; \n\\^`<>{}[]#%\"~|山/" + testGetObjectKey;
S3TestUtils.putObject(S3PresignerIntegrationTest.class, client, testBucket, scaryObjectKey, testObjectContent);
assertThatPresigningWorks(testBucket, scaryObjectKey);
}
private void assertThatPresigningWorks(String bucket, String objectKey) throws IOException {
PresignedGetObjectRequest presigned =
presigner.presignGetObject(r -> r.signatureDuration(Duration.ofMinutes(5))
.getObjectRequest(gor -> gor.bucket(bucket).key(objectKey)));
assertThat(presigned.isBrowserExecutable()).isTrue();
try (InputStream response = presigned.url().openConnection().getInputStream()) {
assertThat(IoUtils.toUtf8String(response)).isEqualTo(testObjectContent);
}
}
@Test
public void browserIncompatiblePresignedUrlDoesNotWorkWithoutAdditionalHeaders() throws IOException {
PresignedGetObjectRequest presigned =
presigner.presignGetObject(r -> r.signatureDuration(Duration.ofMinutes(5))
.getObjectRequest(gor -> gor.bucket(testBucket)
.key(testGetObjectKey)
.requestPayer(RequestPayer.REQUESTER)));
assertThat(presigned.isBrowserExecutable()).isFalse();
HttpURLConnection connection = (HttpURLConnection) presigned.url().openConnection();
connection.connect();
try {
assertThat(connection.getResponseCode()).isEqualTo(403);
} finally {
connection.disconnect();
}
}
@Test
public void browserIncompatiblePresignedUrlWorksWithAdditionalHeaders() throws IOException {
PresignedGetObjectRequest presigned =
presigner.presignGetObject(r -> r.signatureDuration(Duration.ofMinutes(5))
.getObjectRequest(gor -> gor.bucket(testBucket)
.key(testGetObjectKey)
.requestPayer(RequestPayer.REQUESTER)));
assertThat(presigned.isBrowserExecutable()).isFalse();
HttpURLConnection connection = (HttpURLConnection) presigned.url().openConnection();
presigned.httpRequest().headers().forEach((header, values) -> {
values.forEach(value -> {
connection.addRequestProperty(header, value);
});
});
try (InputStream content = connection.getInputStream()) {
assertThat(IoUtils.toUtf8String(content)).isEqualTo(testObjectContent);
}
}
@Test
public void getObject_PresignedHttpRequestCanBeInvokedDirectlyBySdk() throws IOException {
PresignedGetObjectRequest presigned =
presigner.presignGetObject(r -> r.signatureDuration(Duration.ofMinutes(5))
.getObjectRequest(gor -> gor.bucket(testBucket)
.key(testGetObjectKey)
.requestPayer(RequestPayer.REQUESTER)));
assertThat(presigned.isBrowserExecutable()).isFalse();
SdkHttpClient httpClient = ApacheHttpClient.builder().build(); // or UrlConnectionHttpClient.builder().build()
ContentStreamProvider requestPayload = presigned.signedPayload()
.map(SdkBytes::asContentStreamProvider)
.orElse(null);
HttpExecuteRequest request = HttpExecuteRequest.builder()
.request(presigned.httpRequest())
.contentStreamProvider(requestPayload)
.build();
HttpExecuteResponse response = httpClient.prepareRequest(request).call();
assertThat(response.responseBody()).isPresent();
try (InputStream responseStream = response.responseBody().get()) {
assertThat(IoUtils.toUtf8String(responseStream)).isEqualTo(testObjectContent);
}
}
@Test
public void deleteObject_PresignedHttpRequestCanBeInvokedDirectlyBySdk() throws IOException {
String objectKey = generateRandomObjectKey();
S3TestUtils.addCleanupTask(S3PresignerIntegrationTest.class,
() -> client.deleteObject(r -> r.bucket(testBucket).key(objectKey)));
client.putObject(r -> r.bucket(testBucket).key(objectKey), RequestBody.fromString("DeleteObjectPresignRequestTest"));
PresignedDeleteObjectRequest presigned =
presigner.presignDeleteObject(r -> r.signatureDuration(Duration.ofMinutes(5))
.deleteObjectRequest(delo -> delo.bucket(testBucket)
.key(objectKey)
.requestPayer(RequestPayer.REQUESTER)));
assertThat(presigned.isBrowserExecutable()).isFalse();
SdkHttpClient httpClient = ApacheHttpClient.builder().build(); // or UrlConnectionHttpClient.builder().build()
ContentStreamProvider requestPayload = presigned.signedPayload()
.map(SdkBytes::asContentStreamProvider)
.orElse(null);
HttpExecuteRequest request = HttpExecuteRequest.builder()
.request(presigned.httpRequest())
.contentStreamProvider(requestPayload)
.build();
HttpExecuteResponse response = httpClient.prepareRequest(request).call();
assertThat(response.responseBody()).isEmpty();
assertThat(response.httpResponse().statusCode()).isEqualTo(204);
}
@Test
public void putObject_PresignedHttpRequestCanBeInvokedDirectlyBySdk() throws IOException {
String objectKey = generateRandomObjectKey();
S3TestUtils.addCleanupTask(S3PresignerIntegrationTest.class,
() -> client.deleteObject(r -> r.bucket(testBucket).key(objectKey)));
PresignedPutObjectRequest presigned =
presigner.presignPutObject(r -> r.signatureDuration(Duration.ofMinutes(5))
.putObjectRequest(por -> por.bucket(testBucket).key(objectKey)));
assertThat(presigned.isBrowserExecutable()).isFalse();
SdkHttpClient httpClient = ApacheHttpClient.builder().build(); // or UrlConnectionHttpClient.builder().build()
ContentStreamProvider requestPayload = () -> new StringInputStream(testObjectContent);
HttpExecuteRequest request = HttpExecuteRequest.builder()
.request(presigned.httpRequest())
.contentStreamProvider(requestPayload)
.build();
HttpExecuteResponse response = httpClient.prepareRequest(request).call();
assertThat(response.responseBody()).isPresent();
assertThat(response.httpResponse().isSuccessful()).isTrue();
response.responseBody().ifPresent(AbortableInputStream::abort);
String content = client.getObjectAsBytes(r -> r.bucket(testBucket).key(objectKey)).asUtf8String();
assertThat(content).isEqualTo(testObjectContent);
}
@Test
public void createMultipartUpload_CanBePresigned() throws IOException {
String objectKey = generateRandomObjectKey();
PresignedCreateMultipartUploadRequest presigned =
presigner.presignCreateMultipartUpload(p -> p.signatureDuration(Duration.ofMinutes(10))
.createMultipartUploadRequest(createMultipartUploadRequest(objectKey)));
HttpExecuteResponse response = execute(presigned, null);
assertThat(response.httpResponse().isSuccessful()).isTrue();
Optional<MultipartUpload> upload = getMultipartUpload(objectKey);
assertThat(upload).isPresent();
client.abortMultipartUpload(abortMultipartUploadRequest(objectKey, upload.get().uploadId()));
}
@Test
public void uploadPart_CanBePresigned() throws IOException {
String objectKey = generateRandomObjectKey();
S3TestUtils.addCleanupTask(S3PresignerIntegrationTest.class,
() -> client.deleteObject(r -> r.bucket(testBucket).key(objectKey)));
CreateMultipartUploadResponse create = client.createMultipartUpload(createMultipartUploadRequest(objectKey));
S3TestUtils.addCleanupTask(S3PresignerIntegrationTest.class,
() -> client.abortMultipartUpload(abortMultipartUploadRequest(objectKey, create.uploadId())));
PresignedUploadPartRequest uploadPart =
presigner.presignUploadPart(up -> up.signatureDuration(Duration.ofDays(1))
.uploadPartRequest(upr -> upr.bucket(testBucket)
.key(objectKey)
.partNumber(1)
.uploadId(create.uploadId())));
HttpExecuteResponse uploadPartResponse = execute(uploadPart, testObjectContent);
assertThat(uploadPartResponse.httpResponse().isSuccessful()).isTrue();
String etag = uploadPartResponse.httpResponse().firstMatchingHeader("ETag").orElse(null);
client.completeMultipartUpload(createMultipartUploadRequest(objectKey, create, etag));
String content = client.getObjectAsBytes(r -> r.bucket(testBucket).key(objectKey)).asUtf8String();
assertThat(content).isEqualTo(testObjectContent);
}
@Test
public void completeMultipartUpload_CanBePresigned() throws IOException {
String objectKey = generateRandomObjectKey();
S3TestUtils.addCleanupTask(S3PresignerIntegrationTest.class,
() -> client.deleteObject(r -> r.bucket(testBucket).key(objectKey)));
CreateMultipartUploadResponse create = client.createMultipartUpload(createMultipartUploadRequest(objectKey));
S3TestUtils.addCleanupTask(S3PresignerIntegrationTest.class,
() -> client.abortMultipartUpload(abortMultipartUploadRequest(objectKey, create.uploadId())));
UploadPartResponse uploadPartResponse = client.uploadPart(uploadPartRequest(objectKey, create),
RequestBody.fromString(testObjectContent));
String etag = uploadPartResponse.eTag();
PresignedCompleteMultipartUploadRequest presignedRequest =
presigner.presignCompleteMultipartUpload(
r -> r.signatureDuration(Duration.ofDays(1))
.completeMultipartUploadRequest(createMultipartUploadRequest(objectKey, create, etag)));
assertThat(execute(presignedRequest, presignedRequest.signedPayload().get().asUtf8String())
.httpResponse().isSuccessful()).isTrue();
String content = client.getObjectAsBytes(r -> r.bucket(testBucket).key(objectKey)).asUtf8String();
assertThat(content).isEqualTo(testObjectContent);
}
@Test
public void abortMultipartUpload_CanBePresigned() throws IOException {
String objectKey = generateRandomObjectKey();
S3TestUtils.addCleanupTask(S3PresignerIntegrationTest.class,
() -> client.deleteObject(r -> r.bucket(testBucket).key(objectKey)));
CreateMultipartUploadResponse create = client.createMultipartUpload(createMultipartUploadRequest(objectKey));
S3TestUtils.addCleanupTask(S3PresignerIntegrationTest.class,
() -> client.abortMultipartUpload(abortMultipartUploadRequest(objectKey, create.uploadId())));
PresignedAbortMultipartUploadRequest presignedRequest = presigner.presignAbortMultipartUpload(
r -> r.signatureDuration(Duration.ofDays(1))
.abortMultipartUploadRequest(abortMultipartUploadRequest(objectKey, create.uploadId())));
assertThat(execute(presignedRequest, null).httpResponse().isSuccessful()).isTrue();
assertThat(getMultipartUpload(objectKey)).isNotPresent();
}
private Consumer<CreateMultipartUploadRequest.Builder> createMultipartUploadRequest(String objectKey) {
return r -> r.bucket(testBucket).key(objectKey);
}
private Consumer<UploadPartRequest.Builder> uploadPartRequest(String objectKey, CreateMultipartUploadResponse create) {
return r -> r.bucket(testBucket)
.key(objectKey)
.partNumber(1)
.uploadId(create.uploadId());
}
private Consumer<CompleteMultipartUploadRequest.Builder> createMultipartUploadRequest(String objectKey, CreateMultipartUploadResponse create, String etag) {
return c -> c.bucket(testBucket)
.key(objectKey)
.uploadId(create.uploadId())
.multipartUpload(m -> m.parts(p -> p.partNumber(1).eTag(etag)));
}
private Consumer<AbortMultipartUploadRequest.Builder> abortMultipartUploadRequest(String objectKey, String uploadId) {
return r -> r.bucket(testBucket)
.key(objectKey)
.uploadId(uploadId);
}
private Optional<MultipartUpload> getMultipartUpload(String objectKey) {
return client.listMultipartUploadsPaginator(r -> r.bucket(testBucket).prefix(objectKey))
.uploads()
.stream()
.filter(u -> u.key().equals(objectKey))
.findAny();
}
private HttpExecuteResponse execute(PresignedRequest presigned, String payload) throws IOException {
SdkHttpClient httpClient = ApacheHttpClient.builder().build();
ContentStreamProvider requestPayload = payload == null ? null : () -> new StringInputStream(payload);
HttpExecuteRequest request = HttpExecuteRequest.builder()
.request(presigned.httpRequest())
.contentStreamProvider(requestPayload)
.build();
return httpClient.prepareRequest(request).call();
}
}
| 4,493 |
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/S3ResponseMetadataIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.io.File;
import java.io.IOException;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import software.amazon.awssdk.core.ResponseBytes;
import software.amazon.awssdk.core.async.AsyncResponseTransformer;
import software.amazon.awssdk.core.sync.ResponseTransformer;
import software.amazon.awssdk.services.s3.model.GetObjectAclResponse;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.S3Response;
import software.amazon.awssdk.services.s3.model.S3ResponseMetadata;
import software.amazon.awssdk.testutils.RandomTempFile;
public class S3ResponseMetadataIntegrationTest extends S3IntegrationTestBase {
private static final String BUCKET = temporaryBucketName(S3ResponseMetadataIntegrationTest.class);
private static final String KEY = "some-key";
private static File file;
@BeforeClass
public static void setupFixture() throws IOException {
createBucket(BUCKET);
file = new RandomTempFile(10_000);
s3.putObject(PutObjectRequest.builder()
.bucket(BUCKET)
.key(KEY)
.build(), file.toPath());
}
@AfterClass
public static void deleteAllBuckets() {
deleteBucketAndAllContents(BUCKET);
file.delete();
}
@Test
public void syncNonStreaming_shouldContainResponseMetadata() {
GetObjectAclResponse response = s3.getObjectAcl(b -> b.key(KEY).bucket(BUCKET));
verifyResponseMetadata(response);
}
@Test
public void syncStreaming_shouldContainResponseMetadata() {
ResponseBytes<GetObjectResponse> responseBytes = s3.getObject(b -> b.key(KEY).bucket(BUCKET), ResponseTransformer.toBytes());
GetObjectResponse response = responseBytes.response();
verifyResponseMetadata(response);
}
@Test
public void asyncNonStreaming_shouldContainResponseMetadata() {
GetObjectAclResponse response = s3Async.getObjectAcl(b -> b.key(KEY).bucket(BUCKET)).join();
verifyResponseMetadata(response);
}
@Test
public void asyncStreaming_shouldContainResponseMetadata() {
verifyResponseMetadata(s3Async.getObject(b -> b.key(KEY).bucket(BUCKET), AsyncResponseTransformer.toBytes()).join().response());
}
private void verifyResponseMetadata(S3Response response) {
S3ResponseMetadata s3ResponseMetadata = response.responseMetadata();
assertThat(s3ResponseMetadata).isNotNull();
assertThat(s3ResponseMetadata.requestId()).isNotEqualTo("UNKNOWN");
assertThat(s3ResponseMetadata.extendedRequestId()).isNotEqualTo("UNKNOWN");
}
}
| 4,494 |
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/ExceptionUnmarshallingIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.assertj.core.api.Assertions.assertThatThrownBy;
import static software.amazon.awssdk.testutils.service.S3BucketUtils.temporaryBucketName;
import java.nio.charset.StandardCharsets;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.model.BucketAlreadyExistsException;
import software.amazon.awssdk.services.s3.model.BucketAlreadyOwnedByYouException;
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.NoSuchUploadException;
import software.amazon.awssdk.services.s3.model.S3Exception;
public class ExceptionUnmarshallingIntegrationTest extends S3IntegrationTestBase {
private static final String BUCKET = temporaryBucketName(ExceptionUnmarshallingIntegrationTest.class);
private static final String KEY = "some-key";
@BeforeClass
public static void setupFixture() {
createBucket(BUCKET);
}
@AfterClass
public static void tearDownFixture() {
deleteBucketAndAllContents(BUCKET);
}
@Test
public void createBucketAlreadyOwnedByYou() {
assertThatThrownBy(() -> s3.createBucket(b -> b.bucket(BUCKET)))
.isInstanceOf(BucketAlreadyOwnedByYouException.class)
.satisfies(e -> assertMetadata((S3Exception) e, "BucketAlreadyOwnedByYou"));
}
@Test
public void getObjectNoSuchKey() {
assertThatThrownBy(() -> s3.getObject(GetObjectRequest.builder().bucket(BUCKET).key(KEY).build()))
.isInstanceOf(NoSuchKeyException.class)
.satisfies(e -> assertMetadata((S3Exception) e, "NoSuchKey"));
}
@Test
public void getObjectNoSuchBucket() {
assertThatThrownBy(() -> s3.getObject(GetObjectRequest.builder().bucket(BUCKET + KEY).key(KEY).build()))
.isInstanceOf(NoSuchBucketException.class)
.satisfies(e -> assertMetadata((S3Exception) e, "NoSuchBucket"));
}
@Test
public void getBucketPolicyNoSuchBucket() {
assertThatThrownBy(() -> s3.getBucketPolicy(b -> b.bucket(BUCKET + KEY)))
.isInstanceOf(NoSuchBucketException.class)
.satisfies(e -> assertMetadata((S3Exception) e, "NoSuchBucket"));
}
@Test
public void asyncGetBucketPolicyNoSuchBucket() {
assertThatThrownBy(() -> s3Async.getBucketPolicy(b -> b.bucket(BUCKET + KEY)).join())
.hasCauseExactlyInstanceOf(NoSuchBucketException.class)
.satisfies(e -> assertMetadata((S3Exception) e.getCause(), "NoSuchBucket"));
}
@Test
public void getObjectAclNoSuchKey() {
assertThatThrownBy(() -> s3.getObjectAcl(b -> b.bucket(BUCKET).key(KEY)))
.isInstanceOf(NoSuchKeyException.class)
.satisfies(e -> assertMetadata((S3Exception) e, "NoSuchKey"));
}
@Test
public void getObjectAclNoSuchBucket() {
assertThatThrownBy(() -> s3.getObjectAcl(b -> b.bucket(BUCKET + KEY).key(KEY)))
.isInstanceOf(NoSuchBucketException.class)
.satisfies(e -> assertMetadata((S3Exception) e, "NoSuchBucket"));
}
@Test
public void abortMultipartNoSuchUpload() {
assertThatThrownBy(() -> s3.abortMultipartUpload(b -> b.bucket(BUCKET).key(KEY).uploadId("23232")))
.isInstanceOf(NoSuchUploadException.class)
.satisfies(e -> assertMetadata((S3Exception) e, "NoSuchUpload"));
}
@Test
public void listObjectsWrongRegion() {
assertThatThrownBy(() -> {
try (S3Client client = s3ClientBuilder().region(Region.EU_CENTRAL_1).build()) {
client.listObjectsV2(b -> b.bucket(BUCKET));
}
}).isExactlyInstanceOf(S3Exception.class) // Make sure it's not a modeled exception, because that's what we're testing
.hasMessageContaining("The bucket you are attempting to access must be addressed using the specified endpoint.")
.satisfies(e -> assertMetadata((S3Exception) e, "PermanentRedirect"));
}
@Test
public void headObjectNoSuchKey() {
assertThatThrownBy(() -> s3.headObject(b -> b.bucket(BUCKET).key(KEY)))
.isInstanceOf(NoSuchKeyException.class)
.satisfies(e -> assertMetadata((NoSuchKeyException) e, "NoSuchKey"))
.satisfies(e -> assertThat(((NoSuchKeyException) e).statusCode()).isEqualTo(404));
}
@Test
public void asyncHeadObjectNoSuchKey() {
assertThatThrownBy(() -> s3Async.headObject(b -> b.bucket(BUCKET).key(KEY)).join())
.hasCauseInstanceOf(NoSuchKeyException.class)
.satisfies(e -> assertMetadata(((NoSuchKeyException) (e.getCause())), "NoSuchKey"))
.satisfies(e -> assertThat(((NoSuchKeyException) (e.getCause())).statusCode()).isEqualTo(404));
}
@Test
public void headBucketNoSuchBucket() {
assertThatThrownBy(() -> s3.headBucket(b -> b.bucket(KEY)))
.isInstanceOf(NoSuchBucketException.class)
.satisfies(e -> assertMetadata((NoSuchBucketException) e, "NoSuchBucket"))
.satisfies(e -> assertThat(((NoSuchBucketException) e).statusCode()).isEqualTo(404));
}
@Test
public void asyncHeadBucketNoSuchBucket() {
assertThatThrownBy(() -> s3Async.headBucket(b -> b.bucket(KEY)).join())
.hasCauseInstanceOf(NoSuchBucketException.class)
.satisfies(e -> assertMetadata(((NoSuchBucketException) (e.getCause())), "NoSuchBucket"))
.satisfies(e -> assertThat(((NoSuchBucketException) (e.getCause())).statusCode()).isEqualTo(404));
}
@Test
public void asyncHeadBucketWrongRegion() {
assertThatThrownBy(() -> {
try (S3AsyncClient s3AsyncClient = s3AsyncClientBuilder().region(Region.EU_CENTRAL_1).build()) {
s3AsyncClient.headBucket(b -> b.bucket(BUCKET)).join();
}
}).hasCauseInstanceOf(S3Exception.class)
.satisfies(e -> assertThat(((S3Exception) (e.getCause())).statusCode()).isEqualTo(301));
}
private void assertMetadata(S3Exception e, String expectedErrorCode) {
assertThat(e.awsErrorDetails()).satisfies(
errorDetails -> {
assertThat(errorDetails.errorCode()).isEqualTo(expectedErrorCode);
assertThat(errorDetails.errorMessage()).isNotEmpty();
assertThat(errorDetails.sdkHttpResponse()).isNotNull();
assertThat(errorDetails.serviceName()).isEqualTo("S3");
}
);
assertThat(e.requestId()).isNotEmpty();
}
}
| 4,495 |
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/ServerSideEncryptionIntegrationTestBase.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.Fail.fail;
import static software.amazon.awssdk.services.s3.S3IntegrationTestBase.createBucket;
import static software.amazon.awssdk.testutils.service.S3BucketUtils.temporaryBucketName;
import java.io.File;
import java.io.IOException;
import java.security.SecureRandom;
import javax.crypto.KeyGenerator;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import software.amazon.awssdk.services.kms.KmsClient;
import software.amazon.awssdk.services.s3.model.ServerSideEncryption;
import software.amazon.awssdk.testutils.RandomTempFile;
public class ServerSideEncryptionIntegrationTestBase extends S3IntegrationTestBase {
protected static final String BUCKET = temporaryBucketName(ServerSideEncryptionIntegrationTestBase.class);
protected static final String BUCKET_WITH_SSE = temporaryBucketName(ServerSideEncryptionIntegrationTestBase.class);
private static final KmsClient KMS = KmsClient.builder()
.region(DEFAULT_REGION)
.credentialsProvider(CREDENTIALS_PROVIDER_CHAIN)
.build();
protected static File file;
private static String keyId;
@BeforeClass
public static void setupFixture() throws IOException {
createBucket(BUCKET);
createBucket(BUCKET_WITH_SSE);
keyId = KMS.createKey().keyMetadata().keyId();
s3.putBucketEncryption(r -> r
.bucket(BUCKET_WITH_SSE)
.serverSideEncryptionConfiguration(ssec -> ssec
.rules(rule -> rule
.applyServerSideEncryptionByDefault(d -> d.kmsMasterKeyID(keyId)
.sseAlgorithm(ServerSideEncryption.AWS_KMS)))));
file = new RandomTempFile(10_000);
}
@AfterClass
public static void tearDownFixture() {
deleteBucketAndAllContents(BUCKET);
deleteBucketAndAllContents(BUCKET_WITH_SSE);
file.delete();
KMS.scheduleKeyDeletion(r -> r.keyId(keyId));
}
protected 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;
}
}
}
| 4,496 |
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/CopyObjectIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 software.amazon.awssdk.testutils.service.S3BucketUtils.temporaryBucketName;
import java.io.File;
import java.util.Date;
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.CopyObjectRequest;
import software.amazon.awssdk.services.s3.model.HeadObjectRequest;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.testutils.RandomTempFile;
/**
* Integration test for the copyObject operation.
*/
public class CopyObjectIntegrationTest extends S3IntegrationTestBase {
/**
* The S3 bucket created and used by these tests.
*/
private static final String BUCKET_NAME = temporaryBucketName("copy-object-integ-test");
/**
* The key of the object being copied.
*/
private static final String SOURCE_KEY = "source-key";
/**
* The key of the copied object.
*/
private static final String DESTINATION_KEY = "destination-key";
/**
* Length of the data uploaded to S3.
*/
private static final long CONTENT_LENGTH = 345L;
/**
* The file of random data uploaded to S3.
*/
private static File file;
/**
* Releases resources used by tests.
*/
@AfterClass
public static void tearDown() {
deleteBucketAndAllContents(BUCKET_NAME);
file.delete();
}
/**
* Creates/populates all the test data needed for these tests (bucket,
* source object, file, source object ETag, etc).
*/
@BeforeClass
public static void initializeTestData() throws Exception {
createBucket(BUCKET_NAME);
file = new RandomTempFile("copy-object-integ-test-" + new Date().getTime(), CONTENT_LENGTH);
s3.putObject(PutObjectRequest.builder()
.bucket(BUCKET_NAME)
.key(SOURCE_KEY)
.build(),
RequestBody.fromFile(file));
}
/**
* Tests that the simple form of the copy object operation correctly copies
* an object.
*/
@Test
public void copyObject_CopiesObjectToNewKey() throws Exception {
s3.copyObject(CopyObjectRequest.builder()
.sourceBucket(BUCKET_NAME)
.sourceKey(SOURCE_KEY)
.destinationBucket(BUCKET_NAME)
.destinationKey(DESTINATION_KEY)
.build());
s3.headObject(HeadObjectRequest.builder()
.bucket(BUCKET_NAME)
.key(DESTINATION_KEY)
.build());
}
}
| 4,497 |
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/ListBucketsIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 org.junit.Test;
import software.amazon.awssdk.regions.Region;
public class ListBucketsIntegrationTest extends S3IntegrationTestBase {
@Test
public void listBuckets_InGlobal_DoesNotThrowException() {
try (S3Client s3 = s3ClientBuilder().region(Region.AWS_GLOBAL).build()) {
s3.listBuckets();
}
}
}
| 4,498 |
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/KeysWithLeadingSlashIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.nio.charset.StandardCharsets;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import software.amazon.awssdk.core.sync.RequestBody;
public class KeysWithLeadingSlashIntegrationTest extends S3IntegrationTestBase {
private static final String BUCKET = temporaryBucketName(KeysWithLeadingSlashIntegrationTest.class);
private static final String KEY = "/keyWithLeadingSlash";
private static final String SLASH_KEY = "/";
private static final String KEY_WITH_SLASH_AND_SPECIAL_CHARS = "/special-chars-@$%";
private static final byte[] CONTENT = "Hello".getBytes(StandardCharsets.UTF_8);
@BeforeClass
public static void setUp() throws Exception {
S3IntegrationTestBase.setUp();
createBucket(BUCKET);
}
@AfterClass
public static void cleanup() {
deleteBucketAndAllContents(BUCKET);
}
@Test
public void putObject_KeyWithLeadingSlash_Succeeds() {
verify(KEY);
}
@Test
public void slashKey_shouldSucceed() {
verify(SLASH_KEY);
}
@Test
public void slashKeyWithSpecialChar_shouldSucceed() {
verify(KEY_WITH_SLASH_AND_SPECIAL_CHARS);
}
private void verify(String key) {
s3.putObject(r -> r.bucket(BUCKET).key(key), RequestBody.fromBytes(CONTENT));
assertThat(s3.getObjectAsBytes(r -> r.bucket(BUCKET).key(key)).asByteArray()).isEqualTo(CONTENT);
String retrievedKey = s3.listObjects(r -> r.bucket(BUCKET)).contents().get(0).key();
assertThat(retrievedKey).isEqualTo(key);
}
}
| 4,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.