index int64 0 0 | repo_id stringlengths 9 205 | file_path stringlengths 31 246 | content stringlengths 1 12.2M | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/client | Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/client/builder/DefaultAwsClientBuilderTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore.client.builder;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static software.amazon.awssdk.awscore.client.config.AwsAdvancedClientOption.ENABLE_DEFAULT_REGION_DETECTION;
import static software.amazon.awssdk.awscore.client.config.AwsClientOption.SERVICE_SIGNING_NAME;
import static software.amazon.awssdk.awscore.client.config.AwsClientOption.SIGNING_REGION;
import static software.amazon.awssdk.core.client.config.SdkAdvancedClientOption.SIGNER;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.net.URI;
import java.time.Duration;
import java.util.Arrays;
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.auth.credentials.AnonymousCredentialsProvider;
import software.amazon.awssdk.auth.signer.Aws4Signer;
import software.amazon.awssdk.awscore.client.config.AwsClientOption;
import software.amazon.awssdk.awscore.internal.defaultsmode.AutoDefaultsModeDiscovery;
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
import software.amazon.awssdk.core.client.config.SdkClientConfiguration;
import software.amazon.awssdk.core.client.config.SdkClientOption;
import software.amazon.awssdk.core.signer.Signer;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.http.SdkHttpConfigurationOption;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.utils.AttributeMap;
/**
* Validate the functionality of the {@link AwsDefaultClientBuilder}.
*/
@RunWith(MockitoJUnitRunner.class)
public class DefaultAwsClientBuilderTest {
private static final AttributeMap MOCK_DEFAULTS = AttributeMap
.builder()
.put(SdkHttpConfigurationOption.READ_TIMEOUT, Duration.ofSeconds(10))
.build();
private static final String ENDPOINT_PREFIX = "s3";
private static final String SIGNING_NAME = "demo";
private static final String SERVICE_NAME = "Demo";
private static final Signer TEST_SIGNER = Aws4Signer.create();
private static final URI ENDPOINT = URI.create("https://example.com");
@Mock
private SdkHttpClient.Builder defaultHttpClientBuilder;
@Mock
private SdkAsyncHttpClient.Builder defaultAsyncHttpClientFactory;
@Mock
private AutoDefaultsModeDiscovery autoModeDiscovery;
@Before
public void setup() {
when(defaultHttpClientBuilder.buildWithDefaults(any())).thenReturn(mock(SdkHttpClient.class));
when(defaultAsyncHttpClientFactory.buildWithDefaults(any())).thenReturn(mock(SdkAsyncHttpClient.class));
}
@Test
public void buildIncludesServiceDefaults() {
TestClient client = testClientBuilder().region(Region.US_WEST_1).build();
assertThat(client.clientConfiguration.option(SIGNER)).isEqualTo(TEST_SIGNER);
assertThat(client.clientConfiguration.option(SIGNING_REGION)).isNotNull();
assertThat(client.clientConfiguration.option(SdkClientOption.SERVICE_NAME)).isEqualTo(SERVICE_NAME);
}
@Test
public void buildWithRegionShouldHaveCorrectEndpointAndSigningRegion() {
TestClient client = testClientBuilder().region(Region.US_WEST_1).build();
assertThat(client.clientConfiguration.option(SdkClientOption.ENDPOINT))
.hasToString("https://" + ENDPOINT_PREFIX + ".us-west-1.amazonaws.com");
assertThat(client.clientConfiguration.option(SIGNING_REGION)).isEqualTo(Region.US_WEST_1);
assertThat(client.clientConfiguration.option(SERVICE_SIGNING_NAME)).isEqualTo(SIGNING_NAME);
}
@Test
public void buildWithFipsRegionThenNonFipsFipsEnabledRemainsSet() {
TestClient client = testClientBuilder()
.region(Region.of("us-west-2-fips")) // first call to setter sets the flag
.region(Region.of("us-west-2"))// second call should clear
.build();
assertThat(client.clientConfiguration.option(AwsClientOption.AWS_REGION)).isEqualTo(Region.US_WEST_2);
assertThat(client.clientConfiguration.option(AwsClientOption.FIPS_ENDPOINT_ENABLED)).isTrue();
}
@Test
public void buildWithSetFipsTrueAndNonFipsRegionFipsEnabledRemainsSet() {
TestClient client = testClientBuilder()
.fipsEnabled(true)
.region(Region.of("us-west-2"))
.build();
assertThat(client.clientConfiguration.option(AwsClientOption.AWS_REGION)).isEqualTo(Region.US_WEST_2);
assertThat(client.clientConfiguration.option(AwsClientOption.FIPS_ENDPOINT_ENABLED)).isTrue();
}
@Test
public void buildWithEndpointShouldHaveCorrectEndpointAndSigningRegion() {
TestClient client = testClientBuilder().region(Region.US_WEST_1).endpointOverride(ENDPOINT).build();
assertThat(client.clientConfiguration.option(SdkClientOption.ENDPOINT)).isEqualTo(ENDPOINT);
assertThat(client.clientConfiguration.option(SIGNING_REGION)).isEqualTo(Region.US_WEST_1);
assertThat(client.clientConfiguration.option(SERVICE_SIGNING_NAME)).isEqualTo(SIGNING_NAME);
}
@Test
public void noClientProvided_DefaultHttpClientIsManagedBySdk() {
TestClient client = testClientBuilder().region(Region.US_WEST_2).build();
assertThat(client.clientConfiguration.option(SdkClientOption.SYNC_HTTP_CLIENT))
.isNotInstanceOf(AwsDefaultClientBuilder.NonManagedSdkHttpClient.class);
verify(defaultHttpClientBuilder, times(1)).buildWithDefaults(any());
}
@Test
public void noAsyncClientProvided_DefaultAsyncHttpClientIsManagedBySdk() {
TestAsyncClient client = testAsyncClientBuilder().region(Region.US_WEST_2).build();
assertThat(client.clientConfiguration.option(SdkClientOption.ASYNC_HTTP_CLIENT))
.isNotInstanceOf(AwsDefaultClientBuilder.NonManagedSdkAsyncHttpClient.class);
verify(defaultAsyncHttpClientFactory, times(1)).buildWithDefaults(any());
}
@Test
public void clientFactoryProvided_ClientIsManagedBySdk() {
TestClient client = testClientBuilder()
.region(Region.US_WEST_2)
.httpClientBuilder((SdkHttpClient.Builder) serviceDefaults -> {
assertThat(serviceDefaults).isEqualTo(MOCK_DEFAULTS);
return mock(SdkHttpClient.class);
})
.build();
assertThat(client.clientConfiguration.option(SdkClientOption.SYNC_HTTP_CLIENT))
.isNotInstanceOf(AwsDefaultClientBuilder.NonManagedSdkHttpClient.class);
verify(defaultHttpClientBuilder, never()).buildWithDefaults(any());
}
@Test
public void asyncHttpClientFactoryProvided_ClientIsManagedBySdk() {
TestAsyncClient client = testAsyncClientBuilder()
.region(Region.US_WEST_2)
.httpClientBuilder((SdkAsyncHttpClient.Builder) serviceDefaults -> {
assertThat(serviceDefaults).isEqualTo(MOCK_DEFAULTS);
return mock(SdkAsyncHttpClient.class);
})
.build();
assertThat(client.clientConfiguration.option(SdkClientOption.ASYNC_HTTP_CLIENT))
.isNotInstanceOf(AwsDefaultClientBuilder.NonManagedSdkAsyncHttpClient.class);
verify(defaultAsyncHttpClientFactory, never()).buildWithDefaults(any());
}
@Test
public void explicitClientProvided_ClientIsNotManagedBySdk() {
String clientName = "foobarsync";
SdkHttpClient sdkHttpClient = mock(SdkHttpClient.class);
TestClient client = testClientBuilder()
.region(Region.US_WEST_2)
.httpClient(sdkHttpClient)
.build();
when(sdkHttpClient.clientName()).thenReturn(clientName);
assertThat(client.clientConfiguration.option(SdkClientOption.SYNC_HTTP_CLIENT))
.isInstanceOf(AwsDefaultClientBuilder.NonManagedSdkHttpClient.class);
assertThat(client.clientConfiguration.option(SdkClientOption.SYNC_HTTP_CLIENT).clientName())
.isEqualTo(clientName);
verify(defaultHttpClientBuilder, never()).buildWithDefaults(any());
}
@Test
public void explicitAsyncHttpClientProvided_ClientIsNotManagedBySdk() {
String clientName = "foobarasync";
SdkAsyncHttpClient sdkAsyncHttpClient = mock(SdkAsyncHttpClient.class);
TestAsyncClient client = testAsyncClientBuilder()
.region(Region.US_WEST_2)
.httpClient(sdkAsyncHttpClient)
.build();
assertThat(client.clientConfiguration.option(SdkClientOption.ASYNC_HTTP_CLIENT))
.isInstanceOf(AwsDefaultClientBuilder.NonManagedSdkAsyncHttpClient.class);
when(sdkAsyncHttpClient.clientName()).thenReturn(clientName);
assertThat(client.clientConfiguration.option(SdkClientOption.ASYNC_HTTP_CLIENT))
.isInstanceOf(AwsDefaultClientBuilder.NonManagedSdkAsyncHttpClient.class);
assertThat(client.clientConfiguration.option(SdkClientOption.ASYNC_HTTP_CLIENT).clientName())
.isEqualTo(clientName);
verify(defaultAsyncHttpClientFactory, never()).buildWithDefaults(any());
}
@Test
public void clientBuilderFieldsHaveBeanEquivalents() throws Exception {
AwsClientBuilder<TestClientBuilder, TestClient> builder = testClientBuilder();
BeanInfo beanInfo = Introspector.getBeanInfo(builder.getClass());
Method[] clientBuilderMethods = AwsClientBuilder.class.getDeclaredMethods();
Arrays.stream(clientBuilderMethods).filter(m -> !m.isSynthetic()).forEach(builderMethod -> {
String propertyName = builderMethod.getName();
Optional<PropertyDescriptor> propertyForMethod =
Arrays.stream(beanInfo.getPropertyDescriptors())
.filter(property -> property.getName().equals(propertyName))
.findFirst();
assertThat(propertyForMethod).as(propertyName + " property").hasValueSatisfying(property -> {
assertThat(property.getReadMethod()).as(propertyName + " getter").isNull();
assertThat(property.getWriteMethod()).as(propertyName + " setter").isNotNull();
});
});
}
private AwsClientBuilder<TestClientBuilder, TestClient> testClientBuilder() {
ClientOverrideConfiguration overrideConfig =
ClientOverrideConfiguration.builder()
.putAdvancedOption(SIGNER, TEST_SIGNER)
.putAdvancedOption(ENABLE_DEFAULT_REGION_DETECTION, false)
.build();
return new TestClientBuilder().credentialsProvider(AnonymousCredentialsProvider.create())
.overrideConfiguration(overrideConfig);
}
private AwsClientBuilder<TestAsyncClientBuilder, TestAsyncClient> testAsyncClientBuilder() {
ClientOverrideConfiguration overrideConfig =
ClientOverrideConfiguration.builder()
.putAdvancedOption(SIGNER, TEST_SIGNER)
.putAdvancedOption(ENABLE_DEFAULT_REGION_DETECTION, false)
.build();
return new TestAsyncClientBuilder().credentialsProvider(AnonymousCredentialsProvider.create())
.overrideConfiguration(overrideConfig);
}
private static class TestClient {
private final SdkClientConfiguration clientConfiguration;
public TestClient(SdkClientConfiguration clientConfiguration) {
this.clientConfiguration = clientConfiguration;
}
}
private class TestClientBuilder extends AwsDefaultClientBuilder<TestClientBuilder, TestClient>
implements AwsClientBuilder<TestClientBuilder, TestClient> {
public TestClientBuilder() {
super(defaultHttpClientBuilder, null, autoModeDiscovery);
}
@Override
protected TestClient buildClient() {
return new TestClient(super.syncClientConfiguration());
}
@Override
protected String serviceEndpointPrefix() {
return ENDPOINT_PREFIX;
}
@Override
protected String signingName() {
return SIGNING_NAME;
}
@Override
protected String serviceName() {
return SERVICE_NAME;
}
@Override
protected AttributeMap serviceHttpConfig() {
return MOCK_DEFAULTS;
}
}
private static class TestAsyncClient {
private final SdkClientConfiguration clientConfiguration;
private TestAsyncClient(SdkClientConfiguration clientConfiguration) {
this.clientConfiguration = clientConfiguration;
}
}
private class TestAsyncClientBuilder extends AwsDefaultClientBuilder<TestAsyncClientBuilder, TestAsyncClient>
implements AwsClientBuilder<TestAsyncClientBuilder, TestAsyncClient> {
public TestAsyncClientBuilder() {
super(defaultHttpClientBuilder, defaultAsyncHttpClientFactory, autoModeDiscovery);
}
@Override
protected TestAsyncClient buildClient() {
return new TestAsyncClient(super.asyncClientConfiguration());
}
@Override
protected String serviceEndpointPrefix() {
return ENDPOINT_PREFIX;
}
@Override
protected String signingName() {
return SIGNING_NAME;
}
@Override
protected String serviceName() {
return SERVICE_NAME;
}
@Override
protected AttributeMap serviceHttpConfig() {
return MOCK_DEFAULTS;
}
}
}
| 1,500 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore | Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/interceptor/TraceIdExecutionInterceptorTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore.interceptor;
import static org.assertj.core.api.Assertions.assertThat;
import java.net.URI;
import java.util.Properties;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
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.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.testutils.EnvironmentVariableHelper;
public class TraceIdExecutionInterceptorTest {
@Test
public void nothingDoneWithoutEnvSettings() {
EnvironmentVariableHelper.run(env -> {
resetRelevantEnvVars(env);
Context.ModifyHttpRequest context = context();
assertThat(modifyHttpRequest(context)).isSameAs(context.httpRequest());
});
}
@Test
public void headerAddedWithEnvSettings() {
EnvironmentVariableHelper.run(env -> {
resetRelevantEnvVars(env);
env.set("AWS_LAMBDA_FUNCTION_NAME", "foo");
env.set("_X_AMZN_TRACE_ID", "bar");
Context.ModifyHttpRequest context = context();
assertThat(modifyHttpRequest(context).firstMatchingHeader("X-Amzn-Trace-Id")).hasValue("bar");
});
}
@Test
public void headerAddedWithSysPropWhenNoEnvSettings() {
EnvironmentVariableHelper.run(env -> {
resetRelevantEnvVars(env);
env.set("AWS_LAMBDA_FUNCTION_NAME", "foo");
Properties props = System.getProperties();
props.setProperty("com.amazonaws.xray.traceHeader", "sys-prop");
Context.ModifyHttpRequest context = context();
assertThat(modifyHttpRequest(context).firstMatchingHeader("X-Amzn-Trace-Id")).hasValue("sys-prop");
});
}
@Test
public void headerAddedWithEnvVariableValueWhenBothEnvAndSysPropAreSet() {
EnvironmentVariableHelper.run(env -> {
resetRelevantEnvVars(env);
env.set("AWS_LAMBDA_FUNCTION_NAME", "foo");
env.set("_X_AMZN_TRACE_ID", "bar");
Properties props = System.getProperties();
props.setProperty("com.amazonaws.xray.traceHeader", "sys-prop");
Context.ModifyHttpRequest context = context();
assertThat(modifyHttpRequest(context).firstMatchingHeader("X-Amzn-Trace-Id")).hasValue("sys-prop");
});
}
@Test
public void headerNotAddedIfHeaderAlreadyExists() {
EnvironmentVariableHelper.run(env -> {
resetRelevantEnvVars(env);
env.set("AWS_LAMBDA_FUNCTION_NAME", "foo");
env.set("_X_AMZN_TRACE_ID", "bar");
Context.ModifyHttpRequest context = context(SdkHttpRequest.builder()
.uri(URI.create("https://localhost"))
.method(SdkHttpMethod.GET)
.putHeader("X-Amzn-Trace-Id", "existing")
.build());
assertThat(modifyHttpRequest(context)).isSameAs(context.httpRequest());
});
}
@Test
public void headerNotAddedIfNotInLambda() {
EnvironmentVariableHelper.run(env -> {
resetRelevantEnvVars(env);
env.set("_X_AMZN_TRACE_ID", "bar");
Context.ModifyHttpRequest context = context();
assertThat(modifyHttpRequest(context)).isSameAs(context.httpRequest());
});
}
@Test
public void headerNotAddedIfNoTraceIdEnvVar() {
EnvironmentVariableHelper.run(env -> {
resetRelevantEnvVars(env);
env.set("_X_AMZN_TRACE_ID", "bar");
Context.ModifyHttpRequest context = context();
assertThat(modifyHttpRequest(context)).isSameAs(context.httpRequest());
});
}
private Context.ModifyHttpRequest context() {
return context(SdkHttpRequest.builder()
.uri(URI.create("https://localhost"))
.method(SdkHttpMethod.GET)
.build());
}
private Context.ModifyHttpRequest context(SdkHttpRequest request) {
return InterceptorContext.builder()
.request(Mockito.mock(SdkRequest.class))
.httpRequest(request)
.build();
}
private SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context) {
return new TraceIdExecutionInterceptor().modifyHttpRequest(context, new ExecutionAttributes());
}
private void resetRelevantEnvVars(EnvironmentVariableHelper env) {
env.remove("AWS_LAMBDA_FUNCTION_NAME");
env.remove("_X_AMZN_TRACE_ID");
}
} | 1,501 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore | Create_ds/aws-sdk-java-v2/core/aws-core/src/test/java/software/amazon/awssdk/awscore/interceptor/HelpfulUnknownHostExceptionInterceptorTest.java | package software.amazon.awssdk.awscore.interceptor;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.net.UnknownHostException;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import software.amazon.awssdk.awscore.AwsExecutionAttribute;
import software.amazon.awssdk.core.SdkRequest;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.interceptor.ExecutionInterceptor;
import software.amazon.awssdk.core.interceptor.InterceptorContext;
import software.amazon.awssdk.core.internal.interceptor.DefaultFailedExecutionContext;
import software.amazon.awssdk.regions.Region;
public class HelpfulUnknownHostExceptionInterceptorTest {
private static final ExecutionInterceptor INTERCEPTOR = new HelpfulUnknownHostExceptionInterceptor();
@Test
public void modifyException_skipsNonUnknownHostExceptions() {
IOException exception = new IOException();
assertThat(modifyException(exception)).isEqualTo(exception);
}
@Test
public void modifyException_supportsNestedUnknownHostExceptions() {
Exception exception = new UnknownHostException();
exception.initCause(new IOException());
exception = new IllegalArgumentException(exception);
exception = new UnsupportedOperationException(exception);
assertThat(modifyException(exception, Region.AWS_GLOBAL)).isInstanceOf(SdkClientException.class);
}
@Test
public void modifyException_returnsGenericHelp_forGlobalRegions() {
UnknownHostException exception = new UnknownHostException();
assertThat(modifyException(exception, Region.AWS_GLOBAL))
.isInstanceOf(SdkClientException.class)
.hasMessageContaining("network");
}
@Test
public void modifyException_returnsGenericHelp_forUnknownServices() {
UnknownHostException exception = new UnknownHostException();
assertThat(modifyException(exception, Region.US_EAST_1, "millems-hotdog-stand"))
.isInstanceOf(SdkClientException.class)
.satisfies(t -> doesNotHaveMessageContaining(t, "global"))
.hasMessageContaining("network");
}
@Test
public void modifyException_returnsGenericHelp_forUnknownServicesInUnknownRegions() {
UnknownHostException exception = new UnknownHostException();
assertThat(modifyException(exception, Region.of("cn-north-99"), "millems-hotdog-stand"))
.isInstanceOf(SdkClientException.class)
.satisfies(t -> doesNotHaveMessageContaining(t, "global"))
.hasMessageContaining("network");
}
@Test
public void modifyException_returnsGenericHelp_forServicesRegionalizedInAllPartitions() {
UnknownHostException exception = new UnknownHostException();
assertThat(modifyException(exception, Region.US_EAST_1, "dynamodb"))
.isInstanceOf(SdkClientException.class)
.satisfies(t -> doesNotHaveMessageContaining(t, "global"))
.hasMessageContaining("network");
}
@Test
public void modifyException_returnsGenericGlobalRegionHelp_forServicesGlobalInSomePartitionOtherThanTheClientPartition() {
UnknownHostException exception = new UnknownHostException();
assertThat(modifyException(exception, Region.of("cn-north-99"), "iam"))
.isInstanceOf(SdkClientException.class)
.satisfies(t -> doesNotHaveMessageContaining(t, "network"))
.hasMessageContaining("aws-global")
.hasMessageContaining("aws-cn-global");
}
@Test
public void modifyException_returnsSpecificGlobalRegionHelp_forServicesGlobalInTheClientRegionPartition() {
UnknownHostException exception = new UnknownHostException();
assertThat(modifyException(exception, Region.of("cn-north-1"), "iam"))
.isInstanceOf(SdkClientException.class)
.satisfies(t -> doesNotHaveMessageContaining(t, "aws-global"))
.hasMessageContaining("aws-cn-global");
}
private void doesNotHaveMessageContaining(Throwable throwable, String value) {
assertThat(throwable.getMessage()).doesNotContain(value);
}
private Throwable modifyException(Throwable throwable) {
return modifyException(throwable, null);
}
private Throwable modifyException(Throwable throwable, Region clientRegion) {
return modifyException(throwable, clientRegion, null);
}
private Throwable modifyException(Throwable throwable, Region clientRegion, String serviceEndpointPrefix) {
SdkRequest sdkRequest = Mockito.mock(SdkRequest.class);
DefaultFailedExecutionContext context =
DefaultFailedExecutionContext.builder()
.interceptorContext(InterceptorContext.builder().request(sdkRequest).build())
.exception(throwable)
.build();
ExecutionAttributes executionAttributes =
new ExecutionAttributes().putAttribute(AwsExecutionAttribute.AWS_REGION, clientRegion)
.putAttribute(AwsExecutionAttribute.ENDPOINT_PREFIX, serviceEndpointPrefix);
return INTERCEPTOR.modifyException(context, executionAttributes);
}
} | 1,502 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/AwsRequestOverrideConfiguration.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore;
import java.util.Objects;
import java.util.Optional;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.auth.credentials.CredentialUtils;
import software.amazon.awssdk.core.RequestOverrideConfiguration;
import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity;
import software.amazon.awssdk.identity.spi.IdentityProvider;
import software.amazon.awssdk.utils.builder.SdkBuilder;
/**
* Request-specific configuration overrides for AWS service clients.
*/
@SdkPublicApi
public final class AwsRequestOverrideConfiguration extends RequestOverrideConfiguration {
private final IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider;
private AwsRequestOverrideConfiguration(BuilderImpl builder) {
super(builder);
this.credentialsProvider = builder.awsCredentialsProvider;
}
/**
* Create a {@link AwsRequestOverrideConfiguration} from the provided {@link RequestOverrideConfiguration}.
*
* Given null, this will return null. Given a {@code AwsRequestOverrideConfiguration} this will return the input. Given
* any other {@code RequestOverrideConfiguration} this will return a new {@code AwsRequestOverrideConfiguration} with all
* the common attributes from the input copied into the result.
*/
public static AwsRequestOverrideConfiguration from(RequestOverrideConfiguration configuration) {
if (configuration == null) {
return null;
}
if (configuration instanceof AwsRequestOverrideConfiguration) {
return (AwsRequestOverrideConfiguration) configuration;
}
return new AwsRequestOverrideConfiguration.BuilderImpl(configuration).build();
}
/**
* The optional {@link AwsCredentialsProvider} that will provide credentials to be used to authenticate this request.
*
* @return The optional {@link AwsCredentialsProvider}.
*/
public Optional<AwsCredentialsProvider> credentialsProvider() {
return Optional.ofNullable(CredentialUtils.toCredentialsProvider(credentialsProvider));
}
/**
* The optional {@link IdentityProvider<? extends AwsCredentialsIdentity>} that will provide credentials to be used to
* authenticate this request.
*
* @return The optional {@link IdentityProvider<? extends AwsCredentialsIdentity>}.
*/
public Optional<IdentityProvider<? extends AwsCredentialsIdentity>> credentialsIdentityProvider() {
return Optional.ofNullable(credentialsProvider);
}
@Override
public Builder toBuilder() {
return new BuilderImpl(this);
}
public static Builder builder() {
return new BuilderImpl();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
AwsRequestOverrideConfiguration that = (AwsRequestOverrideConfiguration) o;
return Objects.equals(credentialsProvider, that.credentialsProvider);
}
@Override
public int hashCode() {
int hashCode = 1;
hashCode = 31 * hashCode + super.hashCode();
hashCode = 31 * hashCode + Objects.hashCode(credentialsProvider);
return hashCode;
}
public interface Builder extends RequestOverrideConfiguration.Builder<Builder>,
SdkBuilder<Builder, AwsRequestOverrideConfiguration> {
/**
* Set the optional {@link AwsCredentialsProvider} that will provide credentials to be used to authenticate this request.
*
* @param credentialsProvider The {@link AwsCredentialsProvider}.
* @return This object for chaining.
*/
default Builder credentialsProvider(AwsCredentialsProvider credentialsProvider) {
return credentialsProvider((IdentityProvider<AwsCredentialsIdentity>) credentialsProvider);
}
/**
* Set the optional {@link IdentityProvider<? extends AwsCredentialsIdentity>} that will provide credentials to be used
* to authenticate this request.
*
* @param credentialsProvider The {@link IdentityProvider<? extends AwsCredentialsIdentity>}.
* @return This object for chaining.
*/
default Builder credentialsProvider(IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider) {
throw new UnsupportedOperationException();
}
/**
* Return the optional {@link AwsCredentialsProvider} that will provide credentials to be used to authenticate this
* request.
*
* @return The optional {@link AwsCredentialsProvider}.
*/
AwsCredentialsProvider credentialsProvider();
@Override
AwsRequestOverrideConfiguration build();
}
private static final class BuilderImpl extends RequestOverrideConfiguration.BuilderImpl<Builder> implements Builder {
private IdentityProvider<? extends AwsCredentialsIdentity> awsCredentialsProvider;
private BuilderImpl() {
}
private BuilderImpl(RequestOverrideConfiguration requestOverrideConfiguration) {
super(requestOverrideConfiguration);
}
private BuilderImpl(AwsRequestOverrideConfiguration awsRequestOverrideConfig) {
super(awsRequestOverrideConfig);
this.awsCredentialsProvider = awsRequestOverrideConfig.credentialsProvider;
}
@Override
public Builder credentialsProvider(IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider) {
this.awsCredentialsProvider = credentialsProvider;
return this;
}
@Override
public AwsCredentialsProvider credentialsProvider() {
return CredentialUtils.toCredentialsProvider(awsCredentialsProvider);
}
@Override
public AwsRequestOverrideConfiguration build() {
return new AwsRequestOverrideConfiguration(this);
}
}
}
| 1,503 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/AwsExecutionAttribute.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute;
import software.amazon.awssdk.awscore.client.config.AwsClientOption;
import software.amazon.awssdk.core.interceptor.ExecutionAttribute;
import software.amazon.awssdk.core.interceptor.ExecutionInterceptor;
import software.amazon.awssdk.core.interceptor.SdkExecutionAttribute;
import software.amazon.awssdk.regions.Region;
/**
* AWS-specific attributes attached to the execution. This information is available to {@link ExecutionInterceptor}s.
*/
@SdkPublicApi
public final class AwsExecutionAttribute extends SdkExecutionAttribute {
/**
* The AWS {@link Region} the client was configured with. This is not always same as the
* {@link AwsSignerExecutionAttribute#SIGNING_REGION} for global services like IAM.
*/
public static final ExecutionAttribute<Region> AWS_REGION = new ExecutionAttribute<>("AwsRegion");
/**
* The {@link AwsClientOption#ENDPOINT_PREFIX} for the client.
*/
public static final ExecutionAttribute<String> ENDPOINT_PREFIX = new ExecutionAttribute<>("AwsEndpointPrefix");
/**
* Whether dualstack endpoints were enabled for this request.
*/
public static final ExecutionAttribute<Boolean> DUALSTACK_ENDPOINT_ENABLED =
new ExecutionAttribute<>("DualstackEndpointsEnabled");
/**
* Whether fips endpoints were enabled for this request.
*/
public static final ExecutionAttribute<Boolean> FIPS_ENDPOINT_ENABLED =
new ExecutionAttribute<>("FipsEndpointsEnabled");
/**
* Whether the client was configured to use the service's global endpoint. This is used as part of endpoint computation by
* the endpoint providers.
*/
public static final ExecutionAttribute<Boolean> USE_GLOBAL_ENDPOINT =
new ExecutionAttribute<>("UseGlobalEndpoint");
private AwsExecutionAttribute() {
}
}
| 1,504 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/AwsRequest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Consumer;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.SdkRequest;
/**
* Base class for all AWS Service requests.
*/
@SdkPublicApi
public abstract class AwsRequest extends SdkRequest {
private final AwsRequestOverrideConfiguration requestOverrideConfig;
protected AwsRequest(Builder builder) {
this.requestOverrideConfig = builder.overrideConfiguration();
}
@Override
public final Optional<AwsRequestOverrideConfiguration> overrideConfiguration() {
return Optional.ofNullable(requestOverrideConfig);
}
@Override
public abstract Builder toBuilder();
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AwsRequest that = (AwsRequest) o;
return Objects.equals(requestOverrideConfig, that.requestOverrideConfig);
}
@Override
public int hashCode() {
return Objects.hashCode(requestOverrideConfig);
}
public interface Builder extends SdkRequest.Builder {
@Override
AwsRequestOverrideConfiguration overrideConfiguration();
/**
* Add an optional request override configuration.
*
* @param awsRequestOverrideConfig The override configuration.
* @return This object for method chaining.
*/
Builder overrideConfiguration(AwsRequestOverrideConfiguration awsRequestOverrideConfig);
/**
* Add an optional request override configuration.
*
* @param builderConsumer A {@link Consumer} to which an empty {@link AwsRequestOverrideConfiguration.Builder} will be
* given.
* @return This object for method chaining.
*/
Builder overrideConfiguration(Consumer<AwsRequestOverrideConfiguration.Builder> builderConsumer);
@Override
AwsRequest build();
}
protected abstract static class BuilderImpl implements Builder {
private AwsRequestOverrideConfiguration awsRequestOverrideConfig;
protected BuilderImpl() {
}
protected BuilderImpl(AwsRequest request) {
request.overrideConfiguration().ifPresent(this::overrideConfiguration);
}
@Override
public Builder overrideConfiguration(AwsRequestOverrideConfiguration awsRequestOverrideConfig) {
this.awsRequestOverrideConfig = awsRequestOverrideConfig;
return this;
}
@Override
public Builder overrideConfiguration(Consumer<AwsRequestOverrideConfiguration.Builder> builderConsumer) {
AwsRequestOverrideConfiguration.Builder b = AwsRequestOverrideConfiguration.builder();
builderConsumer.accept(b);
awsRequestOverrideConfig = b.build();
return this;
}
@Override
public final AwsRequestOverrideConfiguration overrideConfiguration() {
return awsRequestOverrideConfig;
}
}
}
| 1,505 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/AwsResponseMetadata.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore;
import static software.amazon.awssdk.awscore.util.AwsHeader.AWS_REQUEST_ID;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.utils.ToString;
/**
* Represents additional metadata included with a response from a service. Response
* metadata varies by service, but all services return an AWS request ID that
* can be used in the event a service call isn't working as expected and you
* need to work with AWS support to debug an issue.
*/
@SdkProtectedApi
public abstract class AwsResponseMetadata {
private static final String UNKNOWN = "UNKNOWN";
private final Map<String, String> metadata;
/**
* Creates a new ResponseMetadata object from a specified map of raw
* metadata information.
*
* @param metadata
* The raw metadata for the new ResponseMetadata object.
*/
protected AwsResponseMetadata(Map<String, String> metadata) {
this.metadata = Collections.unmodifiableMap(metadata);
}
protected AwsResponseMetadata(AwsResponseMetadata responseMetadata) {
this(responseMetadata == null ? new HashMap<>() : responseMetadata.metadata);
}
/**
* Returns the AWS request ID contained in this response metadata object.
* AWS request IDs can be used in the event a service call isn't working as
* expected and you need to work with AWS support to debug an issue.
*
* <p>
* Can be overriden by subclasses to provide service specific requestId
*
* @return The AWS request ID contained in this response metadata object.
*/
public String requestId() {
return getValue(AWS_REQUEST_ID);
}
@Override
public final String toString() {
return ToString.builder("AwsResponseMetadata")
.add("metadata", metadata.keySet())
.build();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AwsResponseMetadata that = (AwsResponseMetadata) o;
return Objects.equals(metadata, that.metadata);
}
@Override
public int hashCode() {
return Objects.hashCode(metadata);
}
/**
* Get the value based on the key, returning {@link #UNKNOWN} if the value is null.
*
* @param key the key of the value
* @return the value or {@link #UNKNOWN} if not present.
*/
protected final String getValue(String key) {
return Optional.ofNullable(metadata.get(key)).orElse(UNKNOWN);
}
}
| 1,506 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/DefaultAwsResponseMetadata.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore;
import java.util.Map;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.SdkStandardLogger;
/**
* Represents additional metadata included with a response from a service. Response
* metadata varies by service, but all services return an AWS request ID that
* can be used in the event a service call isn't working as expected and you
* need to work with AWS support to debug an issue.
* <p>
* Access to AWS request IDs is also available through the {@link SdkStandardLogger#REQUEST_ID_LOGGER}
* logger.
*/
@SdkProtectedApi
public final class DefaultAwsResponseMetadata extends AwsResponseMetadata {
/**
* Creates a new ResponseMetadata object from a specified map of raw
* metadata information.
*
* @param metadata
* The raw metadata for the new ResponseMetadata object.
*/
private DefaultAwsResponseMetadata(Map<String, String> metadata) {
super(metadata);
}
public static DefaultAwsResponseMetadata create(Map<String, String> metadata) {
return new DefaultAwsResponseMetadata(metadata);
}
}
| 1,507 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/AwsClient.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.core.SdkClient;
/**
* Interface for an AWS Client that extends SdkClient. All AWS service client interfaces should extend this interface.
*/
@SdkPublicApi
@ThreadSafe
public interface AwsClient extends SdkClient {
@Override
default AwsServiceClientConfiguration serviceClientConfiguration() {
throw new UnsupportedOperationException();
}
}
| 1,508 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/AwsResponse.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore;
import java.util.Objects;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.SdkResponse;
/**
* Base class for all AWS Service responses.
*/
@SdkPublicApi
public abstract class AwsResponse extends SdkResponse {
private AwsResponseMetadata responseMetadata;
protected AwsResponse(Builder builder) {
super(builder);
this.responseMetadata = builder.responseMetadata();
}
public AwsResponseMetadata responseMetadata() {
return responseMetadata;
}
@Override
public abstract Builder toBuilder();
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
AwsResponse that = (AwsResponse) o;
return Objects.equals(responseMetadata, that.responseMetadata);
}
@Override
public int hashCode() {
int hashCode = 1;
hashCode = 31 * hashCode + super.hashCode();
hashCode = 31 * hashCode + Objects.hashCode(responseMetadata);
return hashCode;
}
public interface Builder extends SdkResponse.Builder {
AwsResponseMetadata responseMetadata();
Builder responseMetadata(AwsResponseMetadata metadata);
@Override
AwsResponse build();
}
protected abstract static class BuilderImpl extends SdkResponse.BuilderImpl implements Builder {
private AwsResponseMetadata responseMetadata;
protected BuilderImpl() {
}
protected BuilderImpl(AwsResponse response) {
super(response);
this.responseMetadata = response.responseMetadata();
}
@Override
public Builder responseMetadata(AwsResponseMetadata responseMetadata) {
this.responseMetadata = responseMetadata;
return this;
}
@Override
public AwsResponseMetadata responseMetadata() {
return responseMetadata;
}
}
}
| 1,509 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/AwsServiceClientConfiguration.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore;
import java.net.URI;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.SdkServiceClientConfiguration;
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
import software.amazon.awssdk.endpoints.EndpointProvider;
import software.amazon.awssdk.http.auth.spi.scheme.AuthScheme;
import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity;
import software.amazon.awssdk.identity.spi.IdentityProvider;
import software.amazon.awssdk.regions.Region;
/**
* Class to expose AWS service client settings to the user, e.g., region
*/
@SdkPublicApi
public abstract class AwsServiceClientConfiguration extends SdkServiceClientConfiguration {
private final Region region;
private final IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider;
protected AwsServiceClientConfiguration(Builder builder) {
super(builder);
this.region = builder.region();
this.credentialsProvider = builder.credentialsProvider();
}
/**
*
* @return The configured region of the AwsClient
*/
public Region region() {
return this.region;
}
/**
* @return The configured identity provider
*/
public IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider() {
return credentialsProvider;
}
@Override
public int hashCode() {
int result = 1;
result = 31 * result + super.hashCode();
result = 31 * result + (region != null ? region.hashCode() : 0);
result = 31 * result + (credentialsProvider != null ? credentialsProvider.hashCode() : 0);
return result;
}
@Override
public boolean equals(Object o) {
if (!super.equals(o)) {
return false;
}
AwsServiceClientConfiguration that = (AwsServiceClientConfiguration) o;
return Objects.equals(region, that.region)
&& Objects.equals(credentialsProvider, that.credentialsProvider);
}
/**
* The base interface for all AWS service client configuration builders
*/
public interface Builder extends SdkServiceClientConfiguration.Builder {
/**
* Return the region
*/
default Region region() {
throw new UnsupportedOperationException();
}
/**
* Configure the region
*/
default Builder region(Region region) {
throw new UnsupportedOperationException();
}
@Override
default Builder overrideConfiguration(ClientOverrideConfiguration clientOverrideConfiguration) {
throw new UnsupportedOperationException();
}
@Override
default Builder endpointOverride(URI endpointOverride) {
throw new UnsupportedOperationException();
}
@Override
default Builder endpointProvider(EndpointProvider endpointProvider) {
throw new UnsupportedOperationException();
}
@Override
default Builder putAuthScheme(AuthScheme<?> authScheme) {
throw new UnsupportedOperationException();
}
/**
* Configure the credentials provider
*/
default Builder credentialsProvider(IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider) {
throw new UnsupportedOperationException();
}
default IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider() {
throw new UnsupportedOperationException();
}
@Override
AwsServiceClientConfiguration build();
}
protected abstract static class BuilderImpl implements Builder {
protected ClientOverrideConfiguration overrideConfiguration;
protected Region region;
protected URI endpointOverride;
protected EndpointProvider endpointProvider;
protected IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider;
protected Map<String, AuthScheme<?>> authSchemes;
protected BuilderImpl() {
}
protected BuilderImpl(AwsServiceClientConfiguration awsServiceClientConfiguration) {
this.overrideConfiguration = awsServiceClientConfiguration.overrideConfiguration();
this.region = awsServiceClientConfiguration.region();
this.endpointOverride = awsServiceClientConfiguration.endpointOverride().orElse(null);
this.endpointProvider = awsServiceClientConfiguration.endpointProvider().orElse(null);
}
@Override
public final ClientOverrideConfiguration overrideConfiguration() {
return overrideConfiguration;
}
@Override
public final Region region() {
return region;
}
@Override
public final URI endpointOverride() {
return endpointOverride;
}
@Override
public final EndpointProvider endpointProvider() {
return endpointProvider;
}
@Override
public final Builder credentialsProvider(IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider) {
this.credentialsProvider = credentialsProvider;
return this;
}
@Override
public final IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider() {
return credentialsProvider;
}
@Override
public final Builder putAuthScheme(AuthScheme<?> authScheme) {
if (authSchemes == null) {
authSchemes = new HashMap<>();
}
authSchemes.put(authScheme.schemeId(), authScheme);
return this;
}
@Override
public final Map<String, AuthScheme<?>> authSchemes() {
if (authSchemes == null) {
return Collections.emptyMap();
}
return Collections.unmodifiableMap(new HashMap<>(authSchemes));
}
}
}
| 1,510 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/eventstream/EventStreamAsyncResponseTransformer.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore.eventstream;
import static java.util.Collections.emptyList;
import static java.util.Collections.singleton;
import static java.util.Collections.singletonList;
import static software.amazon.awssdk.core.http.HttpResponseHandler.X_AMZN_REQUEST_ID_HEADER;
import static software.amazon.awssdk.core.http.HttpResponseHandler.X_AMZN_REQUEST_ID_HEADERS;
import static software.amazon.awssdk.core.http.HttpResponseHandler.X_AMZ_ID_2_HEADER;
import java.io.ByteArrayInputStream;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.SdkResponse;
import software.amazon.awssdk.core.async.AsyncResponseTransformer;
import software.amazon.awssdk.core.async.SdkPublisher;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.exception.SdkException;
import software.amazon.awssdk.core.http.HttpResponseHandler;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.interceptor.SdkExecutionAttribute;
import software.amazon.awssdk.http.AbortableInputStream;
import software.amazon.awssdk.http.SdkHttpFullResponse;
import software.amazon.awssdk.utils.Logger;
import software.amazon.awssdk.utils.Validate;
import software.amazon.eventstream.Message;
import software.amazon.eventstream.MessageDecoder;
/**
* Unmarshalling layer on top of the {@link AsyncResponseTransformer} to decode event stream messages and deliver them to the
* subscriber.
*
* @param <ResponseT> Initial response type of event stream operation.
* @param <EventT> Base type of event stream message frames.
*/
@SdkProtectedApi
public final class EventStreamAsyncResponseTransformer<ResponseT, EventT>
implements AsyncResponseTransformer<SdkResponse, Void> {
private static final Logger log = Logger.loggerFor(EventStreamAsyncResponseTransformer.class);
/**
* {@link EventStreamResponseHandler} provided by customer.
*/
private final EventStreamResponseHandler<ResponseT, EventT> eventStreamResponseHandler;
/**
* Unmarshalls the initial response.
*/
private final HttpResponseHandler<? extends ResponseT> initialResponseHandler;
/**
* Unmarshalls the event POJO.
*/
private final HttpResponseHandler<? extends EventT> eventResponseHandler;
/**
* Unmarshalls exception events.
*/
private final HttpResponseHandler<? extends Throwable> exceptionResponseHandler;
private final Supplier<ExecutionAttributes> attributesFactory;
/**
* Future to notify on completion. Note that we do not notify this future in the event of an error, that
* is handled separately by the generated client. Ultimately we need this due to a disconnect between
* completion of the request (i.e. finish reading all the data from the wire) and the completion of the event
* stream (i.e. deliver the last event to the subscriber).
*/
private final CompletableFuture<Void> future;
/**
* Whether exceptions may be sent to the downstream event stream response handler. This prevents multiple exception
* deliveries from being performed.
*/
private final AtomicBoolean exceptionsMayBeSent = new AtomicBoolean(true);
/**
* The future generated via {@link #prepare()}.
*/
private volatile CompletableFuture<Void> transformFuture;
/**
* Request Id for the streaming request. The value is populated when the initial response is received from the service.
* As request id is not sent in event messages (including exceptions), this can be returned by the SDK along with
* received exception details.
*/
private volatile String requestId = null;
/**
* Extended Request Id for the streaming request. The value is populated when the initial response is received from the
* service. As request id is not sent in event messages (including exceptions), this can be returned by the SDK along with
* received exception details.
*/
private volatile String extendedRequestId = null;
private EventStreamAsyncResponseTransformer(
EventStreamResponseHandler<ResponseT, EventT> eventStreamResponseHandler,
HttpResponseHandler<? extends ResponseT> initialResponseHandler,
HttpResponseHandler<? extends EventT> eventResponseHandler,
HttpResponseHandler<? extends Throwable> exceptionResponseHandler,
CompletableFuture<Void> future,
String serviceName) {
this.eventStreamResponseHandler = eventStreamResponseHandler;
this.initialResponseHandler = initialResponseHandler;
this.eventResponseHandler = eventResponseHandler;
this.exceptionResponseHandler = exceptionResponseHandler;
this.future = future;
this.attributesFactory = () -> new ExecutionAttributes().putAttribute(SdkExecutionAttribute.SERVICE_NAME, serviceName);
}
/**
* Creates a {@link Builder} used to create {@link EventStreamAsyncResponseTransformer}.
*
* @param <ResponseT> Initial response type.
* @param <EventT> Event type being delivered.
* @return New {@link Builder} instance.
*/
public static <ResponseT, EventT> Builder<ResponseT, EventT> builder() {
return new Builder<>();
}
@Override
public CompletableFuture<Void> prepare() {
transformFuture = new CompletableFuture<>();
return transformFuture;
}
@Override
public void onResponse(SdkResponse response) {
// Capture the request IDs from the initial response, so that we can include them in each event.
if (response != null && response.sdkHttpResponse() != null) {
this.requestId = response.sdkHttpResponse()
.firstMatchingHeader(X_AMZN_REQUEST_ID_HEADERS)
.orElse(null);
this.extendedRequestId = response.sdkHttpResponse()
.firstMatchingHeader(X_AMZ_ID_2_HEADER)
.orElse(null);
log.debug(() -> getLogPrefix() + "Received HTTP response headers: " + response);
}
}
@Override
public void onStream(SdkPublisher<ByteBuffer> publisher) {
Validate.isTrue(transformFuture != null, "onStream() invoked without prepare().");
exceptionsMayBeSent.set(true);
SynchronousMessageDecoder decoder = new SynchronousMessageDecoder();
eventStreamResponseHandler.onEventStream(publisher.flatMapIterable(decoder::decode)
.flatMapIterable(this::transformMessage)
.doAfterOnComplete(this::handleOnStreamComplete)
.doAfterOnError(this::handleOnStreamError)
.doAfterOnCancel(this::handleOnStreamCancel));
}
@Override
public void exceptionOccurred(Throwable throwable) {
if (exceptionsMayBeSent.compareAndSet(true, false)) {
try {
eventStreamResponseHandler.exceptionOccurred(throwable);
} catch (RuntimeException e) {
log.warn(() -> "Exception raised by exceptionOccurred. Ignoring.", e);
}
transformFuture.completeExceptionally(throwable);
}
}
private void handleOnStreamComplete() {
log.trace(() -> getLogPrefix() + "Event stream completed successfully.");
exceptionsMayBeSent.set(false);
eventStreamResponseHandler.complete();
transformFuture.complete(null);
future.complete(null);
}
private void handleOnStreamError(Throwable throwable) {
log.trace(() -> getLogPrefix() + "Event stream failed.", throwable);
exceptionOccurred(throwable);
}
private void handleOnStreamCancel() {
log.trace(() -> getLogPrefix() + "Event stream cancelled.");
exceptionsMayBeSent.set(false);
transformFuture.complete(null);
future.complete(null);
}
private static final class SynchronousMessageDecoder {
private final MessageDecoder decoder = new MessageDecoder();
private Iterable<Message> decode(ByteBuffer bytes) {
decoder.feed(bytes);
return decoder.getDecodedMessages();
}
}
private Iterable<EventT> transformMessage(Message message) {
try {
if (isEvent(message)) {
return transformEventMessage(message);
} else if (isError(message) || isException(message)) {
throw transformErrorMessage(message);
} else {
log.debug(() -> getLogPrefix() + "Decoded a message of an unknown type, it will be dropped: " + message);
return emptyList();
}
} catch (Error | SdkException e) {
throw e;
} catch (Throwable e) {
throw SdkClientException.builder().cause(e).build();
}
}
private Iterable<EventT> transformEventMessage(Message message) throws Exception {
SdkHttpFullResponse response = adaptMessageToResponse(message, false);
if (message.getHeaders().get(":event-type").getString().equals("initial-response")) {
ResponseT initialResponse = initialResponseHandler.handle(response, attributesFactory.get());
eventStreamResponseHandler.responseReceived(initialResponse);
log.debug(() -> getLogPrefix() + "Decoded initial response: " + initialResponse);
return emptyList();
}
EventT event = eventResponseHandler.handle(response, attributesFactory.get());
log.debug(() -> getLogPrefix() + "Decoded event: " + event);
return singleton(event);
}
private Throwable transformErrorMessage(Message message) throws Exception {
SdkHttpFullResponse errorResponse = adaptMessageToResponse(message, true);
Throwable exception = exceptionResponseHandler.handle(errorResponse, attributesFactory.get());
log.debug(() -> getLogPrefix() + "Decoded error or exception: " + exception, exception);
return exception;
}
private String getLogPrefix() {
if (requestId == null) {
return "";
}
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("(");
stringBuilder.append("RequestId: ").append(requestId);
if (extendedRequestId != null) {
stringBuilder.append(", ExtendedRequestId: ").append(extendedRequestId);
}
stringBuilder.append(") ");
return stringBuilder.toString();
}
/**
* Transforms an event stream message into a {@link SdkHttpFullResponse} so we can reuse our existing generated unmarshallers.
*
* @param message Message to transform.
*/
private SdkHttpFullResponse adaptMessageToResponse(Message message, boolean isException) {
Map<String, List<String>> headers =
message.getHeaders()
.entrySet()
.stream()
.collect(HashMap::new, (m, e) -> m.put(e.getKey(), singletonList(e.getValue().getString())), Map::putAll);
if (requestId != null) {
headers.put(X_AMZN_REQUEST_ID_HEADER, singletonList(requestId));
}
if (extendedRequestId != null) {
headers.put(X_AMZ_ID_2_HEADER, singletonList(extendedRequestId));
}
SdkHttpFullResponse.Builder builder =
SdkHttpFullResponse.builder()
.content(AbortableInputStream.create(new ByteArrayInputStream(message.getPayload())))
.headers(headers);
if (!isException) {
builder.statusCode(200);
}
return builder.build();
}
/**
* @param m Message frame.
* @return True if frame is an event frame, false if not.
*/
private boolean isEvent(Message m) {
return "event".equals(m.getHeaders().get(":message-type").getString());
}
/**
* @param m Message frame.
* @return True if frame is an error frame, false if not.
*/
private boolean isError(Message m) {
return "error".equals(m.getHeaders().get(":message-type").getString());
}
/**
* @param m Message frame.
* @return True if frame is an exception frame, false if not.
*/
private boolean isException(Message m) {
return "exception".equals(m.getHeaders().get(":message-type").getString());
}
/**
* Builder for {@link EventStreamAsyncResponseTransformer}.
*
* @param <ResponseT> Initial response type.
* @param <EventT> Event type being delivered.
*/
public static final class Builder<ResponseT, EventT> {
private EventStreamResponseHandler<ResponseT, EventT> eventStreamResponseHandler;
private HttpResponseHandler<? extends ResponseT> initialResponseHandler;
private HttpResponseHandler<? extends EventT> eventResponseHandler;
private HttpResponseHandler<? extends Throwable> exceptionResponseHandler;
private CompletableFuture<Void> future;
private String serviceName;
private Builder() {
}
/**
* @param eventStreamResponseHandler Response handler provided by customer.
* @return This object for method chaining.
*/
public Builder<ResponseT, EventT> eventStreamResponseHandler(
EventStreamResponseHandler<ResponseT, EventT> eventStreamResponseHandler) {
this.eventStreamResponseHandler = eventStreamResponseHandler;
return this;
}
/**
* @param initialResponseHandler Response handler for the initial-response event stream message.
* @return This object for method chaining.
*/
public Builder<ResponseT, EventT> initialResponseHandler(
HttpResponseHandler<? extends ResponseT> initialResponseHandler) {
this.initialResponseHandler = initialResponseHandler;
return this;
}
/**
* @param eventResponseHandler Response handler for the various event types.
* @return This object for method chaining.
*/
public Builder<ResponseT, EventT> eventResponseHandler(HttpResponseHandler<? extends EventT> eventResponseHandler) {
this.eventResponseHandler = eventResponseHandler;
return this;
}
/**
* @param exceptionResponseHandler Response handler for error and exception messages.
* @return This object for method chaining.
*/
public Builder<ResponseT, EventT> exceptionResponseHandler(
HttpResponseHandler<? extends Throwable> exceptionResponseHandler) {
this.exceptionResponseHandler = exceptionResponseHandler;
return this;
}
/**
* This is no longer being used, but is left behind because this is a protected API.
*/
@Deprecated
public Builder<ResponseT, EventT> executor(Executor executor) {
return this;
}
/**
* @param future Future to notify when the last event has been delivered.
* @return This object for method chaining.
*/
public Builder<ResponseT, EventT> future(CompletableFuture<Void> future) {
this.future = future;
return this;
}
/**
* @param serviceName Descriptive name for the service to be used in exception unmarshalling.
* @return This object for method chaining.
*/
public Builder<ResponseT, EventT> serviceName(String serviceName) {
this.serviceName = serviceName;
return this;
}
public EventStreamAsyncResponseTransformer<ResponseT, EventT> build() {
return new EventStreamAsyncResponseTransformer<>(eventStreamResponseHandler,
initialResponseHandler,
eventResponseHandler,
exceptionResponseHandler,
future,
serviceName);
}
}
}
| 1,511 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/eventstream/EventStreamInitialRequestInterceptor.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore.eventstream;
import static software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute.HAS_INITIAL_REQUEST_EVENT;
import static software.amazon.awssdk.core.internal.util.Mimetype.MIMETYPE_EVENT_STREAM;
import static software.amazon.awssdk.http.Header.CONTENT_TYPE;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import org.reactivestreams.Publisher;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.core.interceptor.Context.ModifyHttpRequest;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.interceptor.ExecutionInterceptor;
import software.amazon.awssdk.core.internal.async.AsyncStreamPrepender;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.eventstream.HeaderValue;
import software.amazon.eventstream.Message;
/**
* An interceptor for event stream requests sent over RPC. This interceptor will prepend the initial request (i.e. the
* serialized request POJO) to the stream of events supplied by the caller.
*/
@SdkProtectedApi
public class EventStreamInitialRequestInterceptor implements ExecutionInterceptor {
@Override
public SdkHttpRequest modifyHttpRequest(
ModifyHttpRequest context, ExecutionAttributes executionAttributes
) {
if (!Boolean.TRUE.equals(executionAttributes.getAttribute(HAS_INITIAL_REQUEST_EVENT))) {
return context.httpRequest();
}
return context.httpRequest().toBuilder()
.removeHeader(CONTENT_TYPE)
.putHeader(CONTENT_TYPE, MIMETYPE_EVENT_STREAM)
.build();
}
@Override
public Optional<AsyncRequestBody> modifyAsyncHttpContent(
ModifyHttpRequest context, ExecutionAttributes executionAttributes
) {
if (!Boolean.TRUE.equals(executionAttributes.getAttribute(HAS_INITIAL_REQUEST_EVENT))) {
return context.asyncRequestBody();
}
/*
* At this point in the request execution, the requestBody contains the serialized initial request,
* and the asyncRequestBody contains the event stream proper. We will prepend the former to the
* latter.
*/
byte[] payload = getInitialRequestPayload(context);
String contentType = context.httpRequest()
.firstMatchingHeader(CONTENT_TYPE)
.orElseThrow(() -> new IllegalStateException(CONTENT_TYPE + " header not defined."));
Map<String, HeaderValue> initialRequestEventHeaders = new HashMap<>();
initialRequestEventHeaders.put(":message-type", HeaderValue.fromString("event"));
initialRequestEventHeaders.put(":event-type", HeaderValue.fromString("initial-request"));
initialRequestEventHeaders.put(":content-type", HeaderValue.fromString(contentType));
ByteBuffer initialRequest = new Message(initialRequestEventHeaders, payload).toByteBuffer();
Publisher<ByteBuffer> asyncRequestBody = context.asyncRequestBody()
.orElseThrow(() -> new IllegalStateException("This request is an event streaming request and thus "
+ "should have an asyncRequestBody"));
Publisher<ByteBuffer> withInitialRequest = new AsyncStreamPrepender<>(asyncRequestBody, initialRequest);
return Optional.of(AsyncRequestBody.fromPublisher(withInitialRequest));
}
private byte[] getInitialRequestPayload(ModifyHttpRequest context) {
RequestBody requestBody = context.requestBody()
.orElseThrow(() -> new IllegalStateException("This request should have a requestBody"));
byte[] payload;
try {
try (InputStream inputStream = requestBody.contentStreamProvider().newStream()) {
payload = new byte[inputStream.available()];
int bytesRead = inputStream.read(payload);
if (bytesRead != payload.length) {
throw new IllegalStateException("Expected " + payload.length + " bytes, but only got " +
bytesRead + " bytes");
}
}
} catch (IOException ex) {
throw new RuntimeException("Unable to read serialized request payload", ex);
}
return payload;
}
}
| 1,512 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/eventstream/EventStreamTaggedUnionJsonMarshaller.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore.eventstream;
import static java.util.stream.Collectors.toList;
import java.util.HashMap;
import java.util.Map;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.runtime.transform.Marshaller;
import software.amazon.awssdk.http.SdkHttpFullRequest;
/**
* Composite {@link Marshaller} that dispatches the given event to the
* correct marshaller based on the event class type.
*
* @param <BaseEventT> Base type for all events.
*/
@SdkProtectedApi
public final class EventStreamTaggedUnionJsonMarshaller<BaseEventT> implements Marshaller<BaseEventT> {
private final Map<Class<? extends BaseEventT>,
Marshaller<BaseEventT>> marshallers;
private final Marshaller<BaseEventT> defaultMarshaller;
private EventStreamTaggedUnionJsonMarshaller(Builder<BaseEventT> builder) {
this.marshallers = new HashMap<>(builder.marshallers);
this.defaultMarshaller = builder.defaultMarshaller;
}
@Override
public SdkHttpFullRequest marshall(BaseEventT eventT) {
return marshallers.getOrDefault(eventT.getClass(), defaultMarshaller).marshall(eventT);
}
public static Builder builder() {
return new Builder();
}
public static final class Builder<BaseEventT> {
private final Map<Class<? extends BaseEventT>, Marshaller<BaseEventT>> marshallers = new HashMap<>();
private Marshaller<BaseEventT> defaultMarshaller;
private Builder() {
}
/**
* Registers a new {@link Marshaller} with given event class type.
*
* @param eventClass Class type of the event
* @param marshaller Marshaller for the event
* @return This object for method chaining
*/
public Builder putMarshaller(Class<? extends BaseEventT> eventClass,
Marshaller<BaseEventT> marshaller) {
marshallers.put(eventClass, marshaller);
return this;
}
public EventStreamTaggedUnionJsonMarshaller<BaseEventT> build() {
defaultMarshaller = e -> {
String errorMsg = "Event type should be one of the following types: " +
marshallers.keySet().stream().map(Class::getSimpleName).collect(toList());
throw new IllegalArgumentException(errorMsg);
};
return new EventStreamTaggedUnionJsonMarshaller<>(this);
}
}
}
| 1,513 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/eventstream/DefaultEventStreamResponseHandlerBuilder.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore.eventstream;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import org.reactivestreams.Subscriber;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.async.SdkPublisher;
import software.amazon.awssdk.utils.async.SequentialSubscriber;
/**
* Base class for event stream response handler builders.
*
* @param <ResponseT> Type of POJO response.
* @param <EventT> Type of event being published.
* @param <SubBuilderT> Subtype of builder class for method chaining.
*/
@SdkProtectedApi
public abstract class DefaultEventStreamResponseHandlerBuilder<ResponseT, EventT, SubBuilderT>
implements EventStreamResponseHandler.Builder<ResponseT, EventT, SubBuilderT> {
private Consumer<ResponseT> onResponse;
private Consumer<Throwable> onError;
private Runnable onComplete;
private Supplier<Subscriber<EventT>> subscriber;
private Consumer<SdkPublisher<EventT>> onSubscribe;
private Function<SdkPublisher<EventT>, SdkPublisher<EventT>> publisherTransformer;
protected DefaultEventStreamResponseHandlerBuilder() {
}
@Override
public SubBuilderT onResponse(Consumer<ResponseT> responseConsumer) {
this.onResponse = responseConsumer;
return subclass();
}
Consumer<ResponseT> onResponse() {
return onResponse;
}
@Override
public SubBuilderT onError(Consumer<Throwable> consumer) {
this.onError = consumer;
return subclass();
}
Consumer<Throwable> onError() {
return onError;
}
@Override
public SubBuilderT onComplete(Runnable onComplete) {
this.onComplete = onComplete;
return subclass();
}
Runnable onComplete() {
return onComplete;
}
@Override
public SubBuilderT subscriber(Supplier<Subscriber<EventT>> eventSubscriber) {
this.subscriber = eventSubscriber;
return subclass();
}
@Override
public SubBuilderT subscriber(Consumer<EventT> eventConsumer) {
this.subscriber = () -> new SequentialSubscriber<>(eventConsumer, new CompletableFuture<>());
return subclass();
}
Supplier<Subscriber<EventT>> subscriber() {
return subscriber;
}
@Override
public SubBuilderT onEventStream(Consumer<SdkPublisher<EventT>> onSubscribe) {
this.onSubscribe = onSubscribe;
return subclass();
}
Consumer<SdkPublisher<EventT>> onEventStream() {
return onSubscribe;
}
@Override
public SubBuilderT publisherTransformer(Function<SdkPublisher<EventT>, SdkPublisher<EventT>> publisherTransformer) {
this.publisherTransformer = publisherTransformer;
return subclass();
}
Function<SdkPublisher<EventT>, SdkPublisher<EventT>> publisherTransformer() {
return publisherTransformer;
}
private SubBuilderT subclass() {
return (SubBuilderT) this;
}
}
| 1,514 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/eventstream/EventStreamResponseHandler.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore.eventstream;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.async.SdkPublisher;
/**
* Response handler for event streaming operations.
*
* @param <ResponseT> the POJO response type
* @param <EventT> the event type
*/
@SdkProtectedApi
public interface EventStreamResponseHandler<ResponseT, EventT> {
/**
* Called when the initial response has been received and the POJO response has
* been unmarshalled. This is guaranteed to be called before {@link #onEventStream(SdkPublisher)}.
*
* <p>In the event of a retryable error, this callback may be called multiple times. It
* also may never be invoked if the request never succeeds.</p>
*
* @param response Unmarshalled POJO containing metadata about the streamed data.
*/
void responseReceived(ResponseT response);
/**
* Called when events are ready to be streamed. Implementations must subscribe to the {@link Publisher} and request data via
* a {@link org.reactivestreams.Subscription} as they can handle it.
*
* <p>
* If at any time the subscriber wishes to stop receiving data, it may call {@link Subscription#cancel()}. This
* will <b>NOT</b> be treated as a failure of the response and the response will be completed normally.
* </p>
*
* <p>This callback may never be called if the response has no content or if an error occurs.</p>
*
* <p>
* In the event of a retryable error, this callback may be called multiple times with different Publishers.
* If this method is called more than once, implementation must either reset any state to prepare for another
* stream of data or must throw an exception indicating they cannot reset. If any exception is thrown then no
* automatic retry is performed.
* </p>
*/
void onEventStream(SdkPublisher<EventT> publisher);
/**
* Called when an exception occurs while establishing the connection or streaming the response. Implementations
* should free up any resources in this method. This method may be called multiple times during the lifecycle
* of a request if automatic retries are enabled.
*
* @param throwable Exception that occurred.
*/
void exceptionOccurred(Throwable throwable);
/**
* Called when all data has been successfully published to the {@link org.reactivestreams.Subscriber}. This will
* only be called once during the lifecycle of the request. Implementors should free up any resources they have
* opened.
*/
void complete();
/**
* Base builder for sub-interfaces of {@link EventStreamResponseHandler}.
*/
interface Builder<ResponseT, EventT, SubBuilderT> {
/**
* Callback to invoke when the initial response is received.
*
* @param responseConsumer Callback that will process the initial response.
* @return This builder for method chaining.
*/
SubBuilderT onResponse(Consumer<ResponseT> responseConsumer);
/**
* Callback to invoke in the event on an error.
*
* @param consumer Callback that will process any error that occurs.
* @return This builder for method chaining.
*/
SubBuilderT onError(Consumer<Throwable> consumer);
/**
* Action to invoke when the event stream completes. This will only be invoked
* when all events are being received.
*
* @param runnable Action to run on the completion of the event stream.
* @return This builder for method chaining.
*/
SubBuilderT onComplete(Runnable runnable);
/**
* Subscriber that will subscribe to the {@link SdkPublisher} of events. Subscriber
* must be provided.
*
* @param eventSubscriberSupplier Supplier for a subscriber that will be subscribed to the publisher of events.
* @return This builder for method chaining.
*/
SubBuilderT subscriber(Supplier<Subscriber<EventT>> eventSubscriberSupplier);
/**
* Sets the subscriber to the {@link SdkPublisher} of events. The given consumer will be called for each event received
* by the publisher. Events are requested sequentially after each event is processed. If you need more control over
* the backpressure strategy consider using {@link #subscriber(Supplier)} instead.
*
* @param eventConsumer Consumer that will process incoming events.
* @return This builder for method chaining.
*/
SubBuilderT subscriber(Consumer<EventT> eventConsumer);
/**
* Callback to invoke when the {@link SdkPublisher} is available. This callback must subscribe to the given publisher.
* This method should not be used with {@link #subscriber(Supplier)} or any of it's overloads.
*
* @param onSubscribe Callback that will subscribe to the {@link SdkPublisher}.
* @return This builder for method chaining.
*/
SubBuilderT onEventStream(Consumer<SdkPublisher<EventT>> onSubscribe);
/**
* Allows for optional transformation of the publisher of events before subscribing. This transformation must return
* a {@link SdkPublisher} of the same type so methods like {@link SdkPublisher#map(Function)} and
* {@link SdkPublisher#buffer(int)} that change the type cannot be used with this method.
*
* @param publisherTransformer Function that returns a new {@link SdkPublisher} with augmented behavior.
* @return This builder for method chaining.
*/
SubBuilderT publisherTransformer(Function<SdkPublisher<EventT>, SdkPublisher<EventT>> publisherTransformer);
}
}
| 1,515 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/eventstream/EventStreamTaggedUnionPojoSupplier.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore.eventstream;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.SdkPojo;
import software.amazon.awssdk.http.SdkHttpFullResponse;
@SdkProtectedApi
public final class EventStreamTaggedUnionPojoSupplier implements Function<SdkHttpFullResponse, SdkPojo> {
private final Map<String, Supplier<SdkPojo>> pojoSuppliers;
private final Supplier<SdkPojo> defaultPojoSupplier;
private EventStreamTaggedUnionPojoSupplier(Builder builder) {
this.pojoSuppliers = new HashMap<>(builder.pojoSuppliers);
this.defaultPojoSupplier = builder.defaultPojoSupplier;
}
@Override
public SdkPojo apply(SdkHttpFullResponse sdkHttpFullResponse) {
String eventType = sdkHttpFullResponse.firstMatchingHeader(":event-type").orElse(null);
return pojoSuppliers.getOrDefault(eventType, defaultPojoSupplier).get();
}
public static Builder builder() {
return new Builder();
}
public static final class Builder {
private final Map<String, Supplier<SdkPojo>> pojoSuppliers = new HashMap<>();
private Supplier<SdkPojo> defaultPojoSupplier;
private Builder() {
}
/**
* Registers a new {@link Supplier} of an {@link SdkPojo} associated with a given event type.
*
* @param type Value of ':event-type' header this unmarshaller handles.
* @param pojoSupplier Supplier of {@link SdkPojo}.
* @return This object for method chaining.
*/
public Builder putSdkPojoSupplier(String type,
Supplier<SdkPojo> pojoSupplier) {
pojoSuppliers.put(type, pojoSupplier);
return this;
}
/**
* Registers the default {@link SdkPojo} supplier. Used when the value in the ':event-type' header does not match
* a registered event type (i.e. this is a new event that this version of the SDK doesn't know about).
*
* @param defaultPojoSupplier Default POJO supplier to use when event-type doesn't match a registered event type.
* @return This object for method chaining.
*/
public Builder defaultSdkPojoSupplier(Supplier<SdkPojo> defaultPojoSupplier) {
this.defaultPojoSupplier = defaultPojoSupplier;
return this;
}
public EventStreamTaggedUnionPojoSupplier build() {
return new EventStreamTaggedUnionPojoSupplier(this);
}
}
}
| 1,516 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/eventstream/EventStreamResponseHandlerFromBuilder.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore.eventstream;
import static software.amazon.awssdk.utils.Validate.getOrDefault;
import static software.amazon.awssdk.utils.Validate.mutuallyExclusive;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import org.reactivestreams.Subscriber;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.async.SdkPublisher;
import software.amazon.awssdk.utils.FunctionalUtils;
/**
* Base class for creating implementations of an {@link EventStreamResponseHandler} from a builder.
* See {@link EventStreamResponseHandler.Builder}.
*
* @param <ResponseT> Type of initial response object.
* @param <EventT> Type of event being published.
*/
@SdkProtectedApi
public abstract class EventStreamResponseHandlerFromBuilder<ResponseT, EventT>
implements EventStreamResponseHandler<ResponseT, EventT> {
private final Consumer<ResponseT> responseConsumer;
private final Consumer<Throwable> errorConsumer;
private final Runnable onComplete;
private final Consumer<SdkPublisher<EventT>> onEventStream;
private final Function<SdkPublisher<EventT>, SdkPublisher<EventT>> publisherTransformer;
protected EventStreamResponseHandlerFromBuilder(DefaultEventStreamResponseHandlerBuilder<ResponseT, EventT, ?> builder) {
mutuallyExclusive("onEventStream and subscriber are mutually exclusive, set only one on the Builder",
builder.onEventStream(), builder.subscriber());
Supplier<Subscriber<EventT>> subscriber = builder.subscriber();
this.onEventStream = subscriber != null ? p -> p.subscribe(subscriber.get()) : builder.onEventStream();
if (this.onEventStream == null) {
throw new IllegalArgumentException("Must provide either a subscriber or set onEventStream "
+ "and subscribe to the publisher in the callback method");
}
this.responseConsumer = getOrDefault(builder.onResponse(), FunctionalUtils::noOpConsumer);
this.errorConsumer = getOrDefault(builder.onError(), FunctionalUtils::noOpConsumer);
this.onComplete = getOrDefault(builder.onComplete(), FunctionalUtils::noOpRunnable);
this.publisherTransformer = getOrDefault(builder.publisherTransformer(), Function::identity);
}
@Override
public void responseReceived(ResponseT response) {
responseConsumer.accept(response);
}
@Override
public void onEventStream(SdkPublisher<EventT> p) {
onEventStream.accept(publisherTransformer.apply(p));
}
@Override
public void exceptionOccurred(Throwable throwable) {
errorConsumer.accept(throwable);
}
@Override
public void complete() {
this.onComplete.run();
}
}
| 1,517 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/eventstream/RestEventStreamAsyncResponseTransformer.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore.eventstream;
import java.nio.ByteBuffer;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.SdkResponse;
import software.amazon.awssdk.core.async.AsyncResponseTransformer;
import software.amazon.awssdk.core.async.SdkPublisher;
/**
* Adapter transformer meant for eventstream responses from REST services (REST-XML, REST-JSON). These protocols don't have an
* 'initial-response' event, unlike AWS-JSON. In these protocols "initial response" is treated as the HTTP response itself.
* When this transformer's {@link #onResponse(SdkResponse)} method is invoked, it also invokes it on the eventstream
* response handler, which the normal {@link EventStreamAsyncResponseTransformer} does not do.
*
* @param <ResponseT> Initial response type of event stream operation.
* @param <EventT> Base type of event stream message frames.
*/
@SdkProtectedApi
public class RestEventStreamAsyncResponseTransformer<ResponseT extends SdkResponse, EventT>
implements AsyncResponseTransformer<ResponseT, Void> {
private final EventStreamAsyncResponseTransformer<ResponseT, EventT> delegate;
private final EventStreamResponseHandler<ResponseT, EventT> eventStreamResponseHandler;
private RestEventStreamAsyncResponseTransformer(
EventStreamAsyncResponseTransformer<ResponseT, EventT> delegateAsyncResponseTransformer,
EventStreamResponseHandler<ResponseT, EventT> eventStreamResponseHandler) {
this.delegate = delegateAsyncResponseTransformer;
this.eventStreamResponseHandler = eventStreamResponseHandler;
}
@Override
public CompletableFuture<Void> prepare() {
return delegate.prepare();
}
@Override
public void onResponse(ResponseT response) {
delegate.onResponse(response);
eventStreamResponseHandler.responseReceived(response);
}
@Override
public void onStream(SdkPublisher<ByteBuffer> publisher) {
delegate.onStream(publisher);
}
@Override
public void exceptionOccurred(Throwable throwable) {
delegate.exceptionOccurred(throwable);
}
public static <ResponseT extends SdkResponse, EventT> Builder<ResponseT, EventT> builder() {
return new Builder<>();
}
/**
* Builder for {@link RestEventStreamAsyncResponseTransformer}.
*
* @param <ResponseT> Initial response type.
* @param <EventT> Event type being delivered.
*/
public static final class Builder<ResponseT extends SdkResponse, EventT> {
private EventStreamAsyncResponseTransformer<ResponseT, EventT> delegateAsyncResponseTransformer;
private EventStreamResponseHandler<ResponseT, EventT> eventStreamResponseHandler;
private Builder() {
}
/**
* @param delegateAsyncResponseTransformer {@link EventStreamAsyncResponseTransformer} that can be delegated the work
* common for RPC and REST services
* @return This object for method chaining
*/
public Builder<ResponseT, EventT> eventStreamAsyncResponseTransformer(
EventStreamAsyncResponseTransformer<ResponseT, EventT> delegateAsyncResponseTransformer) {
this.delegateAsyncResponseTransformer = delegateAsyncResponseTransformer;
return this;
}
/**
* @param eventStreamResponseHandler Response handler provided by customer.
* @return This object for method chaining.
*/
public Builder<ResponseT, EventT> eventStreamResponseHandler(
EventStreamResponseHandler<ResponseT, EventT> eventStreamResponseHandler) {
this.eventStreamResponseHandler = eventStreamResponseHandler;
return this;
}
public RestEventStreamAsyncResponseTransformer<ResponseT, EventT> build() {
return new RestEventStreamAsyncResponseTransformer<>(delegateAsyncResponseTransformer,
eventStreamResponseHandler);
}
}
}
| 1,518 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/endpoints/AwsEndpointAttribute.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore.endpoints;
import java.util.Collections;
import java.util.List;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.awscore.endpoints.authscheme.EndpointAuthScheme;
import software.amazon.awssdk.endpoints.EndpointAttributeKey;
/**
* Known endpoint attributes added by endpoint rule sets for AWS services.
*/
@SdkProtectedApi
public final class AwsEndpointAttribute {
/**
* The auth schemes supported by the endpoint.
*/
public static final EndpointAttributeKey<List<EndpointAuthScheme>> AUTH_SCHEMES =
EndpointAttributeKey.forList("AuthSchemes");
private AwsEndpointAttribute() {
}
public static List<EndpointAttributeKey<?>> values() {
return Collections.singletonList(AUTH_SCHEMES);
}
}
| 1,519 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/endpoints | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/endpoints/authscheme/EndpointAuthScheme.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore.endpoints.authscheme;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.endpoints.Endpoint;
/**
* An authentication scheme for an {@link Endpoint} returned by an endpoint provider.
*/
@SdkProtectedApi
public interface EndpointAuthScheme {
String name();
default String schemeId() {
throw new UnsupportedOperationException();
}
}
| 1,520 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/endpoints | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/endpoints/authscheme/SigV4AuthScheme.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore.endpoints.authscheme;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* A Signature Version 4 authentication scheme.
*/
@SdkProtectedApi
public final class SigV4AuthScheme implements EndpointAuthScheme {
private final String signingRegion;
private final String signingName;
private final Boolean disableDoubleEncoding;
private SigV4AuthScheme(Builder b) {
this.signingRegion = b.signingRegion;
this.signingName = b.signingName;
this.disableDoubleEncoding = b.disableDoubleEncoding;
}
@Override
public String name() {
return "sigv4";
}
@Override
public String schemeId() {
return "aws.auth#sigv4";
}
public String signingRegion() {
return signingRegion;
}
public String signingName() {
return signingName;
}
public boolean disableDoubleEncoding() {
return disableDoubleEncoding == null ? false : disableDoubleEncoding;
}
public boolean isDisableDoubleEncodingSet() {
return disableDoubleEncoding != null;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SigV4AuthScheme that = (SigV4AuthScheme) o;
if (disableDoubleEncoding != null ? !disableDoubleEncoding.equals(that.disableDoubleEncoding)
: that.disableDoubleEncoding != null) {
return false;
}
if (signingRegion != null ? !signingRegion.equals(that.signingRegion) : that.signingRegion != null) {
return false;
}
return signingName != null ? signingName.equals(that.signingName) : that.signingName == null;
}
@Override
public int hashCode() {
int result = signingRegion != null ? signingRegion.hashCode() : 0;
result = 31 * result + (signingName != null ? signingName.hashCode() : 0);
result = 31 * result + (disableDoubleEncoding != null ? disableDoubleEncoding.hashCode() : 0);
return result;
}
public static Builder builder() {
return new Builder();
}
public static class Builder {
private String signingRegion;
private String signingName;
private Boolean disableDoubleEncoding;
public Builder signingRegion(String signingRegion) {
this.signingRegion = signingRegion;
return this;
}
public Builder signingName(String signingName) {
this.signingName = signingName;
return this;
}
public Builder disableDoubleEncoding(Boolean disableDoubleEncoding) {
this.disableDoubleEncoding = disableDoubleEncoding;
return this;
}
public SigV4AuthScheme build() {
return new SigV4AuthScheme(this);
}
}
}
| 1,521 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/endpoints | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/endpoints/authscheme/SigV4aAuthScheme.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore.endpoints.authscheme;
import java.util.ArrayList;
import java.util.List;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* A Signature Version 4A authentication scheme.
*/
@SdkProtectedApi
public final class SigV4aAuthScheme implements EndpointAuthScheme {
private final String signingName;
private final List<String> signingRegionSet;
private final Boolean disableDoubleEncoding;
private SigV4aAuthScheme(Builder b) {
this.signingName = b.signingName;
this.signingRegionSet = b.signingRegionSet;
this.disableDoubleEncoding = b.disableDoubleEncoding;
}
public String signingName() {
return signingName;
}
public boolean disableDoubleEncoding() {
return disableDoubleEncoding == null ? false : disableDoubleEncoding;
}
public boolean isDisableDoubleEncodingSet() {
return disableDoubleEncoding != null;
}
public List<String> signingRegionSet() {
return signingRegionSet;
}
@Override
public String name() {
return "sigv4a";
}
@Override
public String schemeId() {
return "aws.auth#sigv4a";
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SigV4aAuthScheme that = (SigV4aAuthScheme) o;
if (disableDoubleEncoding != null ? !disableDoubleEncoding.equals(that.disableDoubleEncoding)
: that.disableDoubleEncoding != null) {
return false;
}
if (signingName != null ? !signingName.equals(that.signingName) : that.signingName != null) {
return false;
}
return signingRegionSet != null ? signingRegionSet.equals(that.signingRegionSet) : that.signingRegionSet == null;
}
@Override
public int hashCode() {
int result = signingName != null ? signingName.hashCode() : 0;
result = 31 * result + (signingRegionSet != null ? signingRegionSet.hashCode() : 0);
result = 31 * result + (disableDoubleEncoding != null ? disableDoubleEncoding.hashCode() : 0);
return result;
}
public static Builder builder() {
return new Builder();
}
public static class Builder {
private final List<String> signingRegionSet = new ArrayList<>();
private String signingName;
private Boolean disableDoubleEncoding;
public Builder addSigningRegion(String signingRegion) {
this.signingRegionSet.add(signingRegion);
return this;
}
public Builder signingName(String signingName) {
this.signingName = signingName;
return this;
}
public Builder disableDoubleEncoding(Boolean disableDoubleEncoding) {
this.disableDoubleEncoding = disableDoubleEncoding;
return this;
}
public SigV4aAuthScheme build() {
return new SigV4aAuthScheme(this);
}
}
}
| 1,522 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/retry/AwsRetryPolicy.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore.retry;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.awscore.internal.AwsErrorCode;
import software.amazon.awssdk.awscore.retry.conditions.RetryOnErrorCodeCondition;
import software.amazon.awssdk.core.retry.RetryMode;
import software.amazon.awssdk.core.retry.RetryPolicy;
import software.amazon.awssdk.core.retry.conditions.OrRetryCondition;
import software.amazon.awssdk.core.retry.conditions.RetryCondition;
/**
* Retry Policy used by clients when communicating with AWS services.
*/
@SdkPublicApi
public final class AwsRetryPolicy {
private AwsRetryPolicy() {
}
/**
* Retrieve the {@link RetryCondition#defaultRetryCondition()} with AWS-specific conditions added.
*/
public static RetryCondition defaultRetryCondition() {
return OrRetryCondition.create(RetryCondition.defaultRetryCondition(), awsRetryCondition());
}
/**
* Retrieve the {@link RetryPolicy#defaultRetryPolicy()} with AWS-specific conditions added.
*/
public static RetryPolicy defaultRetryPolicy() {
return forRetryMode(RetryMode.defaultRetryMode());
}
/**
* Retrieve the {@link RetryPolicy#defaultRetryPolicy()} with AWS-specific conditions added. This uses the specified
* {@link RetryMode} when constructing the {@link RetryPolicy}.
*/
public static RetryPolicy forRetryMode(RetryMode retryMode) {
return addRetryConditions(RetryPolicy.forRetryMode(retryMode));
}
/**
* Update the provided {@link RetryPolicy} to add AWS-specific conditions.
*/
public static RetryPolicy addRetryConditions(RetryPolicy condition) {
return condition.toBuilder()
.retryCondition(OrRetryCondition.create(condition.retryCondition(), awsRetryCondition()))
.build();
}
private static RetryOnErrorCodeCondition awsRetryCondition() {
return RetryOnErrorCodeCondition.create(AwsErrorCode.RETRYABLE_ERROR_CODES);
}
}
| 1,523 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/retry | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/retry/conditions/RetryOnErrorCodeCondition.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore.retry.conditions;
import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.awscore.exception.AwsServiceException;
import software.amazon.awssdk.core.retry.RetryPolicyContext;
import software.amazon.awssdk.core.retry.conditions.RetryCondition;
/**
* Retry condition implementation that retries if the exception or the cause of the exception matches the error codes defined.
*/
@SdkPublicApi
public final class RetryOnErrorCodeCondition implements RetryCondition {
private final Set<String> retryableErrorCodes;
private RetryOnErrorCodeCondition(Set<String> retryableErrorCodes) {
this.retryableErrorCodes = retryableErrorCodes;
}
@Override
public boolean shouldRetry(RetryPolicyContext context) {
Exception ex = context.exception();
if (ex instanceof AwsServiceException) {
AwsServiceException exception = (AwsServiceException) ex;
return retryableErrorCodes.contains(exception.awsErrorDetails().errorCode());
}
return false;
}
public static RetryOnErrorCodeCondition create(String... retryableErrorCodes) {
return new RetryOnErrorCodeCondition(Arrays.stream(retryableErrorCodes).collect(Collectors.toSet()));
}
public static RetryOnErrorCodeCondition create(Set<String> retryableErrorCodes) {
return new RetryOnErrorCodeCondition(retryableErrorCodes);
}
}
| 1,524 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/util/AwsHostNameUtils.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore.util;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.regions.Region;
@SdkProtectedApi
//TODO This isn't used for as many services as it supports. Can we simplify or remove it?
public final class AwsHostNameUtils {
private static final Pattern S3_ENDPOINT_PATTERN =
Pattern.compile("^(?:.+\\.)?s3[.-]([a-z0-9-]+)$");
private static final Pattern STANDARD_CLOUDSEARCH_ENDPOINT_PATTERN =
Pattern.compile("^(?:.+\\.)?([a-z0-9-]+)\\.cloudsearch$");
private static final Pattern EXTENDED_CLOUDSEARCH_ENDPOINT_PATTERN =
Pattern.compile("^(?:.+\\.)?([a-z0-9-]+)\\.cloudsearch\\..+");
private AwsHostNameUtils() {
}
/**
* Attempts to parse the region name from an endpoint based on conventions
* about the endpoint format.
*
* @param host the hostname to parse
* @param serviceHint an optional hint about the service for the endpoint
* @return the region parsed from the hostname, or
* null if no region information could be found.
*/
public static Optional<Region> parseSigningRegion(final String host, final String serviceHint) {
if (host == null) {
throw new IllegalArgumentException("hostname cannot be null");
}
if (host.endsWith(".amazonaws.com")) {
int index = host.length() - ".amazonaws.com".length();
return parseStandardRegionName(host.substring(0, index));
}
if (serviceHint != null) {
if (serviceHint.equals("cloudsearch") && !host.startsWith("cloudsearch.")) {
// CloudSearch domains use the nonstandard domain format
// [domain].[region].cloudsearch.[suffix].
Matcher matcher = EXTENDED_CLOUDSEARCH_ENDPOINT_PATTERN.matcher(host);
if (matcher.matches()) {
return Optional.of(Region.of(matcher.group(1)));
}
}
// If we have a service hint, look for 'service.[region]' or
// 'service-[region]' in the endpoint's hostname.
Pattern pattern = Pattern.compile("^(?:.+\\.)?" + Pattern.quote(serviceHint) + "[.-]([a-z0-9-]+)\\.");
Matcher matcher = pattern.matcher(host);
if (matcher.find()) {
return Optional.of(Region.of(matcher.group(1)));
}
}
// Endpoint is non-standard
return Optional.empty();
}
/**
* Parses the region name from a standard (*.amazonaws.com) endpoint.
*
* @param fragment the portion of the endpoint excluding
* ".amazonaws.com"
* @return the parsed region name (or "us-east-1" as a
* best guess if we can't tell for sure)
*/
private static Optional<Region> parseStandardRegionName(final String fragment) {
Matcher matcher = S3_ENDPOINT_PATTERN.matcher(fragment);
if (matcher.matches()) {
// host was 'bucket.s3-[region].amazonaws.com'.
return Optional.of(Region.of(matcher.group(1)));
}
matcher = STANDARD_CLOUDSEARCH_ENDPOINT_PATTERN.matcher(fragment);
if (matcher.matches()) {
// host was 'domain.[region].cloudsearch.amazonaws.com'.
return Optional.of(Region.of(matcher.group(1)));
}
int index = fragment.lastIndexOf('.');
if (index == -1) {
// host was 'service.amazonaws.com', assume they're talking about us-east-1.
return Optional.of(Region.US_EAST_1);
}
// host was 'service.[region].amazonaws.com'.
String region = fragment.substring(index + 1);
// Special case for iam.us-gov.amazonaws.com, which is actually
// us-gov-west-1.
if ("us-gov".equals(region)) {
region = "us-gov-west-1";
}
if ("s3".equals(region)) {
region = fragment.substring(index + 4);
}
return Optional.of(Region.of(region));
}
}
| 1,525 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/util/AwsHeader.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore.util;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* Constants for commonly used Aws headers.
*/
@SdkProtectedApi
public final class AwsHeader {
public static final String AWS_REQUEST_ID = "AWS_REQUEST_ID";
private AwsHeader() {
}
}
| 1,526 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/util/SignerOverrideUtils.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore.util;
import java.util.Optional;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.awscore.AwsRequest;
import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration;
import software.amazon.awssdk.core.RequestOverrideConfiguration;
import software.amazon.awssdk.core.SdkRequest;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.interceptor.ExecutionInterceptor;
import software.amazon.awssdk.core.interceptor.SdkExecutionAttribute;
import software.amazon.awssdk.core.signer.Signer;
/**
* Utility to override a given {@link SdkRequest}'s {@link Signer}. Typically used by {@link ExecutionInterceptor}s that wish to
* dynamically enable particular signing methods, like SigV4a for multi-region endpoints.
*/
@SdkProtectedApi
public final class SignerOverrideUtils {
private SignerOverrideUtils() {
}
/**
* @deprecated No longer used by modern clients after migration to reference architecture
*/
@Deprecated
public static SdkRequest overrideSignerIfNotOverridden(SdkRequest request,
ExecutionAttributes executionAttributes,
Signer signer) {
return overrideSignerIfNotOverridden(request, executionAttributes, () -> signer);
}
/**
* @deprecated No longer used by modern clients after migration to reference architecture
*/
@Deprecated
public static SdkRequest overrideSignerIfNotOverridden(SdkRequest request,
ExecutionAttributes executionAttributes,
Supplier<Signer> signer) {
if (isSignerOverridden(request, executionAttributes)) {
return request;
}
return overrideSigner(request, signer.get());
}
public static boolean isSignerOverridden(SdkRequest request, ExecutionAttributes executionAttributes) {
boolean isClientSignerOverridden =
Boolean.TRUE.equals(executionAttributes.getAttribute(SdkExecutionAttribute.SIGNER_OVERRIDDEN));
Optional<Signer> requestSigner = request.overrideConfiguration()
.flatMap(RequestOverrideConfiguration::signer);
return isClientSignerOverridden || requestSigner.isPresent();
}
/**
* @deprecated No longer used by modern clients after migration to reference architecture
*/
@Deprecated
private static SdkRequest overrideSigner(SdkRequest request, Signer signer) {
return request.overrideConfiguration()
.flatMap(config -> config.signer()
.map(existingOverrideSigner -> request))
.orElseGet(() -> createNewRequest(request, signer));
}
/**
* @deprecated No longer used by modern clients after migration to reference architecture
*/
@Deprecated
private static SdkRequest createNewRequest(SdkRequest request, Signer signer) {
AwsRequest awsRequest = (AwsRequest) request;
AwsRequestOverrideConfiguration modifiedOverride =
awsRequest.overrideConfiguration()
.map(AwsRequestOverrideConfiguration::toBuilder)
.orElseGet(AwsRequestOverrideConfiguration::builder)
.signer(signer)
.build();
return awsRequest.toBuilder()
.overrideConfiguration(modifiedOverride)
.build();
}
}
| 1,527 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/internal/AwsStatusCode.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore.internal;
import static java.util.Collections.unmodifiableSet;
import java.util.HashSet;
import java.util.Set;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* Contains AWS-specific meanings behind status codes.
*/
@SdkInternalApi
public class AwsStatusCode {
public static final Set<Integer> POSSIBLE_CLOCK_SKEW_STATUS_CODES;
static {
Set<Integer> clockSkewErrorCodes = new HashSet<>(2);
clockSkewErrorCodes.add(401);
clockSkewErrorCodes.add(403);
POSSIBLE_CLOCK_SKEW_STATUS_CODES = unmodifiableSet(clockSkewErrorCodes);
}
private AwsStatusCode() {
}
public static boolean isPossibleClockSkewStatusCode(int statusCode) {
return POSSIBLE_CLOCK_SKEW_STATUS_CODES.contains(statusCode);
}
}
| 1,528 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/internal/AwsExecutionContextBuilder.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore.internal;
import static software.amazon.awssdk.auth.signer.internal.util.SignerMethodResolver.resolveSigningMethodUsed;
import static software.amazon.awssdk.core.interceptor.SdkExecutionAttribute.RESOLVED_CHECKSUM_SPECS;
import java.util.Map;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute;
import software.amazon.awssdk.awscore.AwsExecutionAttribute;
import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration;
import software.amazon.awssdk.awscore.client.config.AwsClientOption;
import software.amazon.awssdk.awscore.internal.authcontext.AuthorizationStrategy;
import software.amazon.awssdk.awscore.internal.authcontext.AuthorizationStrategyFactory;
import software.amazon.awssdk.awscore.util.SignerOverrideUtils;
import software.amazon.awssdk.core.HttpChecksumConstant;
import software.amazon.awssdk.core.RequestOverrideConfiguration;
import software.amazon.awssdk.core.SdkRequest;
import software.amazon.awssdk.core.SdkResponse;
import software.amazon.awssdk.core.SelectedAuthScheme;
import software.amazon.awssdk.core.client.config.SdkAdvancedClientOption;
import software.amazon.awssdk.core.client.config.SdkClientConfiguration;
import software.amazon.awssdk.core.client.config.SdkClientOption;
import software.amazon.awssdk.core.client.handler.ClientExecutionParams;
import software.amazon.awssdk.core.http.ExecutionContext;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.interceptor.ExecutionInterceptorChain;
import software.amazon.awssdk.core.interceptor.InterceptorContext;
import software.amazon.awssdk.core.interceptor.SdkExecutionAttribute;
import software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute;
import software.amazon.awssdk.core.internal.InternalCoreExecutionAttribute;
import software.amazon.awssdk.core.internal.util.HttpChecksumResolver;
import software.amazon.awssdk.core.signer.Signer;
import software.amazon.awssdk.endpoints.EndpointProvider;
import software.amazon.awssdk.http.auth.scheme.NoAuthAuthScheme;
import software.amazon.awssdk.http.auth.spi.scheme.AuthScheme;
import software.amazon.awssdk.http.auth.spi.scheme.AuthSchemeProvider;
import software.amazon.awssdk.identity.spi.IdentityProviders;
import software.amazon.awssdk.metrics.MetricCollector;
@SdkInternalApi
public final class AwsExecutionContextBuilder {
private AwsExecutionContextBuilder() {
}
/**
* Used by both sync and async clients to create the execution context, and run initial interceptors.
*/
public static <InputT extends SdkRequest, OutputT extends SdkResponse> ExecutionContext
invokeInterceptorsAndCreateExecutionContext(ClientExecutionParams<InputT, OutputT> executionParams,
SdkClientConfiguration clientConfig) {
// Note: This is currently copied to DefaultS3Presigner and other presigners.
// Don't edit this without considering those
SdkRequest originalRequest = executionParams.getInput();
MetricCollector metricCollector = resolveMetricCollector(executionParams);
ExecutionAttributes executionAttributes = mergeExecutionAttributeOverrides(
executionParams.executionAttributes(),
clientConfig.option(SdkClientOption.EXECUTION_ATTRIBUTES),
originalRequest.overrideConfiguration().map(c -> c.executionAttributes()).orElse(null));
executionAttributes.putAttributeIfAbsent(SdkExecutionAttribute.API_CALL_METRIC_COLLECTOR, metricCollector);
executionAttributes
.putAttribute(InternalCoreExecutionAttribute.EXECUTION_ATTEMPT, 1)
.putAttribute(AwsSignerExecutionAttribute.SERVICE_CONFIG,
clientConfig.option(SdkClientOption.SERVICE_CONFIGURATION))
.putAttribute(AwsSignerExecutionAttribute.SERVICE_SIGNING_NAME,
clientConfig.option(AwsClientOption.SERVICE_SIGNING_NAME))
.putAttribute(AwsExecutionAttribute.AWS_REGION, clientConfig.option(AwsClientOption.AWS_REGION))
.putAttribute(AwsExecutionAttribute.ENDPOINT_PREFIX, clientConfig.option(AwsClientOption.ENDPOINT_PREFIX))
.putAttribute(AwsSignerExecutionAttribute.SIGNING_REGION, clientConfig.option(AwsClientOption.SIGNING_REGION))
.putAttribute(SdkInternalExecutionAttribute.IS_FULL_DUPLEX, executionParams.isFullDuplex())
.putAttribute(SdkInternalExecutionAttribute.HAS_INITIAL_REQUEST_EVENT, executionParams.hasInitialRequestEvent())
.putAttribute(SdkExecutionAttribute.CLIENT_TYPE, clientConfig.option(SdkClientOption.CLIENT_TYPE))
.putAttribute(SdkExecutionAttribute.SERVICE_NAME, clientConfig.option(SdkClientOption.SERVICE_NAME))
.putAttribute(SdkInternalExecutionAttribute.PROTOCOL_METADATA, executionParams.getProtocolMetadata())
.putAttribute(SdkExecutionAttribute.PROFILE_FILE, clientConfig.option(SdkClientOption.PROFILE_FILE_SUPPLIER) != null ?
clientConfig.option(SdkClientOption.PROFILE_FILE_SUPPLIER).get() :
null)
.putAttribute(SdkExecutionAttribute.PROFILE_FILE_SUPPLIER, clientConfig.option(SdkClientOption.PROFILE_FILE_SUPPLIER))
.putAttribute(SdkExecutionAttribute.PROFILE_NAME, clientConfig.option(SdkClientOption.PROFILE_NAME))
.putAttribute(AwsExecutionAttribute.DUALSTACK_ENDPOINT_ENABLED,
clientConfig.option(AwsClientOption.DUALSTACK_ENDPOINT_ENABLED))
.putAttribute(AwsExecutionAttribute.FIPS_ENDPOINT_ENABLED,
clientConfig.option(AwsClientOption.FIPS_ENDPOINT_ENABLED))
.putAttribute(SdkExecutionAttribute.OPERATION_NAME, executionParams.getOperationName())
.putAttribute(SdkExecutionAttribute.CLIENT_ENDPOINT, clientConfig.option(SdkClientOption.ENDPOINT))
.putAttribute(SdkExecutionAttribute.ENDPOINT_OVERRIDDEN, clientConfig.option(SdkClientOption.ENDPOINT_OVERRIDDEN))
.putAttribute(SdkInternalExecutionAttribute.ENDPOINT_PROVIDER,
resolveEndpointProvider(originalRequest, clientConfig))
.putAttribute(SdkInternalExecutionAttribute.CLIENT_CONTEXT_PARAMS,
clientConfig.option(SdkClientOption.CLIENT_CONTEXT_PARAMS))
.putAttribute(SdkInternalExecutionAttribute.DISABLE_HOST_PREFIX_INJECTION,
clientConfig.option(SdkAdvancedClientOption.DISABLE_HOST_PREFIX_INJECTION))
.putAttribute(SdkExecutionAttribute.SIGNER_OVERRIDDEN, clientConfig.option(SdkClientOption.SIGNER_OVERRIDDEN))
.putAttribute(AwsExecutionAttribute.USE_GLOBAL_ENDPOINT,
clientConfig.option(AwsClientOption.USE_GLOBAL_ENDPOINT))
.putAttribute(RESOLVED_CHECKSUM_SPECS, HttpChecksumResolver.resolveChecksumSpecs(executionAttributes));
// Auth Scheme resolution related attributes
putAuthSchemeResolutionAttributes(executionAttributes, clientConfig, originalRequest);
ExecutionInterceptorChain executionInterceptorChain =
new ExecutionInterceptorChain(clientConfig.option(SdkClientOption.EXECUTION_INTERCEPTORS));
InterceptorContext interceptorContext = InterceptorContext.builder()
.request(originalRequest)
.asyncRequestBody(executionParams.getAsyncRequestBody())
.requestBody(executionParams.getRequestBody())
.build();
interceptorContext = runInitialInterceptors(interceptorContext, executionAttributes, executionInterceptorChain);
Signer signer = null;
if (loadOldSigner(executionAttributes, originalRequest)) {
AuthorizationStrategyFactory authorizationStrategyFactory =
new AuthorizationStrategyFactory(interceptorContext.request(), metricCollector, clientConfig);
AuthorizationStrategy authorizationStrategy =
authorizationStrategyFactory.strategyFor(executionParams.credentialType());
authorizationStrategy.addCredentialsToExecutionAttributes(executionAttributes);
signer = authorizationStrategy.resolveSigner();
}
executionAttributes.putAttribute(HttpChecksumConstant.SIGNING_METHOD,
resolveSigningMethodUsed(
signer, executionAttributes, executionAttributes.getOptionalAttribute(
AwsSignerExecutionAttribute.AWS_CREDENTIALS).orElse(null)));
return ExecutionContext.builder()
.interceptorChain(executionInterceptorChain)
.interceptorContext(interceptorContext)
.executionAttributes(executionAttributes)
.signer(signer)
.metricCollector(metricCollector)
.build();
}
/**
* We will load the old (non-SRA) signer if this client seems like an old version or the customer has provided a signer
* override. We assume that if there's no auth schemes defined, we're on the old code path.
* <p>
* In addition, if authType=none, we don't need to use the old signer, even if overridden.
*/
private static boolean loadOldSigner(ExecutionAttributes attributes, SdkRequest request) {
Map<String, AuthScheme<?>> authSchemes = attributes.getAttribute(SdkInternalExecutionAttribute.AUTH_SCHEMES);
if (authSchemes == null) {
// pre SRA case.
// We used to set IS_NONE_AUTH_TYPE_REQUEST = false when authType=none. Yes, false.
return attributes.getOptionalAttribute(SdkInternalExecutionAttribute.IS_NONE_AUTH_TYPE_REQUEST).orElse(true);
}
// post SRA case.
// By default, SRA uses new HttpSigner, so we shouldn't use old non-SRA Signer, unless the customer has provided a signer
// override.
// But, if the operation was modeled as authTpye=None, we don't want to use the provided overridden Signer either. In
// post SRA, modeled authType=None would default to NoAuthAuthScheme.
// Note, for authType=None operation, technically, customer could override the AuthSchemeProvider and select a different
// AuthScheme (than NoAuthAuthScheme). In this case, we are choosing to use the customer's overridden Signer.
SelectedAuthScheme<?> selectedAuthScheme = attributes.getAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME);
return SignerOverrideUtils.isSignerOverridden(request, attributes) &&
selectedAuthScheme != null &&
!NoAuthAuthScheme.SCHEME_ID.equals(selectedAuthScheme.authSchemeOption().schemeId());
}
private static void putAuthSchemeResolutionAttributes(ExecutionAttributes executionAttributes,
SdkClientConfiguration clientConfig,
SdkRequest originalRequest) {
// TODO(sra-identity-and-auth): When request-level auth scheme provider is added, use the request-level auth scheme
// provider if the customer specified an override, otherwise fall back to the one on the client.
AuthSchemeProvider authSchemeProvider = clientConfig.option(SdkClientOption.AUTH_SCHEME_PROVIDER);
// Use auth schemes that the user specified at the request level with
// preference over those on the client.
// TODO(sra-identity-and-auth): The request level schemes should be "merged" with client level, with request preferred
// over client.
Map<String, AuthScheme<?>> authSchemes = clientConfig.option(SdkClientOption.AUTH_SCHEMES);
IdentityProviders identityProviders = resolveIdentityProviders(originalRequest, clientConfig);
executionAttributes
.putAttribute(SdkInternalExecutionAttribute.AUTH_SCHEME_RESOLVER, authSchemeProvider)
.putAttribute(SdkInternalExecutionAttribute.AUTH_SCHEMES, authSchemes)
.putAttribute(SdkInternalExecutionAttribute.IDENTITY_PROVIDERS, identityProviders);
}
// TODO(sra-identity-and-auth): This is hard coding the logic for the credentialsIdentityProvider from
// AwsRequestOverrideConfiguration. Currently, AwsRequestOverrideConfiguration does not support overriding the
// tokenIdentityProvider. When adding that support this method will need to be updated.
private static IdentityProviders resolveIdentityProviders(SdkRequest originalRequest,
SdkClientConfiguration clientConfig) {
IdentityProviders identityProviders =
clientConfig.option(SdkClientOption.IDENTITY_PROVIDERS);
// identityProviders can be null, for new core with old client. In this case, even if AwsRequestOverrideConfiguration
// has credentialsIdentityProvider set (because it is in new core), it is ok to not setup IDENTITY_PROVIDERS, as old
// client won't have AUTH_SCHEME_PROVIDER/AUTH_SCHEMES set either, which are also needed for SRA logic.
if (identityProviders == null) {
return null;
}
return originalRequest.overrideConfiguration()
.filter(c -> c instanceof AwsRequestOverrideConfiguration)
.map(c -> (AwsRequestOverrideConfiguration) c)
.flatMap(AwsRequestOverrideConfiguration::credentialsIdentityProvider)
.map(identityProvider ->
identityProviders.copy(b -> b.putIdentityProvider(identityProvider)))
.orElse(identityProviders);
}
/**
* Finalize {@link SdkRequest} by running beforeExecution and modifyRequest interceptors.
*
* @param interceptorContext containing the immutable SdkRequest information the interceptor can act on
* @param executionAttributes mutable container of attributes concerning the execution and request
* @return the {@link InterceptorContext} returns a context with a new SdkRequest
*/
public static InterceptorContext runInitialInterceptors(InterceptorContext interceptorContext,
ExecutionAttributes executionAttributes,
ExecutionInterceptorChain executionInterceptorChain) {
executionInterceptorChain.beforeExecution(interceptorContext, executionAttributes);
return executionInterceptorChain.modifyRequest(interceptorContext, executionAttributes);
}
private static <InputT extends SdkRequest, OutputT extends SdkResponse> ExecutionAttributes mergeExecutionAttributeOverrides(
ExecutionAttributes executionAttributes,
ExecutionAttributes clientOverrideExecutionAttributes,
ExecutionAttributes requestOverrideExecutionAttributes) {
executionAttributes.putAbsentAttributes(requestOverrideExecutionAttributes);
executionAttributes.putAbsentAttributes(clientOverrideExecutionAttributes);
return executionAttributes;
}
private static MetricCollector resolveMetricCollector(ClientExecutionParams<?, ?> params) {
MetricCollector metricCollector = params.getMetricCollector();
if (metricCollector == null) {
metricCollector = MetricCollector.create("ApiCall");
}
return metricCollector;
}
/**
* Resolves the endpoint provider, with the request override configuration taking precedence over the
* provided default client clientConfig.
* @return The endpoint provider that will be used by the SDK to resolve endpoints.
*/
private static EndpointProvider resolveEndpointProvider(SdkRequest request,
SdkClientConfiguration clientConfig) {
return request.overrideConfiguration()
.flatMap(RequestOverrideConfiguration::endpointProvider)
.orElse(clientConfig.option(SdkClientOption.ENDPOINT_PROVIDER));
}
}
| 1,529 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/internal/AwsServiceProtocol.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore.internal;
import software.amazon.awssdk.annotations.SdkInternalApi;
@SdkInternalApi
public enum AwsServiceProtocol {
EC2("ec2"),
AWS_JSON("json"),
REST_JSON("rest-json"),
CBOR("cbor"),
QUERY("query"),
REST_XML("rest-xml");
private String protocol;
AwsServiceProtocol(String protocol) {
this.protocol = protocol;
}
public static AwsServiceProtocol fromValue(String strProtocol) {
if (strProtocol == null) {
return null;
}
for (AwsServiceProtocol protocol : values()) {
if (protocol.protocol.equals(strProtocol)) {
return protocol;
}
}
throw new IllegalArgumentException("Unknown enum value for Protocol : " + strProtocol);
}
@Override
public String toString() {
return protocol;
}
}
| 1,530 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/internal/AwsErrorCode.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore.internal;
import static java.util.Collections.unmodifiableSet;
import java.util.HashSet;
import java.util.Set;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* Contains AWS error codes.
*/
@SdkInternalApi
public final class AwsErrorCode {
public static final Set<String> RETRYABLE_ERROR_CODES;
public static final Set<String> THROTTLING_ERROR_CODES;
public static final Set<String> DEFINITE_CLOCK_SKEW_ERROR_CODES;
public static final Set<String> POSSIBLE_CLOCK_SKEW_ERROR_CODES;
static {
Set<String> throttlingErrorCodes = new HashSet<>(9);
throttlingErrorCodes.add("Throttling");
throttlingErrorCodes.add("ThrottlingException");
throttlingErrorCodes.add("ThrottledException");
throttlingErrorCodes.add("ProvisionedThroughputExceededException");
throttlingErrorCodes.add("SlowDown");
throttlingErrorCodes.add("TooManyRequestsException");
throttlingErrorCodes.add("RequestLimitExceeded");
throttlingErrorCodes.add("BandwidthLimitExceeded");
throttlingErrorCodes.add("RequestThrottled");
throttlingErrorCodes.add("RequestThrottledException");
throttlingErrorCodes.add("EC2ThrottledException");
throttlingErrorCodes.add("TransactionInProgressException");
THROTTLING_ERROR_CODES = unmodifiableSet(throttlingErrorCodes);
Set<String> definiteClockSkewErrorCodes = new HashSet<>(3);
definiteClockSkewErrorCodes.add("RequestTimeTooSkewed");
definiteClockSkewErrorCodes.add("RequestExpired");
definiteClockSkewErrorCodes.add("RequestInTheFuture");
DEFINITE_CLOCK_SKEW_ERROR_CODES = unmodifiableSet(definiteClockSkewErrorCodes);
Set<String> possibleClockSkewErrorCodes = new HashSet<>(3);
possibleClockSkewErrorCodes.add("InvalidSignatureException");
possibleClockSkewErrorCodes.add("SignatureDoesNotMatch");
possibleClockSkewErrorCodes.add("AuthFailure");
POSSIBLE_CLOCK_SKEW_ERROR_CODES = unmodifiableSet(possibleClockSkewErrorCodes);
Set<String> retryableErrorCodes = new HashSet<>(1);
retryableErrorCodes.add("PriorRequestNotComplete");
retryableErrorCodes.add("RequestTimeout");
retryableErrorCodes.add("RequestTimeoutException");
retryableErrorCodes.add("InternalError");
RETRYABLE_ERROR_CODES = unmodifiableSet(retryableErrorCodes);
}
private AwsErrorCode() {
}
public static boolean isThrottlingErrorCode(String errorCode) {
return THROTTLING_ERROR_CODES.contains(errorCode);
}
public static boolean isDefiniteClockSkewErrorCode(String errorCode) {
return DEFINITE_CLOCK_SKEW_ERROR_CODES.contains(errorCode);
}
public static boolean isPossibleClockSkewErrorCode(String errorCode) {
return POSSIBLE_CLOCK_SKEW_ERROR_CODES.contains(errorCode);
}
public static boolean isRetryableErrorCode(String errorCode) {
return RETRYABLE_ERROR_CODES.contains(errorCode);
}
}
| 1,531 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/internal/AwsProtocolMetadata.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore.internal;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.SdkProtocolMetadata;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* Contains AWS-specific protocol metadata. Implementation of {@link SdkProtocolMetadata}.
*/
@SdkInternalApi
public final class AwsProtocolMetadata implements SdkProtocolMetadata, ToCopyableBuilder<AwsProtocolMetadata.Builder,
AwsProtocolMetadata> {
private final AwsServiceProtocol serviceProtocol;
private AwsProtocolMetadata(Builder builder) {
this.serviceProtocol = builder.serviceProtocol;
}
public static Builder builder() {
return new Builder();
}
@Override
public Builder toBuilder() {
return new Builder(this);
}
@Override
public String serviceProtocol() {
return serviceProtocol.toString();
}
@Override
public String toString() {
return ToString.builder("AwsProtocolMetadata")
.add("serviceProtocol", serviceProtocol)
.build();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AwsProtocolMetadata protocolMetadata = (AwsProtocolMetadata) o;
return serviceProtocol == protocolMetadata.serviceProtocol;
}
@Override
public int hashCode() {
return serviceProtocol != null ? serviceProtocol.hashCode() : 0;
}
public static final class Builder implements CopyableBuilder<Builder, AwsProtocolMetadata> {
private AwsServiceProtocol serviceProtocol;
private Builder() {
}
private Builder(AwsProtocolMetadata protocolMetadata) {
this.serviceProtocol = protocolMetadata.serviceProtocol;
}
public Builder serviceProtocol(AwsServiceProtocol serviceProtocol) {
this.serviceProtocol = serviceProtocol;
return this;
}
@Override
public AwsProtocolMetadata build() {
return new AwsProtocolMetadata(this);
}
}
}
| 1,532 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/internal | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/internal/token/TokenRefresher.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore.internal.token;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.auth.token.credentials.SdkToken;
import software.amazon.awssdk.utils.SdkAutoCloseable;
/**
* Interface to refresh token.
* @param <T> Class that is a AwsToken.
*/
@SdkInternalApi
public interface TokenRefresher<T extends SdkToken> extends SdkAutoCloseable {
/**
* Gets the fresh token from the service or provided suppliers.
* @return Fresh AwsToken as supplied by suppliers.
*/
T refreshIfStaleAndFetch();
}
| 1,533 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/internal | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/internal/token/TokenTransformer.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore.internal.token;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.auth.token.credentials.SdkToken;
import software.amazon.awssdk.awscore.AwsResponse;
/**
* Transformer to convert the response received from service to respective Token objects.
* @param <T> AwsToken that needs to be transformed to.
* @param <R> AwsResponse that needs to be transformed from.
*/
@SdkInternalApi
public interface TokenTransformer<T extends SdkToken, R extends AwsResponse> {
/**
* API to convert the response received from the service to Token.
* @param awsResponse Response received from service which will have token details.
* @return
*/
T transform(R awsResponse);
}
| 1,534 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/internal | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/internal/token/TokenManager.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore.internal.token;
import java.util.Optional;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.auth.token.credentials.SdkToken;
import software.amazon.awssdk.utils.SdkAutoCloseable;
/**
* An object that knows how to load and optionally, store, an SSO token.
*/
@SdkInternalApi
public interface TokenManager<T extends SdkToken> extends SdkAutoCloseable {
Optional<T> loadToken();
default void storeToken(T token) {
throw new UnsupportedOperationException();
}
}
| 1,535 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/internal | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/internal/token/CachedTokenRefresher.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore.internal.token;
import java.time.Duration;
import java.time.Instant;
import java.util.function.Function;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.auth.token.credentials.SdkToken;
import software.amazon.awssdk.core.exception.SdkException;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.cache.CachedSupplier;
import software.amazon.awssdk.utils.cache.NonBlocking;
import software.amazon.awssdk.utils.cache.RefreshResult;
/**
* Class to cache Tokens which are supplied by the Suppliers while constructing this class. Automatic refresh can be enabled by
* setting autoRefreshDuration in builder methods.
*/
@ThreadSafe
@SdkInternalApi
public final class CachedTokenRefresher<TokenT extends SdkToken> implements TokenRefresher<TokenT> {
private static final Duration DEFAULT_STALE_TIME = Duration.ofMinutes(1);
private static final String THREAD_CLASS_NAME = "sdk-token-refresher";
private final Supplier<TokenT> tokenRetriever;
private final Duration staleDuration;
private final Duration prefetchDuration;
private final Function<SdkException, TokenT> exceptionHandler;
private final CachedSupplier<TokenT> tokenCacheSupplier;
private CachedTokenRefresher(Builder builder) {
Validate.paramNotNull(builder.tokenRetriever, "tokenRetriever");
this.staleDuration = builder.staleDuration == null ? DEFAULT_STALE_TIME : builder.staleDuration;
this.prefetchDuration = builder.prefetchDuration == null ? this.staleDuration : builder.prefetchDuration;
Function<SdkException, TokenT> defaultExceptionHandler = exp -> {
throw exp;
};
this.exceptionHandler = builder.exceptionHandler == null ? defaultExceptionHandler : builder.exceptionHandler;
this.tokenRetriever = builder.tokenRetriever;
CachedSupplier.Builder<TokenT> cachedBuilder = CachedSupplier.builder(this::refreshResult)
.cachedValueName("SsoOidcTokenProvider()");
if (builder.asyncRefreshEnabled) {
cachedBuilder.prefetchStrategy(new NonBlocking(THREAD_CLASS_NAME));
}
this.tokenCacheSupplier = cachedBuilder.build();
}
/**
* Builder method to construct instance of CachedTokenRefresher.
*
* @return
*/
public static Builder builder() {
return new Builder();
}
@Override
public TokenT refreshIfStaleAndFetch() {
return tokenCacheSupplier.get();
}
private TokenT refreshAndGetTokenFromSupplier() {
try {
TokenT freshToken = tokenRetriever.get();
return freshToken;
} catch (SdkException exception) {
return exceptionHandler.apply(exception);
}
}
private RefreshResult<TokenT> refreshResult() {
TokenT tokenT = refreshAndGetTokenFromSupplier();
Instant staleTime = tokenT.expirationTime().isPresent()
? tokenT.expirationTime().get().minus(staleDuration)
: Instant.now();
Instant prefetchTime = tokenT.expirationTime().isPresent()
? tokenT.expirationTime().get().minus(prefetchDuration)
: null;
return RefreshResult.builder(tokenT).staleTime(staleTime).prefetchTime(prefetchTime).build();
}
@Override
public void close() {
tokenCacheSupplier.close();
}
public static class Builder<TokenT extends SdkToken> {
private Function<SdkException, TokenT> exceptionHandler;
private Duration staleDuration;
private Duration prefetchDuration;
private Supplier<TokenT> tokenRetriever;
private Boolean asyncRefreshEnabled = false;
/**
* @param tokenRetriever Supplier to retrieve the token from its respective sources.
* @return
*/
public Builder tokenRetriever(Supplier<TokenT> tokenRetriever) {
this.tokenRetriever = tokenRetriever;
return this;
}
/**
* @param staleDuration The time before which the token is marked as stale to indicate it is time to fetch a fresh token.
* @return
*/
public Builder staleDuration(Duration staleDuration) {
this.staleDuration = staleDuration;
return this;
}
/**
* Configure the amount of time, relative to SSO session token expiration, that the cached credentials are considered
* close to stale and should be updated. See {@link #asyncRefreshEnabled}.
*
* <p>By default, this is 5 minutes.</p>
*/
public Builder prefetchTime(Duration prefetchTime) {
this.prefetchDuration = prefetchTime;
return this;
}
/**
* Configure whether this refresher should fetch tokens asynchronously in the background. If this is true, threads are
* less likely to block when {@link #refreshIfStaleAndFetch()} ()} is called, but additional resources are used to
* maintain the provider.
*
* <p>By default, this is disabled.</p>
*/
public Builder asyncRefreshEnabled(Boolean asyncRefreshEnabled) {
this.asyncRefreshEnabled = asyncRefreshEnabled;
return this;
}
/**
* @param exceptionHandler Handler which takes action when a Runtime exception occurs while fetching a token. Handler can
* return a previously stored token or throw back the exception.
* @return
*/
public Builder exceptionHandler(Function<SdkException, TokenT> exceptionHandler) {
this.exceptionHandler = exceptionHandler;
return this;
}
public CachedTokenRefresher build() {
CachedTokenRefresher cachedTokenRefresher = new CachedTokenRefresher(this);
return cachedTokenRefresher;
}
}
}
| 1,536 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/internal | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/internal/defaultsmode/DefaultsModeResolver.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore.internal.defaultsmode;
import java.util.Locale;
import java.util.Optional;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.awscore.defaultsmode.DefaultsMode;
import software.amazon.awssdk.core.SdkSystemSetting;
import software.amazon.awssdk.core.retry.RetryMode;
import software.amazon.awssdk.profiles.ProfileFile;
import software.amazon.awssdk.profiles.ProfileFileSystemSetting;
import software.amazon.awssdk.profiles.ProfileProperty;
import software.amazon.awssdk.utils.OptionalUtils;
/**
* Allows customizing the variables used during determination of a {@link DefaultsMode}. Created via {@link #create()}.
*/
@SdkInternalApi
public final class DefaultsModeResolver {
private static final DefaultsMode SDK_DEFAULT_DEFAULTS_MODE = DefaultsMode.LEGACY;
private Supplier<ProfileFile> profileFile;
private String profileName;
private DefaultsMode mode;
private DefaultsModeResolver() {
}
public static DefaultsModeResolver create() {
return new DefaultsModeResolver();
}
/**
* Configure the profile file that should be used when determining the {@link RetryMode}. The supplier is only consulted
* if a higher-priority determinant (e.g. environment variables) does not find the setting.
*/
public DefaultsModeResolver profileFile(Supplier<ProfileFile> profileFile) {
this.profileFile = profileFile;
return this;
}
/**
* Configure the profile file name should be used when determining the {@link RetryMode}.
*/
public DefaultsModeResolver profileName(String profileName) {
this.profileName = profileName;
return this;
}
/**
* Configure the {@link DefaultsMode} that should be used if the mode is not specified anywhere else.
*/
public DefaultsModeResolver defaultMode(DefaultsMode mode) {
this.mode = mode;
return this;
}
/**
* Resolve which defaults mode should be used, based on the configured values.
*/
public DefaultsMode resolve() {
return OptionalUtils.firstPresent(DefaultsModeResolver.fromSystemSettings(), () -> fromProfileFile(profileFile,
profileName))
.orElseGet(this::fromDefaultMode);
}
private static Optional<DefaultsMode> fromSystemSettings() {
return SdkSystemSetting.AWS_DEFAULTS_MODE.getStringValue()
.map(value -> DefaultsMode.fromValue(value.toLowerCase(Locale.US)));
}
private static Optional<DefaultsMode> fromProfileFile(Supplier<ProfileFile> profileFile, String profileName) {
profileFile = profileFile != null ? profileFile : ProfileFile::defaultProfileFile;
profileName = profileName != null ? profileName : ProfileFileSystemSetting.AWS_PROFILE.getStringValueOrThrow();
return profileFile.get()
.profile(profileName)
.flatMap(p -> p.property(ProfileProperty.DEFAULTS_MODE))
.map(value -> DefaultsMode.fromValue(value.toLowerCase(Locale.US)));
}
private DefaultsMode fromDefaultMode() {
return mode != null ? mode : SDK_DEFAULT_DEFAULTS_MODE;
}
}
| 1,537 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/internal | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/internal/defaultsmode/AutoDefaultsModeDiscovery.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore.internal.defaultsmode;
import java.util.Optional;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.awscore.defaultsmode.DefaultsMode;
import software.amazon.awssdk.core.SdkSystemSetting;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.regions.internal.util.EC2MetadataUtils;
import software.amazon.awssdk.utils.JavaSystemSetting;
import software.amazon.awssdk.utils.OptionalUtils;
import software.amazon.awssdk.utils.SystemSetting;
import software.amazon.awssdk.utils.internal.SystemSettingUtils;
/**
* This class attempts to discover the appropriate {@link DefaultsMode} by inspecting the environment. It falls
* back to the {@link DefaultsMode#STANDARD} mode if the target mode cannot be determined.
*/
@SdkInternalApi
public class AutoDefaultsModeDiscovery {
private static final String EC2_METADATA_REGION_PATH = "/latest/meta-data/placement/region";
private static final DefaultsMode FALLBACK_DEFAULTS_MODE = DefaultsMode.STANDARD;
private static final String ANDROID_JAVA_VENDOR = "The Android Project";
private static final String AWS_DEFAULT_REGION_ENV_VAR = "AWS_DEFAULT_REGION";
/**
* Discovers the defaultMode using the following workflow:
*
* 1. Check if it's on mobile
* 2. If it's not on mobile (best we can tell), see if we can determine whether we're an in-region or cross-region client.
* 3. If we couldn't figure out the region from environment variables. Check IMDSv2. This step might take up to 1 second
* (default connect timeout)
* 4. Finally, use fallback mode
*/
public DefaultsMode discover(Region regionResolvedFromSdkClient) {
if (isMobile()) {
return DefaultsMode.MOBILE;
}
if (isAwsExecutionEnvironment()) {
Optional<String> regionStr = regionFromAwsExecutionEnvironment();
if (regionStr.isPresent()) {
return compareRegion(regionStr.get(), regionResolvedFromSdkClient);
}
}
Optional<String> regionFromEc2 = queryImdsV2();
if (regionFromEc2.isPresent()) {
return compareRegion(regionFromEc2.get(), regionResolvedFromSdkClient);
}
return FALLBACK_DEFAULTS_MODE;
}
private static DefaultsMode compareRegion(String region, Region clientRegion) {
if (region.equalsIgnoreCase(clientRegion.id())) {
return DefaultsMode.IN_REGION;
}
return DefaultsMode.CROSS_REGION;
}
private static Optional<String> queryImdsV2() {
try {
String ec2InstanceRegion = EC2MetadataUtils.fetchData(EC2_METADATA_REGION_PATH, false, 1);
// ec2InstanceRegion could be null
return Optional.ofNullable(ec2InstanceRegion);
} catch (Exception exception) {
return Optional.empty();
}
}
/**
* Check to see if the application is running on a mobile device by verifying the Java
* vendor system property. Currently only checks for Android. While it's technically possible to
* use Java with iOS, it's not a common use-case.
* <p>
* https://developer.android.com/reference/java/lang/System#getProperties()
*/
private static boolean isMobile() {
return JavaSystemSetting.JAVA_VENDOR.getStringValue()
.filter(o -> o.equals(ANDROID_JAVA_VENDOR))
.isPresent();
}
private static boolean isAwsExecutionEnvironment() {
return SdkSystemSetting.AWS_EXECUTION_ENV.getStringValue().isPresent();
}
private static Optional<String> regionFromAwsExecutionEnvironment() {
Optional<String> regionFromRegionEnvVar = SdkSystemSetting.AWS_REGION.getStringValue();
return OptionalUtils.firstPresent(regionFromRegionEnvVar,
() -> SystemSettingUtils.resolveEnvironmentVariable(new DefaultRegionEnvVar()));
}
private static final class DefaultRegionEnvVar implements SystemSetting {
@Override
public String property() {
return null;
}
@Override
public String environmentVariable() {
return AWS_DEFAULT_REGION_ENV_VAR;
}
@Override
public String defaultValue() {
return null;
}
}
}
| 1,538 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/internal | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/internal/authcontext/AwsCredentialsAuthorizationStrategy.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore.internal.authcontext;
import java.time.Duration;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.auth.credentials.AwsCredentials;
import software.amazon.awssdk.auth.credentials.CredentialUtils;
import software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute;
import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration;
import software.amazon.awssdk.core.RequestOverrideConfiguration;
import software.amazon.awssdk.core.SdkRequest;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.internal.util.MetricUtils;
import software.amazon.awssdk.core.metrics.CoreMetric;
import software.amazon.awssdk.core.signer.Signer;
import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity;
import software.amazon.awssdk.identity.spi.IdentityProvider;
import software.amazon.awssdk.metrics.MetricCollector;
import software.amazon.awssdk.utils.CompletableFutureUtils;
import software.amazon.awssdk.utils.Pair;
import software.amazon.awssdk.utils.Validate;
/**
* An authorization strategy for AWS Credentials that can resolve a compatible signer as
* well as provide resolved AWS credentials as an execution attribute.
*
* @deprecated This is only used for compatibility with pre-SRA authorization logic. After we are comfortable that the new code
* paths are working, we should migrate old clients to the new code paths (where possible) and delete this code.
*/
@Deprecated
@SdkInternalApi
public final class AwsCredentialsAuthorizationStrategy implements AuthorizationStrategy {
private final SdkRequest request;
private final Signer defaultSigner;
private final IdentityProvider<? extends AwsCredentialsIdentity> defaultCredentialsProvider;
private final MetricCollector metricCollector;
public AwsCredentialsAuthorizationStrategy(Builder builder) {
this.request = builder.request();
this.defaultSigner = builder.defaultSigner();
this.defaultCredentialsProvider = builder.defaultCredentialsProvider();
this.metricCollector = builder.metricCollector();
}
public static Builder builder() {
return new Builder();
}
/**
* Request override signers take precedence over the default alternative, for instance what is specified in the
* client. Request override signers can also be modified by modifyRequest interceptors.
*
* @return The signer that will be used by the SDK to sign the request
*
*/
@Override
public Signer resolveSigner() {
return request.overrideConfiguration()
.flatMap(RequestOverrideConfiguration::signer)
.orElse(defaultSigner);
}
/**
* Add credentials to be used by the signer in later stages.
*/
@Override
public void addCredentialsToExecutionAttributes(ExecutionAttributes executionAttributes) {
IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider =
resolveCredentialsProvider(request, defaultCredentialsProvider);
AwsCredentials credentials = CredentialUtils.toCredentials(resolveCredentials(credentialsProvider, metricCollector));
executionAttributes.putAttribute(AwsSignerExecutionAttribute.AWS_CREDENTIALS, credentials);
}
/**
* Resolves the credentials provider, with the request override configuration taking precedence over the
* provided default.
*
* @return The credentials provider that will be used by the SDK to resolve credentials
*/
private static IdentityProvider<? extends AwsCredentialsIdentity> resolveCredentialsProvider(
SdkRequest originalRequest,
IdentityProvider<? extends AwsCredentialsIdentity> defaultProvider) {
return originalRequest.overrideConfiguration()
.filter(c -> c instanceof AwsRequestOverrideConfiguration)
.map(c -> (AwsRequestOverrideConfiguration) c)
.flatMap(AwsRequestOverrideConfiguration::credentialsIdentityProvider)
.orElse(defaultProvider);
}
private static AwsCredentialsIdentity resolveCredentials(
IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider,
MetricCollector metricCollector) {
Validate.notNull(credentialsProvider, "No credentials provider exists to resolve credentials from.");
// TODO(sra-identity-and-auth): internal issue SMITHY-1677. avoid join for async clients.
Pair<? extends AwsCredentialsIdentity, Duration> measured =
MetricUtils.measureDuration(() -> CompletableFutureUtils.joinLikeSync(credentialsProvider.resolveIdentity()));
metricCollector.reportMetric(CoreMetric.CREDENTIALS_FETCH_DURATION, measured.right());
AwsCredentialsIdentity credentials = measured.left();
Validate.validState(credentials != null, "Credential providers must never return null.");
return credentials;
}
public static final class Builder {
private SdkRequest request;
private Signer defaultSigner;
private IdentityProvider<? extends AwsCredentialsIdentity> defaultCredentialsProvider;
private MetricCollector metricCollector;
private Builder() {
}
public SdkRequest request() {
return this.request;
}
public Builder request(SdkRequest request) {
this.request = request;
return this;
}
public Signer defaultSigner() {
return this.defaultSigner;
}
public Builder defaultSigner(Signer defaultSigner) {
this.defaultSigner = defaultSigner;
return this;
}
public IdentityProvider<? extends AwsCredentialsIdentity> defaultCredentialsProvider() {
return this.defaultCredentialsProvider;
}
public Builder defaultCredentialsProvider(IdentityProvider<? extends AwsCredentialsIdentity> defaultCredentialsProvider) {
this.defaultCredentialsProvider = defaultCredentialsProvider;
return this;
}
public MetricCollector metricCollector() {
return this.metricCollector;
}
public Builder metricCollector(MetricCollector metricCollector) {
this.metricCollector = metricCollector;
return this;
}
public AwsCredentialsAuthorizationStrategy build() {
return new AwsCredentialsAuthorizationStrategy(this);
}
}
}
| 1,539 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/internal | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/internal/authcontext/TokenAuthorizationStrategy.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore.internal.authcontext;
import java.time.Duration;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.auth.credentials.TokenUtils;
import software.amazon.awssdk.auth.token.credentials.SdkToken;
import software.amazon.awssdk.auth.token.signer.SdkTokenExecutionAttribute;
import software.amazon.awssdk.core.RequestOverrideConfiguration;
import software.amazon.awssdk.core.SdkRequest;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.internal.util.MetricUtils;
import software.amazon.awssdk.core.metrics.CoreMetric;
import software.amazon.awssdk.core.signer.Signer;
import software.amazon.awssdk.identity.spi.IdentityProvider;
import software.amazon.awssdk.identity.spi.TokenIdentity;
import software.amazon.awssdk.metrics.MetricCollector;
import software.amazon.awssdk.utils.CompletableFutureUtils;
import software.amazon.awssdk.utils.Pair;
import software.amazon.awssdk.utils.Validate;
/**
* An authorization strategy for tokens that can resolve a compatible signer as
* well as provide a resolved token as an execution attribute.
*
* @deprecated This is only used for compatibility with pre-SRA authorization logic. After we are comfortable that the new code
* paths are working, we should migrate old clients to the new code paths (where possible) and delete this code.
*/
@Deprecated
@SdkInternalApi
public final class TokenAuthorizationStrategy implements AuthorizationStrategy {
private final SdkRequest request;
private final Signer defaultSigner;
private final IdentityProvider<? extends TokenIdentity> defaultTokenProvider;
private final MetricCollector metricCollector;
public TokenAuthorizationStrategy(Builder builder) {
this.request = builder.request();
this.defaultSigner = builder.defaultSigner();
this.defaultTokenProvider = builder.defaultTokenProvider();
this.metricCollector = builder.metricCollector();
}
public static Builder builder() {
return new Builder();
}
/**
* Request override signers take precedence over the default alternative, for instance what is specified in the
* client. Request override signers can also be modified by modifyRequest interceptors.
*
* @return The signer that will be used by the SDK to sign the request
*/
@Override
public Signer resolveSigner() {
return request.overrideConfiguration()
.flatMap(RequestOverrideConfiguration::signer)
.orElse(defaultSigner);
}
/**
* Add credentials to be used by the signer in later stages.
*/
@Override
public void addCredentialsToExecutionAttributes(ExecutionAttributes executionAttributes) {
TokenIdentity tokenIdentity = resolveToken(defaultTokenProvider, metricCollector);
SdkToken token = TokenUtils.toSdkToken(tokenIdentity);
executionAttributes.putAttribute(SdkTokenExecutionAttribute.SDK_TOKEN, token);
}
private static TokenIdentity resolveToken(IdentityProvider<? extends TokenIdentity> tokenProvider,
MetricCollector metricCollector) {
Validate.notNull(tokenProvider, "No token provider exists to resolve a token from.");
// TODO(sra-identity-and-auth): internal issue SMITHY-1677. avoid join for async clients.
Pair<TokenIdentity, Duration> measured =
MetricUtils.measureDuration(() -> CompletableFutureUtils.joinLikeSync(tokenProvider.resolveIdentity()));
metricCollector.reportMetric(CoreMetric.TOKEN_FETCH_DURATION, measured.right());
TokenIdentity token = measured.left();
Validate.validState(token != null, "Token providers must never return null.");
return token;
}
public static final class Builder {
private SdkRequest request;
private Signer defaultSigner;
private IdentityProvider<? extends TokenIdentity> defaultTokenProvider;
private MetricCollector metricCollector;
private Builder() {
}
public SdkRequest request() {
return this.request;
}
public Builder request(SdkRequest request) {
this.request = request;
return this;
}
public Signer defaultSigner() {
return this.defaultSigner;
}
public Builder defaultSigner(Signer defaultSigner) {
this.defaultSigner = defaultSigner;
return this;
}
public IdentityProvider<? extends TokenIdentity> defaultTokenProvider() {
return this.defaultTokenProvider;
}
public Builder defaultTokenProvider(IdentityProvider<? extends TokenIdentity> defaultTokenProvider) {
this.defaultTokenProvider = defaultTokenProvider;
return this;
}
public MetricCollector metricCollector() {
return this.metricCollector;
}
public Builder metricCollector(MetricCollector metricCollector) {
this.metricCollector = metricCollector;
return this;
}
public TokenAuthorizationStrategy build() {
return new TokenAuthorizationStrategy(this);
}
}
}
| 1,540 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/internal | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/internal/authcontext/AuthorizationStrategyFactory.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore.internal.authcontext;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.awscore.client.config.AwsClientOption;
import software.amazon.awssdk.core.CredentialType;
import software.amazon.awssdk.core.SdkRequest;
import software.amazon.awssdk.core.client.config.SdkAdvancedClientOption;
import software.amazon.awssdk.core.client.config.SdkClientConfiguration;
import software.amazon.awssdk.core.signer.Signer;
import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity;
import software.amazon.awssdk.identity.spi.IdentityProvider;
import software.amazon.awssdk.identity.spi.TokenIdentity;
import software.amazon.awssdk.metrics.MetricCollector;
/**
* Will create the correct authorization strategy based on provided credential type.
*
* @deprecated This is only used for compatibility with pre-SRA authorization logic. After we are comfortable that the new code
* paths are working, we should migrate old clients to the new code paths (where possible) and delete this code.
*/
@Deprecated
@SdkInternalApi
public final class AuthorizationStrategyFactory {
private final SdkRequest request;
private final MetricCollector metricCollector;
private final SdkClientConfiguration clientConfiguration;
public AuthorizationStrategyFactory(SdkRequest request,
MetricCollector metricCollector,
SdkClientConfiguration clientConfiguration) {
this.request = request;
this.metricCollector = metricCollector;
this.clientConfiguration = clientConfiguration;
}
public AuthorizationStrategy strategyFor(CredentialType credentialType) {
if (credentialType == CredentialType.TOKEN) {
return tokenAuthorizationStrategy();
}
return awsCredentialsAuthorizationStrategy();
}
private TokenAuthorizationStrategy tokenAuthorizationStrategy() {
Signer defaultSigner = clientConfiguration.option(SdkAdvancedClientOption.TOKEN_SIGNER);
// Older generated clients may be setting TOKEN_PROVIDER, hence fallback.
IdentityProvider<? extends TokenIdentity> defaultTokenProvider =
clientConfiguration.option(AwsClientOption.TOKEN_IDENTITY_PROVIDER) == null
? clientConfiguration.option(AwsClientOption.TOKEN_PROVIDER)
: clientConfiguration.option(AwsClientOption.TOKEN_IDENTITY_PROVIDER);
return TokenAuthorizationStrategy.builder()
.request(request)
.defaultSigner(defaultSigner)
.defaultTokenProvider(defaultTokenProvider)
.metricCollector(metricCollector)
.build();
}
private AwsCredentialsAuthorizationStrategy awsCredentialsAuthorizationStrategy() {
Signer defaultSigner = clientConfiguration.option(SdkAdvancedClientOption.SIGNER);
IdentityProvider<? extends AwsCredentialsIdentity> defaultCredentialsProvider =
clientConfiguration.option(AwsClientOption.CREDENTIALS_IDENTITY_PROVIDER);
return AwsCredentialsAuthorizationStrategy.builder()
.request(request)
.defaultSigner(defaultSigner)
.defaultCredentialsProvider(defaultCredentialsProvider)
.metricCollector(metricCollector)
.build();
}
}
| 1,541 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/internal | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/internal/authcontext/AuthorizationStrategy.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore.internal.authcontext;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.signer.Signer;
/**
* Represents a logical unit for providing instructions on how to authorize a request,
* including which signer and which credentials to use.
*
* @deprecated This is only used for compatibility with pre-SRA authorization logic. After we are comfortable that the new code
* paths are working, we should migrate old clients to the new code paths (where possible) and delete this code.
*/
@Deprecated
@SdkInternalApi
public interface AuthorizationStrategy {
Signer resolveSigner();
void addCredentialsToExecutionAttributes(ExecutionAttributes executionAttributes);
}
| 1,542 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/internal/client | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/internal/client/config/AwsClientOptionValidation.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore.internal.client.config;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.awscore.client.config.AwsAdvancedClientOption;
import software.amazon.awssdk.awscore.client.config.AwsClientOption;
import software.amazon.awssdk.core.client.config.SdkClientConfiguration;
import software.amazon.awssdk.core.client.config.SdkClientOptionValidation;
/**
* A set of static methods used to validate that a {@link SdkClientConfiguration} contains all of
* the values required for the AWS client handlers to function.
*/
@SdkInternalApi
public final class AwsClientOptionValidation extends SdkClientOptionValidation {
private AwsClientOptionValidation() {
}
public static void validateAsyncClientOptions(SdkClientConfiguration c) {
validateClientOptions(c);
}
public static void validateSyncClientOptions(SdkClientConfiguration c) {
validateClientOptions(c);
}
private static void validateClientOptions(SdkClientConfiguration c) {
require("credentialsProvider", c.option(AwsClientOption.CREDENTIALS_IDENTITY_PROVIDER));
require("overrideConfiguration.advancedOption[AWS_REGION]", c.option(AwsClientOption.AWS_REGION));
require("overrideConfiguration.advancedOption[SIGNING_REGION]", c.option(AwsClientOption.SIGNING_REGION));
require("overrideConfiguration.advancedOption[SERVICE_SIGNING_NAME]",
c.option(AwsClientOption.SERVICE_SIGNING_NAME));
require("overrideConfiguration.advancedOption[ENABLE_DEFAULT_REGION_DETECTION]",
c.option(AwsAdvancedClientOption.ENABLE_DEFAULT_REGION_DETECTION));
}
}
| 1,543 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/internal | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/internal/interceptor/TracingSystemSetting.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore.internal.interceptor;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.utils.SystemSetting;
/**
* Tracing specific System Setting.
*/
@SdkInternalApi
public enum TracingSystemSetting implements SystemSetting {
// See: https://github.com/aws/aws-xray-sdk-java/issues/251
_X_AMZN_TRACE_ID("com.amazonaws.xray.traceHeader", null);
private final String systemProperty;
private final String defaultValue;
TracingSystemSetting(String systemProperty, String defaultValue) {
this.systemProperty = systemProperty;
this.defaultValue = defaultValue;
}
@Override
public String property() {
return systemProperty;
}
@Override
public String environmentVariable() {
return name();
}
@Override
public String defaultValue() {
return defaultValue;
}
}
| 1,544 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/presigner/SdkPresigner.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore.presigner;
import java.net.URI;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity;
import software.amazon.awssdk.identity.spi.IdentityProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.utils.SdkAutoCloseable;
/**
* The base interface for all SDK presigners.
*/
@SdkPublicApi
public interface SdkPresigner extends SdkAutoCloseable {
/**
* Close this presigner, releasing any resources it might have acquired. It is recommended to invoke this method whenever
* the presigner is done being used, to prevent resource leaks.
* <p/>
* For example, some {@link AwsCredentialsProvider} implementations hold resources that could be released by this method.
*/
@Override
void close();
/**
* The base interface for all SDK presigner builders.
*/
@SdkPublicApi
interface Builder {
/**
* Configure the region for which the requests should be signed.
*
* <p>If this is not specified, the SDK will attempt to identify the endpoint automatically using the following logic:
* <ol>
* <li>Check the 'aws.region' system property for the region.</li>
* <li>Check the 'AWS_REGION' environment variable for the region.</li>
* <li>Check the {user.home}/.aws/credentials and {user.home}/.aws/config files for the region.</li>
* <li>If running in EC2, check the EC2 metadata service for the region.</li>
* </ol>
*
* <p>If the region is not found in any of the locations above, an exception will be thrown at {@link #build()}
* time.
*/
Builder region(Region region);
/**
* Configure the credentials that should be used for request signing.
*
* <p>The default provider will attempt to identify the credentials automatically using the following checks:
* <ol>
* <li>Java System Properties - <code>aws.accessKeyId</code> and <code>aws.secretAccessKey</code></li>
* <li>Environment Variables - <code>AWS_ACCESS_KEY_ID</code> and <code>AWS_SECRET_ACCESS_KEY</code></li>
* <li>Credential profiles file at the default location (~/.aws/credentials) shared by all AWS SDKs and the AWS CLI</li>
* <li>Credentials delivered through the Amazon EC2 container service if AWS_CONTAINER_CREDENTIALS_RELATIVE_URI
* environment variable is set and security manager has permission to access the variable.</li>
* <li>Instance profile credentials delivered through the Amazon EC2 metadata service</li>
* </ol>
*
* <p>If the credentials are not found in any of the locations above, an exception will be thrown at {@link #build()}
* time.
* </p>
*
* <p>The last of {@link #credentialsProvider(AwsCredentialsProvider)} or {@link #credentialsProvider(IdentityProvider)}
* wins.</p>
*/
default Builder credentialsProvider(AwsCredentialsProvider credentialsProvider) {
return credentialsProvider((IdentityProvider<? extends AwsCredentialsIdentity>) credentialsProvider);
}
/**
* Configure the credentials that should be used to authenticate with AWS.
*
* <p>The default provider will attempt to identify the credentials automatically using the following checks:
* <ol>
* <li>Java System Properties - <code>aws.accessKeyId</code> and <code>aws.secretAccessKey</code></li>
* <li>Environment Variables - <code>AWS_ACCESS_KEY_ID</code> and <code>AWS_SECRET_ACCESS_KEY</code></li>
* <li>Credential profiles file at the default location (~/.aws/credentials) shared by all AWS SDKs and the AWS CLI</li>
* <li>Credentials delivered through the Amazon EC2 container service if AWS_CONTAINER_CREDENTIALS_RELATIVE_URI
* environment variable is set and security manager has permission to access the variable.</li>
* <li>Instance profile credentials delivered through the Amazon EC2 metadata service</li>
* </ol>
*
* <p>If the credentials are not found in any of the locations above, an exception will be thrown at {@link #build()}
* time.
* </p>
*
* <p>The last of {@link #credentialsProvider(AwsCredentialsProvider)} or {@link #credentialsProvider(IdentityProvider)}
* wins.</p>
*/
default Builder credentialsProvider(IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider) {
throw new UnsupportedOperationException();
}
/**
* Configure whether the SDK should use the AWS dualstack endpoint.
*
* <p>If this is not specified, the SDK will attempt to determine whether the dualstack endpoint should be used
* automatically using the following logic:
* <ol>
* <li>Check the 'aws.useDualstackEndpoint' system property for 'true' or 'false'.</li>
* <li>Check the 'AWS_USE_DUALSTACK_ENDPOINT' environment variable for 'true' or 'false'.</li>
* <li>Check the {user.home}/.aws/credentials and {user.home}/.aws/config files for the 'use_dualstack_endpoint'
* property set to 'true' or 'false'.</li>
* </ol>
*
* <p>If the setting is not found in any of the locations above, 'false' will be used.
*/
Builder dualstackEnabled(Boolean dualstackEnabled);
/**
* Configure whether the SDK should use the AWS fips endpoint.
*
* <p>If this is not specified, the SDK will attempt to determine whether the fips endpoint should be used
* automatically using the following logic:
* <ol>
* <li>Check the 'aws.useFipsEndpoint' system property for 'true' or 'false'.</li>
* <li>Check the 'AWS_USE_FIPS_ENDPOINT' environment variable for 'true' or 'false'.</li>
* <li>Check the {user.home}/.aws/credentials and {user.home}/.aws/config files for the 'use_fips_endpoint'
* property set to 'true' or 'false'.</li>
* </ol>
*
* <p>If the setting is not found in any of the locations above, 'false' will be used.
*/
Builder fipsEnabled(Boolean fipsEnabled);
/**
* Configure an endpoint that should be used in the pre-signed requests. This will override the endpoint that is usually
* determined by the {@link #region(Region)} and {@link #dualstackEnabled(Boolean)} settings.
*/
Builder endpointOverride(URI endpointOverride);
/**
* Build the presigner using the configuration on this builder.
*/
SdkPresigner build();
}
}
| 1,545 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/presigner/PresignedRequest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore.presigner;
import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely;
import java.net.URL;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.utils.Validate;
/**
* The base class for all presigned requests.
* <p/>
* The {@link #isBrowserExecutable} method can be used to determine whether this request can be executed by a web browser.
*/
@SdkPublicApi
public abstract class PresignedRequest {
private final URL url;
private final Instant expiration;
private final boolean isBrowserExecutable;
private final Map<String, List<String>> signedHeaders;
private final SdkBytes signedPayload;
private final SdkHttpRequest httpRequest;
protected PresignedRequest(DefaultBuilder<?> builder) {
this.expiration = Validate.notNull(builder.expiration, "expiration");
this.isBrowserExecutable = Validate.notNull(builder.isBrowserExecutable, "isBrowserExecutable");
this.signedHeaders = Validate.notEmpty(builder.signedHeaders, "signedHeaders");
this.signedPayload = builder.signedPayload;
this.httpRequest = Validate.notNull(builder.httpRequest, "httpRequest");
this.url = invokeSafely(httpRequest.getUri()::toURL);
}
/**
* The URL that the presigned request will execute against. The {@link #isBrowserExecutable} method can be used to
* determine whether this request will work in a browser.
*/
public URL url() {
return url;
}
/**
* The exact SERVICE time that the request will expire. After this time, attempting to execute the request
* will fail.
* <p/>
* This may differ from the local clock, based on the skew between the local and AWS service clocks.
*/
public Instant expiration() {
return expiration;
}
/**
* Whether the url returned by the url method can be executed in a browser.
* <p/>
* This is true when the HTTP request method is GET and all data included in the signature will be sent by a standard web
* browser.
*/
public boolean isBrowserExecutable() {
return isBrowserExecutable;
}
/**
* Returns the subset of headers that were signed, and MUST be included in the presigned request to prevent
* the request from failing.
*/
public Map<String, List<String>> signedHeaders() {
return signedHeaders;
}
/**
* Returns the payload that was signed, or Optional.empty() if there is no signed payload with this request.
*/
public Optional<SdkBytes> signedPayload() {
return Optional.ofNullable(signedPayload);
}
/**
* The entire SigV4 query-parameter signed request (minus the payload), that can be transmitted as-is to a
* service using any HTTP client that implement the SDK's HTTP client SPI.
* <p>
* This request includes signed AND unsigned headers.
*/
public SdkHttpRequest httpRequest() {
return httpRequest;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PresignedRequest that = (PresignedRequest) o;
if (isBrowserExecutable != that.isBrowserExecutable) {
return false;
}
if (!expiration.equals(that.expiration)) {
return false;
}
if (!signedHeaders.equals(that.signedHeaders)) {
return false;
}
if (signedPayload != null ? !signedPayload.equals(that.signedPayload) : that.signedPayload != null) {
return false;
}
return httpRequest.equals(that.httpRequest);
}
@Override
public int hashCode() {
int result = expiration.hashCode();
result = 31 * result + (isBrowserExecutable ? 1 : 0);
result = 31 * result + signedHeaders.hashCode();
result = 31 * result + (signedPayload != null ? signedPayload.hashCode() : 0);
result = 31 * result + httpRequest.hashCode();
return result;
}
@SdkPublicApi
public interface Builder {
/**
* Configure the exact SERVICE time that the request will expire. After this time, attempting to execute the request
* will fail.
*/
Builder expiration(Instant expiration);
/**
* Configure whether the url returned by the url method can be executed in a browser.
*/
Builder isBrowserExecutable(Boolean isBrowserExecutable);
/**
* Configure the subset of headers that were signed, and MUST be included in the presigned request to prevent
* the request from failing.
*/
Builder signedHeaders(Map<String, List<String>> signedHeaders);
/**
* Configure the payload that was signed.
*/
Builder signedPayload(SdkBytes signedPayload);
/**
* Configure the entire SigV4 query-parameter signed request (minus the payload), that can be transmitted as-is to a
* service using any HTTP client that implement the SDK's HTTP client SPI.
*/
Builder httpRequest(SdkHttpRequest httpRequest);
PresignedRequest build();
}
@SdkProtectedApi
protected abstract static class DefaultBuilder<B extends DefaultBuilder<B>> implements Builder {
private Instant expiration;
private Boolean isBrowserExecutable;
private Map<String, List<String>> signedHeaders;
private SdkBytes signedPayload;
private SdkHttpRequest httpRequest;
protected DefaultBuilder() {
}
protected DefaultBuilder(PresignedRequest request) {
this.expiration = request.expiration;
this.isBrowserExecutable = request.isBrowserExecutable;
this.signedHeaders = request.signedHeaders;
this.signedPayload = request.signedPayload;
this.httpRequest = request.httpRequest;
}
@Override
public B expiration(Instant expiration) {
this.expiration = expiration;
return thisBuilder();
}
@Override
public B isBrowserExecutable(Boolean isBrowserExecutable) {
this.isBrowserExecutable = isBrowserExecutable;
return thisBuilder();
}
@Override
public B signedHeaders(Map<String, List<String>> signedHeaders) {
this.signedHeaders = signedHeaders;
return thisBuilder();
}
@Override
public B signedPayload(SdkBytes signedPayload) {
this.signedPayload = signedPayload;
return thisBuilder();
}
@Override
public B httpRequest(SdkHttpRequest httpRequest) {
this.httpRequest = httpRequest;
return thisBuilder();
}
@SuppressWarnings("unchecked")
private B thisBuilder() {
return (B) this;
}
}
} | 1,546 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/presigner/PresignRequest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore.presigner;
import java.time.Duration;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.utils.Validate;
/**
* The base class for all presign requests.
*/
@SdkPublicApi
public abstract class PresignRequest {
private final Duration signatureDuration;
protected PresignRequest(DefaultBuilder<?> builder) {
this.signatureDuration = Validate.paramNotNull(builder.signatureDuration, "signatureDuration");
}
/**
* Retrieves the duration for which this presigned request should be valid. After this time has
* expired, attempting to use the presigned request will fail.
*/
public Duration signatureDuration() {
return this.signatureDuration;
}
/**
* The base interface for all presign request builders.
*/
@SdkPublicApi
public interface Builder {
/**
* Specifies the duration for which this presigned request should be valid. After this time has
* expired, attempting to use the presigned request will fail.
*/
Builder signatureDuration(Duration signatureDuration);
/**
* Build the presigned request, based on the configuration on this builder.
*/
PresignRequest build();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PresignRequest that = (PresignRequest) o;
return signatureDuration.equals(that.signatureDuration);
}
@Override
public int hashCode() {
return signatureDuration.hashCode();
}
@SdkProtectedApi
protected abstract static class DefaultBuilder<B extends DefaultBuilder<B>> implements Builder {
private Duration signatureDuration;
protected DefaultBuilder() {
}
protected DefaultBuilder(PresignRequest request) {
this.signatureDuration = request.signatureDuration;
}
@Override
public B signatureDuration(Duration signatureDuration) {
this.signatureDuration = signatureDuration;
return thisBuilder();
}
@SuppressWarnings("unchecked")
private B thisBuilder() {
return (B) this;
}
}
}
| 1,547 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/endpoint/FipsEnabledProvider.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore.endpoint;
import java.util.Optional;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.SdkSystemSetting;
import software.amazon.awssdk.profiles.ProfileFile;
import software.amazon.awssdk.profiles.ProfileFileSystemSetting;
import software.amazon.awssdk.profiles.ProfileProperty;
import software.amazon.awssdk.utils.Validate;
/**
* A resolver for the default value of whether the SDK should use fips endpoints. This checks environment variables,
* system properties and the profile file for the relevant configuration options when {@link #isFipsEnabled()} is invoked.
*/
@SdkProtectedApi
public class FipsEnabledProvider {
private final Supplier<ProfileFile> profileFile;
private final String profileName;
private FipsEnabledProvider(Builder builder) {
this.profileFile = Validate.paramNotNull(builder.profileFile, "profileFile");
this.profileName = builder.profileName;
}
public static Builder builder() {
return new Builder();
}
/**
* Returns true when dualstack should be used, false when dualstack should not be used, and empty when there is no global
* dualstack configuration.
*/
public Optional<Boolean> isFipsEnabled() {
Optional<Boolean> setting = SdkSystemSetting.AWS_USE_FIPS_ENDPOINT.getBooleanValue();
if (setting.isPresent()) {
return setting;
}
return profileFile.get()
.profile(profileName())
.flatMap(p -> p.booleanProperty(ProfileProperty.USE_FIPS_ENDPOINT));
}
private String profileName() {
return profileName != null ? profileName : ProfileFileSystemSetting.AWS_PROFILE.getStringValueOrThrow();
}
public static final class Builder {
private Supplier<ProfileFile> profileFile = ProfileFile::defaultProfileFile;
private String profileName;
private Builder() {
}
public Builder profileFile(Supplier<ProfileFile> profileFile) {
this.profileFile = profileFile;
return this;
}
public Builder profileName(String profileName) {
this.profileName = profileName;
return this;
}
public FipsEnabledProvider build() {
return new FipsEnabledProvider(this);
}
}
}
| 1,548 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/endpoint/DualstackEnabledProvider.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore.endpoint;
import java.util.Optional;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.SdkSystemSetting;
import software.amazon.awssdk.profiles.Profile;
import software.amazon.awssdk.profiles.ProfileFile;
import software.amazon.awssdk.profiles.ProfileFileSystemSetting;
import software.amazon.awssdk.profiles.ProfileProperty;
import software.amazon.awssdk.utils.Validate;
/**
* A resolver for the default value of whether the SDK should use dualstack endpoints. This checks environment variables,
* system properties and the profile file for the relevant configuration options when {@link #isDualstackEnabled()} is invoked.
*/
@SdkProtectedApi
public class DualstackEnabledProvider {
private final Supplier<ProfileFile> profileFile;
private final String profileName;
private DualstackEnabledProvider(Builder builder) {
this.profileFile = Validate.paramNotNull(builder.profileFile, "profileFile");
this.profileName = builder.profileName;
}
public static Builder builder() {
return new Builder();
}
/**
* Returns true when dualstack should be used, false when dualstack should not be used, and empty when there is no global
* dualstack configuration.
*/
public Optional<Boolean> isDualstackEnabled() {
Optional<Boolean> setting = SdkSystemSetting.AWS_USE_DUALSTACK_ENDPOINT.getBooleanValue();
if (setting.isPresent()) {
return setting;
}
ProfileFile profileFile = this.profileFile.get();
Optional<Profile> profile = profileFile
.profile(profileName());
return profile
.flatMap(p -> p.booleanProperty(ProfileProperty.USE_DUALSTACK_ENDPOINT));
}
private String profileName() {
return profileName != null ? profileName : ProfileFileSystemSetting.AWS_PROFILE.getStringValueOrThrow();
}
public static final class Builder {
private Supplier<ProfileFile> profileFile = ProfileFile::defaultProfileFile;
private String profileName;
private Builder() {
}
public Builder profileFile(Supplier<ProfileFile> profileFile) {
this.profileFile = profileFile;
return this;
}
public Builder profileName(String profileName) {
this.profileName = profileName;
return this;
}
public DualstackEnabledProvider build() {
return new DualstackEnabledProvider(this);
}
}
}
| 1,549 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/endpoint/DefaultServiceEndpointBuilder.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore.endpoint;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.NotThreadSafe;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.profiles.ProfileFile;
import software.amazon.awssdk.profiles.ProfileFileSystemSetting;
import software.amazon.awssdk.regions.EndpointTag;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.regions.ServiceEndpointKey;
import software.amazon.awssdk.regions.ServiceMetadata;
import software.amazon.awssdk.regions.ServiceMetadataAdvancedOption;
import software.amazon.awssdk.utils.Lazy;
import software.amazon.awssdk.utils.Validate;
/**
* Uses service metadata and the request region to construct an endpoint for a specific service
*/
@NotThreadSafe
@SdkProtectedApi
// TODO We may not need this anymore, we should default to AWS partition when resolving
// a region we don't know about yet.
public final class DefaultServiceEndpointBuilder {
private final String serviceName;
private final String protocol;
private Region region;
private Supplier<ProfileFile> profileFile;
private String profileName;
private final Map<ServiceMetadataAdvancedOption<?>, Object> advancedOptions = new HashMap<>();
private Boolean dualstackEnabled;
private Boolean fipsEnabled;
public DefaultServiceEndpointBuilder(String serviceName, String protocol) {
this.serviceName = Validate.paramNotNull(serviceName, "serviceName");
this.protocol = Validate.paramNotNull(protocol, "protocol");
}
public DefaultServiceEndpointBuilder withRegion(Region region) {
if (region == null) {
throw new IllegalArgumentException("Region cannot be null");
}
this.region = region;
return this;
}
public DefaultServiceEndpointBuilder withProfileFile(Supplier<ProfileFile> profileFile) {
this.profileFile = profileFile;
return this;
}
public DefaultServiceEndpointBuilder withProfileFile(ProfileFile profileFile) {
this.profileFile = () -> profileFile;
return this;
}
public DefaultServiceEndpointBuilder withProfileName(String profileName) {
this.profileName = profileName;
return this;
}
public <T> DefaultServiceEndpointBuilder putAdvancedOption(ServiceMetadataAdvancedOption<T> option, T value) {
advancedOptions.put(option, value);
return this;
}
public DefaultServiceEndpointBuilder withDualstackEnabled(Boolean dualstackEnabled) {
this.dualstackEnabled = dualstackEnabled;
return this;
}
public DefaultServiceEndpointBuilder withFipsEnabled(Boolean fipsEnabled) {
this.fipsEnabled = fipsEnabled;
return this;
}
public URI getServiceEndpoint() {
if (profileFile == null) {
profileFile = new Lazy<>(ProfileFile::defaultProfileFile)::getValue;
}
if (profileName == null) {
profileName = ProfileFileSystemSetting.AWS_PROFILE.getStringValueOrThrow();
}
if (dualstackEnabled == null) {
dualstackEnabled = DualstackEnabledProvider.builder()
.profileFile(profileFile)
.profileName(profileName)
.build()
.isDualstackEnabled()
.orElse(false);
}
if (fipsEnabled == null) {
fipsEnabled = FipsEnabledProvider.builder()
.profileFile(profileFile)
.profileName(profileName)
.build()
.isFipsEnabled()
.orElse(false);
}
List<EndpointTag> endpointTags = new ArrayList<>();
if (dualstackEnabled) {
endpointTags.add(EndpointTag.DUALSTACK);
}
if (fipsEnabled) {
endpointTags.add(EndpointTag.FIPS);
}
ServiceMetadata serviceMetadata = ServiceMetadata.of(serviceName)
.reconfigure(c -> c.profileFile(profileFile)
.profileName(profileName)
.advancedOptions(advancedOptions));
URI endpoint = addProtocolToServiceEndpoint(serviceMetadata.endpointFor(ServiceEndpointKey.builder()
.region(region)
.tags(endpointTags)
.build()));
if (endpoint.getHost() == null) {
String error = "Configured region (" + region + ") and tags (" + endpointTags + ") resulted in an invalid URI: "
+ endpoint + ". This is usually caused by an invalid region configuration.";
List<Region> exampleRegions = serviceMetadata.regions();
if (!exampleRegions.isEmpty()) {
error += " Valid regions: " + exampleRegions;
}
throw SdkClientException.create(error);
}
return endpoint;
}
private URI addProtocolToServiceEndpoint(URI endpointWithoutProtocol) throws IllegalArgumentException {
try {
return new URI(protocol + "://" + endpointWithoutProtocol);
} catch (URISyntaxException e) {
throw new IllegalArgumentException(e);
}
}
public Region getRegion() {
return region;
}
}
| 1,550 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/exception/AwsServiceException.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore.exception;
import java.time.Duration;
import java.time.Instant;
import java.util.Optional;
import java.util.StringJoiner;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.awscore.internal.AwsErrorCode;
import software.amazon.awssdk.awscore.internal.AwsStatusCode;
import software.amazon.awssdk.core.exception.SdkServiceException;
import software.amazon.awssdk.core.retry.ClockSkew;
import software.amazon.awssdk.http.SdkHttpResponse;
/**
* Extension of {@link SdkServiceException} that represents an error response returned
* by an Amazon web service.
* <p>
* <p>
* AmazonServiceException provides callers several pieces of
* information that can be used to obtain more information about the error and
* why it occurred. In particular, the errorType field can be used to determine
* if the caller's request was invalid, or the service encountered an error on
* the server side while processing it.
*
* @see SdkServiceException
*/
@SdkPublicApi
public class AwsServiceException extends SdkServiceException {
private AwsErrorDetails awsErrorDetails;
private Duration clockSkew;
protected AwsServiceException(Builder b) {
super(b);
this.awsErrorDetails = b.awsErrorDetails();
this.clockSkew = b.clockSkew();
}
/**
* Additional details pertaining to an exception thrown by an AWS service.
*
* @return {@link AwsErrorDetails}.
*/
public AwsErrorDetails awsErrorDetails() {
return awsErrorDetails;
}
@Override
public String getMessage() {
if (awsErrorDetails != null) {
StringJoiner details = new StringJoiner(", ", "(", ")");
details.add("Service: " + awsErrorDetails().serviceName());
details.add("Status Code: " + statusCode());
details.add("Request ID: " + requestId());
if (extendedRequestId() != null) {
details.add("Extended Request ID: " + extendedRequestId());
}
String message = super.getMessage();
if (message == null) {
message = awsErrorDetails().errorMessage();
}
return message + " " + details;
}
return super.getMessage();
}
@Override
public boolean isClockSkewException() {
if (super.isClockSkewException()) {
return true;
}
if (awsErrorDetails == null) {
return false;
}
if (AwsErrorCode.isDefiniteClockSkewErrorCode(awsErrorDetails.errorCode())) {
return true;
}
SdkHttpResponse sdkHttpResponse = awsErrorDetails.sdkHttpResponse();
if (clockSkew == null || sdkHttpResponse == null) {
return false;
}
boolean isPossibleClockSkewError = AwsErrorCode.isPossibleClockSkewErrorCode(awsErrorDetails.errorCode()) ||
AwsStatusCode.isPossibleClockSkewStatusCode(statusCode());
return isPossibleClockSkewError && ClockSkew.isClockSkewed(Instant.now().minus(clockSkew),
ClockSkew.getServerTime(sdkHttpResponse).orElse(null));
}
@Override
public boolean isThrottlingException() {
return super.isThrottlingException() ||
Optional.ofNullable(awsErrorDetails)
.map(a -> AwsErrorCode.isThrottlingErrorCode(a.errorCode()))
.orElse(false);
}
/**
* @return {@link Builder} instance to construct a new {@link AwsServiceException}.
*/
public static Builder builder() {
return new BuilderImpl();
}
/**
* Create a {@link AwsServiceException.Builder} initialized with the properties of this {@code AwsServiceException}.
*
* @return A new builder initialized with this config's properties.
*/
@Override
public Builder toBuilder() {
return new BuilderImpl(this);
}
public static Class<? extends Builder> serializableBuilderClass() {
return BuilderImpl.class;
}
public interface Builder extends SdkServiceException.Builder {
/**
* Specifies the additional awsErrorDetails from the service response.
* @param awsErrorDetails Object containing additional details from the response.
* @return This object for method chaining.
*/
Builder awsErrorDetails(AwsErrorDetails awsErrorDetails);
/**
* The {@link AwsErrorDetails} from the service response.
*
* @return {@link AwsErrorDetails}.
*/
AwsErrorDetails awsErrorDetails();
/**
* The request-level time skew between the client and server date for the request that generated this exception. Positive
* values imply the client clock is "fast" and negative values imply the client clock is "slow".
*/
Builder clockSkew(Duration timeOffSet);
/**
* The request-level time skew between the client and server date for the request that generated this exception. Positive
* values imply the client clock is "fast" and negative values imply the client clock is "slow".
*/
Duration clockSkew();
@Override
Builder message(String message);
@Override
Builder cause(Throwable t);
@Override
Builder requestId(String requestId);
@Override
Builder extendedRequestId(String extendedRequestId);
@Override
Builder statusCode(int statusCode);
@Override
AwsServiceException build();
}
protected static class BuilderImpl extends SdkServiceException.BuilderImpl implements Builder {
protected AwsErrorDetails awsErrorDetails;
private Duration clockSkew;
protected BuilderImpl() {
}
protected BuilderImpl(AwsServiceException ex) {
super(ex);
this.awsErrorDetails = ex.awsErrorDetails();
}
@Override
public Builder awsErrorDetails(AwsErrorDetails awsErrorDetails) {
this.awsErrorDetails = awsErrorDetails;
return this;
}
@Override
public AwsErrorDetails awsErrorDetails() {
return awsErrorDetails;
}
public AwsErrorDetails getAwsErrorDetails() {
return awsErrorDetails;
}
public void setAwsErrorDetails(AwsErrorDetails awsErrorDetails) {
this.awsErrorDetails = awsErrorDetails;
}
@Override
public Builder clockSkew(Duration clockSkew) {
this.clockSkew = clockSkew;
return this;
}
@Override
public Duration clockSkew() {
return clockSkew;
}
@Override
public Builder message(String message) {
this.message = message;
return this;
}
@Override
public Builder cause(Throwable cause) {
this.cause = cause;
return this;
}
@Override
public Builder writableStackTrace(Boolean writableStackTrace) {
this.writableStackTrace = writableStackTrace;
return this;
}
@Override
public Builder requestId(String requestId) {
this.requestId = requestId;
return this;
}
@Override
public Builder extendedRequestId(String extendedRequestId) {
this.extendedRequestId = extendedRequestId;
return this;
}
@Override
public Builder statusCode(int statusCode) {
this.statusCode = statusCode;
return this;
}
@Override
public AwsServiceException build() {
return new AwsServiceException(this);
}
}
}
| 1,551 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/exception/AwsErrorDetails.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore.exception;
import java.io.Serializable;
import java.util.Objects;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.http.SdkHttpResponse;
import software.amazon.awssdk.utils.ToString;
@SdkPublicApi
public class AwsErrorDetails implements Serializable {
private static final long serialVersionUID = 1L;
private final String errorMessage;
private final String errorCode;
private final String serviceName;
private final SdkHttpResponse sdkHttpResponse;
private final SdkBytes rawResponse;
protected AwsErrorDetails(Builder b) {
this.errorMessage = b.errorMessage();
this.errorCode = b.errorCode();
this.serviceName = b.serviceName();
this.sdkHttpResponse = b.sdkHttpResponse();
this.rawResponse = b.rawResponse();
}
/**
* Returns the name of the service as defined in the static constant
* SERVICE_NAME variable of each service's interface.
*
* @return The name of the service that sent this error response.
*/
public String serviceName() {
return serviceName;
}
/**
* @return the human-readable error message provided by the service.
*/
public String errorMessage() {
return errorMessage;
}
/**
* Returns the error code associated with the response.
*/
public String errorCode() {
return errorCode;
}
/**
* Returns the response payload as bytes.
*/
public SdkBytes rawResponse() {
return rawResponse;
}
/**
* Returns a map of HTTP headers associated with the error response.
*/
public SdkHttpResponse sdkHttpResponse() {
return sdkHttpResponse;
}
/**
* @return {@link AwsErrorDetails.Builder} instance to construct a new {@link AwsErrorDetails}.
*/
public static Builder builder() {
return new BuilderImpl();
}
/**
* Create a {@link AwsErrorDetails.Builder} initialized with the properties of this {@code AwsErrorDetails}.
*
* @return A new builder initialized with this config's properties.
*/
public Builder toBuilder() {
return new BuilderImpl(this);
}
public static Class<? extends Builder> serializableBuilderClass() {
return BuilderImpl.class;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AwsErrorDetails that = (AwsErrorDetails) o;
return Objects.equals(errorMessage, that.errorMessage) &&
Objects.equals(errorCode, that.errorCode) &&
Objects.equals(serviceName, that.serviceName) &&
Objects.equals(sdkHttpResponse, that.sdkHttpResponse) &&
Objects.equals(rawResponse, that.rawResponse);
}
@Override
public int hashCode() {
int result = Objects.hashCode(errorMessage);
result = 31 * result + Objects.hashCode(errorCode);
result = 31 * result + Objects.hashCode(serviceName);
result = 31 * result + Objects.hashCode(sdkHttpResponse);
result = 31 * result + Objects.hashCode(rawResponse);
return result;
}
@Override
public String toString() {
return ToString.builder("AwsErrorDetails")
.add("errorMessage", errorMessage)
.add("errorCode", errorCode)
.add("serviceName", serviceName)
.build();
}
public interface Builder {
/**
* Specifies the error message returned by the service.
*
* @param errorMessage The error message returned by the service.
* @return This object for method chaining.
*/
Builder errorMessage(String errorMessage);
/**
* The error message specified by the service.
*
* @return The error message specified by the service.
*/
String errorMessage();
/**
* Specifies the error code returned by the service.
*
* @param errorCode The error code returned by the service.
* @return This object for method chaining.
*/
Builder errorCode(String errorCode);
/**
* The error code specified by the service.
*
* @return The error code specified by the service.
*/
String errorCode();
/**
* Specifies the name of the service that returned this error.
*
* @param serviceName The name of the service.
* @return This object for method chaining.
*/
Builder serviceName(String serviceName);
/**
* Returns the name of the service as defined in the static constant
* SERVICE_NAME variable of each service's interface.
*
* @return The name of the service that returned this error.
*/
String serviceName();
/**
* Specifies the {@link SdkHttpResponse} returned on the error response from the service.
*
* @param sdkHttpResponse The HTTP response from the service.
* @return This object for method chaining.
*/
Builder sdkHttpResponse(SdkHttpResponse sdkHttpResponse);
/**
* The HTTP response returned from the service.
*
* @return {@link SdkHttpResponse}.
*/
SdkHttpResponse sdkHttpResponse();
/**
* Specifies raw http response from the service.
*
* @param rawResponse raw byte response from the service.
* @return The object for method chaining.
*/
Builder rawResponse(SdkBytes rawResponse);
/**
* The raw response from the service.
*
* @return The raw response from the service in a byte array.
*/
SdkBytes rawResponse();
/**
* Creates a new {@link AwsErrorDetails} with the properties set on this builder.
*
* @return The new {@link AwsErrorDetails}.
*/
AwsErrorDetails build();
}
protected static final class BuilderImpl implements Builder {
private String errorMessage;
private String errorCode;
private String serviceName;
private SdkHttpResponse sdkHttpResponse;
private SdkBytes rawResponse;
private BuilderImpl() {
}
private BuilderImpl(AwsErrorDetails awsErrorDetails) {
this.errorMessage = awsErrorDetails.errorMessage();
this.errorCode = awsErrorDetails.errorCode();
this.serviceName = awsErrorDetails.serviceName();
this.sdkHttpResponse = awsErrorDetails.sdkHttpResponse();
this.rawResponse = awsErrorDetails.rawResponse();
}
@Override
public Builder errorMessage(String errorMessage) {
this.errorMessage = errorMessage;
return this;
}
@Override
public String errorMessage() {
return errorMessage;
}
@Override
public Builder errorCode(String errorCode) {
this.errorCode = errorCode;
return this;
}
@Override
public String errorCode() {
return errorCode;
}
@Override
public Builder serviceName(String serviceName) {
this.serviceName = serviceName;
return this;
}
@Override
public String serviceName() {
return serviceName;
}
@Override
public Builder sdkHttpResponse(SdkHttpResponse sdkHttpResponse) {
this.sdkHttpResponse = sdkHttpResponse;
return this;
}
@Override
public SdkHttpResponse sdkHttpResponse() {
return sdkHttpResponse;
}
@Override
public Builder rawResponse(SdkBytes rawResponse) {
this.rawResponse = rawResponse;
return this;
}
@Override
public SdkBytes rawResponse() {
return rawResponse;
}
@Override
public AwsErrorDetails build() {
return new AwsErrorDetails(this);
}
}
}
| 1,552 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/client | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/client/handler/AwsClientHandlerUtils.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore.client.handler;
import static software.amazon.awssdk.utils.CollectionUtils.firstIfPresent;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.ByteBuffer;
import java.util.LinkedHashMap;
import java.util.Map;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.utils.IoUtils;
import software.amazon.eventstream.HeaderValue;
import software.amazon.eventstream.Message;
@SdkProtectedApi
public final class AwsClientHandlerUtils {
private AwsClientHandlerUtils() {
}
/**
* Encodes the request into a flow message and then returns bytebuffer from the message.
*
* @param request The request to encode
* @return A bytebuffer representing the given request
*/
public static ByteBuffer encodeEventStreamRequestToByteBuffer(SdkHttpFullRequest request) {
Map<String, HeaderValue> headers = new LinkedHashMap<>();
request.forEachHeader((name, value) -> headers.put(name, HeaderValue.fromString(firstIfPresent(value))));
byte[] payload = null;
if (request.contentStreamProvider().isPresent()) {
try {
payload = IoUtils.toByteArray(request.contentStreamProvider().get().newStream());
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
return new Message(headers, payload).toByteBuffer();
}
}
| 1,553 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/client | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/client/handler/AwsAsyncClientHandler.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore.client.handler;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.awscore.internal.AwsExecutionContextBuilder;
import software.amazon.awssdk.awscore.internal.client.config.AwsClientOptionValidation;
import software.amazon.awssdk.core.SdkRequest;
import software.amazon.awssdk.core.SdkResponse;
import software.amazon.awssdk.core.async.AsyncResponseTransformer;
import software.amazon.awssdk.core.client.config.SdkClientConfiguration;
import software.amazon.awssdk.core.client.handler.AsyncClientHandler;
import software.amazon.awssdk.core.client.handler.ClientExecutionParams;
import software.amazon.awssdk.core.client.handler.SdkAsyncClientHandler;
import software.amazon.awssdk.core.http.ExecutionContext;
/**
* Async client handler for AWS SDK clients.
*/
@ThreadSafe
@Immutable
@SdkProtectedApi
public final class AwsAsyncClientHandler extends SdkAsyncClientHandler implements AsyncClientHandler {
public AwsAsyncClientHandler(SdkClientConfiguration clientConfiguration) {
super(clientConfiguration);
AwsClientOptionValidation.validateAsyncClientOptions(clientConfiguration);
}
@Override
public <InputT extends SdkRequest, OutputT extends SdkResponse> CompletableFuture<OutputT> execute(
ClientExecutionParams<InputT, OutputT> executionParams) {
return super.execute(executionParams);
}
@Override
public <InputT extends SdkRequest, OutputT extends SdkResponse, ReturnT> CompletableFuture<ReturnT> execute(
ClientExecutionParams<InputT, OutputT> executionParams,
AsyncResponseTransformer<OutputT, ReturnT> asyncResponseTransformer) {
return super.execute(executionParams, asyncResponseTransformer);
}
@Override
protected <InputT extends SdkRequest, OutputT extends SdkResponse> ExecutionContext
invokeInterceptorsAndCreateExecutionContext(ClientExecutionParams<InputT, OutputT> executionParams) {
SdkClientConfiguration clientConfiguration = resolveRequestConfiguration(executionParams);
return AwsExecutionContextBuilder.invokeInterceptorsAndCreateExecutionContext(executionParams, clientConfiguration);
}
}
| 1,554 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/client | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/client/handler/AwsSyncClientHandler.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore.client.handler;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.annotations.ThreadSafe;
import software.amazon.awssdk.awscore.internal.AwsExecutionContextBuilder;
import software.amazon.awssdk.awscore.internal.client.config.AwsClientOptionValidation;
import software.amazon.awssdk.core.SdkRequest;
import software.amazon.awssdk.core.SdkResponse;
import software.amazon.awssdk.core.client.config.SdkClientConfiguration;
import software.amazon.awssdk.core.client.handler.ClientExecutionParams;
import software.amazon.awssdk.core.client.handler.SdkSyncClientHandler;
import software.amazon.awssdk.core.client.handler.SyncClientHandler;
import software.amazon.awssdk.core.http.Crc32Validation;
import software.amazon.awssdk.core.http.ExecutionContext;
import software.amazon.awssdk.core.http.HttpResponseHandler;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.sync.ResponseTransformer;
import software.amazon.awssdk.http.SdkHttpFullResponse;
/**
* Client handler for AWS SDK clients.
*/
@ThreadSafe
@Immutable
@SdkProtectedApi
public final class AwsSyncClientHandler extends SdkSyncClientHandler implements SyncClientHandler {
public AwsSyncClientHandler(SdkClientConfiguration clientConfiguration) {
super(clientConfiguration);
AwsClientOptionValidation.validateSyncClientOptions(clientConfiguration);
}
@Override
public <InputT extends SdkRequest, OutputT extends SdkResponse> OutputT execute(
ClientExecutionParams<InputT, OutputT> executionParams) {
ClientExecutionParams<InputT, OutputT> clientExecutionParams = addCrc32Validation(executionParams);
return super.execute(clientExecutionParams);
}
@Override
public <InputT extends SdkRequest, OutputT extends SdkResponse, ReturnT> ReturnT execute(
ClientExecutionParams<InputT, OutputT> executionParams,
ResponseTransformer<OutputT, ReturnT> responseTransformer) {
return super.execute(executionParams, responseTransformer);
}
@Override
protected <InputT extends SdkRequest, OutputT extends SdkResponse> ExecutionContext
invokeInterceptorsAndCreateExecutionContext(ClientExecutionParams<InputT, OutputT> executionParams) {
SdkClientConfiguration clientConfiguration = resolveRequestConfiguration(executionParams);
return AwsExecutionContextBuilder.invokeInterceptorsAndCreateExecutionContext(executionParams, clientConfiguration);
}
private <InputT extends SdkRequest, OutputT> ClientExecutionParams<InputT, OutputT> addCrc32Validation(
ClientExecutionParams<InputT, OutputT> executionParams) {
if (executionParams.getCombinedResponseHandler() != null) {
return executionParams.withCombinedResponseHandler(
new Crc32ValidationResponseHandler<>(executionParams.getCombinedResponseHandler()));
} else {
return executionParams.withResponseHandler(
new Crc32ValidationResponseHandler<>(executionParams.getResponseHandler()));
}
}
/**
* Decorate {@link HttpResponseHandler} to validate CRC32 if needed.
*/
private class Crc32ValidationResponseHandler<T> implements HttpResponseHandler<T> {
private final HttpResponseHandler<T> delegate;
private Crc32ValidationResponseHandler(HttpResponseHandler<T> delegate) {
this.delegate = delegate;
}
@Override
public T handle(SdkHttpFullResponse response, ExecutionAttributes executionAttributes) throws Exception {
return delegate.handle(Crc32Validation.validate(isCalculateCrc32FromCompressedData(), response), executionAttributes);
}
}
}
| 1,555 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/client | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/client/config/AwsAdvancedClientOption.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore.client.config;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.awscore.client.builder.AwsClientBuilder;
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration.Builder;
import software.amazon.awssdk.core.client.config.SdkAdvancedClientOption;
import software.amazon.awssdk.regions.Region;
/**
* A collection of advanced options that can be configured on an AWS client via
* {@link Builder#putAdvancedOption(SdkAdvancedClientOption, Object)}.
*
* <p>These options are usually not required outside of testing or advanced libraries, so most users should not need to configure
* them.</p>
*
* @param <T> The type of value associated with the option.
*/
@SdkPublicApi
public final class AwsAdvancedClientOption<T> extends SdkAdvancedClientOption<T> {
/**
* Whether region detection should be enabled. Region detection is used when the {@link AwsClientBuilder#region(Region)} is
* not specified. This is enabled by default.
*/
public static final AwsAdvancedClientOption<Boolean> ENABLE_DEFAULT_REGION_DETECTION =
new AwsAdvancedClientOption<>(Boolean.class);
private AwsAdvancedClientOption(Class<T> valueClass) {
super(valueClass);
}
}
| 1,556 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/client | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/client/config/AwsClientOption.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore.client.config;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.auth.token.credentials.SdkTokenProvider;
import software.amazon.awssdk.awscore.client.builder.AwsClientBuilder;
import software.amazon.awssdk.awscore.defaultsmode.DefaultsMode;
import software.amazon.awssdk.core.client.config.ClientOption;
import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity;
import software.amazon.awssdk.identity.spi.IdentityProvider;
import software.amazon.awssdk.identity.spi.TokenIdentity;
import software.amazon.awssdk.regions.Region;
@SdkProtectedApi
public final class AwsClientOption<T> extends ClientOption<T> {
/**
* This option is deprecated in favor of {@link #CREDENTIALS_IDENTITY_PROVIDER}.
* @see AwsClientBuilder#credentialsProvider(AwsCredentialsProvider)
*/
@Deprecated
// smithy codegen TODO: This could be removed when doing a minor version bump where we told customers we'll be breaking
// protected APIs. Postpone this to when we do Smithy code generator migration, where we'll likely have to start
// breaking a lot of protected things.
public static final AwsClientOption<AwsCredentialsProvider> CREDENTIALS_PROVIDER =
new AwsClientOption<>(AwsCredentialsProvider.class);
/**
* @see AwsClientBuilder#credentialsProvider(IdentityProvider)
*/
public static final AwsClientOption<IdentityProvider<? extends AwsCredentialsIdentity>> CREDENTIALS_IDENTITY_PROVIDER =
new AwsClientOption<>(new UnsafeValueType(IdentityProvider.class));
/**
* AWS Region the client was configured with. Note that this is not always the signing region in the case of global
* services like IAM.
*/
public static final AwsClientOption<Region> AWS_REGION = new AwsClientOption<>(Region.class);
/**
* AWS Region to be used for signing the request. This is not always same as {@link #AWS_REGION} in case of global services.
*/
public static final AwsClientOption<Region> SIGNING_REGION = new AwsClientOption<>(Region.class);
/**
* Whether the SDK should resolve dualstack endpoints instead of default endpoints. See
* {@link AwsClientBuilder#dualstackEnabled(Boolean)}.
*/
public static final AwsClientOption<Boolean> DUALSTACK_ENDPOINT_ENABLED = new AwsClientOption<>(Boolean.class);
/**
* Whether the SDK should resolve fips endpoints instead of default endpoints. See
* {@link AwsClientBuilder#fipsEnabled(Boolean)}.
*/
public static final ClientOption<Boolean> FIPS_ENDPOINT_ENABLED = new AwsClientOption<>(Boolean.class);
/**
* Scope name to use during signing of a request.
*/
public static final AwsClientOption<String> SERVICE_SIGNING_NAME = new AwsClientOption<>(String.class);
/**
* The first part of the URL in the DNS name for the service. Eg. in the endpoint "dynamodb.amazonaws.com", this is the
* "dynamodb".
*
* For standard services, this should match the "endpointPrefix" field in the AWS model.
*/
public static final AwsClientOption<String> ENDPOINT_PREFIX = new AwsClientOption<>(String.class);
/**
* Configuration of the DEFAULTS_MODE. Unlike {@link #DEFAULTS_MODE}, this may be {@link DefaultsMode#AUTO}.
*/
public static final AwsClientOption<DefaultsMode> CONFIGURED_DEFAULTS_MODE = new AwsClientOption<>(DefaultsMode.class);
/**
* Option used by the rest of the SDK to read the {@link DefaultsMode}. This will never be {@link DefaultsMode#AUTO}.
*/
public static final AwsClientOption<DefaultsMode> DEFAULTS_MODE = new AwsClientOption<>(DefaultsMode.class);
/**
* Option to specify whether global endpoint should be used.
*/
public static final AwsClientOption<Boolean> USE_GLOBAL_ENDPOINT = new AwsClientOption<>(Boolean.class);
/**
* Option to specific the {@link SdkTokenProvider} to use for bearer token authorization.
* This option is deprecated in favor or {@link #TOKEN_IDENTITY_PROVIDER}
*/
@Deprecated
public static final AwsClientOption<SdkTokenProvider> TOKEN_PROVIDER = new AwsClientOption<>(SdkTokenProvider.class);
/**
* Option to specific the {@link SdkTokenProvider} to use for bearer token authorization.
*/
public static final AwsClientOption<IdentityProvider<? extends TokenIdentity>> TOKEN_IDENTITY_PROVIDER =
new AwsClientOption<>(new UnsafeValueType(IdentityProvider.class));
private AwsClientOption(Class<T> valueClass) {
super(valueClass);
}
private AwsClientOption(UnsafeValueType valueType) {
super(valueType);
}
}
| 1,557 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/client | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/client/builder/AwsAsyncClientBuilder.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore.client.builder;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.client.builder.SdkAsyncClientBuilder;
/**
* This includes required and optional override configuration required by every AWS async client builder. An instance can be
* acquired by calling the static "builder" method on the type of async client you wish to create.
*
* <p>Implementations of this interface are mutable and not thread-safe.</p>
*
* @param <B> The type of builder that should be returned by the fluent builder methods in this interface.
* @param <C> The type of client generated by this builder.
*/
@SdkPublicApi
public interface AwsAsyncClientBuilder<B extends AwsAsyncClientBuilder<B, C>, C> extends SdkAsyncClientBuilder<B, C> {
}
| 1,558 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/client | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/client/builder/AwsSyncClientBuilder.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore.client.builder;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.client.builder.SdkSyncClientBuilder;
/**
* This includes required and optional override configuration required by every sync client builder. An instance can be acquired
* by calling the static "builder" method on the type of sync client you wish to create.
*
* <p>Implementations of this interface are mutable and not thread-safe.</p>
*
* @param <B> The type of builder that should be returned by the fluent builder methods in this interface.
* @param <C> The type of client generated by this builder.
*/
@SdkPublicApi
public interface AwsSyncClientBuilder<B extends AwsSyncClientBuilder<B, C>, C> extends SdkSyncClientBuilder<B, C> {
}
| 1,559 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/client | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/client/builder/AwsClientBuilder.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore.client.builder;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.awscore.defaultsmode.DefaultsMode;
import software.amazon.awssdk.core.client.builder.SdkClientBuilder;
import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity;
import software.amazon.awssdk.identity.spi.IdentityProvider;
import software.amazon.awssdk.regions.Region;
/**
* This includes required and optional override configuration required by every client builder. An instance can be acquired by
* calling the static "builder" method on the type of client you wish to create.
*
* <p>Implementations of this interface are mutable and not thread-safe.</p>
*
* @param <BuilderT> The type of builder that should be returned by the fluent builder methods in this interface.
* @param <ClientT> The type of client generated by this builder.
*/
@SdkPublicApi
public interface AwsClientBuilder<BuilderT extends AwsClientBuilder<BuilderT, ClientT>, ClientT>
extends SdkClientBuilder<BuilderT, ClientT> {
/**
* Configure the credentials that should be used to authenticate with AWS.
*
* <p>The default provider will attempt to identify the credentials automatically using the following checks:
* <ol>
* <li>Java System Properties - <code>aws.accessKeyId</code> and <code>aws.secretAccessKey</code></li>
* <li>Environment Variables - <code>AWS_ACCESS_KEY_ID</code> and <code>AWS_SECRET_ACCESS_KEY</code></li>
* <li>Credential profiles file at the default location (~/.aws/credentials) shared by all AWS SDKs and the AWS CLI</li>
* <li>Credentials delivered through the Amazon EC2 container service if AWS_CONTAINER_CREDENTIALS_RELATIVE_URI environment
* variable is set and security manager has permission to access the variable.</li>
* <li>Instance profile credentials delivered through the Amazon EC2 metadata service</li>
* </ol>
*
* <p>If the credentials are not found in any of the locations above, an exception will be thrown at {@link #build()} time.
* </p>
*
* <p>The last of {@link #credentialsProvider(AwsCredentialsProvider)} or {@link #credentialsProvider(IdentityProvider)}
* wins.</p>
*/
default BuilderT credentialsProvider(AwsCredentialsProvider credentialsProvider) {
return credentialsProvider((IdentityProvider<AwsCredentialsIdentity>) credentialsProvider);
}
/**
* Configure the credentials that should be used to authenticate with AWS.
*
* <p>The default provider will attempt to identify the credentials automatically using the following checks:
* <ol>
* <li>Java System Properties - <code>aws.accessKeyId</code> and <code>aws.secretAccessKey</code></li>
* <li>Environment Variables - <code>AWS_ACCESS_KEY_ID</code> and <code>AWS_SECRET_ACCESS_KEY</code></li>
* <li>Credential profiles file at the default location (~/.aws/credentials) shared by all AWS SDKs and the AWS CLI</li>
* <li>Credentials delivered through the Amazon EC2 container service if AWS_CONTAINER_CREDENTIALS_RELATIVE_URI environment
* variable is set and security manager has permission to access the variable.</li>
* <li>Instance profile credentials delivered through the Amazon EC2 metadata service</li>
* </ol>
*
* <p>If the credentials are not found in any of the locations above, an exception will be thrown at {@link #build()} time.
* </p>
*
* <p>The last of {@link #credentialsProvider(AwsCredentialsProvider)} or {@link #credentialsProvider(IdentityProvider)}
* wins.</p>
*/
default BuilderT credentialsProvider(IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider) {
throw new UnsupportedOperationException();
}
/**
* Configure the region with which the SDK should communicate.
*
* <p>If this is not specified, the SDK will attempt to identify the endpoint automatically using the following logic:
* <ol>
* <li>Check the 'aws.region' system property for the region.</li>
* <li>Check the 'AWS_REGION' environment variable for the region.</li>
* <li>Check the {user.home}/.aws/credentials and {user.home}/.aws/config files for the region.</li>
* <li>If running in EC2, check the EC2 metadata service for the region.</li>
* </ol>
*
* <p>If the region is not found in any of the locations above, an exception will be thrown at {@link #build()} time.
*/
BuilderT region(Region region);
/**
* Sets the {@link DefaultsMode} that will be used to determine how certain default configuration options are resolved in
* the SDK.
*
* <p>
* If this is not specified, the SDK will attempt to identify the defaults mode automatically using the following logic:
* <ol>
* <li>Check the "defaults_mode" profile file property.</li>
* <li>Check "aws.defaultsMode" system property.</li>
* <li>Check the "AWS_DEFAULTS_MODE" environment variable.</li>
* </ol>
*
* @param defaultsMode the defaultsMode to use
* @return This object for method chaining.
* @see DefaultsMode
*/
default BuilderT defaultsMode(DefaultsMode defaultsMode) {
throw new UnsupportedOperationException();
}
/**
* Configure whether the SDK should use the AWS dualstack endpoint.
*
* <p>If this is not specified, the SDK will attempt to determine whether the dualstack endpoint should be used
* automatically using the following logic:
* <ol>
* <li>Check the 'aws.useDualstackEndpoint' system property for 'true' or 'false'.</li>
* <li>Check the 'AWS_USE_DUALSTACK_ENDPOINT' environment variable for 'true' or 'false'.</li>
* <li>Check the {user.home}/.aws/credentials and {user.home}/.aws/config files for the 'use_dualstack_endpoint'
* property set to 'true' or 'false'.</li>
* </ol>
*
* <p>If the setting is not found in any of the locations above, 'false' will be used.
*/
BuilderT dualstackEnabled(Boolean dualstackEndpointEnabled);
/**
* Configure whether the SDK should use the AWS fips endpoints.
*
* <p>If this is not specified, the SDK will attempt to determine whether the fips endpoint should be used
* automatically using the following logic:
* <ol>
* <li>Check the 'aws.useFipsEndpoint' system property for 'true' or 'false'.</li>
* <li>Check the 'AWS_USE_FIPS_ENDPOINT' environment variable for 'true' or 'false'.</li>
* <li>Check the {user.home}/.aws/credentials and {user.home}/.aws/config files for the 'use_fips_endpoint'
* property set to 'true' or 'false'.</li>
* </ol>
*
* <p>If the setting is not found in any of the locations above, 'false' will be used.
*/
BuilderT fipsEnabled(Boolean fipsEndpointEnabled);
}
| 1,560 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/client | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/client/builder/AwsDefaultClientBuilder.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore.client.builder;
import java.net.URI;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.annotations.SdkTestInternalApi;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.auth.credentials.CredentialUtils;
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.awscore.client.config.AwsAdvancedClientOption;
import software.amazon.awssdk.awscore.client.config.AwsClientOption;
import software.amazon.awssdk.awscore.defaultsmode.DefaultsMode;
import software.amazon.awssdk.awscore.endpoint.DefaultServiceEndpointBuilder;
import software.amazon.awssdk.awscore.endpoint.DualstackEnabledProvider;
import software.amazon.awssdk.awscore.endpoint.FipsEnabledProvider;
import software.amazon.awssdk.awscore.eventstream.EventStreamInitialRequestInterceptor;
import software.amazon.awssdk.awscore.interceptor.HelpfulUnknownHostExceptionInterceptor;
import software.amazon.awssdk.awscore.interceptor.TraceIdExecutionInterceptor;
import software.amazon.awssdk.awscore.internal.defaultsmode.AutoDefaultsModeDiscovery;
import software.amazon.awssdk.awscore.internal.defaultsmode.DefaultsModeConfiguration;
import software.amazon.awssdk.awscore.internal.defaultsmode.DefaultsModeResolver;
import software.amazon.awssdk.awscore.retry.AwsRetryPolicy;
import software.amazon.awssdk.core.client.builder.SdkDefaultClientBuilder;
import software.amazon.awssdk.core.client.config.SdkAdvancedClientOption;
import software.amazon.awssdk.core.client.config.SdkClientConfiguration;
import software.amazon.awssdk.core.client.config.SdkClientOption;
import software.amazon.awssdk.core.interceptor.ExecutionInterceptor;
import software.amazon.awssdk.core.retry.RetryMode;
import software.amazon.awssdk.core.retry.RetryPolicy;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity;
import software.amazon.awssdk.identity.spi.IdentityProvider;
import software.amazon.awssdk.identity.spi.IdentityProviders;
import software.amazon.awssdk.profiles.ProfileFile;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.regions.ServiceMetadata;
import software.amazon.awssdk.regions.ServiceMetadataAdvancedOption;
import software.amazon.awssdk.regions.providers.DefaultAwsRegionProviderChain;
import software.amazon.awssdk.utils.AttributeMap;
import software.amazon.awssdk.utils.AttributeMap.LazyValueSource;
import software.amazon.awssdk.utils.CollectionUtils;
import software.amazon.awssdk.utils.Logger;
import software.amazon.awssdk.utils.Pair;
import software.amazon.awssdk.utils.StringUtils;
/**
* An SDK-internal implementation of the methods in {@link AwsClientBuilder}, {@link AwsAsyncClientBuilder} and
* {@link AwsSyncClientBuilder}. This implements all methods required by those interfaces, allowing service-specific builders to
* just
* implement the configuration they wish to add.
*
* <p>By implementing both the sync and async interface's methods, service-specific builders can share code between their sync
* and
* async variants without needing one to extend the other. Note: This only defines the methods in the sync and async builder
* interfaces. It does not implement the interfaces themselves. This is because the sync and async client builder interfaces both
* require a type-constrained parameter for use in fluent chaining, and a generic type parameter conflict is introduced into the
* class hierarchy by this interface extending the builder interfaces themselves.</p>
*
* <p>Like all {@link AwsClientBuilder}s, this class is not thread safe.</p>
*
* @param <BuilderT> The type of builder, for chaining.
* @param <ClientT> The type of client generated by this builder.
*/
@SdkProtectedApi
public abstract class AwsDefaultClientBuilder<BuilderT extends AwsClientBuilder<BuilderT, ClientT>, ClientT>
extends SdkDefaultClientBuilder<BuilderT, ClientT>
implements AwsClientBuilder<BuilderT, ClientT> {
private static final Logger log = Logger.loggerFor(AwsClientBuilder.class);
private static final String DEFAULT_ENDPOINT_PROTOCOL = "https";
private static final String[] FIPS_SEARCH = {"fips-", "-fips"};
private static final String[] FIPS_REPLACE = {"", ""};
private final AutoDefaultsModeDiscovery autoDefaultsModeDiscovery;
protected AwsDefaultClientBuilder() {
super();
autoDefaultsModeDiscovery = new AutoDefaultsModeDiscovery();
}
@SdkTestInternalApi
AwsDefaultClientBuilder(SdkHttpClient.Builder defaultHttpClientBuilder,
SdkAsyncHttpClient.Builder defaultAsyncHttpClientFactory,
AutoDefaultsModeDiscovery autoDefaultsModeDiscovery) {
super(defaultHttpClientBuilder, defaultAsyncHttpClientFactory);
this.autoDefaultsModeDiscovery = autoDefaultsModeDiscovery;
}
/**
* Implemented by child classes to define the endpoint prefix used when communicating with AWS. This constitutes the first
* part of the URL in the DNS name for the service. Eg. in the endpoint "dynamodb.amazonaws.com", this is the "dynamodb".
*
* <p>For standard services, this should match the "endpointPrefix" field in the AWS model.</p>
*/
protected abstract String serviceEndpointPrefix();
/**
* Implemented by child classes to define the signing-name that should be used when signing requests when communicating with
* AWS.
*/
protected abstract String signingName();
/**
* Implemented by child classes to define the service name used to identify the request in things like metrics.
*/
protected abstract String serviceName();
@Override
protected final SdkClientConfiguration mergeChildDefaults(SdkClientConfiguration configuration) {
SdkClientConfiguration config = mergeServiceDefaults(configuration);
config = config.merge(c -> c.option(AwsAdvancedClientOption.ENABLE_DEFAULT_REGION_DETECTION, true)
.option(SdkAdvancedClientOption.DISABLE_HOST_PREFIX_INJECTION, false)
.option(AwsClientOption.SERVICE_SIGNING_NAME, signingName())
.option(SdkClientOption.SERVICE_NAME, serviceName())
.option(AwsClientOption.ENDPOINT_PREFIX, serviceEndpointPrefix()));
return mergeInternalDefaults(config);
}
/**
* Optionally overridden by child classes to define service-specific default configuration.
*/
protected SdkClientConfiguration mergeServiceDefaults(SdkClientConfiguration configuration) {
return configuration;
}
/**
* Optionally overridden by child classes to define internal default configuration.
*/
protected SdkClientConfiguration mergeInternalDefaults(SdkClientConfiguration configuration) {
return configuration;
}
/**
* Return a client configuration object, populated with the following chain of priorities.
* <ol>
* <li>Defaults vended from {@link DefaultsMode} </li>
* <li>AWS Global Defaults</li>
* </ol>
*/
@Override
protected final SdkClientConfiguration finalizeChildConfiguration(SdkClientConfiguration configuration) {
configuration = finalizeServiceConfiguration(configuration);
configuration = finalizeAwsConfiguration(configuration);
return configuration;
}
private SdkClientConfiguration finalizeAwsConfiguration(SdkClientConfiguration configuration) {
return configuration.toBuilder()
.option(SdkClientOption.EXECUTION_INTERCEPTORS, addAwsInterceptors(configuration))
.lazyOptionIfAbsent(AwsClientOption.AWS_REGION, this::resolveRegion)
.lazyOptionIfAbsent(AwsClientOption.DUALSTACK_ENDPOINT_ENABLED, this::resolveDualstackEndpointEnabled)
.lazyOptionIfAbsent(AwsClientOption.FIPS_ENDPOINT_ENABLED, this::resolveFipsEndpointEnabled)
.lazyOption(AwsClientOption.DEFAULTS_MODE, this::resolveDefaultsMode)
.lazyOption(SdkClientOption.DEFAULT_RETRY_MODE, this::resolveDefaultRetryMode)
.lazyOption(ServiceMetadataAdvancedOption.DEFAULT_S3_US_EAST_1_REGIONAL_ENDPOINT,
this::resolveDefaultS3UsEast1RegionalEndpoint)
.lazyOptionIfAbsent(AwsClientOption.CREDENTIALS_IDENTITY_PROVIDER,
this::resolveCredentialsIdentityProvider)
// CREDENTIALS_PROVIDER is also set, since older clients may be relying on it
.lazyOptionIfAbsent(AwsClientOption.CREDENTIALS_PROVIDER, this::resolveCredentialsProvider)
.lazyOptionIfAbsent(SdkClientOption.ENDPOINT, this::resolveEndpoint)
.lazyOption(AwsClientOption.SIGNING_REGION, this::resolveSigningRegion)
.lazyOption(SdkClientOption.HTTP_CLIENT_CONFIG, this::resolveHttpClientConfig)
.applyMutation(this::configureRetryPolicy)
.lazyOptionIfAbsent(SdkClientOption.IDENTITY_PROVIDERS, this::resolveIdentityProviders)
.build();
}
/**
* Return HTTP related defaults with the following chain of priorities.
* <ol>
* <li>Service-Specific Defaults</li>
* <li>Defaults vended by {@link DefaultsMode}</li>
* </ol>
*/
private AttributeMap resolveHttpClientConfig(LazyValueSource config) {
AttributeMap attributeMap = serviceHttpConfig();
return mergeSmartHttpDefaults(config, attributeMap);
}
/**
* Optionally overridden by child classes to define service-specific HTTP configuration defaults.
*/
protected AttributeMap serviceHttpConfig() {
return AttributeMap.empty();
}
private IdentityProviders resolveIdentityProviders(LazyValueSource config) {
// By default, all AWS clients get an identity provider for AWS credentials. Child classes may override this to specify
// AWS credentials and another identity type like Bearer credentials.
return IdentityProviders.builder()
.putIdentityProvider(config.get(AwsClientOption.CREDENTIALS_IDENTITY_PROVIDER))
.build();
}
private DefaultsMode resolveDefaultsMode(LazyValueSource config) {
DefaultsMode configuredMode = config.get(AwsClientOption.CONFIGURED_DEFAULTS_MODE);
if (configuredMode == null) {
configuredMode = DefaultsModeResolver.create()
.profileFile(config.get(SdkClientOption.PROFILE_FILE_SUPPLIER))
.profileName(config.get(SdkClientOption.PROFILE_NAME))
.resolve();
}
if (configuredMode != DefaultsMode.AUTO) {
return configuredMode;
}
return autoDefaultsModeDiscovery.discover(config.get(AwsClientOption.AWS_REGION));
}
private RetryMode resolveDefaultRetryMode(LazyValueSource config) {
return DefaultsModeConfiguration.defaultConfig(config.get(AwsClientOption.DEFAULTS_MODE))
.get(SdkClientOption.DEFAULT_RETRY_MODE);
}
private String resolveDefaultS3UsEast1RegionalEndpoint(LazyValueSource config) {
return DefaultsModeConfiguration.defaultConfig(config.get(AwsClientOption.DEFAULTS_MODE))
.get(ServiceMetadataAdvancedOption.DEFAULT_S3_US_EAST_1_REGIONAL_ENDPOINT);
}
/**
* Optionally overridden by child classes to derive service-specific configuration from the default-applied configuration.
*/
protected SdkClientConfiguration finalizeServiceConfiguration(SdkClientConfiguration configuration) {
return configuration;
}
/**
* Merged the HTTP defaults specified for each {@link DefaultsMode}
*/
private AttributeMap mergeSmartHttpDefaults(LazyValueSource config, AttributeMap attributeMap) {
DefaultsMode defaultsMode = config.get(AwsClientOption.DEFAULTS_MODE);
return attributeMap.merge(DefaultsModeConfiguration.defaultHttpConfig(defaultsMode));
}
/**
* Resolve the signing region from the default-applied configuration.
*/
private Region resolveSigningRegion(LazyValueSource config) {
return ServiceMetadata.of(serviceEndpointPrefix())
.signingRegion(config.get(AwsClientOption.AWS_REGION));
}
/**
* Resolve the endpoint from the default-applied configuration.
*/
private URI resolveEndpoint(LazyValueSource config) {
return new DefaultServiceEndpointBuilder(serviceEndpointPrefix(), DEFAULT_ENDPOINT_PROTOCOL)
.withRegion(config.get(AwsClientOption.AWS_REGION))
.withProfileFile(config.get(SdkClientOption.PROFILE_FILE_SUPPLIER))
.withProfileName(config.get(SdkClientOption.PROFILE_NAME))
.putAdvancedOption(ServiceMetadataAdvancedOption.DEFAULT_S3_US_EAST_1_REGIONAL_ENDPOINT,
config.get(ServiceMetadataAdvancedOption.DEFAULT_S3_US_EAST_1_REGIONAL_ENDPOINT))
.withDualstackEnabled(config.get(AwsClientOption.DUALSTACK_ENDPOINT_ENABLED))
.withFipsEnabled(config.get(AwsClientOption.FIPS_ENDPOINT_ENABLED))
.getServiceEndpoint();
}
/**
* Resolve the region that should be used based on the customer's configuration.
*/
private Region resolveRegion(LazyValueSource config) {
Boolean defaultRegionDetectionEnabled = config.get(AwsAdvancedClientOption.ENABLE_DEFAULT_REGION_DETECTION);
if (defaultRegionDetectionEnabled != null && !defaultRegionDetectionEnabled) {
throw new IllegalStateException("No region was configured, and use-region-provider-chain was disabled.");
}
Supplier<ProfileFile> profileFile = config.get(SdkClientOption.PROFILE_FILE_SUPPLIER);
String profileName = config.get(SdkClientOption.PROFILE_NAME);
return DefaultAwsRegionProviderChain.builder()
.profileFile(profileFile)
.profileName(profileName)
.build()
.getRegion();
}
/**
* Resolve whether a dualstack endpoint should be used for this client.
*/
private Boolean resolveDualstackEndpointEnabled(LazyValueSource config) {
Supplier<ProfileFile> profileFile = config.get(SdkClientOption.PROFILE_FILE_SUPPLIER);
String profileName = config.get(SdkClientOption.PROFILE_NAME);
return DualstackEnabledProvider.builder()
.profileFile(profileFile)
.profileName(profileName)
.build()
.isDualstackEnabled()
.orElse(null);
}
/**
* Resolve whether a fips endpoint should be used for this client.
*/
private Boolean resolveFipsEndpointEnabled(LazyValueSource config) {
Supplier<ProfileFile> profileFile = config.get(SdkClientOption.PROFILE_FILE_SUPPLIER);
String profileName = config.get(SdkClientOption.PROFILE_NAME);
return FipsEnabledProvider.builder()
.profileFile(profileFile)
.profileName(profileName)
.build()
.isFipsEnabled()
.orElse(null);
}
/**
* Resolve the credentials that should be used based on the customer's configuration.
*/
private IdentityProvider<? extends AwsCredentialsIdentity> resolveCredentialsIdentityProvider(LazyValueSource config) {
return DefaultCredentialsProvider.builder()
.profileFile(config.get(SdkClientOption.PROFILE_FILE_SUPPLIER))
.profileName(config.get(SdkClientOption.PROFILE_NAME))
.build();
}
private AwsCredentialsProvider resolveCredentialsProvider(LazyValueSource config) {
return CredentialUtils.toCredentialsProvider(config.get(AwsClientOption.CREDENTIALS_IDENTITY_PROVIDER));
}
private void configureRetryPolicy(SdkClientConfiguration.Builder config) {
RetryPolicy policy = config.option(SdkClientOption.RETRY_POLICY);
if (policy != null) {
if (policy.additionalRetryConditionsAllowed()) {
config.option(SdkClientOption.RETRY_POLICY, AwsRetryPolicy.addRetryConditions(policy));
}
return;
}
config.lazyOption(SdkClientOption.RETRY_POLICY, this::resolveAwsRetryPolicy);
}
private RetryPolicy resolveAwsRetryPolicy(LazyValueSource config) {
RetryMode retryMode = RetryMode.resolver()
.profileFile(config.get(SdkClientOption.PROFILE_FILE_SUPPLIER))
.profileName(config.get(SdkClientOption.PROFILE_NAME))
.defaultRetryMode(config.get(SdkClientOption.DEFAULT_RETRY_MODE))
.resolve();
return AwsRetryPolicy.forRetryMode(retryMode);
}
@Override
public final BuilderT region(Region region) {
Region regionToSet = region;
Boolean fipsEnabled = null;
if (region != null) {
Pair<Region, Optional<Boolean>> transformedRegion = transformFipsPseudoRegionIfNecessary(region);
regionToSet = transformedRegion.left();
fipsEnabled = transformedRegion.right().orElse(null);
}
clientConfiguration.option(AwsClientOption.AWS_REGION, regionToSet);
if (fipsEnabled != null) {
clientConfiguration.option(AwsClientOption.FIPS_ENDPOINT_ENABLED, fipsEnabled);
}
return thisBuilder();
}
public final void setRegion(Region region) {
region(region);
}
@Override
public BuilderT dualstackEnabled(Boolean dualstackEndpointEnabled) {
clientConfiguration.option(AwsClientOption.DUALSTACK_ENDPOINT_ENABLED, dualstackEndpointEnabled);
return thisBuilder();
}
public final void setDualstackEnabled(Boolean dualstackEndpointEnabled) {
dualstackEnabled(dualstackEndpointEnabled);
}
@Override
public BuilderT fipsEnabled(Boolean dualstackEndpointEnabled) {
clientConfiguration.option(AwsClientOption.FIPS_ENDPOINT_ENABLED, dualstackEndpointEnabled);
return thisBuilder();
}
public final void setFipsEnabled(Boolean fipsEndpointEnabled) {
fipsEnabled(fipsEndpointEnabled);
}
public final void setCredentialsProvider(AwsCredentialsProvider credentialsProvider) {
credentialsProvider(credentialsProvider);
}
@Override
public final BuilderT credentialsProvider(IdentityProvider<? extends AwsCredentialsIdentity> identityProvider) {
clientConfiguration.option(AwsClientOption.CREDENTIALS_IDENTITY_PROVIDER, identityProvider);
return thisBuilder();
}
public final void setCredentialsProvider(IdentityProvider<? extends AwsCredentialsIdentity> identityProvider) {
credentialsProvider(identityProvider);
}
private List<ExecutionInterceptor> addAwsInterceptors(SdkClientConfiguration config) {
List<ExecutionInterceptor> interceptors = awsInterceptors();
interceptors = CollectionUtils.mergeLists(interceptors, config.option(SdkClientOption.EXECUTION_INTERCEPTORS));
return interceptors;
}
private List<ExecutionInterceptor> awsInterceptors() {
return Arrays.asList(new HelpfulUnknownHostExceptionInterceptor(),
new EventStreamInitialRequestInterceptor(),
new TraceIdExecutionInterceptor());
}
@Override
public final BuilderT defaultsMode(DefaultsMode defaultsMode) {
clientConfiguration.option(AwsClientOption.CONFIGURED_DEFAULTS_MODE, defaultsMode);
return thisBuilder();
}
public final void setDefaultsMode(DefaultsMode defaultsMode) {
defaultsMode(defaultsMode);
}
/**
* If the region is a FIPS pseudo region (contains "fips"), this method returns a pair of values, the left side being the
* region with the "fips" string removed, and the right being {@code true}. Otherwise, the region is returned
* unchanged, and the right will be empty.
*/
private static Pair<Region, Optional<Boolean>> transformFipsPseudoRegionIfNecessary(Region region) {
String id = region.id();
String newId = StringUtils.replaceEach(id, FIPS_SEARCH, FIPS_REPLACE);
if (!newId.equals(id)) {
log.info(() -> String.format("Replacing input region %s with %s and setting fipsEnabled to true", id, newId));
return Pair.of(Region.of(newId), Optional.of(true));
}
return Pair.of(region, Optional.empty());
}
}
| 1,561 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/interceptor/HelpfulUnknownHostExceptionInterceptor.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore.interceptor;
import java.net.UnknownHostException;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.awscore.AwsExecutionAttribute;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.interceptor.Context;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.interceptor.ExecutionInterceptor;
import software.amazon.awssdk.regions.PartitionMetadata;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.regions.RegionMetadata;
import software.amazon.awssdk.regions.ServiceMetadata;
import software.amazon.awssdk.regions.ServicePartitionMetadata;
/**
* This interceptor will monitor for {@link UnknownHostException}s and provide the customer with additional information they can
* use to debug or fix the problem.
*/
@SdkInternalApi
public final class HelpfulUnknownHostExceptionInterceptor implements ExecutionInterceptor {
@Override
public Throwable modifyException(Context.FailedExecution context, ExecutionAttributes executionAttributes) {
if (!hasCause(context.exception(), UnknownHostException.class)) {
return context.exception();
}
StringBuilder error = new StringBuilder();
error.append("Received an UnknownHostException when attempting to interact with a service. See cause for the "
+ "exact endpoint that is failing to resolve. ");
Optional<String> globalRegionErrorDetails = getGlobalRegionErrorDetails(executionAttributes);
if (globalRegionErrorDetails.isPresent()) {
error.append(globalRegionErrorDetails.get());
} else {
error.append("If this is happening on an endpoint that previously worked, there may be a network connectivity "
+ "issue or your DNS cache could be storing endpoints for too long.");
}
return SdkClientException.builder().message(error.toString()).cause(context.exception()).build();
}
/**
* If the customer is interacting with a global service (one with a single endpoint/region for an entire partition), this
* will return error details that can instruct the customer on how to configure their client for success.
*/
private Optional<String> getGlobalRegionErrorDetails(ExecutionAttributes executionAttributes) {
Region clientRegion = clientRegion(executionAttributes);
if (clientRegion.isGlobalRegion()) {
return Optional.empty();
}
List<ServicePartitionMetadata> globalPartitionsForService = globalPartitionsForService(executionAttributes);
if (globalPartitionsForService.isEmpty()) {
return Optional.empty();
}
String clientPartition = Optional.ofNullable(clientRegion.metadata())
.map(RegionMetadata::partition)
.map(PartitionMetadata::id)
.orElse(null);
Optional<Region> globalRegionForClientRegion =
globalPartitionsForService.stream()
.filter(p -> p.partition().id().equals(clientPartition))
.findAny()
.flatMap(ServicePartitionMetadata::globalRegion);
if (!globalRegionForClientRegion.isPresent()) {
String globalRegionsForThisService = globalPartitionsForService.stream()
.map(ServicePartitionMetadata::globalRegion)
.filter(Optional::isPresent)
.map(Optional::get)
.filter(Region::isGlobalRegion)
.map(Region::id)
.collect(Collectors.joining("/"));
return Optional.of("This specific service may be a global service, in which case you should configure a global "
+ "region like " + globalRegionsForThisService + " on the client.");
}
Region globalRegion = globalRegionForClientRegion.get();
return Optional.of("This specific service is global in the same partition as the region configured on this client ("
+ clientRegion + "). If this is the first time you're trying to talk to this service in this region, "
+ "you should try configuring the global region on your client, instead: " + globalRegion);
}
/**
* Retrieve the region configured on the client.
*/
private Region clientRegion(ExecutionAttributes executionAttributes) {
return executionAttributes.getAttribute(AwsExecutionAttribute.AWS_REGION);
}
/**
* Retrieve all global partitions for the AWS service that we're interacting with.
*/
private List<ServicePartitionMetadata> globalPartitionsForService(ExecutionAttributes executionAttributes) {
return ServiceMetadata.of(executionAttributes.getAttribute(AwsExecutionAttribute.ENDPOINT_PREFIX))
.servicePartitions()
.stream()
.filter(sp -> sp.globalRegion().isPresent())
.collect(Collectors.toList());
}
private boolean hasCause(Throwable thrown, Class<? extends Throwable> cause) {
if (thrown == null) {
return false;
}
if (cause.isAssignableFrom(thrown.getClass())) {
return true;
}
return hasCause(thrown.getCause(), cause);
}
}
| 1,562 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/interceptor/TraceIdExecutionInterceptor.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore.interceptor;
import java.util.Optional;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.awscore.internal.interceptor.TracingSystemSetting;
import software.amazon.awssdk.core.interceptor.Context;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.interceptor.ExecutionInterceptor;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.utils.SystemSetting;
/**
* The {@code TraceIdExecutionInterceptor} copies the trace details to the {@link #TRACE_ID_HEADER} header, assuming we seem to
* be running in a lambda environment.
*/
@SdkInternalApi
public class TraceIdExecutionInterceptor implements ExecutionInterceptor {
private static final String TRACE_ID_HEADER = "X-Amzn-Trace-Id";
private static final String LAMBDA_FUNCTION_NAME_ENVIRONMENT_VARIABLE = "AWS_LAMBDA_FUNCTION_NAME";
@Override
public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) {
Optional<String> traceIdHeader = traceIdHeader(context);
if (!traceIdHeader.isPresent()) {
Optional<String> lambdafunctionName = lambdaFunctionNameEnvironmentVariable();
Optional<String> traceId = traceId();
if (lambdafunctionName.isPresent() && traceId.isPresent()) {
return context.httpRequest().copy(r -> r.putHeader(TRACE_ID_HEADER, traceId.get()));
}
}
return context.httpRequest();
}
private Optional<String> traceIdHeader(Context.ModifyHttpRequest context) {
return context.httpRequest().firstMatchingHeader(TRACE_ID_HEADER);
}
private Optional<String> traceId() {
return TracingSystemSetting._X_AMZN_TRACE_ID.getStringValue();
}
private Optional<String> lambdaFunctionNameEnvironmentVariable() {
// CHECKSTYLE:OFF - This is not configured by the customer, so it should not be configurable by system property
return SystemSetting.getStringValueFromEnvironmentVariable(LAMBDA_FUNCTION_NAME_ENVIRONMENT_VARIABLE);
// CHECKSTYLE:ON
}
}
| 1,563 |
0 | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore | Create_ds/aws-sdk-java-v2/core/aws-core/src/main/java/software/amazon/awssdk/awscore/interceptor/GlobalServiceExecutionInterceptor.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.awscore.interceptor;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.interceptor.Context;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.interceptor.ExecutionInterceptor;
/**
* A more specific version of {@link HelpfulUnknownHostExceptionInterceptor} that was used for older IAM clients. This can be
* removed if we ever drop backwards-compatibility with older IAM client versions, because newer IAM client versions do not
* depend on this interceptor.
*/
@SdkProtectedApi
public class GlobalServiceExecutionInterceptor implements ExecutionInterceptor {
private static final HelpfulUnknownHostExceptionInterceptor DELEGATE = new HelpfulUnknownHostExceptionInterceptor();
@Override
public Throwable modifyException(Context.FailedExecution context, ExecutionAttributes executionAttributes) {
return DELEGATE.modifyException(context, executionAttributes);
}
}
| 1,564 |
0 | Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions/RegionTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.regions;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertSame;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
public class RegionTest {
@Test(expected = NullPointerException.class)
public void of_ThrowsNullPointerException_WhenNullValue() {
Region.of(null);
}
@Test(expected = IllegalArgumentException.class)
public void of_ThrowsIllegalArgumentException_WhenEmptyString() {
Region.of("");
}
@Test(expected = IllegalArgumentException.class)
public void of_ThrowsIllegalArgumentException_WhenBlankString() {
Region.of(" ");
}
@Test
public void of_ReturnsRegion_WhenValidString() {
Region region = Region.of("us-east-1");
assertThat(region.id()).isEqualTo("us-east-1");
assertSame(Region.US_EAST_1, region);
}
@Test
public void sameValueSameClassAreSameInstance() {
Region first = Region.of("first");
Region alsoFirst = Region.of("first");
assertThat(first).isSameAs(alsoFirst);
}
@Test
public void canBeUsedAsKeysInMap() {
Map<Region, String> someMap = new HashMap<>();
someMap.put(Region.of("key"), "A Value");
assertThat(someMap.get(Region.of("key"))).isEqualTo("A Value");
}
@Test
public void idIsUrlEncoded() {
Region region = Region.of("http://my-host.com/?");
assertThat(region.id()).isEqualTo("http%3A%2F%2Fmy-host.com%2F%3F");
}
}
| 1,565 |
0 | Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions/ServiceEndpointKeyTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.regions;
import nl.jqno.equalsverifier.EqualsVerifier;
import org.junit.jupiter.api.Test;
public class ServiceEndpointKeyTest {
@Test
public void equalsHashCodeTest() {
EqualsVerifier.forClass(ServiceEndpointKey.class)
.withNonnullFields("region", "tags")
.verify();
}
} | 1,566 |
0 | Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions/PartitionEndpointKeyTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.regions;
import nl.jqno.equalsverifier.EqualsVerifier;
import org.junit.jupiter.api.Test;
public class PartitionEndpointKeyTest {
@Test
public void equalsHashCodeTest() {
EqualsVerifier.forClass(PartitionEndpointKey.class)
.withNonnullFields("tags")
.verify();
}
} | 1,567 |
0 | Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions/PartitionServiceMetadataTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.regions;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Test;
public class PartitionServiceMetadataTest {
private static final List<String> AWS_PARTITION_GLOBAL_SERVICES = Arrays.asList(
"budgets", "cloudfront", "iam", "route53", "shield", "waf");
private static final List<String> AWS_PARTITION_REGIONALIZED_SERVICES = Arrays.asList(
"acm", "apigateway", "application-autoscaling", "appstream2", "autoscaling", "batch",
"cloudformation", "cloudhsm", "cloudsearch", "cloudtrail", "codebuild", "codecommit", "codedeploy",
"codepipeline", "cognito-identity", "cognito-idp", "cognito-sync", "config", "cur", "data.iot",
"datapipeline", "directconnect", "dms", "ds", "dynamodb", "ec2", "ecs", "elasticache",
"elasticbeanstalk", "elasticfilesystem", "elasticloadbalancing", "elasticmapreduce", "elastictranscoder",
"email", "es", "events", "firehose", "gamelift", "glacier", "inspector",
"iot", "kinesis", "kinesisanalytics", "kms", "lambda", "lightsail", "logs", "machinelearning",
"marketplacecommerceanalytics", "metering.marketplace", "mobileanalytics", "monitoring", "opsworks",
"opsworks-cm", "pinpoint", "polly", "rds", "redshift", "rekognition", "route53domains", "s3",
"sdb", "servicecatalog", "sms", "snowball", "sns", "sqs", "ssm", "states", "storagegateway",
"streams.dynamodb", "sts", "support", "swf", "waf-regional", "workspaces", "xray");
private static final List<String> AWS_CN_PARTITION_GLOBAL_SERVICES = Arrays.asList("iam");
private static final List<String> AWS_CN_PARTITION_REGIONALIZED_SERVICES = Arrays.asList(
"autoscaling", "cloudformation", "cloudtrail", "config", "directconnect", "dynamodb",
"ec2", "elasticache", "elasticbeanstalk", "elasticloadbalancing", "elasticmapreduce",
"events", "glacier", "kinesis", "logs", "monitoring", "rds", "redshift", "s3",
"sns", "sqs", "storagegateway", "streams.dynamodb", "sts", "swf");
private static final List<String> AWS_US_GOV_PARTITION_REGIONALIZED_SERVICES = Arrays.asList(
"autoscaling", "cloudformation", "cloudhsm", "cloudtrail", "config", "directconnect",
"dynamodb", "ec2", "elasticache", "elasticloadbalancing", "elasticmapreduce", "glacier",
"kms", "logs", "monitoring", "rds", "redshift", "s3", "snowball", "sns", "sqs", "streams.dynamodb",
"sts", "swf");
private static final List<String> AWS_US_GOV_PARTITION_GLOBAL_SERVICES = Arrays.asList("iam");
@Test
public void endpointFor_ReturnsEndpoint_ForAllRegionalizedServices_When_AwsPartition() {
AWS_PARTITION_REGIONALIZED_SERVICES.forEach(
s -> assertThat(ServiceMetadata.of(s).endpointFor(Region.US_EAST_1)).isNotNull());
}
@Test
public void endpointFor_ReturnsEndpoint_ForAllGlobalServices_When_AwsGlobalRegion() {
AWS_PARTITION_GLOBAL_SERVICES.forEach(
s -> assertThat(ServiceMetadata.of(s).endpointFor(Region.AWS_GLOBAL)).isNotNull());
}
@Test
public void endpointFor_ReturnsEndpoint_ForAllRegionalizedServices_When_AwsCnPartition() {
AWS_CN_PARTITION_REGIONALIZED_SERVICES.forEach(
s -> assertThat(ServiceMetadata.of(s).endpointFor(Region.CN_NORTH_1)).isNotNull());
}
@Test
public void endpointFor_ReturnsEndpoint_ForAllGlobalServices_When_AwsCnGlobalRegion() {
AWS_CN_PARTITION_GLOBAL_SERVICES.forEach(
s -> assertThat(ServiceMetadata.of(s).endpointFor(Region.AWS_CN_GLOBAL)).isNotNull());
}
@Test
public void endpointFor_ReturnsEndpoint_ForAllRegionalizedServices_When_AwsUsGovPartition() {
AWS_US_GOV_PARTITION_REGIONALIZED_SERVICES.forEach(
s -> assertThat(ServiceMetadata.of(s).endpointFor(Region.US_GOV_WEST_1)).isNotNull());
}
@Test
public void endpointFor_ReturnsEndpoint_ForAllGlobalServices_When_AwsUsGovGlobalRegion() {
AWS_US_GOV_PARTITION_GLOBAL_SERVICES.forEach(
s -> assertThat(ServiceMetadata.of(s).endpointFor(Region.AWS_US_GOV_GLOBAL)).isNotNull());
}
@Test
public void regions_ReturnsGreaterThan15Regions_ForS3() {
assertThat(ServiceMetadata.of("s3").regions().size()).isGreaterThan(15);
}
@Test
public void servicePartitions_ReturnsAllValidPartitions() {
validateServicesAreInPartition(AWS_PARTITION_GLOBAL_SERVICES, "aws");
validateServicesAreInPartition(AWS_PARTITION_REGIONALIZED_SERVICES, "aws");
validateServicesAreInPartition(AWS_CN_PARTITION_GLOBAL_SERVICES, "aws-cn");
validateServicesAreInPartition(AWS_CN_PARTITION_REGIONALIZED_SERVICES, "aws-cn");
validateServicesAreInPartition(AWS_US_GOV_PARTITION_GLOBAL_SERVICES, "aws-us-gov");
validateServicesAreInPartition(AWS_US_GOV_PARTITION_REGIONALIZED_SERVICES, "aws-us-gov");
}
@Test
public void servicePartitions_HasGlobalEndpoint_ForGlobalServices() {
validateHasGlobalEndpointInPartition(AWS_PARTITION_GLOBAL_SERVICES, "aws", true);
validateHasGlobalEndpointInPartition(AWS_CN_PARTITION_GLOBAL_SERVICES, "aws-cn", true);
validateHasGlobalEndpointInPartition(AWS_US_GOV_PARTITION_GLOBAL_SERVICES, "aws-us-gov", true);
}
@Test
public void servicePartitions_HasNoGlobalEndpoint_ForRegionalServices() {
validateHasGlobalEndpointInPartition(AWS_PARTITION_REGIONALIZED_SERVICES, "aws", false);
validateHasGlobalEndpointInPartition(AWS_CN_PARTITION_REGIONALIZED_SERVICES, "aws-cn", false);
validateHasGlobalEndpointInPartition(AWS_US_GOV_PARTITION_REGIONALIZED_SERVICES, "aws-us-gov", false);
}
private void validateHasGlobalEndpointInPartition(List<String> services, String partition, boolean hasGlobalEndpoint) {
services.forEach(s -> assertThat(ServiceMetadata.of(s)
.servicePartitions()
.stream()
.filter(sp -> sp.partition().id().equals(partition))
.anyMatch(sp -> sp.globalRegion().isPresent()))
.as(s + " is global in " + partition)
.isEqualTo(hasGlobalEndpoint));
}
private void validateServicesAreInPartition(List<String> services, String partition) {
services.forEach(s -> assertThat(ServiceMetadata.of(s)
.servicePartitions()
.stream()
.map(p -> p.partition().id())
.collect(Collectors.toList()))
.as(s + " is in " + partition)
.contains(partition));
}
}
| 1,568 |
0 | Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions | Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions/servicemetadata/GeneratedServiceMetadataProviderTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.regions.servicemetadata;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.regions.GeneratedServiceMetadataProvider;
public class GeneratedServiceMetadataProviderTest {
private static final GeneratedServiceMetadataProvider PROVIDER = new GeneratedServiceMetadataProvider();
@Test
public void s3Metadata_isEnhanced() {
assertThat(PROVIDER.serviceMetadata("s3")).isInstanceOf(EnhancedS3ServiceMetadata.class);
}
}
| 1,569 |
0 | Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions | Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions/servicemetadata/EnhancedS3ServiceMetadataTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.regions.servicemetadata;
import static org.assertj.core.api.Assertions.assertThat;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collection;
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.profiles.ProfileFile;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.regions.ServiceMetadata;
import software.amazon.awssdk.regions.ServiceMetadataAdvancedOption;
import software.amazon.awssdk.testutils.EnvironmentVariableHelper;
import software.amazon.awssdk.utils.Validate;
@RunWith(Parameterized.class)
public class EnhancedS3ServiceMetadataTest {
private static final EnvironmentVariableHelper ENVIRONMENT_VARIABLE_HELPER = new EnvironmentVariableHelper();
private static final URI S3_GLOBAL_ENDPOINT = URI.create("s3.amazonaws.com");
private static final URI S3_IAD_REGIONAL_ENDPOINT = URI.create("s3.us-east-1.amazonaws.com");
private ServiceMetadata enhancedMetadata = new EnhancedS3ServiceMetadata();
@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, S3_GLOBAL_ENDPOINT),
// Test precedence
new TestData("regional", null, null, null, S3_IAD_REGIONAL_ENDPOINT),
new TestData("test", "regional", "/profileconfig/s3_regional_config_profile.tst", "regional",
S3_GLOBAL_ENDPOINT),
new TestData(null, "regional", "/profileconfig/s3_regional_config_profile.tst", "non-regional",
S3_IAD_REGIONAL_ENDPOINT),
new TestData(null, null, "/profileconfig/s3_regional_config_profile.tst", "non-regional", S3_IAD_REGIONAL_ENDPOINT),
new TestData(null, null, null, "regional", S3_IAD_REGIONAL_ENDPOINT),
// Test capitalization standardization
new TestData("rEgIONal", null, null, null, S3_IAD_REGIONAL_ENDPOINT),
new TestData(null, "rEgIONal", null, null, S3_IAD_REGIONAL_ENDPOINT),
new TestData(null, null, "/profileconfig/s3_regional_config_profile_mixed_case.tst", null, S3_IAD_REGIONAL_ENDPOINT),
new TestData(null, null, null, "rEgIONal", S3_IAD_REGIONAL_ENDPOINT),
// Test other value
new TestData("othervalue", null, null, null, S3_GLOBAL_ENDPOINT),
new TestData(null, "dafsad", null, null, S3_GLOBAL_ENDPOINT),
new TestData(null, null, "/profileconfig/s3_regional_config_profile_non_regional.tst", null, S3_GLOBAL_ENDPOINT),
new TestData(null, null, null, "somehtingelse", S3_GLOBAL_ENDPOINT),
});
}
@After
public void methodSetup() {
ENVIRONMENT_VARIABLE_HELPER.reset();
System.clearProperty(SdkSystemSetting.AWS_S3_US_EAST_1_REGIONAL_ENDPOINT.property());
}
@Test
public void differentCombinationOfConfigs_shouldResolveCorrectly() {
enhancedMetadata =
new EnhancedS3ServiceMetadata().reconfigure(c -> c.putAdvancedOption(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();
enhancedMetadata = enhancedMetadata.reconfigure(c -> c.profileFile(() -> file)
.profileName("regional_s3_endpoint")
.putAdvancedOption(ServiceMetadataAdvancedOption.DEFAULT_S3_US_EAST_1_REGIONAL_ENDPOINT,
testData.advancedOption));
}
URI result = enhancedMetadata.endpointFor(Region.US_EAST_1);
assertThat(result).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 URI expected;
TestData(String systemProperty, String envVarValue, String configFile, String advancedOption, URI expected) {
this.envVarValue = envVarValue;
this.systemProperty = systemProperty;
this.configFile = configFile;
this.advancedOption = advancedOption;
this.expected = expected;
}
}
}
| 1,570 |
0 | Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions | Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions/util/HttpCredentialsUtilsTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.regions.util;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.github.tomakehurst.wiremock.client.WireMock;
import com.github.tomakehurst.wiremock.core.WireMockConfiguration;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.exception.SdkServiceException;
import software.amazon.awssdk.core.util.SdkUserAgent;
import software.amazon.awssdk.regions.internal.util.ConnectionUtils;
import software.amazon.awssdk.regions.internal.util.SocketUtils;
@RunWith(MockitoJUnitRunner.class)
public class HttpCredentialsUtilsTest {
@ClassRule
public static WireMockRule mockServer = new WireMockRule(WireMockConfiguration.wireMockConfig().port(0), false);
private static final String CREDENTIALS_PATH = "/dummy/credentials/path";
private static final String SUCCESS_BODY = "{\"AccessKeyId\":\"ACCESS_KEY_ID\",\"SecretAccessKey\":\"SECRET_ACCESS_KEY\","
+ "\"Token\":\"TOKEN_TOKEN_TOKEN\",\"Expiration\":\"3000-05-03T04:55:54Z\"}";
private static URI endpoint;
private static Map<String, String> headers = new HashMap<String, String>()
{
{
put("User-Agent", SdkUserAgent.create().userAgent());
put("Accept", "*/*");
put("Connection", "keep-alive");
}
};
private static CustomRetryPolicy customRetryPolicy;
private static HttpResourcesUtils httpCredentialsUtils;
@Mock
private ConnectionUtils mockConnection;
@BeforeClass
public static void setup() throws URISyntaxException {
endpoint = new URI("http://localhost:" + mockServer.port() + CREDENTIALS_PATH);
customRetryPolicy = new CustomRetryPolicy();
httpCredentialsUtils = HttpResourcesUtils.instance();
}
/**
* When a connection to end host cannot be opened, throws {@link IOException}.
*/
@Test(expected = IOException.class)
public void readResourceThrowsIOExceptionWhenNoConnection() throws IOException, URISyntaxException {
int port = 0;
try {
port = SocketUtils.getUnusedPort();
} catch (IOException ioexception) {
fail("Unable to find an unused port");
}
httpCredentialsUtils.readResource(new URI("http://localhost:" + port));
}
/**
* When server returns with status code 200,
* the test successfully returns the body from the response.
*/
@Test
public void readResouceReturnsResponseBodyFor200Response() throws IOException {
generateStub(200, SUCCESS_BODY);
assertEquals(SUCCESS_BODY, httpCredentialsUtils.readResource(endpoint));
}
/**
* When server returns with 404 status code,
* the test should throw SdkClientException.
*/
@Test
public void readResouceReturnsAceFor404ErrorResponse() throws Exception {
try {
httpCredentialsUtils.readResource(new URI("http://localhost:" + mockServer.port() + "/dummyPath"));
fail("Expected SdkClientException");
} catch (SdkClientException ace) {
assertTrue(ace.getMessage().contains("The requested metadata is not found at"));
}
}
/**
* When server returns a status code other than 200 and 404,
* the test should throw SdkServiceException. The request
* is not retried.
*/
@Test
public void readResouceReturnsServiceExceptionFor5xxResponse() throws IOException {
generateStub(500, "{\"code\":\"500 Internal Server Error\",\"message\":\"ERROR_MESSAGE\"}");
try {
httpCredentialsUtils.readResource(endpoint);
fail("Expected SdkServiceException");
} catch (SdkServiceException exception) {
assertEquals(500, exception.statusCode());
}
}
/**
* When server returns a status code other than 200 and 404
* and error body message is not in Json format,
* the test throws SdkServiceException.
*/
@Test
public void readResouceNonJsonErrorBody() throws IOException {
generateStub(500, "Non Json error body");
try {
httpCredentialsUtils.readResource(endpoint);
fail("Expected SdkServiceException");
} catch (SdkServiceException exception) {
assertEquals(500, exception.statusCode());
}
}
/**
* When readResource is called with default retry policy and IOException occurs,
* the request is not retried.
*/
@Test
public void readResouceWithDefaultRetryPolicy_DoesNotRetry_ForIoException() throws IOException {
Mockito.when(mockConnection.connectToEndpoint(endpoint, headers, "GET")).thenThrow(new IOException());
try {
new HttpResourcesUtils(mockConnection).readResource(endpoint);
fail("Expected an IOexception");
} catch (IOException exception) {
Mockito.verify(mockConnection, Mockito.times(1)).connectToEndpoint(endpoint, headers, "GET");
}
}
/**
* When readResource is called with custom retry policy and IOException occurs,
* the request is retried and the number of retries is equal to the value
* returned by getMaxRetries method of the custom retry policy.
*/
@Test
public void readResouceWithCustomRetryPolicy_DoesRetry_ForIoException() throws IOException {
Mockito.when(mockConnection.connectToEndpoint(endpoint, headers, "GET")).thenThrow(new IOException());
try {
new HttpResourcesUtils(mockConnection).readResource(endpointProvider(endpoint, customRetryPolicy));
fail("Expected an IOexception");
} catch (IOException exception) {
Mockito.verify(mockConnection, Mockito.times(CustomRetryPolicy.MAX_RETRIES + 1)).connectToEndpoint(endpoint, headers, "GET");
}
}
/**
* When readResource is called with custom retry policy
* and the exception is not an IOException,
* then the request is not retried.
*/
@Test
public void readResouceWithCustomRetryPolicy_DoesNotRetry_ForNonIoException() throws IOException {
generateStub(500, "Non Json error body");
Mockito.when(mockConnection.connectToEndpoint(endpoint, headers, "GET")).thenCallRealMethod();
try {
new HttpResourcesUtils(mockConnection).readResource(endpointProvider(endpoint, customRetryPolicy));
fail("Expected an SdkServiceException");
} catch (SdkServiceException exception) {
Mockito.verify(mockConnection, Mockito.times(1)).connectToEndpoint(endpoint, headers, "GET");
}
}
private void generateStub(int statusCode, String message) {
WireMock.stubFor(
WireMock.get(WireMock.urlPathEqualTo(CREDENTIALS_PATH))
.willReturn(WireMock.aResponse()
.withStatus(statusCode)
.withHeader("Content-Type", "application/json")
.withHeader("charset", "utf-8")
.withBody(message)));
}
/**
* Retry policy that retries only if a request fails with an IOException.
*/
private static class CustomRetryPolicy implements ResourcesEndpointRetryPolicy {
private static final int MAX_RETRIES = 3;
@Override
public boolean shouldRetry(int retriesAttempted, ResourcesEndpointRetryParameters retryParams) {
if (retriesAttempted >= MAX_RETRIES) {
return false;
}
if (retryParams.getException() != null && retryParams.getException() instanceof IOException) {
return true;
}
return false;
}
}
private static ResourcesEndpointProvider endpointProvider(URI endpoint, ResourcesEndpointRetryPolicy retryPolicy) {
return new ResourcesEndpointProvider() {
@Override
public URI endpoint() throws IOException {
return endpoint;
}
@Override
public ResourcesEndpointRetryPolicy retryPolicy() {
return retryPolicy;
}
};
}
}
| 1,571 |
0 | Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions | Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions/providers/AwsRegionProviderChainTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.regions.providers;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.junit.Test;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.regions.Region;
public class AwsRegionProviderChainTest {
@Test
public void firstProviderInChainGivesRegionInformation_DoesNotConsultOtherProviders() {
AwsRegionProvider providerOne = mock(AwsRegionProvider.class);
AwsRegionProvider providerTwo = mock(AwsRegionProvider.class);
AwsRegionProvider providerThree = mock(AwsRegionProvider.class);
AwsRegionProviderChain chain = new AwsRegionProviderChain(providerOne, providerTwo,
providerThree);
final Region expectedRegion = Region.of("some-region-string");
when(providerOne.getRegion()).thenReturn(expectedRegion);
assertEquals(expectedRegion, chain.getRegion());
verify(providerTwo, never()).getRegion();
verify(providerThree, never()).getRegion();
}
@Test
public void lastProviderInChainGivesRegionInformation() {
final Region expectedRegion = Region.of("some-region-string");
AwsRegionProviderChain chain = new AwsRegionProviderChain(new NeverAwsRegionProvider(),
new NeverAwsRegionProvider(),
new StaticAwsRegionProvider(
expectedRegion));
assertEquals(expectedRegion, chain.getRegion());
}
@Test
public void providerThrowsException_ContinuesToNextInChain() {
final Region expectedRegion = Region.of("some-region-string");
AwsRegionProviderChain chain = new AwsRegionProviderChain(new NeverAwsRegionProvider(),
new FaultyAwsRegionProvider(),
new StaticAwsRegionProvider(
expectedRegion));
assertEquals(expectedRegion, chain.getRegion());
}
/**
* Only Exceptions should be caught and continued, Errors should propagate to caller and short
* circuit the chain.
*/
@Test(expected = Error.class)
public void providerThrowsError_DoesNotContinueChain() {
final Region expectedRegion = Region.of("some-region-string");
AwsRegionProviderChain chain = new AwsRegionProviderChain(new NeverAwsRegionProvider(),
new FatalAwsRegionProvider(),
new StaticAwsRegionProvider(
expectedRegion));
assertEquals(expectedRegion, chain.getRegion());
}
@Test (expected = SdkClientException.class)
public void noProviderGivesRegion_ThrowsException() {
AwsRegionProviderChain chain = new AwsRegionProviderChain(new NeverAwsRegionProvider(),
new NeverAwsRegionProvider(),
new NeverAwsRegionProvider());
chain.getRegion();
}
private static class NeverAwsRegionProvider implements AwsRegionProvider {
@Override
public Region getRegion() throws SdkClientException {
return null;
}
}
private static class StaticAwsRegionProvider implements AwsRegionProvider {
private final Region region;
public StaticAwsRegionProvider(Region region) {
this.region = region;
}
@Override
public Region getRegion() {
return region;
}
}
private static class FaultyAwsRegionProvider implements AwsRegionProvider {
@Override
public Region getRegion() throws SdkClientException {
throw SdkClientException.builder().message("Unable to fetch region info").build();
}
}
private static class FatalAwsRegionProvider implements AwsRegionProvider {
@Override
public Region getRegion() throws SdkClientException {
throw new Error("Something really bad happened");
}
}
}
| 1,572 |
0 | Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions | Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions/providers/LazyAwsRegionProviderTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.regions.providers;
import java.util.function.Supplier;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
public class LazyAwsRegionProviderTest {
@SuppressWarnings("unchecked")
private Supplier<AwsRegionProvider> regionProviderConstructor = Mockito.mock(Supplier.class);
private AwsRegionProvider regionProvider = Mockito.mock(AwsRegionProvider.class);
@BeforeEach
public void reset() {
Mockito.reset(regionProvider, regionProviderConstructor);
Mockito.when(regionProviderConstructor.get()).thenReturn(regionProvider);
}
@Test
public void creationDoesntInvokeSupplier() {
new LazyAwsRegionProvider(regionProviderConstructor);
Mockito.verifyNoMoreInteractions(regionProviderConstructor);
}
@Test
public void getRegionInvokesSupplierExactlyOnce() {
LazyAwsRegionProvider lazyRegionProvider = new LazyAwsRegionProvider(regionProviderConstructor);
lazyRegionProvider.getRegion();
lazyRegionProvider.getRegion();
Mockito.verify(regionProviderConstructor, Mockito.times(1)).get();
Mockito.verify(regionProvider, Mockito.times(2)).getRegion();
}
} | 1,573 |
0 | Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions | Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions/providers/InstanceProfileRegionProviderTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.regions.providers;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import software.amazon.awssdk.core.SdkSystemSetting;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.regions.internal.util.EC2MetadataUtilsServer;
/**
* Tests broken up by fixture.
*/
@RunWith(Enclosed.class)
public class InstanceProfileRegionProviderTest {
/**
* If the EC2 metadata service is running it should return the region the server is mocked
* with.
*/
public static class MetadataServiceRunningTest {
private static EC2MetadataUtilsServer server;
private AwsRegionProvider regionProvider;
@BeforeClass
public static void setupFixture() throws IOException {
server = new EC2MetadataUtilsServer(0);
server.start();
System.setProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT.property(),
"http://localhost:" + server.getLocalPort());
}
@AfterClass
public static void tearDownFixture() throws IOException {
server.stop();
System.clearProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT.property());
}
@Before
public void setup() {
regionProvider = new InstanceProfileRegionProvider();
}
@Test
public void metadataServiceRunning_ProvidesCorrectRegion() {
assertEquals(Region.US_EAST_1, regionProvider.getRegion());
}
@Test(expected = SdkClientException.class)
public void ec2MetadataDisabled_shouldReturnNull() {
try {
System.setProperty(SdkSystemSetting.AWS_EC2_METADATA_DISABLED.property(), "true");
regionProvider.getRegion();
} finally {
System.clearProperty(SdkSystemSetting.AWS_EC2_METADATA_DISABLED.property());
}
}
}
/**
* If the EC2 metadata service is not present then the provider will throw an exception. If the provider is used
* in a {@link AwsRegionProviderChain}, the chain will catch the exception and go on to the next region provider.
*/
public static class MetadataServiceNotRunning {
private AwsRegionProvider regionProvider;
@Before
public void setup() {
System.setProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT.property(), "http://localhost:54123");
regionProvider = new InstanceProfileRegionProvider();
}
@Test (expected = SdkClientException.class)
public void metadataServiceNotRunning_ThrowsException() {
regionProvider.getRegion();
}
}
}
| 1,574 |
0 | Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions | Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions/providers/AwsProfileRegionProviderTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.regions.providers;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.net.URISyntaxException;
import java.nio.file.Paths;
import org.junit.Rule;
import org.junit.Test;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.profiles.ProfileFileSystemSetting;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.testutils.EnvironmentVariableHelper;
public class AwsProfileRegionProviderTest {
@Rule
public EnvironmentVariableHelper settingsHelper = new EnvironmentVariableHelper();
@Test
public void nonExistentDefaultConfigFile_ThrowsException() {
settingsHelper.set(ProfileFileSystemSetting.AWS_CONFIG_FILE, "/var/tmp/this/is/invalid.txt");
settingsHelper.set(ProfileFileSystemSetting.AWS_SHARED_CREDENTIALS_FILE, "/var/tmp/this/is/also.invalid.txt");
assertThatThrownBy(() -> new AwsProfileRegionProvider().getRegion())
.isInstanceOf(SdkClientException.class)
.hasMessageContaining("No region provided in profile: default");
}
@Test
public void profilePresentAndRegionIsSet_ProvidesCorrectRegion() throws URISyntaxException {
String testFile = "/profileconfig/test-profiles.tst";
settingsHelper.set(ProfileFileSystemSetting.AWS_PROFILE, "test");
settingsHelper.set(ProfileFileSystemSetting.AWS_CONFIG_FILE, Paths.get(getClass().getResource(testFile).toURI()).toString());
assertThat(new AwsProfileRegionProvider().getRegion()).isEqualTo(Region.of("saa"));
}
}
| 1,575 |
0 | Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions | Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions/internal/RegionScopeTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.regions.internal;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import software.amazon.awssdk.regions.RegionScope;
@RunWith(Parameterized.class)
public class RegionScopeTest {
private final TestCase testCase;
public RegionScopeTest(TestCase testCase) {
this.testCase = testCase;
}
@Test
public void validateRegionScope() {
try {
RegionScope regionScope = RegionScope.create(testCase.regionScope);
assertThat(regionScope.id()).isEqualTo(testCase.regionScope);
} catch (RuntimeException e) {
if (testCase.expectedException == null) {
throw e;
}
assertThat(e).isInstanceOf(testCase.expectedException);
}
}
@Parameterized.Parameters(name = "{0}")
public static Collection<TestCase> testCases() {
List<TestCase> cases = new ArrayList<>();
cases.add(new TestCase().setCaseName("Standard Region accepted").setRegionScope("eu-north-1"));
cases.add(new TestCase().setCaseName("Wildcard last segment accepted").setRegionScope("eu-north-*"));
cases.add(new TestCase().setCaseName("Wildcard middle segment accepted").setRegionScope("eu-*"));
cases.add(new TestCase().setCaseName("Global Wildcard accepted").setRegionScope("*"));
cases.add(new TestCase().setCaseName("Null string fails").setRegionScope(null).setExpectedException(NullPointerException.class));
cases.add(new TestCase().setCaseName("Empty string fails")
.setRegionScope("")
.setExpectedException(IllegalArgumentException.class));
cases.add(new TestCase().setCaseName("Blank string fails")
.setRegionScope(" ")
.setExpectedException(IllegalArgumentException.class));
cases.add(new TestCase().setCaseName("Wildcard mixed last segment fails")
.setRegionScope("eu-north-45*")
.setExpectedException(IllegalArgumentException.class));
cases.add(new TestCase().setCaseName("Wildcard mixed middle segment fails")
.setRegionScope("eu-north*")
.setExpectedException(IllegalArgumentException.class));
cases.add(new TestCase().setCaseName("Wildcard mixed global fails")
.setRegionScope("eu*")
.setExpectedException(IllegalArgumentException.class));
cases.add(new TestCase().setCaseName("Wildcard not at end fails")
.setRegionScope("*-north-1")
.setExpectedException(IllegalArgumentException.class));
cases.add(new TestCase().setCaseName("Double wildcard fails")
.setRegionScope("**")
.setExpectedException(IllegalArgumentException.class));
return cases;
}
private static class TestCase {
private String caseName;
private String regionScope;
private Class<? extends RuntimeException> expectedException;
public TestCase setCaseName(String caseName) {
this.caseName = caseName;
return this;
}
public TestCase setRegionScope(String regionScope) {
this.regionScope = regionScope;
return this;
}
public TestCase setExpectedException(Class<? extends RuntimeException> expectedException) {
this.expectedException = expectedException;
return this;
}
@Override
public String toString() {
return this.caseName + (regionScope == null ? "" : ": " + regionScope);
}
}
}
| 1,576 |
0 | Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions/internal | Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions/internal/util/EC2MetadataUtilsTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.regions.internal.util;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.put;
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.urlPathEqualTo;
import static org.assertj.core.api.Assertions.assertThat;
import com.github.tomakehurst.wiremock.client.WireMock;
import com.github.tomakehurst.wiremock.http.Fault;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import software.amazon.awssdk.core.SdkSystemSetting;
import software.amazon.awssdk.core.exception.SdkClientException;
public class EC2MetadataUtilsTest {
private static final String TOKEN_RESOURCE_PATH = "/latest/api/token";
private static final String TOKEN_HEADER = "x-aws-ec2-metadata-token";
private static final String EC2_METADATA_TOKEN_TTL_HEADER = "x-aws-ec2-metadata-token-ttl-seconds";
private static final String EC2_METADATA_ROOT = "/latest/meta-data";
private static final String AMI_ID_RESOURCE = EC2_METADATA_ROOT + "/ami-id";
@Rule
public ExpectedException thrown = ExpectedException.none();
@Rule
public WireMockRule mockMetadataEndpoint = new WireMockRule();
@Before
public void methodSetup() {
System.setProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT.property(), "http://localhost:" + mockMetadataEndpoint.port());
EC2MetadataUtils.clearCache();
}
@Test
public void getToken_queriesCorrectPath() {
stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withBody("some-token")));
String token = EC2MetadataUtils.getToken();
assertThat(token).isEqualTo("some-token");
WireMock.verify(putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)).withHeader(EC2_METADATA_TOKEN_TTL_HEADER, equalTo("21600")));
}
@Test
public void getAmiId_queriesAndIncludesToken() {
stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withBody("some-token")));
stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)).willReturn(aResponse().withBody("{}")));
EC2MetadataUtils.getAmiId();
WireMock.verify(putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)).withHeader(EC2_METADATA_TOKEN_TTL_HEADER, equalTo("21600")));
WireMock.verify(getRequestedFor(urlPathEqualTo(AMI_ID_RESOURCE)).withHeader(TOKEN_HEADER, equalTo("some-token")));
}
@Test
public void getAmiId_tokenQueryTimeout_fallsBackToInsecure() {
stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withFixedDelay(Integer.MAX_VALUE)));
stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)).willReturn(aResponse().withBody("{}")));
EC2MetadataUtils.getAmiId();
WireMock.verify(putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)).withHeader(EC2_METADATA_TOKEN_TTL_HEADER, equalTo("21600")));
WireMock.verify(getRequestedFor(urlPathEqualTo(AMI_ID_RESOURCE)).withoutHeader(TOKEN_HEADER));
}
@Test
public void getAmiId_queriesTokenResource_403Error_fallbackToInsecure() {
stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withStatus(403).withBody("oops")));
stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)).willReturn(aResponse().withBody("{}")));
EC2MetadataUtils.getAmiId();
WireMock.verify(putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)).withHeader(EC2_METADATA_TOKEN_TTL_HEADER, equalTo("21600")));
WireMock.verify(getRequestedFor(urlPathEqualTo(AMI_ID_RESOURCE)).withoutHeader(TOKEN_HEADER));
}
@Test
public void getAmiId_queriesTokenResource_404Error_fallbackToInsecure() {
stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withStatus(404).withBody("oops")));
stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)).willReturn(aResponse().withBody("{}")));
EC2MetadataUtils.getAmiId();
WireMock.verify(putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)).withHeader(EC2_METADATA_TOKEN_TTL_HEADER, equalTo("21600")));
WireMock.verify(getRequestedFor(urlPathEqualTo(AMI_ID_RESOURCE)).withoutHeader(TOKEN_HEADER));
}
@Test
public void getAmiId_queriesTokenResource_405Error_fallbackToInsecure() {
stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withStatus(405).withBody("oops")));
stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)).willReturn(aResponse().withBody("{}")));
EC2MetadataUtils.getAmiId();
WireMock.verify(putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)).withHeader(EC2_METADATA_TOKEN_TTL_HEADER, equalTo("21600")));
WireMock.verify(getRequestedFor(urlPathEqualTo(AMI_ID_RESOURCE)).withoutHeader(TOKEN_HEADER));
}
@Test
public void getAmiId_queriesTokenResource_400Error_throws() {
thrown.expect(SdkClientException.class);
thrown.expectMessage("token");
stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withStatus(400).withBody("oops")));
stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)).willReturn(aResponse().withBody("{}")));
EC2MetadataUtils.getAmiId();
}
@Test
public void fetchDataWithAttemptNumber_ioError_shouldHonor() {
int attempts = 1;
thrown.expect(SdkClientException.class);
thrown.expectMessage("Unable to contact EC2 metadata service");
stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withBody("some-token")));;
stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)).willReturn(aResponse().withFault(Fault.CONNECTION_RESET_BY_PEER)));
EC2MetadataUtils.fetchData(AMI_ID_RESOURCE, false, attempts);
WireMock.verify(attempts, getRequestedFor(urlPathEqualTo(AMI_ID_RESOURCE)));
}
}
| 1,577 |
0 | Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions/internal | Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions/internal/util/EC2MetadataUtilsServer.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.regions.internal.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
/**
* Starts a new EC2 Metadata server instance with given address and port number.
*/
public class EC2MetadataUtilsServer {
private ServerSocket server;
public EC2MetadataUtilsServer(int port)
throws UnknownHostException, IOException {
server = new ServerSocket(port, 1, InetAddress.getLoopbackAddress());
}
public void start()
throws UnknownHostException, IOException {
Thread thread = new Thread() {
@Override
public void run() {
try {
startServer();
} catch (IOException exception) {
if ((exception instanceof SocketException)
&& (exception.getMessage().equals("Socket closed"))) {
return;
}
throw new RuntimeException("BOOM", exception);
}
}
};
thread.setDaemon(true);
thread.start();
}
public void stop() throws IOException {
if (server != null) {
server.close();
}
}
public int getLocalPort() {
return server.getLocalPort();
}
private void startServer() throws IOException {
while (true) {
try (Socket sock = server.accept(); BufferedReader reader = new BufferedReader(new InputStreamReader(
sock.getInputStream()));
PrintWriter writer = new PrintWriter(sock.getOutputStream());) {
handleConnection(reader, writer);
}
}
}
private void handleConnection(BufferedReader input,
PrintWriter output) throws IOException {
String line = input.readLine();
if (line == null) {
return;
}
String[] parts = line.split(" ");
if (parts.length != 3) {
throw new RuntimeException("Bogus request: " + line);
}
if (!"GET".equals(parts[0]) && !"PUT".equals(parts[0])) {
throw new RuntimeException("Bogus verb: " + line);
}
ignoreRequest(input);
String path = parts[1];
if (path.equals("/latest/meta-data/iam/info")) {
outputIamInfo(output);
} else if (path.equals("/latest/meta-data/iam/security-credentials")) {
outputIamCredList(output);
} else if (path
.startsWith("/latest/meta-data/iam/security-credentials/")) {
outputIamCred(output);
} else if (path.equals("/latest/dynamic/instance-identity/document")) {
outputInstanceInfo(output);
} else if (path.equals("/latest/dynamic/instance-identity/signature")) {
outputInstanceSignature(output);
} else if (path.equals("/latest/api/token")) {
outputToken(output);
} else {
throw new RuntimeException("Unknown path: " + path);
}
}
private void ignoreRequest(BufferedReader input) throws IOException {
while (true) {
String line = input.readLine();
if (line == null) {
throw new RuntimeException("Unexpected end of input");
}
if (line.length() == 0) {
return;
}
}
}
private void outputToken(PrintWriter output) {
String payload = "test-token";
output.println("HTTP/1.1 200 OK");
output.println("Connection: close");
output.println("Content-Length: " + payload.length());
output.println();
output.print(payload);
output.flush();
}
private void outputIamInfo(PrintWriter output) throws IOException {
String payload =
"{"
+ "\"Code\":\"Success\","
+ "\"LastUpdated\":\"2014-04-07T08:18:41Z\","
+ "\"InstanceProfileArn\":\"foobar\","
+ "\"InstanceProfileId\":\"moobily\","
+ "\"NewFeature\":12345"
+ "}";
output.println("HTTP/1.1 200 OK");
output.println("Connection: close");
output.println("Content-Length: " + payload.length());
output.println();
output.print(payload);
output.flush();
}
private void outputIamCredList(PrintWriter output)
throws IOException {
String payload = "test1\ntest2";
output.println("HTTP/1.1 200 OK");
output.println("Connection: close");
output.println("Content-Length: " + payload.length());
output.println();
output.print(payload);
output.flush();
}
private void outputIamCred(PrintWriter output) throws IOException {
String payload =
"{"
+ "\"Code\":\"Success\","
+ "\"LastUpdated\":\"2014-04-07T08:18:41Z\","
+ "\"Type\":\"AWS-HMAC\","
+ "\"AccessKeyId\":\"foobar\","
+ "\"SecretAccessKey\":\"moobily\","
+ "\"Token\":\"beebop\","
+ "\"Expiration\":\"2014-04-08T23:16:53Z\""
+ "}";
output.println("HTTP/1.1 200 OK");
output.println("Connection: close");
output.println("Content-Length: " + payload.length());
output.println();
output.print(payload);
output.flush();
}
private void outputInstanceInfo(PrintWriter output)
throws IOException {
String payload = constructInstanceInfo();
output.println("HTTP/1.1 200 OK");
output.println("Connection: close");
output.println("Content-Length: " + payload.length());
output.println();
output.print(payload);
output.flush();
}
protected String constructInstanceInfo() {
return "{"
+ "\"pendingTime\":\"2014-08-07T22:07:46Z\","
+ "\"instanceType\":\"m1.small\","
+ "\"imageId\":\"ami-a49665cc\","
+ "\"instanceId\":\"i-6b2de041\","
+ "\"billingProducts\":[\"foo\"],"
+ "\"architecture\":\"x86_64\","
+ "\"accountId\":\"599169622985\","
+ "\"kernelId\":\"aki-919dcaf8\","
+ "\"ramdiskId\":\"baz\","
+ "\"region\":\"us-east-1\","
+ "\"version\":\"2010-08-31\","
+ "\"availabilityZone\":\"us-east-1b\","
+ "\"privateIp\":\"10.201.215.38\","
+ "\"devpayProductCodes\":[\"bar\"],"
+ "\"marketplaceProductCodes\":[\"qaz\"]"
+ "}";
}
private void outputInstanceSignature(PrintWriter output) {
String payload = "foobar";
output.println("HTTP/1.1 200 OK");
output.println("Connection: close");
output.println("Content-Length: " + payload.length());
output.println();
output.print(payload);
output.flush();
}
}
| 1,578 |
0 | Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions/internal | Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions/internal/util/ConnectionUtilsComponentTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.regions.internal.util;
import static java.util.Collections.emptyMap;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assume.assumeTrue;
import com.github.tomakehurst.wiremock.client.WireMock;
import com.github.tomakehurst.wiremock.core.WireMockConfiguration;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.Inet4Address;
import java.net.URI;
import java.util.Collections;
import org.junit.After;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
public class ConnectionUtilsComponentTest {
@ClassRule
public static WireMockRule mockProxyServer = new WireMockRule(WireMockConfiguration.wireMockConfig().port(0), false);
@Rule
public WireMockRule mockServer = new WireMockRule(WireMockConfiguration.wireMockConfig().port(0), false);
private final ConnectionUtils sut = ConnectionUtils.create();
@After
public void cleanup() {
System.getProperties().remove("http.proxyHost");
System.getProperties().remove("http.proxyPort");
}
@Test
public void proxiesAreNotUsedEvenIfPropertyIsSet() throws IOException {
assumeTrue(Inet4Address.getLocalHost().isReachable(100));
System.getProperties().put("http.proxyHost", "localhost");
System.getProperties().put("http.proxyPort", String.valueOf(mockProxyServer.port()));
HttpURLConnection connection = sut.connectToEndpoint(URI.create("http://" + Inet4Address.getLocalHost().getHostAddress() + ":" + mockServer.port()), emptyMap());
assertThat(connection.usingProxy()).isFalse();
}
@Test
public void headersArePassedAsPartOfRequest() throws IOException {
HttpURLConnection connection = sut.connectToEndpoint(URI.create("http://localhost:" + mockServer.port()), Collections.singletonMap("HeaderA", "ValueA"));
connection.getResponseCode();
mockServer.verify(WireMock.getRequestedFor(WireMock.urlMatching("/")).withHeader("HeaderA", WireMock.equalTo("ValueA")));
}
@Test
public void shouldNotFollowRedirects() throws IOException {
mockServer.stubFor(WireMock.get(WireMock.urlMatching("/")).willReturn(WireMock.aResponse().withStatus(301).withHeader("Location", "http://localhost:" + mockServer.port() + "/hello")));
HttpURLConnection connection = sut.connectToEndpoint(URI.create("http://localhost:" + mockServer.port()), Collections.emptyMap());
assertThat(connection.getResponseCode()).isEqualTo(301);
}
}
| 1,579 |
0 | Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions/internal | Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions/internal/util/Ec2MetadataUtilsTt0049160280Test.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.regions.internal.util;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
public class Ec2MetadataUtilsTt0049160280Test {
private static final String JSON = "{"
+ " \"privateIp\" : \"172.31.56.174\","
+ " \"devpayProductCodes\" : null,"
+ " \"availabilityZone\" : \"us-east-1b\","
+ " \"version\" : \"2010-08-31\","
+ " \"accountId\" : \"123456789012\","
+ " \"instanceId\" : \"i-b32c0064\","
+ " \"billingProducts\" : [\"bp-6ba54002\" ],"
+ " \"imageId\" : \"ami-ac3a1cc4\","
+ " \"instanceType\" : \"t2.small\","
+ " \"kernelId\" : null,"
+ " \"ramdiskId\" : null,"
+ " \"pendingTime\" : \"2015-04-13T19:57:24Z\","
+ " \"architecture\" : \"x86_64\","
+ " \"region\" : \"us-east-1\""
+ "}";
@Test
public void getRegionIntern() throws Exception {
String region = EC2MetadataUtils.doGetEC2InstanceRegion(JSON);
assertEquals("us-east-1", region);
}
@Test
public void tt0049160280() {
EC2MetadataUtils.InstanceInfo info = EC2MetadataUtils.doGetInstanceInfo(JSON);
String[] billingProducts = info.getBillingProducts();
assertTrue(billingProducts.length == 1);
assertEquals(billingProducts[0], "bp-6ba54002");
}
@Test
public void devProductCodes() {
final String JSON = "{"
+ " \"privateIp\" : \"172.31.56.174\","
+ " \"devpayProductCodes\" : [\"foo\", \"bar\"],"
+ " \"availabilityZone\" : \"us-east-1b\","
+ " \"version\" : \"2010-08-31\","
+ " \"accountId\" : \"123456789012\","
+ " \"instanceId\" : \"i-b32c0064\","
+ " \"billingProducts\" : [\"bp-6ba54002\" ],"
+ " \"imageId\" : \"ami-ac3a1cc4\","
+ " \"instanceType\" : \"t2.small\","
+ " \"kernelId\" : null,"
+ " \"ramdiskId\" : null,"
+ " \"pendingTime\" : \"2015-04-13T19:57:24Z\","
+ " \"architecture\" : \"x86_64\","
+ " \"region\" : \"us-east-1\""
+ "}";
EC2MetadataUtils.InstanceInfo info = EC2MetadataUtils.doGetInstanceInfo(JSON);
String[] devpayProductCodes = info.getDevpayProductCodes();
assertTrue(devpayProductCodes.length == 2);
assertEquals(devpayProductCodes[0], "foo");
assertEquals(devpayProductCodes[1], "bar");
}
}
| 1,580 |
0 | Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions/internal | Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions/internal/util/SocketUtils.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.regions.internal.util;
import java.io.IOException;
import java.net.ServerSocket;
public class SocketUtils {
/**
* Returns an unused port in the localhost.
*/
public static int getUnusedPort() throws IOException {
try (ServerSocket socket = new ServerSocket(0)) {
socket.setReuseAddress(true);
return socket.getLocalPort();
}
}
}
| 1,581 |
0 | Create_ds/aws-sdk-java-v2/core/regions/src/it/java/software/amazon/awssdk/regions | Create_ds/aws-sdk-java-v2/core/regions/src/it/java/software/amazon/awssdk/regions/util/EC2MetadataUtilsIntegrationTest.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.regions.util;
import java.io.IOException;
import java.util.Map;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import software.amazon.awssdk.core.SdkSystemSetting;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.regions.internal.util.EC2MetadataUtils;
import software.amazon.awssdk.regions.internal.util.EC2MetadataUtilsServer;
public class EC2MetadataUtilsIntegrationTest {
private static EC2MetadataUtilsServer SERVER = null;
@BeforeClass
public static void setUp() throws IOException {
SERVER = new EC2MetadataUtilsServer( 0);
SERVER.start();
System.setProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT.property(),
"http://localhost:" + SERVER.getLocalPort());
}
@AfterClass
public static void cleanUp() throws IOException {
if (SERVER != null) {
SERVER.stop();
}
System.clearProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT.property());
}
@Test(expected = SdkClientException.class)
public void ec2MetadataDisabled_shouldThrowException() {
try {
System.setProperty(SdkSystemSetting.AWS_EC2_METADATA_DISABLED.property(), "true");
EC2MetadataUtils.getInstanceId();
} finally {
System.clearProperty(SdkSystemSetting.AWS_EC2_METADATA_DISABLED.property());
}
}
@Test
public void testInstanceSignature() {
String signature = EC2MetadataUtils.getInstanceSignature();
Assert.assertEquals("foobar", signature);
}
@Test
public void testInstanceInfo() {
EC2MetadataUtils.InstanceInfo info = EC2MetadataUtils.getInstanceInfo();
Assert.assertEquals("2014-08-07T22:07:46Z", info.getPendingTime());
Assert.assertEquals("m1.small", info.getInstanceType());
Assert.assertEquals("ami-a49665cc", info.getImageId());
Assert.assertEquals("i-6b2de041", info.getInstanceId());
Assert.assertEquals("foo", info.getBillingProducts()[0]);
Assert.assertEquals("x86_64", info.getArchitecture());
Assert.assertEquals("599169622985", info.getAccountId());
Assert.assertEquals("aki-919dcaf8", info.getKernelId());
Assert.assertEquals("baz", info.getRamdiskId());
Assert.assertEquals("us-east-1", info.getRegion());
Assert.assertEquals("2010-08-31", info.getVersion());
Assert.assertEquals("us-east-1b", info.getAvailabilityZone());
Assert.assertEquals("10.201.215.38", info.getPrivateIp());
Assert.assertEquals("bar", info.getDevpayProductCodes()[0]);
Assert.assertEquals("qaz", info.getMarketplaceProductCodes()[0]);
}
}
| 1,582 |
0 | Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/ServiceMetadata.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.regions;
import java.net.URI;
import java.util.List;
import java.util.function.Consumer;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.profiles.ProfileFile;
import software.amazon.awssdk.regions.internal.MetadataLoader;
/**
* Metadata about a service, like S3, DynamoDB, etc.
*
* <p>This is useful for building meta-functionality around AWS services. For example, UIs that list the available regions for a
* service would use the {@link #regions()} method for a service.</p>
*
* <p>This is usually created by calling the {@code serviceMetadata} method on the service client's interface, but can also be
* created by calling the {@link #of(String)} method and providing the service's unique endpoint prefix.</p>
*/
@SdkPublicApi
public interface ServiceMetadata {
/**
* Retrieve the AWS endpoint that should be used for this service in the provided region, if no {@link EndpointTag}s are
* desired.
*
* @param region The region that should be used to load the service endpoint.
* @return The region-specific endpoint for this service.
* @throws RuntimeException if an endpoint cannot be determined.
*/
default URI endpointFor(Region region) {
return endpointFor(ServiceEndpointKey.builder().region(region).build());
}
/**
* Retrieve the AWS endpoint that should be used for this service associated with the provided {@link ServiceEndpointKey}.
*
* @param key The service endpoint key with which an endpoint should be retrieved.
* @return The region-specific endpoint for this service.
* @throws RuntimeException if an endpoint cannot be determined.
*/
default URI endpointFor(ServiceEndpointKey key) {
throw new UnsupportedOperationException();
}
/**
* Retrieve the region that should be used for message signing when communicating with this service in the provided region.
* For most services, this will match the provided region, but it may differ for unusual services or when using a region that
* does not correspond to a physical location, like {@link Region#AWS_GLOBAL}.
*
* @param region The region from which the signing region should be derived.
* @return The region that should be used for signing messages when communicating with this service in the requested region.
*/
default Region signingRegion(Region region) {
return signingRegion(ServiceEndpointKey.builder().region(region).build());
}
/**
* Retrieve the region that should be used for message signing when communicating with this service in the provided region
* and with the provided endpoint tags. For most services, this will match the provided region, but it may differ for
* unusual services or when using a region that does not correspond to a physical location, like {@link Region#AWS_GLOBAL}.
*
* @param key The service endpoint key with which an endpoint should be retrieved.
* @return The region that should be used for signing messages when communicating with this service in the requested region.
*/
default Region signingRegion(ServiceEndpointKey key) {
throw new UnsupportedOperationException();
}
/**
* Retrieve the list of regions this service is currently available in.
*
* @return The list of regions this service is currently available in.
*/
List<Region> regions();
/**
* Retrieve the service-specific partition configuration of each partition in which this service is currently available.
*
* @return The list of service-specific service metadata for each partition in which this service is available.
*/
List<ServicePartitionMetadata> servicePartitions();
/**
* Load the service metadata for the provided service endpoint prefix. This should only be used when you do not wish to have
* a dependency on the service for which you are retrieving the metadata. When you have a dependency on the service client,
* the metadata should instead be loaded using the service client's {@code serviceMetadata()} method.
*
* @param serviceEndpointPrefix The service-specific endpoint prefix of the service about which you wish to load metadata.
* @return The service metadata for the requested service.
*/
static ServiceMetadata of(String serviceEndpointPrefix) {
ServiceMetadata metadata = MetadataLoader.serviceMetadata(serviceEndpointPrefix);
return metadata == null ? new DefaultServiceMetadata(serviceEndpointPrefix) : metadata;
}
/**
* Reconfigure this service metadata using the provided {@link ServiceMetadataConfiguration}. This is useful, because some
* service metadata instances refer to external configuration that might wish to be modified, like a {@link ProfileFile}.
*/
default ServiceMetadata reconfigure(ServiceMetadataConfiguration configuration) {
return this;
}
/**
* Reconfigure this service metadata using the provided {@link ServiceMetadataConfiguration}. This is useful, because some
* service metadata instances refer to external configuration that might wish to be modified, like a {@link ProfileFile}.
*
* This is a shorthand form of {@link #reconfigure(ServiceMetadataConfiguration)}, without the need to call
* {@code builder()} or {@code build()}.
*/
default ServiceMetadata reconfigure(Consumer<ServiceMetadataConfiguration.Builder> consumer) {
ServiceMetadataConfiguration.Builder configuration = ServiceMetadataConfiguration.builder();
consumer.accept(configuration);
return reconfigure(configuration.build());
}
}
| 1,583 |
0 | Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/ServiceMetadataAdvancedOption.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.regions;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.SdkSystemSetting;
import software.amazon.awssdk.core.client.config.ClientOption;
import software.amazon.awssdk.profiles.ProfileProperty;
/**
* A collection of advanced options that can be configured on a {@link ServiceMetadata} via
* {@link ServiceMetadataConfiguration.Builder#putAdvancedOption(ServiceMetadataAdvancedOption, Object)}.
*
* @param <T> The type of value associated with the option.
*/
@SdkPublicApi
public class ServiceMetadataAdvancedOption<T> extends ClientOption<T> {
/**
* The default S3 regional endpoint setting for the {@code us-east-1} region to use. Setting
* the value to {@code regional} causes the SDK to use the {@code s3.us-east-1.amazonaws.com} endpoint when using the
* {@link Region#US_EAST_1} region instead of the global {@code s3.amazonaws.com} by default if it's not configured otherwise
* via {@link SdkSystemSetting#AWS_S3_US_EAST_1_REGIONAL_ENDPOINT} or {@link ProfileProperty#S3_US_EAST_1_REGIONAL_ENDPOINT}
*/
public static final ServiceMetadataAdvancedOption<String> DEFAULT_S3_US_EAST_1_REGIONAL_ENDPOINT =
new ServiceMetadataAdvancedOption<>(String.class);
protected ServiceMetadataAdvancedOption(Class<T> valueClass) {
super(valueClass);
}
}
| 1,584 |
0 | Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/PartitionEndpointKey.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.regions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.Mutable;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
/**
* A key used to look up a specific partition hostname or DNS suffix via
* {@link PartitionMetadata#hostname(PartitionEndpointKey)} or {@link PartitionMetadata#dnsSuffix(PartitionEndpointKey)}.
*/
@SdkPublicApi
@Immutable
public final class PartitionEndpointKey {
private final Set<EndpointTag> tags;
private PartitionEndpointKey(DefaultBuilder builder) {
this.tags = Collections.unmodifiableSet(new HashSet<>(Validate.paramNotNull(builder.tags, "tags")));
Validate.noNullElements(builder.tags, "tags must not contain null.");
}
/**
* Create a builder for a {@link PartitionEndpointKey}.
*/
public static Builder builder() {
return new DefaultBuilder();
}
public Set<EndpointTag> tags() {
return tags;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PartitionEndpointKey that = (PartitionEndpointKey) o;
return tags.equals(that.tags);
}
@Override
public int hashCode() {
return tags.hashCode();
}
@Override
public String toString() {
return ToString.builder("PartitionEndpointKey")
.add("tags", tags)
.toString();
}
@SdkPublicApi
@Mutable
public interface Builder {
/**
* Configure the tags associated with the partition endpoint that should be retrieved.
*/
Builder tags(Collection<EndpointTag> tags);
/**
* Configure the tags associated with the partition endpoint that should be retrieved.
*/
Builder tags(EndpointTag... tags);
/**
* Create a {@link PartitionEndpointKey} from the configuration on this builder.
*/
PartitionEndpointKey build();
}
private static class DefaultBuilder implements Builder {
private List<EndpointTag> tags = Collections.emptyList();
@Override
public Builder tags(Collection<EndpointTag> tags) {
this.tags = new ArrayList<>(tags);
return this;
}
@Override
public Builder tags(EndpointTag... tags) {
this.tags = Arrays.asList(tags);
return this;
}
public List<EndpointTag> getTags() {
return Collections.unmodifiableList(tags);
}
public void setTags(Collection<EndpointTag> tags) {
this.tags = new ArrayList<>(tags);
}
@Override
public PartitionEndpointKey build() {
return new PartitionEndpointKey(this);
}
}
}
| 1,585 |
0 | Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/ServicePartitionMetadata.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.regions;
import java.util.Optional;
import software.amazon.awssdk.annotations.SdkPublicApi;
/**
* The metadata associated with a specific service, in a specific partition.
*
* This can be loaded via {@link ServiceMetadata#servicePartitions()}.
*/
@SdkPublicApi
public interface ServicePartitionMetadata {
/**
* Retrieve the partition to which this service is known to exist.
*/
PartitionMetadata partition();
/**
* Retrieve the global region associated with this service, in this {@link #partition()}. This will return empty if the
* service is regionalized in the partition.
*/
Optional<Region> globalRegion();
}
| 1,586 |
0 | Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/DefaultServiceMetadata.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.regions;
import java.net.URI;
import java.util.Collections;
import java.util.List;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.regions.internal.util.ServiceMetadataUtils;
@SdkPublicApi
public class DefaultServiceMetadata implements ServiceMetadata {
private final String endpointPrefix;
public DefaultServiceMetadata(String endpointPrefix) {
this.endpointPrefix = endpointPrefix;
}
@Override
public URI endpointFor(ServiceEndpointKey key) {
PartitionMetadata partition = PartitionMetadata.of(key.region());
PartitionEndpointKey endpointKey = PartitionEndpointKey.builder().tags(key.tags()).build();
String hostname = partition.hostname(endpointKey);
String dnsName = partition.dnsSuffix(endpointKey);
return ServiceMetadataUtils.endpointFor(hostname, endpointPrefix, key.region().id(), dnsName);
}
@Override
public Region signingRegion(ServiceEndpointKey key) {
return key.region();
}
@Override
public List<Region> regions() {
return Collections.emptyList();
}
@Override
public List<ServicePartitionMetadata> servicePartitions() {
return Collections.emptyList();
}
}
| 1,587 |
0 | Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/RegionMetadata.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.regions;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.regions.internal.MetadataLoader;
/**
* A collection of metadata about a region. This can be loaded using the {@link #of(Region)} method.
*/
@SdkPublicApi
public interface RegionMetadata {
/**
* The unique system ID for this region; ex: "us-east-1".
*
* @return The unique system ID for this region.
*/
String id();
/**
* Returns the default domain for this region; ex: "amazonaws.com", without considering any {@link EndpointTag}s
* or environment variables.
*
* @return The domain for this region.
* @deprecated This information does not consider any endpoint variant factors, like {@link EndpointTag}s. If those factors
* are important, use {@link ServiceMetadata#endpointFor(ServiceEndpointKey)} or
* {@link PartitionMetadata#dnsSuffix(PartitionEndpointKey)}.
*/
@Deprecated
String domain();
/**
* Returns the metadata for this region's partition.
*/
PartitionMetadata partition();
/**
* Returns the description of this region; ex: "US East (N. Virginia)".
*
* @return The description for this region
*/
String description();
/**
* Returns the region metadata pertaining to the given region.
*
* @param region The region to get the metadata for.
* @return The metadata for that region.
*/
static RegionMetadata of(Region region) {
return MetadataLoader.regionMetadata(region);
}
}
| 1,588 |
0 | Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/PartitionMetadataProvider.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.regions;
import software.amazon.awssdk.annotations.SdkPublicApi;
@SdkPublicApi
public interface PartitionMetadataProvider {
/**
* Returns the partition metadata for a given partition.
*
* @param partition The partition to find partition metadata for.
* @return {@link PartitionMetadata} for the given partition
*/
PartitionMetadata partitionMetadata(String partition);
/**
* Returns the partition metadata for a given region.
*
* @param region The region to find partition metadata for.
* @return {@link PartitionMetadata} for the given region.
*/
PartitionMetadata partitionMetadata(Region region);
}
| 1,589 |
0 | Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/ServiceEndpointKey.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.regions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.Mutable;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
/**
* A ServiceEndpointKey uniquely identifies a service endpoint, and can be used to look up endpoints via
* {@link ServiceMetadata#endpointFor(ServiceEndpointKey)}.
*
* <p>An endpoint is uniquely identified by the {@link Region} of that service and the {@link EndpointTag}s associated with that
* endpoint. For example, the {@link EndpointTag#FIPS} endpoint in {@link Region#US_WEST_2}.
*
* <p>This can be created via {@link #builder()}.
*/
@SdkPublicApi
@Immutable
public final class ServiceEndpointKey {
private final Region region;
private final Set<EndpointTag> tags;
private ServiceEndpointKey(DefaultBuilder builder) {
this.region = Validate.paramNotNull(builder.region, "region");
this.tags = Collections.unmodifiableSet(new LinkedHashSet<>(Validate.paramNotNull(builder.tags, "tags")));
Validate.noNullElements(builder.tags, "tags must not contain null.");
}
/**
* Create a builder for {@link ServiceEndpointKey}s.
*/
public static Builder builder() {
return new DefaultBuilder();
}
/**
* Retrieve the region associated with the endpoint.
*/
public Region region() {
return region;
}
/**
* Retrieve the tags associated with the endpoint (or the empty set, to use the default endpoint).
*/
public Set<EndpointTag> tags() {
return tags;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ServiceEndpointKey that = (ServiceEndpointKey) o;
if (!region.equals(that.region)) {
return false;
}
return tags.equals(that.tags);
}
@Override
public int hashCode() {
int result = region.hashCode();
result = 31 * result + tags.hashCode();
return result;
}
@Override
public String toString() {
return ToString.builder("ServiceEndpointKey")
.add("region", region)
.add("tags", tags)
.toString();
}
@SdkPublicApi
@Mutable
public interface Builder {
/**
* Configure the region associated with the endpoint that should be loaded.
*/
Builder region(Region region);
/**
* Configure the tags associated with the endpoint that should be loaded.
*/
Builder tags(Collection<EndpointTag> tags);
/**
* Configure the tags associated with the endpoint that should be loaded.
*/
Builder tags(EndpointTag... tags);
/**
* Build a {@link ServiceEndpointKey} using the configuration on this builder.
*/
ServiceEndpointKey build();
}
private static class DefaultBuilder implements Builder {
private Region region;
private List<EndpointTag> tags = Collections.emptyList();
@Override
public Builder region(Region region) {
this.region = region;
return this;
}
public Region getRegion() {
return region;
}
public void setRegion(Region region) {
this.region = region;
}
@Override
public Builder tags(Collection<EndpointTag> tags) {
this.tags = new ArrayList<>(tags);
return this;
}
@Override
public Builder tags(EndpointTag... tags) {
this.tags = Arrays.asList(tags);
return this;
}
public List<EndpointTag> getTags() {
return Collections.unmodifiableList(tags);
}
public void setTags(Collection<EndpointTag> tags) {
this.tags = new ArrayList<>(tags);
}
@Override
public ServiceEndpointKey build() {
return new ServiceEndpointKey(this);
}
}
}
| 1,590 |
0 | Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/ServiceMetadataConfiguration.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.regions;
import java.util.Map;
import java.util.Optional;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.profiles.ProfileFile;
import software.amazon.awssdk.profiles.ProfileFileSystemSetting;
import software.amazon.awssdk.utils.AttributeMap;
/**
* Configuration for a {@link ServiceMetadata}. This allows modifying the values used by default when a metadata instance is
* generating endpoint data.
*
* Created using a {@link #builder()}.
*/
@SdkPublicApi
public final class ServiceMetadataConfiguration {
private final Supplier<ProfileFile> profileFile;
private final String profileName;
private final AttributeMap advancedOptions;
private ServiceMetadataConfiguration(Builder builder) {
this.profileFile = builder.profileFile;
this.profileName = builder.profileName;
this.advancedOptions = builder.advancedOptions.build();
}
/**
* Create a {@link Builder} that can be used to create {@link ServiceMetadataConfiguration} instances.
*/
public static Builder builder() {
return new Builder();
}
/**
* Retrieve the profile file configured via {@link Builder#profileFile(Supplier)}.
*/
public Supplier<ProfileFile> profileFile() {
return profileFile;
}
/**
* Retrieve the profile name configured via {@link Builder#profileName(String)}.
*/
public String profileName() {
return profileName;
}
/**
* Load the optional requested advanced option that was configured on the service metadata builder.
*
* @see ServiceMetadataConfiguration.Builder#putAdvancedOption(ServiceMetadataAdvancedOption, Object)
*/
public <T> Optional<T> advancedOption(ServiceMetadataAdvancedOption<T> option) {
return Optional.ofNullable(advancedOptions.get(option));
}
public static final class Builder {
private Supplier<ProfileFile> profileFile;
private String profileName;
private AttributeMap.Builder advancedOptions = AttributeMap.builder();
private Builder() {
}
/**
* Configure the profile file used by some services to calculate the endpoint from the region. The supplier is only
* invoked zero or one time, and only the first time the value is needed.
*
* If this is null, the {@link ProfileFile#defaultProfileFile()} is used.
*/
public Builder profileFile(Supplier<ProfileFile> profileFile) {
this.profileFile = profileFile;
return this;
}
/**
* Configure which profile in the {@link #profileFile(Supplier)} should be usedto calculate the endpoint from the region.
*
* If this is null, the {@link ProfileFileSystemSetting#AWS_PROFILE} is used.
*/
public Builder profileName(String profileName) {
this.profileName = profileName;
return this;
}
/**
* Configure the map of advanced override options. This will override all values currently configured. The values in the
* map must match the key type of the map, or a runtime exception will be raised.
*/
public <T> Builder putAdvancedOption(ServiceMetadataAdvancedOption<T> option, T value) {
this.advancedOptions.put(option, value);
return this;
}
/**
* Configure an advanced override option.
* @see ServiceMetadataAdvancedOption
*/
public Builder advancedOptions(Map<ServiceMetadataAdvancedOption<?>, ?> advancedOptions) {
this.advancedOptions.putAll(advancedOptions);
return this;
}
/**
* Build the {@link ServiceMetadata} instance with the updated configuration.
*/
public ServiceMetadataConfiguration build() {
return new ServiceMetadataConfiguration(this);
}
}
}
| 1,591 |
0 | Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/RegionMetadataProvider.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.regions;
import software.amazon.awssdk.annotations.SdkPublicApi;
@SdkPublicApi
public interface RegionMetadataProvider {
/**
* Returns the region metadata with the name given, if it exists in the metadata
* or if it can be derived from the metadata.
*
* Otherwise, returns null.
*
* @param region the region to search for
* @return the corresponding region metadata, if it exists or derived.
*/
RegionMetadata regionMetadata(Region region);
}
| 1,592 |
0 | Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/RegionScope.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.regions;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.utils.Validate;
/**
* This class represents the concept of a regional scope, in form of a string with possible wildcards.
* <p/>
* The string can contain a region value such as us-east-1, or add the wildcard '*' at the end of the region
* string to represent all possible regional combinations that can match the expression. A wildcard must be
* it's own segment and preceeded by a '-' dash, unless the whole expression is the wildcard.
* <p/>
* Examples of valid combinations:
* <ul>
* <li>'us-east-1' - Represents the region exactly</li>
* <li>'eu-west-*' - Represents all regions that start with 'eu-west-'</li>
* <li>'eu-*' - Represents all regions that start with 'eu-'</li>
* <li>'*' - Represents all regions, i.e. a global scope</li>
* </ul>
* <p/>
* Examples of invalid combinations:
* <ul>
* <li>'us-*-1' - The wildcard must appear at the end.</li>
* <li>'eu-we*' - The wildcard must be its own segment</li>
* </ul>
*/
@SdkPublicApi
public final class RegionScope {
public static final RegionScope GLOBAL;
private static final Pattern REGION_SCOPE_PATTERN;
//Pattern must be compiled when static scope is created
static {
REGION_SCOPE_PATTERN = Pattern.compile("^([a-z0-9-])*([*]?)$");
GLOBAL = RegionScope.create("*");
}
private final String regionScope;
private RegionScope(String regionScope) {
this.regionScope = Validate.paramNotBlank(regionScope, "regionScope");
validateFormat(regionScope);
}
/**
* Gets the string representation of this region scope.
*/
public String id() {
return this.regionScope;
}
/**
* Creates a RegionScope with the supplied value.
*
* @param value See class documentation {@link RegionScope} for allowed values.
*/
public static RegionScope create(String value) {
return new RegionScope(value);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
RegionScope that = (RegionScope) o;
return regionScope.equals(that.regionScope);
}
@Override
public int hashCode() {
return 31 * (1 + (regionScope != null ? regionScope.hashCode() : 0));
}
private void validateFormat(String regionScope) {
Matcher matcher = REGION_SCOPE_PATTERN.matcher(regionScope);
if (!matcher.matches()) {
if (regionScope.contains(",")) {
throw new IllegalArgumentException("Incorrect region scope '" + regionScope + "'. Region scopes with more than "
+ "one region defined are not supported.");
}
throw new IllegalArgumentException("Incorrect region scope '" + regionScope + "'. Region scope must be a"
+ " string that either is a complete region string, such as 'us-east-1',"
+ " or uses the wildcard '*' to represent any region that starts with"
+ " the preceding parts. Wildcards must appear as a separate segment after"
+ " a '-' dash, for example 'us-east-*'. A global scope of '*' is allowed.");
}
List<String> segments = Arrays.asList(regionScope.split("-"));
String lastSegment = segments.get(segments.size() - 1);
if (lastSegment.contains("*") && lastSegment.length() != 1) {
throw new IllegalArgumentException("Incorrect region scope '" + regionScope
+ "'. A wildcard must only appear on its own at the end of the expression "
+ "after a '-' dash. A global scope of '*' is allowed.");
}
}
}
| 1,593 |
0 | Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/PartitionMetadata.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.regions;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.regions.internal.MetadataLoader;
/**
* Metadata about a partition such as aws or aws-cn.
*
* <p>This is useful for building meta-functionality around AWS services. Partition metadata helps to provide
* data about regions which may not yet be in the endpoints.json file but have a specific prefix.</p>
*/
@SdkPublicApi
public interface PartitionMetadata {
/**
* Returns the DNS suffix, such as amazonaws.com for this partition. This is the DNS suffix with no
* {@link EndpointTag}s.
*
* @return The DNS suffix for this partition with no endpoint tags.
* @see #dnsSuffix(PartitionEndpointKey)
*/
default String dnsSuffix() {
return dnsSuffix(PartitionEndpointKey.builder().build());
}
/**
* Returns the DNS suffix, such as amazonaws.com for this partition. This returns the DNS suffix associated with the tags in
* the provided {@link PartitionEndpointKey}.
*
* @return The DNS suffix for this partition with the endpoint tags specified in the endpoint key, or null if one is not
* known.
*/
default String dnsSuffix(PartitionEndpointKey key) {
throw new UnsupportedOperationException();
}
/**
* Returns the hostname pattern, such as {service}.{region}.{dnsSuffix} for this partition. This is the hostname pattern
* with no {@link EndpointTag}s.
*
* @return The hostname pattern for this partition with no endpoint tags.
* @see #hostname(PartitionEndpointKey)
*/
default String hostname() {
return hostname(PartitionEndpointKey.builder().build());
}
/**
* Returns the hostname pattern, such as {service}.{region}.{dnsSuffix} for this partition. This returns the hostname
* associated with the tags in the provided {@link PartitionEndpointKey}.
*
* @return The hostname pattern for this partition with the endpoint tags specified in the endpoint key, or null if one is
* not known.
*/
default String hostname(PartitionEndpointKey key) {
throw new UnsupportedOperationException();
}
/**
* Returns the identifier for this partition, such as aws.
*
* @return The identifier for this partition.
*/
String id();
/**
* Returns the partition name for this partition, such as AWS Standard
*
* @return The name of this partition
*/
String name();
/**
* Returns the region regex used for pattern matching for this partition.
*
* @return The region regex of this partition.
*/
String regionRegex();
/**
* Retrieves the partition metadata for a given partition.
*
* @param partition The partition to get metadata for.
*
* @return {@link PartitionMetadata} for the given partition.
*/
static PartitionMetadata of(String partition) {
return MetadataLoader.partitionMetadata(partition);
}
/**
* Retrieves the partition metadata for a given region.
*
* @param region The region to get the partition metadata for.
*
* @return {@link PartitionMetadata} for the given region.
*/
static PartitionMetadata of(Region region) {
return MetadataLoader.partitionMetadata(region);
}
}
| 1,594 |
0 | Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/ServiceMetadataProvider.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.regions;
import software.amazon.awssdk.annotations.SdkPublicApi;
@SdkPublicApi
public interface ServiceMetadataProvider {
/**
* Returns the service metadata with the name given, if it exists in the metadata
* or if it can be derived from the metadata.
*
* Otherwise, returns null.
*
* @param service the service to search for
* @return the corresponding service metadata, if it exists or derived.
*/
ServiceMetadata serviceMetadata(String service);
}
| 1,595 |
0 | Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions | Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/servicemetadata/EnhancedS3ServiceMetadata.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.regions.servicemetadata;
import java.net.URI;
import java.util.List;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.SdkSystemSetting;
import software.amazon.awssdk.profiles.ProfileFile;
import software.amazon.awssdk.profiles.ProfileFileSystemSetting;
import software.amazon.awssdk.profiles.ProfileProperty;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.regions.ServiceEndpointKey;
import software.amazon.awssdk.regions.ServiceMetadata;
import software.amazon.awssdk.regions.ServiceMetadataAdvancedOption;
import software.amazon.awssdk.regions.ServiceMetadataConfiguration;
import software.amazon.awssdk.regions.ServicePartitionMetadata;
import software.amazon.awssdk.utils.Lazy;
import software.amazon.awssdk.utils.Logger;
/**
* Decorator metadata class for S3 to allow customers to opt in to using the
* regional S3 us-east-1 endpoint instead of the legacy
* {@code s3.amazonaws.com} when specifying the us-east-1 region.
*/
@SdkPublicApi
public final class EnhancedS3ServiceMetadata implements ServiceMetadata {
private static final Logger log = Logger.loggerFor(EnhancedS3ServiceMetadata.class);
private static final String REGIONAL_SETTING = "regional";
private final Lazy<Boolean> useUsEast1RegionalEndpoint;
private final ServiceMetadata s3ServiceMetadata;
public EnhancedS3ServiceMetadata() {
this(ServiceMetadataConfiguration.builder().build());
}
private EnhancedS3ServiceMetadata(ServiceMetadataConfiguration config) {
Supplier<ProfileFile> profileFile = config.profileFile() != null ? config.profileFile()
: ProfileFile::defaultProfileFile;
Supplier<String> profileName = config.profileName() != null ? () -> config.profileName()
: ProfileFileSystemSetting.AWS_PROFILE::getStringValueOrThrow;
this.useUsEast1RegionalEndpoint = new Lazy<>(() -> useUsEast1RegionalEndpoint(profileFile, profileName, config));
this.s3ServiceMetadata = new S3ServiceMetadata().reconfigure(config);
}
@Override
public URI endpointFor(ServiceEndpointKey key) {
if (Region.US_EAST_1.equals(key.region()) && key.tags().isEmpty() && !useUsEast1RegionalEndpoint.getValue()) {
return URI.create("s3.amazonaws.com");
}
return s3ServiceMetadata.endpointFor(key);
}
@Override
public Region signingRegion(ServiceEndpointKey key) {
return s3ServiceMetadata.signingRegion(key);
}
@Override
public List<Region> regions() {
return s3ServiceMetadata.regions();
}
@Override
public List<ServicePartitionMetadata> servicePartitions() {
return s3ServiceMetadata.servicePartitions();
}
private boolean useUsEast1RegionalEndpoint(Supplier<ProfileFile> profileFile, Supplier<String> profileName,
ServiceMetadataConfiguration config) {
String env = envVarSetting();
if (env != null) {
return REGIONAL_SETTING.equalsIgnoreCase(env);
}
String profile = profileFileSetting(profileFile, profileName);
if (profile != null) {
return REGIONAL_SETTING.equalsIgnoreCase(profile);
}
return config.advancedOption(ServiceMetadataAdvancedOption.DEFAULT_S3_US_EAST_1_REGIONAL_ENDPOINT)
.filter(REGIONAL_SETTING::equalsIgnoreCase).isPresent();
}
private static String envVarSetting() {
return SdkSystemSetting.AWS_S3_US_EAST_1_REGIONAL_ENDPOINT.getStringValue().orElse(null);
}
private String profileFileSetting(Supplier<ProfileFile> profileFileSupplier, Supplier<String> profileNameSupplier) {
try {
ProfileFile profileFile = profileFileSupplier.get();
String profileName = profileNameSupplier.get();
if (profileFile == null || profileName == null) {
return null;
}
return profileFile.profile(profileName)
.flatMap(p -> p.property(ProfileProperty.S3_US_EAST_1_REGIONAL_ENDPOINT))
.orElse(null);
} catch (Exception t) {
log.warn(() -> "Unable to load config file", t);
return null;
}
}
@Override
public ServiceMetadata reconfigure(ServiceMetadataConfiguration configuration) {
return new EnhancedS3ServiceMetadata(configuration);
}
}
| 1,596 |
0 | Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions | Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/util/ResourcesEndpointProvider.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.regions.util;
import java.io.IOException;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.util.SdkUserAgent;
/**
* <p>
* Abstract class to return an endpoint URI from which the resources can be loaded.
* </p>
* <p>
* By default, the request won't be retried if the request fails while computing endpoint.
* </p>
*/
@SdkProtectedApi
@FunctionalInterface
public interface ResourcesEndpointProvider {
/**
* Returns the URI that contains the credentials.
* @return
* URI to retrieve the credentials.
*
* @throws IOException
* If any problems are encountered while connecting to the
* service to retrieve the endpoint.
*/
URI endpoint() throws IOException;
/**
* Allows the extending class to provide a custom retry policy.
* The default behavior is not to retry.
*/
default ResourcesEndpointRetryPolicy retryPolicy() {
return ResourcesEndpointRetryPolicy.NO_RETRY;
}
/**
* Allows passing additional headers to the request
*/
default Map<String, String> headers() {
Map<String, String> requestHeaders = new HashMap<>();
requestHeaders.put("User-Agent", SdkUserAgent.create().userAgent());
requestHeaders.put("Accept", "*/*");
requestHeaders.put("Connection", "keep-alive");
return requestHeaders;
}
}
| 1,597 |
0 | Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions | Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/util/ResourcesEndpointRetryParameters.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.regions.util;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* Parameters that are used in {@link ResourcesEndpointRetryPolicy}.
*/
@SdkProtectedApi
public final class ResourcesEndpointRetryParameters {
private final Integer statusCode;
private final Exception exception;
private ResourcesEndpointRetryParameters(Builder builder) {
this.statusCode = builder.statusCode;
this.exception = builder.exception;
}
public static Builder builder() {
return new Builder();
}
public Integer getStatusCode() {
return statusCode;
}
public Exception getException() {
return exception;
}
public static class Builder {
private final Integer statusCode;
private final Exception exception;
private Builder() {
this.statusCode = null;
this.exception = null;
}
private Builder(Integer statusCode, Exception exception) {
this.statusCode = statusCode;
this.exception = exception;
}
/**
* @param statusCode The status code from Http response.
*
* @return This object for method chaining.
*/
public Builder withStatusCode(Integer statusCode) {
return new Builder(statusCode, this.exception);
}
/**
*
* @param exception The exception that was thrown.
* @return This object for method chaining.
*/
public Builder withException(Exception exception) {
return new Builder(this.statusCode, exception);
}
public ResourcesEndpointRetryParameters build() {
return new ResourcesEndpointRetryParameters(this);
}
}
}
| 1,598 |
0 | Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions | Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/util/ResourcesEndpointRetryPolicy.java | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.regions.util;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* Custom retry policy that retrieve information from a local endpoint in EC2 host.
*
* Internal use only.
*/
@SdkProtectedApi
public interface ResourcesEndpointRetryPolicy {
ResourcesEndpointRetryPolicy NO_RETRY = (retriesAttempted, retryParams) -> false;
/**
* Returns whether a failed request should be retried.
*
* @param retriesAttempted
* The number of times the current request has been
* attempted.
*
* @return True if the failed request should be retried.
*/
boolean shouldRetry(int retriesAttempted, ResourcesEndpointRetryParameters retryParams);
}
| 1,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.